2 use base qw( FS::cust_main::Packages
4 FS::cust_main::NationalID
6 FS::cust_main::Billing_Realtime
7 FS::cust_main::Billing_Discount
8 FS::cust_main::Billing_ThirdParty
9 FS::cust_main::Location
10 FS::cust_main::Credit_Limit
12 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
20 use vars qw( $DEBUG $me $conf
23 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
29 use Scalar::Util qw( blessed );
30 use Time::Local qw(timelocal);
33 use Digest::MD5 qw(md5_base64);
36 use File::Temp; #qw( tempfile );
37 use Business::CreditCard 0.28;
39 use FS::UID qw( dbh driver_name );
40 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
42 use FS::Misc qw( generate_email send_email generate_ps do_print );
43 use FS::Msgcat qw(gettext);
50 use FS::cust_bill_void;
51 use FS::legacy_cust_bill;
53 use FS::cust_pay_pending;
54 use FS::cust_pay_void;
55 use FS::cust_pay_batch;
58 use FS::part_referral;
59 use FS::cust_main_county;
60 use FS::cust_location;
63 use FS::cust_main_exemption;
64 use FS::cust_tax_adjustment;
65 use FS::cust_tax_location;
66 use FS::agent_currency;
67 use FS::cust_main_invoice;
69 use FS::prepay_credit;
75 use FS::payment_gateway;
76 use FS::agent_payment_gateway;
78 use FS::cust_main_note;
79 use FS::cust_attachment;
82 use FS::upgrade_journal;
86 # 1 is mostly method/subroutine entry and options
87 # 2 traces progress of some operations
88 # 3 is even more information including possibly sensitive data
90 $me = '[FS::cust_main]';
93 $ignore_expired_card = 0;
94 $ignore_banned_card = 0;
95 $ignore_invalid_card = 0;
99 @encrypted_fields = ('payinfo', 'paycvv');
100 sub nohistory_fields { ('payinfo', 'paycvv'); }
102 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
104 #ask FS::UID to run this stuff for us later
105 #$FS::UID::callback{'FS::cust_main'} = sub {
106 install_callback FS::UID sub {
107 $conf = new FS::Conf;
108 #yes, need it for stuff below (prolly should be cached)
109 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
114 my ( $hashref, $cache ) = @_;
115 if ( exists $hashref->{'pkgnum'} ) {
116 #@{ $self->{'_pkgnum'} } = ();
117 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
118 $self->{'_pkgnum'} = $subcache;
119 #push @{ $self->{'_pkgnum'} },
120 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
126 FS::cust_main - Object methods for cust_main records
132 $record = new FS::cust_main \%hash;
133 $record = new FS::cust_main { 'column' => 'value' };
135 $error = $record->insert;
137 $error = $new_record->replace($old_record);
139 $error = $record->delete;
141 $error = $record->check;
143 @cust_pkg = $record->all_pkgs;
145 @cust_pkg = $record->ncancelled_pkgs;
147 @cust_pkg = $record->suspended_pkgs;
149 $error = $record->bill;
150 $error = $record->bill %options;
151 $error = $record->bill 'time' => $time;
153 $error = $record->collect;
154 $error = $record->collect %options;
155 $error = $record->collect 'invoice_time' => $time,
160 An FS::cust_main object represents a customer. FS::cust_main inherits from
161 FS::Record. The following fields are currently supported:
167 Primary key (assigned automatically for new customers)
171 Agent (see L<FS::agent>)
175 Advertising source (see L<FS::part_referral>)
187 Cocial security number (optional)
211 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
215 Payment Information (See L<FS::payinfo_Mixin> for data format)
219 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
223 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
227 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
231 Start date month (maestro/solo cards only)
235 Start date year (maestro/solo cards only)
239 Issue number (maestro/solo cards only)
243 Name on card or billing name
247 IP address from which payment information was received
251 Tax exempt, empty or `Y'
255 Order taker (see L<FS::access_user>)
261 =item referral_custnum
263 Referring customer number
267 Enable individual CDR spooling, empty or `Y'
271 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
275 Discourage individual CDR printing, empty or `Y'
279 Allow self-service editing of ticket subjects, empty or 'Y'
281 =item calling_list_exempt
283 Do not call, empty or 'Y'
293 Creates a new customer. To add the customer to the database, see L<"insert">.
295 Note that this stores the hash reference, not a distinct copy of the hash it
296 points to. You can ask the object for a copy with the I<hash> method.
300 sub table { 'cust_main'; }
302 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
304 Adds this customer to the database. If there is an error, returns the error,
305 otherwise returns false.
307 Usually the customer's location will not yet exist in the database, and
308 the C<bill_location> and C<ship_location> pseudo-fields must be set to
309 uninserted L<FS::cust_location> objects. These will be inserted and linked
310 (in both directions) to the new customer record. If they're references
311 to the same object, they will become the same location.
313 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
314 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
315 are inserted atomicly, or the transaction is rolled back. Passing an empty
316 hash reference is equivalent to not supplying this parameter. There should be
317 a better explanation of this, but until then, here's an example:
320 tie %hash, 'Tie::RefHash'; #this part is important
322 $cust_pkg => [ $svc_acct ],
325 $cust_main->insert( \%hash );
327 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
328 be set as the invoicing list (see L<"invoicing_list">). Errors return as
329 expected and rollback the entire transaction; it is not necessary to call
330 check_invoicing_list first. The invoicing_list is set after the records in the
331 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
332 invoicing_list destination to the newly-created svc_acct. Here's an example:
334 $cust_main->insert( {}, [ $email, 'POST' ] );
336 Currently available options are: I<depend_jobnum>, I<noexport>,
337 I<tax_exemption> and I<prospectnum>.
339 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
340 on the supplied jobnum (they will not run until the specific job completes).
341 This can be used to defer provisioning until some action completes (such
342 as running the customer's credit card successfully).
344 The I<noexport> option is deprecated. If I<noexport> is set true, no
345 provisioning jobs (exports) are scheduled. (You can schedule them later with
346 the B<reexport> method.)
348 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
349 of tax names and exemption numbers. FS::cust_main_exemption records will be
350 created and inserted.
352 If I<prospectnum> is set, moves contacts and locations from that prospect.
354 If I<contact> is set to an arrayref of FS::contact objects, inserts those
355 new contacts with this new customer.
361 my $cust_pkgs = @_ ? shift : {};
362 my $invoicing_list = @_ ? shift : '';
364 warn "$me insert called with options ".
365 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
368 local $SIG{HUP} = 'IGNORE';
369 local $SIG{INT} = 'IGNORE';
370 local $SIG{QUIT} = 'IGNORE';
371 local $SIG{TERM} = 'IGNORE';
372 local $SIG{TSTP} = 'IGNORE';
373 local $SIG{PIPE} = 'IGNORE';
375 my $oldAutoCommit = $FS::UID::AutoCommit;
376 local $FS::UID::AutoCommit = 0;
379 my $prepay_identifier = '';
380 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
382 if ( $self->payby eq 'PREPAY' ) {
384 $self->payby('BILL');
385 $prepay_identifier = $self->payinfo;
388 warn " looking up prepaid card $prepay_identifier\n"
391 my $error = $self->get_prepay( $prepay_identifier,
392 'amount_ref' => \$amount,
393 'seconds_ref' => \$seconds,
394 'upbytes_ref' => \$upbytes,
395 'downbytes_ref' => \$downbytes,
396 'totalbytes_ref' => \$totalbytes,
399 $dbh->rollback if $oldAutoCommit;
400 #return "error applying prepaid card (transaction rolled back): $error";
404 $payby = 'PREP' if $amount;
406 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|PPAL)$/ ) {
409 $self->payby('BILL');
410 $amount = $self->paid;
415 foreach my $l (qw(bill_location ship_location)) {
417 my $loc = delete $self->hashref->{$l} or next;
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->prospectnum ) {
433 $loc->prospectnum('');
434 $loc->set(custnum_pending => 1);
435 my $error = $loc->replace;
437 $dbh->rollback if $oldAutoCommit;
438 my $label = $l eq 'ship_location' ? 'service' : 'billing';
439 return "$error (moving $label location)";
442 } elsif ( ($loc->custnum || 0) > 0 ) {
443 # then it somehow belongs to another customer--shouldn't happen
444 $dbh->rollback if $oldAutoCommit;
445 return "$l belongs to customer ".$loc->custnum;
447 # else it already belongs to this customer
448 # (happens when ship_location is identical to bill_location)
450 $self->set($l.'num', $loc->locationnum);
452 if ( $self->get($l.'num') eq '' ) {
453 $dbh->rollback if $oldAutoCommit;
458 warn " inserting $self\n"
461 $self->signupdate(time) unless $self->signupdate;
463 $self->auto_agent_custid()
464 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
466 my $error = $self->SUPER::insert;
468 $dbh->rollback if $oldAutoCommit;
469 #return "inserting cust_main record (transaction rolled back): $error";
473 # now set cust_location.custnum
474 foreach my $l (qw(bill_location ship_location)) {
475 warn " setting $l.custnum\n"
477 my $loc = $self->$l or next;
478 unless ( $loc->custnum ) {
479 $loc->set(custnum => $self->custnum);
480 $error ||= $loc->replace;
484 $dbh->rollback if $oldAutoCommit;
485 return "error setting $l custnum: $error";
489 warn " setting invoicing list\n"
492 if ( $invoicing_list ) {
493 $error = $self->check_invoicing_list( $invoicing_list );
495 $dbh->rollback if $oldAutoCommit;
496 #return "checking invoicing_list (transaction rolled back): $error";
499 $self->invoicing_list( $invoicing_list );
502 warn " setting customer tags\n"
505 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
506 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
507 'custnum' => $self->custnum };
508 my $error = $cust_tag->insert;
510 $dbh->rollback if $oldAutoCommit;
515 my $prospectnum = delete $options{'prospectnum'};
516 if ( $prospectnum ) {
518 warn " moving contacts and locations from prospect $prospectnum\n"
522 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
523 unless ( $prospect_main ) {
524 $dbh->rollback if $oldAutoCommit;
525 return "Unknown prospectnum $prospectnum";
527 $prospect_main->custnum($self->custnum);
528 $prospect_main->disabled('Y');
529 my $error = $prospect_main->replace;
531 $dbh->rollback if $oldAutoCommit;
535 my @contact = $prospect_main->contact;
536 my @cust_location = $prospect_main->cust_location;
537 my @qual = $prospect_main->qual;
539 foreach my $r ( @contact, @cust_location, @qual ) {
541 $r->custnum($self->custnum);
542 my $error = $r->replace;
544 $dbh->rollback if $oldAutoCommit;
551 my $contact = delete $options{'contact'};
554 foreach my $c ( @$contact ) {
555 $c->custnum($self->custnum);
556 my $error = $c->insert;
558 $dbh->rollback if $oldAutoCommit;
566 warn " setting cust_main_exemption\n"
569 my $tax_exemption = delete $options{'tax_exemption'};
570 if ( $tax_exemption ) {
572 $tax_exemption = { map { $_ => '' } @$tax_exemption }
573 if ref($tax_exemption) eq 'ARRAY';
575 foreach my $taxname ( keys %$tax_exemption ) {
576 my $cust_main_exemption = new FS::cust_main_exemption {
577 'custnum' => $self->custnum,
578 'taxname' => $taxname,
579 'exempt_number' => $tax_exemption->{$taxname},
581 my $error = $cust_main_exemption->insert;
583 $dbh->rollback if $oldAutoCommit;
584 return "inserting cust_main_exemption (transaction rolled back): $error";
589 warn " ordering packages\n"
592 $error = $self->order_pkgs( $cust_pkgs,
594 'seconds_ref' => \$seconds,
595 'upbytes_ref' => \$upbytes,
596 'downbytes_ref' => \$downbytes,
597 'totalbytes_ref' => \$totalbytes,
600 $dbh->rollback if $oldAutoCommit;
605 $dbh->rollback if $oldAutoCommit;
606 return "No svc_acct record to apply pre-paid time";
608 if ( $upbytes || $downbytes || $totalbytes ) {
609 $dbh->rollback if $oldAutoCommit;
610 return "No svc_acct record to apply pre-paid data";
614 warn " inserting initial $payby payment of $amount\n"
616 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
618 $dbh->rollback if $oldAutoCommit;
619 return "inserting payment (transaction rolled back): $error";
623 unless ( $import || $skip_fuzzyfiles ) {
624 warn " queueing fuzzyfiles update\n"
626 $error = $self->queue_fuzzyfiles_update;
628 $dbh->rollback if $oldAutoCommit;
629 return "updating fuzzy search cache: $error";
633 # FS::geocode_Mixin::after_insert or something?
634 if ( $conf->config('tax_district_method') and !$import ) {
635 # if anything non-empty, try to look it up
636 my $queue = new FS::queue {
637 'job' => 'FS::geocode_Mixin::process_district_update',
638 'custnum' => $self->custnum,
640 my $error = $queue->insert( ref($self), $self->custnum );
642 $dbh->rollback if $oldAutoCommit;
643 return "queueing tax district update: $error";
648 warn " exporting\n" if $DEBUG > 1;
650 my $export_args = $options{'export_args'} || [];
653 map qsearch( 'part_export', {exportnum=>$_} ),
654 $conf->config('cust_main-exports'); #, $agentnum
656 foreach my $part_export ( @part_export ) {
657 my $error = $part_export->export_insert($self, @$export_args);
659 $dbh->rollback if $oldAutoCommit;
660 return "exporting to ". $part_export->exporttype.
661 " (transaction rolled back): $error";
665 #foreach my $depend_jobnum ( @$depend_jobnums ) {
666 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
668 # foreach my $jobnum ( @jobnums ) {
669 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
670 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
672 # my $error = $queue->depend_insert($depend_jobnum);
674 # $dbh->rollback if $oldAutoCommit;
675 # return "error queuing job dependancy: $error";
682 #if ( exists $options{'jobnums'} ) {
683 # push @{ $options{'jobnums'} }, @jobnums;
686 warn " insert complete; committing transaction\n"
689 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
694 use File::CounterFile;
695 sub auto_agent_custid {
698 my $format = $conf->config('cust_main-auto_agent_custid');
700 if ( $format eq '1YMMXXXXXXXX' ) {
702 my $counter = new File::CounterFile 'cust_main.agent_custid';
705 my $ym = 100000000000 + time2str('%y%m00000000', time);
706 if ( $ym > $counter->value ) {
707 $counter->{'value'} = $agent_custid = $ym;
708 $counter->{'updated'} = 1;
710 $agent_custid = $counter->inc;
716 die "Unknown cust_main-auto_agent_custid format: $format";
719 $self->agent_custid($agent_custid);
723 =item PACKAGE METHODS
725 Documentation on customer package methods has been moved to
726 L<FS::cust_main::Packages>.
728 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
730 Recharges this (existing) customer with the specified prepaid card (see
731 L<FS::prepay_credit>), specified either by I<identifier> or as an
732 FS::prepay_credit object. If there is an error, returns the error, otherwise
735 Optionally, five scalar references can be passed as well. They will have their
736 values filled in with the amount, number of seconds, and number of upload,
737 download, and total bytes applied by this prepaid card.
741 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
742 #the only place that uses these args
743 sub recharge_prepay {
744 my( $self, $prepay_credit, $amountref, $secondsref,
745 $upbytesref, $downbytesref, $totalbytesref ) = @_;
747 local $SIG{HUP} = 'IGNORE';
748 local $SIG{INT} = 'IGNORE';
749 local $SIG{QUIT} = 'IGNORE';
750 local $SIG{TERM} = 'IGNORE';
751 local $SIG{TSTP} = 'IGNORE';
752 local $SIG{PIPE} = 'IGNORE';
754 my $oldAutoCommit = $FS::UID::AutoCommit;
755 local $FS::UID::AutoCommit = 0;
758 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
760 my $error = $self->get_prepay( $prepay_credit,
761 'amount_ref' => \$amount,
762 'seconds_ref' => \$seconds,
763 'upbytes_ref' => \$upbytes,
764 'downbytes_ref' => \$downbytes,
765 'totalbytes_ref' => \$totalbytes,
767 || $self->increment_seconds($seconds)
768 || $self->increment_upbytes($upbytes)
769 || $self->increment_downbytes($downbytes)
770 || $self->increment_totalbytes($totalbytes)
771 || $self->insert_cust_pay_prepay( $amount,
773 ? $prepay_credit->identifier
778 $dbh->rollback if $oldAutoCommit;
782 if ( defined($amountref) ) { $$amountref = $amount; }
783 if ( defined($secondsref) ) { $$secondsref = $seconds; }
784 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
785 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
786 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
788 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
793 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
795 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
796 specified either by I<identifier> or as an FS::prepay_credit object.
798 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
799 incremented by the values of the prepaid card.
801 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
802 check or set this customer's I<agentnum>.
804 If there is an error, returns the error, otherwise returns false.
810 my( $self, $prepay_credit, %opt ) = @_;
812 local $SIG{HUP} = 'IGNORE';
813 local $SIG{INT} = 'IGNORE';
814 local $SIG{QUIT} = 'IGNORE';
815 local $SIG{TERM} = 'IGNORE';
816 local $SIG{TSTP} = 'IGNORE';
817 local $SIG{PIPE} = 'IGNORE';
819 my $oldAutoCommit = $FS::UID::AutoCommit;
820 local $FS::UID::AutoCommit = 0;
823 unless ( ref($prepay_credit) ) {
825 my $identifier = $prepay_credit;
827 $prepay_credit = qsearchs(
829 { 'identifier' => $identifier },
834 unless ( $prepay_credit ) {
835 $dbh->rollback if $oldAutoCommit;
836 return "Invalid prepaid card: ". $identifier;
841 if ( $prepay_credit->agentnum ) {
842 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
843 $dbh->rollback if $oldAutoCommit;
844 return "prepaid card not valid for agent ". $self->agentnum;
846 $self->agentnum($prepay_credit->agentnum);
849 my $error = $prepay_credit->delete;
851 $dbh->rollback if $oldAutoCommit;
852 return "removing prepay_credit (transaction rolled back): $error";
855 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
856 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
858 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
863 =item increment_upbytes SECONDS
865 Updates this customer's single or primary account (see L<FS::svc_acct>) by
866 the specified number of upbytes. If there is an error, returns the error,
867 otherwise returns false.
871 sub increment_upbytes {
872 _increment_column( shift, 'upbytes', @_);
875 =item increment_downbytes SECONDS
877 Updates this customer's single or primary account (see L<FS::svc_acct>) by
878 the specified number of downbytes. If there is an error, returns the error,
879 otherwise returns false.
883 sub increment_downbytes {
884 _increment_column( shift, 'downbytes', @_);
887 =item increment_totalbytes SECONDS
889 Updates this customer's single or primary account (see L<FS::svc_acct>) by
890 the specified number of totalbytes. If there is an error, returns the error,
891 otherwise returns false.
895 sub increment_totalbytes {
896 _increment_column( shift, 'totalbytes', @_);
899 =item increment_seconds SECONDS
901 Updates this customer's single or primary account (see L<FS::svc_acct>) by
902 the specified number of seconds. If there is an error, returns the error,
903 otherwise returns false.
907 sub increment_seconds {
908 _increment_column( shift, 'seconds', @_);
911 =item _increment_column AMOUNT
913 Updates this customer's single or primary account (see L<FS::svc_acct>) by
914 the specified number of seconds or bytes. If there is an error, returns
915 the error, otherwise returns false.
919 sub _increment_column {
920 my( $self, $column, $amount ) = @_;
921 warn "$me increment_column called: $column, $amount\n"
924 return '' unless $amount;
926 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
927 $self->ncancelled_pkgs;
930 return 'No packages with primary or single services found'.
931 ' to apply pre-paid time';
932 } elsif ( scalar(@cust_pkg) > 1 ) {
933 #maybe have a way to specify the package/account?
934 return 'Multiple packages found to apply pre-paid time';
937 my $cust_pkg = $cust_pkg[0];
938 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
942 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
945 return 'No account found to apply pre-paid time';
946 } elsif ( scalar(@cust_svc) > 1 ) {
947 return 'Multiple accounts found to apply pre-paid time';
950 my $svc_acct = $cust_svc[0]->svc_x;
951 warn " found service svcnum ". $svc_acct->pkgnum.
952 ' ('. $svc_acct->email. ")\n"
955 $column = "increment_$column";
956 $svc_acct->$column($amount);
960 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
962 Inserts a prepayment in the specified amount for this customer. An optional
963 second argument can specify the prepayment identifier for tracking purposes.
964 If there is an error, returns the error, otherwise returns false.
968 sub insert_cust_pay_prepay {
969 shift->insert_cust_pay('PREP', @_);
972 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
974 Inserts a cash payment in the specified amount for this customer. An optional
975 second argument can specify the payment identifier for tracking purposes.
976 If there is an error, returns the error, otherwise returns false.
980 sub insert_cust_pay_cash {
981 shift->insert_cust_pay('CASH', @_);
984 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
986 Inserts a Western Union payment in the specified amount for this customer. An
987 optional second argument can specify the prepayment identifier for tracking
988 purposes. If there is an error, returns the error, otherwise returns false.
992 sub insert_cust_pay_west {
993 shift->insert_cust_pay('WEST', @_);
996 sub insert_cust_pay {
997 my( $self, $payby, $amount ) = splice(@_, 0, 3);
998 my $payinfo = scalar(@_) ? shift : '';
1000 my $cust_pay = new FS::cust_pay {
1001 'custnum' => $self->custnum,
1002 'paid' => sprintf('%.2f', $amount),
1003 #'_date' => #date the prepaid card was purchased???
1005 'payinfo' => $payinfo,
1011 =item delete [ OPTION => VALUE ... ]
1013 This deletes the customer. If there is an error, returns the error, otherwise
1016 This will completely remove all traces of the customer record. This is not
1017 what you want when a customer cancels service; for that, cancel all of the
1018 customer's packages (see L</cancel>).
1020 If the customer has any uncancelled packages, you need to pass a new (valid)
1021 customer number for those packages to be transferred to, as the "new_customer"
1022 option. Cancelled packages will be deleted. Did I mention that this is NOT
1023 what you want when a customer cancels service and that you really should be
1024 looking at L<FS::cust_pkg/cancel>?
1026 You can't delete a customer with invoices (see L<FS::cust_bill>),
1027 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1028 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1029 set the "delete_financials" option to a true value.
1034 my( $self, %opt ) = @_;
1036 local $SIG{HUP} = 'IGNORE';
1037 local $SIG{INT} = 'IGNORE';
1038 local $SIG{QUIT} = 'IGNORE';
1039 local $SIG{TERM} = 'IGNORE';
1040 local $SIG{TSTP} = 'IGNORE';
1041 local $SIG{PIPE} = 'IGNORE';
1043 my $oldAutoCommit = $FS::UID::AutoCommit;
1044 local $FS::UID::AutoCommit = 0;
1047 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1048 $dbh->rollback if $oldAutoCommit;
1049 return "Can't delete a master agent customer";
1052 #use FS::access_user
1053 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1054 $dbh->rollback if $oldAutoCommit;
1055 return "Can't delete a master employee customer";
1058 tie my %financial_tables, 'Tie::IxHash',
1059 'cust_bill' => 'invoices',
1060 'cust_statement' => 'statements',
1061 'cust_credit' => 'credits',
1062 'cust_pay' => 'payments',
1063 'cust_refund' => 'refunds',
1066 foreach my $table ( keys %financial_tables ) {
1068 my @records = $self->$table();
1070 if ( @records && ! $opt{'delete_financials'} ) {
1071 $dbh->rollback if $oldAutoCommit;
1072 return "Can't delete a customer with ". $financial_tables{$table};
1075 foreach my $record ( @records ) {
1076 my $error = $record->delete;
1078 $dbh->rollback if $oldAutoCommit;
1079 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1085 my @cust_pkg = $self->ncancelled_pkgs;
1087 my $new_custnum = $opt{'new_custnum'};
1088 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1089 $dbh->rollback if $oldAutoCommit;
1090 return "Invalid new customer number: $new_custnum";
1092 foreach my $cust_pkg ( @cust_pkg ) {
1093 my %hash = $cust_pkg->hash;
1094 $hash{'custnum'} = $new_custnum;
1095 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1096 my $error = $new_cust_pkg->replace($cust_pkg,
1097 options => { $cust_pkg->options },
1100 $dbh->rollback if $oldAutoCommit;
1105 my @cancelled_cust_pkg = $self->all_pkgs;
1106 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1107 my $error = $cust_pkg->delete;
1109 $dbh->rollback if $oldAutoCommit;
1114 #cust_tax_adjustment in financials?
1115 #cust_pay_pending? ouch
1117 foreach my $table (qw(
1118 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1119 cust_location cust_main_note cust_tax_adjustment
1120 cust_pay_void cust_pay_batch queue cust_tax_exempt
1122 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1123 my $error = $record->delete;
1125 $dbh->rollback if $oldAutoCommit;
1131 my $sth = $dbh->prepare(
1132 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1134 my $errstr = $dbh->errstr;
1135 $dbh->rollback if $oldAutoCommit;
1138 $sth->execute($self->custnum) or do {
1139 my $errstr = $sth->errstr;
1140 $dbh->rollback if $oldAutoCommit;
1146 my $ticket_dbh = '';
1147 if ($conf->config('ticket_system') eq 'RT_Internal') {
1149 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1150 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1151 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1152 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1155 if ( $ticket_dbh ) {
1157 my $ticket_sth = $ticket_dbh->prepare(
1158 'DELETE FROM Links WHERE Target = ?'
1160 my $errstr = $ticket_dbh->errstr;
1161 $dbh->rollback if $oldAutoCommit;
1164 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1166 my $errstr = $ticket_sth->errstr;
1167 $dbh->rollback if $oldAutoCommit;
1171 #check and see if the customer is the only link on the ticket, and
1172 #if so, set the ticket to deleted status in RT?
1173 #maybe someday, for now this will at least fix tickets not displaying
1177 #delete the customer record
1179 my $error = $self->SUPER::delete;
1181 $dbh->rollback if $oldAutoCommit;
1185 # cust_main exports!
1187 #my $export_args = $options{'export_args'} || [];
1190 map qsearch( 'part_export', {exportnum=>$_} ),
1191 $conf->config('cust_main-exports'); #, $agentnum
1193 foreach my $part_export ( @part_export ) {
1194 my $error = $part_export->export_delete( $self ); #, @$export_args);
1196 $dbh->rollback if $oldAutoCommit;
1197 return "exporting to ". $part_export->exporttype.
1198 " (transaction rolled back): $error";
1202 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1207 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1209 This merges this customer into the provided new custnum, and then deletes the
1210 customer. If there is an error, returns the error, otherwise returns false.
1212 The source customer's name, company name, phone numbers, agent,
1213 referring customer, customer class, advertising source, order taker, and
1214 billing information (except balance) are discarded.
1216 All packages are moved to the target customer. Packages with package locations
1217 are preserved. Packages without package locations are moved to a new package
1218 location with the source customer's service/shipping address.
1220 All invoices, statements, payments, credits and refunds are moved to the target
1221 customer. The source customer's balance is added to the target customer.
1223 All notes, attachments, tickets and customer tags are moved to the target
1226 Change history is not currently moved.
1231 my( $self, $new_custnum, %opt ) = @_;
1233 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1235 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1236 or return "Invalid new customer number: $new_custnum";
1238 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1239 if $self->agentnum != $new_cust_main->agentnum
1240 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1242 local $SIG{HUP} = 'IGNORE';
1243 local $SIG{INT} = 'IGNORE';
1244 local $SIG{QUIT} = 'IGNORE';
1245 local $SIG{TERM} = 'IGNORE';
1246 local $SIG{TSTP} = 'IGNORE';
1247 local $SIG{PIPE} = 'IGNORE';
1249 my $oldAutoCommit = $FS::UID::AutoCommit;
1250 local $FS::UID::AutoCommit = 0;
1253 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1254 $dbh->rollback if $oldAutoCommit;
1255 return "Can't merge a master agent customer";
1258 #use FS::access_user
1259 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1260 $dbh->rollback if $oldAutoCommit;
1261 return "Can't merge a master employee customer";
1264 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1265 'status' => { op=>'!=', value=>'done' },
1269 $dbh->rollback if $oldAutoCommit;
1270 return "Can't merge a customer with pending payments";
1273 tie my %financial_tables, 'Tie::IxHash',
1274 'cust_bill' => 'invoices',
1275 'cust_bill_void' => 'voided invoices',
1276 'cust_statement' => 'statements',
1277 'cust_credit' => 'credits',
1278 'cust_credit_void' => 'voided credits',
1279 'cust_pay' => 'payments',
1280 'cust_pay_void' => 'voided payments',
1281 'cust_refund' => 'refunds',
1284 foreach my $table ( keys %financial_tables ) {
1286 my @records = $self->$table();
1288 foreach my $record ( @records ) {
1289 $record->custnum($new_custnum);
1290 my $error = $record->replace;
1292 $dbh->rollback if $oldAutoCommit;
1293 return "Error merging ". $financial_tables{$table}. ": $error\n";
1299 my $name = $self->ship_name; #?
1301 my $locationnum = '';
1302 foreach my $cust_pkg ( $self->all_pkgs ) {
1303 $cust_pkg->custnum($new_custnum);
1305 unless ( $cust_pkg->locationnum ) {
1306 unless ( $locationnum ) {
1307 my $cust_location = new FS::cust_location {
1308 $self->location_hash,
1309 'custnum' => $new_custnum,
1311 my $error = $cust_location->insert;
1313 $dbh->rollback if $oldAutoCommit;
1316 $locationnum = $cust_location->locationnum;
1318 $cust_pkg->locationnum($locationnum);
1321 my $error = $cust_pkg->replace;
1323 $dbh->rollback if $oldAutoCommit;
1327 # add customer (ship) name to svc_phone.phone_name if blank
1328 my @cust_svc = $cust_pkg->cust_svc;
1329 foreach my $cust_svc (@cust_svc) {
1330 my($label, $value, $svcdb) = $cust_svc->label;
1331 next unless $svcdb eq 'svc_phone';
1332 my $svc_phone = $cust_svc->svc_x;
1333 next if $svc_phone->phone_name;
1334 $svc_phone->phone_name($name);
1335 my $error = $svc_phone->replace;
1337 $dbh->rollback if $oldAutoCommit;
1345 # cust_tax_exempt (texas tax exemptions)
1346 # cust_recon (some sort of not-well understood thing for OnPac)
1348 #these are moved over
1349 foreach my $table (qw(
1350 cust_tag cust_location contact cust_attachment cust_main_note
1351 cust_tax_adjustment cust_pay_batch queue
1353 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1354 $record->custnum($new_custnum);
1355 my $error = $record->replace;
1357 $dbh->rollback if $oldAutoCommit;
1363 #these aren't preserved
1364 foreach my $table (qw(
1365 cust_main_exemption cust_main_invoice
1367 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1368 my $error = $record->delete;
1370 $dbh->rollback if $oldAutoCommit;
1377 my $sth = $dbh->prepare(
1378 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1380 my $errstr = $dbh->errstr;
1381 $dbh->rollback if $oldAutoCommit;
1384 $sth->execute($new_custnum, $self->custnum) or do {
1385 my $errstr = $sth->errstr;
1386 $dbh->rollback if $oldAutoCommit;
1392 my $ticket_dbh = '';
1393 if ($conf->config('ticket_system') eq 'RT_Internal') {
1395 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1396 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1397 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1398 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1401 if ( $ticket_dbh ) {
1403 my $ticket_sth = $ticket_dbh->prepare(
1404 'UPDATE Links SET Target = ? WHERE Target = ?'
1406 my $errstr = $ticket_dbh->errstr;
1407 $dbh->rollback if $oldAutoCommit;
1410 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1411 'freeside://freeside/cust_main/'.$self->custnum)
1413 my $errstr = $ticket_sth->errstr;
1414 $dbh->rollback if $oldAutoCommit;
1420 #delete the customer record
1422 my $error = $self->delete;
1424 $dbh->rollback if $oldAutoCommit;
1428 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1433 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1435 Replaces the OLD_RECORD with this one in the database. If there is an error,
1436 returns the error, otherwise returns false.
1438 To change the customer's address, set the pseudo-fields C<bill_location> and
1439 C<ship_location>. The address will still only change if at least one of the
1440 address fields differs from the existing values.
1442 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1443 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1444 expected and rollback the entire transaction; it is not necessary to call
1445 check_invoicing_list first. Here's an example:
1447 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1449 Currently available options are: I<tax_exemption>.
1451 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1452 of tax names and exemption numbers. FS::cust_main_exemption records will be
1453 deleted and inserted as appropriate.
1460 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1462 : $self->replace_old;
1466 warn "$me replace called\n"
1469 my $curuser = $FS::CurrentUser::CurrentUser;
1470 if ( $self->payby eq 'COMP'
1471 && $self->payby ne $old->payby
1472 && ! $curuser->access_right('Complimentary customer')
1475 return "You are not permitted to create complimentary accounts.";
1478 local($ignore_expired_card) = 1
1479 if $old->payby =~ /^(CARD|DCRD)$/
1480 && $self->payby =~ /^(CARD|DCRD)$/
1481 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1483 local($ignore_banned_card) = 1
1484 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1485 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1486 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1488 return "Invoicing locale is required"
1491 && $conf->exists('cust_main-require_locale');
1493 local $SIG{HUP} = 'IGNORE';
1494 local $SIG{INT} = 'IGNORE';
1495 local $SIG{QUIT} = 'IGNORE';
1496 local $SIG{TERM} = 'IGNORE';
1497 local $SIG{TSTP} = 'IGNORE';
1498 local $SIG{PIPE} = 'IGNORE';
1500 my $oldAutoCommit = $FS::UID::AutoCommit;
1501 local $FS::UID::AutoCommit = 0;
1504 for my $l (qw(bill_location ship_location)) {
1505 my $old_loc = $old->$l;
1506 my $new_loc = $self->$l;
1508 # find the existing location if there is one
1509 $new_loc->set('custnum' => $self->custnum);
1510 my $error = $new_loc->find_or_insert;
1512 $dbh->rollback if $oldAutoCommit;
1515 $self->set($l.'num', $new_loc->locationnum);
1518 # replace the customer record
1519 my $error = $self->SUPER::replace($old);
1522 $dbh->rollback if $oldAutoCommit;
1526 # now move packages to the new service location
1527 $self->set('ship_location', ''); #flush cache
1528 if ( $old->ship_locationnum and # should only be null during upgrade...
1529 $old->ship_locationnum != $self->ship_locationnum ) {
1530 $error = $old->ship_location->move_to($self->ship_location);
1532 $dbh->rollback if $oldAutoCommit;
1536 # don't move packages based on the billing location, but
1537 # disable it if it's no longer in use
1538 if ( $old->bill_locationnum and
1539 $old->bill_locationnum != $self->bill_locationnum ) {
1540 $error = $old->bill_location->disable_if_unused;
1542 $dbh->rollback if $oldAutoCommit;
1547 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1548 my $invoicing_list = shift @param;
1549 $error = $self->check_invoicing_list( $invoicing_list );
1551 $dbh->rollback if $oldAutoCommit;
1554 $self->invoicing_list( $invoicing_list );
1557 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1559 #this could be more efficient than deleting and re-inserting, if it matters
1560 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1561 my $error = $cust_tag->delete;
1563 $dbh->rollback if $oldAutoCommit;
1567 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1568 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1569 'custnum' => $self->custnum };
1570 my $error = $cust_tag->insert;
1572 $dbh->rollback if $oldAutoCommit;
1579 my %options = @param;
1581 my $tax_exemption = delete $options{'tax_exemption'};
1582 if ( $tax_exemption ) {
1584 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1585 if ref($tax_exemption) eq 'ARRAY';
1587 my %cust_main_exemption =
1588 map { $_->taxname => $_ }
1589 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1591 foreach my $taxname ( keys %$tax_exemption ) {
1593 if ( $cust_main_exemption{$taxname} &&
1594 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1597 delete $cust_main_exemption{$taxname};
1601 my $cust_main_exemption = new FS::cust_main_exemption {
1602 'custnum' => $self->custnum,
1603 'taxname' => $taxname,
1604 'exempt_number' => $tax_exemption->{$taxname},
1606 my $error = $cust_main_exemption->insert;
1608 $dbh->rollback if $oldAutoCommit;
1609 return "inserting cust_main_exemption (transaction rolled back): $error";
1613 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1614 my $error = $cust_main_exemption->delete;
1616 $dbh->rollback if $oldAutoCommit;
1617 return "deleting cust_main_exemption (transaction rolled back): $error";
1623 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1624 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1625 && $self->get('payinfo') !~ /^99\d{14}$/
1627 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1632 # card/check/lec info has changed, want to retry realtime_ invoice events
1633 my $error = $self->retry_realtime;
1635 $dbh->rollback if $oldAutoCommit;
1640 unless ( $import || $skip_fuzzyfiles ) {
1641 $error = $self->queue_fuzzyfiles_update;
1643 $dbh->rollback if $oldAutoCommit;
1644 return "updating fuzzy search cache: $error";
1648 # tax district update in cust_location
1650 # cust_main exports!
1652 my $export_args = $options{'export_args'} || [];
1655 map qsearch( 'part_export', {exportnum=>$_} ),
1656 $conf->config('cust_main-exports'); #, $agentnum
1658 foreach my $part_export ( @part_export ) {
1659 my $error = $part_export->export_replace( $self, $old, @$export_args);
1661 $dbh->rollback if $oldAutoCommit;
1662 return "exporting to ". $part_export->exporttype.
1663 " (transaction rolled back): $error";
1667 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1672 =item queue_fuzzyfiles_update
1674 Used by insert & replace to update the fuzzy search cache
1678 use FS::cust_main::Search;
1679 sub queue_fuzzyfiles_update {
1682 local $SIG{HUP} = 'IGNORE';
1683 local $SIG{INT} = 'IGNORE';
1684 local $SIG{QUIT} = 'IGNORE';
1685 local $SIG{TERM} = 'IGNORE';
1686 local $SIG{TSTP} = 'IGNORE';
1687 local $SIG{PIPE} = 'IGNORE';
1689 my $oldAutoCommit = $FS::UID::AutoCommit;
1690 local $FS::UID::AutoCommit = 0;
1693 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1694 my $queue = new FS::queue {
1695 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1697 my @args = "cust_main.$field", $self->get($field);
1698 my $error = $queue->insert( @args );
1700 $dbh->rollback if $oldAutoCommit;
1701 return "queueing job (transaction rolled back): $error";
1706 push @locations, $self->bill_location if $self->bill_locationnum;
1707 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1708 foreach my $location (@locations) {
1709 my $queue = new FS::queue {
1710 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1712 my @args = 'cust_location.address1', $location->address1;
1713 my $error = $queue->insert( @args );
1715 $dbh->rollback if $oldAutoCommit;
1716 return "queueing job (transaction rolled back): $error";
1720 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1727 Checks all fields to make sure this is a valid customer record. If there is
1728 an error, returns the error, otherwise returns false. Called by the insert
1729 and replace methods.
1736 warn "$me check BEFORE: \n". $self->_dump
1740 $self->ut_numbern('custnum')
1741 || $self->ut_number('agentnum')
1742 || $self->ut_textn('agent_custid')
1743 || $self->ut_number('refnum')
1744 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1745 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1746 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1747 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1748 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1749 || $self->ut_textn('custbatch')
1750 || $self->ut_name('last')
1751 || $self->ut_name('first')
1752 || $self->ut_snumbern('signupdate')
1753 || $self->ut_snumbern('birthdate')
1754 || $self->ut_namen('spouse_last')
1755 || $self->ut_namen('spouse_first')
1756 || $self->ut_snumbern('spouse_birthdate')
1757 || $self->ut_snumbern('anniversary_date')
1758 || $self->ut_textn('company')
1759 || $self->ut_textn('ship_company')
1760 || $self->ut_anything('comments')
1761 || $self->ut_numbern('referral_custnum')
1762 || $self->ut_textn('stateid')
1763 || $self->ut_textn('stateid_state')
1764 || $self->ut_textn('invoice_terms')
1765 || $self->ut_floatn('cdr_termination_percentage')
1766 || $self->ut_floatn('credit_limit')
1767 || $self->ut_numbern('billday')
1768 || $self->ut_numbern('prorate_day')
1769 || $self->ut_flag('edit_subject')
1770 || $self->ut_flag('calling_list_exempt')
1771 || $self->ut_flag('invoice_noemail')
1772 || $self->ut_flag('message_noemail')
1773 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1774 || $self->ut_currencyn('currency')
1777 foreach (qw(company ship_company)) {
1778 my $company = $self->get($_);
1779 $company =~ s/^\s+//;
1780 $company =~ s/\s+$//;
1781 $company =~ s/\s+/ /g;
1782 $self->set($_, $company);
1785 #barf. need message catalogs. i18n. etc.
1786 $error .= "Please select an advertising source."
1787 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1788 return $error if $error;
1790 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1791 or return "Unknown agent";
1793 if ( $self->currency ) {
1794 my $agent_currency = qsearchs( 'agent_currency', {
1795 'agentnum' => $agent->agentnum,
1796 'currency' => $self->currency,
1798 or return "Agent ". $agent->agent.
1799 " not permitted to offer ". $self->currency. " invoicing";
1802 return "Unknown refnum"
1803 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1805 return "Unknown referring custnum: ". $self->referral_custnum
1806 unless ! $self->referral_custnum
1807 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1809 if ( $self->ss eq '' ) {
1814 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1815 or return "Illegal social security number: ". $self->ss;
1816 $self->ss("$1-$2-$3");
1819 # cust_main_county verification now handled by cust_location check
1822 $self->ut_phonen('daytime', $self->country)
1823 || $self->ut_phonen('night', $self->country)
1824 || $self->ut_phonen('fax', $self->country)
1825 || $self->ut_phonen('mobile', $self->country)
1827 return $error if $error;
1829 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1831 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1834 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1836 : FS::Msgcat::_gettext('daytime');
1837 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1839 : FS::Msgcat::_gettext('night');
1841 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1843 : FS::Msgcat::_gettext('mobile');
1845 return "$daytime_label, $night_label or $mobile_label is required"
1849 ### start of stuff moved to cust_payby
1850 # then mostly kept here to support upgrades (can remove in 5.x)
1851 # but modified to allow everything to be empty
1853 if ( $self->payby ) {
1854 FS::payby->can_payby($self->table, $self->payby)
1855 or return "Illegal payby: ". $self->payby;
1860 $error = $self->ut_numbern('paystart_month')
1861 || $self->ut_numbern('paystart_year')
1862 || $self->ut_numbern('payissue')
1863 || $self->ut_textn('paytype')
1865 return $error if $error;
1867 if ( $self->payip eq '' ) {
1870 $error = $self->ut_ip('payip');
1871 return $error if $error;
1874 # If it is encrypted and the private key is not availaible then we can't
1875 # check the credit card.
1876 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1878 # Need some kind of global flag to accept invalid cards, for testing
1880 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1881 $self->payby =~ /^(CARD|DCRD)$/ ) {
1883 my $payinfo = $self->payinfo;
1884 $payinfo =~ s/\D//g;
1885 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1886 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1888 $self->payinfo($payinfo);
1890 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1892 return gettext('unknown_card_type')
1893 if $self->payinfo !~ /^99\d{14}$/ #token
1894 && cardtype($self->payinfo) eq "Unknown";
1896 unless ( $ignore_banned_card ) {
1897 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1899 if ( $ban->bantype eq 'warn' ) {
1900 #or others depending on value of $ban->reason ?
1901 return '_duplicate_card'.
1902 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1903 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1904 ' (ban# '. $ban->bannum. ')'
1905 unless $self->override_ban_warn;
1907 return 'Banned credit card: banned on '.
1908 time2str('%a %h %o at %r', $ban->_date).
1909 ' by '. $ban->otaker.
1910 ' (ban# '. $ban->bannum. ')';
1915 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1916 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1917 $self->paycvv =~ /^(\d{4})$/
1918 or return "CVV2 (CID) for American Express cards is four digits.";
1921 $self->paycvv =~ /^(\d{3})$/
1922 or return "CVV2 (CVC2/CID) is three digits.";
1929 my $cardtype = cardtype($payinfo);
1930 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1932 return "Start date or issue number is required for $cardtype cards"
1933 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1935 return "Start month must be between 1 and 12"
1936 if $self->paystart_month
1937 and $self->paystart_month < 1 || $self->paystart_month > 12;
1939 return "Start year must be 1990 or later"
1940 if $self->paystart_year
1941 and $self->paystart_year < 1990;
1943 return "Issue number must be beween 1 and 99"
1945 and $self->payissue < 1 || $self->payissue > 99;
1948 $self->paystart_month('');
1949 $self->paystart_year('');
1950 $self->payissue('');
1953 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1954 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1956 my $payinfo = $self->payinfo;
1957 $payinfo =~ s/[^\d\@\.]//g;
1958 if ( $conf->config('echeck-country') eq 'CA' ) {
1959 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1960 or return 'invalid echeck account@branch.bank';
1961 $payinfo = "$1\@$2.$3";
1962 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1963 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1964 $payinfo = "$1\@$2";
1966 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1967 $payinfo = "$1\@$2";
1969 $self->payinfo($payinfo);
1972 unless ( $ignore_banned_card ) {
1973 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1975 if ( $ban->bantype eq 'warn' ) {
1976 #or others depending on value of $ban->reason ?
1977 return '_duplicate_ach' unless $self->override_ban_warn;
1979 return 'Banned ACH account: banned on '.
1980 time2str('%a %h %o at %r', $ban->_date).
1981 ' by '. $ban->otaker.
1982 ' (ban# '. $ban->bannum. ')';
1987 } elsif ( $self->payby eq 'LECB' ) {
1989 my $payinfo = $self->payinfo;
1990 $payinfo =~ s/\D//g;
1991 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1993 $self->payinfo($payinfo);
1996 } elsif ( $self->payby eq 'BILL' ) {
1998 $error = $self->ut_textn('payinfo');
1999 return "Illegal P.O. number: ". $self->payinfo if $error;
2002 } elsif ( $self->payby eq 'COMP' ) {
2004 my $curuser = $FS::CurrentUser::CurrentUser;
2005 if ( ! $self->custnum
2006 && ! $curuser->access_right('Complimentary customer')
2009 return "You are not permitted to create complimentary accounts."
2012 $error = $self->ut_textn('payinfo');
2013 return "Illegal comp account issuer: ". $self->payinfo if $error;
2016 } elsif ( $self->payby eq 'PREPAY' ) {
2018 my $payinfo = $self->payinfo;
2019 $payinfo =~ s/\W//g; #anything else would just confuse things
2020 $self->payinfo($payinfo);
2021 $error = $self->ut_alpha('payinfo');
2022 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2023 return "Unknown prepayment identifier"
2024 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2029 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2030 return "Expiration date required"
2031 # shouldn't payinfo_check do this?
2032 unless ! $self->payby
2033 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2037 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2038 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2039 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2040 ( $m, $y ) = ( $2, "19$1" );
2041 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2042 ( $m, $y ) = ( $3, "20$2" );
2044 return "Illegal expiration date: ". $self->paydate;
2046 $m = sprintf('%02d',$m);
2047 $self->paydate("$y-$m-01");
2048 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2049 return gettext('expired_card')
2051 && !$ignore_expired_card
2052 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2055 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2056 ( ! $conf->exists('require_cardname')
2057 || $self->payby !~ /^(CARD|DCRD)$/ )
2059 $self->payname( $self->first. " ". $self->getfield('last') );
2062 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2063 $self->payname =~ /^([\w \,\.\-\']*)$/
2064 or return gettext('illegal_name'). " payname: ". $self->payname;
2067 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2068 or return gettext('illegal_name'). " payname: ". $self->payname;
2074 ### end of stuff moved to cust_payby
2076 return "Please select an invoicing locale"
2079 && $conf->exists('cust_main-require_locale');
2081 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2082 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2086 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2088 warn "$me check AFTER: \n". $self->_dump
2091 $self->SUPER::check;
2096 Returns a list of fields which have ship_ duplicates.
2101 qw( last first company
2103 address1 address2 city county state zip country
2105 daytime night fax mobile
2109 =item has_ship_address
2111 Returns true if this customer record has a separate shipping address.
2115 sub has_ship_address {
2117 $self->bill_locationnum != $self->ship_locationnum;
2122 Returns a list of key/value pairs, with the following keys: address1,
2123 adddress2, city, county, state, zip, country, district, and geocode. The
2124 shipping address is used if present.
2130 $self->ship_location->location_hash;
2135 Returns all locations (see L<FS::cust_location>) for this customer.
2141 qsearch('cust_location', { 'custnum' => $self->custnum,
2142 'prospectnum' => '' } );
2147 Returns all contacts (see L<FS::contact>) for this customer.
2151 #already used :/ sub contact {
2154 qsearch('contact', { 'custnum' => $self->custnum } );
2159 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2166 'table' => 'cust_payby',
2167 'hashref' => { 'custnum' => $self->custnum },
2168 'order_by' => 'ORDER BY weight ASC',
2174 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2175 and L<FS::cust_pkg>) for this customer, except those on hold.
2177 Returns a list: an empty list on success or a list of errors.
2183 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2188 Unsuspends all suspended packages in the on-hold state (those without setup
2189 dates) for this customer.
2195 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2200 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2202 Returns a list: an empty list on success or a list of errors.
2208 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2211 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2213 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2214 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2215 of a list of pkgparts; the hashref has the following keys:
2219 =item pkgparts - listref of pkgparts
2221 =item (other options are passed to the suspend method)
2226 Returns a list: an empty list on success or a list of errors.
2230 sub suspend_if_pkgpart {
2232 my (@pkgparts, %opt);
2233 if (ref($_[0]) eq 'HASH'){
2234 @pkgparts = @{$_[0]{pkgparts}};
2239 grep { $_->suspend(%opt) }
2240 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2241 $self->unsuspended_pkgs;
2244 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2246 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2247 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2248 instead of a list of pkgparts; the hashref has the following keys:
2252 =item pkgparts - listref of pkgparts
2254 =item (other options are passed to the suspend method)
2258 Returns a list: an empty list on success or a list of errors.
2262 sub suspend_unless_pkgpart {
2264 my (@pkgparts, %opt);
2265 if (ref($_[0]) eq 'HASH'){
2266 @pkgparts = @{$_[0]{pkgparts}};
2271 grep { $_->suspend(%opt) }
2272 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2273 $self->unsuspended_pkgs;
2276 =item cancel [ OPTION => VALUE ... ]
2278 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2280 Available options are:
2284 =item quiet - can be set true to supress email cancellation notices.
2286 =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.
2288 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2290 =item nobill - can be set true to skip billing if it might otherwise be done.
2294 Always returns a list: an empty list on success or a list of errors.
2298 # nb that dates are not specified as valid options to this method
2301 my( $self, %opt ) = @_;
2303 warn "$me cancel called on customer ". $self->custnum. " with options ".
2304 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2307 return ( 'access denied' )
2308 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2310 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2312 #should try decryption (we might have the private key)
2313 # and if not maybe queue a job for the server that does?
2314 return ( "Can't (yet) ban encrypted credit cards" )
2315 if $self->is_encrypted($self->payinfo);
2317 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2318 my $error = $ban->insert;
2319 return ( $error ) if $error;
2323 my @pkgs = $self->ncancelled_pkgs;
2325 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2327 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2328 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2332 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2333 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2336 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2339 sub _banned_pay_hashref {
2350 'payby' => $payby2ban{$self->payby},
2351 'payinfo' => $self->payinfo,
2352 #don't ever *search* on reason! #'reason' =>
2356 sub _new_banned_pay_hashref {
2358 my $hr = $self->_banned_pay_hashref;
2359 $hr->{payinfo} = md5_base64($hr->{payinfo});
2365 Returns all notes (see L<FS::cust_main_note>) for this customer.
2370 my($self,$orderby_classnum) = (shift,shift);
2371 my $orderby = "_DATE DESC";
2372 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2373 qsearch( 'cust_main_note',
2374 { 'custnum' => $self->custnum },
2376 "ORDER BY $orderby",
2382 Returns the agent (see L<FS::agent>) for this customer.
2386 Returns the agent name (see L<FS::agent>) for this customer.
2392 $self->agent->agent;
2397 Returns any tags associated with this customer, as FS::cust_tag objects,
2398 or an empty list if there are no tags.
2402 Returns any tags associated with this customer, as FS::part_tag objects,
2403 or an empty list if there are no tags.
2409 map $_->part_tag, $self->cust_tag;
2415 Returns the customer class, as an FS::cust_class object, or the empty string
2416 if there is no customer class.
2420 Returns the customer category name, or the empty string if there is no customer
2427 my $cust_class = $self->cust_class;
2429 ? $cust_class->categoryname
2435 Returns the customer class name, or the empty string if there is no customer
2442 my $cust_class = $self->cust_class;
2444 ? $cust_class->classname
2450 Returns the external tax status, as an FS::tax_status object, or the empty
2451 string if there is no tax status.
2457 if ( $self->taxstatusnum ) {
2458 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2466 Returns the tax status code if there is one.
2472 my $tax_status = $self->tax_status;
2474 ? $tax_status->taxstatus
2478 =item BILLING METHODS
2480 Documentation on billing methods has been moved to
2481 L<FS::cust_main::Billing>.
2483 =item REALTIME BILLING METHODS
2485 Documentation on realtime billing methods has been moved to
2486 L<FS::cust_main::Billing_Realtime>.
2490 Removes the I<paycvv> field from the database directly.
2492 If there is an error, returns the error, otherwise returns false.
2498 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2499 or return dbh->errstr;
2500 $sth->execute($self->custnum)
2501 or return $sth->errstr;
2506 =item batch_card OPTION => VALUE...
2508 Adds a payment for this invoice to the pending credit card batch (see
2509 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2510 runs the payment using a realtime gateway.
2512 Options may include:
2514 B<amount>: the amount to be paid; defaults to the customer's balance minus
2515 any payments in transit.
2517 B<payby>: the payment method; defaults to cust_main.payby
2519 B<realtime>: runs this as a realtime payment instead of adding it to a
2522 B<invnum>: sets cust_pay_batch.invnum.
2524 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2525 the billing address for the payment; defaults to the customer's billing
2528 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2529 date, and name; defaults to those fields in cust_main.
2534 my ($self, %options) = @_;
2537 if (exists($options{amount})) {
2538 $amount = $options{amount};
2540 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2542 return '' unless $amount > 0;
2544 my $invnum = delete $options{invnum};
2545 my $payby = $options{payby} || $self->payby; #still dubious
2547 if ($options{'realtime'}) {
2548 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2554 my $oldAutoCommit = $FS::UID::AutoCommit;
2555 local $FS::UID::AutoCommit = 0;
2558 #this needs to handle mysql as well as Pg, like svc_acct.pm
2559 #(make it into a common function if folks need to do batching with mysql)
2560 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2561 or return "Cannot lock pay_batch: " . $dbh->errstr;
2565 'payby' => FS::payby->payby2payment($payby),
2567 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2569 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2571 unless ( $pay_batch ) {
2572 $pay_batch = new FS::pay_batch \%pay_batch;
2573 my $error = $pay_batch->insert;
2575 $dbh->rollback if $oldAutoCommit;
2576 die "error creating new batch: $error\n";
2580 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2581 'batchnum' => $pay_batch->batchnum,
2582 'custnum' => $self->custnum,
2585 foreach (qw( address1 address2 city state zip country latitude longitude
2586 payby payinfo paydate payname ))
2588 $options{$_} = '' unless exists($options{$_});
2591 my $loc = $self->bill_location;
2593 my $cust_pay_batch = new FS::cust_pay_batch ( {
2594 'batchnum' => $pay_batch->batchnum,
2595 'invnum' => $invnum || 0, # is there a better value?
2596 # this field should be
2598 # cust_bill_pay_batch now
2599 'custnum' => $self->custnum,
2600 'last' => $self->getfield('last'),
2601 'first' => $self->getfield('first'),
2602 'address1' => $options{address1} || $loc->address1,
2603 'address2' => $options{address2} || $loc->address2,
2604 'city' => $options{city} || $loc->city,
2605 'state' => $options{state} || $loc->state,
2606 'zip' => $options{zip} || $loc->zip,
2607 'country' => $options{country} || $loc->country,
2608 'payby' => $options{payby} || $self->payby,
2609 'payinfo' => $options{payinfo} || $self->payinfo,
2610 'exp' => $options{paydate} || $self->paydate,
2611 'payname' => $options{payname} || $self->payname,
2612 'amount' => $amount, # consolidating
2615 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2616 if $old_cust_pay_batch;
2619 if ($old_cust_pay_batch) {
2620 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2622 $error = $cust_pay_batch->insert;
2626 $dbh->rollback if $oldAutoCommit;
2630 my $unapplied = $self->total_unapplied_credits
2631 + $self->total_unapplied_payments
2632 + $self->in_transit_payments;
2633 foreach my $cust_bill ($self->open_cust_bill) {
2634 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2635 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2636 'invnum' => $cust_bill->invnum,
2637 'paybatchnum' => $cust_pay_batch->paybatchnum,
2638 'amount' => $cust_bill->owed,
2641 if ($unapplied >= $cust_bill_pay_batch->amount){
2642 $unapplied -= $cust_bill_pay_batch->amount;
2645 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2646 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2648 $error = $cust_bill_pay_batch->insert;
2650 $dbh->rollback if $oldAutoCommit;
2655 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2661 Returns the total owed for this customer on all invoices
2662 (see L<FS::cust_bill/owed>).
2668 $self->total_owed_date(2145859200); #12/31/2037
2671 =item total_owed_date TIME
2673 Returns the total owed for this customer on all invoices with date earlier than
2674 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2675 see L<Time::Local> and L<Date::Parse> for conversion functions.
2679 sub total_owed_date {
2683 my $custnum = $self->custnum;
2685 my $owed_sql = FS::cust_bill->owed_sql;
2688 SELECT SUM($owed_sql) FROM cust_bill
2689 WHERE custnum = $custnum
2693 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2697 =item total_owed_pkgnum PKGNUM
2699 Returns the total owed on all invoices for this customer's specific package
2700 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2704 sub total_owed_pkgnum {
2705 my( $self, $pkgnum ) = @_;
2706 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2709 =item total_owed_date_pkgnum TIME PKGNUM
2711 Returns the total owed for this customer's specific package when using
2712 experimental package balances on all invoices with date earlier than
2713 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2714 see L<Time::Local> and L<Date::Parse> for conversion functions.
2718 sub total_owed_date_pkgnum {
2719 my( $self, $time, $pkgnum ) = @_;
2722 foreach my $cust_bill (
2723 grep { $_->_date <= $time }
2724 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2726 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2728 sprintf( "%.2f", $total_bill );
2734 Returns the total amount of all payments.
2741 $total += $_->paid foreach $self->cust_pay;
2742 sprintf( "%.2f", $total );
2745 =item total_unapplied_credits
2747 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2748 customer. See L<FS::cust_credit/credited>.
2750 =item total_credited
2752 Old name for total_unapplied_credits. Don't use.
2756 sub total_credited {
2757 #carp "total_credited deprecated, use total_unapplied_credits";
2758 shift->total_unapplied_credits(@_);
2761 sub total_unapplied_credits {
2764 my $custnum = $self->custnum;
2766 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2769 SELECT SUM($unapplied_sql) FROM cust_credit
2770 WHERE custnum = $custnum
2773 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2777 =item total_unapplied_credits_pkgnum PKGNUM
2779 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2780 customer. See L<FS::cust_credit/credited>.
2784 sub total_unapplied_credits_pkgnum {
2785 my( $self, $pkgnum ) = @_;
2786 my $total_credit = 0;
2787 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2788 sprintf( "%.2f", $total_credit );
2792 =item total_unapplied_payments
2794 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2795 See L<FS::cust_pay/unapplied>.
2799 sub total_unapplied_payments {
2802 my $custnum = $self->custnum;
2804 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2807 SELECT SUM($unapplied_sql) FROM cust_pay
2808 WHERE custnum = $custnum
2811 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2815 =item total_unapplied_payments_pkgnum PKGNUM
2817 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2818 specific package when using experimental package balances. See
2819 L<FS::cust_pay/unapplied>.
2823 sub total_unapplied_payments_pkgnum {
2824 my( $self, $pkgnum ) = @_;
2825 my $total_unapplied = 0;
2826 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2827 sprintf( "%.2f", $total_unapplied );
2831 =item total_unapplied_refunds
2833 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2834 customer. See L<FS::cust_refund/unapplied>.
2838 sub total_unapplied_refunds {
2840 my $custnum = $self->custnum;
2842 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2845 SELECT SUM($unapplied_sql) FROM cust_refund
2846 WHERE custnum = $custnum
2849 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2855 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2856 total_unapplied_credits minus total_unapplied_payments).
2862 $self->balance_date_range;
2865 =item balance_date TIME
2867 Returns the balance for this customer, only considering invoices with date
2868 earlier than TIME (total_owed_date minus total_credited minus
2869 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2870 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2877 $self->balance_date_range(shift);
2880 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2882 Returns the balance for this customer, optionally considering invoices with
2883 date earlier than START_TIME, and not later than END_TIME
2884 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2886 Times are specified as SQL fragments or numeric
2887 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2888 L<Date::Parse> for conversion functions. The empty string can be passed
2889 to disable that time constraint completely.
2891 Accepts the same options as L<balance_date_sql>:
2895 =item unapplied_date
2897 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)
2901 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2902 time will be ignored. Note that START_TIME and END_TIME only limit the date
2903 range for invoices and I<unapplied> payments, credits, and refunds.
2909 sub balance_date_range {
2911 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2912 ') FROM cust_main WHERE custnum='. $self->custnum;
2913 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2916 =item balance_pkgnum PKGNUM
2918 Returns the balance for this customer's specific package when using
2919 experimental package balances (total_owed plus total_unrefunded, minus
2920 total_unapplied_credits minus total_unapplied_payments)
2924 sub balance_pkgnum {
2925 my( $self, $pkgnum ) = @_;
2928 $self->total_owed_pkgnum($pkgnum)
2929 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2930 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2931 - $self->total_unapplied_credits_pkgnum($pkgnum)
2932 - $self->total_unapplied_payments_pkgnum($pkgnum)
2936 =item in_transit_payments
2938 Returns the total of requests for payments for this customer pending in
2939 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2943 sub in_transit_payments {
2945 my $in_transit_payments = 0;
2946 foreach my $pay_batch ( qsearch('pay_batch', {
2949 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2950 'batchnum' => $pay_batch->batchnum,
2951 'custnum' => $self->custnum,
2953 $in_transit_payments += $cust_pay_batch->amount;
2956 sprintf( "%.2f", $in_transit_payments );
2961 Returns a hash of useful information for making a payment.
2971 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2972 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2973 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2977 For credit card transactions:
2989 For electronic check transactions:
3004 $return{balance} = $self->balance;
3006 $return{payname} = $self->payname
3007 || ( $self->first. ' '. $self->get('last') );
3009 $return{$_} = $self->bill_location->$_
3010 for qw(address1 address2 city state zip);
3012 $return{payby} = $self->payby;
3013 $return{stateid_state} = $self->stateid_state;
3015 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3016 $return{card_type} = cardtype($self->payinfo);
3017 $return{payinfo} = $self->paymask;
3019 @return{'month', 'year'} = $self->paydate_monthyear;
3023 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3024 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3025 $return{payinfo1} = $payinfo1;
3026 $return{payinfo2} = $payinfo2;
3027 $return{paytype} = $self->paytype;
3028 $return{paystate} = $self->paystate;
3032 #doubleclick protection
3034 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3040 =item paydate_monthyear
3042 Returns a two-element list consisting of the month and year of this customer's
3043 paydate (credit card expiration date for CARD customers)
3047 sub paydate_monthyear {
3049 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3051 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3060 Returns the exact time in seconds corresponding to the payment method
3061 expiration date. For CARD/DCRD customers this is the end of the month;
3062 for others (COMP is the only other payby that uses paydate) it's the start.
3063 Returns 0 if the paydate is empty or set to the far future.
3069 my ($month, $year) = $self->paydate_monthyear;
3070 return 0 if !$year or $year >= 2037;
3071 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3073 if ( $month == 13 ) {
3077 return timelocal(0,0,0,1,$month-1,$year) - 1;
3080 return timelocal(0,0,0,1,$month-1,$year);
3084 =item paydate_epoch_sql
3086 Class method. Returns an SQL expression to obtain the payment expiration date
3087 as a number of seconds.
3091 # Special expiration date behavior for non-CARD/DCRD customers has been
3092 # carefully preserved. Do we really use that?
3093 sub paydate_epoch_sql {
3095 my $table = shift || 'cust_main';
3096 my ($case1, $case2);
3097 if ( driver_name eq 'Pg' ) {
3098 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3099 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3101 elsif ( lc(driver_name) eq 'mysql' ) {
3102 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3103 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3106 return "CASE WHEN $table.payby IN('CARD','DCRD')
3112 =item tax_exemption TAXNAME
3117 my( $self, $taxname ) = @_;
3119 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3120 'taxname' => $taxname,
3125 =item cust_main_exemption
3127 =item invoicing_list [ ARRAYREF ]
3129 If an arguement is given, sets these email addresses as invoice recipients
3130 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3131 (except as warnings), so use check_invoicing_list first.
3133 Returns a list of email addresses (with svcnum entries expanded).
3135 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3136 check it without disturbing anything by passing nothing.
3138 This interface may change in the future.
3142 sub invoicing_list {
3143 my( $self, $arrayref ) = @_;
3146 my @cust_main_invoice;
3147 if ( $self->custnum ) {
3148 @cust_main_invoice =
3149 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3151 @cust_main_invoice = ();
3153 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3154 #warn $cust_main_invoice->destnum;
3155 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3156 #warn $cust_main_invoice->destnum;
3157 my $error = $cust_main_invoice->delete;
3158 warn $error if $error;
3161 if ( $self->custnum ) {
3162 @cust_main_invoice =
3163 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3165 @cust_main_invoice = ();
3167 my %seen = map { $_->address => 1 } @cust_main_invoice;
3168 foreach my $address ( @{$arrayref} ) {
3169 next if exists $seen{$address} && $seen{$address};
3170 $seen{$address} = 1;
3171 my $cust_main_invoice = new FS::cust_main_invoice ( {
3172 'custnum' => $self->custnum,
3175 my $error = $cust_main_invoice->insert;
3176 warn $error if $error;
3180 if ( $self->custnum ) {
3182 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3189 =item check_invoicing_list ARRAYREF
3191 Checks these arguements as valid input for the invoicing_list method. If there
3192 is an error, returns the error, otherwise returns false.
3196 sub check_invoicing_list {
3197 my( $self, $arrayref ) = @_;
3199 foreach my $address ( @$arrayref ) {
3201 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3202 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3205 my $cust_main_invoice = new FS::cust_main_invoice ( {
3206 'custnum' => $self->custnum,
3209 my $error = $self->custnum
3210 ? $cust_main_invoice->check
3211 : $cust_main_invoice->checkdest
3213 return $error if $error;
3217 return "Email address required"
3218 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3219 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3224 =item set_default_invoicing_list
3226 Sets the invoicing list to all accounts associated with this customer,
3227 overwriting any previous invoicing list.
3231 sub set_default_invoicing_list {
3233 $self->invoicing_list($self->all_emails);
3238 Returns the email addresses of all accounts provisioned for this customer.
3245 foreach my $cust_pkg ( $self->all_pkgs ) {
3246 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3248 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3249 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3251 $list{$_}=1 foreach map { $_->email } @svc_acct;
3256 =item invoicing_list_addpost
3258 Adds postal invoicing to this customer. If this customer is already configured
3259 to receive postal invoices, does nothing.
3263 sub invoicing_list_addpost {
3265 return if grep { $_ eq 'POST' } $self->invoicing_list;
3266 my @invoicing_list = $self->invoicing_list;
3267 push @invoicing_list, 'POST';
3268 $self->invoicing_list(\@invoicing_list);
3271 =item invoicing_list_emailonly
3273 Returns the list of email invoice recipients (invoicing_list without non-email
3274 destinations such as POST and FAX).
3278 sub invoicing_list_emailonly {
3280 warn "$me invoicing_list_emailonly called"
3282 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3285 =item invoicing_list_emailonly_scalar
3287 Returns the list of email invoice recipients (invoicing_list without non-email
3288 destinations such as POST and FAX) as a comma-separated scalar.
3292 sub invoicing_list_emailonly_scalar {
3294 warn "$me invoicing_list_emailonly_scalar called"
3296 join(', ', $self->invoicing_list_emailonly);
3299 =item referral_custnum_cust_main
3301 Returns the customer who referred this customer (or the empty string, if
3302 this customer was not referred).
3304 Note the difference with referral_cust_main method: This method,
3305 referral_custnum_cust_main returns the single customer (if any) who referred
3306 this customer, while referral_cust_main returns an array of customers referred
3311 sub referral_custnum_cust_main {
3313 return '' unless $self->referral_custnum;
3314 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3317 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3319 Returns an array of customers referred by this customer (referral_custnum set
3320 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3321 customers referred by customers referred by this customer and so on, inclusive.
3322 The default behavior is DEPTH 1 (no recursion).
3324 Note the difference with referral_custnum_cust_main method: This method,
3325 referral_cust_main, returns an array of customers referred BY this customer,
3326 while referral_custnum_cust_main returns the single customer (if any) who
3327 referred this customer.
3331 sub referral_cust_main {
3333 my $depth = @_ ? shift : 1;
3334 my $exclude = @_ ? shift : {};
3337 map { $exclude->{$_->custnum}++; $_; }
3338 grep { ! $exclude->{ $_->custnum } }
3339 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3343 map { $_->referral_cust_main($depth-1, $exclude) }
3350 =item referral_cust_main_ncancelled
3352 Same as referral_cust_main, except only returns customers with uncancelled
3357 sub referral_cust_main_ncancelled {
3359 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3362 =item referral_cust_pkg [ DEPTH ]
3364 Like referral_cust_main, except returns a flat list of all unsuspended (and
3365 uncancelled) packages for each customer. The number of items in this list may
3366 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3370 sub referral_cust_pkg {
3372 my $depth = @_ ? shift : 1;
3374 map { $_->unsuspended_pkgs }
3375 grep { $_->unsuspended_pkgs }
3376 $self->referral_cust_main($depth);
3379 =item referring_cust_main
3381 Returns the single cust_main record for the customer who referred this customer
3382 (referral_custnum), or false.
3386 sub referring_cust_main {
3388 return '' unless $self->referral_custnum;
3389 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3392 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3394 Applies a credit to this customer. If there is an error, returns the error,
3395 otherwise returns false.
3397 REASON can be a text string, an FS::reason object, or a scalar reference to
3398 a reasonnum. If a text string, it will be automatically inserted as a new
3399 reason, and a 'reason_type' option must be passed to indicate the
3400 FS::reason_type for the new reason.
3402 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3403 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3404 I<commission_pkgnum>.
3406 Any other options are passed to FS::cust_credit::insert.
3411 my( $self, $amount, $reason, %options ) = @_;
3413 my $cust_credit = new FS::cust_credit {
3414 'custnum' => $self->custnum,
3415 'amount' => $amount,
3418 if ( ref($reason) ) {
3420 if ( ref($reason) eq 'SCALAR' ) {
3421 $cust_credit->reasonnum( $$reason );
3423 $cust_credit->reasonnum( $reason->reasonnum );
3427 $cust_credit->set('reason', $reason)
3430 $cust_credit->$_( delete $options{$_} )
3431 foreach grep exists($options{$_}),
3432 qw( addlinfo eventnum ),
3433 map "commission_$_", qw( agentnum salesnum pkgnum );
3435 $cust_credit->insert(%options);
3439 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3441 Creates a one-time charge for this customer. If there is an error, returns
3442 the error, otherwise returns false.
3444 New-style, with a hashref of options:
3446 my $error = $cust_main->charge(
3450 'start_date' => str2time('7/4/2009'),
3451 'pkg' => 'Description',
3452 'comment' => 'Comment',
3453 'additional' => [], #extra invoice detail
3454 'classnum' => 1, #pkg_class
3456 'setuptax' => '', # or 'Y' for tax exempt
3458 'locationnum'=> 1234, # optional
3461 'taxclass' => 'Tax class',
3464 'taxproduct' => 2, #part_pkg_taxproduct
3465 'override' => {}, #XXX describe
3467 #will be filled in with the new object
3468 'cust_pkg_ref' => \$cust_pkg,
3470 #generate an invoice immediately
3472 'invoice_terms' => '', #with these terms
3478 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3484 my ( $amount, $quantity, $start_date, $classnum );
3485 my ( $pkg, $comment, $additional );
3486 my ( $setuptax, $taxclass ); #internal taxes
3487 my ( $taxproduct, $override ); #vendor (CCH) taxes
3489 my $cust_pkg_ref = '';
3490 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3492 if ( ref( $_[0] ) ) {
3493 $amount = $_[0]->{amount};
3494 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3495 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3496 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3497 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3498 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3499 : '$'. sprintf("%.2f",$amount);
3500 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3501 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3502 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3503 $additional = $_[0]->{additional} || [];
3504 $taxproduct = $_[0]->{taxproductnum};
3505 $override = { '' => $_[0]->{tax_override} };
3506 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3507 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3508 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3509 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3514 $pkg = @_ ? shift : 'One-time charge';
3515 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3517 $taxclass = @_ ? shift : '';
3521 local $SIG{HUP} = 'IGNORE';
3522 local $SIG{INT} = 'IGNORE';
3523 local $SIG{QUIT} = 'IGNORE';
3524 local $SIG{TERM} = 'IGNORE';
3525 local $SIG{TSTP} = 'IGNORE';
3526 local $SIG{PIPE} = 'IGNORE';
3528 my $oldAutoCommit = $FS::UID::AutoCommit;
3529 local $FS::UID::AutoCommit = 0;
3532 my $part_pkg = new FS::part_pkg ( {
3534 'comment' => $comment,
3538 'classnum' => ( $classnum ? $classnum : '' ),
3539 'setuptax' => $setuptax,
3540 'taxclass' => $taxclass,
3541 'taxproductnum' => $taxproduct,
3544 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3545 ( 0 .. @$additional - 1 )
3547 'additional_count' => scalar(@$additional),
3548 'setup_fee' => $amount,
3551 my $error = $part_pkg->insert( options => \%options,
3552 tax_overrides => $override,
3555 $dbh->rollback if $oldAutoCommit;
3559 my $pkgpart = $part_pkg->pkgpart;
3560 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3561 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3562 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3563 $error = $type_pkgs->insert;
3565 $dbh->rollback if $oldAutoCommit;
3570 my $cust_pkg = new FS::cust_pkg ( {
3571 'custnum' => $self->custnum,
3572 'pkgpart' => $pkgpart,
3573 'quantity' => $quantity,
3574 'start_date' => $start_date,
3575 'no_auto' => $no_auto,
3576 'locationnum'=> $locationnum,
3579 $error = $cust_pkg->insert;
3581 $dbh->rollback if $oldAutoCommit;
3583 } elsif ( $cust_pkg_ref ) {
3584 ${$cust_pkg_ref} = $cust_pkg;
3588 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3589 'pkg_list' => [ $cust_pkg ],
3592 $dbh->rollback if $oldAutoCommit;
3597 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3602 #=item charge_postal_fee
3604 #Applies a one time charge this customer. If there is an error,
3605 #returns the error, returns the cust_pkg charge object or false
3606 #if there was no charge.
3610 # This should be a customer event. For that to work requires that bill
3611 # also be a customer event.
3613 sub charge_postal_fee {
3616 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3617 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3619 my $cust_pkg = new FS::cust_pkg ( {
3620 'custnum' => $self->custnum,
3621 'pkgpart' => $pkgpart,
3625 my $error = $cust_pkg->insert;
3626 $error ? $error : $cust_pkg;
3629 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3631 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3633 Optionally, a list or hashref of additional arguments to the qsearch call can
3640 my $opt = ref($_[0]) ? shift : { @_ };
3642 #return $self->num_cust_bill unless wantarray || keys %$opt;
3644 $opt->{'table'} = 'cust_bill';
3645 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3646 $opt->{'hashref'}{'custnum'} = $self->custnum;
3647 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3649 map { $_ } #behavior of sort undefined in scalar context
3650 sort { $a->_date <=> $b->_date }
3654 =item open_cust_bill
3656 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3661 sub open_cust_bill {
3665 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3671 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3673 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3677 sub legacy_cust_bill {
3680 #return $self->num_legacy_cust_bill unless wantarray;
3682 map { $_ } #behavior of sort undefined in scalar context
3683 sort { $a->_date <=> $b->_date }
3684 qsearch({ 'table' => 'legacy_cust_bill',
3685 'hashref' => { 'custnum' => $self->custnum, },
3686 'order_by' => 'ORDER BY _date ASC',
3690 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3692 Returns all the statements (see L<FS::cust_statement>) for this customer.
3694 Optionally, a list or hashref of additional arguments to the qsearch call can
3699 =item cust_bill_void
3701 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3705 sub cust_bill_void {
3708 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3709 sort { $a->_date <=> $b->_date }
3710 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3713 sub cust_statement {
3715 my $opt = ref($_[0]) ? shift : { @_ };
3717 #return $self->num_cust_statement unless wantarray || keys %$opt;
3719 $opt->{'table'} = 'cust_statement';
3720 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3721 $opt->{'hashref'}{'custnum'} = $self->custnum;
3722 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3724 map { $_ } #behavior of sort undefined in scalar context
3725 sort { $a->_date <=> $b->_date }
3729 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3731 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3733 Optionally, a list or hashref of additional arguments to the qsearch call can
3734 be passed following the SVCDB.
3741 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3742 warn "$me svc_x requires a svcdb";
3745 my $opt = ref($_[0]) ? shift : { @_ };
3747 $opt->{'table'} = $svcdb;
3748 $opt->{'addl_from'} =
3749 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3750 ($opt->{'addl_from'} || '');
3752 my $custnum = $self->custnum;
3753 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3754 my $where = "cust_pkg.custnum = $custnum";
3756 my $extra_sql = $opt->{'extra_sql'} || '';
3757 if ( keys %{ $opt->{'hashref'} } ) {
3758 $extra_sql = " AND $where $extra_sql";
3761 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3762 $extra_sql = "WHERE $where AND $1";
3765 $extra_sql = "WHERE $where $extra_sql";
3768 $opt->{'extra_sql'} = $extra_sql;
3773 # required for use as an eventtable;
3776 $self->svc_x('svc_acct', @_);
3781 Returns all the credits (see L<FS::cust_credit>) for this customer.
3787 map { $_ } #return $self->num_cust_credit unless wantarray;
3788 sort { $a->_date <=> $b->_date }
3789 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3792 =item cust_credit_pkgnum
3794 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3795 package when using experimental package balances.
3799 sub cust_credit_pkgnum {
3800 my( $self, $pkgnum ) = @_;
3801 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3802 sort { $a->_date <=> $b->_date }
3803 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3804 'pkgnum' => $pkgnum,
3809 =item cust_credit_void
3811 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3815 sub cust_credit_void {
3818 sort { $a->_date <=> $b->_date }
3819 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3824 Returns all the payments (see L<FS::cust_pay>) for this customer.
3830 my $opt = ref($_[0]) ? shift : { @_ };
3832 return $self->num_cust_pay unless wantarray || keys %$opt;
3834 $opt->{'table'} = 'cust_pay';
3835 $opt->{'hashref'}{'custnum'} = $self->custnum;
3837 map { $_ } #behavior of sort undefined in scalar context
3838 sort { $a->_date <=> $b->_date }
3845 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3846 called automatically when the cust_pay method is used in a scalar context.
3852 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3853 my $sth = dbh->prepare($sql) or die dbh->errstr;
3854 $sth->execute($self->custnum) or die $sth->errstr;
3855 $sth->fetchrow_arrayref->[0];
3858 =item unapplied_cust_pay
3860 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3864 sub unapplied_cust_pay {
3868 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3874 =item cust_pay_pkgnum
3876 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3877 package when using experimental package balances.
3881 sub cust_pay_pkgnum {
3882 my( $self, $pkgnum ) = @_;
3883 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3884 sort { $a->_date <=> $b->_date }
3885 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3886 'pkgnum' => $pkgnum,
3893 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3899 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3900 sort { $a->_date <=> $b->_date }
3901 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3904 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3906 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3908 Optionally, a list or hashref of additional arguments to the qsearch call can
3913 sub cust_pay_batch {
3915 my $opt = ref($_[0]) ? shift : { @_ };
3917 #return $self->num_cust_statement unless wantarray || keys %$opt;
3919 $opt->{'table'} = 'cust_pay_batch';
3920 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3921 $opt->{'hashref'}{'custnum'} = $self->custnum;
3922 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3924 map { $_ } #behavior of sort undefined in scalar context
3925 sort { $a->paybatchnum <=> $b->paybatchnum }
3929 =item cust_pay_pending
3931 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3932 (without status "done").
3936 sub cust_pay_pending {
3938 return $self->num_cust_pay_pending unless wantarray;
3939 sort { $a->_date <=> $b->_date }
3940 qsearch( 'cust_pay_pending', {
3941 'custnum' => $self->custnum,
3942 'status' => { op=>'!=', value=>'done' },
3947 =item cust_pay_pending_attempt
3949 Returns all payment attempts / declined payments for this customer, as pending
3950 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3951 a corresponding payment (see L<FS::cust_pay>).
3955 sub cust_pay_pending_attempt {
3957 return $self->num_cust_pay_pending_attempt unless wantarray;
3958 sort { $a->_date <=> $b->_date }
3959 qsearch( 'cust_pay_pending', {
3960 'custnum' => $self->custnum,
3967 =item num_cust_pay_pending
3969 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3970 customer (without status "done"). Also called automatically when the
3971 cust_pay_pending method is used in a scalar context.
3975 sub num_cust_pay_pending {
3978 " SELECT COUNT(*) FROM cust_pay_pending ".
3979 " WHERE custnum = ? AND status != 'done' ",
3984 =item num_cust_pay_pending_attempt
3986 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3987 customer, with status "done" but without a corresp. Also called automatically when the
3988 cust_pay_pending method is used in a scalar context.
3992 sub num_cust_pay_pending_attempt {
3995 " SELECT COUNT(*) FROM cust_pay_pending ".
3996 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4003 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4009 map { $_ } #return $self->num_cust_refund unless wantarray;
4010 sort { $a->_date <=> $b->_date }
4011 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4014 =item display_custnum
4016 Returns the displayed customer number for this customer: agent_custid if
4017 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4021 sub display_custnum {
4024 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4025 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
4026 if ( $special eq 'CoStAg' ) {
4027 $prefix = uc( join('',
4029 ($self->state =~ /^(..)/),
4030 $prefix || ($self->agent->agent =~ /^(..)/)
4033 elsif ( $special eq 'CoStCl' ) {
4034 $prefix = uc( join('',
4036 ($self->state =~ /^(..)/),
4037 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
4040 # add any others here if needed
4043 my $length = $conf->config('cust_main-custnum-display_length');
4044 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
4045 return $self->agent_custid;
4046 } elsif ( $prefix ) {
4047 $length = 8 if !defined($length);
4049 sprintf('%0'.$length.'d', $self->custnum)
4050 } elsif ( $length ) {
4051 return sprintf('%0'.$length.'d', $self->custnum);
4053 return $self->custnum;
4059 Returns a name string for this customer, either "Company (Last, First)" or
4066 my $name = $self->contact;
4067 $name = $self->company. " ($name)" if $self->company;
4071 =item service_contact
4073 Returns the L<FS::contact> object for this customer that has the 'Service'
4074 contact class, or undef if there is no such contact. Deprecated; don't use
4079 sub service_contact {
4081 if ( !exists($self->{service_contact}) ) {
4082 my $classnum = $self->scalar_sql(
4083 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4084 ) || 0; #if it's zero, qsearchs will return nothing
4085 $self->{service_contact} = qsearchs('contact', {
4086 'classnum' => $classnum, 'custnum' => $self->custnum
4089 $self->{service_contact};
4094 Returns a name string for this (service/shipping) contact, either
4095 "Company (Last, First)" or "Last, First".
4102 my $name = $self->ship_contact;
4103 $name = $self->company. " ($name)" if $self->company;
4109 Returns a name string for this customer, either "Company" or "First Last".
4115 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4118 =item ship_name_short
4120 Returns a name string for this (service/shipping) contact, either "Company"
4125 sub ship_name_short {
4127 $self->service_contact
4128 ? $self->ship_contact_firstlast
4134 Returns this customer's full (billing) contact name only, "Last, First"
4140 $self->get('last'). ', '. $self->first;
4145 Returns this customer's full (shipping) contact name only, "Last, First"
4151 my $contact = $self->service_contact || $self;
4152 $contact->get('last') . ', ' . $contact->get('first');
4155 =item contact_firstlast
4157 Returns this customers full (billing) contact name only, "First Last".
4161 sub contact_firstlast {
4163 $self->first. ' '. $self->get('last');
4166 =item ship_contact_firstlast
4168 Returns this customer's full (shipping) contact name only, "First Last".
4172 sub ship_contact_firstlast {
4174 my $contact = $self->service_contact || $self;
4175 $contact->get('first') . ' '. $contact->get('last');
4178 #XXX this doesn't work in 3.x+
4181 #Returns this customer's full country name
4187 # code2country($self->country);
4190 sub bill_country_full {
4192 code2country($self->bill_location->country);
4195 sub ship_country_full {
4197 code2country($self->ship_location->country);
4200 =item county_state_county [ PREFIX ]
4202 Returns a string consisting of just the county, state and country.
4206 sub county_state_country {
4209 if ( @_ && $_[0] && $self->has_ship_address ) {
4210 $locationnum = $self->ship_locationnum;
4212 $locationnum = $self->bill_locationnum;
4214 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4215 $cust_location->county_state_country;
4218 =item geocode DATA_VENDOR
4220 Returns a value for the customer location as encoded by DATA_VENDOR.
4221 Currently this only makes sense for "CCH" as DATA_VENDOR.
4229 Returns a status string for this customer, currently:
4233 =item prospect - No packages have ever been ordered
4235 =item ordered - Recurring packages all are new (not yet billed).
4237 =item active - One or more recurring packages is active
4239 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4241 =item suspended - All non-cancelled recurring packages are suspended
4243 =item cancelled - All recurring packages are cancelled
4247 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4248 cust_main-status_module configuration option.
4252 sub status { shift->cust_status(@_); }
4256 for my $status ( FS::cust_main->statuses() ) {
4257 my $method = $status.'_sql';
4258 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4259 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4260 $sth->execute( ($self->custnum) x $numnum )
4261 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4262 return $status if $sth->fetchrow_arrayref->[0];
4266 =item ucfirst_cust_status
4268 =item ucfirst_status
4270 Returns the status with the first character capitalized.
4274 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4276 sub ucfirst_cust_status {
4278 ucfirst($self->cust_status);
4283 Returns a hex triplet color string for this customer's status.
4287 sub statuscolor { shift->cust_statuscolor(@_); }
4289 sub cust_statuscolor {
4291 __PACKAGE__->statuscolors->{$self->cust_status};
4294 =item tickets [ STATUS ]
4296 Returns an array of hashes representing the customer's RT tickets.
4298 An optional status (or arrayref or hashref of statuses) may be specified.
4304 my $status = ( @_ && $_[0] ) ? shift : '';
4306 my $num = $conf->config('cust_main-max_tickets') || 10;
4309 if ( $conf->config('ticket_system') ) {
4310 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4312 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4321 foreach my $priority (
4322 $conf->config('ticket_system-custom_priority_field-values'), ''
4324 last if scalar(@tickets) >= $num;
4326 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4327 $num - scalar(@tickets),
4338 # Return services representing svc_accts in customer support packages
4339 sub support_services {
4341 my %packages = map { $_ => 1 } $conf->config('support_packages');
4343 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4344 grep { $_->part_svc->svcdb eq 'svc_acct' }
4345 map { $_->cust_svc }
4346 grep { exists $packages{ $_->pkgpart } }
4347 $self->ncancelled_pkgs;
4351 # Return a list of latitude/longitude for one of the services (if any)
4352 sub service_coordinates {
4356 grep { $_->latitude && $_->longitude }
4358 map { $_->cust_svc }
4359 $self->ncancelled_pkgs;
4361 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4366 Returns a masked version of the named field
4371 my ($self,$field) = @_;
4375 'x'x(length($self->getfield($field))-4).
4376 substr($self->getfield($field), (length($self->getfield($field))-4));
4382 =head1 CLASS METHODS
4388 Class method that returns the list of possible status strings for customers
4389 (see L<the status method|/status>). For example:
4391 @statuses = FS::cust_main->statuses();
4397 keys %{ $self->statuscolors };
4400 =item cust_status_sql
4402 Returns an SQL fragment to determine the status of a cust_main record, as a
4407 sub cust_status_sql {
4409 for my $status ( FS::cust_main->statuses() ) {
4410 my $method = $status.'_sql';
4411 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4420 Returns an SQL expression identifying prospective cust_main records (customers
4421 with no packages ever ordered)
4425 use vars qw($select_count_pkgs);
4426 $select_count_pkgs =
4427 "SELECT COUNT(*) FROM cust_pkg
4428 WHERE cust_pkg.custnum = cust_main.custnum";
4430 sub select_count_pkgs_sql {
4435 " 0 = ( $select_count_pkgs ) ";
4440 Returns an SQL expression identifying ordered cust_main records (customers with
4441 no active packages, but recurring packages not yet setup or one time charges
4447 FS::cust_main->none_active_sql.
4448 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4453 Returns an SQL expression identifying active cust_main records (customers with
4454 active recurring packages).
4459 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4462 =item none_active_sql
4464 Returns an SQL expression identifying cust_main records with no active
4465 recurring packages. This includes customers of status prospect, ordered,
4466 inactive, and suspended.
4470 sub none_active_sql {
4471 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4476 Returns an SQL expression identifying inactive cust_main records (customers with
4477 no active recurring packages, but otherwise unsuspended/uncancelled).
4482 FS::cust_main->none_active_sql.
4483 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4489 Returns an SQL expression identifying suspended cust_main records.
4494 sub suspended_sql { susp_sql(@_); }
4496 FS::cust_main->none_active_sql.
4497 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4503 Returns an SQL expression identifying cancelled cust_main records.
4507 sub cancel_sql { shift->cancelled_sql(@_); }
4510 =item uncancelled_sql
4512 Returns an SQL expression identifying un-cancelled cust_main records.
4516 sub uncancelled_sql { uncancel_sql(@_); }
4517 sub uncancel_sql { "
4518 ( 0 < ( $select_count_pkgs
4519 AND ( cust_pkg.cancel IS NULL
4520 OR cust_pkg.cancel = 0
4523 OR 0 = ( $select_count_pkgs )
4529 Returns an SQL fragment to retreive the balance.
4534 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4535 WHERE cust_bill.custnum = cust_main.custnum )
4536 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4537 WHERE cust_pay.custnum = cust_main.custnum )
4538 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4539 WHERE cust_credit.custnum = cust_main.custnum )
4540 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4541 WHERE cust_refund.custnum = cust_main.custnum )
4544 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4546 Returns an SQL fragment to retreive the balance for this customer, optionally
4547 considering invoices with date earlier than START_TIME, and not
4548 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4549 total_unapplied_payments).
4551 Times are specified as SQL fragments or numeric
4552 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4553 L<Date::Parse> for conversion functions. The empty string can be passed
4554 to disable that time constraint completely.
4556 Available options are:
4560 =item unapplied_date
4562 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)
4567 set to true to remove all customer comparison clauses, for totals
4572 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4577 JOIN clause (typically used with the total option)
4581 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4582 time will be ignored. Note that START_TIME and END_TIME only limit the date
4583 range for invoices and I<unapplied> payments, credits, and refunds.
4589 sub balance_date_sql {
4590 my( $class, $start, $end, %opt ) = @_;
4592 my $cutoff = $opt{'cutoff'};
4594 my $owed = FS::cust_bill->owed_sql($cutoff);
4595 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4596 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4597 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4599 my $j = $opt{'join'} || '';
4601 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4602 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4603 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4604 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4606 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4607 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4608 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4609 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4614 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4616 Returns an SQL fragment to retreive the total unapplied payments for this
4617 customer, only considering payments with date earlier than START_TIME, and
4618 optionally not later than END_TIME.
4620 Times are specified as SQL fragments or numeric
4621 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4622 L<Date::Parse> for conversion functions. The empty string can be passed
4623 to disable that time constraint completely.
4625 Available options are:
4629 sub unapplied_payments_date_sql {
4630 my( $class, $start, $end, %opt ) = @_;
4632 my $cutoff = $opt{'cutoff'};
4634 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4636 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4637 'unapplied_date'=>1 );
4639 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4642 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4644 Helper method for balance_date_sql; name (and usage) subject to change
4645 (suggestions welcome).
4647 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4648 cust_refund, cust_credit or cust_pay).
4650 If TABLE is "cust_bill" or the unapplied_date option is true, only
4651 considers records with date earlier than START_TIME, and optionally not
4652 later than END_TIME .
4656 sub _money_table_where {
4657 my( $class, $table, $start, $end, %opt ) = @_;
4660 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4661 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4662 push @where, "$table._date <= $start" if defined($start) && length($start);
4663 push @where, "$table._date > $end" if defined($end) && length($end);
4665 push @where, @{$opt{'where'}} if $opt{'where'};
4666 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4672 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4673 use FS::cust_main::Search;
4676 FS::cust_main::Search->search(@_);
4685 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4687 Deprecated. Use event notification and message templates
4688 (L<FS::msg_template>) instead.
4690 Sends a templated email notification to the customer (see L<Text::Template>).
4692 OPTIONS is a hash and may include
4694 I<from> - the email sender (default is invoice_from)
4696 I<to> - comma-separated scalar or arrayref of recipients
4697 (default is invoicing_list)
4699 I<subject> - The subject line of the sent email notification
4700 (default is "Notice from company_name")
4702 I<extra_fields> - a hashref of name/value pairs which will be substituted
4705 The following variables are vavailable in the template.
4707 I<$first> - the customer first name
4708 I<$last> - the customer last name
4709 I<$company> - the customer company
4710 I<$payby> - a description of the method of payment for the customer
4711 # would be nice to use FS::payby::shortname
4712 I<$payinfo> - the account information used to collect for this customer
4713 I<$expdate> - the expiration of the customer payment in seconds from epoch
4718 my ($self, $template, %options) = @_;
4720 return unless $conf->exists($template);
4722 my $from = $conf->config('invoice_from', $self->agentnum)
4723 if $conf->exists('invoice_from', $self->agentnum);
4724 $from = $options{from} if exists($options{from});
4726 my $to = join(',', $self->invoicing_list_emailonly);
4727 $to = $options{to} if exists($options{to});
4729 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4730 if $conf->exists('company_name', $self->agentnum);
4731 $subject = $options{subject} if exists($options{subject});
4733 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4734 SOURCE => [ map "$_\n",
4735 $conf->config($template)]
4737 or die "can't create new Text::Template object: Text::Template::ERROR";
4738 $notify_template->compile()
4739 or die "can't compile template: Text::Template::ERROR";
4741 $FS::notify_template::_template::company_name =
4742 $conf->config('company_name', $self->agentnum);
4743 $FS::notify_template::_template::company_address =
4744 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4746 my $paydate = $self->paydate || '2037-12-31';
4747 $FS::notify_template::_template::first = $self->first;
4748 $FS::notify_template::_template::last = $self->last;
4749 $FS::notify_template::_template::company = $self->company;
4750 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4751 my $payby = $self->payby;
4752 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4753 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4755 #credit cards expire at the end of the month/year of their exp date
4756 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4757 $FS::notify_template::_template::payby = 'credit card';
4758 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4759 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4761 }elsif ($payby eq 'COMP') {
4762 $FS::notify_template::_template::payby = 'complimentary account';
4764 $FS::notify_template::_template::payby = 'current method';
4766 $FS::notify_template::_template::expdate = $expire_time;
4768 for (keys %{$options{extra_fields}}){
4770 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4773 send_email(from => $from,
4775 subject => $subject,
4776 body => $notify_template->fill_in( PACKAGE =>
4777 'FS::notify_template::_template' ),
4782 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4784 Generates a templated notification to the customer (see L<Text::Template>).
4786 OPTIONS is a hash and may include
4788 I<extra_fields> - a hashref of name/value pairs which will be substituted
4789 into the template. These values may override values mentioned below
4790 and those from the customer record.
4792 The following variables are available in the template instead of or in addition
4793 to the fields of the customer record.
4795 I<$payby> - a description of the method of payment for the customer
4796 # would be nice to use FS::payby::shortname
4797 I<$payinfo> - the masked account information used to collect for this customer
4798 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4799 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4803 # a lot like cust_bill::print_latex
4804 sub generate_letter {
4805 my ($self, $template, %options) = @_;
4807 return unless $conf->exists($template);
4809 my $letter_template = new Text::Template
4811 SOURCE => [ map "$_\n", $conf->config($template)],
4812 DELIMITERS => [ '[@--', '--@]' ],
4814 or die "can't create new Text::Template object: Text::Template::ERROR";
4816 $letter_template->compile()
4817 or die "can't compile template: Text::Template::ERROR";
4819 my %letter_data = map { $_ => $self->$_ } $self->fields;
4820 $letter_data{payinfo} = $self->mask_payinfo;
4822 #my $paydate = $self->paydate || '2037-12-31';
4823 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4825 my $payby = $self->payby;
4826 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4827 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4829 #credit cards expire at the end of the month/year of their exp date
4830 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4831 $letter_data{payby} = 'credit card';
4832 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4833 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4835 }elsif ($payby eq 'COMP') {
4836 $letter_data{payby} = 'complimentary account';
4838 $letter_data{payby} = 'current method';
4840 $letter_data{expdate} = $expire_time;
4842 for (keys %{$options{extra_fields}}){
4843 $letter_data{$_} = $options{extra_fields}->{$_};
4846 unless(exists($letter_data{returnaddress})){
4847 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4848 $self->agent_template)
4850 if ( length($retadd) ) {
4851 $letter_data{returnaddress} = $retadd;
4852 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4853 $letter_data{returnaddress} =
4854 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4858 ( $conf->config('company_name', $self->agentnum),
4859 $conf->config('company_address', $self->agentnum),
4863 $letter_data{returnaddress} = '~';
4867 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4869 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4871 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4873 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4877 ) or die "can't open temp file: $!\n";
4878 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4879 or die "can't write temp file: $!\n";
4881 $letter_data{'logo_file'} = $lh->filename;
4883 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4887 ) or die "can't open temp file: $!\n";
4889 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4891 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4892 return ($1, $letter_data{'logo_file'});
4896 =item print_ps TEMPLATE
4898 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4904 my($file, $lfile) = $self->generate_letter(@_);
4905 my $ps = FS::Misc::generate_ps($file);
4906 unlink($file.'.tex');
4912 =item print TEMPLATE
4914 Prints the filled in template.
4916 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4920 sub queueable_print {
4923 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4924 or die "invalid customer number: " . $opt{custnum};
4926 my $error = $self->print( { 'template' => $opt{template} } );
4927 die $error if $error;
4931 my ($self, $template) = (shift, shift);
4933 [ $self->print_ps($template) ],
4934 'agentnum' => $self->agentnum,
4938 #these three subs should just go away once agent stuff is all config overrides
4940 sub agent_template {
4942 $self->_agent_plandata('agent_templatename');
4945 sub agent_invoice_from {
4947 $self->_agent_plandata('agent_invoice_from');
4950 sub _agent_plandata {
4951 my( $self, $option ) = @_;
4953 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4954 #agent-specific Conf
4956 use FS::part_event::Condition;
4958 my $agentnum = $self->agentnum;
4960 my $regexp = regexp_sql();
4962 my $part_event_option =
4964 'select' => 'part_event_option.*',
4965 'table' => 'part_event_option',
4967 LEFT JOIN part_event USING ( eventpart )
4968 LEFT JOIN part_event_option AS peo_agentnum
4969 ON ( part_event.eventpart = peo_agentnum.eventpart
4970 AND peo_agentnum.optionname = 'agentnum'
4971 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4973 LEFT JOIN part_event_condition
4974 ON ( part_event.eventpart = part_event_condition.eventpart
4975 AND part_event_condition.conditionname = 'cust_bill_age'
4977 LEFT JOIN part_event_condition_option
4978 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4979 AND part_event_condition_option.optionname = 'age'
4982 #'hashref' => { 'optionname' => $option },
4983 #'hashref' => { 'part_event_option.optionname' => $option },
4985 " WHERE part_event_option.optionname = ". dbh->quote($option).
4986 " AND action = 'cust_bill_send_agent' ".
4987 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4988 " AND peo_agentnum.optionname = 'agentnum' ".
4989 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4991 CASE WHEN part_event_condition_option.optionname IS NULL
4993 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4995 , part_event.weight".
4999 unless ( $part_event_option ) {
5000 return $self->agent->invoice_template || ''
5001 if $option eq 'agent_templatename';
5005 $part_event_option->optionvalue;
5009 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5011 Subroutine (not a method), designed to be called from the queue.
5013 Takes a list of options and values.
5015 Pulls up the customer record via the custnum option and calls bill_and_collect.
5020 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5022 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5023 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5025 #without this errors don't get rolled back
5026 $args{'fatal'} = 1; # runs from job queue, will be caught
5028 $cust_main->bill_and_collect( %args );
5031 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5033 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5034 C<collect> part. This is used in batch tax calculation, where invoice
5035 generation and collection events have to be completely separated.
5039 sub queued_collect {
5041 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5043 $cust_main->collect(%args);
5046 sub process_bill_and_collect {
5049 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5050 or die "custnum '$param->{custnum}' not found!\n";
5051 $param->{'job'} = $job;
5052 $param->{'fatal'} = 1; # runs from job queue, will be caught
5053 $param->{'retry'} = 1;
5055 $cust_main->bill_and_collect( %$param );
5058 #starting to take quite a while for big dbs
5059 # (JRNL: journaled so it only happens once per database)
5060 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5061 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5062 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5063 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5064 # JRNL leading/trailing spaces in first, last, company
5065 # JRNL migrate to cust_payby
5066 # - otaker upgrade? journal and call it good? (double check to make sure
5067 # we're not still setting otaker here)
5069 #only going to get worse with new location stuff...
5071 sub _upgrade_data { #class method
5072 my ($class, %opts) = @_;
5075 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5078 #this seems to be the only expensive one.. why does it take so long?
5079 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5081 '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';
5082 FS::upgrade_journal->set_done('cust_main__signupdate');
5085 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5087 # fix yyyy-m-dd formatted paydates
5088 if ( driver_name =~ /^mysql/i ) {
5090 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5091 } else { # the SQL standard
5093 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5095 FS::upgrade_journal->set_done('cust_main__paydate');
5098 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5100 push @statements, #fix the weird BILL with a cc# in payinfo problem
5102 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5104 FS::upgrade_journal->set_done('cust_main__payinfo');
5109 foreach my $sql ( @statements ) {
5110 my $sth = dbh->prepare($sql) or die dbh->errstr;
5111 $sth->execute or die $sth->errstr;
5112 #warn ( (time - $t). " seconds\n" );
5116 local($ignore_expired_card) = 1;
5117 local($ignore_banned_card) = 1;
5118 local($skip_fuzzyfiles) = 1;
5119 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5121 FS::cust_main::Location->_upgrade_data(%opts);
5123 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5125 foreach my $cust_main ( qsearch({
5126 'table' => 'cust_main',
5128 'extra_sql' => 'WHERE '.
5130 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5131 qw( first last company )
5134 my $error = $cust_main->replace;
5135 die $error if $error;
5138 FS::upgrade_journal->set_done('cust_main__trimspaces');
5142 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5144 #we don't want to decrypt them, just stuff them as-is into cust_payby
5145 local(@encrypted_fields) = ();
5147 local($FS::cust_payby::ignore_expired_card) = 1;
5148 local($FS::cust_payby::ignore_banned_card) = 1;
5150 my @payfields = qw( payby payinfo paycvv paymask
5151 paydate paystart_month paystart_year payissue
5152 payname paystate paytype payip
5155 my $search = new FS::Cursor {
5156 'table' => 'cust_main',
5157 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5160 while (my $cust_main = $search->fetch) {
5162 my $cust_payby = new FS::cust_payby {
5163 'custnum' => $cust_main->custnum,
5165 map { $_ => $cust_main->$_(); } @payfields
5168 my $error = $cust_payby->insert;
5169 die $error if $error;
5171 $cust_main->setfield($_, '') foreach @payfields;
5172 $error = $cust_main->replace;
5173 die $error if $error;
5177 FS::upgrade_journal->set_done('cust_main__cust_payby');
5180 $class->_upgrade_otaker(%opts);
5190 The delete method should possibly take an FS::cust_main object reference
5191 instead of a scalar customer number.
5193 Bill and collect options should probably be passed as references instead of a
5196 There should probably be a configuration file with a list of allowed credit
5199 No multiple currency support (probably a larger project than just this module).
5201 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5203 Birthdates rely on negative epoch values.
5205 The payby for card/check batches is broken. With mixed batching, bad
5208 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5212 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5213 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5214 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.