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
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
31 use Digest::MD5 qw(md5_base64);
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
37 use FS::UID qw( dbh driver_name );
38 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
40 use FS::Misc qw( generate_email send_email generate_ps do_print );
41 use FS::Msgcat qw(gettext);
48 use FS::cust_bill_void;
49 use FS::legacy_cust_bill;
51 use FS::cust_pay_pending;
52 use FS::cust_pay_void;
53 use FS::cust_pay_batch;
56 use FS::part_referral;
57 use FS::cust_main_county;
58 use FS::cust_location;
60 use FS::cust_main_exemption;
61 use FS::cust_tax_adjustment;
62 use FS::cust_tax_location;
64 use FS::agent_currency;
65 use FS::cust_main_invoice;
67 use FS::prepay_credit;
73 use FS::payment_gateway;
74 use FS::agent_payment_gateway;
76 use FS::cust_main_note;
77 use FS::cust_attachment;
80 use FS::upgrade_journal;
84 # 1 is mostly method/subroutine entry and options
85 # 2 traces progress of some operations
86 # 3 is even more information including possibly sensitive data
88 $me = '[FS::cust_main]';
91 $ignore_expired_card = 0;
92 $ignore_banned_card = 0;
93 $ignore_invalid_card = 0;
97 @encrypted_fields = ('payinfo', 'paycvv');
98 sub nohistory_fields { ('payinfo', 'paycvv'); }
100 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
102 #ask FS::UID to run this stuff for us later
103 #$FS::UID::callback{'FS::cust_main'} = sub {
104 install_callback FS::UID sub {
105 $conf = new FS::Conf;
106 #yes, need it for stuff below (prolly should be cached)
107 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
112 my ( $hashref, $cache ) = @_;
113 if ( exists $hashref->{'pkgnum'} ) {
114 #@{ $self->{'_pkgnum'} } = ();
115 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
116 $self->{'_pkgnum'} = $subcache;
117 #push @{ $self->{'_pkgnum'} },
118 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
124 FS::cust_main - Object methods for cust_main records
130 $record = new FS::cust_main \%hash;
131 $record = new FS::cust_main { 'column' => 'value' };
133 $error = $record->insert;
135 $error = $new_record->replace($old_record);
137 $error = $record->delete;
139 $error = $record->check;
141 @cust_pkg = $record->all_pkgs;
143 @cust_pkg = $record->ncancelled_pkgs;
145 @cust_pkg = $record->suspended_pkgs;
147 $error = $record->bill;
148 $error = $record->bill %options;
149 $error = $record->bill 'time' => $time;
151 $error = $record->collect;
152 $error = $record->collect %options;
153 $error = $record->collect 'invoice_time' => $time,
158 An FS::cust_main object represents a customer. FS::cust_main inherits from
159 FS::Record. The following fields are currently supported:
165 Primary key (assigned automatically for new customers)
169 Agent (see L<FS::agent>)
173 Advertising source (see L<FS::part_referral>)
185 Cocial security number (optional)
209 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
213 Payment Information (See L<FS::payinfo_Mixin> for data format)
217 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
221 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
225 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
229 Start date month (maestro/solo cards only)
233 Start date year (maestro/solo cards only)
237 Issue number (maestro/solo cards only)
241 Name on card or billing name
245 IP address from which payment information was received
249 Tax exempt, empty or `Y'
253 Order taker (see L<FS::access_user>)
259 =item referral_custnum
261 Referring customer number
265 Enable individual CDR spooling, empty or `Y'
269 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
273 Discourage individual CDR printing, empty or `Y'
277 Allow self-service editing of ticket subjects, empty or 'Y'
279 =item calling_list_exempt
281 Do not call, empty or 'Y'
291 Creates a new customer. To add the customer to the database, see L<"insert">.
293 Note that this stores the hash reference, not a distinct copy of the hash it
294 points to. You can ask the object for a copy with the I<hash> method.
298 sub table { 'cust_main'; }
300 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
302 Adds this customer to the database. If there is an error, returns the error,
303 otherwise returns false.
305 Usually the customer's location will not yet exist in the database, and
306 the C<bill_location> and C<ship_location> pseudo-fields must be set to
307 uninserted L<FS::cust_location> objects. These will be inserted and linked
308 (in both directions) to the new customer record. If they're references
309 to the same object, they will become the same location.
311 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
312 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
313 are inserted atomicly, or the transaction is rolled back. Passing an empty
314 hash reference is equivalent to not supplying this parameter. There should be
315 a better explanation of this, but until then, here's an example:
318 tie %hash, 'Tie::RefHash'; #this part is important
320 $cust_pkg => [ $svc_acct ],
323 $cust_main->insert( \%hash );
325 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
326 be set as the invoicing list (see L<"invoicing_list">). Errors return as
327 expected and rollback the entire transaction; it is not necessary to call
328 check_invoicing_list first. The invoicing_list is set after the records in the
329 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
330 invoicing_list destination to the newly-created svc_acct. Here's an example:
332 $cust_main->insert( {}, [ $email, 'POST' ] );
334 Currently available options are: I<depend_jobnum>, I<noexport>,
335 I<tax_exemption> and I<prospectnum>.
337 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
338 on the supplied jobnum (they will not run until the specific job completes).
339 This can be used to defer provisioning until some action completes (such
340 as running the customer's credit card successfully).
342 The I<noexport> option is deprecated. If I<noexport> is set true, no
343 provisioning jobs (exports) are scheduled. (You can schedule them later with
344 the B<reexport> method.)
346 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
347 of tax names and exemption numbers. FS::cust_main_exemption records will be
348 created and inserted.
350 If I<prospectnum> is set, moves contacts and locations from that prospect.
356 my $cust_pkgs = @_ ? shift : {};
357 my $invoicing_list = @_ ? shift : '';
359 warn "$me insert called with options ".
360 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
363 local $SIG{HUP} = 'IGNORE';
364 local $SIG{INT} = 'IGNORE';
365 local $SIG{QUIT} = 'IGNORE';
366 local $SIG{TERM} = 'IGNORE';
367 local $SIG{TSTP} = 'IGNORE';
368 local $SIG{PIPE} = 'IGNORE';
370 my $oldAutoCommit = $FS::UID::AutoCommit;
371 local $FS::UID::AutoCommit = 0;
374 my $prepay_identifier = '';
375 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
377 if ( $self->payby eq 'PREPAY' ) {
379 $self->payby('BILL');
380 $prepay_identifier = $self->payinfo;
383 warn " looking up prepaid card $prepay_identifier\n"
386 my $error = $self->get_prepay( $prepay_identifier,
387 'amount_ref' => \$amount,
388 'seconds_ref' => \$seconds,
389 'upbytes_ref' => \$upbytes,
390 'downbytes_ref' => \$downbytes,
391 'totalbytes_ref' => \$totalbytes,
394 $dbh->rollback if $oldAutoCommit;
395 #return "error applying prepaid card (transaction rolled back): $error";
399 $payby = 'PREP' if $amount;
401 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|PPAL)$/ ) {
404 $self->payby('BILL');
405 $amount = $self->paid;
410 foreach my $l (qw(bill_location ship_location)) {
411 my $loc = delete $self->hashref->{$l};
412 # XXX if we're moving a prospect's locations, do that here
414 #return "$l not set";
415 #location-less customer records are now permitted
419 if ( !$loc->locationnum ) {
420 # warn the location that we're going to insert it with no custnum
421 $loc->set(custnum_pending => 1);
422 warn " inserting $l\n"
424 my $error = $loc->insert;
426 $dbh->rollback if $oldAutoCommit;
427 my $label = $l eq 'ship_location' ? 'service' : 'billing';
428 return "$error (in $label location)";
431 elsif ( ($loc->custnum || 0) > 0 or $loc->prospectnum ) {
432 # then it somehow belongs to another customer--shouldn't happen
433 $dbh->rollback if $oldAutoCommit;
434 return "$l belongs to customer ".$loc->custnum;
436 # else it already belongs to this customer
437 # (happens when ship_location is identical to bill_location)
439 $self->set($l.'num', $loc->locationnum);
441 if ( $self->get($l.'num') eq '' ) {
442 $dbh->rollback if $oldAutoCommit;
447 warn " inserting $self\n"
450 $self->signupdate(time) unless $self->signupdate;
452 $self->auto_agent_custid()
453 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
455 my $error = $self->SUPER::insert;
457 $dbh->rollback if $oldAutoCommit;
458 #return "inserting cust_main record (transaction rolled back): $error";
462 # now set cust_location.custnum
463 foreach my $l (qw(bill_location ship_location)) {
464 warn " setting $l.custnum\n"
466 my $loc = $self->$l or next;
467 unless ( $loc->custnum ) {
468 $loc->set(custnum => $self->custnum);
469 $error ||= $loc->replace;
473 $dbh->rollback if $oldAutoCommit;
474 return "error setting $l custnum: $error";
478 warn " setting invoicing list\n"
481 if ( $invoicing_list ) {
482 $error = $self->check_invoicing_list( $invoicing_list );
484 $dbh->rollback if $oldAutoCommit;
485 #return "checking invoicing_list (transaction rolled back): $error";
488 $self->invoicing_list( $invoicing_list );
491 warn " setting customer tags\n"
494 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
495 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
496 'custnum' => $self->custnum };
497 my $error = $cust_tag->insert;
499 $dbh->rollback if $oldAutoCommit;
504 my $prospectnum = delete $options{'prospectnum'};
505 if ( $prospectnum ) {
507 warn " moving contacts and locations from prospect $prospectnum\n"
511 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
512 unless ( $prospect_main ) {
513 $dbh->rollback if $oldAutoCommit;
514 return "Unknown prospectnum $prospectnum";
516 $prospect_main->custnum($self->custnum);
517 $prospect_main->disabled('Y');
518 my $error = $prospect_main->replace;
520 $dbh->rollback if $oldAutoCommit;
524 my @contact = $prospect_main->contact;
525 my @cust_location = $prospect_main->cust_location;
526 my @qual = $prospect_main->qual;
528 foreach my $r ( @contact, @cust_location, @qual ) {
530 $r->custnum($self->custnum);
531 my $error = $r->replace;
533 $dbh->rollback if $oldAutoCommit;
540 warn " setting cust_main_exemption\n"
543 my $tax_exemption = delete $options{'tax_exemption'};
544 if ( $tax_exemption ) {
546 $tax_exemption = { map { $_ => '' } @$tax_exemption }
547 if ref($tax_exemption) eq 'ARRAY';
549 foreach my $taxname ( keys %$tax_exemption ) {
550 my $cust_main_exemption = new FS::cust_main_exemption {
551 'custnum' => $self->custnum,
552 'taxname' => $taxname,
553 'exempt_number' => $tax_exemption->{$taxname},
555 my $error = $cust_main_exemption->insert;
557 $dbh->rollback if $oldAutoCommit;
558 return "inserting cust_main_exemption (transaction rolled back): $error";
563 warn " ordering packages\n"
566 $error = $self->order_pkgs( $cust_pkgs,
568 'seconds_ref' => \$seconds,
569 'upbytes_ref' => \$upbytes,
570 'downbytes_ref' => \$downbytes,
571 'totalbytes_ref' => \$totalbytes,
574 $dbh->rollback if $oldAutoCommit;
579 $dbh->rollback if $oldAutoCommit;
580 return "No svc_acct record to apply pre-paid time";
582 if ( $upbytes || $downbytes || $totalbytes ) {
583 $dbh->rollback if $oldAutoCommit;
584 return "No svc_acct record to apply pre-paid data";
588 warn " inserting initial $payby payment of $amount\n"
590 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
592 $dbh->rollback if $oldAutoCommit;
593 return "inserting payment (transaction rolled back): $error";
597 unless ( $import || $skip_fuzzyfiles ) {
598 warn " queueing fuzzyfiles update\n"
600 $error = $self->queue_fuzzyfiles_update;
602 $dbh->rollback if $oldAutoCommit;
603 return "updating fuzzy search cache: $error";
607 # FS::geocode_Mixin::after_insert or something?
608 if ( $conf->config('tax_district_method') and !$import ) {
609 # if anything non-empty, try to look it up
610 my $queue = new FS::queue {
611 'job' => 'FS::geocode_Mixin::process_district_update',
612 'custnum' => $self->custnum,
614 my $error = $queue->insert( ref($self), $self->custnum );
616 $dbh->rollback if $oldAutoCommit;
617 return "queueing tax district update: $error";
622 warn " exporting\n" if $DEBUG > 1;
624 my $export_args = $options{'export_args'} || [];
627 map qsearch( 'part_export', {exportnum=>$_} ),
628 $conf->config('cust_main-exports'); #, $agentnum
630 foreach my $part_export ( @part_export ) {
631 my $error = $part_export->export_insert($self, @$export_args);
633 $dbh->rollback if $oldAutoCommit;
634 return "exporting to ". $part_export->exporttype.
635 " (transaction rolled back): $error";
639 #foreach my $depend_jobnum ( @$depend_jobnums ) {
640 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
642 # foreach my $jobnum ( @jobnums ) {
643 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
644 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
646 # my $error = $queue->depend_insert($depend_jobnum);
648 # $dbh->rollback if $oldAutoCommit;
649 # return "error queuing job dependancy: $error";
656 #if ( exists $options{'jobnums'} ) {
657 # push @{ $options{'jobnums'} }, @jobnums;
660 warn " insert complete; committing transaction\n"
663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
668 use File::CounterFile;
669 sub auto_agent_custid {
672 my $format = $conf->config('cust_main-auto_agent_custid');
674 if ( $format eq '1YMMXXXXXXXX' ) {
676 my $counter = new File::CounterFile 'cust_main.agent_custid';
679 my $ym = 100000000000 + time2str('%y%m00000000', time);
680 if ( $ym > $counter->value ) {
681 $counter->{'value'} = $agent_custid = $ym;
682 $counter->{'updated'} = 1;
684 $agent_custid = $counter->inc;
690 die "Unknown cust_main-auto_agent_custid format: $format";
693 $self->agent_custid($agent_custid);
697 =item PACKAGE METHODS
699 Documentation on customer package methods has been moved to
700 L<FS::cust_main::Packages>.
702 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
704 Recharges this (existing) customer with the specified prepaid card (see
705 L<FS::prepay_credit>), specified either by I<identifier> or as an
706 FS::prepay_credit object. If there is an error, returns the error, otherwise
709 Optionally, five scalar references can be passed as well. They will have their
710 values filled in with the amount, number of seconds, and number of upload,
711 download, and total bytes applied by this prepaid card.
715 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
716 #the only place that uses these args
717 sub recharge_prepay {
718 my( $self, $prepay_credit, $amountref, $secondsref,
719 $upbytesref, $downbytesref, $totalbytesref ) = @_;
721 local $SIG{HUP} = 'IGNORE';
722 local $SIG{INT} = 'IGNORE';
723 local $SIG{QUIT} = 'IGNORE';
724 local $SIG{TERM} = 'IGNORE';
725 local $SIG{TSTP} = 'IGNORE';
726 local $SIG{PIPE} = 'IGNORE';
728 my $oldAutoCommit = $FS::UID::AutoCommit;
729 local $FS::UID::AutoCommit = 0;
732 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
734 my $error = $self->get_prepay( $prepay_credit,
735 'amount_ref' => \$amount,
736 'seconds_ref' => \$seconds,
737 'upbytes_ref' => \$upbytes,
738 'downbytes_ref' => \$downbytes,
739 'totalbytes_ref' => \$totalbytes,
741 || $self->increment_seconds($seconds)
742 || $self->increment_upbytes($upbytes)
743 || $self->increment_downbytes($downbytes)
744 || $self->increment_totalbytes($totalbytes)
745 || $self->insert_cust_pay_prepay( $amount,
747 ? $prepay_credit->identifier
752 $dbh->rollback if $oldAutoCommit;
756 if ( defined($amountref) ) { $$amountref = $amount; }
757 if ( defined($secondsref) ) { $$secondsref = $seconds; }
758 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
759 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
760 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
762 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
767 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
769 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
770 specified either by I<identifier> or as an FS::prepay_credit object.
772 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
773 incremented by the values of the prepaid card.
775 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
776 check or set this customer's I<agentnum>.
778 If there is an error, returns the error, otherwise returns false.
784 my( $self, $prepay_credit, %opt ) = @_;
786 local $SIG{HUP} = 'IGNORE';
787 local $SIG{INT} = 'IGNORE';
788 local $SIG{QUIT} = 'IGNORE';
789 local $SIG{TERM} = 'IGNORE';
790 local $SIG{TSTP} = 'IGNORE';
791 local $SIG{PIPE} = 'IGNORE';
793 my $oldAutoCommit = $FS::UID::AutoCommit;
794 local $FS::UID::AutoCommit = 0;
797 unless ( ref($prepay_credit) ) {
799 my $identifier = $prepay_credit;
801 $prepay_credit = qsearchs(
803 { 'identifier' => $identifier },
808 unless ( $prepay_credit ) {
809 $dbh->rollback if $oldAutoCommit;
810 return "Invalid prepaid card: ". $identifier;
815 if ( $prepay_credit->agentnum ) {
816 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
817 $dbh->rollback if $oldAutoCommit;
818 return "prepaid card not valid for agent ". $self->agentnum;
820 $self->agentnum($prepay_credit->agentnum);
823 my $error = $prepay_credit->delete;
825 $dbh->rollback if $oldAutoCommit;
826 return "removing prepay_credit (transaction rolled back): $error";
829 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
830 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
832 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
837 =item increment_upbytes SECONDS
839 Updates this customer's single or primary account (see L<FS::svc_acct>) by
840 the specified number of upbytes. If there is an error, returns the error,
841 otherwise returns false.
845 sub increment_upbytes {
846 _increment_column( shift, 'upbytes', @_);
849 =item increment_downbytes SECONDS
851 Updates this customer's single or primary account (see L<FS::svc_acct>) by
852 the specified number of downbytes. If there is an error, returns the error,
853 otherwise returns false.
857 sub increment_downbytes {
858 _increment_column( shift, 'downbytes', @_);
861 =item increment_totalbytes SECONDS
863 Updates this customer's single or primary account (see L<FS::svc_acct>) by
864 the specified number of totalbytes. If there is an error, returns the error,
865 otherwise returns false.
869 sub increment_totalbytes {
870 _increment_column( shift, 'totalbytes', @_);
873 =item increment_seconds SECONDS
875 Updates this customer's single or primary account (see L<FS::svc_acct>) by
876 the specified number of seconds. If there is an error, returns the error,
877 otherwise returns false.
881 sub increment_seconds {
882 _increment_column( shift, 'seconds', @_);
885 =item _increment_column AMOUNT
887 Updates this customer's single or primary account (see L<FS::svc_acct>) by
888 the specified number of seconds or bytes. If there is an error, returns
889 the error, otherwise returns false.
893 sub _increment_column {
894 my( $self, $column, $amount ) = @_;
895 warn "$me increment_column called: $column, $amount\n"
898 return '' unless $amount;
900 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
901 $self->ncancelled_pkgs;
904 return 'No packages with primary or single services found'.
905 ' to apply pre-paid time';
906 } elsif ( scalar(@cust_pkg) > 1 ) {
907 #maybe have a way to specify the package/account?
908 return 'Multiple packages found to apply pre-paid time';
911 my $cust_pkg = $cust_pkg[0];
912 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
916 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
919 return 'No account found to apply pre-paid time';
920 } elsif ( scalar(@cust_svc) > 1 ) {
921 return 'Multiple accounts found to apply pre-paid time';
924 my $svc_acct = $cust_svc[0]->svc_x;
925 warn " found service svcnum ". $svc_acct->pkgnum.
926 ' ('. $svc_acct->email. ")\n"
929 $column = "increment_$column";
930 $svc_acct->$column($amount);
934 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
936 Inserts a prepayment in the specified amount for this customer. An optional
937 second argument can specify the prepayment identifier for tracking purposes.
938 If there is an error, returns the error, otherwise returns false.
942 sub insert_cust_pay_prepay {
943 shift->insert_cust_pay('PREP', @_);
946 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
948 Inserts a cash payment in the specified amount for this customer. An optional
949 second argument can specify the payment identifier for tracking purposes.
950 If there is an error, returns the error, otherwise returns false.
954 sub insert_cust_pay_cash {
955 shift->insert_cust_pay('CASH', @_);
958 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
960 Inserts a Western Union payment in the specified amount for this customer. An
961 optional second argument can specify the prepayment identifier for tracking
962 purposes. If there is an error, returns the error, otherwise returns false.
966 sub insert_cust_pay_west {
967 shift->insert_cust_pay('WEST', @_);
970 sub insert_cust_pay {
971 my( $self, $payby, $amount ) = splice(@_, 0, 3);
972 my $payinfo = scalar(@_) ? shift : '';
974 my $cust_pay = new FS::cust_pay {
975 'custnum' => $self->custnum,
976 'paid' => sprintf('%.2f', $amount),
977 #'_date' => #date the prepaid card was purchased???
979 'payinfo' => $payinfo,
985 =item delete [ OPTION => VALUE ... ]
987 This deletes the customer. If there is an error, returns the error, otherwise
990 This will completely remove all traces of the customer record. This is not
991 what you want when a customer cancels service; for that, cancel all of the
992 customer's packages (see L</cancel>).
994 If the customer has any uncancelled packages, you need to pass a new (valid)
995 customer number for those packages to be transferred to, as the "new_customer"
996 option. Cancelled packages will be deleted. Did I mention that this is NOT
997 what you want when a customer cancels service and that you really should be
998 looking at L<FS::cust_pkg/cancel>?
1000 You can't delete a customer with invoices (see L<FS::cust_bill>),
1001 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1002 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1003 set the "delete_financials" option to a true value.
1008 my( $self, %opt ) = @_;
1010 local $SIG{HUP} = 'IGNORE';
1011 local $SIG{INT} = 'IGNORE';
1012 local $SIG{QUIT} = 'IGNORE';
1013 local $SIG{TERM} = 'IGNORE';
1014 local $SIG{TSTP} = 'IGNORE';
1015 local $SIG{PIPE} = 'IGNORE';
1017 my $oldAutoCommit = $FS::UID::AutoCommit;
1018 local $FS::UID::AutoCommit = 0;
1021 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1022 $dbh->rollback if $oldAutoCommit;
1023 return "Can't delete a master agent customer";
1026 #use FS::access_user
1027 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1028 $dbh->rollback if $oldAutoCommit;
1029 return "Can't delete a master employee customer";
1032 tie my %financial_tables, 'Tie::IxHash',
1033 'cust_bill' => 'invoices',
1034 'cust_statement' => 'statements',
1035 'cust_credit' => 'credits',
1036 'cust_pay' => 'payments',
1037 'cust_refund' => 'refunds',
1040 foreach my $table ( keys %financial_tables ) {
1042 my @records = $self->$table();
1044 if ( @records && ! $opt{'delete_financials'} ) {
1045 $dbh->rollback if $oldAutoCommit;
1046 return "Can't delete a customer with ". $financial_tables{$table};
1049 foreach my $record ( @records ) {
1050 my $error = $record->delete;
1052 $dbh->rollback if $oldAutoCommit;
1053 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1059 my @cust_pkg = $self->ncancelled_pkgs;
1061 my $new_custnum = $opt{'new_custnum'};
1062 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1063 $dbh->rollback if $oldAutoCommit;
1064 return "Invalid new customer number: $new_custnum";
1066 foreach my $cust_pkg ( @cust_pkg ) {
1067 my %hash = $cust_pkg->hash;
1068 $hash{'custnum'} = $new_custnum;
1069 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1070 my $error = $new_cust_pkg->replace($cust_pkg,
1071 options => { $cust_pkg->options },
1074 $dbh->rollback if $oldAutoCommit;
1079 my @cancelled_cust_pkg = $self->all_pkgs;
1080 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1081 my $error = $cust_pkg->delete;
1083 $dbh->rollback if $oldAutoCommit;
1088 #cust_tax_adjustment in financials?
1089 #cust_pay_pending? ouch
1091 foreach my $table (qw(
1092 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1093 cust_location cust_main_note cust_tax_adjustment
1094 cust_pay_void cust_pay_batch queue cust_tax_exempt
1096 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1097 my $error = $record->delete;
1099 $dbh->rollback if $oldAutoCommit;
1105 my $sth = $dbh->prepare(
1106 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1108 my $errstr = $dbh->errstr;
1109 $dbh->rollback if $oldAutoCommit;
1112 $sth->execute($self->custnum) or do {
1113 my $errstr = $sth->errstr;
1114 $dbh->rollback if $oldAutoCommit;
1120 my $ticket_dbh = '';
1121 if ($conf->config('ticket_system') eq 'RT_Internal') {
1123 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1124 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1125 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1126 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1129 if ( $ticket_dbh ) {
1131 my $ticket_sth = $ticket_dbh->prepare(
1132 'DELETE FROM Links WHERE Target = ?'
1134 my $errstr = $ticket_dbh->errstr;
1135 $dbh->rollback if $oldAutoCommit;
1138 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1140 my $errstr = $ticket_sth->errstr;
1141 $dbh->rollback if $oldAutoCommit;
1145 #check and see if the customer is the only link on the ticket, and
1146 #if so, set the ticket to deleted status in RT?
1147 #maybe someday, for now this will at least fix tickets not displaying
1151 #delete the customer record
1153 my $error = $self->SUPER::delete;
1155 $dbh->rollback if $oldAutoCommit;
1159 # cust_main exports!
1161 #my $export_args = $options{'export_args'} || [];
1164 map qsearch( 'part_export', {exportnum=>$_} ),
1165 $conf->config('cust_main-exports'); #, $agentnum
1167 foreach my $part_export ( @part_export ) {
1168 my $error = $part_export->export_delete( $self ); #, @$export_args);
1170 $dbh->rollback if $oldAutoCommit;
1171 return "exporting to ". $part_export->exporttype.
1172 " (transaction rolled back): $error";
1176 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1181 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1183 This merges this customer into the provided new custnum, and then deletes the
1184 customer. If there is an error, returns the error, otherwise returns false.
1186 The source customer's name, company name, phone numbers, agent,
1187 referring customer, customer class, advertising source, order taker, and
1188 billing information (except balance) are discarded.
1190 All packages are moved to the target customer. Packages with package locations
1191 are preserved. Packages without package locations are moved to a new package
1192 location with the source customer's service/shipping address.
1194 All invoices, statements, payments, credits and refunds are moved to the target
1195 customer. The source customer's balance is added to the target customer.
1197 All notes, attachments, tickets and customer tags are moved to the target
1200 Change history is not currently moved.
1205 my( $self, $new_custnum, %opt ) = @_;
1207 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1209 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1210 or return "Invalid new customer number: $new_custnum";
1212 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1213 if $self->agentnum != $new_cust_main->agentnum
1214 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1216 local $SIG{HUP} = 'IGNORE';
1217 local $SIG{INT} = 'IGNORE';
1218 local $SIG{QUIT} = 'IGNORE';
1219 local $SIG{TERM} = 'IGNORE';
1220 local $SIG{TSTP} = 'IGNORE';
1221 local $SIG{PIPE} = 'IGNORE';
1223 my $oldAutoCommit = $FS::UID::AutoCommit;
1224 local $FS::UID::AutoCommit = 0;
1227 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1228 $dbh->rollback if $oldAutoCommit;
1229 return "Can't merge a master agent customer";
1232 #use FS::access_user
1233 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1234 $dbh->rollback if $oldAutoCommit;
1235 return "Can't merge a master employee customer";
1238 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1239 'status' => { op=>'!=', value=>'done' },
1243 $dbh->rollback if $oldAutoCommit;
1244 return "Can't merge a customer with pending payments";
1247 tie my %financial_tables, 'Tie::IxHash',
1248 'cust_bill' => 'invoices',
1249 'cust_bill_void' => 'voided invoices',
1250 'cust_statement' => 'statements',
1251 'cust_credit' => 'credits',
1252 'cust_credit_void' => 'voided credits',
1253 'cust_pay' => 'payments',
1254 'cust_pay_void' => 'voided payments',
1255 'cust_refund' => 'refunds',
1258 foreach my $table ( keys %financial_tables ) {
1260 my @records = $self->$table();
1262 foreach my $record ( @records ) {
1263 $record->custnum($new_custnum);
1264 my $error = $record->replace;
1266 $dbh->rollback if $oldAutoCommit;
1267 return "Error merging ". $financial_tables{$table}. ": $error\n";
1273 my $name = $self->ship_name; #?
1275 my $locationnum = '';
1276 foreach my $cust_pkg ( $self->all_pkgs ) {
1277 $cust_pkg->custnum($new_custnum);
1279 unless ( $cust_pkg->locationnum ) {
1280 unless ( $locationnum ) {
1281 my $cust_location = new FS::cust_location {
1282 $self->location_hash,
1283 'custnum' => $new_custnum,
1285 my $error = $cust_location->insert;
1287 $dbh->rollback if $oldAutoCommit;
1290 $locationnum = $cust_location->locationnum;
1292 $cust_pkg->locationnum($locationnum);
1295 my $error = $cust_pkg->replace;
1297 $dbh->rollback if $oldAutoCommit;
1301 # add customer (ship) name to svc_phone.phone_name if blank
1302 my @cust_svc = $cust_pkg->cust_svc;
1303 foreach my $cust_svc (@cust_svc) {
1304 my($label, $value, $svcdb) = $cust_svc->label;
1305 next unless $svcdb eq 'svc_phone';
1306 my $svc_phone = $cust_svc->svc_x;
1307 next if $svc_phone->phone_name;
1308 $svc_phone->phone_name($name);
1309 my $error = $svc_phone->replace;
1311 $dbh->rollback if $oldAutoCommit;
1319 # cust_tax_exempt (texas tax exemptions)
1320 # cust_recon (some sort of not-well understood thing for OnPac)
1322 #these are moved over
1323 foreach my $table (qw(
1324 cust_tag cust_location contact cust_attachment cust_main_note
1325 cust_tax_adjustment cust_pay_batch queue
1327 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1328 $record->custnum($new_custnum);
1329 my $error = $record->replace;
1331 $dbh->rollback if $oldAutoCommit;
1337 #these aren't preserved
1338 foreach my $table (qw(
1339 cust_main_exemption cust_main_invoice
1341 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1342 my $error = $record->delete;
1344 $dbh->rollback if $oldAutoCommit;
1351 my $sth = $dbh->prepare(
1352 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1354 my $errstr = $dbh->errstr;
1355 $dbh->rollback if $oldAutoCommit;
1358 $sth->execute($new_custnum, $self->custnum) or do {
1359 my $errstr = $sth->errstr;
1360 $dbh->rollback if $oldAutoCommit;
1366 my $ticket_dbh = '';
1367 if ($conf->config('ticket_system') eq 'RT_Internal') {
1369 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1370 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1371 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1372 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1375 if ( $ticket_dbh ) {
1377 my $ticket_sth = $ticket_dbh->prepare(
1378 'UPDATE Links SET Target = ? WHERE Target = ?'
1380 my $errstr = $ticket_dbh->errstr;
1381 $dbh->rollback if $oldAutoCommit;
1384 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1385 'freeside://freeside/cust_main/'.$self->custnum)
1387 my $errstr = $ticket_sth->errstr;
1388 $dbh->rollback if $oldAutoCommit;
1394 #delete the customer record
1396 my $error = $self->delete;
1398 $dbh->rollback if $oldAutoCommit;
1402 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1407 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1409 Replaces the OLD_RECORD with this one in the database. If there is an error,
1410 returns the error, otherwise returns false.
1412 To change the customer's address, set the pseudo-fields C<bill_location> and
1413 C<ship_location>. The address will still only change if at least one of the
1414 address fields differs from the existing values.
1416 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1417 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1418 expected and rollback the entire transaction; it is not necessary to call
1419 check_invoicing_list first. Here's an example:
1421 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1423 Currently available options are: I<tax_exemption>.
1425 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1426 of tax names and exemption numbers. FS::cust_main_exemption records will be
1427 deleted and inserted as appropriate.
1434 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1436 : $self->replace_old;
1440 warn "$me replace called\n"
1443 my $curuser = $FS::CurrentUser::CurrentUser;
1444 if ( $self->payby eq 'COMP'
1445 && $self->payby ne $old->payby
1446 && ! $curuser->access_right('Complimentary customer')
1449 return "You are not permitted to create complimentary accounts.";
1452 local($ignore_expired_card) = 1
1453 if $old->payby =~ /^(CARD|DCRD)$/
1454 && $self->payby =~ /^(CARD|DCRD)$/
1455 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1457 local($ignore_banned_card) = 1
1458 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1459 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1460 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1462 return "Invoicing locale is required"
1465 && $conf->exists('cust_main-require_locale');
1467 local $SIG{HUP} = 'IGNORE';
1468 local $SIG{INT} = 'IGNORE';
1469 local $SIG{QUIT} = 'IGNORE';
1470 local $SIG{TERM} = 'IGNORE';
1471 local $SIG{TSTP} = 'IGNORE';
1472 local $SIG{PIPE} = 'IGNORE';
1474 my $oldAutoCommit = $FS::UID::AutoCommit;
1475 local $FS::UID::AutoCommit = 0;
1478 for my $l (qw(bill_location ship_location)) {
1479 my $old_loc = $old->$l;
1480 my $new_loc = $self->$l;
1482 # find the existing location if there is one
1483 $new_loc->set('custnum' => $self->custnum);
1484 my $error = $new_loc->find_or_insert;
1486 $dbh->rollback if $oldAutoCommit;
1489 $self->set($l.'num', $new_loc->locationnum);
1492 # replace the customer record
1493 my $error = $self->SUPER::replace($old);
1496 $dbh->rollback if $oldAutoCommit;
1500 # now move packages to the new service location
1501 $self->set('ship_location', ''); #flush cache
1502 if ( $old->ship_locationnum and # should only be null during upgrade...
1503 $old->ship_locationnum != $self->ship_locationnum ) {
1504 $error = $old->ship_location->move_to($self->ship_location);
1506 $dbh->rollback if $oldAutoCommit;
1510 # don't move packages based on the billing location, but
1511 # disable it if it's no longer in use
1512 if ( $old->bill_locationnum and
1513 $old->bill_locationnum != $self->bill_locationnum ) {
1514 $error = $old->bill_location->disable_if_unused;
1516 $dbh->rollback if $oldAutoCommit;
1521 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1522 my $invoicing_list = shift @param;
1523 $error = $self->check_invoicing_list( $invoicing_list );
1525 $dbh->rollback if $oldAutoCommit;
1528 $self->invoicing_list( $invoicing_list );
1531 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1533 #this could be more efficient than deleting and re-inserting, if it matters
1534 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1535 my $error = $cust_tag->delete;
1537 $dbh->rollback if $oldAutoCommit;
1541 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1542 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1543 'custnum' => $self->custnum };
1544 my $error = $cust_tag->insert;
1546 $dbh->rollback if $oldAutoCommit;
1553 my %options = @param;
1555 my $tax_exemption = delete $options{'tax_exemption'};
1556 if ( $tax_exemption ) {
1558 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1559 if ref($tax_exemption) eq 'ARRAY';
1561 my %cust_main_exemption =
1562 map { $_->taxname => $_ }
1563 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1565 foreach my $taxname ( keys %$tax_exemption ) {
1567 if ( $cust_main_exemption{$taxname} &&
1568 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1571 delete $cust_main_exemption{$taxname};
1575 my $cust_main_exemption = new FS::cust_main_exemption {
1576 'custnum' => $self->custnum,
1577 'taxname' => $taxname,
1578 'exempt_number' => $tax_exemption->{$taxname},
1580 my $error = $cust_main_exemption->insert;
1582 $dbh->rollback if $oldAutoCommit;
1583 return "inserting cust_main_exemption (transaction rolled back): $error";
1587 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1588 my $error = $cust_main_exemption->delete;
1590 $dbh->rollback if $oldAutoCommit;
1591 return "deleting cust_main_exemption (transaction rolled back): $error";
1597 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1598 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1599 && $self->get('payinfo') !~ /^99\d{14}$/
1601 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1606 # card/check/lec info has changed, want to retry realtime_ invoice events
1607 my $error = $self->retry_realtime;
1609 $dbh->rollback if $oldAutoCommit;
1614 unless ( $import || $skip_fuzzyfiles ) {
1615 $error = $self->queue_fuzzyfiles_update;
1617 $dbh->rollback if $oldAutoCommit;
1618 return "updating fuzzy search cache: $error";
1622 # tax district update in cust_location
1624 # cust_main exports!
1626 my $export_args = $options{'export_args'} || [];
1629 map qsearch( 'part_export', {exportnum=>$_} ),
1630 $conf->config('cust_main-exports'); #, $agentnum
1632 foreach my $part_export ( @part_export ) {
1633 my $error = $part_export->export_replace( $self, $old, @$export_args);
1635 $dbh->rollback if $oldAutoCommit;
1636 return "exporting to ". $part_export->exporttype.
1637 " (transaction rolled back): $error";
1641 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1646 =item queue_fuzzyfiles_update
1648 Used by insert & replace to update the fuzzy search cache
1652 use FS::cust_main::Search;
1653 sub queue_fuzzyfiles_update {
1656 local $SIG{HUP} = 'IGNORE';
1657 local $SIG{INT} = 'IGNORE';
1658 local $SIG{QUIT} = 'IGNORE';
1659 local $SIG{TERM} = 'IGNORE';
1660 local $SIG{TSTP} = 'IGNORE';
1661 local $SIG{PIPE} = 'IGNORE';
1663 my $oldAutoCommit = $FS::UID::AutoCommit;
1664 local $FS::UID::AutoCommit = 0;
1667 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1668 my $queue = new FS::queue {
1669 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1671 my @args = "cust_main.$field", $self->get($field);
1672 my $error = $queue->insert( @args );
1674 $dbh->rollback if $oldAutoCommit;
1675 return "queueing job (transaction rolled back): $error";
1680 push @locations, $self->bill_location if $self->bill_locationnum;
1681 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1682 foreach my $location (@locations) {
1683 my $queue = new FS::queue {
1684 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1686 my @args = 'cust_location.address1', $location->address1;
1687 my $error = $queue->insert( @args );
1689 $dbh->rollback if $oldAutoCommit;
1690 return "queueing job (transaction rolled back): $error";
1694 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1701 Checks all fields to make sure this is a valid customer record. If there is
1702 an error, returns the error, otherwise returns false. Called by the insert
1703 and replace methods.
1710 warn "$me check BEFORE: \n". $self->_dump
1714 $self->ut_numbern('custnum')
1715 || $self->ut_number('agentnum')
1716 || $self->ut_textn('agent_custid')
1717 || $self->ut_number('refnum')
1718 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1719 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1720 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1721 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1722 || $self->ut_textn('custbatch')
1723 || $self->ut_name('last')
1724 || $self->ut_name('first')
1725 || $self->ut_snumbern('signupdate')
1726 || $self->ut_snumbern('birthdate')
1727 || $self->ut_snumbern('spouse_birthdate')
1728 || $self->ut_snumbern('anniversary_date')
1729 || $self->ut_textn('company')
1730 || $self->ut_textn('ship_company')
1731 || $self->ut_anything('comments')
1732 || $self->ut_numbern('referral_custnum')
1733 || $self->ut_textn('stateid')
1734 || $self->ut_textn('stateid_state')
1735 || $self->ut_textn('invoice_terms')
1736 || $self->ut_floatn('cdr_termination_percentage')
1737 || $self->ut_floatn('credit_limit')
1738 || $self->ut_numbern('billday')
1739 || $self->ut_numbern('prorate_day')
1740 || $self->ut_flag('edit_subject')
1741 || $self->ut_flag('calling_list_exempt')
1742 || $self->ut_flag('invoice_noemail')
1743 || $self->ut_flag('message_noemail')
1744 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1745 || $self->ut_currencyn('currency')
1748 foreach (qw(company ship_company)) {
1749 my $company = $self->get($_);
1750 $company =~ s/^\s+//;
1751 $company =~ s/\s+$//;
1752 $company =~ s/\s+/ /g;
1753 $self->set($_, $company);
1756 #barf. need message catalogs. i18n. etc.
1757 $error .= "Please select an advertising source."
1758 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1759 return $error if $error;
1761 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1762 or return "Unknown agent";
1764 if ( $self->currency ) {
1765 my $agent_currency = qsearchs( 'agent_currency', {
1766 'agentnum' => $agent->agentnum,
1767 'currency' => $self->currency,
1769 or return "Agent ". $agent->agent.
1770 " not permitted to offer ". $self->currency. " invoicing";
1773 return "Unknown refnum"
1774 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1776 return "Unknown referring custnum: ". $self->referral_custnum
1777 unless ! $self->referral_custnum
1778 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1780 if ( $self->ss eq '' ) {
1785 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1786 or return "Illegal social security number: ". $self->ss;
1787 $self->ss("$1-$2-$3");
1790 # cust_main_county verification now handled by cust_location check
1793 $self->ut_phonen('daytime', $self->country)
1794 || $self->ut_phonen('night', $self->country)
1795 || $self->ut_phonen('fax', $self->country)
1796 || $self->ut_phonen('mobile', $self->country)
1798 return $error if $error;
1800 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1802 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1805 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1807 : FS::Msgcat::_gettext('daytime');
1808 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1810 : FS::Msgcat::_gettext('night');
1812 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1814 : FS::Msgcat::_gettext('mobile');
1816 return "$daytime_label, $night_label or $mobile_label is required"
1820 ### start of stuff moved to cust_payby
1821 # then mostly kept here to support upgrades (can remove in 5.x)
1822 # but modified to allow everything to be empty
1824 if ( $self->payby ) {
1825 FS::payby->can_payby($self->table, $self->payby)
1826 or return "Illegal payby: ". $self->payby;
1831 $error = $self->ut_numbern('paystart_month')
1832 || $self->ut_numbern('paystart_year')
1833 || $self->ut_numbern('payissue')
1834 || $self->ut_textn('paytype')
1836 return $error if $error;
1838 if ( $self->payip eq '' ) {
1841 $error = $self->ut_ip('payip');
1842 return $error if $error;
1845 # If it is encrypted and the private key is not availaible then we can't
1846 # check the credit card.
1847 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1849 # Need some kind of global flag to accept invalid cards, for testing
1851 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1852 $self->payby =~ /^(CARD|DCRD)$/ ) {
1854 my $payinfo = $self->payinfo;
1855 $payinfo =~ s/\D//g;
1856 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1857 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1859 $self->payinfo($payinfo);
1861 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1863 return gettext('unknown_card_type')
1864 if $self->payinfo !~ /^99\d{14}$/ #token
1865 && cardtype($self->payinfo) eq "Unknown";
1867 unless ( $ignore_banned_card ) {
1868 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1870 if ( $ban->bantype eq 'warn' ) {
1871 #or others depending on value of $ban->reason ?
1872 return '_duplicate_card'.
1873 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1874 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1875 ' (ban# '. $ban->bannum. ')'
1876 unless $self->override_ban_warn;
1878 return 'Banned credit card: banned on '.
1879 time2str('%a %h %o at %r', $ban->_date).
1880 ' by '. $ban->otaker.
1881 ' (ban# '. $ban->bannum. ')';
1886 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1887 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1888 $self->paycvv =~ /^(\d{4})$/
1889 or return "CVV2 (CID) for American Express cards is four digits.";
1892 $self->paycvv =~ /^(\d{3})$/
1893 or return "CVV2 (CVC2/CID) is three digits.";
1900 my $cardtype = cardtype($payinfo);
1901 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1903 return "Start date or issue number is required for $cardtype cards"
1904 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1906 return "Start month must be between 1 and 12"
1907 if $self->paystart_month
1908 and $self->paystart_month < 1 || $self->paystart_month > 12;
1910 return "Start year must be 1990 or later"
1911 if $self->paystart_year
1912 and $self->paystart_year < 1990;
1914 return "Issue number must be beween 1 and 99"
1916 and $self->payissue < 1 || $self->payissue > 99;
1919 $self->paystart_month('');
1920 $self->paystart_year('');
1921 $self->payissue('');
1924 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1925 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1927 my $payinfo = $self->payinfo;
1928 $payinfo =~ s/[^\d\@\.]//g;
1929 if ( $conf->config('echeck-country') eq 'CA' ) {
1930 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1931 or return 'invalid echeck account@branch.bank';
1932 $payinfo = "$1\@$2.$3";
1933 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1934 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1935 $payinfo = "$1\@$2";
1937 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1938 $payinfo = "$1\@$2";
1940 $self->payinfo($payinfo);
1943 unless ( $ignore_banned_card ) {
1944 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1946 if ( $ban->bantype eq 'warn' ) {
1947 #or others depending on value of $ban->reason ?
1948 return '_duplicate_ach' unless $self->override_ban_warn;
1950 return 'Banned ACH account: banned on '.
1951 time2str('%a %h %o at %r', $ban->_date).
1952 ' by '. $ban->otaker.
1953 ' (ban# '. $ban->bannum. ')';
1958 } elsif ( $self->payby eq 'LECB' ) {
1960 my $payinfo = $self->payinfo;
1961 $payinfo =~ s/\D//g;
1962 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1964 $self->payinfo($payinfo);
1967 } elsif ( $self->payby eq 'BILL' ) {
1969 $error = $self->ut_textn('payinfo');
1970 return "Illegal P.O. number: ". $self->payinfo if $error;
1973 } elsif ( $self->payby eq 'COMP' ) {
1975 my $curuser = $FS::CurrentUser::CurrentUser;
1976 if ( ! $self->custnum
1977 && ! $curuser->access_right('Complimentary customer')
1980 return "You are not permitted to create complimentary accounts."
1983 $error = $self->ut_textn('payinfo');
1984 return "Illegal comp account issuer: ". $self->payinfo if $error;
1987 } elsif ( $self->payby eq 'PREPAY' ) {
1989 my $payinfo = $self->payinfo;
1990 $payinfo =~ s/\W//g; #anything else would just confuse things
1991 $self->payinfo($payinfo);
1992 $error = $self->ut_alpha('payinfo');
1993 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1994 return "Unknown prepayment identifier"
1995 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2000 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2001 return "Expiration date required"
2002 # shouldn't payinfo_check do this?
2003 unless ! $self->payby
2004 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2008 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2009 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2010 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2011 ( $m, $y ) = ( $2, "19$1" );
2012 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2013 ( $m, $y ) = ( $3, "20$2" );
2015 return "Illegal expiration date: ". $self->paydate;
2017 $m = sprintf('%02d',$m);
2018 $self->paydate("$y-$m-01");
2019 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2020 return gettext('expired_card')
2022 && !$ignore_expired_card
2023 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2026 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2027 ( ! $conf->exists('require_cardname')
2028 || $self->payby !~ /^(CARD|DCRD)$/ )
2030 $self->payname( $self->first. " ". $self->getfield('last') );
2032 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2033 or return gettext('illegal_name'). " payname: ". $self->payname;
2037 ### end of stuff moved to cust_payby
2039 return "Please select an invoicing locale"
2042 && $conf->exists('cust_main-require_locale');
2044 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2045 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2049 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2051 warn "$me check AFTER: \n". $self->_dump
2054 $self->SUPER::check;
2059 Returns a list of fields which have ship_ duplicates.
2064 qw( last first company
2065 address1 address2 city county state zip country
2067 daytime night fax mobile
2071 =item has_ship_address
2073 Returns true if this customer record has a separate shipping address.
2077 sub has_ship_address {
2079 $self->bill_locationnum != $self->ship_locationnum;
2084 Returns a list of key/value pairs, with the following keys: address1,
2085 adddress2, city, county, state, zip, country, district, and geocode. The
2086 shipping address is used if present.
2092 $self->ship_location->location_hash;
2097 Returns all locations (see L<FS::cust_location>) for this customer.
2103 qsearch('cust_location', { 'custnum' => $self->custnum,
2104 'prospectnum' => '' } );
2109 Returns all contacts (see L<FS::contact>) for this customer.
2113 #already used :/ sub contact {
2116 qsearch('contact', { 'custnum' => $self->custnum } );
2121 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2128 'table' => 'cust_payby',
2129 'hashref' => { 'custnum' => $self->custnum },
2130 'order_by' => 'ORDER BY weight ASC',
2136 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2137 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2138 on success or a list of errors.
2144 grep { $_->unsuspend } $self->suspended_pkgs;
2149 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2151 Returns a list: an empty list on success or a list of errors.
2157 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2160 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2162 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2163 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2164 of a list of pkgparts; the hashref has the following keys:
2168 =item pkgparts - listref of pkgparts
2170 =item (other options are passed to the suspend method)
2175 Returns a list: an empty list on success or a list of errors.
2179 sub suspend_if_pkgpart {
2181 my (@pkgparts, %opt);
2182 if (ref($_[0]) eq 'HASH'){
2183 @pkgparts = @{$_[0]{pkgparts}};
2188 grep { $_->suspend(%opt) }
2189 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2190 $self->unsuspended_pkgs;
2193 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2195 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2196 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2197 instead of a list of pkgparts; the hashref has the following keys:
2201 =item pkgparts - listref of pkgparts
2203 =item (other options are passed to the suspend method)
2207 Returns a list: an empty list on success or a list of errors.
2211 sub suspend_unless_pkgpart {
2213 my (@pkgparts, %opt);
2214 if (ref($_[0]) eq 'HASH'){
2215 @pkgparts = @{$_[0]{pkgparts}};
2220 grep { $_->suspend(%opt) }
2221 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2222 $self->unsuspended_pkgs;
2225 =item cancel [ OPTION => VALUE ... ]
2227 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2229 Available options are:
2233 =item quiet - can be set true to supress email cancellation notices.
2235 =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.
2237 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2239 =item nobill - can be set true to skip billing if it might otherwise be done.
2243 Always returns a list: an empty list on success or a list of errors.
2247 # nb that dates are not specified as valid options to this method
2250 my( $self, %opt ) = @_;
2252 warn "$me cancel called on customer ". $self->custnum. " with options ".
2253 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2256 return ( 'access denied' )
2257 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2259 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2261 #should try decryption (we might have the private key)
2262 # and if not maybe queue a job for the server that does?
2263 return ( "Can't (yet) ban encrypted credit cards" )
2264 if $self->is_encrypted($self->payinfo);
2266 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2267 my $error = $ban->insert;
2268 return ( $error ) if $error;
2272 my @pkgs = $self->ncancelled_pkgs;
2274 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2276 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2277 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2281 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2282 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2285 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2288 sub _banned_pay_hashref {
2299 'payby' => $payby2ban{$self->payby},
2300 'payinfo' => $self->payinfo,
2301 #don't ever *search* on reason! #'reason' =>
2305 sub _new_banned_pay_hashref {
2307 my $hr = $self->_banned_pay_hashref;
2308 $hr->{payinfo} = md5_base64($hr->{payinfo});
2314 Returns all notes (see L<FS::cust_main_note>) for this customer.
2319 my($self,$orderby_classnum) = (shift,shift);
2320 my $orderby = "_DATE DESC";
2321 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2322 qsearch( 'cust_main_note',
2323 { 'custnum' => $self->custnum },
2325 "ORDER BY $orderby",
2331 Returns the agent (see L<FS::agent>) for this customer.
2337 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2342 Returns the agent name (see L<FS::agent>) for this customer.
2348 $self->agent->agent;
2353 Returns any tags associated with this customer, as FS::cust_tag objects,
2354 or an empty list if there are no tags.
2360 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2365 Returns any tags associated with this customer, as FS::part_tag objects,
2366 or an empty list if there are no tags.
2372 map $_->part_tag, $self->cust_tag;
2378 Returns the customer class, as an FS::cust_class object, or the empty string
2379 if there is no customer class.
2385 if ( $self->classnum ) {
2386 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2394 Returns the customer category name, or the empty string if there is no customer
2401 my $cust_class = $self->cust_class;
2403 ? $cust_class->categoryname
2409 Returns the customer class name, or the empty string if there is no customer
2416 my $cust_class = $self->cust_class;
2418 ? $cust_class->classname
2422 =item BILLING METHODS
2424 Documentation on billing methods has been moved to
2425 L<FS::cust_main::Billing>.
2427 =item REALTIME BILLING METHODS
2429 Documentation on realtime billing methods has been moved to
2430 L<FS::cust_main::Billing_Realtime>.
2434 Removes the I<paycvv> field from the database directly.
2436 If there is an error, returns the error, otherwise returns false.
2442 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2443 or return dbh->errstr;
2444 $sth->execute($self->custnum)
2445 or return $sth->errstr;
2450 =item batch_card OPTION => VALUE...
2452 Adds a payment for this invoice to the pending credit card batch (see
2453 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2454 runs the payment using a realtime gateway.
2456 Options may include:
2458 B<amount>: the amount to be paid; defaults to the customer's balance minus
2459 any payments in transit.
2461 B<payby>: the payment method; defaults to cust_main.payby
2463 B<realtime>: runs this as a realtime payment instead of adding it to a
2466 B<invnum>: sets cust_pay_batch.invnum.
2468 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2469 the billing address for the payment; defaults to the customer's billing
2472 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2473 date, and name; defaults to those fields in cust_main.
2478 my ($self, %options) = @_;
2481 if (exists($options{amount})) {
2482 $amount = $options{amount};
2484 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2486 return '' unless $amount > 0;
2488 my $invnum = delete $options{invnum};
2489 my $payby = $options{payby} || $self->payby; #still dubious
2491 if ($options{'realtime'}) {
2492 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2498 my $oldAutoCommit = $FS::UID::AutoCommit;
2499 local $FS::UID::AutoCommit = 0;
2502 #this needs to handle mysql as well as Pg, like svc_acct.pm
2503 #(make it into a common function if folks need to do batching with mysql)
2504 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2505 or return "Cannot lock pay_batch: " . $dbh->errstr;
2509 'payby' => FS::payby->payby2payment($payby),
2511 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2513 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2515 unless ( $pay_batch ) {
2516 $pay_batch = new FS::pay_batch \%pay_batch;
2517 my $error = $pay_batch->insert;
2519 $dbh->rollback if $oldAutoCommit;
2520 die "error creating new batch: $error\n";
2524 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2525 'batchnum' => $pay_batch->batchnum,
2526 'custnum' => $self->custnum,
2529 foreach (qw( address1 address2 city state zip country latitude longitude
2530 payby payinfo paydate payname ))
2532 $options{$_} = '' unless exists($options{$_});
2535 my $loc = $self->bill_location;
2537 my $cust_pay_batch = new FS::cust_pay_batch ( {
2538 'batchnum' => $pay_batch->batchnum,
2539 'invnum' => $invnum || 0, # is there a better value?
2540 # this field should be
2542 # cust_bill_pay_batch now
2543 'custnum' => $self->custnum,
2544 'last' => $self->getfield('last'),
2545 'first' => $self->getfield('first'),
2546 'address1' => $options{address1} || $loc->address1,
2547 'address2' => $options{address2} || $loc->address2,
2548 'city' => $options{city} || $loc->city,
2549 'state' => $options{state} || $loc->state,
2550 'zip' => $options{zip} || $loc->zip,
2551 'country' => $options{country} || $loc->country,
2552 'payby' => $options{payby} || $self->payby,
2553 'payinfo' => $options{payinfo} || $self->payinfo,
2554 'exp' => $options{paydate} || $self->paydate,
2555 'payname' => $options{payname} || $self->payname,
2556 'amount' => $amount, # consolidating
2559 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2560 if $old_cust_pay_batch;
2563 if ($old_cust_pay_batch) {
2564 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2566 $error = $cust_pay_batch->insert;
2570 $dbh->rollback if $oldAutoCommit;
2574 my $unapplied = $self->total_unapplied_credits
2575 + $self->total_unapplied_payments
2576 + $self->in_transit_payments;
2577 foreach my $cust_bill ($self->open_cust_bill) {
2578 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2579 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2580 'invnum' => $cust_bill->invnum,
2581 'paybatchnum' => $cust_pay_batch->paybatchnum,
2582 'amount' => $cust_bill->owed,
2585 if ($unapplied >= $cust_bill_pay_batch->amount){
2586 $unapplied -= $cust_bill_pay_batch->amount;
2589 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2590 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2592 $error = $cust_bill_pay_batch->insert;
2594 $dbh->rollback if $oldAutoCommit;
2599 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2605 Returns the total owed for this customer on all invoices
2606 (see L<FS::cust_bill/owed>).
2612 $self->total_owed_date(2145859200); #12/31/2037
2615 =item total_owed_date TIME
2617 Returns the total owed for this customer 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 {
2627 my $custnum = $self->custnum;
2629 my $owed_sql = FS::cust_bill->owed_sql;
2632 SELECT SUM($owed_sql) FROM cust_bill
2633 WHERE custnum = $custnum
2637 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2641 =item total_owed_pkgnum PKGNUM
2643 Returns the total owed on all invoices for this customer's specific package
2644 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2648 sub total_owed_pkgnum {
2649 my( $self, $pkgnum ) = @_;
2650 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2653 =item total_owed_date_pkgnum TIME PKGNUM
2655 Returns the total owed for this customer's specific package when using
2656 experimental package balances on all invoices with date earlier than
2657 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2658 see L<Time::Local> and L<Date::Parse> for conversion functions.
2662 sub total_owed_date_pkgnum {
2663 my( $self, $time, $pkgnum ) = @_;
2666 foreach my $cust_bill (
2667 grep { $_->_date <= $time }
2668 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2670 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2672 sprintf( "%.2f", $total_bill );
2678 Returns the total amount of all payments.
2685 $total += $_->paid foreach $self->cust_pay;
2686 sprintf( "%.2f", $total );
2689 =item total_unapplied_credits
2691 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2692 customer. See L<FS::cust_credit/credited>.
2694 =item total_credited
2696 Old name for total_unapplied_credits. Don't use.
2700 sub total_credited {
2701 #carp "total_credited deprecated, use total_unapplied_credits";
2702 shift->total_unapplied_credits(@_);
2705 sub total_unapplied_credits {
2708 my $custnum = $self->custnum;
2710 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2713 SELECT SUM($unapplied_sql) FROM cust_credit
2714 WHERE custnum = $custnum
2717 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2721 =item total_unapplied_credits_pkgnum PKGNUM
2723 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2724 customer. See L<FS::cust_credit/credited>.
2728 sub total_unapplied_credits_pkgnum {
2729 my( $self, $pkgnum ) = @_;
2730 my $total_credit = 0;
2731 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2732 sprintf( "%.2f", $total_credit );
2736 =item total_unapplied_payments
2738 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2739 See L<FS::cust_pay/unapplied>.
2743 sub total_unapplied_payments {
2746 my $custnum = $self->custnum;
2748 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2751 SELECT SUM($unapplied_sql) FROM cust_pay
2752 WHERE custnum = $custnum
2755 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2759 =item total_unapplied_payments_pkgnum PKGNUM
2761 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2762 specific package when using experimental package balances. See
2763 L<FS::cust_pay/unapplied>.
2767 sub total_unapplied_payments_pkgnum {
2768 my( $self, $pkgnum ) = @_;
2769 my $total_unapplied = 0;
2770 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2771 sprintf( "%.2f", $total_unapplied );
2775 =item total_unapplied_refunds
2777 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2778 customer. See L<FS::cust_refund/unapplied>.
2782 sub total_unapplied_refunds {
2784 my $custnum = $self->custnum;
2786 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2789 SELECT SUM($unapplied_sql) FROM cust_refund
2790 WHERE custnum = $custnum
2793 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2799 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2800 total_unapplied_credits minus total_unapplied_payments).
2806 $self->balance_date_range;
2809 =item balance_date TIME
2811 Returns the balance for this customer, only considering invoices with date
2812 earlier than TIME (total_owed_date minus total_credited minus
2813 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2814 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2821 $self->balance_date_range(shift);
2824 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2826 Returns the balance for this customer, optionally considering invoices with
2827 date earlier than START_TIME, and not later than END_TIME
2828 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2830 Times are specified as SQL fragments or numeric
2831 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2832 L<Date::Parse> for conversion functions. The empty string can be passed
2833 to disable that time constraint completely.
2835 Available options are:
2839 =item unapplied_date
2841 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)
2847 sub balance_date_range {
2849 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2850 ') FROM cust_main WHERE custnum='. $self->custnum;
2851 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2854 =item balance_pkgnum PKGNUM
2856 Returns the balance for this customer's specific package when using
2857 experimental package balances (total_owed plus total_unrefunded, minus
2858 total_unapplied_credits minus total_unapplied_payments)
2862 sub balance_pkgnum {
2863 my( $self, $pkgnum ) = @_;
2866 $self->total_owed_pkgnum($pkgnum)
2867 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2868 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2869 - $self->total_unapplied_credits_pkgnum($pkgnum)
2870 - $self->total_unapplied_payments_pkgnum($pkgnum)
2874 =item in_transit_payments
2876 Returns the total of requests for payments for this customer pending in
2877 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2881 sub in_transit_payments {
2883 my $in_transit_payments = 0;
2884 foreach my $pay_batch ( qsearch('pay_batch', {
2887 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2888 'batchnum' => $pay_batch->batchnum,
2889 'custnum' => $self->custnum,
2891 $in_transit_payments += $cust_pay_batch->amount;
2894 sprintf( "%.2f", $in_transit_payments );
2899 Returns a hash of useful information for making a payment.
2909 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2910 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2911 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2915 For credit card transactions:
2927 For electronic check transactions:
2942 $return{balance} = $self->balance;
2944 $return{payname} = $self->payname
2945 || ( $self->first. ' '. $self->get('last') );
2947 $return{$_} = $self->bill_location->$_
2948 for qw(address1 address2 city state zip);
2950 $return{payby} = $self->payby;
2951 $return{stateid_state} = $self->stateid_state;
2953 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2954 $return{card_type} = cardtype($self->payinfo);
2955 $return{payinfo} = $self->paymask;
2957 @return{'month', 'year'} = $self->paydate_monthyear;
2961 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2962 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2963 $return{payinfo1} = $payinfo1;
2964 $return{payinfo2} = $payinfo2;
2965 $return{paytype} = $self->paytype;
2966 $return{paystate} = $self->paystate;
2970 #doubleclick protection
2972 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2978 =item paydate_monthyear
2980 Returns a two-element list consisting of the month and year of this customer's
2981 paydate (credit card expiration date for CARD customers)
2985 sub paydate_monthyear {
2987 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2989 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2998 Returns the exact time in seconds corresponding to the payment method
2999 expiration date. For CARD/DCRD customers this is the end of the month;
3000 for others (COMP is the only other payby that uses paydate) it's the start.
3001 Returns 0 if the paydate is empty or set to the far future.
3007 my ($month, $year) = $self->paydate_monthyear;
3008 return 0 if !$year or $year >= 2037;
3009 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3011 if ( $month == 13 ) {
3015 return timelocal(0,0,0,1,$month-1,$year) - 1;
3018 return timelocal(0,0,0,1,$month-1,$year);
3022 =item paydate_epoch_sql
3024 Class method. Returns an SQL expression to obtain the payment expiration date
3025 as a number of seconds.
3029 # Special expiration date behavior for non-CARD/DCRD customers has been
3030 # carefully preserved. Do we really use that?
3031 sub paydate_epoch_sql {
3033 my $table = shift || 'cust_main';
3034 my ($case1, $case2);
3035 if ( driver_name eq 'Pg' ) {
3036 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3037 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3039 elsif ( lc(driver_name) eq 'mysql' ) {
3040 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3041 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3044 return "CASE WHEN $table.payby IN('CARD','DCRD')
3050 =item tax_exemption TAXNAME
3055 my( $self, $taxname ) = @_;
3057 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3058 'taxname' => $taxname,
3063 =item cust_main_exemption
3067 sub cust_main_exemption {
3069 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3072 =item invoicing_list [ ARRAYREF ]
3074 If an arguement is given, sets these email addresses as invoice recipients
3075 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3076 (except as warnings), so use check_invoicing_list first.
3078 Returns a list of email addresses (with svcnum entries expanded).
3080 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3081 check it without disturbing anything by passing nothing.
3083 This interface may change in the future.
3087 sub invoicing_list {
3088 my( $self, $arrayref ) = @_;
3091 my @cust_main_invoice;
3092 if ( $self->custnum ) {
3093 @cust_main_invoice =
3094 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3096 @cust_main_invoice = ();
3098 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3099 #warn $cust_main_invoice->destnum;
3100 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3101 #warn $cust_main_invoice->destnum;
3102 my $error = $cust_main_invoice->delete;
3103 warn $error if $error;
3106 if ( $self->custnum ) {
3107 @cust_main_invoice =
3108 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3110 @cust_main_invoice = ();
3112 my %seen = map { $_->address => 1 } @cust_main_invoice;
3113 foreach my $address ( @{$arrayref} ) {
3114 next if exists $seen{$address} && $seen{$address};
3115 $seen{$address} = 1;
3116 my $cust_main_invoice = new FS::cust_main_invoice ( {
3117 'custnum' => $self->custnum,
3120 my $error = $cust_main_invoice->insert;
3121 warn $error if $error;
3125 if ( $self->custnum ) {
3127 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3134 =item check_invoicing_list ARRAYREF
3136 Checks these arguements as valid input for the invoicing_list method. If there
3137 is an error, returns the error, otherwise returns false.
3141 sub check_invoicing_list {
3142 my( $self, $arrayref ) = @_;
3144 foreach my $address ( @$arrayref ) {
3146 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3147 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3150 my $cust_main_invoice = new FS::cust_main_invoice ( {
3151 'custnum' => $self->custnum,
3154 my $error = $self->custnum
3155 ? $cust_main_invoice->check
3156 : $cust_main_invoice->checkdest
3158 return $error if $error;
3162 return "Email address required"
3163 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3164 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3169 =item set_default_invoicing_list
3171 Sets the invoicing list to all accounts associated with this customer,
3172 overwriting any previous invoicing list.
3176 sub set_default_invoicing_list {
3178 $self->invoicing_list($self->all_emails);
3183 Returns the email addresses of all accounts provisioned for this customer.
3190 foreach my $cust_pkg ( $self->all_pkgs ) {
3191 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3193 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3194 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3196 $list{$_}=1 foreach map { $_->email } @svc_acct;
3201 =item invoicing_list_addpost
3203 Adds postal invoicing to this customer. If this customer is already configured
3204 to receive postal invoices, does nothing.
3208 sub invoicing_list_addpost {
3210 return if grep { $_ eq 'POST' } $self->invoicing_list;
3211 my @invoicing_list = $self->invoicing_list;
3212 push @invoicing_list, 'POST';
3213 $self->invoicing_list(\@invoicing_list);
3216 =item invoicing_list_emailonly
3218 Returns the list of email invoice recipients (invoicing_list without non-email
3219 destinations such as POST and FAX).
3223 sub invoicing_list_emailonly {
3225 warn "$me invoicing_list_emailonly called"
3227 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3230 =item invoicing_list_emailonly_scalar
3232 Returns the list of email invoice recipients (invoicing_list without non-email
3233 destinations such as POST and FAX) as a comma-separated scalar.
3237 sub invoicing_list_emailonly_scalar {
3239 warn "$me invoicing_list_emailonly_scalar called"
3241 join(', ', $self->invoicing_list_emailonly);
3244 =item referral_custnum_cust_main
3246 Returns the customer who referred this customer (or the empty string, if
3247 this customer was not referred).
3249 Note the difference with referral_cust_main method: This method,
3250 referral_custnum_cust_main returns the single customer (if any) who referred
3251 this customer, while referral_cust_main returns an array of customers referred
3256 sub referral_custnum_cust_main {
3258 return '' unless $self->referral_custnum;
3259 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3262 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3264 Returns an array of customers referred by this customer (referral_custnum set
3265 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3266 customers referred by customers referred by this customer and so on, inclusive.
3267 The default behavior is DEPTH 1 (no recursion).
3269 Note the difference with referral_custnum_cust_main method: This method,
3270 referral_cust_main, returns an array of customers referred BY this customer,
3271 while referral_custnum_cust_main returns the single customer (if any) who
3272 referred this customer.
3276 sub referral_cust_main {
3278 my $depth = @_ ? shift : 1;
3279 my $exclude = @_ ? shift : {};
3282 map { $exclude->{$_->custnum}++; $_; }
3283 grep { ! $exclude->{ $_->custnum } }
3284 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3288 map { $_->referral_cust_main($depth-1, $exclude) }
3295 =item referral_cust_main_ncancelled
3297 Same as referral_cust_main, except only returns customers with uncancelled
3302 sub referral_cust_main_ncancelled {
3304 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3307 =item referral_cust_pkg [ DEPTH ]
3309 Like referral_cust_main, except returns a flat list of all unsuspended (and
3310 uncancelled) packages for each customer. The number of items in this list may
3311 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3315 sub referral_cust_pkg {
3317 my $depth = @_ ? shift : 1;
3319 map { $_->unsuspended_pkgs }
3320 grep { $_->unsuspended_pkgs }
3321 $self->referral_cust_main($depth);
3324 =item referring_cust_main
3326 Returns the single cust_main record for the customer who referred this customer
3327 (referral_custnum), or false.
3331 sub referring_cust_main {
3333 return '' unless $self->referral_custnum;
3334 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3337 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3339 Applies a credit to this customer. If there is an error, returns the error,
3340 otherwise returns false.
3342 REASON can be a text string, an FS::reason object, or a scalar reference to
3343 a reasonnum. If a text string, it will be automatically inserted as a new
3344 reason, and a 'reason_type' option must be passed to indicate the
3345 FS::reason_type for the new reason.
3347 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3348 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3349 I<commission_pkgnum>.
3351 Any other options are passed to FS::cust_credit::insert.
3356 my( $self, $amount, $reason, %options ) = @_;
3358 my $cust_credit = new FS::cust_credit {
3359 'custnum' => $self->custnum,
3360 'amount' => $amount,
3363 if ( ref($reason) ) {
3365 if ( ref($reason) eq 'SCALAR' ) {
3366 $cust_credit->reasonnum( $$reason );
3368 $cust_credit->reasonnum( $reason->reasonnum );
3372 $cust_credit->set('reason', $reason)
3375 $cust_credit->$_( delete $options{$_} )
3376 foreach grep exists($options{$_}),
3377 qw( addlinfo eventnum ),
3378 map "commission_$_", qw( agentnum salesnum pkgnum );
3380 $cust_credit->insert(%options);
3384 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3386 Creates a one-time charge for this customer. If there is an error, returns
3387 the error, otherwise returns false.
3389 New-style, with a hashref of options:
3391 my $error = $cust_main->charge(
3395 'start_date' => str2time('7/4/2009'),
3396 'pkg' => 'Description',
3397 'comment' => 'Comment',
3398 'additional' => [], #extra invoice detail
3399 'classnum' => 1, #pkg_class
3401 'setuptax' => '', # or 'Y' for tax exempt
3403 'locationnum'=> 1234, # optional
3406 'taxclass' => 'Tax class',
3409 'taxproduct' => 2, #part_pkg_taxproduct
3410 'override' => {}, #XXX describe
3412 #will be filled in with the new object
3413 'cust_pkg_ref' => \$cust_pkg,
3415 #generate an invoice immediately
3417 'invoice_terms' => '', #with these terms
3423 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3429 my ( $amount, $quantity, $start_date, $classnum );
3430 my ( $pkg, $comment, $additional );
3431 my ( $setuptax, $taxclass ); #internal taxes
3432 my ( $taxproduct, $override ); #vendor (CCH) taxes
3434 my $cust_pkg_ref = '';
3435 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3437 if ( ref( $_[0] ) ) {
3438 $amount = $_[0]->{amount};
3439 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3440 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3441 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3442 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3443 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3444 : '$'. sprintf("%.2f",$amount);
3445 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3446 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3447 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3448 $additional = $_[0]->{additional} || [];
3449 $taxproduct = $_[0]->{taxproductnum};
3450 $override = { '' => $_[0]->{tax_override} };
3451 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3452 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3453 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3454 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3459 $pkg = @_ ? shift : 'One-time charge';
3460 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3462 $taxclass = @_ ? shift : '';
3466 local $SIG{HUP} = 'IGNORE';
3467 local $SIG{INT} = 'IGNORE';
3468 local $SIG{QUIT} = 'IGNORE';
3469 local $SIG{TERM} = 'IGNORE';
3470 local $SIG{TSTP} = 'IGNORE';
3471 local $SIG{PIPE} = 'IGNORE';
3473 my $oldAutoCommit = $FS::UID::AutoCommit;
3474 local $FS::UID::AutoCommit = 0;
3477 my $part_pkg = new FS::part_pkg ( {
3479 'comment' => $comment,
3483 'classnum' => ( $classnum ? $classnum : '' ),
3484 'setuptax' => $setuptax,
3485 'taxclass' => $taxclass,
3486 'taxproductnum' => $taxproduct,
3489 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3490 ( 0 .. @$additional - 1 )
3492 'additional_count' => scalar(@$additional),
3493 'setup_fee' => $amount,
3496 my $error = $part_pkg->insert( options => \%options,
3497 tax_overrides => $override,
3500 $dbh->rollback if $oldAutoCommit;
3504 my $pkgpart = $part_pkg->pkgpart;
3505 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3506 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3507 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3508 $error = $type_pkgs->insert;
3510 $dbh->rollback if $oldAutoCommit;
3515 my $cust_pkg = new FS::cust_pkg ( {
3516 'custnum' => $self->custnum,
3517 'pkgpart' => $pkgpart,
3518 'quantity' => $quantity,
3519 'start_date' => $start_date,
3520 'no_auto' => $no_auto,
3521 'locationnum'=> $locationnum,
3524 $error = $cust_pkg->insert;
3526 $dbh->rollback if $oldAutoCommit;
3528 } elsif ( $cust_pkg_ref ) {
3529 ${$cust_pkg_ref} = $cust_pkg;
3533 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3534 'pkg_list' => [ $cust_pkg ],
3537 $dbh->rollback if $oldAutoCommit;
3542 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3547 #=item charge_postal_fee
3549 #Applies a one time charge this customer. If there is an error,
3550 #returns the error, returns the cust_pkg charge object or false
3551 #if there was no charge.
3555 # This should be a customer event. For that to work requires that bill
3556 # also be a customer event.
3558 sub charge_postal_fee {
3561 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3562 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3564 my $cust_pkg = new FS::cust_pkg ( {
3565 'custnum' => $self->custnum,
3566 'pkgpart' => $pkgpart,
3570 my $error = $cust_pkg->insert;
3571 $error ? $error : $cust_pkg;
3574 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3576 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3578 Optionally, a list or hashref of additional arguments to the qsearch call can
3585 my $opt = ref($_[0]) ? shift : { @_ };
3587 #return $self->num_cust_bill unless wantarray || keys %$opt;
3589 $opt->{'table'} = 'cust_bill';
3590 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3591 $opt->{'hashref'}{'custnum'} = $self->custnum;
3592 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3594 map { $_ } #behavior of sort undefined in scalar context
3595 sort { $a->_date <=> $b->_date }
3599 =item open_cust_bill
3601 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3606 sub open_cust_bill {
3610 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3616 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3618 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3622 sub legacy_cust_bill {
3625 #return $self->num_legacy_cust_bill unless wantarray;
3627 map { $_ } #behavior of sort undefined in scalar context
3628 sort { $a->_date <=> $b->_date }
3629 qsearch({ 'table' => 'legacy_cust_bill',
3630 'hashref' => { 'custnum' => $self->custnum, },
3631 'order_by' => 'ORDER BY _date ASC',
3635 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3637 Returns all the statements (see L<FS::cust_statement>) for this customer.
3639 Optionally, a list or hashref of additional arguments to the qsearch call can
3644 =item cust_bill_void
3646 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3650 sub cust_bill_void {
3653 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3654 sort { $a->_date <=> $b->_date }
3655 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3658 sub cust_statement {
3660 my $opt = ref($_[0]) ? shift : { @_ };
3662 #return $self->num_cust_statement unless wantarray || keys %$opt;
3664 $opt->{'table'} = 'cust_statement';
3665 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3666 $opt->{'hashref'}{'custnum'} = $self->custnum;
3667 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3669 map { $_ } #behavior of sort undefined in scalar context
3670 sort { $a->_date <=> $b->_date }
3674 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3676 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3678 Optionally, a list or hashref of additional arguments to the qsearch call can
3679 be passed following the SVCDB.
3686 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3687 warn "$me svc_x requires a svcdb";
3690 my $opt = ref($_[0]) ? shift : { @_ };
3692 $opt->{'table'} = $svcdb;
3693 $opt->{'addl_from'} =
3694 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3695 ($opt->{'addl_from'} || '');
3697 my $custnum = $self->custnum;
3698 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3699 my $where = "cust_pkg.custnum = $custnum";
3701 my $extra_sql = $opt->{'extra_sql'} || '';
3702 if ( keys %{ $opt->{'hashref'} } ) {
3703 $extra_sql = " AND $where $extra_sql";
3706 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3707 $extra_sql = "WHERE $where AND $1";
3710 $extra_sql = "WHERE $where $extra_sql";
3713 $opt->{'extra_sql'} = $extra_sql;
3718 # required for use as an eventtable;
3721 $self->svc_x('svc_acct', @_);
3726 Returns all the credits (see L<FS::cust_credit>) for this customer.
3732 map { $_ } #return $self->num_cust_credit unless wantarray;
3733 sort { $a->_date <=> $b->_date }
3734 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3737 =item cust_credit_pkgnum
3739 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3740 package when using experimental package balances.
3744 sub cust_credit_pkgnum {
3745 my( $self, $pkgnum ) = @_;
3746 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3747 sort { $a->_date <=> $b->_date }
3748 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3749 'pkgnum' => $pkgnum,
3754 =item cust_credit_void
3756 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3760 sub cust_credit_void {
3763 sort { $a->_date <=> $b->_date }
3764 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3769 Returns all the payments (see L<FS::cust_pay>) for this customer.
3775 return $self->num_cust_pay unless wantarray;
3776 sort { $a->_date <=> $b->_date }
3777 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3782 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3783 called automatically when the cust_pay method is used in a scalar context.
3789 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3790 my $sth = dbh->prepare($sql) or die dbh->errstr;
3791 $sth->execute($self->custnum) or die $sth->errstr;
3792 $sth->fetchrow_arrayref->[0];
3795 =item cust_pay_pkgnum
3797 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3798 package when using experimental package balances.
3802 sub cust_pay_pkgnum {
3803 my( $self, $pkgnum ) = @_;
3804 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3805 sort { $a->_date <=> $b->_date }
3806 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3807 'pkgnum' => $pkgnum,
3814 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3820 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3821 sort { $a->_date <=> $b->_date }
3822 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3825 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3827 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3829 Optionally, a list or hashref of additional arguments to the qsearch call can
3834 sub cust_pay_batch {
3836 my $opt = ref($_[0]) ? shift : { @_ };
3838 #return $self->num_cust_statement unless wantarray || keys %$opt;
3840 $opt->{'table'} = 'cust_pay_batch';
3841 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3842 $opt->{'hashref'}{'custnum'} = $self->custnum;
3843 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3845 map { $_ } #behavior of sort undefined in scalar context
3846 sort { $a->paybatchnum <=> $b->paybatchnum }
3850 =item cust_pay_pending
3852 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3853 (without status "done").
3857 sub cust_pay_pending {
3859 return $self->num_cust_pay_pending unless wantarray;
3860 sort { $a->_date <=> $b->_date }
3861 qsearch( 'cust_pay_pending', {
3862 'custnum' => $self->custnum,
3863 'status' => { op=>'!=', value=>'done' },
3868 =item cust_pay_pending_attempt
3870 Returns all payment attempts / declined payments for this customer, as pending
3871 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3872 a corresponding payment (see L<FS::cust_pay>).
3876 sub cust_pay_pending_attempt {
3878 return $self->num_cust_pay_pending_attempt unless wantarray;
3879 sort { $a->_date <=> $b->_date }
3880 qsearch( 'cust_pay_pending', {
3881 'custnum' => $self->custnum,
3888 =item num_cust_pay_pending
3890 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3891 customer (without status "done"). Also called automatically when the
3892 cust_pay_pending method is used in a scalar context.
3896 sub num_cust_pay_pending {
3899 " SELECT COUNT(*) FROM cust_pay_pending ".
3900 " WHERE custnum = ? AND status != 'done' ",
3905 =item num_cust_pay_pending_attempt
3907 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3908 customer, with status "done" but without a corresp. Also called automatically when the
3909 cust_pay_pending method is used in a scalar context.
3913 sub num_cust_pay_pending_attempt {
3916 " SELECT COUNT(*) FROM cust_pay_pending ".
3917 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3924 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3930 map { $_ } #return $self->num_cust_refund unless wantarray;
3931 sort { $a->_date <=> $b->_date }
3932 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3935 =item display_custnum
3937 Returns the displayed customer number for this customer: agent_custid if
3938 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3942 sub display_custnum {
3945 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3946 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3947 if ( $special eq 'CoStAg' ) {
3948 $prefix = uc( join('',
3950 ($self->state =~ /^(..)/),
3951 $prefix || ($self->agent->agent =~ /^(..)/)
3954 elsif ( $special eq 'CoStCl' ) {
3955 $prefix = uc( join('',
3957 ($self->state =~ /^(..)/),
3958 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3961 # add any others here if needed
3964 my $length = $conf->config('cust_main-custnum-display_length');
3965 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3966 return $self->agent_custid;
3967 } elsif ( $prefix ) {
3968 $length = 8 if !defined($length);
3970 sprintf('%0'.$length.'d', $self->custnum)
3971 } elsif ( $length ) {
3972 return sprintf('%0'.$length.'d', $self->custnum);
3974 return $self->custnum;
3980 Returns a name string for this customer, either "Company (Last, First)" or
3987 my $name = $self->contact;
3988 $name = $self->company. " ($name)" if $self->company;
3992 =item service_contact
3994 Returns the L<FS::contact> object for this customer that has the 'Service'
3995 contact class, or undef if there is no such contact. Deprecated; don't use
4000 sub service_contact {
4002 if ( !exists($self->{service_contact}) ) {
4003 my $classnum = $self->scalar_sql(
4004 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4005 ) || 0; #if it's zero, qsearchs will return nothing
4006 $self->{service_contact} = qsearchs('contact', {
4007 'classnum' => $classnum, 'custnum' => $self->custnum
4010 $self->{service_contact};
4015 Returns a name string for this (service/shipping) contact, either
4016 "Company (Last, First)" or "Last, First".
4023 my $name = $self->ship_contact;
4024 $name = $self->company. " ($name)" if $self->company;
4030 Returns a name string for this customer, either "Company" or "First Last".
4036 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4039 =item ship_name_short
4041 Returns a name string for this (service/shipping) contact, either "Company"
4046 sub ship_name_short {
4048 $self->service_contact
4049 ? $self->ship_contact_firstlast
4055 Returns this customer's full (billing) contact name only, "Last, First"
4061 $self->get('last'). ', '. $self->first;
4066 Returns this customer's full (shipping) contact name only, "Last, First"
4072 my $contact = $self->service_contact || $self;
4073 $contact->get('last') . ', ' . $contact->get('first');
4076 =item contact_firstlast
4078 Returns this customers full (billing) contact name only, "First Last".
4082 sub contact_firstlast {
4084 $self->first. ' '. $self->get('last');
4087 =item ship_contact_firstlast
4089 Returns this customer's full (shipping) contact name only, "First Last".
4093 sub ship_contact_firstlast {
4095 my $contact = $self->service_contact || $self;
4096 $contact->get('first') . ' '. $contact->get('last');
4099 #XXX this doesn't work in 3.x+
4102 #Returns this customer's full country name
4108 # code2country($self->country);
4111 sub bill_country_full {
4113 code2country($self->bill_location->country);
4116 sub ship_country_full {
4118 code2country($self->ship_location->country);
4121 =item county_state_county [ PREFIX ]
4123 Returns a string consisting of just the county, state and country.
4127 sub county_state_country {
4130 if ( @_ && $_[0] && $self->has_ship_address ) {
4131 $locationnum = $self->ship_locationnum;
4133 $locationnum = $self->bill_locationnum;
4135 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4136 $cust_location->county_state_country;
4139 =item geocode DATA_VENDOR
4141 Returns a value for the customer location as encoded by DATA_VENDOR.
4142 Currently this only makes sense for "CCH" as DATA_VENDOR.
4150 Returns a status string for this customer, currently:
4154 =item prospect - No packages have ever been ordered
4156 =item ordered - Recurring packages all are new (not yet billed).
4158 =item active - One or more recurring packages is active
4160 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4162 =item suspended - All non-cancelled recurring packages are suspended
4164 =item cancelled - All recurring packages are cancelled
4168 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4169 cust_main-status_module configuration option.
4173 sub status { shift->cust_status(@_); }
4177 for my $status ( FS::cust_main->statuses() ) {
4178 my $method = $status.'_sql';
4179 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4180 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4181 $sth->execute( ($self->custnum) x $numnum )
4182 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4183 return $status if $sth->fetchrow_arrayref->[0];
4187 =item ucfirst_cust_status
4189 =item ucfirst_status
4191 Returns the status with the first character capitalized.
4195 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4197 sub ucfirst_cust_status {
4199 ucfirst($self->cust_status);
4204 Returns a hex triplet color string for this customer's status.
4208 sub statuscolor { shift->cust_statuscolor(@_); }
4210 sub cust_statuscolor {
4212 __PACKAGE__->statuscolors->{$self->cust_status};
4215 =item tickets [ STATUS ]
4217 Returns an array of hashes representing the customer's RT tickets.
4219 An optional status (or arrayref or hashref of statuses) may be specified.
4225 my $status = ( @_ && $_[0] ) ? shift : '';
4227 my $num = $conf->config('cust_main-max_tickets') || 10;
4230 if ( $conf->config('ticket_system') ) {
4231 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4233 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4242 foreach my $priority (
4243 $conf->config('ticket_system-custom_priority_field-values'), ''
4245 last if scalar(@tickets) >= $num;
4247 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4248 $num - scalar(@tickets),
4259 # Return services representing svc_accts in customer support packages
4260 sub support_services {
4262 my %packages = map { $_ => 1 } $conf->config('support_packages');
4264 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4265 grep { $_->part_svc->svcdb eq 'svc_acct' }
4266 map { $_->cust_svc }
4267 grep { exists $packages{ $_->pkgpart } }
4268 $self->ncancelled_pkgs;
4272 # Return a list of latitude/longitude for one of the services (if any)
4273 sub service_coordinates {
4277 grep { $_->latitude && $_->longitude }
4279 map { $_->cust_svc }
4280 $self->ncancelled_pkgs;
4282 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4287 Returns a masked version of the named field
4292 my ($self,$field) = @_;
4296 'x'x(length($self->getfield($field))-4).
4297 substr($self->getfield($field), (length($self->getfield($field))-4));
4303 =head1 CLASS METHODS
4309 Class method that returns the list of possible status strings for customers
4310 (see L<the status method|/status>). For example:
4312 @statuses = FS::cust_main->statuses();
4318 keys %{ $self->statuscolors };
4321 =item cust_status_sql
4323 Returns an SQL fragment to determine the status of a cust_main record, as a
4328 sub cust_status_sql {
4330 for my $status ( FS::cust_main->statuses() ) {
4331 my $method = $status.'_sql';
4332 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4341 Returns an SQL expression identifying prospective cust_main records (customers
4342 with no packages ever ordered)
4346 use vars qw($select_count_pkgs);
4347 $select_count_pkgs =
4348 "SELECT COUNT(*) FROM cust_pkg
4349 WHERE cust_pkg.custnum = cust_main.custnum";
4351 sub select_count_pkgs_sql {
4356 " 0 = ( $select_count_pkgs ) ";
4361 Returns an SQL expression identifying ordered cust_main records (customers with
4362 no active packages, but recurring packages not yet setup or one time charges
4368 FS::cust_main->none_active_sql.
4369 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4374 Returns an SQL expression identifying active cust_main records (customers with
4375 active recurring packages).
4380 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4383 =item none_active_sql
4385 Returns an SQL expression identifying cust_main records with no active
4386 recurring packages. This includes customers of status prospect, ordered,
4387 inactive, and suspended.
4391 sub none_active_sql {
4392 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4397 Returns an SQL expression identifying inactive cust_main records (customers with
4398 no active recurring packages, but otherwise unsuspended/uncancelled).
4403 FS::cust_main->none_active_sql.
4404 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4410 Returns an SQL expression identifying suspended cust_main records.
4415 sub suspended_sql { susp_sql(@_); }
4417 FS::cust_main->none_active_sql.
4418 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4424 Returns an SQL expression identifying cancelled cust_main records.
4428 sub cancel_sql { shift->cancelled_sql(@_); }
4431 =item uncancelled_sql
4433 Returns an SQL expression identifying un-cancelled cust_main records.
4437 sub uncancelled_sql { uncancel_sql(@_); }
4438 sub uncancel_sql { "
4439 ( 0 < ( $select_count_pkgs
4440 AND ( cust_pkg.cancel IS NULL
4441 OR cust_pkg.cancel = 0
4444 OR 0 = ( $select_count_pkgs )
4450 Returns an SQL fragment to retreive the balance.
4455 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4456 WHERE cust_bill.custnum = cust_main.custnum )
4457 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4458 WHERE cust_pay.custnum = cust_main.custnum )
4459 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4460 WHERE cust_credit.custnum = cust_main.custnum )
4461 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4462 WHERE cust_refund.custnum = cust_main.custnum )
4465 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4467 Returns an SQL fragment to retreive the balance for this customer, optionally
4468 considering invoices with date earlier than START_TIME, and not
4469 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4470 total_unapplied_payments).
4472 Times are specified as SQL fragments or numeric
4473 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4474 L<Date::Parse> for conversion functions. The empty string can be passed
4475 to disable that time constraint completely.
4477 Available options are:
4481 =item unapplied_date
4483 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)
4488 set to true to remove all customer comparison clauses, for totals
4493 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4498 JOIN clause (typically used with the total option)
4502 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4503 time will be ignored. Note that START_TIME and END_TIME only limit the date
4504 range for invoices and I<unapplied> payments, credits, and refunds.
4510 sub balance_date_sql {
4511 my( $class, $start, $end, %opt ) = @_;
4513 my $cutoff = $opt{'cutoff'};
4515 my $owed = FS::cust_bill->owed_sql($cutoff);
4516 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4517 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4518 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4520 my $j = $opt{'join'} || '';
4522 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4523 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4524 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4525 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4527 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4528 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4529 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4530 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4535 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4537 Returns an SQL fragment to retreive the total unapplied payments for this
4538 customer, only considering payments with date earlier than START_TIME, and
4539 optionally not later than END_TIME.
4541 Times are specified as SQL fragments or numeric
4542 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4543 L<Date::Parse> for conversion functions. The empty string can be passed
4544 to disable that time constraint completely.
4546 Available options are:
4550 sub unapplied_payments_date_sql {
4551 my( $class, $start, $end, %opt ) = @_;
4553 my $cutoff = $opt{'cutoff'};
4555 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4557 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4558 'unapplied_date'=>1 );
4560 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4563 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4565 Helper method for balance_date_sql; name (and usage) subject to change
4566 (suggestions welcome).
4568 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4569 cust_refund, cust_credit or cust_pay).
4571 If TABLE is "cust_bill" or the unapplied_date option is true, only
4572 considers records with date earlier than START_TIME, and optionally not
4573 later than END_TIME .
4577 sub _money_table_where {
4578 my( $class, $table, $start, $end, %opt ) = @_;
4581 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4582 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4583 push @where, "$table._date <= $start" if defined($start) && length($start);
4584 push @where, "$table._date > $end" if defined($end) && length($end);
4586 push @where, @{$opt{'where'}} if $opt{'where'};
4587 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4593 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4594 use FS::cust_main::Search;
4597 FS::cust_main::Search->search(@_);
4612 #warn join('-',keys %$param);
4613 my $fh = $param->{filehandle};
4614 my $agentnum = $param->{agentnum};
4615 my $format = $param->{format};
4617 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4620 if ( $format eq 'simple' ) {
4621 @fields = qw( custnum agent_custid amount pkg );
4623 die "unknown format $format";
4626 eval "use Text::CSV_XS;";
4629 my $csv = new Text::CSV_XS;
4636 local $SIG{HUP} = 'IGNORE';
4637 local $SIG{INT} = 'IGNORE';
4638 local $SIG{QUIT} = 'IGNORE';
4639 local $SIG{TERM} = 'IGNORE';
4640 local $SIG{TSTP} = 'IGNORE';
4641 local $SIG{PIPE} = 'IGNORE';
4643 my $oldAutoCommit = $FS::UID::AutoCommit;
4644 local $FS::UID::AutoCommit = 0;
4647 #while ( $columns = $csv->getline($fh) ) {
4649 while ( defined($line=<$fh>) ) {
4651 $csv->parse($line) or do {
4652 $dbh->rollback if $oldAutoCommit;
4653 return "can't parse: ". $csv->error_input();
4656 my @columns = $csv->fields();
4657 #warn join('-',@columns);
4660 foreach my $field ( @fields ) {
4661 $row{$field} = shift @columns;
4664 if ( $row{custnum} && $row{agent_custid} ) {
4665 dbh->rollback if $oldAutoCommit;
4666 return "can't specify custnum with agent_custid $row{agent_custid}";
4670 if ( $row{agent_custid} && $agentnum ) {
4671 %hash = ( 'agent_custid' => $row{agent_custid},
4672 'agentnum' => $agentnum,
4676 if ( $row{custnum} ) {
4677 %hash = ( 'custnum' => $row{custnum} );
4680 unless ( scalar(keys %hash) ) {
4681 $dbh->rollback if $oldAutoCommit;
4682 return "can't find customer without custnum or agent_custid and agentnum";
4685 my $cust_main = qsearchs('cust_main', { %hash } );
4686 unless ( $cust_main ) {
4687 $dbh->rollback if $oldAutoCommit;
4688 my $custnum = $row{custnum} || $row{agent_custid};
4689 return "unknown custnum $custnum";
4692 if ( $row{'amount'} > 0 ) {
4693 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4695 $dbh->rollback if $oldAutoCommit;
4699 } elsif ( $row{'amount'} < 0 ) {
4700 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4703 $dbh->rollback if $oldAutoCommit;
4713 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4715 return "Empty file!" unless $imported;
4721 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4723 Deprecated. Use event notification and message templates
4724 (L<FS::msg_template>) instead.
4726 Sends a templated email notification to the customer (see L<Text::Template>).
4728 OPTIONS is a hash and may include
4730 I<from> - the email sender (default is invoice_from)
4732 I<to> - comma-separated scalar or arrayref of recipients
4733 (default is invoicing_list)
4735 I<subject> - The subject line of the sent email notification
4736 (default is "Notice from company_name")
4738 I<extra_fields> - a hashref of name/value pairs which will be substituted
4741 The following variables are vavailable in the template.
4743 I<$first> - the customer first name
4744 I<$last> - the customer last name
4745 I<$company> - the customer company
4746 I<$payby> - a description of the method of payment for the customer
4747 # would be nice to use FS::payby::shortname
4748 I<$payinfo> - the account information used to collect for this customer
4749 I<$expdate> - the expiration of the customer payment in seconds from epoch
4754 my ($self, $template, %options) = @_;
4756 return unless $conf->exists($template);
4758 my $from = $conf->config('invoice_from', $self->agentnum)
4759 if $conf->exists('invoice_from', $self->agentnum);
4760 $from = $options{from} if exists($options{from});
4762 my $to = join(',', $self->invoicing_list_emailonly);
4763 $to = $options{to} if exists($options{to});
4765 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4766 if $conf->exists('company_name', $self->agentnum);
4767 $subject = $options{subject} if exists($options{subject});
4769 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4770 SOURCE => [ map "$_\n",
4771 $conf->config($template)]
4773 or die "can't create new Text::Template object: Text::Template::ERROR";
4774 $notify_template->compile()
4775 or die "can't compile template: Text::Template::ERROR";
4777 $FS::notify_template::_template::company_name =
4778 $conf->config('company_name', $self->agentnum);
4779 $FS::notify_template::_template::company_address =
4780 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4782 my $paydate = $self->paydate || '2037-12-31';
4783 $FS::notify_template::_template::first = $self->first;
4784 $FS::notify_template::_template::last = $self->last;
4785 $FS::notify_template::_template::company = $self->company;
4786 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4787 my $payby = $self->payby;
4788 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4789 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4791 #credit cards expire at the end of the month/year of their exp date
4792 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4793 $FS::notify_template::_template::payby = 'credit card';
4794 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4795 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4797 }elsif ($payby eq 'COMP') {
4798 $FS::notify_template::_template::payby = 'complimentary account';
4800 $FS::notify_template::_template::payby = 'current method';
4802 $FS::notify_template::_template::expdate = $expire_time;
4804 for (keys %{$options{extra_fields}}){
4806 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4809 send_email(from => $from,
4811 subject => $subject,
4812 body => $notify_template->fill_in( PACKAGE =>
4813 'FS::notify_template::_template' ),
4818 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4820 Generates a templated notification to the customer (see L<Text::Template>).
4822 OPTIONS is a hash and may include
4824 I<extra_fields> - a hashref of name/value pairs which will be substituted
4825 into the template. These values may override values mentioned below
4826 and those from the customer record.
4828 The following variables are available in the template instead of or in addition
4829 to the fields of the customer record.
4831 I<$payby> - a description of the method of payment for the customer
4832 # would be nice to use FS::payby::shortname
4833 I<$payinfo> - the masked account information used to collect for this customer
4834 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4835 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4839 # a lot like cust_bill::print_latex
4840 sub generate_letter {
4841 my ($self, $template, %options) = @_;
4843 return unless $conf->exists($template);
4845 my $letter_template = new Text::Template
4847 SOURCE => [ map "$_\n", $conf->config($template)],
4848 DELIMITERS => [ '[@--', '--@]' ],
4850 or die "can't create new Text::Template object: Text::Template::ERROR";
4852 $letter_template->compile()
4853 or die "can't compile template: Text::Template::ERROR";
4855 my %letter_data = map { $_ => $self->$_ } $self->fields;
4856 $letter_data{payinfo} = $self->mask_payinfo;
4858 #my $paydate = $self->paydate || '2037-12-31';
4859 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4861 my $payby = $self->payby;
4862 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4863 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4865 #credit cards expire at the end of the month/year of their exp date
4866 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4867 $letter_data{payby} = 'credit card';
4868 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4869 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4871 }elsif ($payby eq 'COMP') {
4872 $letter_data{payby} = 'complimentary account';
4874 $letter_data{payby} = 'current method';
4876 $letter_data{expdate} = $expire_time;
4878 for (keys %{$options{extra_fields}}){
4879 $letter_data{$_} = $options{extra_fields}->{$_};
4882 unless(exists($letter_data{returnaddress})){
4883 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4884 $self->agent_template)
4886 if ( length($retadd) ) {
4887 $letter_data{returnaddress} = $retadd;
4888 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4889 $letter_data{returnaddress} =
4890 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4894 ( $conf->config('company_name', $self->agentnum),
4895 $conf->config('company_address', $self->agentnum),
4899 $letter_data{returnaddress} = '~';
4903 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4905 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4907 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4909 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4913 ) or die "can't open temp file: $!\n";
4914 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4915 or die "can't write temp file: $!\n";
4917 $letter_data{'logo_file'} = $lh->filename;
4919 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4923 ) or die "can't open temp file: $!\n";
4925 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4927 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4928 return ($1, $letter_data{'logo_file'});
4932 =item print_ps TEMPLATE
4934 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4940 my($file, $lfile) = $self->generate_letter(@_);
4941 my $ps = FS::Misc::generate_ps($file);
4942 unlink($file.'.tex');
4948 =item print TEMPLATE
4950 Prints the filled in template.
4952 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4956 sub queueable_print {
4959 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4960 or die "invalid customer number: " . $opt{custnum};
4962 my $error = $self->print( { 'template' => $opt{template} } );
4963 die $error if $error;
4967 my ($self, $template) = (shift, shift);
4969 [ $self->print_ps($template) ],
4970 'agentnum' => $self->agentnum,
4974 #these three subs should just go away once agent stuff is all config overrides
4976 sub agent_template {
4978 $self->_agent_plandata('agent_templatename');
4981 sub agent_invoice_from {
4983 $self->_agent_plandata('agent_invoice_from');
4986 sub _agent_plandata {
4987 my( $self, $option ) = @_;
4989 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4990 #agent-specific Conf
4992 use FS::part_event::Condition;
4994 my $agentnum = $self->agentnum;
4996 my $regexp = regexp_sql();
4998 my $part_event_option =
5000 'select' => 'part_event_option.*',
5001 'table' => 'part_event_option',
5003 LEFT JOIN part_event USING ( eventpart )
5004 LEFT JOIN part_event_option AS peo_agentnum
5005 ON ( part_event.eventpart = peo_agentnum.eventpart
5006 AND peo_agentnum.optionname = 'agentnum'
5007 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5009 LEFT JOIN part_event_condition
5010 ON ( part_event.eventpart = part_event_condition.eventpart
5011 AND part_event_condition.conditionname = 'cust_bill_age'
5013 LEFT JOIN part_event_condition_option
5014 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5015 AND part_event_condition_option.optionname = 'age'
5018 #'hashref' => { 'optionname' => $option },
5019 #'hashref' => { 'part_event_option.optionname' => $option },
5021 " WHERE part_event_option.optionname = ". dbh->quote($option).
5022 " AND action = 'cust_bill_send_agent' ".
5023 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5024 " AND peo_agentnum.optionname = 'agentnum' ".
5025 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5027 CASE WHEN part_event_condition_option.optionname IS NULL
5029 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5031 , part_event.weight".
5035 unless ( $part_event_option ) {
5036 return $self->agent->invoice_template || ''
5037 if $option eq 'agent_templatename';
5041 $part_event_option->optionvalue;
5045 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5047 Subroutine (not a method), designed to be called from the queue.
5049 Takes a list of options and values.
5051 Pulls up the customer record via the custnum option and calls bill_and_collect.
5056 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5058 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5059 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5061 $cust_main->bill_and_collect( %args );
5064 sub process_bill_and_collect {
5066 my $param = thaw(decode_base64(shift));
5067 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5068 or die "custnum '$param->{custnum}' not found!\n";
5069 $param->{'job'} = $job;
5070 $param->{'fatal'} = 1; # runs from job queue, will be caught
5071 $param->{'retry'} = 1;
5073 $cust_main->bill_and_collect( %$param );
5076 #starting to take quite a while for big dbs
5077 # (JRNL: journaled so it only happens once per database)
5078 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5079 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5080 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5081 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5082 # JRNL leading/trailing spaces in first, last, company
5083 # JRNL migrate to cust_payby
5084 # - otaker upgrade? journal and call it good? (double check to make sure
5085 # we're not still setting otaker here)
5087 #only going to get worse with new location stuff...
5089 sub _upgrade_data { #class method
5090 my ($class, %opts) = @_;
5093 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5096 #this seems to be the only expensive one.. why does it take so long?
5097 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5099 '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';
5100 FS::upgrade_journal->set_done('cust_main__signupdate');
5103 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5105 # fix yyyy-m-dd formatted paydates
5106 if ( driver_name =~ /^mysql/i ) {
5108 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5109 } else { # the SQL standard
5111 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5113 FS::upgrade_journal->set_done('cust_main__paydate');
5116 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5118 push @statements, #fix the weird BILL with a cc# in payinfo problem
5120 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5122 FS::upgrade_journal->set_done('cust_main__payinfo');
5127 foreach my $sql ( @statements ) {
5128 my $sth = dbh->prepare($sql) or die dbh->errstr;
5129 $sth->execute or die $sth->errstr;
5130 #warn ( (time - $t). " seconds\n" );
5134 local($ignore_expired_card) = 1;
5135 local($ignore_banned_card) = 1;
5136 local($skip_fuzzyfiles) = 1;
5137 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5139 FS::cust_main::Location->_upgrade_data(%opts);
5141 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5143 foreach my $cust_main ( qsearch({
5144 'table' => 'cust_main',
5146 'extra_sql' => 'WHERE '.
5148 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5149 qw( first last company )
5152 my $error = $cust_main->replace;
5153 die $error if $error;
5156 FS::upgrade_journal->set_done('cust_main__trimspaces');
5160 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5162 #we don't want to decrypt them, just stuff them as-is into cust_payby
5163 local(@encrypted_fields) = ();
5165 local($FS::cust_payby::ignore_expired_card) = 1;
5166 local($FS::cust_payby::ignore_banned_card) = 1;
5168 my @payfields = qw( payby payinfo paycvv paymask
5169 paydate paystart_month paystart_year payissue
5170 payname paystate paytype payip
5173 my $search = new FS::Cursor {
5174 'table' => 'cust_main',
5175 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5178 while (my $cust_main = $search->fetch) {
5180 my $cust_payby = new FS::cust_payby {
5181 'custnum' => $cust_main->custnum,
5183 map { $_ => $cust_main->$_(); } @payfields
5186 my $error = $cust_payby->insert;
5187 die $error if $error;
5189 $cust_main->setfield($_, '') foreach @payfields;
5190 $error = $cust_main->replace;
5191 die $error if $error;
5195 FS::upgrade_journal->set_done('cust_main__cust_payby');
5198 $class->_upgrade_otaker(%opts);
5208 The delete method should possibly take an FS::cust_main object reference
5209 instead of a scalar customer number.
5211 Bill and collect options should probably be passed as references instead of a
5214 There should probably be a configuration file with a list of allowed credit
5217 No multiple currency support (probably a larger project than just this module).
5219 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5221 Birthdates rely on negative epoch values.
5223 The payby for card/check batches is broken. With mixed batching, bad
5226 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5230 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5231 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5232 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.