2 use base qw( FS::cust_main::Packages
4 FS::cust_main::NationalID
6 FS::cust_main::Billing_Realtime
7 FS::cust_main::Billing_Discount
8 FS::cust_main::Billing_ThirdParty
9 FS::cust_main::Location
10 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
11 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
18 use vars qw( $DEBUG $me $conf
21 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
27 use Scalar::Util qw( blessed );
28 use Time::Local qw(timelocal);
29 use Storable qw(thaw);
33 use Digest::MD5 qw(md5_base64);
36 use File::Temp; #qw( tempfile );
37 use Business::CreditCard 0.28;
39 use FS::UID qw( dbh driver_name );
40 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
42 use FS::Misc qw( generate_email send_email generate_ps do_print );
43 use FS::Msgcat qw(gettext);
50 use FS::cust_bill_void;
51 use FS::legacy_cust_bill;
53 use FS::cust_pay_pending;
54 use FS::cust_pay_void;
55 use FS::cust_pay_batch;
58 use FS::part_referral;
59 use FS::cust_main_county;
60 use FS::cust_location;
62 use FS::cust_main_exemption;
63 use FS::cust_tax_adjustment;
64 use FS::cust_tax_location;
65 use FS::agent_currency;
66 use FS::cust_main_invoice;
68 use FS::prepay_credit;
74 use FS::payment_gateway;
75 use FS::agent_payment_gateway;
77 use FS::cust_main_note;
78 use FS::cust_attachment;
81 use FS::upgrade_journal;
85 # 1 is mostly method/subroutine entry and options
86 # 2 traces progress of some operations
87 # 3 is even more information including possibly sensitive data
89 $me = '[FS::cust_main]';
92 $ignore_expired_card = 0;
93 $ignore_banned_card = 0;
94 $ignore_invalid_card = 0;
98 @encrypted_fields = ('payinfo', 'paycvv');
99 sub nohistory_fields { ('payinfo', 'paycvv'); }
101 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
103 #ask FS::UID to run this stuff for us later
104 #$FS::UID::callback{'FS::cust_main'} = sub {
105 install_callback FS::UID sub {
106 $conf = new FS::Conf;
107 #yes, need it for stuff below (prolly should be cached)
108 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
113 my ( $hashref, $cache ) = @_;
114 if ( exists $hashref->{'pkgnum'} ) {
115 #@{ $self->{'_pkgnum'} } = ();
116 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
117 $self->{'_pkgnum'} = $subcache;
118 #push @{ $self->{'_pkgnum'} },
119 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
125 FS::cust_main - Object methods for cust_main records
131 $record = new FS::cust_main \%hash;
132 $record = new FS::cust_main { 'column' => 'value' };
134 $error = $record->insert;
136 $error = $new_record->replace($old_record);
138 $error = $record->delete;
140 $error = $record->check;
142 @cust_pkg = $record->all_pkgs;
144 @cust_pkg = $record->ncancelled_pkgs;
146 @cust_pkg = $record->suspended_pkgs;
148 $error = $record->bill;
149 $error = $record->bill %options;
150 $error = $record->bill 'time' => $time;
152 $error = $record->collect;
153 $error = $record->collect %options;
154 $error = $record->collect 'invoice_time' => $time,
159 An FS::cust_main object represents a customer. FS::cust_main inherits from
160 FS::Record. The following fields are currently supported:
166 Primary key (assigned automatically for new customers)
170 Agent (see L<FS::agent>)
174 Advertising source (see L<FS::part_referral>)
186 Cocial security number (optional)
210 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
214 Payment Information (See L<FS::payinfo_Mixin> for data format)
218 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
222 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
226 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
230 Start date month (maestro/solo cards only)
234 Start date year (maestro/solo cards only)
238 Issue number (maestro/solo cards only)
242 Name on card or billing name
246 IP address from which payment information was received
250 Tax exempt, empty or `Y'
254 Order taker (see L<FS::access_user>)
260 =item referral_custnum
262 Referring customer number
266 Enable individual CDR spooling, empty or `Y'
270 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
274 Discourage individual CDR printing, empty or `Y'
278 Allow self-service editing of ticket subjects, empty or 'Y'
280 =item calling_list_exempt
282 Do not call, empty or 'Y'
292 Creates a new customer. To add the customer to the database, see L<"insert">.
294 Note that this stores the hash reference, not a distinct copy of the hash it
295 points to. You can ask the object for a copy with the I<hash> method.
299 sub table { 'cust_main'; }
301 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
303 Adds this customer to the database. If there is an error, returns the error,
304 otherwise returns false.
306 Usually the customer's location will not yet exist in the database, and
307 the C<bill_location> and C<ship_location> pseudo-fields must be set to
308 uninserted L<FS::cust_location> objects. These will be inserted and linked
309 (in both directions) to the new customer record. If they're references
310 to the same object, they will become the same location.
312 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
313 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
314 are inserted atomicly, or the transaction is rolled back. Passing an empty
315 hash reference is equivalent to not supplying this parameter. There should be
316 a better explanation of this, but until then, here's an example:
319 tie %hash, 'Tie::RefHash'; #this part is important
321 $cust_pkg => [ $svc_acct ],
324 $cust_main->insert( \%hash );
326 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
327 be set as the invoicing list (see L<"invoicing_list">). Errors return as
328 expected and rollback the entire transaction; it is not necessary to call
329 check_invoicing_list first. The invoicing_list is set after the records in the
330 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
331 invoicing_list destination to the newly-created svc_acct. Here's an example:
333 $cust_main->insert( {}, [ $email, 'POST' ] );
335 Currently available options are: I<depend_jobnum>, I<noexport>,
336 I<tax_exemption> and I<prospectnum>.
338 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
339 on the supplied jobnum (they will not run until the specific job completes).
340 This can be used to defer provisioning until some action completes (such
341 as running the customer's credit card successfully).
343 The I<noexport> option is deprecated. If I<noexport> is set true, no
344 provisioning jobs (exports) are scheduled. (You can schedule them later with
345 the B<reexport> method.)
347 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
348 of tax names and exemption numbers. FS::cust_main_exemption records will be
349 created and inserted.
351 If I<prospectnum> is set, moves contacts and locations from that prospect.
353 If I<contact> is set to an arrayref of FS::contact objects, inserts those
354 new contacts with this new customer.
360 my $cust_pkgs = @_ ? shift : {};
361 my $invoicing_list = @_ ? shift : '';
363 warn "$me insert called with options ".
364 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
367 local $SIG{HUP} = 'IGNORE';
368 local $SIG{INT} = 'IGNORE';
369 local $SIG{QUIT} = 'IGNORE';
370 local $SIG{TERM} = 'IGNORE';
371 local $SIG{TSTP} = 'IGNORE';
372 local $SIG{PIPE} = 'IGNORE';
374 my $oldAutoCommit = $FS::UID::AutoCommit;
375 local $FS::UID::AutoCommit = 0;
378 my $prepay_identifier = '';
379 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
381 if ( $self->payby eq 'PREPAY' ) {
383 $self->payby('BILL');
384 $prepay_identifier = $self->payinfo;
387 warn " looking up prepaid card $prepay_identifier\n"
390 my $error = $self->get_prepay( $prepay_identifier,
391 'amount_ref' => \$amount,
392 'seconds_ref' => \$seconds,
393 'upbytes_ref' => \$upbytes,
394 'downbytes_ref' => \$downbytes,
395 'totalbytes_ref' => \$totalbytes,
398 $dbh->rollback if $oldAutoCommit;
399 #return "error applying prepaid card (transaction rolled back): $error";
403 $payby = 'PREP' if $amount;
405 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|PPAL)$/ ) {
408 $self->payby('BILL');
409 $amount = $self->paid;
414 foreach my $l (qw(bill_location ship_location)) {
415 my $loc = delete $self->hashref->{$l};
416 # XXX if we're moving a prospect's locations, do that here
418 #return "$l not set";
419 #location-less customer records are now permitted
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->custnum || 0) > 0 or $loc->prospectnum ) {
436 # then it somehow belongs to another customer--shouldn't happen
437 $dbh->rollback if $oldAutoCommit;
438 return "$l belongs to customer ".$loc->custnum;
440 # else it already belongs to this customer
441 # (happens when ship_location is identical to bill_location)
443 $self->set($l.'num', $loc->locationnum);
445 if ( $self->get($l.'num') eq '' ) {
446 $dbh->rollback if $oldAutoCommit;
451 warn " inserting $self\n"
454 $self->signupdate(time) unless $self->signupdate;
456 $self->auto_agent_custid()
457 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
459 my $error = $self->SUPER::insert;
461 $dbh->rollback if $oldAutoCommit;
462 #return "inserting cust_main record (transaction rolled back): $error";
466 # now set cust_location.custnum
467 foreach my $l (qw(bill_location ship_location)) {
468 warn " setting $l.custnum\n"
470 my $loc = $self->$l or next;
471 unless ( $loc->custnum ) {
472 $loc->set(custnum => $self->custnum);
473 $error ||= $loc->replace;
477 $dbh->rollback if $oldAutoCommit;
478 return "error setting $l custnum: $error";
482 warn " setting invoicing list\n"
485 if ( $invoicing_list ) {
486 $error = $self->check_invoicing_list( $invoicing_list );
488 $dbh->rollback if $oldAutoCommit;
489 #return "checking invoicing_list (transaction rolled back): $error";
492 $self->invoicing_list( $invoicing_list );
495 warn " setting customer tags\n"
498 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
499 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
500 'custnum' => $self->custnum };
501 my $error = $cust_tag->insert;
503 $dbh->rollback if $oldAutoCommit;
508 my $prospectnum = delete $options{'prospectnum'};
509 if ( $prospectnum ) {
511 warn " moving contacts and locations from prospect $prospectnum\n"
515 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
516 unless ( $prospect_main ) {
517 $dbh->rollback if $oldAutoCommit;
518 return "Unknown prospectnum $prospectnum";
520 $prospect_main->custnum($self->custnum);
521 $prospect_main->disabled('Y');
522 my $error = $prospect_main->replace;
524 $dbh->rollback if $oldAutoCommit;
528 my @contact = $prospect_main->contact;
529 my @cust_location = $prospect_main->cust_location;
530 my @qual = $prospect_main->qual;
532 foreach my $r ( @contact, @cust_location, @qual ) {
534 $r->custnum($self->custnum);
535 my $error = $r->replace;
537 $dbh->rollback if $oldAutoCommit;
544 my $contact = delete $options{'contact'};
547 foreach my $c ( @$contact ) {
548 $c->custnum($self->custnum);
549 my $error = $c->insert;
551 $dbh->rollback if $oldAutoCommit;
559 warn " setting cust_main_exemption\n"
562 my $tax_exemption = delete $options{'tax_exemption'};
563 if ( $tax_exemption ) {
565 $tax_exemption = { map { $_ => '' } @$tax_exemption }
566 if ref($tax_exemption) eq 'ARRAY';
568 foreach my $taxname ( keys %$tax_exemption ) {
569 my $cust_main_exemption = new FS::cust_main_exemption {
570 'custnum' => $self->custnum,
571 'taxname' => $taxname,
572 'exempt_number' => $tax_exemption->{$taxname},
574 my $error = $cust_main_exemption->insert;
576 $dbh->rollback if $oldAutoCommit;
577 return "inserting cust_main_exemption (transaction rolled back): $error";
582 warn " ordering packages\n"
585 $error = $self->order_pkgs( $cust_pkgs,
587 'seconds_ref' => \$seconds,
588 'upbytes_ref' => \$upbytes,
589 'downbytes_ref' => \$downbytes,
590 'totalbytes_ref' => \$totalbytes,
593 $dbh->rollback if $oldAutoCommit;
598 $dbh->rollback if $oldAutoCommit;
599 return "No svc_acct record to apply pre-paid time";
601 if ( $upbytes || $downbytes || $totalbytes ) {
602 $dbh->rollback if $oldAutoCommit;
603 return "No svc_acct record to apply pre-paid data";
607 warn " inserting initial $payby payment of $amount\n"
609 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
611 $dbh->rollback if $oldAutoCommit;
612 return "inserting payment (transaction rolled back): $error";
616 unless ( $import || $skip_fuzzyfiles ) {
617 warn " queueing fuzzyfiles update\n"
619 $error = $self->queue_fuzzyfiles_update;
621 $dbh->rollback if $oldAutoCommit;
622 return "updating fuzzy search cache: $error";
626 # FS::geocode_Mixin::after_insert or something?
627 if ( $conf->config('tax_district_method') and !$import ) {
628 # if anything non-empty, try to look it up
629 my $queue = new FS::queue {
630 'job' => 'FS::geocode_Mixin::process_district_update',
631 'custnum' => $self->custnum,
633 my $error = $queue->insert( ref($self), $self->custnum );
635 $dbh->rollback if $oldAutoCommit;
636 return "queueing tax district update: $error";
641 warn " exporting\n" if $DEBUG > 1;
643 my $export_args = $options{'export_args'} || [];
646 map qsearch( 'part_export', {exportnum=>$_} ),
647 $conf->config('cust_main-exports'); #, $agentnum
649 foreach my $part_export ( @part_export ) {
650 my $error = $part_export->export_insert($self, @$export_args);
652 $dbh->rollback if $oldAutoCommit;
653 return "exporting to ". $part_export->exporttype.
654 " (transaction rolled back): $error";
658 #foreach my $depend_jobnum ( @$depend_jobnums ) {
659 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
661 # foreach my $jobnum ( @jobnums ) {
662 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
663 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
665 # my $error = $queue->depend_insert($depend_jobnum);
667 # $dbh->rollback if $oldAutoCommit;
668 # return "error queuing job dependancy: $error";
675 #if ( exists $options{'jobnums'} ) {
676 # push @{ $options{'jobnums'} }, @jobnums;
679 warn " insert complete; committing transaction\n"
682 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
687 use File::CounterFile;
688 sub auto_agent_custid {
691 my $format = $conf->config('cust_main-auto_agent_custid');
693 if ( $format eq '1YMMXXXXXXXX' ) {
695 my $counter = new File::CounterFile 'cust_main.agent_custid';
698 my $ym = 100000000000 + time2str('%y%m00000000', time);
699 if ( $ym > $counter->value ) {
700 $counter->{'value'} = $agent_custid = $ym;
701 $counter->{'updated'} = 1;
703 $agent_custid = $counter->inc;
709 die "Unknown cust_main-auto_agent_custid format: $format";
712 $self->agent_custid($agent_custid);
716 =item PACKAGE METHODS
718 Documentation on customer package methods has been moved to
719 L<FS::cust_main::Packages>.
721 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
723 Recharges this (existing) customer with the specified prepaid card (see
724 L<FS::prepay_credit>), specified either by I<identifier> or as an
725 FS::prepay_credit object. If there is an error, returns the error, otherwise
728 Optionally, five scalar references can be passed as well. They will have their
729 values filled in with the amount, number of seconds, and number of upload,
730 download, and total bytes applied by this prepaid card.
734 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
735 #the only place that uses these args
736 sub recharge_prepay {
737 my( $self, $prepay_credit, $amountref, $secondsref,
738 $upbytesref, $downbytesref, $totalbytesref ) = @_;
740 local $SIG{HUP} = 'IGNORE';
741 local $SIG{INT} = 'IGNORE';
742 local $SIG{QUIT} = 'IGNORE';
743 local $SIG{TERM} = 'IGNORE';
744 local $SIG{TSTP} = 'IGNORE';
745 local $SIG{PIPE} = 'IGNORE';
747 my $oldAutoCommit = $FS::UID::AutoCommit;
748 local $FS::UID::AutoCommit = 0;
751 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
753 my $error = $self->get_prepay( $prepay_credit,
754 'amount_ref' => \$amount,
755 'seconds_ref' => \$seconds,
756 'upbytes_ref' => \$upbytes,
757 'downbytes_ref' => \$downbytes,
758 'totalbytes_ref' => \$totalbytes,
760 || $self->increment_seconds($seconds)
761 || $self->increment_upbytes($upbytes)
762 || $self->increment_downbytes($downbytes)
763 || $self->increment_totalbytes($totalbytes)
764 || $self->insert_cust_pay_prepay( $amount,
766 ? $prepay_credit->identifier
771 $dbh->rollback if $oldAutoCommit;
775 if ( defined($amountref) ) { $$amountref = $amount; }
776 if ( defined($secondsref) ) { $$secondsref = $seconds; }
777 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
778 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
779 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
781 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
786 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
788 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
789 specified either by I<identifier> or as an FS::prepay_credit object.
791 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
792 incremented by the values of the prepaid card.
794 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
795 check or set this customer's I<agentnum>.
797 If there is an error, returns the error, otherwise returns false.
803 my( $self, $prepay_credit, %opt ) = @_;
805 local $SIG{HUP} = 'IGNORE';
806 local $SIG{INT} = 'IGNORE';
807 local $SIG{QUIT} = 'IGNORE';
808 local $SIG{TERM} = 'IGNORE';
809 local $SIG{TSTP} = 'IGNORE';
810 local $SIG{PIPE} = 'IGNORE';
812 my $oldAutoCommit = $FS::UID::AutoCommit;
813 local $FS::UID::AutoCommit = 0;
816 unless ( ref($prepay_credit) ) {
818 my $identifier = $prepay_credit;
820 $prepay_credit = qsearchs(
822 { 'identifier' => $identifier },
827 unless ( $prepay_credit ) {
828 $dbh->rollback if $oldAutoCommit;
829 return "Invalid prepaid card: ". $identifier;
834 if ( $prepay_credit->agentnum ) {
835 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
836 $dbh->rollback if $oldAutoCommit;
837 return "prepaid card not valid for agent ". $self->agentnum;
839 $self->agentnum($prepay_credit->agentnum);
842 my $error = $prepay_credit->delete;
844 $dbh->rollback if $oldAutoCommit;
845 return "removing prepay_credit (transaction rolled back): $error";
848 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
849 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
851 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
856 =item increment_upbytes SECONDS
858 Updates this customer's single or primary account (see L<FS::svc_acct>) by
859 the specified number of upbytes. If there is an error, returns the error,
860 otherwise returns false.
864 sub increment_upbytes {
865 _increment_column( shift, 'upbytes', @_);
868 =item increment_downbytes SECONDS
870 Updates this customer's single or primary account (see L<FS::svc_acct>) by
871 the specified number of downbytes. If there is an error, returns the error,
872 otherwise returns false.
876 sub increment_downbytes {
877 _increment_column( shift, 'downbytes', @_);
880 =item increment_totalbytes SECONDS
882 Updates this customer's single or primary account (see L<FS::svc_acct>) by
883 the specified number of totalbytes. If there is an error, returns the error,
884 otherwise returns false.
888 sub increment_totalbytes {
889 _increment_column( shift, 'totalbytes', @_);
892 =item increment_seconds SECONDS
894 Updates this customer's single or primary account (see L<FS::svc_acct>) by
895 the specified number of seconds. If there is an error, returns the error,
896 otherwise returns false.
900 sub increment_seconds {
901 _increment_column( shift, 'seconds', @_);
904 =item _increment_column AMOUNT
906 Updates this customer's single or primary account (see L<FS::svc_acct>) by
907 the specified number of seconds or bytes. If there is an error, returns
908 the error, otherwise returns false.
912 sub _increment_column {
913 my( $self, $column, $amount ) = @_;
914 warn "$me increment_column called: $column, $amount\n"
917 return '' unless $amount;
919 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
920 $self->ncancelled_pkgs;
923 return 'No packages with primary or single services found'.
924 ' to apply pre-paid time';
925 } elsif ( scalar(@cust_pkg) > 1 ) {
926 #maybe have a way to specify the package/account?
927 return 'Multiple packages found to apply pre-paid time';
930 my $cust_pkg = $cust_pkg[0];
931 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
935 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
938 return 'No account found to apply pre-paid time';
939 } elsif ( scalar(@cust_svc) > 1 ) {
940 return 'Multiple accounts found to apply pre-paid time';
943 my $svc_acct = $cust_svc[0]->svc_x;
944 warn " found service svcnum ". $svc_acct->pkgnum.
945 ' ('. $svc_acct->email. ")\n"
948 $column = "increment_$column";
949 $svc_acct->$column($amount);
953 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
955 Inserts a prepayment in the specified amount for this customer. An optional
956 second argument can specify the prepayment identifier for tracking purposes.
957 If there is an error, returns the error, otherwise returns false.
961 sub insert_cust_pay_prepay {
962 shift->insert_cust_pay('PREP', @_);
965 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
967 Inserts a cash payment in the specified amount for this customer. An optional
968 second argument can specify the payment identifier for tracking purposes.
969 If there is an error, returns the error, otherwise returns false.
973 sub insert_cust_pay_cash {
974 shift->insert_cust_pay('CASH', @_);
977 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
979 Inserts a Western Union payment in the specified amount for this customer. An
980 optional second argument can specify the prepayment identifier for tracking
981 purposes. If there is an error, returns the error, otherwise returns false.
985 sub insert_cust_pay_west {
986 shift->insert_cust_pay('WEST', @_);
989 sub insert_cust_pay {
990 my( $self, $payby, $amount ) = splice(@_, 0, 3);
991 my $payinfo = scalar(@_) ? shift : '';
993 my $cust_pay = new FS::cust_pay {
994 'custnum' => $self->custnum,
995 'paid' => sprintf('%.2f', $amount),
996 #'_date' => #date the prepaid card was purchased???
998 'payinfo' => $payinfo,
1004 =item delete [ OPTION => VALUE ... ]
1006 This deletes the customer. If there is an error, returns the error, otherwise
1009 This will completely remove all traces of the customer record. This is not
1010 what you want when a customer cancels service; for that, cancel all of the
1011 customer's packages (see L</cancel>).
1013 If the customer has any uncancelled packages, you need to pass a new (valid)
1014 customer number for those packages to be transferred to, as the "new_customer"
1015 option. Cancelled packages will be deleted. Did I mention that this is NOT
1016 what you want when a customer cancels service and that you really should be
1017 looking at L<FS::cust_pkg/cancel>?
1019 You can't delete a customer with invoices (see L<FS::cust_bill>),
1020 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1021 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1022 set the "delete_financials" option to a true value.
1027 my( $self, %opt ) = @_;
1029 local $SIG{HUP} = 'IGNORE';
1030 local $SIG{INT} = 'IGNORE';
1031 local $SIG{QUIT} = 'IGNORE';
1032 local $SIG{TERM} = 'IGNORE';
1033 local $SIG{TSTP} = 'IGNORE';
1034 local $SIG{PIPE} = 'IGNORE';
1036 my $oldAutoCommit = $FS::UID::AutoCommit;
1037 local $FS::UID::AutoCommit = 0;
1040 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1041 $dbh->rollback if $oldAutoCommit;
1042 return "Can't delete a master agent customer";
1045 #use FS::access_user
1046 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1047 $dbh->rollback if $oldAutoCommit;
1048 return "Can't delete a master employee customer";
1051 tie my %financial_tables, 'Tie::IxHash',
1052 'cust_bill' => 'invoices',
1053 'cust_statement' => 'statements',
1054 'cust_credit' => 'credits',
1055 'cust_pay' => 'payments',
1056 'cust_refund' => 'refunds',
1059 foreach my $table ( keys %financial_tables ) {
1061 my @records = $self->$table();
1063 if ( @records && ! $opt{'delete_financials'} ) {
1064 $dbh->rollback if $oldAutoCommit;
1065 return "Can't delete a customer with ". $financial_tables{$table};
1068 foreach my $record ( @records ) {
1069 my $error = $record->delete;
1071 $dbh->rollback if $oldAutoCommit;
1072 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1078 my @cust_pkg = $self->ncancelled_pkgs;
1080 my $new_custnum = $opt{'new_custnum'};
1081 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1082 $dbh->rollback if $oldAutoCommit;
1083 return "Invalid new customer number: $new_custnum";
1085 foreach my $cust_pkg ( @cust_pkg ) {
1086 my %hash = $cust_pkg->hash;
1087 $hash{'custnum'} = $new_custnum;
1088 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1089 my $error = $new_cust_pkg->replace($cust_pkg,
1090 options => { $cust_pkg->options },
1093 $dbh->rollback if $oldAutoCommit;
1098 my @cancelled_cust_pkg = $self->all_pkgs;
1099 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1100 my $error = $cust_pkg->delete;
1102 $dbh->rollback if $oldAutoCommit;
1107 #cust_tax_adjustment in financials?
1108 #cust_pay_pending? ouch
1110 foreach my $table (qw(
1111 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1112 cust_location cust_main_note cust_tax_adjustment
1113 cust_pay_void cust_pay_batch queue cust_tax_exempt
1115 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1116 my $error = $record->delete;
1118 $dbh->rollback if $oldAutoCommit;
1124 my $sth = $dbh->prepare(
1125 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1127 my $errstr = $dbh->errstr;
1128 $dbh->rollback if $oldAutoCommit;
1131 $sth->execute($self->custnum) or do {
1132 my $errstr = $sth->errstr;
1133 $dbh->rollback if $oldAutoCommit;
1139 my $ticket_dbh = '';
1140 if ($conf->config('ticket_system') eq 'RT_Internal') {
1142 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1143 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1144 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1145 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1148 if ( $ticket_dbh ) {
1150 my $ticket_sth = $ticket_dbh->prepare(
1151 'DELETE FROM Links WHERE Target = ?'
1153 my $errstr = $ticket_dbh->errstr;
1154 $dbh->rollback if $oldAutoCommit;
1157 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1159 my $errstr = $ticket_sth->errstr;
1160 $dbh->rollback if $oldAutoCommit;
1164 #check and see if the customer is the only link on the ticket, and
1165 #if so, set the ticket to deleted status in RT?
1166 #maybe someday, for now this will at least fix tickets not displaying
1170 #delete the customer record
1172 my $error = $self->SUPER::delete;
1174 $dbh->rollback if $oldAutoCommit;
1178 # cust_main exports!
1180 #my $export_args = $options{'export_args'} || [];
1183 map qsearch( 'part_export', {exportnum=>$_} ),
1184 $conf->config('cust_main-exports'); #, $agentnum
1186 foreach my $part_export ( @part_export ) {
1187 my $error = $part_export->export_delete( $self ); #, @$export_args);
1189 $dbh->rollback if $oldAutoCommit;
1190 return "exporting to ". $part_export->exporttype.
1191 " (transaction rolled back): $error";
1195 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1200 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1202 This merges this customer into the provided new custnum, and then deletes the
1203 customer. If there is an error, returns the error, otherwise returns false.
1205 The source customer's name, company name, phone numbers, agent,
1206 referring customer, customer class, advertising source, order taker, and
1207 billing information (except balance) are discarded.
1209 All packages are moved to the target customer. Packages with package locations
1210 are preserved. Packages without package locations are moved to a new package
1211 location with the source customer's service/shipping address.
1213 All invoices, statements, payments, credits and refunds are moved to the target
1214 customer. The source customer's balance is added to the target customer.
1216 All notes, attachments, tickets and customer tags are moved to the target
1219 Change history is not currently moved.
1224 my( $self, $new_custnum, %opt ) = @_;
1226 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1228 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1229 or return "Invalid new customer number: $new_custnum";
1231 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1232 if $self->agentnum != $new_cust_main->agentnum
1233 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1235 local $SIG{HUP} = 'IGNORE';
1236 local $SIG{INT} = 'IGNORE';
1237 local $SIG{QUIT} = 'IGNORE';
1238 local $SIG{TERM} = 'IGNORE';
1239 local $SIG{TSTP} = 'IGNORE';
1240 local $SIG{PIPE} = 'IGNORE';
1242 my $oldAutoCommit = $FS::UID::AutoCommit;
1243 local $FS::UID::AutoCommit = 0;
1246 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1247 $dbh->rollback if $oldAutoCommit;
1248 return "Can't merge a master agent customer";
1251 #use FS::access_user
1252 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1253 $dbh->rollback if $oldAutoCommit;
1254 return "Can't merge a master employee customer";
1257 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1258 'status' => { op=>'!=', value=>'done' },
1262 $dbh->rollback if $oldAutoCommit;
1263 return "Can't merge a customer with pending payments";
1266 tie my %financial_tables, 'Tie::IxHash',
1267 'cust_bill' => 'invoices',
1268 'cust_bill_void' => 'voided invoices',
1269 'cust_statement' => 'statements',
1270 'cust_credit' => 'credits',
1271 'cust_credit_void' => 'voided credits',
1272 'cust_pay' => 'payments',
1273 'cust_pay_void' => 'voided payments',
1274 'cust_refund' => 'refunds',
1277 foreach my $table ( keys %financial_tables ) {
1279 my @records = $self->$table();
1281 foreach my $record ( @records ) {
1282 $record->custnum($new_custnum);
1283 my $error = $record->replace;
1285 $dbh->rollback if $oldAutoCommit;
1286 return "Error merging ". $financial_tables{$table}. ": $error\n";
1292 my $name = $self->ship_name; #?
1294 my $locationnum = '';
1295 foreach my $cust_pkg ( $self->all_pkgs ) {
1296 $cust_pkg->custnum($new_custnum);
1298 unless ( $cust_pkg->locationnum ) {
1299 unless ( $locationnum ) {
1300 my $cust_location = new FS::cust_location {
1301 $self->location_hash,
1302 'custnum' => $new_custnum,
1304 my $error = $cust_location->insert;
1306 $dbh->rollback if $oldAutoCommit;
1309 $locationnum = $cust_location->locationnum;
1311 $cust_pkg->locationnum($locationnum);
1314 my $error = $cust_pkg->replace;
1316 $dbh->rollback if $oldAutoCommit;
1320 # add customer (ship) name to svc_phone.phone_name if blank
1321 my @cust_svc = $cust_pkg->cust_svc;
1322 foreach my $cust_svc (@cust_svc) {
1323 my($label, $value, $svcdb) = $cust_svc->label;
1324 next unless $svcdb eq 'svc_phone';
1325 my $svc_phone = $cust_svc->svc_x;
1326 next if $svc_phone->phone_name;
1327 $svc_phone->phone_name($name);
1328 my $error = $svc_phone->replace;
1330 $dbh->rollback if $oldAutoCommit;
1338 # cust_tax_exempt (texas tax exemptions)
1339 # cust_recon (some sort of not-well understood thing for OnPac)
1341 #these are moved over
1342 foreach my $table (qw(
1343 cust_tag cust_location contact cust_attachment cust_main_note
1344 cust_tax_adjustment cust_pay_batch queue
1346 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1347 $record->custnum($new_custnum);
1348 my $error = $record->replace;
1350 $dbh->rollback if $oldAutoCommit;
1356 #these aren't preserved
1357 foreach my $table (qw(
1358 cust_main_exemption cust_main_invoice
1360 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1361 my $error = $record->delete;
1363 $dbh->rollback if $oldAutoCommit;
1370 my $sth = $dbh->prepare(
1371 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1373 my $errstr = $dbh->errstr;
1374 $dbh->rollback if $oldAutoCommit;
1377 $sth->execute($new_custnum, $self->custnum) or do {
1378 my $errstr = $sth->errstr;
1379 $dbh->rollback if $oldAutoCommit;
1385 my $ticket_dbh = '';
1386 if ($conf->config('ticket_system') eq 'RT_Internal') {
1388 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1389 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1390 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1391 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1394 if ( $ticket_dbh ) {
1396 my $ticket_sth = $ticket_dbh->prepare(
1397 'UPDATE Links SET Target = ? WHERE Target = ?'
1399 my $errstr = $ticket_dbh->errstr;
1400 $dbh->rollback if $oldAutoCommit;
1403 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1404 'freeside://freeside/cust_main/'.$self->custnum)
1406 my $errstr = $ticket_sth->errstr;
1407 $dbh->rollback if $oldAutoCommit;
1413 #delete the customer record
1415 my $error = $self->delete;
1417 $dbh->rollback if $oldAutoCommit;
1421 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1426 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1428 Replaces the OLD_RECORD with this one in the database. If there is an error,
1429 returns the error, otherwise returns false.
1431 To change the customer's address, set the pseudo-fields C<bill_location> and
1432 C<ship_location>. The address will still only change if at least one of the
1433 address fields differs from the existing values.
1435 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1436 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1437 expected and rollback the entire transaction; it is not necessary to call
1438 check_invoicing_list first. Here's an example:
1440 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1442 Currently available options are: I<tax_exemption>.
1444 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1445 of tax names and exemption numbers. FS::cust_main_exemption records will be
1446 deleted and inserted as appropriate.
1453 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1455 : $self->replace_old;
1459 warn "$me replace called\n"
1462 my $curuser = $FS::CurrentUser::CurrentUser;
1463 if ( $self->payby eq 'COMP'
1464 && $self->payby ne $old->payby
1465 && ! $curuser->access_right('Complimentary customer')
1468 return "You are not permitted to create complimentary accounts.";
1471 local($ignore_expired_card) = 1
1472 if $old->payby =~ /^(CARD|DCRD)$/
1473 && $self->payby =~ /^(CARD|DCRD)$/
1474 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1476 local($ignore_banned_card) = 1
1477 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1478 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1479 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1481 return "Invoicing locale is required"
1484 && $conf->exists('cust_main-require_locale');
1486 local $SIG{HUP} = 'IGNORE';
1487 local $SIG{INT} = 'IGNORE';
1488 local $SIG{QUIT} = 'IGNORE';
1489 local $SIG{TERM} = 'IGNORE';
1490 local $SIG{TSTP} = 'IGNORE';
1491 local $SIG{PIPE} = 'IGNORE';
1493 my $oldAutoCommit = $FS::UID::AutoCommit;
1494 local $FS::UID::AutoCommit = 0;
1497 for my $l (qw(bill_location ship_location)) {
1498 my $old_loc = $old->$l;
1499 my $new_loc = $self->$l;
1501 # find the existing location if there is one
1502 $new_loc->set('custnum' => $self->custnum);
1503 my $error = $new_loc->find_or_insert;
1505 $dbh->rollback if $oldAutoCommit;
1508 $self->set($l.'num', $new_loc->locationnum);
1511 # replace the customer record
1512 my $error = $self->SUPER::replace($old);
1515 $dbh->rollback if $oldAutoCommit;
1519 # now move packages to the new service location
1520 $self->set('ship_location', ''); #flush cache
1521 if ( $old->ship_locationnum and # should only be null during upgrade...
1522 $old->ship_locationnum != $self->ship_locationnum ) {
1523 $error = $old->ship_location->move_to($self->ship_location);
1525 $dbh->rollback if $oldAutoCommit;
1529 # don't move packages based on the billing location, but
1530 # disable it if it's no longer in use
1531 if ( $old->bill_locationnum and
1532 $old->bill_locationnum != $self->bill_locationnum ) {
1533 $error = $old->bill_location->disable_if_unused;
1535 $dbh->rollback if $oldAutoCommit;
1540 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1541 my $invoicing_list = shift @param;
1542 $error = $self->check_invoicing_list( $invoicing_list );
1544 $dbh->rollback if $oldAutoCommit;
1547 $self->invoicing_list( $invoicing_list );
1550 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1552 #this could be more efficient than deleting and re-inserting, if it matters
1553 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1554 my $error = $cust_tag->delete;
1556 $dbh->rollback if $oldAutoCommit;
1560 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1561 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1562 'custnum' => $self->custnum };
1563 my $error = $cust_tag->insert;
1565 $dbh->rollback if $oldAutoCommit;
1572 my %options = @param;
1574 my $tax_exemption = delete $options{'tax_exemption'};
1575 if ( $tax_exemption ) {
1577 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1578 if ref($tax_exemption) eq 'ARRAY';
1580 my %cust_main_exemption =
1581 map { $_->taxname => $_ }
1582 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1584 foreach my $taxname ( keys %$tax_exemption ) {
1586 if ( $cust_main_exemption{$taxname} &&
1587 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1590 delete $cust_main_exemption{$taxname};
1594 my $cust_main_exemption = new FS::cust_main_exemption {
1595 'custnum' => $self->custnum,
1596 'taxname' => $taxname,
1597 'exempt_number' => $tax_exemption->{$taxname},
1599 my $error = $cust_main_exemption->insert;
1601 $dbh->rollback if $oldAutoCommit;
1602 return "inserting cust_main_exemption (transaction rolled back): $error";
1606 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1607 my $error = $cust_main_exemption->delete;
1609 $dbh->rollback if $oldAutoCommit;
1610 return "deleting cust_main_exemption (transaction rolled back): $error";
1616 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1617 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1618 && $self->get('payinfo') !~ /^99\d{14}$/
1620 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1625 # card/check/lec info has changed, want to retry realtime_ invoice events
1626 my $error = $self->retry_realtime;
1628 $dbh->rollback if $oldAutoCommit;
1633 unless ( $import || $skip_fuzzyfiles ) {
1634 $error = $self->queue_fuzzyfiles_update;
1636 $dbh->rollback if $oldAutoCommit;
1637 return "updating fuzzy search cache: $error";
1641 # tax district update in cust_location
1643 # cust_main exports!
1645 my $export_args = $options{'export_args'} || [];
1648 map qsearch( 'part_export', {exportnum=>$_} ),
1649 $conf->config('cust_main-exports'); #, $agentnum
1651 foreach my $part_export ( @part_export ) {
1652 my $error = $part_export->export_replace( $self, $old, @$export_args);
1654 $dbh->rollback if $oldAutoCommit;
1655 return "exporting to ". $part_export->exporttype.
1656 " (transaction rolled back): $error";
1660 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1665 =item queue_fuzzyfiles_update
1667 Used by insert & replace to update the fuzzy search cache
1671 use FS::cust_main::Search;
1672 sub queue_fuzzyfiles_update {
1675 local $SIG{HUP} = 'IGNORE';
1676 local $SIG{INT} = 'IGNORE';
1677 local $SIG{QUIT} = 'IGNORE';
1678 local $SIG{TERM} = 'IGNORE';
1679 local $SIG{TSTP} = 'IGNORE';
1680 local $SIG{PIPE} = 'IGNORE';
1682 my $oldAutoCommit = $FS::UID::AutoCommit;
1683 local $FS::UID::AutoCommit = 0;
1686 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1687 my $queue = new FS::queue {
1688 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1690 my @args = "cust_main.$field", $self->get($field);
1691 my $error = $queue->insert( @args );
1693 $dbh->rollback if $oldAutoCommit;
1694 return "queueing job (transaction rolled back): $error";
1699 push @locations, $self->bill_location if $self->bill_locationnum;
1700 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1701 foreach my $location (@locations) {
1702 my $queue = new FS::queue {
1703 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1705 my @args = 'cust_location.address1', $location->address1;
1706 my $error = $queue->insert( @args );
1708 $dbh->rollback if $oldAutoCommit;
1709 return "queueing job (transaction rolled back): $error";
1713 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1720 Checks all fields to make sure this is a valid customer record. If there is
1721 an error, returns the error, otherwise returns false. Called by the insert
1722 and replace methods.
1729 warn "$me check BEFORE: \n". $self->_dump
1733 $self->ut_numbern('custnum')
1734 || $self->ut_number('agentnum')
1735 || $self->ut_textn('agent_custid')
1736 || $self->ut_number('refnum')
1737 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1738 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1739 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1740 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1741 || $self->ut_textn('custbatch')
1742 || $self->ut_name('last')
1743 || $self->ut_name('first')
1744 || $self->ut_snumbern('signupdate')
1745 || $self->ut_snumbern('birthdate')
1746 || $self->ut_snumbern('spouse_birthdate')
1747 || $self->ut_snumbern('anniversary_date')
1748 || $self->ut_textn('company')
1749 || $self->ut_textn('ship_company')
1750 || $self->ut_anything('comments')
1751 || $self->ut_numbern('referral_custnum')
1752 || $self->ut_textn('stateid')
1753 || $self->ut_textn('stateid_state')
1754 || $self->ut_textn('invoice_terms')
1755 || $self->ut_floatn('cdr_termination_percentage')
1756 || $self->ut_floatn('credit_limit')
1757 || $self->ut_numbern('billday')
1758 || $self->ut_numbern('prorate_day')
1759 || $self->ut_flag('edit_subject')
1760 || $self->ut_flag('calling_list_exempt')
1761 || $self->ut_flag('invoice_noemail')
1762 || $self->ut_flag('message_noemail')
1763 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1764 || $self->ut_currencyn('currency')
1767 foreach (qw(company ship_company)) {
1768 my $company = $self->get($_);
1769 $company =~ s/^\s+//;
1770 $company =~ s/\s+$//;
1771 $company =~ s/\s+/ /g;
1772 $self->set($_, $company);
1775 #barf. need message catalogs. i18n. etc.
1776 $error .= "Please select an advertising source."
1777 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1778 return $error if $error;
1780 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1781 or return "Unknown agent";
1783 if ( $self->currency ) {
1784 my $agent_currency = qsearchs( 'agent_currency', {
1785 'agentnum' => $agent->agentnum,
1786 'currency' => $self->currency,
1788 or return "Agent ". $agent->agent.
1789 " not permitted to offer ". $self->currency. " invoicing";
1792 return "Unknown refnum"
1793 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1795 return "Unknown referring custnum: ". $self->referral_custnum
1796 unless ! $self->referral_custnum
1797 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1799 if ( $self->ss eq '' ) {
1804 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1805 or return "Illegal social security number: ". $self->ss;
1806 $self->ss("$1-$2-$3");
1809 # cust_main_county verification now handled by cust_location check
1812 $self->ut_phonen('daytime', $self->country)
1813 || $self->ut_phonen('night', $self->country)
1814 || $self->ut_phonen('fax', $self->country)
1815 || $self->ut_phonen('mobile', $self->country)
1817 return $error if $error;
1819 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1821 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1824 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1826 : FS::Msgcat::_gettext('daytime');
1827 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1829 : FS::Msgcat::_gettext('night');
1831 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1833 : FS::Msgcat::_gettext('mobile');
1835 return "$daytime_label, $night_label or $mobile_label is required"
1839 ### start of stuff moved to cust_payby
1840 # then mostly kept here to support upgrades (can remove in 5.x)
1841 # but modified to allow everything to be empty
1843 if ( $self->payby ) {
1844 FS::payby->can_payby($self->table, $self->payby)
1845 or return "Illegal payby: ". $self->payby;
1850 $error = $self->ut_numbern('paystart_month')
1851 || $self->ut_numbern('paystart_year')
1852 || $self->ut_numbern('payissue')
1853 || $self->ut_textn('paytype')
1855 return $error if $error;
1857 if ( $self->payip eq '' ) {
1860 $error = $self->ut_ip('payip');
1861 return $error if $error;
1864 # If it is encrypted and the private key is not availaible then we can't
1865 # check the credit card.
1866 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1868 # Need some kind of global flag to accept invalid cards, for testing
1870 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1871 $self->payby =~ /^(CARD|DCRD)$/ ) {
1873 my $payinfo = $self->payinfo;
1874 $payinfo =~ s/\D//g;
1875 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1876 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1878 $self->payinfo($payinfo);
1880 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1882 return gettext('unknown_card_type')
1883 if $self->payinfo !~ /^99\d{14}$/ #token
1884 && cardtype($self->payinfo) eq "Unknown";
1886 unless ( $ignore_banned_card ) {
1887 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1889 if ( $ban->bantype eq 'warn' ) {
1890 #or others depending on value of $ban->reason ?
1891 return '_duplicate_card'.
1892 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1893 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1894 ' (ban# '. $ban->bannum. ')'
1895 unless $self->override_ban_warn;
1897 return 'Banned credit card: banned on '.
1898 time2str('%a %h %o at %r', $ban->_date).
1899 ' by '. $ban->otaker.
1900 ' (ban# '. $ban->bannum. ')';
1905 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1906 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1907 $self->paycvv =~ /^(\d{4})$/
1908 or return "CVV2 (CID) for American Express cards is four digits.";
1911 $self->paycvv =~ /^(\d{3})$/
1912 or return "CVV2 (CVC2/CID) is three digits.";
1919 my $cardtype = cardtype($payinfo);
1920 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1922 return "Start date or issue number is required for $cardtype cards"
1923 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1925 return "Start month must be between 1 and 12"
1926 if $self->paystart_month
1927 and $self->paystart_month < 1 || $self->paystart_month > 12;
1929 return "Start year must be 1990 or later"
1930 if $self->paystart_year
1931 and $self->paystart_year < 1990;
1933 return "Issue number must be beween 1 and 99"
1935 and $self->payissue < 1 || $self->payissue > 99;
1938 $self->paystart_month('');
1939 $self->paystart_year('');
1940 $self->payissue('');
1943 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1944 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1946 my $payinfo = $self->payinfo;
1947 $payinfo =~ s/[^\d\@\.]//g;
1948 if ( $conf->config('echeck-country') eq 'CA' ) {
1949 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1950 or return 'invalid echeck account@branch.bank';
1951 $payinfo = "$1\@$2.$3";
1952 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1953 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1954 $payinfo = "$1\@$2";
1956 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1957 $payinfo = "$1\@$2";
1959 $self->payinfo($payinfo);
1962 unless ( $ignore_banned_card ) {
1963 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1965 if ( $ban->bantype eq 'warn' ) {
1966 #or others depending on value of $ban->reason ?
1967 return '_duplicate_ach' unless $self->override_ban_warn;
1969 return 'Banned ACH account: banned on '.
1970 time2str('%a %h %o at %r', $ban->_date).
1971 ' by '. $ban->otaker.
1972 ' (ban# '. $ban->bannum. ')';
1977 } elsif ( $self->payby eq 'LECB' ) {
1979 my $payinfo = $self->payinfo;
1980 $payinfo =~ s/\D//g;
1981 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1983 $self->payinfo($payinfo);
1986 } elsif ( $self->payby eq 'BILL' ) {
1988 $error = $self->ut_textn('payinfo');
1989 return "Illegal P.O. number: ". $self->payinfo if $error;
1992 } elsif ( $self->payby eq 'COMP' ) {
1994 my $curuser = $FS::CurrentUser::CurrentUser;
1995 if ( ! $self->custnum
1996 && ! $curuser->access_right('Complimentary customer')
1999 return "You are not permitted to create complimentary accounts."
2002 $error = $self->ut_textn('payinfo');
2003 return "Illegal comp account issuer: ". $self->payinfo if $error;
2006 } elsif ( $self->payby eq 'PREPAY' ) {
2008 my $payinfo = $self->payinfo;
2009 $payinfo =~ s/\W//g; #anything else would just confuse things
2010 $self->payinfo($payinfo);
2011 $error = $self->ut_alpha('payinfo');
2012 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2013 return "Unknown prepayment identifier"
2014 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2019 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2020 return "Expiration date required"
2021 # shouldn't payinfo_check do this?
2022 unless ! $self->payby
2023 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2027 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2028 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2029 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2030 ( $m, $y ) = ( $2, "19$1" );
2031 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2032 ( $m, $y ) = ( $3, "20$2" );
2034 return "Illegal expiration date: ". $self->paydate;
2036 $m = sprintf('%02d',$m);
2037 $self->paydate("$y-$m-01");
2038 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2039 return gettext('expired_card')
2041 && !$ignore_expired_card
2042 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2045 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2046 ( ! $conf->exists('require_cardname')
2047 || $self->payby !~ /^(CARD|DCRD)$/ )
2049 $self->payname( $self->first. " ". $self->getfield('last') );
2052 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2053 $self->payname =~ /^([\w \,\.\-\']*)$/
2054 or return gettext('illegal_name'). " payname: ". $self->payname;
2057 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2058 or return gettext('illegal_name'). " payname: ". $self->payname;
2064 ### end of stuff moved to cust_payby
2066 return "Please select an invoicing locale"
2069 && $conf->exists('cust_main-require_locale');
2071 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2072 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2076 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2078 warn "$me check AFTER: \n". $self->_dump
2081 $self->SUPER::check;
2086 Returns a list of fields which have ship_ duplicates.
2091 qw( last first company
2092 address1 address2 city county state zip country
2094 daytime night fax mobile
2098 =item has_ship_address
2100 Returns true if this customer record has a separate shipping address.
2104 sub has_ship_address {
2106 $self->bill_locationnum != $self->ship_locationnum;
2111 Returns a list of key/value pairs, with the following keys: address1,
2112 adddress2, city, county, state, zip, country, district, and geocode. The
2113 shipping address is used if present.
2119 $self->ship_location->location_hash;
2124 Returns all locations (see L<FS::cust_location>) for this customer.
2130 qsearch('cust_location', { 'custnum' => $self->custnum,
2131 'prospectnum' => '' } );
2136 Returns all contacts (see L<FS::contact>) for this customer.
2140 #already used :/ sub contact {
2143 qsearch('contact', { 'custnum' => $self->custnum } );
2148 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2155 'table' => 'cust_payby',
2156 'hashref' => { 'custnum' => $self->custnum },
2157 'order_by' => 'ORDER BY weight ASC',
2163 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2164 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2165 on success or a list of errors.
2171 grep { $_->unsuspend } $self->suspended_pkgs;
2176 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2178 Returns a list: an empty list on success or a list of errors.
2184 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2187 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2189 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2190 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2191 of a list of pkgparts; the hashref has the following keys:
2195 =item pkgparts - listref of pkgparts
2197 =item (other options are passed to the suspend method)
2202 Returns a list: an empty list on success or a list of errors.
2206 sub suspend_if_pkgpart {
2208 my (@pkgparts, %opt);
2209 if (ref($_[0]) eq 'HASH'){
2210 @pkgparts = @{$_[0]{pkgparts}};
2215 grep { $_->suspend(%opt) }
2216 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2217 $self->unsuspended_pkgs;
2220 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2222 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2223 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2224 instead of a list of pkgparts; the hashref has the following keys:
2228 =item pkgparts - listref of pkgparts
2230 =item (other options are passed to the suspend method)
2234 Returns a list: an empty list on success or a list of errors.
2238 sub suspend_unless_pkgpart {
2240 my (@pkgparts, %opt);
2241 if (ref($_[0]) eq 'HASH'){
2242 @pkgparts = @{$_[0]{pkgparts}};
2247 grep { $_->suspend(%opt) }
2248 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2249 $self->unsuspended_pkgs;
2252 =item cancel [ OPTION => VALUE ... ]
2254 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2256 Available options are:
2260 =item quiet - can be set true to supress email cancellation notices.
2262 =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.
2264 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2266 =item nobill - can be set true to skip billing if it might otherwise be done.
2270 Always returns a list: an empty list on success or a list of errors.
2274 # nb that dates are not specified as valid options to this method
2277 my( $self, %opt ) = @_;
2279 warn "$me cancel called on customer ". $self->custnum. " with options ".
2280 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2283 return ( 'access denied' )
2284 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2286 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2288 #should try decryption (we might have the private key)
2289 # and if not maybe queue a job for the server that does?
2290 return ( "Can't (yet) ban encrypted credit cards" )
2291 if $self->is_encrypted($self->payinfo);
2293 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2294 my $error = $ban->insert;
2295 return ( $error ) if $error;
2299 my @pkgs = $self->ncancelled_pkgs;
2301 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2303 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2304 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2308 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2309 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2312 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2315 sub _banned_pay_hashref {
2326 'payby' => $payby2ban{$self->payby},
2327 'payinfo' => $self->payinfo,
2328 #don't ever *search* on reason! #'reason' =>
2332 sub _new_banned_pay_hashref {
2334 my $hr = $self->_banned_pay_hashref;
2335 $hr->{payinfo} = md5_base64($hr->{payinfo});
2341 Returns all notes (see L<FS::cust_main_note>) for this customer.
2346 my($self,$orderby_classnum) = (shift,shift);
2347 my $orderby = "_DATE DESC";
2348 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2349 qsearch( 'cust_main_note',
2350 { 'custnum' => $self->custnum },
2352 "ORDER BY $orderby",
2358 Returns the agent (see L<FS::agent>) for this customer.
2362 Returns the agent name (see L<FS::agent>) for this customer.
2368 $self->agent->agent;
2373 Returns any tags associated with this customer, as FS::cust_tag objects,
2374 or an empty list if there are no tags.
2378 Returns any tags associated with this customer, as FS::part_tag objects,
2379 or an empty list if there are no tags.
2385 map $_->part_tag, $self->cust_tag;
2391 Returns the customer class, as an FS::cust_class object, or the empty string
2392 if there is no customer class.
2396 Returns the customer category name, or the empty string if there is no customer
2403 my $cust_class = $self->cust_class;
2405 ? $cust_class->categoryname
2411 Returns the customer class name, or the empty string if there is no customer
2418 my $cust_class = $self->cust_class;
2420 ? $cust_class->classname
2424 =item BILLING METHODS
2426 Documentation on billing methods has been moved to
2427 L<FS::cust_main::Billing>.
2429 =item REALTIME BILLING METHODS
2431 Documentation on realtime billing methods has been moved to
2432 L<FS::cust_main::Billing_Realtime>.
2436 Removes the I<paycvv> field from the database directly.
2438 If there is an error, returns the error, otherwise returns false.
2444 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2445 or return dbh->errstr;
2446 $sth->execute($self->custnum)
2447 or return $sth->errstr;
2452 =item batch_card OPTION => VALUE...
2454 Adds a payment for this invoice to the pending credit card batch (see
2455 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2456 runs the payment using a realtime gateway.
2458 Options may include:
2460 B<amount>: the amount to be paid; defaults to the customer's balance minus
2461 any payments in transit.
2463 B<payby>: the payment method; defaults to cust_main.payby
2465 B<realtime>: runs this as a realtime payment instead of adding it to a
2468 B<invnum>: sets cust_pay_batch.invnum.
2470 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2471 the billing address for the payment; defaults to the customer's billing
2474 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2475 date, and name; defaults to those fields in cust_main.
2480 my ($self, %options) = @_;
2483 if (exists($options{amount})) {
2484 $amount = $options{amount};
2486 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2488 return '' unless $amount > 0;
2490 my $invnum = delete $options{invnum};
2491 my $payby = $options{payby} || $self->payby; #still dubious
2493 if ($options{'realtime'}) {
2494 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2500 my $oldAutoCommit = $FS::UID::AutoCommit;
2501 local $FS::UID::AutoCommit = 0;
2504 #this needs to handle mysql as well as Pg, like svc_acct.pm
2505 #(make it into a common function if folks need to do batching with mysql)
2506 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2507 or return "Cannot lock pay_batch: " . $dbh->errstr;
2511 'payby' => FS::payby->payby2payment($payby),
2513 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2515 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2517 unless ( $pay_batch ) {
2518 $pay_batch = new FS::pay_batch \%pay_batch;
2519 my $error = $pay_batch->insert;
2521 $dbh->rollback if $oldAutoCommit;
2522 die "error creating new batch: $error\n";
2526 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2527 'batchnum' => $pay_batch->batchnum,
2528 'custnum' => $self->custnum,
2531 foreach (qw( address1 address2 city state zip country latitude longitude
2532 payby payinfo paydate payname ))
2534 $options{$_} = '' unless exists($options{$_});
2537 my $loc = $self->bill_location;
2539 my $cust_pay_batch = new FS::cust_pay_batch ( {
2540 'batchnum' => $pay_batch->batchnum,
2541 'invnum' => $invnum || 0, # is there a better value?
2542 # this field should be
2544 # cust_bill_pay_batch now
2545 'custnum' => $self->custnum,
2546 'last' => $self->getfield('last'),
2547 'first' => $self->getfield('first'),
2548 'address1' => $options{address1} || $loc->address1,
2549 'address2' => $options{address2} || $loc->address2,
2550 'city' => $options{city} || $loc->city,
2551 'state' => $options{state} || $loc->state,
2552 'zip' => $options{zip} || $loc->zip,
2553 'country' => $options{country} || $loc->country,
2554 'payby' => $options{payby} || $self->payby,
2555 'payinfo' => $options{payinfo} || $self->payinfo,
2556 'exp' => $options{paydate} || $self->paydate,
2557 'payname' => $options{payname} || $self->payname,
2558 'amount' => $amount, # consolidating
2561 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2562 if $old_cust_pay_batch;
2565 if ($old_cust_pay_batch) {
2566 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2568 $error = $cust_pay_batch->insert;
2572 $dbh->rollback if $oldAutoCommit;
2576 my $unapplied = $self->total_unapplied_credits
2577 + $self->total_unapplied_payments
2578 + $self->in_transit_payments;
2579 foreach my $cust_bill ($self->open_cust_bill) {
2580 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2581 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2582 'invnum' => $cust_bill->invnum,
2583 'paybatchnum' => $cust_pay_batch->paybatchnum,
2584 'amount' => $cust_bill->owed,
2587 if ($unapplied >= $cust_bill_pay_batch->amount){
2588 $unapplied -= $cust_bill_pay_batch->amount;
2591 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2592 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2594 $error = $cust_bill_pay_batch->insert;
2596 $dbh->rollback if $oldAutoCommit;
2601 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2607 Returns the total owed for this customer on all invoices
2608 (see L<FS::cust_bill/owed>).
2614 $self->total_owed_date(2145859200); #12/31/2037
2617 =item total_owed_date TIME
2619 Returns the total owed for this customer on all invoices with date earlier than
2620 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2621 see L<Time::Local> and L<Date::Parse> for conversion functions.
2625 sub total_owed_date {
2629 my $custnum = $self->custnum;
2631 my $owed_sql = FS::cust_bill->owed_sql;
2634 SELECT SUM($owed_sql) FROM cust_bill
2635 WHERE custnum = $custnum
2639 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2643 =item total_owed_pkgnum PKGNUM
2645 Returns the total owed on all invoices for this customer's specific package
2646 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2650 sub total_owed_pkgnum {
2651 my( $self, $pkgnum ) = @_;
2652 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2655 =item total_owed_date_pkgnum TIME PKGNUM
2657 Returns the total owed for this customer's specific package when using
2658 experimental package balances on all invoices with date earlier than
2659 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2660 see L<Time::Local> and L<Date::Parse> for conversion functions.
2664 sub total_owed_date_pkgnum {
2665 my( $self, $time, $pkgnum ) = @_;
2668 foreach my $cust_bill (
2669 grep { $_->_date <= $time }
2670 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2672 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2674 sprintf( "%.2f", $total_bill );
2680 Returns the total amount of all payments.
2687 $total += $_->paid foreach $self->cust_pay;
2688 sprintf( "%.2f", $total );
2691 =item total_unapplied_credits
2693 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2694 customer. See L<FS::cust_credit/credited>.
2696 =item total_credited
2698 Old name for total_unapplied_credits. Don't use.
2702 sub total_credited {
2703 #carp "total_credited deprecated, use total_unapplied_credits";
2704 shift->total_unapplied_credits(@_);
2707 sub total_unapplied_credits {
2710 my $custnum = $self->custnum;
2712 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2715 SELECT SUM($unapplied_sql) FROM cust_credit
2716 WHERE custnum = $custnum
2719 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2723 =item total_unapplied_credits_pkgnum PKGNUM
2725 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2726 customer. See L<FS::cust_credit/credited>.
2730 sub total_unapplied_credits_pkgnum {
2731 my( $self, $pkgnum ) = @_;
2732 my $total_credit = 0;
2733 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2734 sprintf( "%.2f", $total_credit );
2738 =item total_unapplied_payments
2740 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2741 See L<FS::cust_pay/unapplied>.
2745 sub total_unapplied_payments {
2748 my $custnum = $self->custnum;
2750 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2753 SELECT SUM($unapplied_sql) FROM cust_pay
2754 WHERE custnum = $custnum
2757 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2761 =item total_unapplied_payments_pkgnum PKGNUM
2763 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2764 specific package when using experimental package balances. See
2765 L<FS::cust_pay/unapplied>.
2769 sub total_unapplied_payments_pkgnum {
2770 my( $self, $pkgnum ) = @_;
2771 my $total_unapplied = 0;
2772 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2773 sprintf( "%.2f", $total_unapplied );
2777 =item total_unapplied_refunds
2779 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2780 customer. See L<FS::cust_refund/unapplied>.
2784 sub total_unapplied_refunds {
2786 my $custnum = $self->custnum;
2788 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2791 SELECT SUM($unapplied_sql) FROM cust_refund
2792 WHERE custnum = $custnum
2795 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2801 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2802 total_unapplied_credits minus total_unapplied_payments).
2808 $self->balance_date_range;
2811 =item balance_date TIME
2813 Returns the balance for this customer, only considering invoices with date
2814 earlier than TIME (total_owed_date minus total_credited minus
2815 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2816 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2823 $self->balance_date_range(shift);
2826 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2828 Returns the balance for this customer, optionally considering invoices with
2829 date earlier than START_TIME, and not later than END_TIME
2830 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2832 Times are specified as SQL fragments or numeric
2833 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2834 L<Date::Parse> for conversion functions. The empty string can be passed
2835 to disable that time constraint completely.
2837 Available options are:
2841 =item unapplied_date
2843 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)
2849 sub balance_date_range {
2851 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2852 ') FROM cust_main WHERE custnum='. $self->custnum;
2853 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2856 =item balance_pkgnum PKGNUM
2858 Returns the balance for this customer's specific package when using
2859 experimental package balances (total_owed plus total_unrefunded, minus
2860 total_unapplied_credits minus total_unapplied_payments)
2864 sub balance_pkgnum {
2865 my( $self, $pkgnum ) = @_;
2868 $self->total_owed_pkgnum($pkgnum)
2869 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2870 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2871 - $self->total_unapplied_credits_pkgnum($pkgnum)
2872 - $self->total_unapplied_payments_pkgnum($pkgnum)
2876 =item in_transit_payments
2878 Returns the total of requests for payments for this customer pending in
2879 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2883 sub in_transit_payments {
2885 my $in_transit_payments = 0;
2886 foreach my $pay_batch ( qsearch('pay_batch', {
2889 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2890 'batchnum' => $pay_batch->batchnum,
2891 'custnum' => $self->custnum,
2893 $in_transit_payments += $cust_pay_batch->amount;
2896 sprintf( "%.2f", $in_transit_payments );
2901 Returns a hash of useful information for making a payment.
2911 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2912 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2913 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2917 For credit card transactions:
2929 For electronic check transactions:
2944 $return{balance} = $self->balance;
2946 $return{payname} = $self->payname
2947 || ( $self->first. ' '. $self->get('last') );
2949 $return{$_} = $self->bill_location->$_
2950 for qw(address1 address2 city state zip);
2952 $return{payby} = $self->payby;
2953 $return{stateid_state} = $self->stateid_state;
2955 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2956 $return{card_type} = cardtype($self->payinfo);
2957 $return{payinfo} = $self->paymask;
2959 @return{'month', 'year'} = $self->paydate_monthyear;
2963 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2964 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2965 $return{payinfo1} = $payinfo1;
2966 $return{payinfo2} = $payinfo2;
2967 $return{paytype} = $self->paytype;
2968 $return{paystate} = $self->paystate;
2972 #doubleclick protection
2974 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2980 =item paydate_monthyear
2982 Returns a two-element list consisting of the month and year of this customer's
2983 paydate (credit card expiration date for CARD customers)
2987 sub paydate_monthyear {
2989 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2991 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3000 Returns the exact time in seconds corresponding to the payment method
3001 expiration date. For CARD/DCRD customers this is the end of the month;
3002 for others (COMP is the only other payby that uses paydate) it's the start.
3003 Returns 0 if the paydate is empty or set to the far future.
3009 my ($month, $year) = $self->paydate_monthyear;
3010 return 0 if !$year or $year >= 2037;
3011 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3013 if ( $month == 13 ) {
3017 return timelocal(0,0,0,1,$month-1,$year) - 1;
3020 return timelocal(0,0,0,1,$month-1,$year);
3024 =item paydate_epoch_sql
3026 Class method. Returns an SQL expression to obtain the payment expiration date
3027 as a number of seconds.
3031 # Special expiration date behavior for non-CARD/DCRD customers has been
3032 # carefully preserved. Do we really use that?
3033 sub paydate_epoch_sql {
3035 my $table = shift || 'cust_main';
3036 my ($case1, $case2);
3037 if ( driver_name eq 'Pg' ) {
3038 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3039 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3041 elsif ( lc(driver_name) eq 'mysql' ) {
3042 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3043 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3046 return "CASE WHEN $table.payby IN('CARD','DCRD')
3052 =item tax_exemption TAXNAME
3057 my( $self, $taxname ) = @_;
3059 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3060 'taxname' => $taxname,
3065 =item cust_main_exemption
3067 =item invoicing_list [ ARRAYREF ]
3069 If an arguement is given, sets these email addresses as invoice recipients
3070 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3071 (except as warnings), so use check_invoicing_list first.
3073 Returns a list of email addresses (with svcnum entries expanded).
3075 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3076 check it without disturbing anything by passing nothing.
3078 This interface may change in the future.
3082 sub invoicing_list {
3083 my( $self, $arrayref ) = @_;
3086 my @cust_main_invoice;
3087 if ( $self->custnum ) {
3088 @cust_main_invoice =
3089 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3091 @cust_main_invoice = ();
3093 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3094 #warn $cust_main_invoice->destnum;
3095 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3096 #warn $cust_main_invoice->destnum;
3097 my $error = $cust_main_invoice->delete;
3098 warn $error if $error;
3101 if ( $self->custnum ) {
3102 @cust_main_invoice =
3103 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3105 @cust_main_invoice = ();
3107 my %seen = map { $_->address => 1 } @cust_main_invoice;
3108 foreach my $address ( @{$arrayref} ) {
3109 next if exists $seen{$address} && $seen{$address};
3110 $seen{$address} = 1;
3111 my $cust_main_invoice = new FS::cust_main_invoice ( {
3112 'custnum' => $self->custnum,
3115 my $error = $cust_main_invoice->insert;
3116 warn $error if $error;
3120 if ( $self->custnum ) {
3122 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3129 =item check_invoicing_list ARRAYREF
3131 Checks these arguements as valid input for the invoicing_list method. If there
3132 is an error, returns the error, otherwise returns false.
3136 sub check_invoicing_list {
3137 my( $self, $arrayref ) = @_;
3139 foreach my $address ( @$arrayref ) {
3141 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3142 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3145 my $cust_main_invoice = new FS::cust_main_invoice ( {
3146 'custnum' => $self->custnum,
3149 my $error = $self->custnum
3150 ? $cust_main_invoice->check
3151 : $cust_main_invoice->checkdest
3153 return $error if $error;
3157 return "Email address required"
3158 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3159 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3164 =item set_default_invoicing_list
3166 Sets the invoicing list to all accounts associated with this customer,
3167 overwriting any previous invoicing list.
3171 sub set_default_invoicing_list {
3173 $self->invoicing_list($self->all_emails);
3178 Returns the email addresses of all accounts provisioned for this customer.
3185 foreach my $cust_pkg ( $self->all_pkgs ) {
3186 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3188 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3189 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3191 $list{$_}=1 foreach map { $_->email } @svc_acct;
3196 =item invoicing_list_addpost
3198 Adds postal invoicing to this customer. If this customer is already configured
3199 to receive postal invoices, does nothing.
3203 sub invoicing_list_addpost {
3205 return if grep { $_ eq 'POST' } $self->invoicing_list;
3206 my @invoicing_list = $self->invoicing_list;
3207 push @invoicing_list, 'POST';
3208 $self->invoicing_list(\@invoicing_list);
3211 =item invoicing_list_emailonly
3213 Returns the list of email invoice recipients (invoicing_list without non-email
3214 destinations such as POST and FAX).
3218 sub invoicing_list_emailonly {
3220 warn "$me invoicing_list_emailonly called"
3222 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3225 =item invoicing_list_emailonly_scalar
3227 Returns the list of email invoice recipients (invoicing_list without non-email
3228 destinations such as POST and FAX) as a comma-separated scalar.
3232 sub invoicing_list_emailonly_scalar {
3234 warn "$me invoicing_list_emailonly_scalar called"
3236 join(', ', $self->invoicing_list_emailonly);
3239 =item referral_custnum_cust_main
3241 Returns the customer who referred this customer (or the empty string, if
3242 this customer was not referred).
3244 Note the difference with referral_cust_main method: This method,
3245 referral_custnum_cust_main returns the single customer (if any) who referred
3246 this customer, while referral_cust_main returns an array of customers referred
3251 sub referral_custnum_cust_main {
3253 return '' unless $self->referral_custnum;
3254 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3257 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3259 Returns an array of customers referred by this customer (referral_custnum set
3260 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3261 customers referred by customers referred by this customer and so on, inclusive.
3262 The default behavior is DEPTH 1 (no recursion).
3264 Note the difference with referral_custnum_cust_main method: This method,
3265 referral_cust_main, returns an array of customers referred BY this customer,
3266 while referral_custnum_cust_main returns the single customer (if any) who
3267 referred this customer.
3271 sub referral_cust_main {
3273 my $depth = @_ ? shift : 1;
3274 my $exclude = @_ ? shift : {};
3277 map { $exclude->{$_->custnum}++; $_; }
3278 grep { ! $exclude->{ $_->custnum } }
3279 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3283 map { $_->referral_cust_main($depth-1, $exclude) }
3290 =item referral_cust_main_ncancelled
3292 Same as referral_cust_main, except only returns customers with uncancelled
3297 sub referral_cust_main_ncancelled {
3299 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3302 =item referral_cust_pkg [ DEPTH ]
3304 Like referral_cust_main, except returns a flat list of all unsuspended (and
3305 uncancelled) packages for each customer. The number of items in this list may
3306 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3310 sub referral_cust_pkg {
3312 my $depth = @_ ? shift : 1;
3314 map { $_->unsuspended_pkgs }
3315 grep { $_->unsuspended_pkgs }
3316 $self->referral_cust_main($depth);
3319 =item referring_cust_main
3321 Returns the single cust_main record for the customer who referred this customer
3322 (referral_custnum), or false.
3326 sub referring_cust_main {
3328 return '' unless $self->referral_custnum;
3329 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3332 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3334 Applies a credit to this customer. If there is an error, returns the error,
3335 otherwise returns false.
3337 REASON can be a text string, an FS::reason object, or a scalar reference to
3338 a reasonnum. If a text string, it will be automatically inserted as a new
3339 reason, and a 'reason_type' option must be passed to indicate the
3340 FS::reason_type for the new reason.
3342 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3343 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3344 I<commission_pkgnum>.
3346 Any other options are passed to FS::cust_credit::insert.
3351 my( $self, $amount, $reason, %options ) = @_;
3353 my $cust_credit = new FS::cust_credit {
3354 'custnum' => $self->custnum,
3355 'amount' => $amount,
3358 if ( ref($reason) ) {
3360 if ( ref($reason) eq 'SCALAR' ) {
3361 $cust_credit->reasonnum( $$reason );
3363 $cust_credit->reasonnum( $reason->reasonnum );
3367 $cust_credit->set('reason', $reason)
3370 $cust_credit->$_( delete $options{$_} )
3371 foreach grep exists($options{$_}),
3372 qw( addlinfo eventnum ),
3373 map "commission_$_", qw( agentnum salesnum pkgnum );
3375 $cust_credit->insert(%options);
3379 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3381 Creates a one-time charge for this customer. If there is an error, returns
3382 the error, otherwise returns false.
3384 New-style, with a hashref of options:
3386 my $error = $cust_main->charge(
3390 'start_date' => str2time('7/4/2009'),
3391 'pkg' => 'Description',
3392 'comment' => 'Comment',
3393 'additional' => [], #extra invoice detail
3394 'classnum' => 1, #pkg_class
3396 'setuptax' => '', # or 'Y' for tax exempt
3398 'locationnum'=> 1234, # optional
3401 'taxclass' => 'Tax class',
3404 'taxproduct' => 2, #part_pkg_taxproduct
3405 'override' => {}, #XXX describe
3407 #will be filled in with the new object
3408 'cust_pkg_ref' => \$cust_pkg,
3410 #generate an invoice immediately
3412 'invoice_terms' => '', #with these terms
3418 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3424 my ( $amount, $quantity, $start_date, $classnum );
3425 my ( $pkg, $comment, $additional );
3426 my ( $setuptax, $taxclass ); #internal taxes
3427 my ( $taxproduct, $override ); #vendor (CCH) taxes
3429 my $cust_pkg_ref = '';
3430 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3432 if ( ref( $_[0] ) ) {
3433 $amount = $_[0]->{amount};
3434 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3435 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3436 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3437 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3438 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3439 : '$'. sprintf("%.2f",$amount);
3440 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3441 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3442 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3443 $additional = $_[0]->{additional} || [];
3444 $taxproduct = $_[0]->{taxproductnum};
3445 $override = { '' => $_[0]->{tax_override} };
3446 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3447 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3448 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3449 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3454 $pkg = @_ ? shift : 'One-time charge';
3455 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3457 $taxclass = @_ ? shift : '';
3461 local $SIG{HUP} = 'IGNORE';
3462 local $SIG{INT} = 'IGNORE';
3463 local $SIG{QUIT} = 'IGNORE';
3464 local $SIG{TERM} = 'IGNORE';
3465 local $SIG{TSTP} = 'IGNORE';
3466 local $SIG{PIPE} = 'IGNORE';
3468 my $oldAutoCommit = $FS::UID::AutoCommit;
3469 local $FS::UID::AutoCommit = 0;
3472 my $part_pkg = new FS::part_pkg ( {
3474 'comment' => $comment,
3478 'classnum' => ( $classnum ? $classnum : '' ),
3479 'setuptax' => $setuptax,
3480 'taxclass' => $taxclass,
3481 'taxproductnum' => $taxproduct,
3484 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3485 ( 0 .. @$additional - 1 )
3487 'additional_count' => scalar(@$additional),
3488 'setup_fee' => $amount,
3491 my $error = $part_pkg->insert( options => \%options,
3492 tax_overrides => $override,
3495 $dbh->rollback if $oldAutoCommit;
3499 my $pkgpart = $part_pkg->pkgpart;
3500 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3501 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3502 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3503 $error = $type_pkgs->insert;
3505 $dbh->rollback if $oldAutoCommit;
3510 my $cust_pkg = new FS::cust_pkg ( {
3511 'custnum' => $self->custnum,
3512 'pkgpart' => $pkgpart,
3513 'quantity' => $quantity,
3514 'start_date' => $start_date,
3515 'no_auto' => $no_auto,
3516 'locationnum'=> $locationnum,
3519 $error = $cust_pkg->insert;
3521 $dbh->rollback if $oldAutoCommit;
3523 } elsif ( $cust_pkg_ref ) {
3524 ${$cust_pkg_ref} = $cust_pkg;
3528 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3529 'pkg_list' => [ $cust_pkg ],
3532 $dbh->rollback if $oldAutoCommit;
3537 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3542 #=item charge_postal_fee
3544 #Applies a one time charge this customer. If there is an error,
3545 #returns the error, returns the cust_pkg charge object or false
3546 #if there was no charge.
3550 # This should be a customer event. For that to work requires that bill
3551 # also be a customer event.
3553 sub charge_postal_fee {
3556 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3557 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3559 my $cust_pkg = new FS::cust_pkg ( {
3560 'custnum' => $self->custnum,
3561 'pkgpart' => $pkgpart,
3565 my $error = $cust_pkg->insert;
3566 $error ? $error : $cust_pkg;
3569 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3571 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3573 Optionally, a list or hashref of additional arguments to the qsearch call can
3580 my $opt = ref($_[0]) ? shift : { @_ };
3582 #return $self->num_cust_bill unless wantarray || keys %$opt;
3584 $opt->{'table'} = 'cust_bill';
3585 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3586 $opt->{'hashref'}{'custnum'} = $self->custnum;
3587 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3589 map { $_ } #behavior of sort undefined in scalar context
3590 sort { $a->_date <=> $b->_date }
3594 =item open_cust_bill
3596 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3601 sub open_cust_bill {
3605 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3611 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3613 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3617 sub legacy_cust_bill {
3620 #return $self->num_legacy_cust_bill unless wantarray;
3622 map { $_ } #behavior of sort undefined in scalar context
3623 sort { $a->_date <=> $b->_date }
3624 qsearch({ 'table' => 'legacy_cust_bill',
3625 'hashref' => { 'custnum' => $self->custnum, },
3626 'order_by' => 'ORDER BY _date ASC',
3630 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3632 Returns all the statements (see L<FS::cust_statement>) for this customer.
3634 Optionally, a list or hashref of additional arguments to the qsearch call can
3639 =item cust_bill_void
3641 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3645 sub cust_bill_void {
3648 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3649 sort { $a->_date <=> $b->_date }
3650 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3653 sub cust_statement {
3655 my $opt = ref($_[0]) ? shift : { @_ };
3657 #return $self->num_cust_statement unless wantarray || keys %$opt;
3659 $opt->{'table'} = 'cust_statement';
3660 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3661 $opt->{'hashref'}{'custnum'} = $self->custnum;
3662 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3664 map { $_ } #behavior of sort undefined in scalar context
3665 sort { $a->_date <=> $b->_date }
3669 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3671 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3673 Optionally, a list or hashref of additional arguments to the qsearch call can
3674 be passed following the SVCDB.
3681 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3682 warn "$me svc_x requires a svcdb";
3685 my $opt = ref($_[0]) ? shift : { @_ };
3687 $opt->{'table'} = $svcdb;
3688 $opt->{'addl_from'} =
3689 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3690 ($opt->{'addl_from'} || '');
3692 my $custnum = $self->custnum;
3693 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3694 my $where = "cust_pkg.custnum = $custnum";
3696 my $extra_sql = $opt->{'extra_sql'} || '';
3697 if ( keys %{ $opt->{'hashref'} } ) {
3698 $extra_sql = " AND $where $extra_sql";
3701 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3702 $extra_sql = "WHERE $where AND $1";
3705 $extra_sql = "WHERE $where $extra_sql";
3708 $opt->{'extra_sql'} = $extra_sql;
3713 # required for use as an eventtable;
3716 $self->svc_x('svc_acct', @_);
3721 Returns all the credits (see L<FS::cust_credit>) for this customer.
3727 map { $_ } #return $self->num_cust_credit unless wantarray;
3728 sort { $a->_date <=> $b->_date }
3729 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3732 =item cust_credit_pkgnum
3734 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3735 package when using experimental package balances.
3739 sub cust_credit_pkgnum {
3740 my( $self, $pkgnum ) = @_;
3741 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3742 sort { $a->_date <=> $b->_date }
3743 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3744 'pkgnum' => $pkgnum,
3749 =item cust_credit_void
3751 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3755 sub cust_credit_void {
3758 sort { $a->_date <=> $b->_date }
3759 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3764 Returns all the payments (see L<FS::cust_pay>) for this customer.
3770 return $self->num_cust_pay unless wantarray;
3771 sort { $a->_date <=> $b->_date }
3772 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3777 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3778 called automatically when the cust_pay method is used in a scalar context.
3784 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3785 my $sth = dbh->prepare($sql) or die dbh->errstr;
3786 $sth->execute($self->custnum) or die $sth->errstr;
3787 $sth->fetchrow_arrayref->[0];
3790 =item cust_pay_pkgnum
3792 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3793 package when using experimental package balances.
3797 sub cust_pay_pkgnum {
3798 my( $self, $pkgnum ) = @_;
3799 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3800 sort { $a->_date <=> $b->_date }
3801 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3802 'pkgnum' => $pkgnum,
3809 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3815 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3816 sort { $a->_date <=> $b->_date }
3817 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3820 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3822 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3824 Optionally, a list or hashref of additional arguments to the qsearch call can
3829 sub cust_pay_batch {
3831 my $opt = ref($_[0]) ? shift : { @_ };
3833 #return $self->num_cust_statement unless wantarray || keys %$opt;
3835 $opt->{'table'} = 'cust_pay_batch';
3836 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3837 $opt->{'hashref'}{'custnum'} = $self->custnum;
3838 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3840 map { $_ } #behavior of sort undefined in scalar context
3841 sort { $a->paybatchnum <=> $b->paybatchnum }
3845 =item cust_pay_pending
3847 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3848 (without status "done").
3852 sub cust_pay_pending {
3854 return $self->num_cust_pay_pending unless wantarray;
3855 sort { $a->_date <=> $b->_date }
3856 qsearch( 'cust_pay_pending', {
3857 'custnum' => $self->custnum,
3858 'status' => { op=>'!=', value=>'done' },
3863 =item cust_pay_pending_attempt
3865 Returns all payment attempts / declined payments for this customer, as pending
3866 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3867 a corresponding payment (see L<FS::cust_pay>).
3871 sub cust_pay_pending_attempt {
3873 return $self->num_cust_pay_pending_attempt unless wantarray;
3874 sort { $a->_date <=> $b->_date }
3875 qsearch( 'cust_pay_pending', {
3876 'custnum' => $self->custnum,
3883 =item num_cust_pay_pending
3885 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3886 customer (without status "done"). Also called automatically when the
3887 cust_pay_pending method is used in a scalar context.
3891 sub num_cust_pay_pending {
3894 " SELECT COUNT(*) FROM cust_pay_pending ".
3895 " WHERE custnum = ? AND status != 'done' ",
3900 =item num_cust_pay_pending_attempt
3902 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3903 customer, with status "done" but without a corresp. Also called automatically when the
3904 cust_pay_pending method is used in a scalar context.
3908 sub num_cust_pay_pending_attempt {
3911 " SELECT COUNT(*) FROM cust_pay_pending ".
3912 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3919 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3925 map { $_ } #return $self->num_cust_refund unless wantarray;
3926 sort { $a->_date <=> $b->_date }
3927 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3930 =item display_custnum
3932 Returns the displayed customer number for this customer: agent_custid if
3933 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3937 sub display_custnum {
3940 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3941 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3942 if ( $special eq 'CoStAg' ) {
3943 $prefix = uc( join('',
3945 ($self->state =~ /^(..)/),
3946 $prefix || ($self->agent->agent =~ /^(..)/)
3949 elsif ( $special eq 'CoStCl' ) {
3950 $prefix = uc( join('',
3952 ($self->state =~ /^(..)/),
3953 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3956 # add any others here if needed
3959 my $length = $conf->config('cust_main-custnum-display_length');
3960 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3961 return $self->agent_custid;
3962 } elsif ( $prefix ) {
3963 $length = 8 if !defined($length);
3965 sprintf('%0'.$length.'d', $self->custnum)
3966 } elsif ( $length ) {
3967 return sprintf('%0'.$length.'d', $self->custnum);
3969 return $self->custnum;
3975 Returns a name string for this customer, either "Company (Last, First)" or
3982 my $name = $self->contact;
3983 $name = $self->company. " ($name)" if $self->company;
3987 =item service_contact
3989 Returns the L<FS::contact> object for this customer that has the 'Service'
3990 contact class, or undef if there is no such contact. Deprecated; don't use
3995 sub service_contact {
3997 if ( !exists($self->{service_contact}) ) {
3998 my $classnum = $self->scalar_sql(
3999 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4000 ) || 0; #if it's zero, qsearchs will return nothing
4001 $self->{service_contact} = qsearchs('contact', {
4002 'classnum' => $classnum, 'custnum' => $self->custnum
4005 $self->{service_contact};
4010 Returns a name string for this (service/shipping) contact, either
4011 "Company (Last, First)" or "Last, First".
4018 my $name = $self->ship_contact;
4019 $name = $self->company. " ($name)" if $self->company;
4025 Returns a name string for this customer, either "Company" or "First Last".
4031 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4034 =item ship_name_short
4036 Returns a name string for this (service/shipping) contact, either "Company"
4041 sub ship_name_short {
4043 $self->service_contact
4044 ? $self->ship_contact_firstlast
4050 Returns this customer's full (billing) contact name only, "Last, First"
4056 $self->get('last'). ', '. $self->first;
4061 Returns this customer's full (shipping) contact name only, "Last, First"
4067 my $contact = $self->service_contact || $self;
4068 $contact->get('last') . ', ' . $contact->get('first');
4071 =item contact_firstlast
4073 Returns this customers full (billing) contact name only, "First Last".
4077 sub contact_firstlast {
4079 $self->first. ' '. $self->get('last');
4082 =item ship_contact_firstlast
4084 Returns this customer's full (shipping) contact name only, "First Last".
4088 sub ship_contact_firstlast {
4090 my $contact = $self->service_contact || $self;
4091 $contact->get('first') . ' '. $contact->get('last');
4094 #XXX this doesn't work in 3.x+
4097 #Returns this customer's full country name
4103 # code2country($self->country);
4106 sub bill_country_full {
4108 code2country($self->bill_location->country);
4111 sub ship_country_full {
4113 code2country($self->ship_location->country);
4116 =item county_state_county [ PREFIX ]
4118 Returns a string consisting of just the county, state and country.
4122 sub county_state_country {
4125 if ( @_ && $_[0] && $self->has_ship_address ) {
4126 $locationnum = $self->ship_locationnum;
4128 $locationnum = $self->bill_locationnum;
4130 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4131 $cust_location->county_state_country;
4134 =item geocode DATA_VENDOR
4136 Returns a value for the customer location as encoded by DATA_VENDOR.
4137 Currently this only makes sense for "CCH" as DATA_VENDOR.
4145 Returns a status string for this customer, currently:
4149 =item prospect - No packages have ever been ordered
4151 =item ordered - Recurring packages all are new (not yet billed).
4153 =item active - One or more recurring packages is active
4155 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4157 =item suspended - All non-cancelled recurring packages are suspended
4159 =item cancelled - All recurring packages are cancelled
4163 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4164 cust_main-status_module configuration option.
4168 sub status { shift->cust_status(@_); }
4172 for my $status ( FS::cust_main->statuses() ) {
4173 my $method = $status.'_sql';
4174 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4175 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4176 $sth->execute( ($self->custnum) x $numnum )
4177 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4178 return $status if $sth->fetchrow_arrayref->[0];
4182 =item ucfirst_cust_status
4184 =item ucfirst_status
4186 Returns the status with the first character capitalized.
4190 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4192 sub ucfirst_cust_status {
4194 ucfirst($self->cust_status);
4199 Returns a hex triplet color string for this customer's status.
4203 sub statuscolor { shift->cust_statuscolor(@_); }
4205 sub cust_statuscolor {
4207 __PACKAGE__->statuscolors->{$self->cust_status};
4210 =item tickets [ STATUS ]
4212 Returns an array of hashes representing the customer's RT tickets.
4214 An optional status (or arrayref or hashref of statuses) may be specified.
4220 my $status = ( @_ && $_[0] ) ? shift : '';
4222 my $num = $conf->config('cust_main-max_tickets') || 10;
4225 if ( $conf->config('ticket_system') ) {
4226 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4228 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4237 foreach my $priority (
4238 $conf->config('ticket_system-custom_priority_field-values'), ''
4240 last if scalar(@tickets) >= $num;
4242 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4243 $num - scalar(@tickets),
4254 # Return services representing svc_accts in customer support packages
4255 sub support_services {
4257 my %packages = map { $_ => 1 } $conf->config('support_packages');
4259 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4260 grep { $_->part_svc->svcdb eq 'svc_acct' }
4261 map { $_->cust_svc }
4262 grep { exists $packages{ $_->pkgpart } }
4263 $self->ncancelled_pkgs;
4267 # Return a list of latitude/longitude for one of the services (if any)
4268 sub service_coordinates {
4272 grep { $_->latitude && $_->longitude }
4274 map { $_->cust_svc }
4275 $self->ncancelled_pkgs;
4277 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4282 Returns a masked version of the named field
4287 my ($self,$field) = @_;
4291 'x'x(length($self->getfield($field))-4).
4292 substr($self->getfield($field), (length($self->getfield($field))-4));
4298 =head1 CLASS METHODS
4304 Class method that returns the list of possible status strings for customers
4305 (see L<the status method|/status>). For example:
4307 @statuses = FS::cust_main->statuses();
4313 keys %{ $self->statuscolors };
4316 =item cust_status_sql
4318 Returns an SQL fragment to determine the status of a cust_main record, as a
4323 sub cust_status_sql {
4325 for my $status ( FS::cust_main->statuses() ) {
4326 my $method = $status.'_sql';
4327 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4336 Returns an SQL expression identifying prospective cust_main records (customers
4337 with no packages ever ordered)
4341 use vars qw($select_count_pkgs);
4342 $select_count_pkgs =
4343 "SELECT COUNT(*) FROM cust_pkg
4344 WHERE cust_pkg.custnum = cust_main.custnum";
4346 sub select_count_pkgs_sql {
4351 " 0 = ( $select_count_pkgs ) ";
4356 Returns an SQL expression identifying ordered cust_main records (customers with
4357 no active packages, but recurring packages not yet setup or one time charges
4363 FS::cust_main->none_active_sql.
4364 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4369 Returns an SQL expression identifying active cust_main records (customers with
4370 active recurring packages).
4375 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4378 =item none_active_sql
4380 Returns an SQL expression identifying cust_main records with no active
4381 recurring packages. This includes customers of status prospect, ordered,
4382 inactive, and suspended.
4386 sub none_active_sql {
4387 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4392 Returns an SQL expression identifying inactive cust_main records (customers with
4393 no active recurring packages, but otherwise unsuspended/uncancelled).
4398 FS::cust_main->none_active_sql.
4399 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4405 Returns an SQL expression identifying suspended cust_main records.
4410 sub suspended_sql { susp_sql(@_); }
4412 FS::cust_main->none_active_sql.
4413 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4419 Returns an SQL expression identifying cancelled cust_main records.
4423 sub cancel_sql { shift->cancelled_sql(@_); }
4426 =item uncancelled_sql
4428 Returns an SQL expression identifying un-cancelled cust_main records.
4432 sub uncancelled_sql { uncancel_sql(@_); }
4433 sub uncancel_sql { "
4434 ( 0 < ( $select_count_pkgs
4435 AND ( cust_pkg.cancel IS NULL
4436 OR cust_pkg.cancel = 0
4439 OR 0 = ( $select_count_pkgs )
4445 Returns an SQL fragment to retreive the balance.
4450 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4451 WHERE cust_bill.custnum = cust_main.custnum )
4452 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4453 WHERE cust_pay.custnum = cust_main.custnum )
4454 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4455 WHERE cust_credit.custnum = cust_main.custnum )
4456 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4457 WHERE cust_refund.custnum = cust_main.custnum )
4460 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4462 Returns an SQL fragment to retreive the balance for this customer, optionally
4463 considering invoices with date earlier than START_TIME, and not
4464 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4465 total_unapplied_payments).
4467 Times are specified as SQL fragments or numeric
4468 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4469 L<Date::Parse> for conversion functions. The empty string can be passed
4470 to disable that time constraint completely.
4472 Available options are:
4476 =item unapplied_date
4478 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)
4483 set to true to remove all customer comparison clauses, for totals
4488 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4493 JOIN clause (typically used with the total option)
4497 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4498 time will be ignored. Note that START_TIME and END_TIME only limit the date
4499 range for invoices and I<unapplied> payments, credits, and refunds.
4505 sub balance_date_sql {
4506 my( $class, $start, $end, %opt ) = @_;
4508 my $cutoff = $opt{'cutoff'};
4510 my $owed = FS::cust_bill->owed_sql($cutoff);
4511 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4512 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4513 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4515 my $j = $opt{'join'} || '';
4517 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4518 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4519 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4520 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4522 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4523 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4524 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4525 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4530 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4532 Returns an SQL fragment to retreive the total unapplied payments for this
4533 customer, only considering payments with date earlier than START_TIME, and
4534 optionally not later than END_TIME.
4536 Times are specified as SQL fragments or numeric
4537 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4538 L<Date::Parse> for conversion functions. The empty string can be passed
4539 to disable that time constraint completely.
4541 Available options are:
4545 sub unapplied_payments_date_sql {
4546 my( $class, $start, $end, %opt ) = @_;
4548 my $cutoff = $opt{'cutoff'};
4550 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4552 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4553 'unapplied_date'=>1 );
4555 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4558 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4560 Helper method for balance_date_sql; name (and usage) subject to change
4561 (suggestions welcome).
4563 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4564 cust_refund, cust_credit or cust_pay).
4566 If TABLE is "cust_bill" or the unapplied_date option is true, only
4567 considers records with date earlier than START_TIME, and optionally not
4568 later than END_TIME .
4572 sub _money_table_where {
4573 my( $class, $table, $start, $end, %opt ) = @_;
4576 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4577 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4578 push @where, "$table._date <= $start" if defined($start) && length($start);
4579 push @where, "$table._date > $end" if defined($end) && length($end);
4581 push @where, @{$opt{'where'}} if $opt{'where'};
4582 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4588 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4589 use FS::cust_main::Search;
4592 FS::cust_main::Search->search(@_);
4607 #warn join('-',keys %$param);
4608 my $fh = $param->{filehandle};
4609 my $agentnum = $param->{agentnum};
4610 my $format = $param->{format};
4612 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4615 if ( $format eq 'simple' ) {
4616 @fields = qw( custnum agent_custid amount pkg );
4618 die "unknown format $format";
4621 eval "use Text::CSV_XS;";
4624 my $csv = new Text::CSV_XS;
4631 local $SIG{HUP} = 'IGNORE';
4632 local $SIG{INT} = 'IGNORE';
4633 local $SIG{QUIT} = 'IGNORE';
4634 local $SIG{TERM} = 'IGNORE';
4635 local $SIG{TSTP} = 'IGNORE';
4636 local $SIG{PIPE} = 'IGNORE';
4638 my $oldAutoCommit = $FS::UID::AutoCommit;
4639 local $FS::UID::AutoCommit = 0;
4642 #while ( $columns = $csv->getline($fh) ) {
4644 while ( defined($line=<$fh>) ) {
4646 $csv->parse($line) or do {
4647 $dbh->rollback if $oldAutoCommit;
4648 return "can't parse: ". $csv->error_input();
4651 my @columns = $csv->fields();
4652 #warn join('-',@columns);
4655 foreach my $field ( @fields ) {
4656 $row{$field} = shift @columns;
4659 if ( $row{custnum} && $row{agent_custid} ) {
4660 dbh->rollback if $oldAutoCommit;
4661 return "can't specify custnum with agent_custid $row{agent_custid}";
4665 if ( $row{agent_custid} && $agentnum ) {
4666 %hash = ( 'agent_custid' => $row{agent_custid},
4667 'agentnum' => $agentnum,
4671 if ( $row{custnum} ) {
4672 %hash = ( 'custnum' => $row{custnum} );
4675 unless ( scalar(keys %hash) ) {
4676 $dbh->rollback if $oldAutoCommit;
4677 return "can't find customer without custnum or agent_custid and agentnum";
4680 my $cust_main = qsearchs('cust_main', { %hash } );
4681 unless ( $cust_main ) {
4682 $dbh->rollback if $oldAutoCommit;
4683 my $custnum = $row{custnum} || $row{agent_custid};
4684 return "unknown custnum $custnum";
4687 if ( $row{'amount'} > 0 ) {
4688 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4690 $dbh->rollback if $oldAutoCommit;
4694 } elsif ( $row{'amount'} < 0 ) {
4695 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4698 $dbh->rollback if $oldAutoCommit;
4708 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4710 return "Empty file!" unless $imported;
4716 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4718 Deprecated. Use event notification and message templates
4719 (L<FS::msg_template>) instead.
4721 Sends a templated email notification to the customer (see L<Text::Template>).
4723 OPTIONS is a hash and may include
4725 I<from> - the email sender (default is invoice_from)
4727 I<to> - comma-separated scalar or arrayref of recipients
4728 (default is invoicing_list)
4730 I<subject> - The subject line of the sent email notification
4731 (default is "Notice from company_name")
4733 I<extra_fields> - a hashref of name/value pairs which will be substituted
4736 The following variables are vavailable in the template.
4738 I<$first> - the customer first name
4739 I<$last> - the customer last name
4740 I<$company> - the customer company
4741 I<$payby> - a description of the method of payment for the customer
4742 # would be nice to use FS::payby::shortname
4743 I<$payinfo> - the account information used to collect for this customer
4744 I<$expdate> - the expiration of the customer payment in seconds from epoch
4749 my ($self, $template, %options) = @_;
4751 return unless $conf->exists($template);
4753 my $from = $conf->config('invoice_from', $self->agentnum)
4754 if $conf->exists('invoice_from', $self->agentnum);
4755 $from = $options{from} if exists($options{from});
4757 my $to = join(',', $self->invoicing_list_emailonly);
4758 $to = $options{to} if exists($options{to});
4760 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4761 if $conf->exists('company_name', $self->agentnum);
4762 $subject = $options{subject} if exists($options{subject});
4764 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4765 SOURCE => [ map "$_\n",
4766 $conf->config($template)]
4768 or die "can't create new Text::Template object: Text::Template::ERROR";
4769 $notify_template->compile()
4770 or die "can't compile template: Text::Template::ERROR";
4772 $FS::notify_template::_template::company_name =
4773 $conf->config('company_name', $self->agentnum);
4774 $FS::notify_template::_template::company_address =
4775 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4777 my $paydate = $self->paydate || '2037-12-31';
4778 $FS::notify_template::_template::first = $self->first;
4779 $FS::notify_template::_template::last = $self->last;
4780 $FS::notify_template::_template::company = $self->company;
4781 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4782 my $payby = $self->payby;
4783 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4784 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4786 #credit cards expire at the end of the month/year of their exp date
4787 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4788 $FS::notify_template::_template::payby = 'credit card';
4789 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4790 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4792 }elsif ($payby eq 'COMP') {
4793 $FS::notify_template::_template::payby = 'complimentary account';
4795 $FS::notify_template::_template::payby = 'current method';
4797 $FS::notify_template::_template::expdate = $expire_time;
4799 for (keys %{$options{extra_fields}}){
4801 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4804 send_email(from => $from,
4806 subject => $subject,
4807 body => $notify_template->fill_in( PACKAGE =>
4808 'FS::notify_template::_template' ),
4813 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4815 Generates a templated notification to the customer (see L<Text::Template>).
4817 OPTIONS is a hash and may include
4819 I<extra_fields> - a hashref of name/value pairs which will be substituted
4820 into the template. These values may override values mentioned below
4821 and those from the customer record.
4823 The following variables are available in the template instead of or in addition
4824 to the fields of the customer record.
4826 I<$payby> - a description of the method of payment for the customer
4827 # would be nice to use FS::payby::shortname
4828 I<$payinfo> - the masked account information used to collect for this customer
4829 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4830 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4834 # a lot like cust_bill::print_latex
4835 sub generate_letter {
4836 my ($self, $template, %options) = @_;
4838 return unless $conf->exists($template);
4840 my $letter_template = new Text::Template
4842 SOURCE => [ map "$_\n", $conf->config($template)],
4843 DELIMITERS => [ '[@--', '--@]' ],
4845 or die "can't create new Text::Template object: Text::Template::ERROR";
4847 $letter_template->compile()
4848 or die "can't compile template: Text::Template::ERROR";
4850 my %letter_data = map { $_ => $self->$_ } $self->fields;
4851 $letter_data{payinfo} = $self->mask_payinfo;
4853 #my $paydate = $self->paydate || '2037-12-31';
4854 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4856 my $payby = $self->payby;
4857 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4858 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4860 #credit cards expire at the end of the month/year of their exp date
4861 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4862 $letter_data{payby} = 'credit card';
4863 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4864 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4866 }elsif ($payby eq 'COMP') {
4867 $letter_data{payby} = 'complimentary account';
4869 $letter_data{payby} = 'current method';
4871 $letter_data{expdate} = $expire_time;
4873 for (keys %{$options{extra_fields}}){
4874 $letter_data{$_} = $options{extra_fields}->{$_};
4877 unless(exists($letter_data{returnaddress})){
4878 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4879 $self->agent_template)
4881 if ( length($retadd) ) {
4882 $letter_data{returnaddress} = $retadd;
4883 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4884 $letter_data{returnaddress} =
4885 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4889 ( $conf->config('company_name', $self->agentnum),
4890 $conf->config('company_address', $self->agentnum),
4894 $letter_data{returnaddress} = '~';
4898 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4900 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4902 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4904 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4908 ) or die "can't open temp file: $!\n";
4909 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4910 or die "can't write temp file: $!\n";
4912 $letter_data{'logo_file'} = $lh->filename;
4914 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4918 ) or die "can't open temp file: $!\n";
4920 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4922 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4923 return ($1, $letter_data{'logo_file'});
4927 =item print_ps TEMPLATE
4929 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4935 my($file, $lfile) = $self->generate_letter(@_);
4936 my $ps = FS::Misc::generate_ps($file);
4937 unlink($file.'.tex');
4943 =item print TEMPLATE
4945 Prints the filled in template.
4947 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4951 sub queueable_print {
4954 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4955 or die "invalid customer number: " . $opt{custnum};
4957 my $error = $self->print( { 'template' => $opt{template} } );
4958 die $error if $error;
4962 my ($self, $template) = (shift, shift);
4964 [ $self->print_ps($template) ],
4965 'agentnum' => $self->agentnum,
4969 #these three subs should just go away once agent stuff is all config overrides
4971 sub agent_template {
4973 $self->_agent_plandata('agent_templatename');
4976 sub agent_invoice_from {
4978 $self->_agent_plandata('agent_invoice_from');
4981 sub _agent_plandata {
4982 my( $self, $option ) = @_;
4984 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4985 #agent-specific Conf
4987 use FS::part_event::Condition;
4989 my $agentnum = $self->agentnum;
4991 my $regexp = regexp_sql();
4993 my $part_event_option =
4995 'select' => 'part_event_option.*',
4996 'table' => 'part_event_option',
4998 LEFT JOIN part_event USING ( eventpart )
4999 LEFT JOIN part_event_option AS peo_agentnum
5000 ON ( part_event.eventpart = peo_agentnum.eventpart
5001 AND peo_agentnum.optionname = 'agentnum'
5002 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5004 LEFT JOIN part_event_condition
5005 ON ( part_event.eventpart = part_event_condition.eventpart
5006 AND part_event_condition.conditionname = 'cust_bill_age'
5008 LEFT JOIN part_event_condition_option
5009 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5010 AND part_event_condition_option.optionname = 'age'
5013 #'hashref' => { 'optionname' => $option },
5014 #'hashref' => { 'part_event_option.optionname' => $option },
5016 " WHERE part_event_option.optionname = ". dbh->quote($option).
5017 " AND action = 'cust_bill_send_agent' ".
5018 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5019 " AND peo_agentnum.optionname = 'agentnum' ".
5020 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5022 CASE WHEN part_event_condition_option.optionname IS NULL
5024 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5026 , part_event.weight".
5030 unless ( $part_event_option ) {
5031 return $self->agent->invoice_template || ''
5032 if $option eq 'agent_templatename';
5036 $part_event_option->optionvalue;
5040 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5042 Subroutine (not a method), designed to be called from the queue.
5044 Takes a list of options and values.
5046 Pulls up the customer record via the custnum option and calls bill_and_collect.
5051 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5053 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5054 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5056 #without this errors don't get rolled back
5057 $args{'fatal'} = 1; # runs from job queue, will be caught
5059 $cust_main->bill_and_collect( %args );
5062 sub process_bill_and_collect {
5064 my $param = thaw(decode_base64(shift));
5065 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5066 or die "custnum '$param->{custnum}' not found!\n";
5067 $param->{'job'} = $job;
5068 $param->{'fatal'} = 1; # runs from job queue, will be caught
5069 $param->{'retry'} = 1;
5071 $cust_main->bill_and_collect( %$param );
5074 #starting to take quite a while for big dbs
5075 # (JRNL: journaled so it only happens once per database)
5076 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5077 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5078 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5079 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5080 # JRNL leading/trailing spaces in first, last, company
5081 # JRNL migrate to cust_payby
5082 # - otaker upgrade? journal and call it good? (double check to make sure
5083 # we're not still setting otaker here)
5085 #only going to get worse with new location stuff...
5087 sub _upgrade_data { #class method
5088 my ($class, %opts) = @_;
5091 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5094 #this seems to be the only expensive one.. why does it take so long?
5095 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5097 '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';
5098 FS::upgrade_journal->set_done('cust_main__signupdate');
5101 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5103 # fix yyyy-m-dd formatted paydates
5104 if ( driver_name =~ /^mysql/i ) {
5106 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5107 } else { # the SQL standard
5109 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5111 FS::upgrade_journal->set_done('cust_main__paydate');
5114 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5116 push @statements, #fix the weird BILL with a cc# in payinfo problem
5118 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5120 FS::upgrade_journal->set_done('cust_main__payinfo');
5125 foreach my $sql ( @statements ) {
5126 my $sth = dbh->prepare($sql) or die dbh->errstr;
5127 $sth->execute or die $sth->errstr;
5128 #warn ( (time - $t). " seconds\n" );
5132 local($ignore_expired_card) = 1;
5133 local($ignore_banned_card) = 1;
5134 local($skip_fuzzyfiles) = 1;
5135 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5137 FS::cust_main::Location->_upgrade_data(%opts);
5139 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5141 foreach my $cust_main ( qsearch({
5142 'table' => 'cust_main',
5144 'extra_sql' => 'WHERE '.
5146 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5147 qw( first last company )
5150 my $error = $cust_main->replace;
5151 die $error if $error;
5154 FS::upgrade_journal->set_done('cust_main__trimspaces');
5158 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5160 #we don't want to decrypt them, just stuff them as-is into cust_payby
5161 local(@encrypted_fields) = ();
5163 local($FS::cust_payby::ignore_expired_card) = 1;
5164 local($FS::cust_payby::ignore_banned_card) = 1;
5166 my @payfields = qw( payby payinfo paycvv paymask
5167 paydate paystart_month paystart_year payissue
5168 payname paystate paytype payip
5171 my $search = new FS::Cursor {
5172 'table' => 'cust_main',
5173 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5176 while (my $cust_main = $search->fetch) {
5178 my $cust_payby = new FS::cust_payby {
5179 'custnum' => $cust_main->custnum,
5181 map { $_ => $cust_main->$_(); } @payfields
5184 my $error = $cust_payby->insert;
5185 die $error if $error;
5187 $cust_main->setfield($_, '') foreach @payfields;
5188 $error = $cust_main->replace;
5189 die $error if $error;
5193 FS::upgrade_journal->set_done('cust_main__cust_payby');
5196 $class->_upgrade_otaker(%opts);
5206 The delete method should possibly take an FS::cust_main object reference
5207 instead of a scalar customer number.
5209 Bill and collect options should probably be passed as references instead of a
5212 There should probably be a configuration file with a list of allowed credit
5215 No multiple currency support (probably a larger project than just this module).
5217 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5219 Birthdates rely on negative epoch values.
5221 The payby for card/check batches is broken. With mixed batching, bad
5224 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5228 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5229 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5230 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.