5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6 FS::cust_main::NationalID
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
12 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
16 use vars qw( $DEBUG $me $conf
19 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
24 use Scalar::Util qw( blessed );
25 use Time::Local qw(timelocal);
26 use Storable qw(thaw);
30 use Digest::MD5 qw(md5_base64);
33 use File::Temp; #qw( tempfile );
34 use Business::CreditCard 0.28;
36 use FS::UID qw( dbh driver_name );
37 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
39 use FS::Misc qw( generate_email send_email generate_ps do_print );
40 use FS::Msgcat qw(gettext);
47 use FS::cust_bill_void;
48 use FS::legacy_cust_bill;
50 use FS::cust_pay_pending;
51 use FS::cust_pay_void;
52 use FS::cust_pay_batch;
55 use FS::part_referral;
56 use FS::cust_main_county;
57 use FS::cust_location;
59 use FS::cust_main_exemption;
60 use FS::cust_tax_adjustment;
61 use FS::cust_tax_location;
63 use FS::agent_currency;
64 use FS::cust_main_invoice;
66 use FS::prepay_credit;
72 use FS::payment_gateway;
73 use FS::agent_payment_gateway;
75 use FS::cust_main_note;
76 use FS::cust_attachment;
79 use FS::upgrade_journal;
83 # 1 is mostly method/subroutine entry and options
84 # 2 traces progress of some operations
85 # 3 is even more information including possibly sensitive data
87 $me = '[FS::cust_main]';
90 $ignore_expired_card = 0;
91 $ignore_banned_card = 0;
95 @encrypted_fields = ('payinfo', 'paycvv');
96 sub nohistory_fields { ('payinfo', 'paycvv'); }
98 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
100 #ask FS::UID to run this stuff for us later
101 #$FS::UID::callback{'FS::cust_main'} = sub {
102 install_callback FS::UID sub {
103 $conf = new FS::Conf;
104 #yes, need it for stuff below (prolly should be cached)
109 my ( $hashref, $cache ) = @_;
110 if ( exists $hashref->{'pkgnum'} ) {
111 #@{ $self->{'_pkgnum'} } = ();
112 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
113 $self->{'_pkgnum'} = $subcache;
114 #push @{ $self->{'_pkgnum'} },
115 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
121 FS::cust_main - Object methods for cust_main records
127 $record = new FS::cust_main \%hash;
128 $record = new FS::cust_main { 'column' => 'value' };
130 $error = $record->insert;
132 $error = $new_record->replace($old_record);
134 $error = $record->delete;
136 $error = $record->check;
138 @cust_pkg = $record->all_pkgs;
140 @cust_pkg = $record->ncancelled_pkgs;
142 @cust_pkg = $record->suspended_pkgs;
144 $error = $record->bill;
145 $error = $record->bill %options;
146 $error = $record->bill 'time' => $time;
148 $error = $record->collect;
149 $error = $record->collect %options;
150 $error = $record->collect 'invoice_time' => $time,
155 An FS::cust_main object represents a customer. FS::cust_main inherits from
156 FS::Record. The following fields are currently supported:
162 Primary key (assigned automatically for new customers)
166 Agent (see L<FS::agent>)
170 Advertising source (see L<FS::part_referral>)
182 Cocial security number (optional)
206 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
210 Payment Information (See L<FS::payinfo_Mixin> for data format)
214 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
218 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
222 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
226 Start date month (maestro/solo cards only)
230 Start date year (maestro/solo cards only)
234 Issue number (maestro/solo cards only)
238 Name on card or billing name
242 IP address from which payment information was received
246 Tax exempt, empty or `Y'
250 Order taker (see L<FS::access_user>)
256 =item referral_custnum
258 Referring customer number
262 Enable individual CDR spooling, empty or `Y'
266 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
270 Discourage individual CDR printing, empty or `Y'
274 Allow self-service editing of ticket subjects, empty or 'Y'
276 =item calling_list_exempt
278 Do not call, empty or 'Y'
288 Creates a new customer. To add the customer to the database, see L<"insert">.
290 Note that this stores the hash reference, not a distinct copy of the hash it
291 points to. You can ask the object for a copy with the I<hash> method.
295 sub table { 'cust_main'; }
297 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
299 Adds this customer to the database. If there is an error, returns the error,
300 otherwise returns false.
302 Usually the customer's location will not yet exist in the database, and
303 the C<bill_location> and C<ship_location> pseudo-fields must be set to
304 uninserted L<FS::cust_location> objects. These will be inserted and linked
305 (in both directions) to the new customer record. If they're references
306 to the same object, they will become the same location.
308 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
309 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
310 are inserted atomicly, or the transaction is rolled back. Passing an empty
311 hash reference is equivalent to not supplying this parameter. There should be
312 a better explanation of this, but until then, here's an example:
315 tie %hash, 'Tie::RefHash'; #this part is important
317 $cust_pkg => [ $svc_acct ],
320 $cust_main->insert( \%hash );
322 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
323 be set as the invoicing list (see L<"invoicing_list">). Errors return as
324 expected and rollback the entire transaction; it is not necessary to call
325 check_invoicing_list first. The invoicing_list is set after the records in the
326 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
327 invoicing_list destination to the newly-created svc_acct. Here's an example:
329 $cust_main->insert( {}, [ $email, 'POST' ] );
331 Currently available options are: I<depend_jobnum>, I<noexport>,
332 I<tax_exemption> and I<prospectnum>.
334 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
335 on the supplied jobnum (they will not run until the specific job completes).
336 This can be used to defer provisioning until some action completes (such
337 as running the customer's credit card successfully).
339 The I<noexport> option is deprecated. If I<noexport> is set true, no
340 provisioning jobs (exports) are scheduled. (You can schedule them later with
341 the B<reexport> method.)
343 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
344 of tax names and exemption numbers. FS::cust_main_exemption records will be
345 created and inserted.
347 If I<prospectnum> is set, moves contacts and locations from that prospect.
353 my $cust_pkgs = @_ ? shift : {};
354 my $invoicing_list = @_ ? shift : '';
356 warn "$me insert called with options ".
357 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
360 local $SIG{HUP} = 'IGNORE';
361 local $SIG{INT} = 'IGNORE';
362 local $SIG{QUIT} = 'IGNORE';
363 local $SIG{TERM} = 'IGNORE';
364 local $SIG{TSTP} = 'IGNORE';
365 local $SIG{PIPE} = 'IGNORE';
367 my $oldAutoCommit = $FS::UID::AutoCommit;
368 local $FS::UID::AutoCommit = 0;
371 my $prepay_identifier = '';
372 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
374 if ( $self->payby eq 'PREPAY' ) {
376 $self->payby('BILL');
377 $prepay_identifier = $self->payinfo;
380 warn " looking up prepaid card $prepay_identifier\n"
383 my $error = $self->get_prepay( $prepay_identifier,
384 'amount_ref' => \$amount,
385 'seconds_ref' => \$seconds,
386 'upbytes_ref' => \$upbytes,
387 'downbytes_ref' => \$downbytes,
388 'totalbytes_ref' => \$totalbytes,
391 $dbh->rollback if $oldAutoCommit;
392 #return "error applying prepaid card (transaction rolled back): $error";
396 $payby = 'PREP' if $amount;
398 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|PPAL)$/ ) {
401 $self->payby('BILL');
402 $amount = $self->paid;
407 foreach my $l (qw(bill_location ship_location)) {
408 my $loc = delete $self->hashref->{$l};
409 # XXX if we're moving a prospect's locations, do that here
414 if ( !$loc->locationnum ) {
415 # warn the location that we're going to insert it with no custnum
416 $loc->set(custnum_pending => 1);
417 warn " inserting $l\n"
419 my $error = $loc->insert;
421 $dbh->rollback if $oldAutoCommit;
422 my $label = $l eq 'ship_location' ? 'service' : 'billing';
423 return "$error (in $label location)";
426 elsif ( ($loc->custnum || 0) > 0 or $loc->prospectnum ) {
427 # then it somehow belongs to another customer--shouldn't happen
428 $dbh->rollback if $oldAutoCommit;
429 return "$l belongs to customer ".$loc->custnum;
431 # else it already belongs to this customer
432 # (happens when ship_location is identical to bill_location)
434 $self->set($l.'num', $loc->locationnum);
436 if ( $self->get($l.'num') eq '' ) {
437 $dbh->rollback if $oldAutoCommit;
442 warn " inserting $self\n"
445 $self->signupdate(time) unless $self->signupdate;
447 $self->auto_agent_custid()
448 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
450 my $error = $self->SUPER::insert;
452 $dbh->rollback if $oldAutoCommit;
453 #return "inserting cust_main record (transaction rolled back): $error";
457 # now set cust_location.custnum
458 foreach my $l (qw(bill_location ship_location)) {
459 warn " setting $l.custnum\n"
462 unless ( $loc->custnum ) {
463 $loc->set(custnum => $self->custnum);
464 $error ||= $loc->replace;
468 $dbh->rollback if $oldAutoCommit;
469 return "error setting $l custnum: $error";
473 warn " setting invoicing list\n"
476 if ( $invoicing_list ) {
477 $error = $self->check_invoicing_list( $invoicing_list );
479 $dbh->rollback if $oldAutoCommit;
480 #return "checking invoicing_list (transaction rolled back): $error";
483 $self->invoicing_list( $invoicing_list );
486 warn " setting customer tags\n"
489 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
490 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
491 'custnum' => $self->custnum };
492 my $error = $cust_tag->insert;
494 $dbh->rollback if $oldAutoCommit;
499 my $prospectnum = delete $options{'prospectnum'};
500 if ( $prospectnum ) {
502 warn " moving contacts and locations from prospect $prospectnum\n"
506 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
507 unless ( $prospect_main ) {
508 $dbh->rollback if $oldAutoCommit;
509 return "Unknown prospectnum $prospectnum";
511 $prospect_main->custnum($self->custnum);
512 $prospect_main->disabled('Y');
513 my $error = $prospect_main->replace;
515 $dbh->rollback if $oldAutoCommit;
519 my @contact = $prospect_main->contact;
520 my @cust_location = $prospect_main->cust_location;
521 my @qual = $prospect_main->qual;
523 foreach my $r ( @contact, @cust_location, @qual ) {
525 $r->custnum($self->custnum);
526 my $error = $r->replace;
528 $dbh->rollback if $oldAutoCommit;
535 warn " setting cust_main_exemption\n"
538 my $tax_exemption = delete $options{'tax_exemption'};
539 if ( $tax_exemption ) {
541 $tax_exemption = { map { $_ => '' } @$tax_exemption }
542 if ref($tax_exemption) eq 'ARRAY';
544 foreach my $taxname ( keys %$tax_exemption ) {
545 my $cust_main_exemption = new FS::cust_main_exemption {
546 'custnum' => $self->custnum,
547 'taxname' => $taxname,
548 'exempt_number' => $tax_exemption->{$taxname},
550 my $error = $cust_main_exemption->insert;
552 $dbh->rollback if $oldAutoCommit;
553 return "inserting cust_main_exemption (transaction rolled back): $error";
558 warn " ordering packages\n"
561 $error = $self->order_pkgs( $cust_pkgs,
563 'seconds_ref' => \$seconds,
564 'upbytes_ref' => \$upbytes,
565 'downbytes_ref' => \$downbytes,
566 'totalbytes_ref' => \$totalbytes,
569 $dbh->rollback if $oldAutoCommit;
574 $dbh->rollback if $oldAutoCommit;
575 return "No svc_acct record to apply pre-paid time";
577 if ( $upbytes || $downbytes || $totalbytes ) {
578 $dbh->rollback if $oldAutoCommit;
579 return "No svc_acct record to apply pre-paid data";
583 warn " inserting initial $payby payment of $amount\n"
585 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
587 $dbh->rollback if $oldAutoCommit;
588 return "inserting payment (transaction rolled back): $error";
592 unless ( $import || $skip_fuzzyfiles ) {
593 warn " queueing fuzzyfiles update\n"
595 $error = $self->queue_fuzzyfiles_update;
597 $dbh->rollback if $oldAutoCommit;
598 return "updating fuzzy search cache: $error";
602 # FS::geocode_Mixin::after_insert or something?
603 if ( $conf->config('tax_district_method') and !$import ) {
604 # if anything non-empty, try to look it up
605 my $queue = new FS::queue {
606 'job' => 'FS::geocode_Mixin::process_district_update',
607 'custnum' => $self->custnum,
609 my $error = $queue->insert( ref($self), $self->custnum );
611 $dbh->rollback if $oldAutoCommit;
612 return "queueing tax district update: $error";
617 warn " exporting\n" if $DEBUG > 1;
619 my $export_args = $options{'export_args'} || [];
622 map qsearch( 'part_export', {exportnum=>$_} ),
623 $conf->config('cust_main-exports'); #, $agentnum
625 foreach my $part_export ( @part_export ) {
626 my $error = $part_export->export_insert($self, @$export_args);
628 $dbh->rollback if $oldAutoCommit;
629 return "exporting to ". $part_export->exporttype.
630 " (transaction rolled back): $error";
634 #foreach my $depend_jobnum ( @$depend_jobnums ) {
635 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
637 # foreach my $jobnum ( @jobnums ) {
638 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
639 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
641 # my $error = $queue->depend_insert($depend_jobnum);
643 # $dbh->rollback if $oldAutoCommit;
644 # return "error queuing job dependancy: $error";
651 #if ( exists $options{'jobnums'} ) {
652 # push @{ $options{'jobnums'} }, @jobnums;
655 warn " insert complete; committing transaction\n"
658 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
663 use File::CounterFile;
664 sub auto_agent_custid {
667 my $format = $conf->config('cust_main-auto_agent_custid');
669 if ( $format eq '1YMMXXXXXXXX' ) {
671 my $counter = new File::CounterFile 'cust_main.agent_custid';
674 my $ym = 100000000000 + time2str('%y%m00000000', time);
675 if ( $ym > $counter->value ) {
676 $counter->{'value'} = $agent_custid = $ym;
677 $counter->{'updated'} = 1;
679 $agent_custid = $counter->inc;
685 die "Unknown cust_main-auto_agent_custid format: $format";
688 $self->agent_custid($agent_custid);
692 =item PACKAGE METHODS
694 Documentation on customer package methods has been moved to
695 L<FS::cust_main::Packages>.
697 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
699 Recharges this (existing) customer with the specified prepaid card (see
700 L<FS::prepay_credit>), specified either by I<identifier> or as an
701 FS::prepay_credit object. If there is an error, returns the error, otherwise
704 Optionally, five scalar references can be passed as well. They will have their
705 values filled in with the amount, number of seconds, and number of upload,
706 download, and total bytes applied by this prepaid card.
710 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
711 #the only place that uses these args
712 sub recharge_prepay {
713 my( $self, $prepay_credit, $amountref, $secondsref,
714 $upbytesref, $downbytesref, $totalbytesref ) = @_;
716 local $SIG{HUP} = 'IGNORE';
717 local $SIG{INT} = 'IGNORE';
718 local $SIG{QUIT} = 'IGNORE';
719 local $SIG{TERM} = 'IGNORE';
720 local $SIG{TSTP} = 'IGNORE';
721 local $SIG{PIPE} = 'IGNORE';
723 my $oldAutoCommit = $FS::UID::AutoCommit;
724 local $FS::UID::AutoCommit = 0;
727 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
729 my $error = $self->get_prepay( $prepay_credit,
730 'amount_ref' => \$amount,
731 'seconds_ref' => \$seconds,
732 'upbytes_ref' => \$upbytes,
733 'downbytes_ref' => \$downbytes,
734 'totalbytes_ref' => \$totalbytes,
736 || $self->increment_seconds($seconds)
737 || $self->increment_upbytes($upbytes)
738 || $self->increment_downbytes($downbytes)
739 || $self->increment_totalbytes($totalbytes)
740 || $self->insert_cust_pay_prepay( $amount,
742 ? $prepay_credit->identifier
747 $dbh->rollback if $oldAutoCommit;
751 if ( defined($amountref) ) { $$amountref = $amount; }
752 if ( defined($secondsref) ) { $$secondsref = $seconds; }
753 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
754 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
755 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
757 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
762 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
764 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
765 specified either by I<identifier> or as an FS::prepay_credit object.
767 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
768 incremented by the values of the prepaid card.
770 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
771 check or set this customer's I<agentnum>.
773 If there is an error, returns the error, otherwise returns false.
779 my( $self, $prepay_credit, %opt ) = @_;
781 local $SIG{HUP} = 'IGNORE';
782 local $SIG{INT} = 'IGNORE';
783 local $SIG{QUIT} = 'IGNORE';
784 local $SIG{TERM} = 'IGNORE';
785 local $SIG{TSTP} = 'IGNORE';
786 local $SIG{PIPE} = 'IGNORE';
788 my $oldAutoCommit = $FS::UID::AutoCommit;
789 local $FS::UID::AutoCommit = 0;
792 unless ( ref($prepay_credit) ) {
794 my $identifier = $prepay_credit;
796 $prepay_credit = qsearchs(
798 { 'identifier' => $identifier },
803 unless ( $prepay_credit ) {
804 $dbh->rollback if $oldAutoCommit;
805 return "Invalid prepaid card: ". $identifier;
810 if ( $prepay_credit->agentnum ) {
811 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
812 $dbh->rollback if $oldAutoCommit;
813 return "prepaid card not valid for agent ". $self->agentnum;
815 $self->agentnum($prepay_credit->agentnum);
818 my $error = $prepay_credit->delete;
820 $dbh->rollback if $oldAutoCommit;
821 return "removing prepay_credit (transaction rolled back): $error";
824 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
825 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
827 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
832 =item increment_upbytes SECONDS
834 Updates this customer's single or primary account (see L<FS::svc_acct>) by
835 the specified number of upbytes. If there is an error, returns the error,
836 otherwise returns false.
840 sub increment_upbytes {
841 _increment_column( shift, 'upbytes', @_);
844 =item increment_downbytes SECONDS
846 Updates this customer's single or primary account (see L<FS::svc_acct>) by
847 the specified number of downbytes. If there is an error, returns the error,
848 otherwise returns false.
852 sub increment_downbytes {
853 _increment_column( shift, 'downbytes', @_);
856 =item increment_totalbytes SECONDS
858 Updates this customer's single or primary account (see L<FS::svc_acct>) by
859 the specified number of totalbytes. If there is an error, returns the error,
860 otherwise returns false.
864 sub increment_totalbytes {
865 _increment_column( shift, 'totalbytes', @_);
868 =item increment_seconds SECONDS
870 Updates this customer's single or primary account (see L<FS::svc_acct>) by
871 the specified number of seconds. If there is an error, returns the error,
872 otherwise returns false.
876 sub increment_seconds {
877 _increment_column( shift, 'seconds', @_);
880 =item _increment_column AMOUNT
882 Updates this customer's single or primary account (see L<FS::svc_acct>) by
883 the specified number of seconds or bytes. If there is an error, returns
884 the error, otherwise returns false.
888 sub _increment_column {
889 my( $self, $column, $amount ) = @_;
890 warn "$me increment_column called: $column, $amount\n"
893 return '' unless $amount;
895 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
896 $self->ncancelled_pkgs;
899 return 'No packages with primary or single services found'.
900 ' to apply pre-paid time';
901 } elsif ( scalar(@cust_pkg) > 1 ) {
902 #maybe have a way to specify the package/account?
903 return 'Multiple packages found to apply pre-paid time';
906 my $cust_pkg = $cust_pkg[0];
907 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
911 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
914 return 'No account found to apply pre-paid time';
915 } elsif ( scalar(@cust_svc) > 1 ) {
916 return 'Multiple accounts found to apply pre-paid time';
919 my $svc_acct = $cust_svc[0]->svc_x;
920 warn " found service svcnum ". $svc_acct->pkgnum.
921 ' ('. $svc_acct->email. ")\n"
924 $column = "increment_$column";
925 $svc_acct->$column($amount);
929 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
931 Inserts a prepayment in the specified amount for this customer. An optional
932 second argument can specify the prepayment identifier for tracking purposes.
933 If there is an error, returns the error, otherwise returns false.
937 sub insert_cust_pay_prepay {
938 shift->insert_cust_pay('PREP', @_);
941 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
943 Inserts a cash payment in the specified amount for this customer. An optional
944 second argument can specify the payment identifier for tracking purposes.
945 If there is an error, returns the error, otherwise returns false.
949 sub insert_cust_pay_cash {
950 shift->insert_cust_pay('CASH', @_);
953 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
955 Inserts a Western Union payment in the specified amount for this customer. An
956 optional second argument can specify the prepayment identifier for tracking
957 purposes. If there is an error, returns the error, otherwise returns false.
961 sub insert_cust_pay_west {
962 shift->insert_cust_pay('WEST', @_);
965 sub insert_cust_pay {
966 my( $self, $payby, $amount ) = splice(@_, 0, 3);
967 my $payinfo = scalar(@_) ? shift : '';
969 my $cust_pay = new FS::cust_pay {
970 'custnum' => $self->custnum,
971 'paid' => sprintf('%.2f', $amount),
972 #'_date' => #date the prepaid card was purchased???
974 'payinfo' => $payinfo,
980 =item delete [ OPTION => VALUE ... ]
982 This deletes the customer. If there is an error, returns the error, otherwise
985 This will completely remove all traces of the customer record. This is not
986 what you want when a customer cancels service; for that, cancel all of the
987 customer's packages (see L</cancel>).
989 If the customer has any uncancelled packages, you need to pass a new (valid)
990 customer number for those packages to be transferred to, as the "new_customer"
991 option. Cancelled packages will be deleted. Did I mention that this is NOT
992 what you want when a customer cancels service and that you really should be
993 looking at L<FS::cust_pkg/cancel>?
995 You can't delete a customer with invoices (see L<FS::cust_bill>),
996 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
997 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
998 set the "delete_financials" option to a true value.
1003 my( $self, %opt ) = @_;
1005 local $SIG{HUP} = 'IGNORE';
1006 local $SIG{INT} = 'IGNORE';
1007 local $SIG{QUIT} = 'IGNORE';
1008 local $SIG{TERM} = 'IGNORE';
1009 local $SIG{TSTP} = 'IGNORE';
1010 local $SIG{PIPE} = 'IGNORE';
1012 my $oldAutoCommit = $FS::UID::AutoCommit;
1013 local $FS::UID::AutoCommit = 0;
1016 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1017 $dbh->rollback if $oldAutoCommit;
1018 return "Can't delete a master agent customer";
1021 #use FS::access_user
1022 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1023 $dbh->rollback if $oldAutoCommit;
1024 return "Can't delete a master employee customer";
1027 tie my %financial_tables, 'Tie::IxHash',
1028 'cust_bill' => 'invoices',
1029 'cust_statement' => 'statements',
1030 'cust_credit' => 'credits',
1031 'cust_pay' => 'payments',
1032 'cust_refund' => 'refunds',
1035 foreach my $table ( keys %financial_tables ) {
1037 my @records = $self->$table();
1039 if ( @records && ! $opt{'delete_financials'} ) {
1040 $dbh->rollback if $oldAutoCommit;
1041 return "Can't delete a customer with ". $financial_tables{$table};
1044 foreach my $record ( @records ) {
1045 my $error = $record->delete;
1047 $dbh->rollback if $oldAutoCommit;
1048 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1054 my @cust_pkg = $self->ncancelled_pkgs;
1056 my $new_custnum = $opt{'new_custnum'};
1057 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1058 $dbh->rollback if $oldAutoCommit;
1059 return "Invalid new customer number: $new_custnum";
1061 foreach my $cust_pkg ( @cust_pkg ) {
1062 my %hash = $cust_pkg->hash;
1063 $hash{'custnum'} = $new_custnum;
1064 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1065 my $error = $new_cust_pkg->replace($cust_pkg,
1066 options => { $cust_pkg->options },
1069 $dbh->rollback if $oldAutoCommit;
1074 my @cancelled_cust_pkg = $self->all_pkgs;
1075 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1076 my $error = $cust_pkg->delete;
1078 $dbh->rollback if $oldAutoCommit;
1083 #cust_tax_adjustment in financials?
1084 #cust_pay_pending? ouch
1086 foreach my $table (qw(
1087 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1088 cust_location cust_main_note cust_tax_adjustment
1089 cust_pay_void cust_pay_batch queue cust_tax_exempt
1091 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1092 my $error = $record->delete;
1094 $dbh->rollback if $oldAutoCommit;
1100 my $sth = $dbh->prepare(
1101 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1103 my $errstr = $dbh->errstr;
1104 $dbh->rollback if $oldAutoCommit;
1107 $sth->execute($self->custnum) or do {
1108 my $errstr = $sth->errstr;
1109 $dbh->rollback if $oldAutoCommit;
1115 my $ticket_dbh = '';
1116 if ($conf->config('ticket_system') eq 'RT_Internal') {
1118 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1119 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1120 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1121 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1124 if ( $ticket_dbh ) {
1126 my $ticket_sth = $ticket_dbh->prepare(
1127 'DELETE FROM Links WHERE Target = ?'
1129 my $errstr = $ticket_dbh->errstr;
1130 $dbh->rollback if $oldAutoCommit;
1133 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1135 my $errstr = $ticket_sth->errstr;
1136 $dbh->rollback if $oldAutoCommit;
1140 #check and see if the customer is the only link on the ticket, and
1141 #if so, set the ticket to deleted status in RT?
1142 #maybe someday, for now this will at least fix tickets not displaying
1146 #delete the customer record
1148 my $error = $self->SUPER::delete;
1150 $dbh->rollback if $oldAutoCommit;
1154 # cust_main exports!
1156 #my $export_args = $options{'export_args'} || [];
1159 map qsearch( 'part_export', {exportnum=>$_} ),
1160 $conf->config('cust_main-exports'); #, $agentnum
1162 foreach my $part_export ( @part_export ) {
1163 my $error = $part_export->export_delete( $self ); #, @$export_args);
1165 $dbh->rollback if $oldAutoCommit;
1166 return "exporting to ". $part_export->exporttype.
1167 " (transaction rolled back): $error";
1171 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1176 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1178 This merges this customer into the provided new custnum, and then deletes the
1179 customer. If there is an error, returns the error, otherwise returns false.
1181 The source customer's name, company name, phone numbers, agent,
1182 referring customer, customer class, advertising source, order taker, and
1183 billing information (except balance) are discarded.
1185 All packages are moved to the target customer. Packages with package locations
1186 are preserved. Packages without package locations are moved to a new package
1187 location with the source customer's service/shipping address.
1189 All invoices, statements, payments, credits and refunds are moved to the target
1190 customer. The source customer's balance is added to the target customer.
1192 All notes, attachments, tickets and customer tags are moved to the target
1195 Change history is not currently moved.
1200 my( $self, $new_custnum, %opt ) = @_;
1202 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1204 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1205 or return "Invalid new customer number: $new_custnum";
1207 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1208 if $self->agentnum != $new_cust_main->agentnum
1209 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1211 local $SIG{HUP} = 'IGNORE';
1212 local $SIG{INT} = 'IGNORE';
1213 local $SIG{QUIT} = 'IGNORE';
1214 local $SIG{TERM} = 'IGNORE';
1215 local $SIG{TSTP} = 'IGNORE';
1216 local $SIG{PIPE} = 'IGNORE';
1218 my $oldAutoCommit = $FS::UID::AutoCommit;
1219 local $FS::UID::AutoCommit = 0;
1222 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1223 $dbh->rollback if $oldAutoCommit;
1224 return "Can't merge a master agent customer";
1227 #use FS::access_user
1228 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1229 $dbh->rollback if $oldAutoCommit;
1230 return "Can't merge a master employee customer";
1233 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1234 'status' => { op=>'!=', value=>'done' },
1238 $dbh->rollback if $oldAutoCommit;
1239 return "Can't merge a customer with pending payments";
1242 tie my %financial_tables, 'Tie::IxHash',
1243 'cust_bill' => 'invoices',
1244 'cust_bill_void' => 'voided invoices',
1245 'cust_statement' => 'statements',
1246 'cust_credit' => 'credits',
1247 'cust_pay' => 'payments',
1248 'cust_pay_void' => 'voided payments',
1249 'cust_refund' => 'refunds',
1252 foreach my $table ( keys %financial_tables ) {
1254 my @records = $self->$table();
1256 foreach my $record ( @records ) {
1257 $record->custnum($new_custnum);
1258 my $error = $record->replace;
1260 $dbh->rollback if $oldAutoCommit;
1261 return "Error merging ". $financial_tables{$table}. ": $error\n";
1267 my $name = $self->ship_name; #?
1269 my $locationnum = '';
1270 foreach my $cust_pkg ( $self->all_pkgs ) {
1271 $cust_pkg->custnum($new_custnum);
1273 unless ( $cust_pkg->locationnum ) {
1274 unless ( $locationnum ) {
1275 my $cust_location = new FS::cust_location {
1276 $self->location_hash,
1277 'custnum' => $new_custnum,
1279 my $error = $cust_location->insert;
1281 $dbh->rollback if $oldAutoCommit;
1284 $locationnum = $cust_location->locationnum;
1286 $cust_pkg->locationnum($locationnum);
1289 my $error = $cust_pkg->replace;
1291 $dbh->rollback if $oldAutoCommit;
1295 # add customer (ship) name to svc_phone.phone_name if blank
1296 my @cust_svc = $cust_pkg->cust_svc;
1297 foreach my $cust_svc (@cust_svc) {
1298 my($label, $value, $svcdb) = $cust_svc->label;
1299 next unless $svcdb eq 'svc_phone';
1300 my $svc_phone = $cust_svc->svc_x;
1301 next if $svc_phone->phone_name;
1302 $svc_phone->phone_name($name);
1303 my $error = $svc_phone->replace;
1305 $dbh->rollback if $oldAutoCommit;
1313 # cust_tax_exempt (texas tax exemptions)
1314 # cust_recon (some sort of not-well understood thing for OnPac)
1316 #these are moved over
1317 foreach my $table (qw(
1318 cust_tag cust_location contact cust_attachment cust_main_note
1319 cust_tax_adjustment cust_pay_batch queue
1321 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1322 $record->custnum($new_custnum);
1323 my $error = $record->replace;
1325 $dbh->rollback if $oldAutoCommit;
1331 #these aren't preserved
1332 foreach my $table (qw(
1333 cust_main_exemption cust_main_invoice
1335 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1336 my $error = $record->delete;
1338 $dbh->rollback if $oldAutoCommit;
1345 my $sth = $dbh->prepare(
1346 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1348 my $errstr = $dbh->errstr;
1349 $dbh->rollback if $oldAutoCommit;
1352 $sth->execute($new_custnum, $self->custnum) or do {
1353 my $errstr = $sth->errstr;
1354 $dbh->rollback if $oldAutoCommit;
1360 my $ticket_dbh = '';
1361 if ($conf->config('ticket_system') eq 'RT_Internal') {
1363 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1364 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1365 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1366 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1369 if ( $ticket_dbh ) {
1371 my $ticket_sth = $ticket_dbh->prepare(
1372 'UPDATE Links SET Target = ? WHERE Target = ?'
1374 my $errstr = $ticket_dbh->errstr;
1375 $dbh->rollback if $oldAutoCommit;
1378 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1379 'freeside://freeside/cust_main/'.$self->custnum)
1381 my $errstr = $ticket_sth->errstr;
1382 $dbh->rollback if $oldAutoCommit;
1388 #delete the customer record
1390 my $error = $self->delete;
1392 $dbh->rollback if $oldAutoCommit;
1396 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1401 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1403 Replaces the OLD_RECORD with this one in the database. If there is an error,
1404 returns the error, otherwise returns false.
1406 To change the customer's address, set the pseudo-fields C<bill_location> and
1407 C<ship_location>. The address will still only change if at least one of the
1408 address fields differs from the existing values.
1410 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1411 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1412 expected and rollback the entire transaction; it is not necessary to call
1413 check_invoicing_list first. Here's an example:
1415 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1417 Currently available options are: I<tax_exemption>.
1419 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1420 of tax names and exemption numbers. FS::cust_main_exemption records will be
1421 deleted and inserted as appropriate.
1428 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1430 : $self->replace_old;
1434 warn "$me replace called\n"
1437 my $curuser = $FS::CurrentUser::CurrentUser;
1438 if ( $self->payby eq 'COMP'
1439 && $self->payby ne $old->payby
1440 && ! $curuser->access_right('Complimentary customer')
1443 return "You are not permitted to create complimentary accounts.";
1446 local($ignore_expired_card) = 1
1447 if $old->payby =~ /^(CARD|DCRD)$/
1448 && $self->payby =~ /^(CARD|DCRD)$/
1449 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1451 local($ignore_banned_card) = 1
1452 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1453 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1454 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1456 return "Invoicing locale is required"
1459 && $conf->exists('cust_main-require_locale');
1461 local $SIG{HUP} = 'IGNORE';
1462 local $SIG{INT} = 'IGNORE';
1463 local $SIG{QUIT} = 'IGNORE';
1464 local $SIG{TERM} = 'IGNORE';
1465 local $SIG{TSTP} = 'IGNORE';
1466 local $SIG{PIPE} = 'IGNORE';
1468 my $oldAutoCommit = $FS::UID::AutoCommit;
1469 local $FS::UID::AutoCommit = 0;
1472 for my $l (qw(bill_location ship_location)) {
1473 my $old_loc = $old->$l;
1474 my $new_loc = $self->$l;
1476 # find the existing location if there is one
1477 $new_loc->set('custnum' => $self->custnum);
1478 my $error = $new_loc->find_or_insert;
1480 $dbh->rollback if $oldAutoCommit;
1483 $self->set($l.'num', $new_loc->locationnum);
1486 # replace the customer record
1487 my $error = $self->SUPER::replace($old);
1490 $dbh->rollback if $oldAutoCommit;
1494 # now move packages to the new service location
1495 $self->set('ship_location', ''); #flush cache
1496 if ( $old->ship_locationnum and # should only be null during upgrade...
1497 $old->ship_locationnum != $self->ship_locationnum ) {
1498 $error = $old->ship_location->move_to($self->ship_location);
1500 $dbh->rollback if $oldAutoCommit;
1504 # don't move packages based on the billing location, but
1505 # disable it if it's no longer in use
1506 if ( $old->bill_locationnum and
1507 $old->bill_locationnum != $self->bill_locationnum ) {
1508 $error = $old->bill_location->disable_if_unused;
1510 $dbh->rollback if $oldAutoCommit;
1515 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1516 my $invoicing_list = shift @param;
1517 $error = $self->check_invoicing_list( $invoicing_list );
1519 $dbh->rollback if $oldAutoCommit;
1522 $self->invoicing_list( $invoicing_list );
1525 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1527 #this could be more efficient than deleting and re-inserting, if it matters
1528 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1529 my $error = $cust_tag->delete;
1531 $dbh->rollback if $oldAutoCommit;
1535 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1536 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1537 'custnum' => $self->custnum };
1538 my $error = $cust_tag->insert;
1540 $dbh->rollback if $oldAutoCommit;
1547 my %options = @param;
1549 my $tax_exemption = delete $options{'tax_exemption'};
1550 if ( $tax_exemption ) {
1552 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1553 if ref($tax_exemption) eq 'ARRAY';
1555 my %cust_main_exemption =
1556 map { $_->taxname => $_ }
1557 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1559 foreach my $taxname ( keys %$tax_exemption ) {
1561 if ( $cust_main_exemption{$taxname} &&
1562 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1565 delete $cust_main_exemption{$taxname};
1569 my $cust_main_exemption = new FS::cust_main_exemption {
1570 'custnum' => $self->custnum,
1571 'taxname' => $taxname,
1572 'exempt_number' => $tax_exemption->{$taxname},
1574 my $error = $cust_main_exemption->insert;
1576 $dbh->rollback if $oldAutoCommit;
1577 return "inserting cust_main_exemption (transaction rolled back): $error";
1581 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1582 my $error = $cust_main_exemption->delete;
1584 $dbh->rollback if $oldAutoCommit;
1585 return "deleting cust_main_exemption (transaction rolled back): $error";
1591 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1592 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1593 && $self->get('payinfo') !~ /^99\d{14}$/
1595 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1600 # card/check/lec info has changed, want to retry realtime_ invoice events
1601 my $error = $self->retry_realtime;
1603 $dbh->rollback if $oldAutoCommit;
1608 unless ( $import || $skip_fuzzyfiles ) {
1609 $error = $self->queue_fuzzyfiles_update;
1611 $dbh->rollback if $oldAutoCommit;
1612 return "updating fuzzy search cache: $error";
1616 # tax district update in cust_location
1618 # cust_main exports!
1620 my $export_args = $options{'export_args'} || [];
1623 map qsearch( 'part_export', {exportnum=>$_} ),
1624 $conf->config('cust_main-exports'); #, $agentnum
1626 foreach my $part_export ( @part_export ) {
1627 my $error = $part_export->export_replace( $self, $old, @$export_args);
1629 $dbh->rollback if $oldAutoCommit;
1630 return "exporting to ". $part_export->exporttype.
1631 " (transaction rolled back): $error";
1635 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1640 =item queue_fuzzyfiles_update
1642 Used by insert & replace to update the fuzzy search cache
1646 use FS::cust_main::Search;
1647 sub queue_fuzzyfiles_update {
1650 local $SIG{HUP} = 'IGNORE';
1651 local $SIG{INT} = 'IGNORE';
1652 local $SIG{QUIT} = 'IGNORE';
1653 local $SIG{TERM} = 'IGNORE';
1654 local $SIG{TSTP} = 'IGNORE';
1655 local $SIG{PIPE} = 'IGNORE';
1657 my $oldAutoCommit = $FS::UID::AutoCommit;
1658 local $FS::UID::AutoCommit = 0;
1661 my @locations = $self->bill_location;
1662 push @locations, $self->ship_location if $self->has_ship_address;
1663 foreach my $location (@locations) {
1664 my $queue = new FS::queue {
1665 'job' => 'FS::cust_main::Search::append_fuzzyfiles'
1667 my @args = map $location->get($_), @FS::cust_main::Search::fuzzyfields;
1668 my $error = $queue->insert( @args );
1670 $dbh->rollback if $oldAutoCommit;
1671 return "queueing job (transaction rolled back): $error";
1675 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1682 Checks all fields to make sure this is a valid customer record. If there is
1683 an error, returns the error, otherwise returns false. Called by the insert
1684 and replace methods.
1691 warn "$me check BEFORE: \n". $self->_dump
1695 $self->ut_numbern('custnum')
1696 || $self->ut_number('agentnum')
1697 || $self->ut_textn('agent_custid')
1698 || $self->ut_number('refnum')
1699 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1700 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1701 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1702 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1703 || $self->ut_textn('custbatch')
1704 || $self->ut_name('last')
1705 || $self->ut_name('first')
1706 || $self->ut_snumbern('signupdate')
1707 || $self->ut_snumbern('birthdate')
1708 || $self->ut_snumbern('spouse_birthdate')
1709 || $self->ut_snumbern('anniversary_date')
1710 || $self->ut_textn('company')
1711 || $self->ut_anything('comments')
1712 || $self->ut_numbern('referral_custnum')
1713 || $self->ut_textn('stateid')
1714 || $self->ut_textn('stateid_state')
1715 || $self->ut_textn('invoice_terms')
1716 || $self->ut_floatn('cdr_termination_percentage')
1717 || $self->ut_floatn('credit_limit')
1718 || $self->ut_numbern('billday')
1719 || $self->ut_numbern('prorate_day')
1720 || $self->ut_flag('edit_subject')
1721 || $self->ut_flag('calling_list_exempt')
1722 || $self->ut_flag('invoice_noemail')
1723 || $self->ut_flag('message_noemail')
1724 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1725 || $self->ut_currencyn('currency')
1728 my $company = $self->company;
1729 $company =~ s/^\s+//;
1730 $company =~ s/\s+$//;
1731 $company =~ s/\s+/ /g;
1732 $self->company($company);
1734 #barf. need message catalogs. i18n. etc.
1735 $error .= "Please select an advertising source."
1736 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1737 return $error if $error;
1739 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1740 or return "Unknown agent";
1742 if ( $self->currency ) {
1743 my $agent_currency = qsearchs( 'agent_currency', {
1744 'agentnum' => $agent->agentnum,
1745 'currency' => $self->currency,
1747 or return "Agent ". $agent->agent.
1748 " not permitted to offer ". $self->currency. " invoicing";
1751 return "Unknown refnum"
1752 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1754 return "Unknown referring custnum: ". $self->referral_custnum
1755 unless ! $self->referral_custnum
1756 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1758 if ( $self->ss eq '' ) {
1763 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1764 or return "Illegal social security number: ". $self->ss;
1765 $self->ss("$1-$2-$3");
1768 # cust_main_county verification now handled by cust_location check
1771 $self->ut_phonen('daytime', $self->country)
1772 || $self->ut_phonen('night', $self->country)
1773 || $self->ut_phonen('fax', $self->country)
1774 || $self->ut_phonen('mobile', $self->country)
1776 return $error if $error;
1778 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1780 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1783 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1785 : FS::Msgcat::_gettext('daytime');
1786 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1788 : FS::Msgcat::_gettext('night');
1790 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1792 : FS::Msgcat::_gettext('mobile');
1794 return "$daytime_label, $night_label or $mobile_label is required"
1798 ### start of stuff moved to cust_payby
1799 # then mostly kept here to support upgrades (can remove in 5.x)
1800 # but modified to allow everything to be empty
1802 if ( $self->payby ) {
1803 FS::payby->can_payby($self->table, $self->payby)
1804 or return "Illegal payby: ". $self->payby;
1809 $error = $self->ut_numbern('paystart_month')
1810 || $self->ut_numbern('paystart_year')
1811 || $self->ut_numbern('payissue')
1812 || $self->ut_textn('paytype')
1814 return $error if $error;
1816 if ( $self->payip eq '' ) {
1819 $error = $self->ut_ip('payip');
1820 return $error if $error;
1823 # If it is encrypted and the private key is not availaible then we can't
1824 # check the credit card.
1825 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1827 # Need some kind of global flag to accept invalid cards, for testing
1829 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1831 my $payinfo = $self->payinfo;
1832 $payinfo =~ s/\D//g;
1833 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1834 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1836 $self->payinfo($payinfo);
1838 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1840 return gettext('unknown_card_type')
1841 if $self->payinfo !~ /^99\d{14}$/ #token
1842 && cardtype($self->payinfo) eq "Unknown";
1844 unless ( $ignore_banned_card ) {
1845 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1847 if ( $ban->bantype eq 'warn' ) {
1848 #or others depending on value of $ban->reason ?
1849 return '_duplicate_card'.
1850 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1851 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1852 ' (ban# '. $ban->bannum. ')'
1853 unless $self->override_ban_warn;
1855 return 'Banned credit card: banned on '.
1856 time2str('%a %h %o at %r', $ban->_date).
1857 ' by '. $ban->otaker.
1858 ' (ban# '. $ban->bannum. ')';
1863 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1864 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1865 $self->paycvv =~ /^(\d{4})$/
1866 or return "CVV2 (CID) for American Express cards is four digits.";
1869 $self->paycvv =~ /^(\d{3})$/
1870 or return "CVV2 (CVC2/CID) is three digits.";
1877 my $cardtype = cardtype($payinfo);
1878 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1880 return "Start date or issue number is required for $cardtype cards"
1881 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1883 return "Start month must be between 1 and 12"
1884 if $self->paystart_month
1885 and $self->paystart_month < 1 || $self->paystart_month > 12;
1887 return "Start year must be 1990 or later"
1888 if $self->paystart_year
1889 and $self->paystart_year < 1990;
1891 return "Issue number must be beween 1 and 99"
1893 and $self->payissue < 1 || $self->payissue > 99;
1896 $self->paystart_month('');
1897 $self->paystart_year('');
1898 $self->payissue('');
1901 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1903 my $payinfo = $self->payinfo;
1904 $payinfo =~ s/[^\d\@\.]//g;
1905 if ( $conf->config('echeck-country') eq 'CA' ) {
1906 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1907 or return 'invalid echeck account@branch.bank';
1908 $payinfo = "$1\@$2.$3";
1909 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1910 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1911 $payinfo = "$1\@$2";
1913 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1914 $payinfo = "$1\@$2";
1916 $self->payinfo($payinfo);
1919 unless ( $ignore_banned_card ) {
1920 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1922 if ( $ban->bantype eq 'warn' ) {
1923 #or others depending on value of $ban->reason ?
1924 return '_duplicate_ach' unless $self->override_ban_warn;
1926 return 'Banned ACH account: banned on '.
1927 time2str('%a %h %o at %r', $ban->_date).
1928 ' by '. $ban->otaker.
1929 ' (ban# '. $ban->bannum. ')';
1934 } elsif ( $self->payby eq 'LECB' ) {
1936 my $payinfo = $self->payinfo;
1937 $payinfo =~ s/\D//g;
1938 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1940 $self->payinfo($payinfo);
1943 } elsif ( $self->payby eq 'BILL' ) {
1945 $error = $self->ut_textn('payinfo');
1946 return "Illegal P.O. number: ". $self->payinfo if $error;
1949 } elsif ( $self->payby eq 'COMP' ) {
1951 my $curuser = $FS::CurrentUser::CurrentUser;
1952 if ( ! $self->custnum
1953 && ! $curuser->access_right('Complimentary customer')
1956 return "You are not permitted to create complimentary accounts."
1959 $error = $self->ut_textn('payinfo');
1960 return "Illegal comp account issuer: ". $self->payinfo if $error;
1963 } elsif ( $self->payby eq 'PREPAY' ) {
1965 my $payinfo = $self->payinfo;
1966 $payinfo =~ s/\W//g; #anything else would just confuse things
1967 $self->payinfo($payinfo);
1968 $error = $self->ut_alpha('payinfo');
1969 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1970 return "Unknown prepayment identifier"
1971 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1976 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1977 return "Expiration date required"
1978 # shouldn't payinfo_check do this?
1979 unless ! $self->payby
1980 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
1984 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1985 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1986 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1987 ( $m, $y ) = ( $2, "19$1" );
1988 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1989 ( $m, $y ) = ( $3, "20$2" );
1991 return "Illegal expiration date: ". $self->paydate;
1993 $m = sprintf('%02d',$m);
1994 $self->paydate("$y-$m-01");
1995 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1996 return gettext('expired_card')
1998 && !$ignore_expired_card
1999 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2002 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2003 ( ! $conf->exists('require_cardname')
2004 || $self->payby !~ /^(CARD|DCRD)$/ )
2006 $self->payname( $self->first. " ". $self->getfield('last') );
2008 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2009 or return gettext('illegal_name'). " payname: ". $self->payname;
2013 ### end of stuff moved to cust_payby
2015 return "Please select an invoicing locale"
2018 && $conf->exists('cust_main-require_locale');
2020 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2021 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2025 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2027 warn "$me check AFTER: \n". $self->_dump
2030 $self->SUPER::check;
2035 Returns a list of fields which have ship_ duplicates.
2040 qw( last first company
2041 address1 address2 city county state zip country
2043 daytime night fax mobile
2047 =item has_ship_address
2049 Returns true if this customer record has a separate shipping address.
2053 sub has_ship_address {
2055 $self->bill_locationnum != $self->ship_locationnum;
2060 Returns a list of key/value pairs, with the following keys: address1,
2061 adddress2, city, county, state, zip, country, district, and geocode. The
2062 shipping address is used if present.
2068 $self->ship_location->location_hash;
2073 Returns all locations (see L<FS::cust_location>) for this customer.
2079 qsearch('cust_location', { 'custnum' => $self->custnum,
2080 'prospectnum' => '' } );
2085 Returns all contacts (see L<FS::contact>) for this customer.
2089 #already used :/ sub contact {
2092 qsearch('contact', { 'custnum' => $self->custnum } );
2097 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2098 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2099 on success or a list of errors.
2105 grep { $_->unsuspend } $self->suspended_pkgs;
2110 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2112 Returns a list: an empty list on success or a list of errors.
2118 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2121 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2123 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2124 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2125 of a list of pkgparts; the hashref has the following keys:
2129 =item pkgparts - listref of pkgparts
2131 =item (other options are passed to the suspend method)
2136 Returns a list: an empty list on success or a list of errors.
2140 sub suspend_if_pkgpart {
2142 my (@pkgparts, %opt);
2143 if (ref($_[0]) eq 'HASH'){
2144 @pkgparts = @{$_[0]{pkgparts}};
2149 grep { $_->suspend(%opt) }
2150 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2151 $self->unsuspended_pkgs;
2154 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2156 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2157 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2158 instead of a list of pkgparts; the hashref has the following keys:
2162 =item pkgparts - listref of pkgparts
2164 =item (other options are passed to the suspend method)
2168 Returns a list: an empty list on success or a list of errors.
2172 sub suspend_unless_pkgpart {
2174 my (@pkgparts, %opt);
2175 if (ref($_[0]) eq 'HASH'){
2176 @pkgparts = @{$_[0]{pkgparts}};
2181 grep { $_->suspend(%opt) }
2182 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2183 $self->unsuspended_pkgs;
2186 =item cancel [ OPTION => VALUE ... ]
2188 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2190 Available options are:
2194 =item quiet - can be set true to supress email cancellation notices.
2196 =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.
2198 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2200 =item nobill - can be set true to skip billing if it might otherwise be done.
2204 Always returns a list: an empty list on success or a list of errors.
2208 # nb that dates are not specified as valid options to this method
2211 my( $self, %opt ) = @_;
2213 warn "$me cancel called on customer ". $self->custnum. " with options ".
2214 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2217 return ( 'access denied' )
2218 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2220 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2222 #should try decryption (we might have the private key)
2223 # and if not maybe queue a job for the server that does?
2224 return ( "Can't (yet) ban encrypted credit cards" )
2225 if $self->is_encrypted($self->payinfo);
2227 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2228 my $error = $ban->insert;
2229 return ( $error ) if $error;
2233 my @pkgs = $self->ncancelled_pkgs;
2235 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2237 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2238 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2242 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2243 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2246 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2249 sub _banned_pay_hashref {
2260 'payby' => $payby2ban{$self->payby},
2261 'payinfo' => $self->payinfo,
2262 #don't ever *search* on reason! #'reason' =>
2266 sub _new_banned_pay_hashref {
2268 my $hr = $self->_banned_pay_hashref;
2269 $hr->{payinfo} = md5_base64($hr->{payinfo});
2275 Returns all notes (see L<FS::cust_main_note>) for this customer.
2280 my($self,$orderby_classnum) = (shift,shift);
2281 my $orderby = "_DATE DESC";
2282 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2283 qsearch( 'cust_main_note',
2284 { 'custnum' => $self->custnum },
2286 "ORDER BY $orderby",
2292 Returns the agent (see L<FS::agent>) for this customer.
2298 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2303 Returns the agent name (see L<FS::agent>) for this customer.
2309 $self->agent->agent;
2314 Returns any tags associated with this customer, as FS::cust_tag objects,
2315 or an empty list if there are no tags.
2321 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2326 Returns any tags associated with this customer, as FS::part_tag objects,
2327 or an empty list if there are no tags.
2333 map $_->part_tag, $self->cust_tag;
2339 Returns the customer class, as an FS::cust_class object, or the empty string
2340 if there is no customer class.
2346 if ( $self->classnum ) {
2347 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2355 Returns the customer category name, or the empty string if there is no customer
2362 my $cust_class = $self->cust_class;
2364 ? $cust_class->categoryname
2370 Returns the customer class name, or the empty string if there is no customer
2377 my $cust_class = $self->cust_class;
2379 ? $cust_class->classname
2383 =item BILLING METHODS
2385 Documentation on billing methods has been moved to
2386 L<FS::cust_main::Billing>.
2388 =item REALTIME BILLING METHODS
2390 Documentation on realtime billing methods has been moved to
2391 L<FS::cust_main::Billing_Realtime>.
2395 Removes the I<paycvv> field from the database directly.
2397 If there is an error, returns the error, otherwise returns false.
2403 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2404 or return dbh->errstr;
2405 $sth->execute($self->custnum)
2406 or return $sth->errstr;
2411 =item batch_card OPTION => VALUE...
2413 Adds a payment for this invoice to the pending credit card batch (see
2414 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2415 runs the payment using a realtime gateway.
2417 Options may include:
2419 B<amount>: the amount to be paid; defaults to the customer's balance minus
2420 any payments in transit.
2422 B<payby>: the payment method; defaults to cust_main.payby
2424 B<realtime>: runs this as a realtime payment instead of adding it to a
2427 B<invnum>: sets cust_pay_batch.invnum.
2429 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2430 the billing address for the payment; defaults to the customer's billing
2433 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2434 date, and name; defaults to those fields in cust_main.
2439 my ($self, %options) = @_;
2442 if (exists($options{amount})) {
2443 $amount = $options{amount};
2445 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2447 return '' unless $amount > 0;
2449 my $invnum = delete $options{invnum};
2450 my $payby = $options{payby} || $self->payby; #still dubious
2452 if ($options{'realtime'}) {
2453 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2459 my $oldAutoCommit = $FS::UID::AutoCommit;
2460 local $FS::UID::AutoCommit = 0;
2463 #this needs to handle mysql as well as Pg, like svc_acct.pm
2464 #(make it into a common function if folks need to do batching with mysql)
2465 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2466 or return "Cannot lock pay_batch: " . $dbh->errstr;
2470 'payby' => FS::payby->payby2payment($payby),
2472 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2474 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2476 unless ( $pay_batch ) {
2477 $pay_batch = new FS::pay_batch \%pay_batch;
2478 my $error = $pay_batch->insert;
2480 $dbh->rollback if $oldAutoCommit;
2481 die "error creating new batch: $error\n";
2485 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2486 'batchnum' => $pay_batch->batchnum,
2487 'custnum' => $self->custnum,
2490 foreach (qw( address1 address2 city state zip country latitude longitude
2491 payby payinfo paydate payname ))
2493 $options{$_} = '' unless exists($options{$_});
2496 my $loc = $self->bill_location;
2498 my $cust_pay_batch = new FS::cust_pay_batch ( {
2499 'batchnum' => $pay_batch->batchnum,
2500 'invnum' => $invnum || 0, # is there a better value?
2501 # this field should be
2503 # cust_bill_pay_batch now
2504 'custnum' => $self->custnum,
2505 'last' => $self->getfield('last'),
2506 'first' => $self->getfield('first'),
2507 'address1' => $options{address1} || $loc->address1,
2508 'address2' => $options{address2} || $loc->address2,
2509 'city' => $options{city} || $loc->city,
2510 'state' => $options{state} || $loc->state,
2511 'zip' => $options{zip} || $loc->zip,
2512 'country' => $options{country} || $loc->country,
2513 'payby' => $options{payby} || $self->payby,
2514 'payinfo' => $options{payinfo} || $self->payinfo,
2515 'exp' => $options{paydate} || $self->paydate,
2516 'payname' => $options{payname} || $self->payname,
2517 'amount' => $amount, # consolidating
2520 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2521 if $old_cust_pay_batch;
2524 if ($old_cust_pay_batch) {
2525 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2527 $error = $cust_pay_batch->insert;
2531 $dbh->rollback if $oldAutoCommit;
2535 my $unapplied = $self->total_unapplied_credits
2536 + $self->total_unapplied_payments
2537 + $self->in_transit_payments;
2538 foreach my $cust_bill ($self->open_cust_bill) {
2539 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2540 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2541 'invnum' => $cust_bill->invnum,
2542 'paybatchnum' => $cust_pay_batch->paybatchnum,
2543 'amount' => $cust_bill->owed,
2546 if ($unapplied >= $cust_bill_pay_batch->amount){
2547 $unapplied -= $cust_bill_pay_batch->amount;
2550 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2551 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2553 $error = $cust_bill_pay_batch->insert;
2555 $dbh->rollback if $oldAutoCommit;
2560 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2566 Returns the total owed for this customer on all invoices
2567 (see L<FS::cust_bill/owed>).
2573 $self->total_owed_date(2145859200); #12/31/2037
2576 =item total_owed_date TIME
2578 Returns the total owed for this customer on all invoices with date earlier than
2579 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2580 see L<Time::Local> and L<Date::Parse> for conversion functions.
2584 sub total_owed_date {
2588 my $custnum = $self->custnum;
2590 my $owed_sql = FS::cust_bill->owed_sql;
2593 SELECT SUM($owed_sql) FROM cust_bill
2594 WHERE custnum = $custnum
2598 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2602 =item total_owed_pkgnum PKGNUM
2604 Returns the total owed on all invoices for this customer's specific package
2605 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2609 sub total_owed_pkgnum {
2610 my( $self, $pkgnum ) = @_;
2611 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2614 =item total_owed_date_pkgnum TIME PKGNUM
2616 Returns the total owed for this customer's specific package when using
2617 experimental package balances on all invoices with date earlier than
2618 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2619 see L<Time::Local> and L<Date::Parse> for conversion functions.
2623 sub total_owed_date_pkgnum {
2624 my( $self, $time, $pkgnum ) = @_;
2627 foreach my $cust_bill (
2628 grep { $_->_date <= $time }
2629 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2631 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2633 sprintf( "%.2f", $total_bill );
2639 Returns the total amount of all payments.
2646 $total += $_->paid foreach $self->cust_pay;
2647 sprintf( "%.2f", $total );
2650 =item total_unapplied_credits
2652 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2653 customer. See L<FS::cust_credit/credited>.
2655 =item total_credited
2657 Old name for total_unapplied_credits. Don't use.
2661 sub total_credited {
2662 #carp "total_credited deprecated, use total_unapplied_credits";
2663 shift->total_unapplied_credits(@_);
2666 sub total_unapplied_credits {
2669 my $custnum = $self->custnum;
2671 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2674 SELECT SUM($unapplied_sql) FROM cust_credit
2675 WHERE custnum = $custnum
2678 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2682 =item total_unapplied_credits_pkgnum PKGNUM
2684 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2685 customer. See L<FS::cust_credit/credited>.
2689 sub total_unapplied_credits_pkgnum {
2690 my( $self, $pkgnum ) = @_;
2691 my $total_credit = 0;
2692 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2693 sprintf( "%.2f", $total_credit );
2697 =item total_unapplied_payments
2699 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2700 See L<FS::cust_pay/unapplied>.
2704 sub total_unapplied_payments {
2707 my $custnum = $self->custnum;
2709 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2712 SELECT SUM($unapplied_sql) FROM cust_pay
2713 WHERE custnum = $custnum
2716 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2720 =item total_unapplied_payments_pkgnum PKGNUM
2722 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2723 specific package when using experimental package balances. See
2724 L<FS::cust_pay/unapplied>.
2728 sub total_unapplied_payments_pkgnum {
2729 my( $self, $pkgnum ) = @_;
2730 my $total_unapplied = 0;
2731 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2732 sprintf( "%.2f", $total_unapplied );
2736 =item total_unapplied_refunds
2738 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2739 customer. See L<FS::cust_refund/unapplied>.
2743 sub total_unapplied_refunds {
2745 my $custnum = $self->custnum;
2747 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2750 SELECT SUM($unapplied_sql) FROM cust_refund
2751 WHERE custnum = $custnum
2754 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2760 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2761 total_unapplied_credits minus total_unapplied_payments).
2767 $self->balance_date_range;
2770 =item balance_date TIME
2772 Returns the balance for this customer, only considering invoices with date
2773 earlier than TIME (total_owed_date minus total_credited minus
2774 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2775 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2782 $self->balance_date_range(shift);
2785 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2787 Returns the balance for this customer, optionally considering invoices with
2788 date earlier than START_TIME, and not later than END_TIME
2789 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2791 Times are specified as SQL fragments or numeric
2792 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2793 L<Date::Parse> for conversion functions. The empty string can be passed
2794 to disable that time constraint completely.
2796 Available options are:
2800 =item unapplied_date
2802 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)
2808 sub balance_date_range {
2810 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2811 ') FROM cust_main WHERE custnum='. $self->custnum;
2812 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2815 =item balance_pkgnum PKGNUM
2817 Returns the balance for this customer's specific package when using
2818 experimental package balances (total_owed plus total_unrefunded, minus
2819 total_unapplied_credits minus total_unapplied_payments)
2823 sub balance_pkgnum {
2824 my( $self, $pkgnum ) = @_;
2827 $self->total_owed_pkgnum($pkgnum)
2828 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2829 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2830 - $self->total_unapplied_credits_pkgnum($pkgnum)
2831 - $self->total_unapplied_payments_pkgnum($pkgnum)
2835 =item in_transit_payments
2837 Returns the total of requests for payments for this customer pending in
2838 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2842 sub in_transit_payments {
2844 my $in_transit_payments = 0;
2845 foreach my $pay_batch ( qsearch('pay_batch', {
2848 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2849 'batchnum' => $pay_batch->batchnum,
2850 'custnum' => $self->custnum,
2852 $in_transit_payments += $cust_pay_batch->amount;
2855 sprintf( "%.2f", $in_transit_payments );
2860 Returns a hash of useful information for making a payment.
2870 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2871 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2872 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2876 For credit card transactions:
2888 For electronic check transactions:
2903 $return{balance} = $self->balance;
2905 $return{payname} = $self->payname
2906 || ( $self->first. ' '. $self->get('last') );
2908 $return{$_} = $self->bill_location->$_
2909 for qw(address1 address2 city state zip);
2911 $return{payby} = $self->payby;
2912 $return{stateid_state} = $self->stateid_state;
2914 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2915 $return{card_type} = cardtype($self->payinfo);
2916 $return{payinfo} = $self->paymask;
2918 @return{'month', 'year'} = $self->paydate_monthyear;
2922 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2923 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2924 $return{payinfo1} = $payinfo1;
2925 $return{payinfo2} = $payinfo2;
2926 $return{paytype} = $self->paytype;
2927 $return{paystate} = $self->paystate;
2931 #doubleclick protection
2933 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2939 =item paydate_monthyear
2941 Returns a two-element list consisting of the month and year of this customer's
2942 paydate (credit card expiration date for CARD customers)
2946 sub paydate_monthyear {
2948 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2950 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2959 Returns the exact time in seconds corresponding to the payment method
2960 expiration date. For CARD/DCRD customers this is the end of the month;
2961 for others (COMP is the only other payby that uses paydate) it's the start.
2962 Returns 0 if the paydate is empty or set to the far future.
2968 my ($month, $year) = $self->paydate_monthyear;
2969 return 0 if !$year or $year >= 2037;
2970 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2972 if ( $month == 13 ) {
2976 return timelocal(0,0,0,1,$month-1,$year) - 1;
2979 return timelocal(0,0,0,1,$month-1,$year);
2983 =item paydate_epoch_sql
2985 Class method. Returns an SQL expression to obtain the payment expiration date
2986 as a number of seconds.
2990 # Special expiration date behavior for non-CARD/DCRD customers has been
2991 # carefully preserved. Do we really use that?
2992 sub paydate_epoch_sql {
2994 my $table = shift || 'cust_main';
2995 my ($case1, $case2);
2996 if ( driver_name eq 'Pg' ) {
2997 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2998 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3000 elsif ( lc(driver_name) eq 'mysql' ) {
3001 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3002 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3005 return "CASE WHEN $table.payby IN('CARD','DCRD')
3011 =item tax_exemption TAXNAME
3016 my( $self, $taxname ) = @_;
3018 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3019 'taxname' => $taxname,
3024 =item cust_main_exemption
3028 sub cust_main_exemption {
3030 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3033 =item invoicing_list [ ARRAYREF ]
3035 If an arguement is given, sets these email addresses as invoice recipients
3036 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3037 (except as warnings), so use check_invoicing_list first.
3039 Returns a list of email addresses (with svcnum entries expanded).
3041 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3042 check it without disturbing anything by passing nothing.
3044 This interface may change in the future.
3048 sub invoicing_list {
3049 my( $self, $arrayref ) = @_;
3052 my @cust_main_invoice;
3053 if ( $self->custnum ) {
3054 @cust_main_invoice =
3055 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3057 @cust_main_invoice = ();
3059 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3060 #warn $cust_main_invoice->destnum;
3061 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3062 #warn $cust_main_invoice->destnum;
3063 my $error = $cust_main_invoice->delete;
3064 warn $error if $error;
3067 if ( $self->custnum ) {
3068 @cust_main_invoice =
3069 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3071 @cust_main_invoice = ();
3073 my %seen = map { $_->address => 1 } @cust_main_invoice;
3074 foreach my $address ( @{$arrayref} ) {
3075 next if exists $seen{$address} && $seen{$address};
3076 $seen{$address} = 1;
3077 my $cust_main_invoice = new FS::cust_main_invoice ( {
3078 'custnum' => $self->custnum,
3081 my $error = $cust_main_invoice->insert;
3082 warn $error if $error;
3086 if ( $self->custnum ) {
3088 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3095 =item check_invoicing_list ARRAYREF
3097 Checks these arguements as valid input for the invoicing_list method. If there
3098 is an error, returns the error, otherwise returns false.
3102 sub check_invoicing_list {
3103 my( $self, $arrayref ) = @_;
3105 foreach my $address ( @$arrayref ) {
3107 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3108 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3111 my $cust_main_invoice = new FS::cust_main_invoice ( {
3112 'custnum' => $self->custnum,
3115 my $error = $self->custnum
3116 ? $cust_main_invoice->check
3117 : $cust_main_invoice->checkdest
3119 return $error if $error;
3123 return "Email address required"
3124 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3125 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3130 =item set_default_invoicing_list
3132 Sets the invoicing list to all accounts associated with this customer,
3133 overwriting any previous invoicing list.
3137 sub set_default_invoicing_list {
3139 $self->invoicing_list($self->all_emails);
3144 Returns the email addresses of all accounts provisioned for this customer.
3151 foreach my $cust_pkg ( $self->all_pkgs ) {
3152 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3154 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3155 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3157 $list{$_}=1 foreach map { $_->email } @svc_acct;
3162 =item invoicing_list_addpost
3164 Adds postal invoicing to this customer. If this customer is already configured
3165 to receive postal invoices, does nothing.
3169 sub invoicing_list_addpost {
3171 return if grep { $_ eq 'POST' } $self->invoicing_list;
3172 my @invoicing_list = $self->invoicing_list;
3173 push @invoicing_list, 'POST';
3174 $self->invoicing_list(\@invoicing_list);
3177 =item invoicing_list_emailonly
3179 Returns the list of email invoice recipients (invoicing_list without non-email
3180 destinations such as POST and FAX).
3184 sub invoicing_list_emailonly {
3186 warn "$me invoicing_list_emailonly called"
3188 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3191 =item invoicing_list_emailonly_scalar
3193 Returns the list of email invoice recipients (invoicing_list without non-email
3194 destinations such as POST and FAX) as a comma-separated scalar.
3198 sub invoicing_list_emailonly_scalar {
3200 warn "$me invoicing_list_emailonly_scalar called"
3202 join(', ', $self->invoicing_list_emailonly);
3205 =item referral_custnum_cust_main
3207 Returns the customer who referred this customer (or the empty string, if
3208 this customer was not referred).
3210 Note the difference with referral_cust_main method: This method,
3211 referral_custnum_cust_main returns the single customer (if any) who referred
3212 this customer, while referral_cust_main returns an array of customers referred
3217 sub referral_custnum_cust_main {
3219 return '' unless $self->referral_custnum;
3220 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3223 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3225 Returns an array of customers referred by this customer (referral_custnum set
3226 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3227 customers referred by customers referred by this customer and so on, inclusive.
3228 The default behavior is DEPTH 1 (no recursion).
3230 Note the difference with referral_custnum_cust_main method: This method,
3231 referral_cust_main, returns an array of customers referred BY this customer,
3232 while referral_custnum_cust_main returns the single customer (if any) who
3233 referred this customer.
3237 sub referral_cust_main {
3239 my $depth = @_ ? shift : 1;
3240 my $exclude = @_ ? shift : {};
3243 map { $exclude->{$_->custnum}++; $_; }
3244 grep { ! $exclude->{ $_->custnum } }
3245 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3249 map { $_->referral_cust_main($depth-1, $exclude) }
3256 =item referral_cust_main_ncancelled
3258 Same as referral_cust_main, except only returns customers with uncancelled
3263 sub referral_cust_main_ncancelled {
3265 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3268 =item referral_cust_pkg [ DEPTH ]
3270 Like referral_cust_main, except returns a flat list of all unsuspended (and
3271 uncancelled) packages for each customer. The number of items in this list may
3272 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3276 sub referral_cust_pkg {
3278 my $depth = @_ ? shift : 1;
3280 map { $_->unsuspended_pkgs }
3281 grep { $_->unsuspended_pkgs }
3282 $self->referral_cust_main($depth);
3285 =item referring_cust_main
3287 Returns the single cust_main record for the customer who referred this customer
3288 (referral_custnum), or false.
3292 sub referring_cust_main {
3294 return '' unless $self->referral_custnum;
3295 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3298 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3300 Applies a credit to this customer. If there is an error, returns the error,
3301 otherwise returns false.
3303 REASON can be a text string, an FS::reason object, or a scalar reference to
3304 a reasonnum. If a text string, it will be automatically inserted as a new
3305 reason, and a 'reason_type' option must be passed to indicate the
3306 FS::reason_type for the new reason.
3308 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3309 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3310 I<commission_pkgnum>.
3312 Any other options are passed to FS::cust_credit::insert.
3317 my( $self, $amount, $reason, %options ) = @_;
3319 my $cust_credit = new FS::cust_credit {
3320 'custnum' => $self->custnum,
3321 'amount' => $amount,
3324 if ( ref($reason) ) {
3326 if ( ref($reason) eq 'SCALAR' ) {
3327 $cust_credit->reasonnum( $$reason );
3329 $cust_credit->reasonnum( $reason->reasonnum );
3333 $cust_credit->set('reason', $reason)
3336 $cust_credit->$_( delete $options{$_} )
3337 foreach grep exists($options{$_}),
3338 qw( addlinfo eventnum ),
3339 map "commission_$_", qw( agentnum salesnum pkgnum );
3341 $cust_credit->insert(%options);
3345 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3347 Creates a one-time charge for this customer. If there is an error, returns
3348 the error, otherwise returns false.
3350 New-style, with a hashref of options:
3352 my $error = $cust_main->charge(
3356 'start_date' => str2time('7/4/2009'),
3357 'pkg' => 'Description',
3358 'comment' => 'Comment',
3359 'additional' => [], #extra invoice detail
3360 'classnum' => 1, #pkg_class
3362 'setuptax' => '', # or 'Y' for tax exempt
3364 'locationnum'=> 1234, # optional
3367 'taxclass' => 'Tax class',
3370 'taxproduct' => 2, #part_pkg_taxproduct
3371 'override' => {}, #XXX describe
3373 #will be filled in with the new object
3374 'cust_pkg_ref' => \$cust_pkg,
3376 #generate an invoice immediately
3378 'invoice_terms' => '', #with these terms
3384 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3390 my ( $amount, $quantity, $start_date, $classnum );
3391 my ( $pkg, $comment, $additional );
3392 my ( $setuptax, $taxclass ); #internal taxes
3393 my ( $taxproduct, $override ); #vendor (CCH) taxes
3395 my $cust_pkg_ref = '';
3396 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3398 if ( ref( $_[0] ) ) {
3399 $amount = $_[0]->{amount};
3400 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3401 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3402 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3403 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3404 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3405 : '$'. sprintf("%.2f",$amount);
3406 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3407 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3408 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3409 $additional = $_[0]->{additional} || [];
3410 $taxproduct = $_[0]->{taxproductnum};
3411 $override = { '' => $_[0]->{tax_override} };
3412 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3413 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3414 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3415 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3420 $pkg = @_ ? shift : 'One-time charge';
3421 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3423 $taxclass = @_ ? shift : '';
3427 local $SIG{HUP} = 'IGNORE';
3428 local $SIG{INT} = 'IGNORE';
3429 local $SIG{QUIT} = 'IGNORE';
3430 local $SIG{TERM} = 'IGNORE';
3431 local $SIG{TSTP} = 'IGNORE';
3432 local $SIG{PIPE} = 'IGNORE';
3434 my $oldAutoCommit = $FS::UID::AutoCommit;
3435 local $FS::UID::AutoCommit = 0;
3438 my $part_pkg = new FS::part_pkg ( {
3440 'comment' => $comment,
3444 'classnum' => ( $classnum ? $classnum : '' ),
3445 'setuptax' => $setuptax,
3446 'taxclass' => $taxclass,
3447 'taxproductnum' => $taxproduct,
3450 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3451 ( 0 .. @$additional - 1 )
3453 'additional_count' => scalar(@$additional),
3454 'setup_fee' => $amount,
3457 my $error = $part_pkg->insert( options => \%options,
3458 tax_overrides => $override,
3461 $dbh->rollback if $oldAutoCommit;
3465 my $pkgpart = $part_pkg->pkgpart;
3466 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3467 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3468 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3469 $error = $type_pkgs->insert;
3471 $dbh->rollback if $oldAutoCommit;
3476 my $cust_pkg = new FS::cust_pkg ( {
3477 'custnum' => $self->custnum,
3478 'pkgpart' => $pkgpart,
3479 'quantity' => $quantity,
3480 'start_date' => $start_date,
3481 'no_auto' => $no_auto,
3482 'locationnum'=> $locationnum,
3485 $error = $cust_pkg->insert;
3487 $dbh->rollback if $oldAutoCommit;
3489 } elsif ( $cust_pkg_ref ) {
3490 ${$cust_pkg_ref} = $cust_pkg;
3494 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3495 'pkg_list' => [ $cust_pkg ],
3498 $dbh->rollback if $oldAutoCommit;
3503 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3508 #=item charge_postal_fee
3510 #Applies a one time charge this customer. If there is an error,
3511 #returns the error, returns the cust_pkg charge object or false
3512 #if there was no charge.
3516 # This should be a customer event. For that to work requires that bill
3517 # also be a customer event.
3519 sub charge_postal_fee {
3522 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3523 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3525 my $cust_pkg = new FS::cust_pkg ( {
3526 'custnum' => $self->custnum,
3527 'pkgpart' => $pkgpart,
3531 my $error = $cust_pkg->insert;
3532 $error ? $error : $cust_pkg;
3535 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3537 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3539 Optionally, a list or hashref of additional arguments to the qsearch call can
3546 my $opt = ref($_[0]) ? shift : { @_ };
3548 #return $self->num_cust_bill unless wantarray || keys %$opt;
3550 $opt->{'table'} = 'cust_bill';
3551 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3552 $opt->{'hashref'}{'custnum'} = $self->custnum;
3553 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3555 map { $_ } #behavior of sort undefined in scalar context
3556 sort { $a->_date <=> $b->_date }
3560 =item open_cust_bill
3562 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3567 sub open_cust_bill {
3571 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3577 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3579 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3583 sub legacy_cust_bill {
3586 #return $self->num_legacy_cust_bill unless wantarray;
3588 map { $_ } #behavior of sort undefined in scalar context
3589 sort { $a->_date <=> $b->_date }
3590 qsearch({ 'table' => 'legacy_cust_bill',
3591 'hashref' => { 'custnum' => $self->custnum, },
3592 'order_by' => 'ORDER BY _date ASC',
3596 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3598 Returns all the statements (see L<FS::cust_statement>) for this customer.
3600 Optionally, a list or hashref of additional arguments to the qsearch call can
3605 =item cust_bill_void
3607 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3611 sub cust_bill_void {
3614 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3615 sort { $a->_date <=> $b->_date }
3616 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3619 sub cust_statement {
3621 my $opt = ref($_[0]) ? shift : { @_ };
3623 #return $self->num_cust_statement unless wantarray || keys %$opt;
3625 $opt->{'table'} = 'cust_statement';
3626 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3627 $opt->{'hashref'}{'custnum'} = $self->custnum;
3628 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3630 map { $_ } #behavior of sort undefined in scalar context
3631 sort { $a->_date <=> $b->_date }
3635 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3637 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3639 Optionally, a list or hashref of additional arguments to the qsearch call can
3640 be passed following the SVCDB.
3647 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3648 warn "$me svc_x requires a svcdb";
3651 my $opt = ref($_[0]) ? shift : { @_ };
3653 $opt->{'table'} = $svcdb;
3654 $opt->{'addl_from'} =
3655 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3656 ($opt->{'addl_from'} || '');
3658 my $custnum = $self->custnum;
3659 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3660 my $where = "cust_pkg.custnum = $custnum";
3662 my $extra_sql = $opt->{'extra_sql'} || '';
3663 if ( keys %{ $opt->{'hashref'} } ) {
3664 $extra_sql = " AND $where $extra_sql";
3667 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3668 $extra_sql = "WHERE $where AND $1";
3671 $extra_sql = "WHERE $where $extra_sql";
3674 $opt->{'extra_sql'} = $extra_sql;
3679 # required for use as an eventtable;
3682 $self->svc_x('svc_acct', @_);
3687 Returns all the credits (see L<FS::cust_credit>) for this customer.
3693 map { $_ } #return $self->num_cust_credit unless wantarray;
3694 sort { $a->_date <=> $b->_date }
3695 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3698 =item cust_credit_pkgnum
3700 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3701 package when using experimental package balances.
3705 sub cust_credit_pkgnum {
3706 my( $self, $pkgnum ) = @_;
3707 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3708 sort { $a->_date <=> $b->_date }
3709 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3710 'pkgnum' => $pkgnum,
3717 Returns all the payments (see L<FS::cust_pay>) for this customer.
3723 return $self->num_cust_pay unless wantarray;
3724 sort { $a->_date <=> $b->_date }
3725 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3730 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3731 called automatically when the cust_pay method is used in a scalar context.
3737 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3738 my $sth = dbh->prepare($sql) or die dbh->errstr;
3739 $sth->execute($self->custnum) or die $sth->errstr;
3740 $sth->fetchrow_arrayref->[0];
3743 =item cust_pay_pkgnum
3745 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3746 package when using experimental package balances.
3750 sub cust_pay_pkgnum {
3751 my( $self, $pkgnum ) = @_;
3752 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3753 sort { $a->_date <=> $b->_date }
3754 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3755 'pkgnum' => $pkgnum,
3762 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3768 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3769 sort { $a->_date <=> $b->_date }
3770 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3773 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3775 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3777 Optionally, a list or hashref of additional arguments to the qsearch call can
3782 sub cust_pay_batch {
3784 my $opt = ref($_[0]) ? shift : { @_ };
3786 #return $self->num_cust_statement unless wantarray || keys %$opt;
3788 $opt->{'table'} = 'cust_pay_batch';
3789 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3790 $opt->{'hashref'}{'custnum'} = $self->custnum;
3791 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3793 map { $_ } #behavior of sort undefined in scalar context
3794 sort { $a->paybatchnum <=> $b->paybatchnum }
3798 =item cust_pay_pending
3800 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3801 (without status "done").
3805 sub cust_pay_pending {
3807 return $self->num_cust_pay_pending unless wantarray;
3808 sort { $a->_date <=> $b->_date }
3809 qsearch( 'cust_pay_pending', {
3810 'custnum' => $self->custnum,
3811 'status' => { op=>'!=', value=>'done' },
3816 =item cust_pay_pending_attempt
3818 Returns all payment attempts / declined payments for this customer, as pending
3819 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3820 a corresponding payment (see L<FS::cust_pay>).
3824 sub cust_pay_pending_attempt {
3826 return $self->num_cust_pay_pending_attempt unless wantarray;
3827 sort { $a->_date <=> $b->_date }
3828 qsearch( 'cust_pay_pending', {
3829 'custnum' => $self->custnum,
3836 =item num_cust_pay_pending
3838 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3839 customer (without status "done"). Also called automatically when the
3840 cust_pay_pending method is used in a scalar context.
3844 sub num_cust_pay_pending {
3847 " SELECT COUNT(*) FROM cust_pay_pending ".
3848 " WHERE custnum = ? AND status != 'done' ",
3853 =item num_cust_pay_pending_attempt
3855 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3856 customer, with status "done" but without a corresp. Also called automatically when the
3857 cust_pay_pending method is used in a scalar context.
3861 sub num_cust_pay_pending_attempt {
3864 " SELECT COUNT(*) FROM cust_pay_pending ".
3865 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3872 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3878 map { $_ } #return $self->num_cust_refund unless wantarray;
3879 sort { $a->_date <=> $b->_date }
3880 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3883 =item display_custnum
3885 Returns the displayed customer number for this customer: agent_custid if
3886 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3890 sub display_custnum {
3893 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3894 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3895 if ( $special eq 'CoStAg' ) {
3896 $prefix = uc( join('',
3898 ($self->state =~ /^(..)/),
3899 $prefix || ($self->agent->agent =~ /^(..)/)
3902 elsif ( $special eq 'CoStCl' ) {
3903 $prefix = uc( join('',
3905 ($self->state =~ /^(..)/),
3906 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3909 # add any others here if needed
3912 my $length = $conf->config('cust_main-custnum-display_length');
3913 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3914 return $self->agent_custid;
3915 } elsif ( $prefix ) {
3916 $length = 8 if !defined($length);
3918 sprintf('%0'.$length.'d', $self->custnum)
3919 } elsif ( $length ) {
3920 return sprintf('%0'.$length.'d', $self->custnum);
3922 return $self->custnum;
3928 Returns a name string for this customer, either "Company (Last, First)" or
3935 my $name = $self->contact;
3936 $name = $self->company. " ($name)" if $self->company;
3940 =item service_contact
3942 Returns the L<FS::contact> object for this customer that has the 'Service'
3943 contact class, or undef if there is no such contact. Deprecated; don't use
3948 sub service_contact {
3950 if ( !exists($self->{service_contact}) ) {
3951 my $classnum = $self->scalar_sql(
3952 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3953 ) || 0; #if it's zero, qsearchs will return nothing
3954 $self->{service_contact} = qsearchs('contact', {
3955 'classnum' => $classnum, 'custnum' => $self->custnum
3958 $self->{service_contact};
3963 Returns a name string for this (service/shipping) contact, either
3964 "Company (Last, First)" or "Last, First".
3971 my $name = $self->ship_contact;
3972 $name = $self->company. " ($name)" if $self->company;
3978 Returns a name string for this customer, either "Company" or "First Last".
3984 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3987 =item ship_name_short
3989 Returns a name string for this (service/shipping) contact, either "Company"
3994 sub ship_name_short {
3996 $self->service_contact
3997 ? $self->ship_contact_firstlast
4003 Returns this customer's full (billing) contact name only, "Last, First"
4009 $self->get('last'). ', '. $self->first;
4014 Returns this customer's full (shipping) contact name only, "Last, First"
4020 my $contact = $self->service_contact || $self;
4021 $contact->get('last') . ', ' . $contact->get('first');
4024 =item contact_firstlast
4026 Returns this customers full (billing) contact name only, "First Last".
4030 sub contact_firstlast {
4032 $self->first. ' '. $self->get('last');
4035 =item ship_contact_firstlast
4037 Returns this customer's full (shipping) contact name only, "First Last".
4041 sub ship_contact_firstlast {
4043 my $contact = $self->service_contact || $self;
4044 $contact->get('first') . ' '. $contact->get('last');
4047 #XXX this doesn't work in 3.x+
4050 #Returns this customer's full country name
4056 # code2country($self->country);
4059 =item county_state_county [ PREFIX ]
4061 Returns a string consisting of just the county, state and country.
4065 sub county_state_country {
4068 if ( @_ && $_[0] && $self->has_ship_address ) {
4069 $locationnum = $self->ship_locationnum;
4071 $locationnum = $self->bill_locationnum;
4073 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4074 $cust_location->county_state_country;
4077 =item geocode DATA_VENDOR
4079 Returns a value for the customer location as encoded by DATA_VENDOR.
4080 Currently this only makes sense for "CCH" as DATA_VENDOR.
4088 Returns a status string for this customer, currently:
4092 =item prospect - No packages have ever been ordered
4094 =item ordered - Recurring packages all are new (not yet billed).
4096 =item active - One or more recurring packages is active
4098 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4100 =item suspended - All non-cancelled recurring packages are suspended
4102 =item cancelled - All recurring packages are cancelled
4106 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4107 cust_main-status_module configuration option.
4111 sub status { shift->cust_status(@_); }
4115 for my $status ( FS::cust_main->statuses() ) {
4116 my $method = $status.'_sql';
4117 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4118 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4119 $sth->execute( ($self->custnum) x $numnum )
4120 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4121 return $status if $sth->fetchrow_arrayref->[0];
4125 =item ucfirst_cust_status
4127 =item ucfirst_status
4129 Returns the status with the first character capitalized.
4133 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4135 sub ucfirst_cust_status {
4137 ucfirst($self->cust_status);
4142 Returns a hex triplet color string for this customer's status.
4146 sub statuscolor { shift->cust_statuscolor(@_); }
4148 sub cust_statuscolor {
4150 __PACKAGE__->statuscolors->{$self->cust_status};
4153 =item tickets [ STATUS ]
4155 Returns an array of hashes representing the customer's RT tickets.
4157 An optional status (or arrayref or hashref of statuses) may be specified.
4163 my $status = ( @_ && $_[0] ) ? shift : '';
4165 my $num = $conf->config('cust_main-max_tickets') || 10;
4168 if ( $conf->config('ticket_system') ) {
4169 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4171 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4180 foreach my $priority (
4181 $conf->config('ticket_system-custom_priority_field-values'), ''
4183 last if scalar(@tickets) >= $num;
4185 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4186 $num - scalar(@tickets),
4197 # Return services representing svc_accts in customer support packages
4198 sub support_services {
4200 my %packages = map { $_ => 1 } $conf->config('support_packages');
4202 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4203 grep { $_->part_svc->svcdb eq 'svc_acct' }
4204 map { $_->cust_svc }
4205 grep { exists $packages{ $_->pkgpart } }
4206 $self->ncancelled_pkgs;
4210 # Return a list of latitude/longitude for one of the services (if any)
4211 sub service_coordinates {
4215 grep { $_->latitude && $_->longitude }
4217 map { $_->cust_svc }
4218 $self->ncancelled_pkgs;
4220 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4225 Returns a masked version of the named field
4230 my ($self,$field) = @_;
4234 'x'x(length($self->getfield($field))-4).
4235 substr($self->getfield($field), (length($self->getfield($field))-4));
4241 =head1 CLASS METHODS
4247 Class method that returns the list of possible status strings for customers
4248 (see L<the status method|/status>). For example:
4250 @statuses = FS::cust_main->statuses();
4256 keys %{ $self->statuscolors };
4259 =item cust_status_sql
4261 Returns an SQL fragment to determine the status of a cust_main record, as a
4266 sub cust_status_sql {
4268 for my $status ( FS::cust_main->statuses() ) {
4269 my $method = $status.'_sql';
4270 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4279 Returns an SQL expression identifying prospective cust_main records (customers
4280 with no packages ever ordered)
4284 use vars qw($select_count_pkgs);
4285 $select_count_pkgs =
4286 "SELECT COUNT(*) FROM cust_pkg
4287 WHERE cust_pkg.custnum = cust_main.custnum";
4289 sub select_count_pkgs_sql {
4294 " 0 = ( $select_count_pkgs ) ";
4299 Returns an SQL expression identifying ordered cust_main records (customers with
4300 no active packages, but recurring packages not yet setup or one time charges
4306 FS::cust_main->none_active_sql.
4307 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4312 Returns an SQL expression identifying active cust_main records (customers with
4313 active recurring packages).
4318 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4321 =item none_active_sql
4323 Returns an SQL expression identifying cust_main records with no active
4324 recurring packages. This includes customers of status prospect, ordered,
4325 inactive, and suspended.
4329 sub none_active_sql {
4330 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4335 Returns an SQL expression identifying inactive cust_main records (customers with
4336 no active recurring packages, but otherwise unsuspended/uncancelled).
4341 FS::cust_main->none_active_sql.
4342 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4348 Returns an SQL expression identifying suspended cust_main records.
4353 sub suspended_sql { susp_sql(@_); }
4355 FS::cust_main->none_active_sql.
4356 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4362 Returns an SQL expression identifying cancelled cust_main records.
4366 sub cancel_sql { shift->cancelled_sql(@_); }
4369 =item uncancelled_sql
4371 Returns an SQL expression identifying un-cancelled cust_main records.
4375 sub uncancelled_sql { uncancel_sql(@_); }
4376 sub uncancel_sql { "
4377 ( 0 < ( $select_count_pkgs
4378 AND ( cust_pkg.cancel IS NULL
4379 OR cust_pkg.cancel = 0
4382 OR 0 = ( $select_count_pkgs )
4388 Returns an SQL fragment to retreive the balance.
4393 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4394 WHERE cust_bill.custnum = cust_main.custnum )
4395 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4396 WHERE cust_pay.custnum = cust_main.custnum )
4397 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4398 WHERE cust_credit.custnum = cust_main.custnum )
4399 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4400 WHERE cust_refund.custnum = cust_main.custnum )
4403 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4405 Returns an SQL fragment to retreive the balance for this customer, optionally
4406 considering invoices with date earlier than START_TIME, and not
4407 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4408 total_unapplied_payments).
4410 Times are specified as SQL fragments or numeric
4411 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4412 L<Date::Parse> for conversion functions. The empty string can be passed
4413 to disable that time constraint completely.
4415 Available options are:
4419 =item unapplied_date
4421 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)
4426 set to true to remove all customer comparison clauses, for totals
4431 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4436 JOIN clause (typically used with the total option)
4440 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4441 time will be ignored. Note that START_TIME and END_TIME only limit the date
4442 range for invoices and I<unapplied> payments, credits, and refunds.
4448 sub balance_date_sql {
4449 my( $class, $start, $end, %opt ) = @_;
4451 my $cutoff = $opt{'cutoff'};
4453 my $owed = FS::cust_bill->owed_sql($cutoff);
4454 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4455 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4456 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4458 my $j = $opt{'join'} || '';
4460 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4461 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4462 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4463 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4465 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4466 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4467 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4468 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4473 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4475 Returns an SQL fragment to retreive the total unapplied payments for this
4476 customer, only considering payments with date earlier than START_TIME, and
4477 optionally not later than END_TIME.
4479 Times are specified as SQL fragments or numeric
4480 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4481 L<Date::Parse> for conversion functions. The empty string can be passed
4482 to disable that time constraint completely.
4484 Available options are:
4488 sub unapplied_payments_date_sql {
4489 my( $class, $start, $end, %opt ) = @_;
4491 my $cutoff = $opt{'cutoff'};
4493 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4495 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4496 'unapplied_date'=>1 );
4498 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4501 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4503 Helper method for balance_date_sql; name (and usage) subject to change
4504 (suggestions welcome).
4506 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4507 cust_refund, cust_credit or cust_pay).
4509 If TABLE is "cust_bill" or the unapplied_date option is true, only
4510 considers records with date earlier than START_TIME, and optionally not
4511 later than END_TIME .
4515 sub _money_table_where {
4516 my( $class, $table, $start, $end, %opt ) = @_;
4519 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4520 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4521 push @where, "$table._date <= $start" if defined($start) && length($start);
4522 push @where, "$table._date > $end" if defined($end) && length($end);
4524 push @where, @{$opt{'where'}} if $opt{'where'};
4525 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4531 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4532 use FS::cust_main::Search;
4535 FS::cust_main::Search->search(@_);
4550 #warn join('-',keys %$param);
4551 my $fh = $param->{filehandle};
4552 my $agentnum = $param->{agentnum};
4553 my $format = $param->{format};
4555 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4558 if ( $format eq 'simple' ) {
4559 @fields = qw( custnum agent_custid amount pkg );
4561 die "unknown format $format";
4564 eval "use Text::CSV_XS;";
4567 my $csv = new Text::CSV_XS;
4574 local $SIG{HUP} = 'IGNORE';
4575 local $SIG{INT} = 'IGNORE';
4576 local $SIG{QUIT} = 'IGNORE';
4577 local $SIG{TERM} = 'IGNORE';
4578 local $SIG{TSTP} = 'IGNORE';
4579 local $SIG{PIPE} = 'IGNORE';
4581 my $oldAutoCommit = $FS::UID::AutoCommit;
4582 local $FS::UID::AutoCommit = 0;
4585 #while ( $columns = $csv->getline($fh) ) {
4587 while ( defined($line=<$fh>) ) {
4589 $csv->parse($line) or do {
4590 $dbh->rollback if $oldAutoCommit;
4591 return "can't parse: ". $csv->error_input();
4594 my @columns = $csv->fields();
4595 #warn join('-',@columns);
4598 foreach my $field ( @fields ) {
4599 $row{$field} = shift @columns;
4602 if ( $row{custnum} && $row{agent_custid} ) {
4603 dbh->rollback if $oldAutoCommit;
4604 return "can't specify custnum with agent_custid $row{agent_custid}";
4608 if ( $row{agent_custid} && $agentnum ) {
4609 %hash = ( 'agent_custid' => $row{agent_custid},
4610 'agentnum' => $agentnum,
4614 if ( $row{custnum} ) {
4615 %hash = ( 'custnum' => $row{custnum} );
4618 unless ( scalar(keys %hash) ) {
4619 $dbh->rollback if $oldAutoCommit;
4620 return "can't find customer without custnum or agent_custid and agentnum";
4623 my $cust_main = qsearchs('cust_main', { %hash } );
4624 unless ( $cust_main ) {
4625 $dbh->rollback if $oldAutoCommit;
4626 my $custnum = $row{custnum} || $row{agent_custid};
4627 return "unknown custnum $custnum";
4630 if ( $row{'amount'} > 0 ) {
4631 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4633 $dbh->rollback if $oldAutoCommit;
4637 } elsif ( $row{'amount'} < 0 ) {
4638 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4641 $dbh->rollback if $oldAutoCommit;
4651 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4653 return "Empty file!" unless $imported;
4659 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4661 Deprecated. Use event notification and message templates
4662 (L<FS::msg_template>) instead.
4664 Sends a templated email notification to the customer (see L<Text::Template>).
4666 OPTIONS is a hash and may include
4668 I<from> - the email sender (default is invoice_from)
4670 I<to> - comma-separated scalar or arrayref of recipients
4671 (default is invoicing_list)
4673 I<subject> - The subject line of the sent email notification
4674 (default is "Notice from company_name")
4676 I<extra_fields> - a hashref of name/value pairs which will be substituted
4679 The following variables are vavailable in the template.
4681 I<$first> - the customer first name
4682 I<$last> - the customer last name
4683 I<$company> - the customer company
4684 I<$payby> - a description of the method of payment for the customer
4685 # would be nice to use FS::payby::shortname
4686 I<$payinfo> - the account information used to collect for this customer
4687 I<$expdate> - the expiration of the customer payment in seconds from epoch
4692 my ($self, $template, %options) = @_;
4694 return unless $conf->exists($template);
4696 my $from = $conf->config('invoice_from', $self->agentnum)
4697 if $conf->exists('invoice_from', $self->agentnum);
4698 $from = $options{from} if exists($options{from});
4700 my $to = join(',', $self->invoicing_list_emailonly);
4701 $to = $options{to} if exists($options{to});
4703 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4704 if $conf->exists('company_name', $self->agentnum);
4705 $subject = $options{subject} if exists($options{subject});
4707 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4708 SOURCE => [ map "$_\n",
4709 $conf->config($template)]
4711 or die "can't create new Text::Template object: Text::Template::ERROR";
4712 $notify_template->compile()
4713 or die "can't compile template: Text::Template::ERROR";
4715 $FS::notify_template::_template::company_name =
4716 $conf->config('company_name', $self->agentnum);
4717 $FS::notify_template::_template::company_address =
4718 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4720 my $paydate = $self->paydate || '2037-12-31';
4721 $FS::notify_template::_template::first = $self->first;
4722 $FS::notify_template::_template::last = $self->last;
4723 $FS::notify_template::_template::company = $self->company;
4724 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4725 my $payby = $self->payby;
4726 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4727 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4729 #credit cards expire at the end of the month/year of their exp date
4730 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4731 $FS::notify_template::_template::payby = 'credit card';
4732 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4733 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4735 }elsif ($payby eq 'COMP') {
4736 $FS::notify_template::_template::payby = 'complimentary account';
4738 $FS::notify_template::_template::payby = 'current method';
4740 $FS::notify_template::_template::expdate = $expire_time;
4742 for (keys %{$options{extra_fields}}){
4744 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4747 send_email(from => $from,
4749 subject => $subject,
4750 body => $notify_template->fill_in( PACKAGE =>
4751 'FS::notify_template::_template' ),
4756 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4758 Generates a templated notification to the customer (see L<Text::Template>).
4760 OPTIONS is a hash and may include
4762 I<extra_fields> - a hashref of name/value pairs which will be substituted
4763 into the template. These values may override values mentioned below
4764 and those from the customer record.
4766 The following variables are available in the template instead of or in addition
4767 to the fields of the customer record.
4769 I<$payby> - a description of the method of payment for the customer
4770 # would be nice to use FS::payby::shortname
4771 I<$payinfo> - the masked account information used to collect for this customer
4772 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4773 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4777 # a lot like cust_bill::print_latex
4778 sub generate_letter {
4779 my ($self, $template, %options) = @_;
4781 return unless $conf->exists($template);
4783 my $letter_template = new Text::Template
4785 SOURCE => [ map "$_\n", $conf->config($template)],
4786 DELIMITERS => [ '[@--', '--@]' ],
4788 or die "can't create new Text::Template object: Text::Template::ERROR";
4790 $letter_template->compile()
4791 or die "can't compile template: Text::Template::ERROR";
4793 my %letter_data = map { $_ => $self->$_ } $self->fields;
4794 $letter_data{payinfo} = $self->mask_payinfo;
4796 #my $paydate = $self->paydate || '2037-12-31';
4797 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4799 my $payby = $self->payby;
4800 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4801 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4803 #credit cards expire at the end of the month/year of their exp date
4804 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4805 $letter_data{payby} = 'credit card';
4806 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4807 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4809 }elsif ($payby eq 'COMP') {
4810 $letter_data{payby} = 'complimentary account';
4812 $letter_data{payby} = 'current method';
4814 $letter_data{expdate} = $expire_time;
4816 for (keys %{$options{extra_fields}}){
4817 $letter_data{$_} = $options{extra_fields}->{$_};
4820 unless(exists($letter_data{returnaddress})){
4821 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4822 $self->agent_template)
4824 if ( length($retadd) ) {
4825 $letter_data{returnaddress} = $retadd;
4826 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4827 $letter_data{returnaddress} =
4828 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4832 ( $conf->config('company_name', $self->agentnum),
4833 $conf->config('company_address', $self->agentnum),
4837 $letter_data{returnaddress} = '~';
4841 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4843 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4845 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4847 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4851 ) or die "can't open temp file: $!\n";
4852 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4853 or die "can't write temp file: $!\n";
4855 $letter_data{'logo_file'} = $lh->filename;
4857 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4861 ) or die "can't open temp file: $!\n";
4863 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4865 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4866 return ($1, $letter_data{'logo_file'});
4870 =item print_ps TEMPLATE
4872 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4878 my($file, $lfile) = $self->generate_letter(@_);
4879 my $ps = FS::Misc::generate_ps($file);
4880 unlink($file.'.tex');
4886 =item print TEMPLATE
4888 Prints the filled in template.
4890 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4894 sub queueable_print {
4897 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4898 or die "invalid customer number: " . $opt{custnum};
4900 my $error = $self->print( { 'template' => $opt{template} } );
4901 die $error if $error;
4905 my ($self, $template) = (shift, shift);
4907 [ $self->print_ps($template) ],
4908 'agentnum' => $self->agentnum,
4912 #these three subs should just go away once agent stuff is all config overrides
4914 sub agent_template {
4916 $self->_agent_plandata('agent_templatename');
4919 sub agent_invoice_from {
4921 $self->_agent_plandata('agent_invoice_from');
4924 sub _agent_plandata {
4925 my( $self, $option ) = @_;
4927 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4928 #agent-specific Conf
4930 use FS::part_event::Condition;
4932 my $agentnum = $self->agentnum;
4934 my $regexp = regexp_sql();
4936 my $part_event_option =
4938 'select' => 'part_event_option.*',
4939 'table' => 'part_event_option',
4941 LEFT JOIN part_event USING ( eventpart )
4942 LEFT JOIN part_event_option AS peo_agentnum
4943 ON ( part_event.eventpart = peo_agentnum.eventpart
4944 AND peo_agentnum.optionname = 'agentnum'
4945 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4947 LEFT JOIN part_event_condition
4948 ON ( part_event.eventpart = part_event_condition.eventpart
4949 AND part_event_condition.conditionname = 'cust_bill_age'
4951 LEFT JOIN part_event_condition_option
4952 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4953 AND part_event_condition_option.optionname = 'age'
4956 #'hashref' => { 'optionname' => $option },
4957 #'hashref' => { 'part_event_option.optionname' => $option },
4959 " WHERE part_event_option.optionname = ". dbh->quote($option).
4960 " AND action = 'cust_bill_send_agent' ".
4961 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4962 " AND peo_agentnum.optionname = 'agentnum' ".
4963 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4965 CASE WHEN part_event_condition_option.optionname IS NULL
4967 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4969 , part_event.weight".
4973 unless ( $part_event_option ) {
4974 return $self->agent->invoice_template || ''
4975 if $option eq 'agent_templatename';
4979 $part_event_option->optionvalue;
4983 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4985 Subroutine (not a method), designed to be called from the queue.
4987 Takes a list of options and values.
4989 Pulls up the customer record via the custnum option and calls bill_and_collect.
4994 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4996 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4997 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4999 $cust_main->bill_and_collect( %args );
5002 sub process_bill_and_collect {
5004 my $param = thaw(decode_base64(shift));
5005 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5006 or die "custnum '$param->{custnum}' not found!\n";
5007 $param->{'job'} = $job;
5008 $param->{'fatal'} = 1; # runs from job queue, will be caught
5009 $param->{'retry'} = 1;
5011 $cust_main->bill_and_collect( %$param );
5014 #starting to take quite a while for big dbs
5015 # (JRNL: journaled so it only happens once per database)
5016 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5017 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5018 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5019 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5020 # JRNL leading/trailing spaces in first, last, company
5021 # JRNL migrate to cust_payby
5022 # - otaker upgrade? journal and call it good? (double check to make sure
5023 # we're not still setting otaker here)
5025 #only going to get worse with new location stuff...
5027 sub _upgrade_data { #class method
5028 my ($class, %opts) = @_;
5031 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5034 #this seems to be the only expensive one.. why does it take so long?
5035 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5037 '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';
5038 FS::upgrade_journal->set_done('cust_main__signupdate');
5041 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5043 # fix yyyy-m-dd formatted paydates
5044 if ( driver_name =~ /^mysql/i ) {
5046 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5047 } else { # the SQL standard
5049 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5051 FS::upgrade_journal->set_done('cust_main__paydate');
5054 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5056 push @statements, #fix the weird BILL with a cc# in payinfo problem
5058 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5060 FS::upgrade_journal->set_done('cust_main__payinfo');
5065 foreach my $sql ( @statements ) {
5066 my $sth = dbh->prepare($sql) or die dbh->errstr;
5067 $sth->execute or die $sth->errstr;
5068 #warn ( (time - $t). " seconds\n" );
5072 local($ignore_expired_card) = 1;
5073 local($ignore_banned_card) = 1;
5074 local($skip_fuzzyfiles) = 1;
5075 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5077 FS::cust_main::Location->_upgrade_data(%opts);
5079 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5081 foreach my $cust_main ( qsearch({
5082 'table' => 'cust_main',
5084 'extra_sql' => 'WHERE '.
5086 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5087 qw( first last company )
5090 my $error = $cust_main->replace;
5091 die $error if $error;
5094 FS::upgrade_journal->set_done('cust_main__trimspaces');
5098 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5100 #we don't want to decrypt them, just stuff them as-is into cust_payby
5101 local(@encrypted_fields) = ();
5103 local($FS::cust_payby::ignore_expired_card) = 1;
5104 local($FS::cust_payby::ignore_banned_card) = 1;
5106 my @payfields = qw( payby payinfo paycvv paymask
5107 paydate paystart_month paystart_year payissue
5108 payname paystate paytype payip
5111 my $search = new FS::Cursor {
5112 'table' => 'cust_main',
5113 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5116 while (my $cust_main = $search->fetch) {
5118 my $cust_payby = new FS::cust_payby {
5119 'custnum' => $cust_main->custnum,
5121 map { $_ => $cust_main->$_(); } @payfields
5124 my $error = $cust_payby->insert;
5125 die $error if $error;
5127 $cust_main->setfield($_, '') foreach @payfields;
5129 $error = $cust_main->replace;
5130 die $error if $error;
5134 FS::upgrade_journal->set_done('cust_main__trimspaces');
5137 $class->_upgrade_otaker(%opts);
5147 The delete method should possibly take an FS::cust_main object reference
5148 instead of a scalar customer number.
5150 Bill and collect options should probably be passed as references instead of a
5153 There should probably be a configuration file with a list of allowed credit
5156 No multiple currency support (probably a larger project than just this module).
5158 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5160 Birthdates rely on negative epoch values.
5162 The payby for card/check batches is broken. With mixed batching, bad
5165 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5169 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5170 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5171 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.