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.
357 my $cust_pkgs = @_ ? shift : {};
358 my $invoicing_list = @_ ? shift : '';
360 warn "$me insert called with options ".
361 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
364 local $SIG{HUP} = 'IGNORE';
365 local $SIG{INT} = 'IGNORE';
366 local $SIG{QUIT} = 'IGNORE';
367 local $SIG{TERM} = 'IGNORE';
368 local $SIG{TSTP} = 'IGNORE';
369 local $SIG{PIPE} = 'IGNORE';
371 my $oldAutoCommit = $FS::UID::AutoCommit;
372 local $FS::UID::AutoCommit = 0;
375 my $prepay_identifier = '';
376 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
378 if ( $self->payby eq 'PREPAY' ) {
380 $self->payby('BILL');
381 $prepay_identifier = $self->payinfo;
384 warn " looking up prepaid card $prepay_identifier\n"
387 my $error = $self->get_prepay( $prepay_identifier,
388 'amount_ref' => \$amount,
389 'seconds_ref' => \$seconds,
390 'upbytes_ref' => \$upbytes,
391 'downbytes_ref' => \$downbytes,
392 'totalbytes_ref' => \$totalbytes,
395 $dbh->rollback if $oldAutoCommit;
396 #return "error applying prepaid card (transaction rolled back): $error";
400 $payby = 'PREP' if $amount;
402 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|PPAL)$/ ) {
405 $self->payby('BILL');
406 $amount = $self->paid;
411 foreach my $l (qw(bill_location ship_location)) {
412 my $loc = delete $self->hashref->{$l};
413 # XXX if we're moving a prospect's locations, do that here
415 #return "$l not set";
416 #location-less customer records are now permitted
420 if ( !$loc->locationnum ) {
421 # warn the location that we're going to insert it with no custnum
422 $loc->set(custnum_pending => 1);
423 warn " inserting $l\n"
425 my $error = $loc->insert;
427 $dbh->rollback if $oldAutoCommit;
428 my $label = $l eq 'ship_location' ? 'service' : 'billing';
429 return "$error (in $label location)";
432 elsif ( ($loc->custnum || 0) > 0 or $loc->prospectnum ) {
433 # then it somehow belongs to another customer--shouldn't happen
434 $dbh->rollback if $oldAutoCommit;
435 return "$l belongs to customer ".$loc->custnum;
437 # else it already belongs to this customer
438 # (happens when ship_location is identical to bill_location)
440 $self->set($l.'num', $loc->locationnum);
442 if ( $self->get($l.'num') eq '' ) {
443 $dbh->rollback if $oldAutoCommit;
448 warn " inserting $self\n"
451 $self->signupdate(time) unless $self->signupdate;
453 $self->auto_agent_custid()
454 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
456 my $error = $self->SUPER::insert;
458 $dbh->rollback if $oldAutoCommit;
459 #return "inserting cust_main record (transaction rolled back): $error";
463 # now set cust_location.custnum
464 foreach my $l (qw(bill_location ship_location)) {
465 warn " setting $l.custnum\n"
467 my $loc = $self->$l or next;
468 unless ( $loc->custnum ) {
469 $loc->set(custnum => $self->custnum);
470 $error ||= $loc->replace;
474 $dbh->rollback if $oldAutoCommit;
475 return "error setting $l custnum: $error";
479 warn " setting invoicing list\n"
482 if ( $invoicing_list ) {
483 $error = $self->check_invoicing_list( $invoicing_list );
485 $dbh->rollback if $oldAutoCommit;
486 #return "checking invoicing_list (transaction rolled back): $error";
489 $self->invoicing_list( $invoicing_list );
492 warn " setting customer tags\n"
495 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
496 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
497 'custnum' => $self->custnum };
498 my $error = $cust_tag->insert;
500 $dbh->rollback if $oldAutoCommit;
505 my $prospectnum = delete $options{'prospectnum'};
506 if ( $prospectnum ) {
508 warn " moving contacts and locations from prospect $prospectnum\n"
512 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
513 unless ( $prospect_main ) {
514 $dbh->rollback if $oldAutoCommit;
515 return "Unknown prospectnum $prospectnum";
517 $prospect_main->custnum($self->custnum);
518 $prospect_main->disabled('Y');
519 my $error = $prospect_main->replace;
521 $dbh->rollback if $oldAutoCommit;
525 my @contact = $prospect_main->contact;
526 my @cust_location = $prospect_main->cust_location;
527 my @qual = $prospect_main->qual;
529 foreach my $r ( @contact, @cust_location, @qual ) {
531 $r->custnum($self->custnum);
532 my $error = $r->replace;
534 $dbh->rollback if $oldAutoCommit;
541 warn " setting cust_main_exemption\n"
544 my $tax_exemption = delete $options{'tax_exemption'};
545 if ( $tax_exemption ) {
547 $tax_exemption = { map { $_ => '' } @$tax_exemption }
548 if ref($tax_exemption) eq 'ARRAY';
550 foreach my $taxname ( keys %$tax_exemption ) {
551 my $cust_main_exemption = new FS::cust_main_exemption {
552 'custnum' => $self->custnum,
553 'taxname' => $taxname,
554 'exempt_number' => $tax_exemption->{$taxname},
556 my $error = $cust_main_exemption->insert;
558 $dbh->rollback if $oldAutoCommit;
559 return "inserting cust_main_exemption (transaction rolled back): $error";
564 warn " ordering packages\n"
567 $error = $self->order_pkgs( $cust_pkgs,
569 'seconds_ref' => \$seconds,
570 'upbytes_ref' => \$upbytes,
571 'downbytes_ref' => \$downbytes,
572 'totalbytes_ref' => \$totalbytes,
575 $dbh->rollback if $oldAutoCommit;
580 $dbh->rollback if $oldAutoCommit;
581 return "No svc_acct record to apply pre-paid time";
583 if ( $upbytes || $downbytes || $totalbytes ) {
584 $dbh->rollback if $oldAutoCommit;
585 return "No svc_acct record to apply pre-paid data";
589 warn " inserting initial $payby payment of $amount\n"
591 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
593 $dbh->rollback if $oldAutoCommit;
594 return "inserting payment (transaction rolled back): $error";
598 unless ( $import || $skip_fuzzyfiles ) {
599 warn " queueing fuzzyfiles update\n"
601 $error = $self->queue_fuzzyfiles_update;
603 $dbh->rollback if $oldAutoCommit;
604 return "updating fuzzy search cache: $error";
608 # FS::geocode_Mixin::after_insert or something?
609 if ( $conf->config('tax_district_method') and !$import ) {
610 # if anything non-empty, try to look it up
611 my $queue = new FS::queue {
612 'job' => 'FS::geocode_Mixin::process_district_update',
613 'custnum' => $self->custnum,
615 my $error = $queue->insert( ref($self), $self->custnum );
617 $dbh->rollback if $oldAutoCommit;
618 return "queueing tax district update: $error";
623 warn " exporting\n" if $DEBUG > 1;
625 my $export_args = $options{'export_args'} || [];
628 map qsearch( 'part_export', {exportnum=>$_} ),
629 $conf->config('cust_main-exports'); #, $agentnum
631 foreach my $part_export ( @part_export ) {
632 my $error = $part_export->export_insert($self, @$export_args);
634 $dbh->rollback if $oldAutoCommit;
635 return "exporting to ". $part_export->exporttype.
636 " (transaction rolled back): $error";
640 #foreach my $depend_jobnum ( @$depend_jobnums ) {
641 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
643 # foreach my $jobnum ( @jobnums ) {
644 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
645 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
647 # my $error = $queue->depend_insert($depend_jobnum);
649 # $dbh->rollback if $oldAutoCommit;
650 # return "error queuing job dependancy: $error";
657 #if ( exists $options{'jobnums'} ) {
658 # push @{ $options{'jobnums'} }, @jobnums;
661 warn " insert complete; committing transaction\n"
664 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
669 use File::CounterFile;
670 sub auto_agent_custid {
673 my $format = $conf->config('cust_main-auto_agent_custid');
675 if ( $format eq '1YMMXXXXXXXX' ) {
677 my $counter = new File::CounterFile 'cust_main.agent_custid';
680 my $ym = 100000000000 + time2str('%y%m00000000', time);
681 if ( $ym > $counter->value ) {
682 $counter->{'value'} = $agent_custid = $ym;
683 $counter->{'updated'} = 1;
685 $agent_custid = $counter->inc;
691 die "Unknown cust_main-auto_agent_custid format: $format";
694 $self->agent_custid($agent_custid);
698 =item PACKAGE METHODS
700 Documentation on customer package methods has been moved to
701 L<FS::cust_main::Packages>.
703 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
705 Recharges this (existing) customer with the specified prepaid card (see
706 L<FS::prepay_credit>), specified either by I<identifier> or as an
707 FS::prepay_credit object. If there is an error, returns the error, otherwise
710 Optionally, five scalar references can be passed as well. They will have their
711 values filled in with the amount, number of seconds, and number of upload,
712 download, and total bytes applied by this prepaid card.
716 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
717 #the only place that uses these args
718 sub recharge_prepay {
719 my( $self, $prepay_credit, $amountref, $secondsref,
720 $upbytesref, $downbytesref, $totalbytesref ) = @_;
722 local $SIG{HUP} = 'IGNORE';
723 local $SIG{INT} = 'IGNORE';
724 local $SIG{QUIT} = 'IGNORE';
725 local $SIG{TERM} = 'IGNORE';
726 local $SIG{TSTP} = 'IGNORE';
727 local $SIG{PIPE} = 'IGNORE';
729 my $oldAutoCommit = $FS::UID::AutoCommit;
730 local $FS::UID::AutoCommit = 0;
733 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
735 my $error = $self->get_prepay( $prepay_credit,
736 'amount_ref' => \$amount,
737 'seconds_ref' => \$seconds,
738 'upbytes_ref' => \$upbytes,
739 'downbytes_ref' => \$downbytes,
740 'totalbytes_ref' => \$totalbytes,
742 || $self->increment_seconds($seconds)
743 || $self->increment_upbytes($upbytes)
744 || $self->increment_downbytes($downbytes)
745 || $self->increment_totalbytes($totalbytes)
746 || $self->insert_cust_pay_prepay( $amount,
748 ? $prepay_credit->identifier
753 $dbh->rollback if $oldAutoCommit;
757 if ( defined($amountref) ) { $$amountref = $amount; }
758 if ( defined($secondsref) ) { $$secondsref = $seconds; }
759 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
760 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
761 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
763 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
768 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
770 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
771 specified either by I<identifier> or as an FS::prepay_credit object.
773 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
774 incremented by the values of the prepaid card.
776 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
777 check or set this customer's I<agentnum>.
779 If there is an error, returns the error, otherwise returns false.
785 my( $self, $prepay_credit, %opt ) = @_;
787 local $SIG{HUP} = 'IGNORE';
788 local $SIG{INT} = 'IGNORE';
789 local $SIG{QUIT} = 'IGNORE';
790 local $SIG{TERM} = 'IGNORE';
791 local $SIG{TSTP} = 'IGNORE';
792 local $SIG{PIPE} = 'IGNORE';
794 my $oldAutoCommit = $FS::UID::AutoCommit;
795 local $FS::UID::AutoCommit = 0;
798 unless ( ref($prepay_credit) ) {
800 my $identifier = $prepay_credit;
802 $prepay_credit = qsearchs(
804 { 'identifier' => $identifier },
809 unless ( $prepay_credit ) {
810 $dbh->rollback if $oldAutoCommit;
811 return "Invalid prepaid card: ". $identifier;
816 if ( $prepay_credit->agentnum ) {
817 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
818 $dbh->rollback if $oldAutoCommit;
819 return "prepaid card not valid for agent ". $self->agentnum;
821 $self->agentnum($prepay_credit->agentnum);
824 my $error = $prepay_credit->delete;
826 $dbh->rollback if $oldAutoCommit;
827 return "removing prepay_credit (transaction rolled back): $error";
830 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
831 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
833 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
838 =item increment_upbytes SECONDS
840 Updates this customer's single or primary account (see L<FS::svc_acct>) by
841 the specified number of upbytes. If there is an error, returns the error,
842 otherwise returns false.
846 sub increment_upbytes {
847 _increment_column( shift, 'upbytes', @_);
850 =item increment_downbytes SECONDS
852 Updates this customer's single or primary account (see L<FS::svc_acct>) by
853 the specified number of downbytes. If there is an error, returns the error,
854 otherwise returns false.
858 sub increment_downbytes {
859 _increment_column( shift, 'downbytes', @_);
862 =item increment_totalbytes SECONDS
864 Updates this customer's single or primary account (see L<FS::svc_acct>) by
865 the specified number of totalbytes. If there is an error, returns the error,
866 otherwise returns false.
870 sub increment_totalbytes {
871 _increment_column( shift, 'totalbytes', @_);
874 =item increment_seconds SECONDS
876 Updates this customer's single or primary account (see L<FS::svc_acct>) by
877 the specified number of seconds. If there is an error, returns the error,
878 otherwise returns false.
882 sub increment_seconds {
883 _increment_column( shift, 'seconds', @_);
886 =item _increment_column AMOUNT
888 Updates this customer's single or primary account (see L<FS::svc_acct>) by
889 the specified number of seconds or bytes. If there is an error, returns
890 the error, otherwise returns false.
894 sub _increment_column {
895 my( $self, $column, $amount ) = @_;
896 warn "$me increment_column called: $column, $amount\n"
899 return '' unless $amount;
901 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
902 $self->ncancelled_pkgs;
905 return 'No packages with primary or single services found'.
906 ' to apply pre-paid time';
907 } elsif ( scalar(@cust_pkg) > 1 ) {
908 #maybe have a way to specify the package/account?
909 return 'Multiple packages found to apply pre-paid time';
912 my $cust_pkg = $cust_pkg[0];
913 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
917 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
920 return 'No account found to apply pre-paid time';
921 } elsif ( scalar(@cust_svc) > 1 ) {
922 return 'Multiple accounts found to apply pre-paid time';
925 my $svc_acct = $cust_svc[0]->svc_x;
926 warn " found service svcnum ". $svc_acct->pkgnum.
927 ' ('. $svc_acct->email. ")\n"
930 $column = "increment_$column";
931 $svc_acct->$column($amount);
935 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
937 Inserts a prepayment in the specified amount for this customer. An optional
938 second argument can specify the prepayment identifier for tracking purposes.
939 If there is an error, returns the error, otherwise returns false.
943 sub insert_cust_pay_prepay {
944 shift->insert_cust_pay('PREP', @_);
947 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
949 Inserts a cash payment in the specified amount for this customer. An optional
950 second argument can specify the payment identifier for tracking purposes.
951 If there is an error, returns the error, otherwise returns false.
955 sub insert_cust_pay_cash {
956 shift->insert_cust_pay('CASH', @_);
959 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
961 Inserts a Western Union payment in the specified amount for this customer. An
962 optional second argument can specify the prepayment identifier for tracking
963 purposes. If there is an error, returns the error, otherwise returns false.
967 sub insert_cust_pay_west {
968 shift->insert_cust_pay('WEST', @_);
971 sub insert_cust_pay {
972 my( $self, $payby, $amount ) = splice(@_, 0, 3);
973 my $payinfo = scalar(@_) ? shift : '';
975 my $cust_pay = new FS::cust_pay {
976 'custnum' => $self->custnum,
977 'paid' => sprintf('%.2f', $amount),
978 #'_date' => #date the prepaid card was purchased???
980 'payinfo' => $payinfo,
986 =item delete [ OPTION => VALUE ... ]
988 This deletes the customer. If there is an error, returns the error, otherwise
991 This will completely remove all traces of the customer record. This is not
992 what you want when a customer cancels service; for that, cancel all of the
993 customer's packages (see L</cancel>).
995 If the customer has any uncancelled packages, you need to pass a new (valid)
996 customer number for those packages to be transferred to, as the "new_customer"
997 option. Cancelled packages will be deleted. Did I mention that this is NOT
998 what you want when a customer cancels service and that you really should be
999 looking at L<FS::cust_pkg/cancel>?
1001 You can't delete a customer with invoices (see L<FS::cust_bill>),
1002 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1003 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1004 set the "delete_financials" option to a true value.
1009 my( $self, %opt ) = @_;
1011 local $SIG{HUP} = 'IGNORE';
1012 local $SIG{INT} = 'IGNORE';
1013 local $SIG{QUIT} = 'IGNORE';
1014 local $SIG{TERM} = 'IGNORE';
1015 local $SIG{TSTP} = 'IGNORE';
1016 local $SIG{PIPE} = 'IGNORE';
1018 my $oldAutoCommit = $FS::UID::AutoCommit;
1019 local $FS::UID::AutoCommit = 0;
1022 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1023 $dbh->rollback if $oldAutoCommit;
1024 return "Can't delete a master agent customer";
1027 #use FS::access_user
1028 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1029 $dbh->rollback if $oldAutoCommit;
1030 return "Can't delete a master employee customer";
1033 tie my %financial_tables, 'Tie::IxHash',
1034 'cust_bill' => 'invoices',
1035 'cust_statement' => 'statements',
1036 'cust_credit' => 'credits',
1037 'cust_pay' => 'payments',
1038 'cust_refund' => 'refunds',
1041 foreach my $table ( keys %financial_tables ) {
1043 my @records = $self->$table();
1045 if ( @records && ! $opt{'delete_financials'} ) {
1046 $dbh->rollback if $oldAutoCommit;
1047 return "Can't delete a customer with ". $financial_tables{$table};
1050 foreach my $record ( @records ) {
1051 my $error = $record->delete;
1053 $dbh->rollback if $oldAutoCommit;
1054 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1060 my @cust_pkg = $self->ncancelled_pkgs;
1062 my $new_custnum = $opt{'new_custnum'};
1063 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1064 $dbh->rollback if $oldAutoCommit;
1065 return "Invalid new customer number: $new_custnum";
1067 foreach my $cust_pkg ( @cust_pkg ) {
1068 my %hash = $cust_pkg->hash;
1069 $hash{'custnum'} = $new_custnum;
1070 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1071 my $error = $new_cust_pkg->replace($cust_pkg,
1072 options => { $cust_pkg->options },
1075 $dbh->rollback if $oldAutoCommit;
1080 my @cancelled_cust_pkg = $self->all_pkgs;
1081 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1082 my $error = $cust_pkg->delete;
1084 $dbh->rollback if $oldAutoCommit;
1089 #cust_tax_adjustment in financials?
1090 #cust_pay_pending? ouch
1092 foreach my $table (qw(
1093 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1094 cust_location cust_main_note cust_tax_adjustment
1095 cust_pay_void cust_pay_batch queue cust_tax_exempt
1097 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1098 my $error = $record->delete;
1100 $dbh->rollback if $oldAutoCommit;
1106 my $sth = $dbh->prepare(
1107 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1109 my $errstr = $dbh->errstr;
1110 $dbh->rollback if $oldAutoCommit;
1113 $sth->execute($self->custnum) or do {
1114 my $errstr = $sth->errstr;
1115 $dbh->rollback if $oldAutoCommit;
1121 my $ticket_dbh = '';
1122 if ($conf->config('ticket_system') eq 'RT_Internal') {
1124 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1125 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1126 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1127 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1130 if ( $ticket_dbh ) {
1132 my $ticket_sth = $ticket_dbh->prepare(
1133 'DELETE FROM Links WHERE Target = ?'
1135 my $errstr = $ticket_dbh->errstr;
1136 $dbh->rollback if $oldAutoCommit;
1139 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1141 my $errstr = $ticket_sth->errstr;
1142 $dbh->rollback if $oldAutoCommit;
1146 #check and see if the customer is the only link on the ticket, and
1147 #if so, set the ticket to deleted status in RT?
1148 #maybe someday, for now this will at least fix tickets not displaying
1152 #delete the customer record
1154 my $error = $self->SUPER::delete;
1156 $dbh->rollback if $oldAutoCommit;
1160 # cust_main exports!
1162 #my $export_args = $options{'export_args'} || [];
1165 map qsearch( 'part_export', {exportnum=>$_} ),
1166 $conf->config('cust_main-exports'); #, $agentnum
1168 foreach my $part_export ( @part_export ) {
1169 my $error = $part_export->export_delete( $self ); #, @$export_args);
1171 $dbh->rollback if $oldAutoCommit;
1172 return "exporting to ". $part_export->exporttype.
1173 " (transaction rolled back): $error";
1177 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1182 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1184 This merges this customer into the provided new custnum, and then deletes the
1185 customer. If there is an error, returns the error, otherwise returns false.
1187 The source customer's name, company name, phone numbers, agent,
1188 referring customer, customer class, advertising source, order taker, and
1189 billing information (except balance) are discarded.
1191 All packages are moved to the target customer. Packages with package locations
1192 are preserved. Packages without package locations are moved to a new package
1193 location with the source customer's service/shipping address.
1195 All invoices, statements, payments, credits and refunds are moved to the target
1196 customer. The source customer's balance is added to the target customer.
1198 All notes, attachments, tickets and customer tags are moved to the target
1201 Change history is not currently moved.
1206 my( $self, $new_custnum, %opt ) = @_;
1208 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1210 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1211 or return "Invalid new customer number: $new_custnum";
1213 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1214 if $self->agentnum != $new_cust_main->agentnum
1215 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1217 local $SIG{HUP} = 'IGNORE';
1218 local $SIG{INT} = 'IGNORE';
1219 local $SIG{QUIT} = 'IGNORE';
1220 local $SIG{TERM} = 'IGNORE';
1221 local $SIG{TSTP} = 'IGNORE';
1222 local $SIG{PIPE} = 'IGNORE';
1224 my $oldAutoCommit = $FS::UID::AutoCommit;
1225 local $FS::UID::AutoCommit = 0;
1228 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1229 $dbh->rollback if $oldAutoCommit;
1230 return "Can't merge a master agent customer";
1233 #use FS::access_user
1234 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1235 $dbh->rollback if $oldAutoCommit;
1236 return "Can't merge a master employee customer";
1239 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1240 'status' => { op=>'!=', value=>'done' },
1244 $dbh->rollback if $oldAutoCommit;
1245 return "Can't merge a customer with pending payments";
1248 tie my %financial_tables, 'Tie::IxHash',
1249 'cust_bill' => 'invoices',
1250 'cust_bill_void' => 'voided invoices',
1251 'cust_statement' => 'statements',
1252 'cust_credit' => 'credits',
1253 'cust_credit_void' => 'voided credits',
1254 'cust_pay' => 'payments',
1255 'cust_pay_void' => 'voided payments',
1256 'cust_refund' => 'refunds',
1259 foreach my $table ( keys %financial_tables ) {
1261 my @records = $self->$table();
1263 foreach my $record ( @records ) {
1264 $record->custnum($new_custnum);
1265 my $error = $record->replace;
1267 $dbh->rollback if $oldAutoCommit;
1268 return "Error merging ". $financial_tables{$table}. ": $error\n";
1274 my $name = $self->ship_name; #?
1276 my $locationnum = '';
1277 foreach my $cust_pkg ( $self->all_pkgs ) {
1278 $cust_pkg->custnum($new_custnum);
1280 unless ( $cust_pkg->locationnum ) {
1281 unless ( $locationnum ) {
1282 my $cust_location = new FS::cust_location {
1283 $self->location_hash,
1284 'custnum' => $new_custnum,
1286 my $error = $cust_location->insert;
1288 $dbh->rollback if $oldAutoCommit;
1291 $locationnum = $cust_location->locationnum;
1293 $cust_pkg->locationnum($locationnum);
1296 my $error = $cust_pkg->replace;
1298 $dbh->rollback if $oldAutoCommit;
1302 # add customer (ship) name to svc_phone.phone_name if blank
1303 my @cust_svc = $cust_pkg->cust_svc;
1304 foreach my $cust_svc (@cust_svc) {
1305 my($label, $value, $svcdb) = $cust_svc->label;
1306 next unless $svcdb eq 'svc_phone';
1307 my $svc_phone = $cust_svc->svc_x;
1308 next if $svc_phone->phone_name;
1309 $svc_phone->phone_name($name);
1310 my $error = $svc_phone->replace;
1312 $dbh->rollback if $oldAutoCommit;
1320 # cust_tax_exempt (texas tax exemptions)
1321 # cust_recon (some sort of not-well understood thing for OnPac)
1323 #these are moved over
1324 foreach my $table (qw(
1325 cust_tag cust_location contact cust_attachment cust_main_note
1326 cust_tax_adjustment cust_pay_batch queue
1328 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1329 $record->custnum($new_custnum);
1330 my $error = $record->replace;
1332 $dbh->rollback if $oldAutoCommit;
1338 #these aren't preserved
1339 foreach my $table (qw(
1340 cust_main_exemption cust_main_invoice
1342 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1343 my $error = $record->delete;
1345 $dbh->rollback if $oldAutoCommit;
1352 my $sth = $dbh->prepare(
1353 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1355 my $errstr = $dbh->errstr;
1356 $dbh->rollback if $oldAutoCommit;
1359 $sth->execute($new_custnum, $self->custnum) or do {
1360 my $errstr = $sth->errstr;
1361 $dbh->rollback if $oldAutoCommit;
1367 my $ticket_dbh = '';
1368 if ($conf->config('ticket_system') eq 'RT_Internal') {
1370 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1371 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1372 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1373 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1376 if ( $ticket_dbh ) {
1378 my $ticket_sth = $ticket_dbh->prepare(
1379 'UPDATE Links SET Target = ? WHERE Target = ?'
1381 my $errstr = $ticket_dbh->errstr;
1382 $dbh->rollback if $oldAutoCommit;
1385 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1386 'freeside://freeside/cust_main/'.$self->custnum)
1388 my $errstr = $ticket_sth->errstr;
1389 $dbh->rollback if $oldAutoCommit;
1395 #delete the customer record
1397 my $error = $self->delete;
1399 $dbh->rollback if $oldAutoCommit;
1403 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1408 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1410 Replaces the OLD_RECORD with this one in the database. If there is an error,
1411 returns the error, otherwise returns false.
1413 To change the customer's address, set the pseudo-fields C<bill_location> and
1414 C<ship_location>. The address will still only change if at least one of the
1415 address fields differs from the existing values.
1417 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1418 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1419 expected and rollback the entire transaction; it is not necessary to call
1420 check_invoicing_list first. Here's an example:
1422 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1424 Currently available options are: I<tax_exemption>.
1426 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1427 of tax names and exemption numbers. FS::cust_main_exemption records will be
1428 deleted and inserted as appropriate.
1435 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1437 : $self->replace_old;
1441 warn "$me replace called\n"
1444 my $curuser = $FS::CurrentUser::CurrentUser;
1445 if ( $self->payby eq 'COMP'
1446 && $self->payby ne $old->payby
1447 && ! $curuser->access_right('Complimentary customer')
1450 return "You are not permitted to create complimentary accounts.";
1453 local($ignore_expired_card) = 1
1454 if $old->payby =~ /^(CARD|DCRD)$/
1455 && $self->payby =~ /^(CARD|DCRD)$/
1456 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1458 local($ignore_banned_card) = 1
1459 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1460 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1461 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1463 return "Invoicing locale is required"
1466 && $conf->exists('cust_main-require_locale');
1468 local $SIG{HUP} = 'IGNORE';
1469 local $SIG{INT} = 'IGNORE';
1470 local $SIG{QUIT} = 'IGNORE';
1471 local $SIG{TERM} = 'IGNORE';
1472 local $SIG{TSTP} = 'IGNORE';
1473 local $SIG{PIPE} = 'IGNORE';
1475 my $oldAutoCommit = $FS::UID::AutoCommit;
1476 local $FS::UID::AutoCommit = 0;
1479 for my $l (qw(bill_location ship_location)) {
1480 my $old_loc = $old->$l;
1481 my $new_loc = $self->$l;
1483 # find the existing location if there is one
1484 $new_loc->set('custnum' => $self->custnum);
1485 my $error = $new_loc->find_or_insert;
1487 $dbh->rollback if $oldAutoCommit;
1490 $self->set($l.'num', $new_loc->locationnum);
1493 # replace the customer record
1494 my $error = $self->SUPER::replace($old);
1497 $dbh->rollback if $oldAutoCommit;
1501 # now move packages to the new service location
1502 $self->set('ship_location', ''); #flush cache
1503 if ( $old->ship_locationnum and # should only be null during upgrade...
1504 $old->ship_locationnum != $self->ship_locationnum ) {
1505 $error = $old->ship_location->move_to($self->ship_location);
1507 $dbh->rollback if $oldAutoCommit;
1511 # don't move packages based on the billing location, but
1512 # disable it if it's no longer in use
1513 if ( $old->bill_locationnum and
1514 $old->bill_locationnum != $self->bill_locationnum ) {
1515 $error = $old->bill_location->disable_if_unused;
1517 $dbh->rollback if $oldAutoCommit;
1522 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1523 my $invoicing_list = shift @param;
1524 $error = $self->check_invoicing_list( $invoicing_list );
1526 $dbh->rollback if $oldAutoCommit;
1529 $self->invoicing_list( $invoicing_list );
1532 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1534 #this could be more efficient than deleting and re-inserting, if it matters
1535 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1536 my $error = $cust_tag->delete;
1538 $dbh->rollback if $oldAutoCommit;
1542 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1543 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1544 'custnum' => $self->custnum };
1545 my $error = $cust_tag->insert;
1547 $dbh->rollback if $oldAutoCommit;
1554 my %options = @param;
1556 my $tax_exemption = delete $options{'tax_exemption'};
1557 if ( $tax_exemption ) {
1559 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1560 if ref($tax_exemption) eq 'ARRAY';
1562 my %cust_main_exemption =
1563 map { $_->taxname => $_ }
1564 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1566 foreach my $taxname ( keys %$tax_exemption ) {
1568 if ( $cust_main_exemption{$taxname} &&
1569 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1572 delete $cust_main_exemption{$taxname};
1576 my $cust_main_exemption = new FS::cust_main_exemption {
1577 'custnum' => $self->custnum,
1578 'taxname' => $taxname,
1579 'exempt_number' => $tax_exemption->{$taxname},
1581 my $error = $cust_main_exemption->insert;
1583 $dbh->rollback if $oldAutoCommit;
1584 return "inserting cust_main_exemption (transaction rolled back): $error";
1588 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1589 my $error = $cust_main_exemption->delete;
1591 $dbh->rollback if $oldAutoCommit;
1592 return "deleting cust_main_exemption (transaction rolled back): $error";
1598 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1599 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1600 && $self->get('payinfo') !~ /^99\d{14}$/
1602 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1607 # card/check/lec info has changed, want to retry realtime_ invoice events
1608 my $error = $self->retry_realtime;
1610 $dbh->rollback if $oldAutoCommit;
1615 unless ( $import || $skip_fuzzyfiles ) {
1616 $error = $self->queue_fuzzyfiles_update;
1618 $dbh->rollback if $oldAutoCommit;
1619 return "updating fuzzy search cache: $error";
1623 # tax district update in cust_location
1625 # cust_main exports!
1627 my $export_args = $options{'export_args'} || [];
1630 map qsearch( 'part_export', {exportnum=>$_} ),
1631 $conf->config('cust_main-exports'); #, $agentnum
1633 foreach my $part_export ( @part_export ) {
1634 my $error = $part_export->export_replace( $self, $old, @$export_args);
1636 $dbh->rollback if $oldAutoCommit;
1637 return "exporting to ". $part_export->exporttype.
1638 " (transaction rolled back): $error";
1642 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1647 =item queue_fuzzyfiles_update
1649 Used by insert & replace to update the fuzzy search cache
1653 use FS::cust_main::Search;
1654 sub queue_fuzzyfiles_update {
1657 local $SIG{HUP} = 'IGNORE';
1658 local $SIG{INT} = 'IGNORE';
1659 local $SIG{QUIT} = 'IGNORE';
1660 local $SIG{TERM} = 'IGNORE';
1661 local $SIG{TSTP} = 'IGNORE';
1662 local $SIG{PIPE} = 'IGNORE';
1664 my $oldAutoCommit = $FS::UID::AutoCommit;
1665 local $FS::UID::AutoCommit = 0;
1668 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1669 my $queue = new FS::queue {
1670 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1672 my @args = "cust_main.$field", $self->get($field);
1673 my $error = $queue->insert( @args );
1675 $dbh->rollback if $oldAutoCommit;
1676 return "queueing job (transaction rolled back): $error";
1681 push @locations, $self->bill_location if $self->bill_locationnum;
1682 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1683 foreach my $location (@locations) {
1684 my $queue = new FS::queue {
1685 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1687 my @args = 'cust_location.address1', $location->address1;
1688 my $error = $queue->insert( @args );
1690 $dbh->rollback if $oldAutoCommit;
1691 return "queueing job (transaction rolled back): $error";
1695 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1702 Checks all fields to make sure this is a valid customer record. If there is
1703 an error, returns the error, otherwise returns false. Called by the insert
1704 and replace methods.
1711 warn "$me check BEFORE: \n". $self->_dump
1715 $self->ut_numbern('custnum')
1716 || $self->ut_number('agentnum')
1717 || $self->ut_textn('agent_custid')
1718 || $self->ut_number('refnum')
1719 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1720 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1721 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1722 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1723 || $self->ut_textn('custbatch')
1724 || $self->ut_name('last')
1725 || $self->ut_name('first')
1726 || $self->ut_snumbern('signupdate')
1727 || $self->ut_snumbern('birthdate')
1728 || $self->ut_snumbern('spouse_birthdate')
1729 || $self->ut_snumbern('anniversary_date')
1730 || $self->ut_textn('company')
1731 || $self->ut_textn('ship_company')
1732 || $self->ut_anything('comments')
1733 || $self->ut_numbern('referral_custnum')
1734 || $self->ut_textn('stateid')
1735 || $self->ut_textn('stateid_state')
1736 || $self->ut_textn('invoice_terms')
1737 || $self->ut_floatn('cdr_termination_percentage')
1738 || $self->ut_floatn('credit_limit')
1739 || $self->ut_numbern('billday')
1740 || $self->ut_numbern('prorate_day')
1741 || $self->ut_flag('edit_subject')
1742 || $self->ut_flag('calling_list_exempt')
1743 || $self->ut_flag('invoice_noemail')
1744 || $self->ut_flag('message_noemail')
1745 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1746 || $self->ut_currencyn('currency')
1749 foreach (qw(company ship_company)) {
1750 my $company = $self->get($_);
1751 $company =~ s/^\s+//;
1752 $company =~ s/\s+$//;
1753 $company =~ s/\s+/ /g;
1754 $self->set($_, $company);
1757 #barf. need message catalogs. i18n. etc.
1758 $error .= "Please select an advertising source."
1759 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1760 return $error if $error;
1762 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1763 or return "Unknown agent";
1765 if ( $self->currency ) {
1766 my $agent_currency = qsearchs( 'agent_currency', {
1767 'agentnum' => $agent->agentnum,
1768 'currency' => $self->currency,
1770 or return "Agent ". $agent->agent.
1771 " not permitted to offer ". $self->currency. " invoicing";
1774 return "Unknown refnum"
1775 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1777 return "Unknown referring custnum: ". $self->referral_custnum
1778 unless ! $self->referral_custnum
1779 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1781 if ( $self->ss eq '' ) {
1786 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1787 or return "Illegal social security number: ". $self->ss;
1788 $self->ss("$1-$2-$3");
1791 # cust_main_county verification now handled by cust_location check
1794 $self->ut_phonen('daytime', $self->country)
1795 || $self->ut_phonen('night', $self->country)
1796 || $self->ut_phonen('fax', $self->country)
1797 || $self->ut_phonen('mobile', $self->country)
1799 return $error if $error;
1801 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1803 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1806 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1808 : FS::Msgcat::_gettext('daytime');
1809 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1811 : FS::Msgcat::_gettext('night');
1813 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1815 : FS::Msgcat::_gettext('mobile');
1817 return "$daytime_label, $night_label or $mobile_label is required"
1821 ### start of stuff moved to cust_payby
1822 # then mostly kept here to support upgrades (can remove in 5.x)
1823 # but modified to allow everything to be empty
1825 if ( $self->payby ) {
1826 FS::payby->can_payby($self->table, $self->payby)
1827 or return "Illegal payby: ". $self->payby;
1832 $error = $self->ut_numbern('paystart_month')
1833 || $self->ut_numbern('paystart_year')
1834 || $self->ut_numbern('payissue')
1835 || $self->ut_textn('paytype')
1837 return $error if $error;
1839 if ( $self->payip eq '' ) {
1842 $error = $self->ut_ip('payip');
1843 return $error if $error;
1846 # If it is encrypted and the private key is not availaible then we can't
1847 # check the credit card.
1848 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1850 # Need some kind of global flag to accept invalid cards, for testing
1852 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1853 $self->payby =~ /^(CARD|DCRD)$/ ) {
1855 my $payinfo = $self->payinfo;
1856 $payinfo =~ s/\D//g;
1857 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1858 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1860 $self->payinfo($payinfo);
1862 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1864 return gettext('unknown_card_type')
1865 if $self->payinfo !~ /^99\d{14}$/ #token
1866 && cardtype($self->payinfo) eq "Unknown";
1868 unless ( $ignore_banned_card ) {
1869 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1871 if ( $ban->bantype eq 'warn' ) {
1872 #or others depending on value of $ban->reason ?
1873 return '_duplicate_card'.
1874 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1875 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1876 ' (ban# '. $ban->bannum. ')'
1877 unless $self->override_ban_warn;
1879 return 'Banned credit card: banned on '.
1880 time2str('%a %h %o at %r', $ban->_date).
1881 ' by '. $ban->otaker.
1882 ' (ban# '. $ban->bannum. ')';
1887 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1888 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1889 $self->paycvv =~ /^(\d{4})$/
1890 or return "CVV2 (CID) for American Express cards is four digits.";
1893 $self->paycvv =~ /^(\d{3})$/
1894 or return "CVV2 (CVC2/CID) is three digits.";
1901 my $cardtype = cardtype($payinfo);
1902 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1904 return "Start date or issue number is required for $cardtype cards"
1905 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1907 return "Start month must be between 1 and 12"
1908 if $self->paystart_month
1909 and $self->paystart_month < 1 || $self->paystart_month > 12;
1911 return "Start year must be 1990 or later"
1912 if $self->paystart_year
1913 and $self->paystart_year < 1990;
1915 return "Issue number must be beween 1 and 99"
1917 and $self->payissue < 1 || $self->payissue > 99;
1920 $self->paystart_month('');
1921 $self->paystart_year('');
1922 $self->payissue('');
1925 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1926 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1928 my $payinfo = $self->payinfo;
1929 $payinfo =~ s/[^\d\@\.]//g;
1930 if ( $conf->config('echeck-country') eq 'CA' ) {
1931 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1932 or return 'invalid echeck account@branch.bank';
1933 $payinfo = "$1\@$2.$3";
1934 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1935 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1936 $payinfo = "$1\@$2";
1938 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1939 $payinfo = "$1\@$2";
1941 $self->payinfo($payinfo);
1944 unless ( $ignore_banned_card ) {
1945 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1947 if ( $ban->bantype eq 'warn' ) {
1948 #or others depending on value of $ban->reason ?
1949 return '_duplicate_ach' unless $self->override_ban_warn;
1951 return 'Banned ACH account: banned on '.
1952 time2str('%a %h %o at %r', $ban->_date).
1953 ' by '. $ban->otaker.
1954 ' (ban# '. $ban->bannum. ')';
1959 } elsif ( $self->payby eq 'LECB' ) {
1961 my $payinfo = $self->payinfo;
1962 $payinfo =~ s/\D//g;
1963 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1965 $self->payinfo($payinfo);
1968 } elsif ( $self->payby eq 'BILL' ) {
1970 $error = $self->ut_textn('payinfo');
1971 return "Illegal P.O. number: ". $self->payinfo if $error;
1974 } elsif ( $self->payby eq 'COMP' ) {
1976 my $curuser = $FS::CurrentUser::CurrentUser;
1977 if ( ! $self->custnum
1978 && ! $curuser->access_right('Complimentary customer')
1981 return "You are not permitted to create complimentary accounts."
1984 $error = $self->ut_textn('payinfo');
1985 return "Illegal comp account issuer: ". $self->payinfo if $error;
1988 } elsif ( $self->payby eq 'PREPAY' ) {
1990 my $payinfo = $self->payinfo;
1991 $payinfo =~ s/\W//g; #anything else would just confuse things
1992 $self->payinfo($payinfo);
1993 $error = $self->ut_alpha('payinfo');
1994 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1995 return "Unknown prepayment identifier"
1996 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2001 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2002 return "Expiration date required"
2003 # shouldn't payinfo_check do this?
2004 unless ! $self->payby
2005 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2009 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2010 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2011 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2012 ( $m, $y ) = ( $2, "19$1" );
2013 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2014 ( $m, $y ) = ( $3, "20$2" );
2016 return "Illegal expiration date: ". $self->paydate;
2018 $m = sprintf('%02d',$m);
2019 $self->paydate("$y-$m-01");
2020 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2021 return gettext('expired_card')
2023 && !$ignore_expired_card
2024 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2027 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2028 ( ! $conf->exists('require_cardname')
2029 || $self->payby !~ /^(CARD|DCRD)$/ )
2031 $self->payname( $self->first. " ". $self->getfield('last') );
2033 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2034 or return gettext('illegal_name'). " payname: ". $self->payname;
2038 ### end of stuff moved to cust_payby
2040 return "Please select an invoicing locale"
2043 && $conf->exists('cust_main-require_locale');
2045 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2046 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2050 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2052 warn "$me check AFTER: \n". $self->_dump
2055 $self->SUPER::check;
2060 Returns a list of fields which have ship_ duplicates.
2065 qw( last first company
2066 address1 address2 city county state zip country
2068 daytime night fax mobile
2072 =item has_ship_address
2074 Returns true if this customer record has a separate shipping address.
2078 sub has_ship_address {
2080 $self->bill_locationnum != $self->ship_locationnum;
2085 Returns a list of key/value pairs, with the following keys: address1,
2086 adddress2, city, county, state, zip, country, district, and geocode. The
2087 shipping address is used if present.
2093 $self->ship_location->location_hash;
2098 Returns all locations (see L<FS::cust_location>) for this customer.
2104 qsearch('cust_location', { 'custnum' => $self->custnum,
2105 'prospectnum' => '' } );
2110 Returns all contacts (see L<FS::contact>) for this customer.
2114 #already used :/ sub contact {
2117 qsearch('contact', { 'custnum' => $self->custnum } );
2122 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2129 'table' => 'cust_payby',
2130 'hashref' => { 'custnum' => $self->custnum },
2131 'order_by' => 'ORDER BY weight ASC',
2137 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2138 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2139 on success or a list of errors.
2145 grep { $_->unsuspend } $self->suspended_pkgs;
2150 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2152 Returns a list: an empty list on success or a list of errors.
2158 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2161 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2163 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2164 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2165 of a list of pkgparts; the hashref has the following keys:
2169 =item pkgparts - listref of pkgparts
2171 =item (other options are passed to the suspend method)
2176 Returns a list: an empty list on success or a list of errors.
2180 sub suspend_if_pkgpart {
2182 my (@pkgparts, %opt);
2183 if (ref($_[0]) eq 'HASH'){
2184 @pkgparts = @{$_[0]{pkgparts}};
2189 grep { $_->suspend(%opt) }
2190 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2191 $self->unsuspended_pkgs;
2194 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2196 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2197 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2198 instead of a list of pkgparts; the hashref has the following keys:
2202 =item pkgparts - listref of pkgparts
2204 =item (other options are passed to the suspend method)
2208 Returns a list: an empty list on success or a list of errors.
2212 sub suspend_unless_pkgpart {
2214 my (@pkgparts, %opt);
2215 if (ref($_[0]) eq 'HASH'){
2216 @pkgparts = @{$_[0]{pkgparts}};
2221 grep { $_->suspend(%opt) }
2222 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2223 $self->unsuspended_pkgs;
2226 =item cancel [ OPTION => VALUE ... ]
2228 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2230 Available options are:
2234 =item quiet - can be set true to supress email cancellation notices.
2236 =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.
2238 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2240 =item nobill - can be set true to skip billing if it might otherwise be done.
2244 Always returns a list: an empty list on success or a list of errors.
2248 # nb that dates are not specified as valid options to this method
2251 my( $self, %opt ) = @_;
2253 warn "$me cancel called on customer ". $self->custnum. " with options ".
2254 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2257 return ( 'access denied' )
2258 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2260 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2262 #should try decryption (we might have the private key)
2263 # and if not maybe queue a job for the server that does?
2264 return ( "Can't (yet) ban encrypted credit cards" )
2265 if $self->is_encrypted($self->payinfo);
2267 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2268 my $error = $ban->insert;
2269 return ( $error ) if $error;
2273 my @pkgs = $self->ncancelled_pkgs;
2275 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2277 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2278 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2282 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2283 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2286 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2289 sub _banned_pay_hashref {
2300 'payby' => $payby2ban{$self->payby},
2301 'payinfo' => $self->payinfo,
2302 #don't ever *search* on reason! #'reason' =>
2306 sub _new_banned_pay_hashref {
2308 my $hr = $self->_banned_pay_hashref;
2309 $hr->{payinfo} = md5_base64($hr->{payinfo});
2315 Returns all notes (see L<FS::cust_main_note>) for this customer.
2320 my($self,$orderby_classnum) = (shift,shift);
2321 my $orderby = "_DATE DESC";
2322 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2323 qsearch( 'cust_main_note',
2324 { 'custnum' => $self->custnum },
2326 "ORDER BY $orderby",
2332 Returns the agent (see L<FS::agent>) for this customer.
2336 Returns the agent name (see L<FS::agent>) for this customer.
2342 $self->agent->agent;
2347 Returns any tags associated with this customer, as FS::cust_tag objects,
2348 or an empty list if there are no tags.
2352 Returns any tags associated with this customer, as FS::part_tag objects,
2353 or an empty list if there are no tags.
2359 map $_->part_tag, $self->cust_tag;
2365 Returns the customer class, as an FS::cust_class object, or the empty string
2366 if there is no customer class.
2370 Returns the customer category name, or the empty string if there is no customer
2377 my $cust_class = $self->cust_class;
2379 ? $cust_class->categoryname
2385 Returns the customer class name, or the empty string if there is no customer
2392 my $cust_class = $self->cust_class;
2394 ? $cust_class->classname
2398 =item BILLING METHODS
2400 Documentation on billing methods has been moved to
2401 L<FS::cust_main::Billing>.
2403 =item REALTIME BILLING METHODS
2405 Documentation on realtime billing methods has been moved to
2406 L<FS::cust_main::Billing_Realtime>.
2410 Removes the I<paycvv> field from the database directly.
2412 If there is an error, returns the error, otherwise returns false.
2418 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2419 or return dbh->errstr;
2420 $sth->execute($self->custnum)
2421 or return $sth->errstr;
2426 =item batch_card OPTION => VALUE...
2428 Adds a payment for this invoice to the pending credit card batch (see
2429 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2430 runs the payment using a realtime gateway.
2432 Options may include:
2434 B<amount>: the amount to be paid; defaults to the customer's balance minus
2435 any payments in transit.
2437 B<payby>: the payment method; defaults to cust_main.payby
2439 B<realtime>: runs this as a realtime payment instead of adding it to a
2442 B<invnum>: sets cust_pay_batch.invnum.
2444 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2445 the billing address for the payment; defaults to the customer's billing
2448 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2449 date, and name; defaults to those fields in cust_main.
2454 my ($self, %options) = @_;
2457 if (exists($options{amount})) {
2458 $amount = $options{amount};
2460 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2462 return '' unless $amount > 0;
2464 my $invnum = delete $options{invnum};
2465 my $payby = $options{payby} || $self->payby; #still dubious
2467 if ($options{'realtime'}) {
2468 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2474 my $oldAutoCommit = $FS::UID::AutoCommit;
2475 local $FS::UID::AutoCommit = 0;
2478 #this needs to handle mysql as well as Pg, like svc_acct.pm
2479 #(make it into a common function if folks need to do batching with mysql)
2480 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2481 or return "Cannot lock pay_batch: " . $dbh->errstr;
2485 'payby' => FS::payby->payby2payment($payby),
2487 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2489 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2491 unless ( $pay_batch ) {
2492 $pay_batch = new FS::pay_batch \%pay_batch;
2493 my $error = $pay_batch->insert;
2495 $dbh->rollback if $oldAutoCommit;
2496 die "error creating new batch: $error\n";
2500 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2501 'batchnum' => $pay_batch->batchnum,
2502 'custnum' => $self->custnum,
2505 foreach (qw( address1 address2 city state zip country latitude longitude
2506 payby payinfo paydate payname ))
2508 $options{$_} = '' unless exists($options{$_});
2511 my $loc = $self->bill_location;
2513 my $cust_pay_batch = new FS::cust_pay_batch ( {
2514 'batchnum' => $pay_batch->batchnum,
2515 'invnum' => $invnum || 0, # is there a better value?
2516 # this field should be
2518 # cust_bill_pay_batch now
2519 'custnum' => $self->custnum,
2520 'last' => $self->getfield('last'),
2521 'first' => $self->getfield('first'),
2522 'address1' => $options{address1} || $loc->address1,
2523 'address2' => $options{address2} || $loc->address2,
2524 'city' => $options{city} || $loc->city,
2525 'state' => $options{state} || $loc->state,
2526 'zip' => $options{zip} || $loc->zip,
2527 'country' => $options{country} || $loc->country,
2528 'payby' => $options{payby} || $self->payby,
2529 'payinfo' => $options{payinfo} || $self->payinfo,
2530 'exp' => $options{paydate} || $self->paydate,
2531 'payname' => $options{payname} || $self->payname,
2532 'amount' => $amount, # consolidating
2535 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2536 if $old_cust_pay_batch;
2539 if ($old_cust_pay_batch) {
2540 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2542 $error = $cust_pay_batch->insert;
2546 $dbh->rollback if $oldAutoCommit;
2550 my $unapplied = $self->total_unapplied_credits
2551 + $self->total_unapplied_payments
2552 + $self->in_transit_payments;
2553 foreach my $cust_bill ($self->open_cust_bill) {
2554 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2555 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2556 'invnum' => $cust_bill->invnum,
2557 'paybatchnum' => $cust_pay_batch->paybatchnum,
2558 'amount' => $cust_bill->owed,
2561 if ($unapplied >= $cust_bill_pay_batch->amount){
2562 $unapplied -= $cust_bill_pay_batch->amount;
2565 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2566 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2568 $error = $cust_bill_pay_batch->insert;
2570 $dbh->rollback if $oldAutoCommit;
2575 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2581 Returns the total owed for this customer on all invoices
2582 (see L<FS::cust_bill/owed>).
2588 $self->total_owed_date(2145859200); #12/31/2037
2591 =item total_owed_date TIME
2593 Returns the total owed for this customer on all invoices with date earlier than
2594 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2595 see L<Time::Local> and L<Date::Parse> for conversion functions.
2599 sub total_owed_date {
2603 my $custnum = $self->custnum;
2605 my $owed_sql = FS::cust_bill->owed_sql;
2608 SELECT SUM($owed_sql) FROM cust_bill
2609 WHERE custnum = $custnum
2613 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2617 =item total_owed_pkgnum PKGNUM
2619 Returns the total owed on all invoices for this customer's specific package
2620 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2624 sub total_owed_pkgnum {
2625 my( $self, $pkgnum ) = @_;
2626 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2629 =item total_owed_date_pkgnum TIME PKGNUM
2631 Returns the total owed for this customer's specific package when using
2632 experimental package balances on all invoices with date earlier than
2633 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2634 see L<Time::Local> and L<Date::Parse> for conversion functions.
2638 sub total_owed_date_pkgnum {
2639 my( $self, $time, $pkgnum ) = @_;
2642 foreach my $cust_bill (
2643 grep { $_->_date <= $time }
2644 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2646 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2648 sprintf( "%.2f", $total_bill );
2654 Returns the total amount of all payments.
2661 $total += $_->paid foreach $self->cust_pay;
2662 sprintf( "%.2f", $total );
2665 =item total_unapplied_credits
2667 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2668 customer. See L<FS::cust_credit/credited>.
2670 =item total_credited
2672 Old name for total_unapplied_credits. Don't use.
2676 sub total_credited {
2677 #carp "total_credited deprecated, use total_unapplied_credits";
2678 shift->total_unapplied_credits(@_);
2681 sub total_unapplied_credits {
2684 my $custnum = $self->custnum;
2686 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2689 SELECT SUM($unapplied_sql) FROM cust_credit
2690 WHERE custnum = $custnum
2693 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2697 =item total_unapplied_credits_pkgnum PKGNUM
2699 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2700 customer. See L<FS::cust_credit/credited>.
2704 sub total_unapplied_credits_pkgnum {
2705 my( $self, $pkgnum ) = @_;
2706 my $total_credit = 0;
2707 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2708 sprintf( "%.2f", $total_credit );
2712 =item total_unapplied_payments
2714 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2715 See L<FS::cust_pay/unapplied>.
2719 sub total_unapplied_payments {
2722 my $custnum = $self->custnum;
2724 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2727 SELECT SUM($unapplied_sql) FROM cust_pay
2728 WHERE custnum = $custnum
2731 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2735 =item total_unapplied_payments_pkgnum PKGNUM
2737 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2738 specific package when using experimental package balances. See
2739 L<FS::cust_pay/unapplied>.
2743 sub total_unapplied_payments_pkgnum {
2744 my( $self, $pkgnum ) = @_;
2745 my $total_unapplied = 0;
2746 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2747 sprintf( "%.2f", $total_unapplied );
2751 =item total_unapplied_refunds
2753 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2754 customer. See L<FS::cust_refund/unapplied>.
2758 sub total_unapplied_refunds {
2760 my $custnum = $self->custnum;
2762 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2765 SELECT SUM($unapplied_sql) FROM cust_refund
2766 WHERE custnum = $custnum
2769 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2775 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2776 total_unapplied_credits minus total_unapplied_payments).
2782 $self->balance_date_range;
2785 =item balance_date TIME
2787 Returns the balance for this customer, only considering invoices with date
2788 earlier than TIME (total_owed_date minus total_credited minus
2789 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2790 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2797 $self->balance_date_range(shift);
2800 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2802 Returns the balance for this customer, optionally considering invoices with
2803 date earlier than START_TIME, and not later than END_TIME
2804 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2806 Times are specified as SQL fragments or numeric
2807 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2808 L<Date::Parse> for conversion functions. The empty string can be passed
2809 to disable that time constraint completely.
2811 Available options are:
2815 =item unapplied_date
2817 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)
2823 sub balance_date_range {
2825 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2826 ') FROM cust_main WHERE custnum='. $self->custnum;
2827 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2830 =item balance_pkgnum PKGNUM
2832 Returns the balance for this customer's specific package when using
2833 experimental package balances (total_owed plus total_unrefunded, minus
2834 total_unapplied_credits minus total_unapplied_payments)
2838 sub balance_pkgnum {
2839 my( $self, $pkgnum ) = @_;
2842 $self->total_owed_pkgnum($pkgnum)
2843 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2844 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2845 - $self->total_unapplied_credits_pkgnum($pkgnum)
2846 - $self->total_unapplied_payments_pkgnum($pkgnum)
2850 =item in_transit_payments
2852 Returns the total of requests for payments for this customer pending in
2853 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2857 sub in_transit_payments {
2859 my $in_transit_payments = 0;
2860 foreach my $pay_batch ( qsearch('pay_batch', {
2863 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2864 'batchnum' => $pay_batch->batchnum,
2865 'custnum' => $self->custnum,
2867 $in_transit_payments += $cust_pay_batch->amount;
2870 sprintf( "%.2f", $in_transit_payments );
2875 Returns a hash of useful information for making a payment.
2885 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2886 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2887 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2891 For credit card transactions:
2903 For electronic check transactions:
2918 $return{balance} = $self->balance;
2920 $return{payname} = $self->payname
2921 || ( $self->first. ' '. $self->get('last') );
2923 $return{$_} = $self->bill_location->$_
2924 for qw(address1 address2 city state zip);
2926 $return{payby} = $self->payby;
2927 $return{stateid_state} = $self->stateid_state;
2929 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2930 $return{card_type} = cardtype($self->payinfo);
2931 $return{payinfo} = $self->paymask;
2933 @return{'month', 'year'} = $self->paydate_monthyear;
2937 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2938 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2939 $return{payinfo1} = $payinfo1;
2940 $return{payinfo2} = $payinfo2;
2941 $return{paytype} = $self->paytype;
2942 $return{paystate} = $self->paystate;
2946 #doubleclick protection
2948 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2954 =item paydate_monthyear
2956 Returns a two-element list consisting of the month and year of this customer's
2957 paydate (credit card expiration date for CARD customers)
2961 sub paydate_monthyear {
2963 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2965 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2974 Returns the exact time in seconds corresponding to the payment method
2975 expiration date. For CARD/DCRD customers this is the end of the month;
2976 for others (COMP is the only other payby that uses paydate) it's the start.
2977 Returns 0 if the paydate is empty or set to the far future.
2983 my ($month, $year) = $self->paydate_monthyear;
2984 return 0 if !$year or $year >= 2037;
2985 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2987 if ( $month == 13 ) {
2991 return timelocal(0,0,0,1,$month-1,$year) - 1;
2994 return timelocal(0,0,0,1,$month-1,$year);
2998 =item paydate_epoch_sql
3000 Class method. Returns an SQL expression to obtain the payment expiration date
3001 as a number of seconds.
3005 # Special expiration date behavior for non-CARD/DCRD customers has been
3006 # carefully preserved. Do we really use that?
3007 sub paydate_epoch_sql {
3009 my $table = shift || 'cust_main';
3010 my ($case1, $case2);
3011 if ( driver_name eq 'Pg' ) {
3012 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3013 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3015 elsif ( lc(driver_name) eq 'mysql' ) {
3016 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3017 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3020 return "CASE WHEN $table.payby IN('CARD','DCRD')
3026 =item tax_exemption TAXNAME
3031 my( $self, $taxname ) = @_;
3033 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3034 'taxname' => $taxname,
3039 =item cust_main_exemption
3041 =item invoicing_list [ ARRAYREF ]
3043 If an arguement is given, sets these email addresses as invoice recipients
3044 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3045 (except as warnings), so use check_invoicing_list first.
3047 Returns a list of email addresses (with svcnum entries expanded).
3049 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3050 check it without disturbing anything by passing nothing.
3052 This interface may change in the future.
3056 sub invoicing_list {
3057 my( $self, $arrayref ) = @_;
3060 my @cust_main_invoice;
3061 if ( $self->custnum ) {
3062 @cust_main_invoice =
3063 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3065 @cust_main_invoice = ();
3067 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3068 #warn $cust_main_invoice->destnum;
3069 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3070 #warn $cust_main_invoice->destnum;
3071 my $error = $cust_main_invoice->delete;
3072 warn $error if $error;
3075 if ( $self->custnum ) {
3076 @cust_main_invoice =
3077 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3079 @cust_main_invoice = ();
3081 my %seen = map { $_->address => 1 } @cust_main_invoice;
3082 foreach my $address ( @{$arrayref} ) {
3083 next if exists $seen{$address} && $seen{$address};
3084 $seen{$address} = 1;
3085 my $cust_main_invoice = new FS::cust_main_invoice ( {
3086 'custnum' => $self->custnum,
3089 my $error = $cust_main_invoice->insert;
3090 warn $error if $error;
3094 if ( $self->custnum ) {
3096 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3103 =item check_invoicing_list ARRAYREF
3105 Checks these arguements as valid input for the invoicing_list method. If there
3106 is an error, returns the error, otherwise returns false.
3110 sub check_invoicing_list {
3111 my( $self, $arrayref ) = @_;
3113 foreach my $address ( @$arrayref ) {
3115 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3116 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3119 my $cust_main_invoice = new FS::cust_main_invoice ( {
3120 'custnum' => $self->custnum,
3123 my $error = $self->custnum
3124 ? $cust_main_invoice->check
3125 : $cust_main_invoice->checkdest
3127 return $error if $error;
3131 return "Email address required"
3132 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3133 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3138 =item set_default_invoicing_list
3140 Sets the invoicing list to all accounts associated with this customer,
3141 overwriting any previous invoicing list.
3145 sub set_default_invoicing_list {
3147 $self->invoicing_list($self->all_emails);
3152 Returns the email addresses of all accounts provisioned for this customer.
3159 foreach my $cust_pkg ( $self->all_pkgs ) {
3160 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3162 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3163 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3165 $list{$_}=1 foreach map { $_->email } @svc_acct;
3170 =item invoicing_list_addpost
3172 Adds postal invoicing to this customer. If this customer is already configured
3173 to receive postal invoices, does nothing.
3177 sub invoicing_list_addpost {
3179 return if grep { $_ eq 'POST' } $self->invoicing_list;
3180 my @invoicing_list = $self->invoicing_list;
3181 push @invoicing_list, 'POST';
3182 $self->invoicing_list(\@invoicing_list);
3185 =item invoicing_list_emailonly
3187 Returns the list of email invoice recipients (invoicing_list without non-email
3188 destinations such as POST and FAX).
3192 sub invoicing_list_emailonly {
3194 warn "$me invoicing_list_emailonly called"
3196 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3199 =item invoicing_list_emailonly_scalar
3201 Returns the list of email invoice recipients (invoicing_list without non-email
3202 destinations such as POST and FAX) as a comma-separated scalar.
3206 sub invoicing_list_emailonly_scalar {
3208 warn "$me invoicing_list_emailonly_scalar called"
3210 join(', ', $self->invoicing_list_emailonly);
3213 =item referral_custnum_cust_main
3215 Returns the customer who referred this customer (or the empty string, if
3216 this customer was not referred).
3218 Note the difference with referral_cust_main method: This method,
3219 referral_custnum_cust_main returns the single customer (if any) who referred
3220 this customer, while referral_cust_main returns an array of customers referred
3225 sub referral_custnum_cust_main {
3227 return '' unless $self->referral_custnum;
3228 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3231 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3233 Returns an array of customers referred by this customer (referral_custnum set
3234 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3235 customers referred by customers referred by this customer and so on, inclusive.
3236 The default behavior is DEPTH 1 (no recursion).
3238 Note the difference with referral_custnum_cust_main method: This method,
3239 referral_cust_main, returns an array of customers referred BY this customer,
3240 while referral_custnum_cust_main returns the single customer (if any) who
3241 referred this customer.
3245 sub referral_cust_main {
3247 my $depth = @_ ? shift : 1;
3248 my $exclude = @_ ? shift : {};
3251 map { $exclude->{$_->custnum}++; $_; }
3252 grep { ! $exclude->{ $_->custnum } }
3253 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3257 map { $_->referral_cust_main($depth-1, $exclude) }
3264 =item referral_cust_main_ncancelled
3266 Same as referral_cust_main, except only returns customers with uncancelled
3271 sub referral_cust_main_ncancelled {
3273 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3276 =item referral_cust_pkg [ DEPTH ]
3278 Like referral_cust_main, except returns a flat list of all unsuspended (and
3279 uncancelled) packages for each customer. The number of items in this list may
3280 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3284 sub referral_cust_pkg {
3286 my $depth = @_ ? shift : 1;
3288 map { $_->unsuspended_pkgs }
3289 grep { $_->unsuspended_pkgs }
3290 $self->referral_cust_main($depth);
3293 =item referring_cust_main
3295 Returns the single cust_main record for the customer who referred this customer
3296 (referral_custnum), or false.
3300 sub referring_cust_main {
3302 return '' unless $self->referral_custnum;
3303 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3306 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3308 Applies a credit to this customer. If there is an error, returns the error,
3309 otherwise returns false.
3311 REASON can be a text string, an FS::reason object, or a scalar reference to
3312 a reasonnum. If a text string, it will be automatically inserted as a new
3313 reason, and a 'reason_type' option must be passed to indicate the
3314 FS::reason_type for the new reason.
3316 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3317 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3318 I<commission_pkgnum>.
3320 Any other options are passed to FS::cust_credit::insert.
3325 my( $self, $amount, $reason, %options ) = @_;
3327 my $cust_credit = new FS::cust_credit {
3328 'custnum' => $self->custnum,
3329 'amount' => $amount,
3332 if ( ref($reason) ) {
3334 if ( ref($reason) eq 'SCALAR' ) {
3335 $cust_credit->reasonnum( $$reason );
3337 $cust_credit->reasonnum( $reason->reasonnum );
3341 $cust_credit->set('reason', $reason)
3344 $cust_credit->$_( delete $options{$_} )
3345 foreach grep exists($options{$_}),
3346 qw( addlinfo eventnum ),
3347 map "commission_$_", qw( agentnum salesnum pkgnum );
3349 $cust_credit->insert(%options);
3353 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3355 Creates a one-time charge for this customer. If there is an error, returns
3356 the error, otherwise returns false.
3358 New-style, with a hashref of options:
3360 my $error = $cust_main->charge(
3364 'start_date' => str2time('7/4/2009'),
3365 'pkg' => 'Description',
3366 'comment' => 'Comment',
3367 'additional' => [], #extra invoice detail
3368 'classnum' => 1, #pkg_class
3370 'setuptax' => '', # or 'Y' for tax exempt
3372 'locationnum'=> 1234, # optional
3375 'taxclass' => 'Tax class',
3378 'taxproduct' => 2, #part_pkg_taxproduct
3379 'override' => {}, #XXX describe
3381 #will be filled in with the new object
3382 'cust_pkg_ref' => \$cust_pkg,
3384 #generate an invoice immediately
3386 'invoice_terms' => '', #with these terms
3392 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3398 my ( $amount, $quantity, $start_date, $classnum );
3399 my ( $pkg, $comment, $additional );
3400 my ( $setuptax, $taxclass ); #internal taxes
3401 my ( $taxproduct, $override ); #vendor (CCH) taxes
3403 my $cust_pkg_ref = '';
3404 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3406 if ( ref( $_[0] ) ) {
3407 $amount = $_[0]->{amount};
3408 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3409 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3410 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3411 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3412 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3413 : '$'. sprintf("%.2f",$amount);
3414 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3415 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3416 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3417 $additional = $_[0]->{additional} || [];
3418 $taxproduct = $_[0]->{taxproductnum};
3419 $override = { '' => $_[0]->{tax_override} };
3420 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3421 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3422 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3423 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3428 $pkg = @_ ? shift : 'One-time charge';
3429 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3431 $taxclass = @_ ? shift : '';
3435 local $SIG{HUP} = 'IGNORE';
3436 local $SIG{INT} = 'IGNORE';
3437 local $SIG{QUIT} = 'IGNORE';
3438 local $SIG{TERM} = 'IGNORE';
3439 local $SIG{TSTP} = 'IGNORE';
3440 local $SIG{PIPE} = 'IGNORE';
3442 my $oldAutoCommit = $FS::UID::AutoCommit;
3443 local $FS::UID::AutoCommit = 0;
3446 my $part_pkg = new FS::part_pkg ( {
3448 'comment' => $comment,
3452 'classnum' => ( $classnum ? $classnum : '' ),
3453 'setuptax' => $setuptax,
3454 'taxclass' => $taxclass,
3455 'taxproductnum' => $taxproduct,
3458 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3459 ( 0 .. @$additional - 1 )
3461 'additional_count' => scalar(@$additional),
3462 'setup_fee' => $amount,
3465 my $error = $part_pkg->insert( options => \%options,
3466 tax_overrides => $override,
3469 $dbh->rollback if $oldAutoCommit;
3473 my $pkgpart = $part_pkg->pkgpart;
3474 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3475 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3476 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3477 $error = $type_pkgs->insert;
3479 $dbh->rollback if $oldAutoCommit;
3484 my $cust_pkg = new FS::cust_pkg ( {
3485 'custnum' => $self->custnum,
3486 'pkgpart' => $pkgpart,
3487 'quantity' => $quantity,
3488 'start_date' => $start_date,
3489 'no_auto' => $no_auto,
3490 'locationnum'=> $locationnum,
3493 $error = $cust_pkg->insert;
3495 $dbh->rollback if $oldAutoCommit;
3497 } elsif ( $cust_pkg_ref ) {
3498 ${$cust_pkg_ref} = $cust_pkg;
3502 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3503 'pkg_list' => [ $cust_pkg ],
3506 $dbh->rollback if $oldAutoCommit;
3511 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3516 #=item charge_postal_fee
3518 #Applies a one time charge this customer. If there is an error,
3519 #returns the error, returns the cust_pkg charge object or false
3520 #if there was no charge.
3524 # This should be a customer event. For that to work requires that bill
3525 # also be a customer event.
3527 sub charge_postal_fee {
3530 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3531 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3533 my $cust_pkg = new FS::cust_pkg ( {
3534 'custnum' => $self->custnum,
3535 'pkgpart' => $pkgpart,
3539 my $error = $cust_pkg->insert;
3540 $error ? $error : $cust_pkg;
3543 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3545 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3547 Optionally, a list or hashref of additional arguments to the qsearch call can
3554 my $opt = ref($_[0]) ? shift : { @_ };
3556 #return $self->num_cust_bill unless wantarray || keys %$opt;
3558 $opt->{'table'} = 'cust_bill';
3559 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3560 $opt->{'hashref'}{'custnum'} = $self->custnum;
3561 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3563 map { $_ } #behavior of sort undefined in scalar context
3564 sort { $a->_date <=> $b->_date }
3568 =item open_cust_bill
3570 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3575 sub open_cust_bill {
3579 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3585 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3587 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3591 sub legacy_cust_bill {
3594 #return $self->num_legacy_cust_bill unless wantarray;
3596 map { $_ } #behavior of sort undefined in scalar context
3597 sort { $a->_date <=> $b->_date }
3598 qsearch({ 'table' => 'legacy_cust_bill',
3599 'hashref' => { 'custnum' => $self->custnum, },
3600 'order_by' => 'ORDER BY _date ASC',
3604 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3606 Returns all the statements (see L<FS::cust_statement>) for this customer.
3608 Optionally, a list or hashref of additional arguments to the qsearch call can
3613 =item cust_bill_void
3615 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3619 sub cust_bill_void {
3622 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3623 sort { $a->_date <=> $b->_date }
3624 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3627 sub cust_statement {
3629 my $opt = ref($_[0]) ? shift : { @_ };
3631 #return $self->num_cust_statement unless wantarray || keys %$opt;
3633 $opt->{'table'} = 'cust_statement';
3634 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3635 $opt->{'hashref'}{'custnum'} = $self->custnum;
3636 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3638 map { $_ } #behavior of sort undefined in scalar context
3639 sort { $a->_date <=> $b->_date }
3643 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3645 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3647 Optionally, a list or hashref of additional arguments to the qsearch call can
3648 be passed following the SVCDB.
3655 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3656 warn "$me svc_x requires a svcdb";
3659 my $opt = ref($_[0]) ? shift : { @_ };
3661 $opt->{'table'} = $svcdb;
3662 $opt->{'addl_from'} =
3663 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3664 ($opt->{'addl_from'} || '');
3666 my $custnum = $self->custnum;
3667 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3668 my $where = "cust_pkg.custnum = $custnum";
3670 my $extra_sql = $opt->{'extra_sql'} || '';
3671 if ( keys %{ $opt->{'hashref'} } ) {
3672 $extra_sql = " AND $where $extra_sql";
3675 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3676 $extra_sql = "WHERE $where AND $1";
3679 $extra_sql = "WHERE $where $extra_sql";
3682 $opt->{'extra_sql'} = $extra_sql;
3687 # required for use as an eventtable;
3690 $self->svc_x('svc_acct', @_);
3695 Returns all the credits (see L<FS::cust_credit>) for this customer.
3701 map { $_ } #return $self->num_cust_credit unless wantarray;
3702 sort { $a->_date <=> $b->_date }
3703 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3706 =item cust_credit_pkgnum
3708 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3709 package when using experimental package balances.
3713 sub cust_credit_pkgnum {
3714 my( $self, $pkgnum ) = @_;
3715 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3716 sort { $a->_date <=> $b->_date }
3717 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3718 'pkgnum' => $pkgnum,
3723 =item cust_credit_void
3725 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3729 sub cust_credit_void {
3732 sort { $a->_date <=> $b->_date }
3733 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3738 Returns all the payments (see L<FS::cust_pay>) for this customer.
3744 return $self->num_cust_pay unless wantarray;
3745 sort { $a->_date <=> $b->_date }
3746 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3751 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3752 called automatically when the cust_pay method is used in a scalar context.
3758 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3759 my $sth = dbh->prepare($sql) or die dbh->errstr;
3760 $sth->execute($self->custnum) or die $sth->errstr;
3761 $sth->fetchrow_arrayref->[0];
3764 =item cust_pay_pkgnum
3766 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3767 package when using experimental package balances.
3771 sub cust_pay_pkgnum {
3772 my( $self, $pkgnum ) = @_;
3773 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3774 sort { $a->_date <=> $b->_date }
3775 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3776 'pkgnum' => $pkgnum,
3783 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3789 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3790 sort { $a->_date <=> $b->_date }
3791 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3794 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3796 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3798 Optionally, a list or hashref of additional arguments to the qsearch call can
3803 sub cust_pay_batch {
3805 my $opt = ref($_[0]) ? shift : { @_ };
3807 #return $self->num_cust_statement unless wantarray || keys %$opt;
3809 $opt->{'table'} = 'cust_pay_batch';
3810 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3811 $opt->{'hashref'}{'custnum'} = $self->custnum;
3812 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3814 map { $_ } #behavior of sort undefined in scalar context
3815 sort { $a->paybatchnum <=> $b->paybatchnum }
3819 =item cust_pay_pending
3821 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3822 (without status "done").
3826 sub cust_pay_pending {
3828 return $self->num_cust_pay_pending unless wantarray;
3829 sort { $a->_date <=> $b->_date }
3830 qsearch( 'cust_pay_pending', {
3831 'custnum' => $self->custnum,
3832 'status' => { op=>'!=', value=>'done' },
3837 =item cust_pay_pending_attempt
3839 Returns all payment attempts / declined payments for this customer, as pending
3840 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3841 a corresponding payment (see L<FS::cust_pay>).
3845 sub cust_pay_pending_attempt {
3847 return $self->num_cust_pay_pending_attempt unless wantarray;
3848 sort { $a->_date <=> $b->_date }
3849 qsearch( 'cust_pay_pending', {
3850 'custnum' => $self->custnum,
3857 =item num_cust_pay_pending
3859 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3860 customer (without status "done"). Also called automatically when the
3861 cust_pay_pending method is used in a scalar context.
3865 sub num_cust_pay_pending {
3868 " SELECT COUNT(*) FROM cust_pay_pending ".
3869 " WHERE custnum = ? AND status != 'done' ",
3874 =item num_cust_pay_pending_attempt
3876 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3877 customer, with status "done" but without a corresp. Also called automatically when the
3878 cust_pay_pending method is used in a scalar context.
3882 sub num_cust_pay_pending_attempt {
3885 " SELECT COUNT(*) FROM cust_pay_pending ".
3886 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3893 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3899 map { $_ } #return $self->num_cust_refund unless wantarray;
3900 sort { $a->_date <=> $b->_date }
3901 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3904 =item display_custnum
3906 Returns the displayed customer number for this customer: agent_custid if
3907 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3911 sub display_custnum {
3914 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3915 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3916 if ( $special eq 'CoStAg' ) {
3917 $prefix = uc( join('',
3919 ($self->state =~ /^(..)/),
3920 $prefix || ($self->agent->agent =~ /^(..)/)
3923 elsif ( $special eq 'CoStCl' ) {
3924 $prefix = uc( join('',
3926 ($self->state =~ /^(..)/),
3927 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3930 # add any others here if needed
3933 my $length = $conf->config('cust_main-custnum-display_length');
3934 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3935 return $self->agent_custid;
3936 } elsif ( $prefix ) {
3937 $length = 8 if !defined($length);
3939 sprintf('%0'.$length.'d', $self->custnum)
3940 } elsif ( $length ) {
3941 return sprintf('%0'.$length.'d', $self->custnum);
3943 return $self->custnum;
3949 Returns a name string for this customer, either "Company (Last, First)" or
3956 my $name = $self->contact;
3957 $name = $self->company. " ($name)" if $self->company;
3961 =item service_contact
3963 Returns the L<FS::contact> object for this customer that has the 'Service'
3964 contact class, or undef if there is no such contact. Deprecated; don't use
3969 sub service_contact {
3971 if ( !exists($self->{service_contact}) ) {
3972 my $classnum = $self->scalar_sql(
3973 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3974 ) || 0; #if it's zero, qsearchs will return nothing
3975 $self->{service_contact} = qsearchs('contact', {
3976 'classnum' => $classnum, 'custnum' => $self->custnum
3979 $self->{service_contact};
3984 Returns a name string for this (service/shipping) contact, either
3985 "Company (Last, First)" or "Last, First".
3992 my $name = $self->ship_contact;
3993 $name = $self->company. " ($name)" if $self->company;
3999 Returns a name string for this customer, either "Company" or "First Last".
4005 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4008 =item ship_name_short
4010 Returns a name string for this (service/shipping) contact, either "Company"
4015 sub ship_name_short {
4017 $self->service_contact
4018 ? $self->ship_contact_firstlast
4024 Returns this customer's full (billing) contact name only, "Last, First"
4030 $self->get('last'). ', '. $self->first;
4035 Returns this customer's full (shipping) contact name only, "Last, First"
4041 my $contact = $self->service_contact || $self;
4042 $contact->get('last') . ', ' . $contact->get('first');
4045 =item contact_firstlast
4047 Returns this customers full (billing) contact name only, "First Last".
4051 sub contact_firstlast {
4053 $self->first. ' '. $self->get('last');
4056 =item ship_contact_firstlast
4058 Returns this customer's full (shipping) contact name only, "First Last".
4062 sub ship_contact_firstlast {
4064 my $contact = $self->service_contact || $self;
4065 $contact->get('first') . ' '. $contact->get('last');
4068 #XXX this doesn't work in 3.x+
4071 #Returns this customer's full country name
4077 # code2country($self->country);
4080 sub bill_country_full {
4082 code2country($self->bill_location->country);
4085 sub ship_country_full {
4087 code2country($self->ship_location->country);
4090 =item county_state_county [ PREFIX ]
4092 Returns a string consisting of just the county, state and country.
4096 sub county_state_country {
4099 if ( @_ && $_[0] && $self->has_ship_address ) {
4100 $locationnum = $self->ship_locationnum;
4102 $locationnum = $self->bill_locationnum;
4104 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4105 $cust_location->county_state_country;
4108 =item geocode DATA_VENDOR
4110 Returns a value for the customer location as encoded by DATA_VENDOR.
4111 Currently this only makes sense for "CCH" as DATA_VENDOR.
4119 Returns a status string for this customer, currently:
4123 =item prospect - No packages have ever been ordered
4125 =item ordered - Recurring packages all are new (not yet billed).
4127 =item active - One or more recurring packages is active
4129 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4131 =item suspended - All non-cancelled recurring packages are suspended
4133 =item cancelled - All recurring packages are cancelled
4137 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4138 cust_main-status_module configuration option.
4142 sub status { shift->cust_status(@_); }
4146 for my $status ( FS::cust_main->statuses() ) {
4147 my $method = $status.'_sql';
4148 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4149 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4150 $sth->execute( ($self->custnum) x $numnum )
4151 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4152 return $status if $sth->fetchrow_arrayref->[0];
4156 =item ucfirst_cust_status
4158 =item ucfirst_status
4160 Returns the status with the first character capitalized.
4164 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4166 sub ucfirst_cust_status {
4168 ucfirst($self->cust_status);
4173 Returns a hex triplet color string for this customer's status.
4177 sub statuscolor { shift->cust_statuscolor(@_); }
4179 sub cust_statuscolor {
4181 __PACKAGE__->statuscolors->{$self->cust_status};
4184 =item tickets [ STATUS ]
4186 Returns an array of hashes representing the customer's RT tickets.
4188 An optional status (or arrayref or hashref of statuses) may be specified.
4194 my $status = ( @_ && $_[0] ) ? shift : '';
4196 my $num = $conf->config('cust_main-max_tickets') || 10;
4199 if ( $conf->config('ticket_system') ) {
4200 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4202 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4211 foreach my $priority (
4212 $conf->config('ticket_system-custom_priority_field-values'), ''
4214 last if scalar(@tickets) >= $num;
4216 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4217 $num - scalar(@tickets),
4228 # Return services representing svc_accts in customer support packages
4229 sub support_services {
4231 my %packages = map { $_ => 1 } $conf->config('support_packages');
4233 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4234 grep { $_->part_svc->svcdb eq 'svc_acct' }
4235 map { $_->cust_svc }
4236 grep { exists $packages{ $_->pkgpart } }
4237 $self->ncancelled_pkgs;
4241 # Return a list of latitude/longitude for one of the services (if any)
4242 sub service_coordinates {
4246 grep { $_->latitude && $_->longitude }
4248 map { $_->cust_svc }
4249 $self->ncancelled_pkgs;
4251 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4256 Returns a masked version of the named field
4261 my ($self,$field) = @_;
4265 'x'x(length($self->getfield($field))-4).
4266 substr($self->getfield($field), (length($self->getfield($field))-4));
4272 =head1 CLASS METHODS
4278 Class method that returns the list of possible status strings for customers
4279 (see L<the status method|/status>). For example:
4281 @statuses = FS::cust_main->statuses();
4287 keys %{ $self->statuscolors };
4290 =item cust_status_sql
4292 Returns an SQL fragment to determine the status of a cust_main record, as a
4297 sub cust_status_sql {
4299 for my $status ( FS::cust_main->statuses() ) {
4300 my $method = $status.'_sql';
4301 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4310 Returns an SQL expression identifying prospective cust_main records (customers
4311 with no packages ever ordered)
4315 use vars qw($select_count_pkgs);
4316 $select_count_pkgs =
4317 "SELECT COUNT(*) FROM cust_pkg
4318 WHERE cust_pkg.custnum = cust_main.custnum";
4320 sub select_count_pkgs_sql {
4325 " 0 = ( $select_count_pkgs ) ";
4330 Returns an SQL expression identifying ordered cust_main records (customers with
4331 no active packages, but recurring packages not yet setup or one time charges
4337 FS::cust_main->none_active_sql.
4338 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4343 Returns an SQL expression identifying active cust_main records (customers with
4344 active recurring packages).
4349 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4352 =item none_active_sql
4354 Returns an SQL expression identifying cust_main records with no active
4355 recurring packages. This includes customers of status prospect, ordered,
4356 inactive, and suspended.
4360 sub none_active_sql {
4361 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4366 Returns an SQL expression identifying inactive cust_main records (customers with
4367 no active recurring packages, but otherwise unsuspended/uncancelled).
4372 FS::cust_main->none_active_sql.
4373 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4379 Returns an SQL expression identifying suspended cust_main records.
4384 sub suspended_sql { susp_sql(@_); }
4386 FS::cust_main->none_active_sql.
4387 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4393 Returns an SQL expression identifying cancelled cust_main records.
4397 sub cancel_sql { shift->cancelled_sql(@_); }
4400 =item uncancelled_sql
4402 Returns an SQL expression identifying un-cancelled cust_main records.
4406 sub uncancelled_sql { uncancel_sql(@_); }
4407 sub uncancel_sql { "
4408 ( 0 < ( $select_count_pkgs
4409 AND ( cust_pkg.cancel IS NULL
4410 OR cust_pkg.cancel = 0
4413 OR 0 = ( $select_count_pkgs )
4419 Returns an SQL fragment to retreive the balance.
4424 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4425 WHERE cust_bill.custnum = cust_main.custnum )
4426 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4427 WHERE cust_pay.custnum = cust_main.custnum )
4428 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4429 WHERE cust_credit.custnum = cust_main.custnum )
4430 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4431 WHERE cust_refund.custnum = cust_main.custnum )
4434 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4436 Returns an SQL fragment to retreive the balance for this customer, optionally
4437 considering invoices with date earlier than START_TIME, and not
4438 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4439 total_unapplied_payments).
4441 Times are specified as SQL fragments or numeric
4442 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4443 L<Date::Parse> for conversion functions. The empty string can be passed
4444 to disable that time constraint completely.
4446 Available options are:
4450 =item unapplied_date
4452 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)
4457 set to true to remove all customer comparison clauses, for totals
4462 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4467 JOIN clause (typically used with the total option)
4471 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4472 time will be ignored. Note that START_TIME and END_TIME only limit the date
4473 range for invoices and I<unapplied> payments, credits, and refunds.
4479 sub balance_date_sql {
4480 my( $class, $start, $end, %opt ) = @_;
4482 my $cutoff = $opt{'cutoff'};
4484 my $owed = FS::cust_bill->owed_sql($cutoff);
4485 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4486 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4487 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4489 my $j = $opt{'join'} || '';
4491 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4492 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4493 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4494 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4496 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4497 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4498 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4499 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4504 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4506 Returns an SQL fragment to retreive the total unapplied payments for this
4507 customer, only considering payments with date earlier than START_TIME, and
4508 optionally not later than END_TIME.
4510 Times are specified as SQL fragments or numeric
4511 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4512 L<Date::Parse> for conversion functions. The empty string can be passed
4513 to disable that time constraint completely.
4515 Available options are:
4519 sub unapplied_payments_date_sql {
4520 my( $class, $start, $end, %opt ) = @_;
4522 my $cutoff = $opt{'cutoff'};
4524 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4526 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4527 'unapplied_date'=>1 );
4529 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4532 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4534 Helper method for balance_date_sql; name (and usage) subject to change
4535 (suggestions welcome).
4537 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4538 cust_refund, cust_credit or cust_pay).
4540 If TABLE is "cust_bill" or the unapplied_date option is true, only
4541 considers records with date earlier than START_TIME, and optionally not
4542 later than END_TIME .
4546 sub _money_table_where {
4547 my( $class, $table, $start, $end, %opt ) = @_;
4550 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4551 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4552 push @where, "$table._date <= $start" if defined($start) && length($start);
4553 push @where, "$table._date > $end" if defined($end) && length($end);
4555 push @where, @{$opt{'where'}} if $opt{'where'};
4556 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4562 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4563 use FS::cust_main::Search;
4566 FS::cust_main::Search->search(@_);
4581 #warn join('-',keys %$param);
4582 my $fh = $param->{filehandle};
4583 my $agentnum = $param->{agentnum};
4584 my $format = $param->{format};
4586 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4589 if ( $format eq 'simple' ) {
4590 @fields = qw( custnum agent_custid amount pkg );
4592 die "unknown format $format";
4595 eval "use Text::CSV_XS;";
4598 my $csv = new Text::CSV_XS;
4605 local $SIG{HUP} = 'IGNORE';
4606 local $SIG{INT} = 'IGNORE';
4607 local $SIG{QUIT} = 'IGNORE';
4608 local $SIG{TERM} = 'IGNORE';
4609 local $SIG{TSTP} = 'IGNORE';
4610 local $SIG{PIPE} = 'IGNORE';
4612 my $oldAutoCommit = $FS::UID::AutoCommit;
4613 local $FS::UID::AutoCommit = 0;
4616 #while ( $columns = $csv->getline($fh) ) {
4618 while ( defined($line=<$fh>) ) {
4620 $csv->parse($line) or do {
4621 $dbh->rollback if $oldAutoCommit;
4622 return "can't parse: ". $csv->error_input();
4625 my @columns = $csv->fields();
4626 #warn join('-',@columns);
4629 foreach my $field ( @fields ) {
4630 $row{$field} = shift @columns;
4633 if ( $row{custnum} && $row{agent_custid} ) {
4634 dbh->rollback if $oldAutoCommit;
4635 return "can't specify custnum with agent_custid $row{agent_custid}";
4639 if ( $row{agent_custid} && $agentnum ) {
4640 %hash = ( 'agent_custid' => $row{agent_custid},
4641 'agentnum' => $agentnum,
4645 if ( $row{custnum} ) {
4646 %hash = ( 'custnum' => $row{custnum} );
4649 unless ( scalar(keys %hash) ) {
4650 $dbh->rollback if $oldAutoCommit;
4651 return "can't find customer without custnum or agent_custid and agentnum";
4654 my $cust_main = qsearchs('cust_main', { %hash } );
4655 unless ( $cust_main ) {
4656 $dbh->rollback if $oldAutoCommit;
4657 my $custnum = $row{custnum} || $row{agent_custid};
4658 return "unknown custnum $custnum";
4661 if ( $row{'amount'} > 0 ) {
4662 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4664 $dbh->rollback if $oldAutoCommit;
4668 } elsif ( $row{'amount'} < 0 ) {
4669 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4672 $dbh->rollback if $oldAutoCommit;
4682 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4684 return "Empty file!" unless $imported;
4690 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4692 Deprecated. Use event notification and message templates
4693 (L<FS::msg_template>) instead.
4695 Sends a templated email notification to the customer (see L<Text::Template>).
4697 OPTIONS is a hash and may include
4699 I<from> - the email sender (default is invoice_from)
4701 I<to> - comma-separated scalar or arrayref of recipients
4702 (default is invoicing_list)
4704 I<subject> - The subject line of the sent email notification
4705 (default is "Notice from company_name")
4707 I<extra_fields> - a hashref of name/value pairs which will be substituted
4710 The following variables are vavailable in the template.
4712 I<$first> - the customer first name
4713 I<$last> - the customer last name
4714 I<$company> - the customer company
4715 I<$payby> - a description of the method of payment for the customer
4716 # would be nice to use FS::payby::shortname
4717 I<$payinfo> - the account information used to collect for this customer
4718 I<$expdate> - the expiration of the customer payment in seconds from epoch
4723 my ($self, $template, %options) = @_;
4725 return unless $conf->exists($template);
4727 my $from = $conf->config('invoice_from', $self->agentnum)
4728 if $conf->exists('invoice_from', $self->agentnum);
4729 $from = $options{from} if exists($options{from});
4731 my $to = join(',', $self->invoicing_list_emailonly);
4732 $to = $options{to} if exists($options{to});
4734 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4735 if $conf->exists('company_name', $self->agentnum);
4736 $subject = $options{subject} if exists($options{subject});
4738 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4739 SOURCE => [ map "$_\n",
4740 $conf->config($template)]
4742 or die "can't create new Text::Template object: Text::Template::ERROR";
4743 $notify_template->compile()
4744 or die "can't compile template: Text::Template::ERROR";
4746 $FS::notify_template::_template::company_name =
4747 $conf->config('company_name', $self->agentnum);
4748 $FS::notify_template::_template::company_address =
4749 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4751 my $paydate = $self->paydate || '2037-12-31';
4752 $FS::notify_template::_template::first = $self->first;
4753 $FS::notify_template::_template::last = $self->last;
4754 $FS::notify_template::_template::company = $self->company;
4755 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4756 my $payby = $self->payby;
4757 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4758 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4760 #credit cards expire at the end of the month/year of their exp date
4761 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4762 $FS::notify_template::_template::payby = 'credit card';
4763 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4764 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4766 }elsif ($payby eq 'COMP') {
4767 $FS::notify_template::_template::payby = 'complimentary account';
4769 $FS::notify_template::_template::payby = 'current method';
4771 $FS::notify_template::_template::expdate = $expire_time;
4773 for (keys %{$options{extra_fields}}){
4775 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4778 send_email(from => $from,
4780 subject => $subject,
4781 body => $notify_template->fill_in( PACKAGE =>
4782 'FS::notify_template::_template' ),
4787 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4789 Generates a templated notification to the customer (see L<Text::Template>).
4791 OPTIONS is a hash and may include
4793 I<extra_fields> - a hashref of name/value pairs which will be substituted
4794 into the template. These values may override values mentioned below
4795 and those from the customer record.
4797 The following variables are available in the template instead of or in addition
4798 to the fields of the customer record.
4800 I<$payby> - a description of the method of payment for the customer
4801 # would be nice to use FS::payby::shortname
4802 I<$payinfo> - the masked account information used to collect for this customer
4803 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4804 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4808 # a lot like cust_bill::print_latex
4809 sub generate_letter {
4810 my ($self, $template, %options) = @_;
4812 return unless $conf->exists($template);
4814 my $letter_template = new Text::Template
4816 SOURCE => [ map "$_\n", $conf->config($template)],
4817 DELIMITERS => [ '[@--', '--@]' ],
4819 or die "can't create new Text::Template object: Text::Template::ERROR";
4821 $letter_template->compile()
4822 or die "can't compile template: Text::Template::ERROR";
4824 my %letter_data = map { $_ => $self->$_ } $self->fields;
4825 $letter_data{payinfo} = $self->mask_payinfo;
4827 #my $paydate = $self->paydate || '2037-12-31';
4828 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4830 my $payby = $self->payby;
4831 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4832 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4834 #credit cards expire at the end of the month/year of their exp date
4835 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4836 $letter_data{payby} = 'credit card';
4837 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4838 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4840 }elsif ($payby eq 'COMP') {
4841 $letter_data{payby} = 'complimentary account';
4843 $letter_data{payby} = 'current method';
4845 $letter_data{expdate} = $expire_time;
4847 for (keys %{$options{extra_fields}}){
4848 $letter_data{$_} = $options{extra_fields}->{$_};
4851 unless(exists($letter_data{returnaddress})){
4852 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4853 $self->agent_template)
4855 if ( length($retadd) ) {
4856 $letter_data{returnaddress} = $retadd;
4857 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4858 $letter_data{returnaddress} =
4859 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4863 ( $conf->config('company_name', $self->agentnum),
4864 $conf->config('company_address', $self->agentnum),
4868 $letter_data{returnaddress} = '~';
4872 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4874 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4876 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4878 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4882 ) or die "can't open temp file: $!\n";
4883 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4884 or die "can't write temp file: $!\n";
4886 $letter_data{'logo_file'} = $lh->filename;
4888 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4892 ) or die "can't open temp file: $!\n";
4894 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4896 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4897 return ($1, $letter_data{'logo_file'});
4901 =item print_ps TEMPLATE
4903 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4909 my($file, $lfile) = $self->generate_letter(@_);
4910 my $ps = FS::Misc::generate_ps($file);
4911 unlink($file.'.tex');
4917 =item print TEMPLATE
4919 Prints the filled in template.
4921 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4925 sub queueable_print {
4928 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4929 or die "invalid customer number: " . $opt{custnum};
4931 my $error = $self->print( { 'template' => $opt{template} } );
4932 die $error if $error;
4936 my ($self, $template) = (shift, shift);
4938 [ $self->print_ps($template) ],
4939 'agentnum' => $self->agentnum,
4943 #these three subs should just go away once agent stuff is all config overrides
4945 sub agent_template {
4947 $self->_agent_plandata('agent_templatename');
4950 sub agent_invoice_from {
4952 $self->_agent_plandata('agent_invoice_from');
4955 sub _agent_plandata {
4956 my( $self, $option ) = @_;
4958 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4959 #agent-specific Conf
4961 use FS::part_event::Condition;
4963 my $agentnum = $self->agentnum;
4965 my $regexp = regexp_sql();
4967 my $part_event_option =
4969 'select' => 'part_event_option.*',
4970 'table' => 'part_event_option',
4972 LEFT JOIN part_event USING ( eventpart )
4973 LEFT JOIN part_event_option AS peo_agentnum
4974 ON ( part_event.eventpart = peo_agentnum.eventpart
4975 AND peo_agentnum.optionname = 'agentnum'
4976 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4978 LEFT JOIN part_event_condition
4979 ON ( part_event.eventpart = part_event_condition.eventpart
4980 AND part_event_condition.conditionname = 'cust_bill_age'
4982 LEFT JOIN part_event_condition_option
4983 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4984 AND part_event_condition_option.optionname = 'age'
4987 #'hashref' => { 'optionname' => $option },
4988 #'hashref' => { 'part_event_option.optionname' => $option },
4990 " WHERE part_event_option.optionname = ". dbh->quote($option).
4991 " AND action = 'cust_bill_send_agent' ".
4992 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4993 " AND peo_agentnum.optionname = 'agentnum' ".
4994 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4996 CASE WHEN part_event_condition_option.optionname IS NULL
4998 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5000 , part_event.weight".
5004 unless ( $part_event_option ) {
5005 return $self->agent->invoice_template || ''
5006 if $option eq 'agent_templatename';
5010 $part_event_option->optionvalue;
5014 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5016 Subroutine (not a method), designed to be called from the queue.
5018 Takes a list of options and values.
5020 Pulls up the customer record via the custnum option and calls bill_and_collect.
5025 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5027 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5028 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5030 $cust_main->bill_and_collect( %args );
5033 sub process_bill_and_collect {
5035 my $param = thaw(decode_base64(shift));
5036 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5037 or die "custnum '$param->{custnum}' not found!\n";
5038 $param->{'job'} = $job;
5039 $param->{'fatal'} = 1; # runs from job queue, will be caught
5040 $param->{'retry'} = 1;
5042 $cust_main->bill_and_collect( %$param );
5045 #starting to take quite a while for big dbs
5046 # (JRNL: journaled so it only happens once per database)
5047 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5048 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5049 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5050 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5051 # JRNL leading/trailing spaces in first, last, company
5052 # JRNL migrate to cust_payby
5053 # - otaker upgrade? journal and call it good? (double check to make sure
5054 # we're not still setting otaker here)
5056 #only going to get worse with new location stuff...
5058 sub _upgrade_data { #class method
5059 my ($class, %opts) = @_;
5062 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5065 #this seems to be the only expensive one.. why does it take so long?
5066 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5068 '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';
5069 FS::upgrade_journal->set_done('cust_main__signupdate');
5072 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5074 # fix yyyy-m-dd formatted paydates
5075 if ( driver_name =~ /^mysql/i ) {
5077 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5078 } else { # the SQL standard
5080 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5082 FS::upgrade_journal->set_done('cust_main__paydate');
5085 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5087 push @statements, #fix the weird BILL with a cc# in payinfo problem
5089 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5091 FS::upgrade_journal->set_done('cust_main__payinfo');
5096 foreach my $sql ( @statements ) {
5097 my $sth = dbh->prepare($sql) or die dbh->errstr;
5098 $sth->execute or die $sth->errstr;
5099 #warn ( (time - $t). " seconds\n" );
5103 local($ignore_expired_card) = 1;
5104 local($ignore_banned_card) = 1;
5105 local($skip_fuzzyfiles) = 1;
5106 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5108 FS::cust_main::Location->_upgrade_data(%opts);
5110 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5112 foreach my $cust_main ( qsearch({
5113 'table' => 'cust_main',
5115 'extra_sql' => 'WHERE '.
5117 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5118 qw( first last company )
5121 my $error = $cust_main->replace;
5122 die $error if $error;
5125 FS::upgrade_journal->set_done('cust_main__trimspaces');
5129 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5131 #we don't want to decrypt them, just stuff them as-is into cust_payby
5132 local(@encrypted_fields) = ();
5134 local($FS::cust_payby::ignore_expired_card) = 1;
5135 local($FS::cust_payby::ignore_banned_card) = 1;
5137 my @payfields = qw( payby payinfo paycvv paymask
5138 paydate paystart_month paystart_year payissue
5139 payname paystate paytype payip
5142 my $search = new FS::Cursor {
5143 'table' => 'cust_main',
5144 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5147 while (my $cust_main = $search->fetch) {
5149 my $cust_payby = new FS::cust_payby {
5150 'custnum' => $cust_main->custnum,
5152 map { $_ => $cust_main->$_(); } @payfields
5155 my $error = $cust_payby->insert;
5156 die $error if $error;
5158 $cust_main->setfield($_, '') foreach @payfields;
5159 $error = $cust_main->replace;
5160 die $error if $error;
5164 FS::upgrade_journal->set_done('cust_main__cust_payby');
5167 $class->_upgrade_otaker(%opts);
5177 The delete method should possibly take an FS::cust_main object reference
5178 instead of a scalar customer number.
5180 Bill and collect options should probably be passed as references instead of a
5183 There should probably be a configuration file with a list of allowed credit
5186 No multiple currency support (probably a larger project than just this module).
5188 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5190 Birthdates rely on negative epoch values.
5192 The payby for card/check batches is broken. With mixed batching, bad
5195 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5199 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5200 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5201 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.