5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6 FS::cust_main::NationalID
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::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
17 use vars qw( $DEBUG $me $conf $default_agent_custid $custnum_display_length
20 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
31 use Digest::MD5 qw(md5_base64);
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
36 use FS::UID qw( getotaker dbh driver_name );
37 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
38 use FS::Misc qw( generate_email send_email generate_ps do_print money_pretty card_types );
39 use FS::Msgcat qw(gettext);
46 use FS::cust_bill_void;
47 use FS::legacy_cust_bill;
49 use FS::cust_pay_pending;
50 use FS::cust_pay_void;
51 use FS::cust_pay_batch;
54 use FS::part_referral;
55 use FS::cust_main_county;
56 use FS::cust_location;
58 use FS::cust_main_exemption;
59 use FS::cust_tax_adjustment;
60 use FS::cust_tax_location;
62 use FS::cust_main_invoice;
64 use FS::prepay_credit;
70 use FS::payment_gateway;
71 use FS::agent_payment_gateway;
73 use FS::cust_main_note;
74 use FS::cust_attachment;
77 use FS::upgrade_journal;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 $me = '[FS::cust_main]';
87 $ignore_expired_card = 0;
88 $ignore_banned_card = 0;
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub {
99 install_callback FS::UID sub {
100 $conf = new FS::Conf;
101 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
102 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
107 my ( $hashref, $cache ) = @_;
108 if ( exists $hashref->{'pkgnum'} ) {
109 #@{ $self->{'_pkgnum'} } = ();
110 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
111 $self->{'_pkgnum'} = $subcache;
112 #push @{ $self->{'_pkgnum'} },
113 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
119 FS::cust_main - Object methods for cust_main records
125 $record = new FS::cust_main \%hash;
126 $record = new FS::cust_main { 'column' => 'value' };
128 $error = $record->insert;
130 $error = $new_record->replace($old_record);
132 $error = $record->delete;
134 $error = $record->check;
136 @cust_pkg = $record->all_pkgs;
138 @cust_pkg = $record->ncancelled_pkgs;
140 @cust_pkg = $record->suspended_pkgs;
142 $error = $record->bill;
143 $error = $record->bill %options;
144 $error = $record->bill 'time' => $time;
146 $error = $record->collect;
147 $error = $record->collect %options;
148 $error = $record->collect 'invoice_time' => $time,
153 An FS::cust_main object represents a customer. FS::cust_main inherits from
154 FS::Record. The following fields are currently supported:
160 Primary key (assigned automatically for new customers)
164 Agent (see L<FS::agent>)
168 Advertising source (see L<FS::part_referral>)
180 Cocial security number (optional)
204 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
208 Payment Information (See L<FS::payinfo_Mixin> for data format)
212 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
216 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
220 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
224 Start date month (maestro/solo cards only)
228 Start date year (maestro/solo cards only)
232 Issue number (maestro/solo cards only)
236 Name on card or billing name
240 IP address from which payment information was received
244 Tax exempt, empty or `Y'
248 Order taker (see L<FS::access_user>)
254 =item referral_custnum
256 Referring customer number
260 Enable individual CDR spooling, empty or `Y'
264 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
268 Discourage individual CDR printing, empty or `Y'
272 Allow self-service editing of ticket subjects, empty or 'Y'
274 =item calling_list_exempt
276 Do not call, empty or 'Y'
278 =item invoice_ship_address
280 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
290 Creates a new customer. To add the customer to the database, see L<"insert">.
292 Note that this stores the hash reference, not a distinct copy of the hash it
293 points to. You can ask the object for a copy with the I<hash> method.
297 sub table { 'cust_main'; }
299 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
301 Adds this customer to the database. If there is an error, returns the error,
302 otherwise returns false.
304 Usually the customer's location will not yet exist in the database, and
305 the C<bill_location> and C<ship_location> pseudo-fields must be set to
306 uninserted L<FS::cust_location> objects. These will be inserted and linked
307 (in both directions) to the new customer record. If they're references
308 to the same object, they will become the same location.
310 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
311 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
312 are inserted atomicly, or the transaction is rolled back. Passing an empty
313 hash reference is equivalent to not supplying this parameter. There should be
314 a better explanation of this, but until then, here's an example:
317 tie %hash, 'Tie::RefHash'; #this part is important
319 $cust_pkg => [ $svc_acct ],
322 $cust_main->insert( \%hash );
324 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
325 be set as the invoicing list (see L<"invoicing_list">). Errors return as
326 expected and rollback the entire transaction; it is not necessary to call
327 check_invoicing_list first. The invoicing_list is set after the records in the
328 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
329 invoicing_list destination to the newly-created svc_acct. Here's an example:
331 $cust_main->insert( {}, [ $email, 'POST' ] );
333 Currently available options are: I<depend_jobnum>, I<noexport>,
334 I<tax_exemption> and I<prospectnum>.
336 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
337 on the supplied jobnum (they will not run until the specific job completes).
338 This can be used to defer provisioning until some action completes (such
339 as running the customer's credit card successfully).
341 The I<noexport> option is deprecated. If I<noexport> is set true, no
342 provisioning jobs (exports) are scheduled. (You can schedule them later with
343 the B<reexport> method.)
345 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
346 of tax names and exemption numbers. FS::cust_main_exemption records will be
347 created and inserted.
349 If I<prospectnum> is set, moves contacts and locations from that prospect.
355 my $cust_pkgs = @_ ? shift : {};
356 my $invoicing_list = @_ ? shift : '';
358 warn "$me insert called with options ".
359 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
362 local $SIG{HUP} = 'IGNORE';
363 local $SIG{INT} = 'IGNORE';
364 local $SIG{QUIT} = 'IGNORE';
365 local $SIG{TERM} = 'IGNORE';
366 local $SIG{TSTP} = 'IGNORE';
367 local $SIG{PIPE} = 'IGNORE';
369 my $oldAutoCommit = $FS::UID::AutoCommit;
370 local $FS::UID::AutoCommit = 0;
373 my $prepay_identifier = '';
374 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
376 if ( $self->payby eq 'PREPAY' ) {
378 $self->payby('BILL');
379 $prepay_identifier = $self->payinfo;
382 warn " looking up prepaid card $prepay_identifier\n"
385 my $error = $self->get_prepay( $prepay_identifier,
386 'amount_ref' => \$amount,
387 'seconds_ref' => \$seconds,
388 'upbytes_ref' => \$upbytes,
389 'downbytes_ref' => \$downbytes,
390 'totalbytes_ref' => \$totalbytes,
393 $dbh->rollback if $oldAutoCommit;
394 #return "error applying prepaid card (transaction rolled back): $error";
398 $payby = 'PREP' if $amount;
400 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
403 $self->payby('BILL');
404 $amount = $self->paid;
409 foreach my $l (qw(bill_location ship_location)) {
411 my $loc = delete $self->hashref->{$l} or return "$l not set";
413 if ( !$loc->locationnum ) {
414 # warn the location that we're going to insert it with no custnum
415 $loc->set(custnum_pending => 1);
416 warn " inserting $l\n"
418 my $error = $loc->insert;
420 $dbh->rollback if $oldAutoCommit;
421 my $label = $l eq 'ship_location' ? 'service' : 'billing';
422 return "$error (in $label location)";
425 } elsif ( $loc->prospectnum ) {
427 $loc->prospectnum('');
428 $loc->set(custnum_pending => 1);
429 my $error = $loc->replace;
431 $dbh->rollback if $oldAutoCommit;
432 my $label = $l eq 'ship_location' ? 'service' : 'billing';
433 return "$error (moving $label location)";
436 } elsif ( ($loc->custnum || 0) > 0 ) {
437 # then it somehow belongs to another customer--shouldn't happen
438 $dbh->rollback if $oldAutoCommit;
439 return "$l belongs to customer ".$loc->custnum;
441 # else it already belongs to this customer
442 # (happens when ship_location is identical to bill_location)
444 $self->set($l.'num', $loc->locationnum);
446 if ( $self->get($l.'num') eq '' ) {
447 $dbh->rollback if $oldAutoCommit;
452 warn " inserting $self\n"
455 $self->signupdate(time) unless $self->signupdate;
457 $self->auto_agent_custid()
458 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
460 my $error = $self->check_payinfo_cardtype
461 || $self->SUPER::insert;
463 $dbh->rollback if $oldAutoCommit;
464 #return "inserting cust_main record (transaction rolled back): $error";
468 # now set cust_location.custnum
469 foreach my $l (qw(bill_location ship_location)) {
470 warn " setting $l.custnum\n"
473 unless ( $loc->custnum ) {
474 $loc->set(custnum => $self->custnum);
475 $error ||= $loc->replace;
479 $dbh->rollback if $oldAutoCommit;
480 return "error setting $l custnum: $error";
484 warn " setting invoicing list\n"
487 if ( $invoicing_list ) {
488 $error = $self->check_invoicing_list( $invoicing_list );
490 $dbh->rollback if $oldAutoCommit;
491 #return "checking invoicing_list (transaction rolled back): $error";
494 $self->invoicing_list( $invoicing_list );
497 warn " setting customer tags\n"
500 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
501 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
502 'custnum' => $self->custnum };
503 my $error = $cust_tag->insert;
505 $dbh->rollback if $oldAutoCommit;
510 my $prospectnum = delete $options{'prospectnum'};
511 if ( $prospectnum ) {
513 warn " moving contacts and locations from prospect $prospectnum\n"
517 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
518 unless ( $prospect_main ) {
519 $dbh->rollback if $oldAutoCommit;
520 return "Unknown prospectnum $prospectnum";
522 $prospect_main->custnum($self->custnum);
523 $prospect_main->disabled('Y');
524 my $error = $prospect_main->replace;
526 $dbh->rollback if $oldAutoCommit;
530 my @contact = $prospect_main->contact;
531 my @cust_location = $prospect_main->cust_location;
532 my @qual = $prospect_main->qual;
534 foreach my $r ( @contact, @cust_location, @qual ) {
536 $r->custnum($self->custnum);
537 my $error = $r->replace;
539 $dbh->rollback if $oldAutoCommit;
546 # validate card (needs custnum already set)
547 if ( $self->payby =~ /^(CARD|DCRD)$/
548 && $conf->exists('business-onlinepayment-verification') ) {
549 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
551 $dbh->rollback if $oldAutoCommit;
556 warn " setting contacts\n"
559 if ( my $contact = delete $options{'contact'} ) {
561 foreach my $c ( @$contact ) {
562 $c->custnum($self->custnum);
563 my $error = $c->insert;
565 $dbh->rollback if $oldAutoCommit;
571 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
573 my $error = $self->process_o2m( 'table' => 'contact',
574 'fields' => FS::contact->cgi_contact_fields,
575 'params' => $contact_params,
578 $dbh->rollback if $oldAutoCommit;
583 warn " setting cust_main_exemption\n"
586 my $tax_exemption = delete $options{'tax_exemption'};
587 if ( $tax_exemption ) {
589 $tax_exemption = { map { $_ => '' } @$tax_exemption }
590 if ref($tax_exemption) eq 'ARRAY';
592 foreach my $taxname ( keys %$tax_exemption ) {
593 my $cust_main_exemption = new FS::cust_main_exemption {
594 'custnum' => $self->custnum,
595 'taxname' => $taxname,
596 'exempt_number' => $tax_exemption->{$taxname},
598 my $error = $cust_main_exemption->insert;
600 $dbh->rollback if $oldAutoCommit;
601 return "inserting cust_main_exemption (transaction rolled back): $error";
606 warn " ordering packages\n"
609 $error = $self->order_pkgs( $cust_pkgs,
611 'seconds_ref' => \$seconds,
612 'upbytes_ref' => \$upbytes,
613 'downbytes_ref' => \$downbytes,
614 'totalbytes_ref' => \$totalbytes,
617 $dbh->rollback if $oldAutoCommit;
622 $dbh->rollback if $oldAutoCommit;
623 return "No svc_acct record to apply pre-paid time";
625 if ( $upbytes || $downbytes || $totalbytes ) {
626 $dbh->rollback if $oldAutoCommit;
627 return "No svc_acct record to apply pre-paid data";
631 warn " inserting initial $payby payment of $amount\n"
633 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
635 $dbh->rollback if $oldAutoCommit;
636 return "inserting payment (transaction rolled back): $error";
640 unless ( $import || $skip_fuzzyfiles ) {
641 warn " queueing fuzzyfiles update\n"
643 $error = $self->queue_fuzzyfiles_update;
645 $dbh->rollback if $oldAutoCommit;
646 return "updating fuzzy search cache: $error";
650 # FS::geocode_Mixin::after_insert or something?
651 if ( $conf->config('tax_district_method') and !$import ) {
652 # if anything non-empty, try to look it up
653 my $queue = new FS::queue {
654 'job' => 'FS::geocode_Mixin::process_district_update',
655 'custnum' => $self->custnum,
657 my $error = $queue->insert( ref($self), $self->custnum );
659 $dbh->rollback if $oldAutoCommit;
660 return "queueing tax district update: $error";
665 warn " exporting\n" if $DEBUG > 1;
667 my $export_args = $options{'export_args'} || [];
670 map qsearch( 'part_export', {exportnum=>$_} ),
671 $conf->config('cust_main-exports'); #, $agentnum
673 foreach my $part_export ( @part_export ) {
674 my $error = $part_export->export_insert($self, @$export_args);
676 $dbh->rollback if $oldAutoCommit;
677 return "exporting to ". $part_export->exporttype.
678 " (transaction rolled back): $error";
682 #foreach my $depend_jobnum ( @$depend_jobnums ) {
683 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
685 # foreach my $jobnum ( @jobnums ) {
686 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
687 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
689 # my $error = $queue->depend_insert($depend_jobnum);
691 # $dbh->rollback if $oldAutoCommit;
692 # return "error queuing job dependancy: $error";
699 #if ( exists $options{'jobnums'} ) {
700 # push @{ $options{'jobnums'} }, @jobnums;
703 warn " insert complete; committing transaction\n"
706 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
711 use File::CounterFile;
712 sub auto_agent_custid {
715 my $format = $conf->config('cust_main-auto_agent_custid');
717 if ( $format eq '1YMMXXXXXXXX' ) {
719 my $counter = new File::CounterFile 'cust_main.agent_custid';
722 my $ym = 100000000000 + time2str('%y%m00000000', time);
723 if ( $ym > $counter->value ) {
724 $counter->{'value'} = $agent_custid = $ym;
725 $counter->{'updated'} = 1;
727 $agent_custid = $counter->inc;
733 die "Unknown cust_main-auto_agent_custid format: $format";
736 $self->agent_custid($agent_custid);
740 =item PACKAGE METHODS
742 Documentation on customer package methods has been moved to
743 L<FS::cust_main::Packages>.
745 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
747 Recharges this (existing) customer with the specified prepaid card (see
748 L<FS::prepay_credit>), specified either by I<identifier> or as an
749 FS::prepay_credit object. If there is an error, returns the error, otherwise
752 Optionally, five scalar references can be passed as well. They will have their
753 values filled in with the amount, number of seconds, and number of upload,
754 download, and total bytes applied by this prepaid card.
758 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
759 #the only place that uses these args
760 sub recharge_prepay {
761 my( $self, $prepay_credit, $amountref, $secondsref,
762 $upbytesref, $downbytesref, $totalbytesref ) = @_;
764 local $SIG{HUP} = 'IGNORE';
765 local $SIG{INT} = 'IGNORE';
766 local $SIG{QUIT} = 'IGNORE';
767 local $SIG{TERM} = 'IGNORE';
768 local $SIG{TSTP} = 'IGNORE';
769 local $SIG{PIPE} = 'IGNORE';
771 my $oldAutoCommit = $FS::UID::AutoCommit;
772 local $FS::UID::AutoCommit = 0;
775 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
777 my $error = $self->get_prepay( $prepay_credit,
778 'amount_ref' => \$amount,
779 'seconds_ref' => \$seconds,
780 'upbytes_ref' => \$upbytes,
781 'downbytes_ref' => \$downbytes,
782 'totalbytes_ref' => \$totalbytes,
784 || $self->increment_seconds($seconds)
785 || $self->increment_upbytes($upbytes)
786 || $self->increment_downbytes($downbytes)
787 || $self->increment_totalbytes($totalbytes)
788 || $self->insert_cust_pay_prepay( $amount,
790 ? $prepay_credit->identifier
795 $dbh->rollback if $oldAutoCommit;
799 if ( defined($amountref) ) { $$amountref = $amount; }
800 if ( defined($secondsref) ) { $$secondsref = $seconds; }
801 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
802 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
803 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
805 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
810 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
812 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
813 specified either by I<identifier> or as an FS::prepay_credit object.
815 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
816 incremented by the values of the prepaid card.
818 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
819 check or set this customer's I<agentnum>.
821 If there is an error, returns the error, otherwise returns false.
827 my( $self, $prepay_credit, %opt ) = @_;
829 local $SIG{HUP} = 'IGNORE';
830 local $SIG{INT} = 'IGNORE';
831 local $SIG{QUIT} = 'IGNORE';
832 local $SIG{TERM} = 'IGNORE';
833 local $SIG{TSTP} = 'IGNORE';
834 local $SIG{PIPE} = 'IGNORE';
836 my $oldAutoCommit = $FS::UID::AutoCommit;
837 local $FS::UID::AutoCommit = 0;
840 unless ( ref($prepay_credit) ) {
842 my $identifier = $prepay_credit;
844 $prepay_credit = qsearchs(
846 { 'identifier' => $identifier },
851 unless ( $prepay_credit ) {
852 $dbh->rollback if $oldAutoCommit;
853 return "Invalid prepaid card: ". $identifier;
858 if ( $prepay_credit->agentnum ) {
859 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
860 $dbh->rollback if $oldAutoCommit;
861 return "prepaid card not valid for agent ". $self->agentnum;
863 $self->agentnum($prepay_credit->agentnum);
866 my $error = $prepay_credit->delete;
868 $dbh->rollback if $oldAutoCommit;
869 return "removing prepay_credit (transaction rolled back): $error";
872 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
873 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
875 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
880 =item increment_upbytes SECONDS
882 Updates this customer's single or primary account (see L<FS::svc_acct>) by
883 the specified number of upbytes. If there is an error, returns the error,
884 otherwise returns false.
888 sub increment_upbytes {
889 _increment_column( shift, 'upbytes', @_);
892 =item increment_downbytes SECONDS
894 Updates this customer's single or primary account (see L<FS::svc_acct>) by
895 the specified number of downbytes. If there is an error, returns the error,
896 otherwise returns false.
900 sub increment_downbytes {
901 _increment_column( shift, 'downbytes', @_);
904 =item increment_totalbytes SECONDS
906 Updates this customer's single or primary account (see L<FS::svc_acct>) by
907 the specified number of totalbytes. If there is an error, returns the error,
908 otherwise returns false.
912 sub increment_totalbytes {
913 _increment_column( shift, 'totalbytes', @_);
916 =item increment_seconds SECONDS
918 Updates this customer's single or primary account (see L<FS::svc_acct>) by
919 the specified number of seconds. If there is an error, returns the error,
920 otherwise returns false.
924 sub increment_seconds {
925 _increment_column( shift, 'seconds', @_);
928 =item _increment_column AMOUNT
930 Updates this customer's single or primary account (see L<FS::svc_acct>) by
931 the specified number of seconds or bytes. If there is an error, returns
932 the error, otherwise returns false.
936 sub _increment_column {
937 my( $self, $column, $amount ) = @_;
938 warn "$me increment_column called: $column, $amount\n"
941 return '' unless $amount;
943 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
944 $self->ncancelled_pkgs;
947 return 'No packages with primary or single services found'.
948 ' to apply pre-paid time';
949 } elsif ( scalar(@cust_pkg) > 1 ) {
950 #maybe have a way to specify the package/account?
951 return 'Multiple packages found to apply pre-paid time';
954 my $cust_pkg = $cust_pkg[0];
955 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
959 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
962 return 'No account found to apply pre-paid time';
963 } elsif ( scalar(@cust_svc) > 1 ) {
964 return 'Multiple accounts found to apply pre-paid time';
967 my $svc_acct = $cust_svc[0]->svc_x;
968 warn " found service svcnum ". $svc_acct->pkgnum.
969 ' ('. $svc_acct->email. ")\n"
972 $column = "increment_$column";
973 $svc_acct->$column($amount);
977 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
979 Inserts a prepayment in the specified amount for this customer. An optional
980 second argument can specify the prepayment identifier for tracking purposes.
981 If there is an error, returns the error, otherwise returns false.
985 sub insert_cust_pay_prepay {
986 shift->insert_cust_pay('PREP', @_);
989 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
991 Inserts a cash payment in the specified amount for this customer. An optional
992 second argument can specify the payment identifier for tracking purposes.
993 If there is an error, returns the error, otherwise returns false.
997 sub insert_cust_pay_cash {
998 shift->insert_cust_pay('CASH', @_);
1001 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1003 Inserts a Western Union payment in the specified amount for this customer. An
1004 optional second argument can specify the prepayment identifier for tracking
1005 purposes. If there is an error, returns the error, otherwise returns false.
1009 sub insert_cust_pay_west {
1010 shift->insert_cust_pay('WEST', @_);
1013 sub insert_cust_pay {
1014 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1015 my $payinfo = scalar(@_) ? shift : '';
1017 my $cust_pay = new FS::cust_pay {
1018 'custnum' => $self->custnum,
1019 'paid' => sprintf('%.2f', $amount),
1020 #'_date' => #date the prepaid card was purchased???
1022 'payinfo' => $payinfo,
1030 This method is deprecated. See the I<depend_jobnum> option to the insert and
1031 order_pkgs methods for a better way to defer provisioning.
1033 Re-schedules all exports by calling the B<reexport> method of all associated
1034 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1035 otherwise returns false.
1042 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1043 "use the depend_jobnum option to insert or order_pkgs to delay export";
1045 local $SIG{HUP} = 'IGNORE';
1046 local $SIG{INT} = 'IGNORE';
1047 local $SIG{QUIT} = 'IGNORE';
1048 local $SIG{TERM} = 'IGNORE';
1049 local $SIG{TSTP} = 'IGNORE';
1050 local $SIG{PIPE} = 'IGNORE';
1052 my $oldAutoCommit = $FS::UID::AutoCommit;
1053 local $FS::UID::AutoCommit = 0;
1056 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1057 my $error = $cust_pkg->reexport;
1059 $dbh->rollback if $oldAutoCommit;
1064 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1069 =item delete [ OPTION => VALUE ... ]
1071 This deletes the customer. If there is an error, returns the error, otherwise
1074 This will completely remove all traces of the customer record. This is not
1075 what you want when a customer cancels service; for that, cancel all of the
1076 customer's packages (see L</cancel>).
1078 If the customer has any uncancelled packages, you need to pass a new (valid)
1079 customer number for those packages to be transferred to, as the "new_customer"
1080 option. Cancelled packages will be deleted. Did I mention that this is NOT
1081 what you want when a customer cancels service and that you really should be
1082 looking at L<FS::cust_pkg/cancel>?
1084 You can't delete a customer with invoices (see L<FS::cust_bill>),
1085 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1086 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1087 set the "delete_financials" option to a true value.
1092 my( $self, %opt ) = @_;
1094 local $SIG{HUP} = 'IGNORE';
1095 local $SIG{INT} = 'IGNORE';
1096 local $SIG{QUIT} = 'IGNORE';
1097 local $SIG{TERM} = 'IGNORE';
1098 local $SIG{TSTP} = 'IGNORE';
1099 local $SIG{PIPE} = 'IGNORE';
1101 my $oldAutoCommit = $FS::UID::AutoCommit;
1102 local $FS::UID::AutoCommit = 0;
1105 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1106 $dbh->rollback if $oldAutoCommit;
1107 return "Can't delete a master agent customer";
1110 #use FS::access_user
1111 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1112 $dbh->rollback if $oldAutoCommit;
1113 return "Can't delete a master employee customer";
1116 tie my %financial_tables, 'Tie::IxHash',
1117 'cust_bill' => 'invoices',
1118 'cust_statement' => 'statements',
1119 'cust_credit' => 'credits',
1120 'cust_pay' => 'payments',
1121 'cust_refund' => 'refunds',
1124 foreach my $table ( keys %financial_tables ) {
1126 my @records = $self->$table();
1128 if ( @records && ! $opt{'delete_financials'} ) {
1129 $dbh->rollback if $oldAutoCommit;
1130 return "Can't delete a customer with ". $financial_tables{$table};
1133 foreach my $record ( @records ) {
1134 my $error = $record->delete;
1136 $dbh->rollback if $oldAutoCommit;
1137 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1143 my @cust_pkg = $self->ncancelled_pkgs;
1145 my $new_custnum = $opt{'new_custnum'};
1146 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1147 $dbh->rollback if $oldAutoCommit;
1148 return "Invalid new customer number: $new_custnum";
1150 foreach my $cust_pkg ( @cust_pkg ) {
1151 my %hash = $cust_pkg->hash;
1152 $hash{'custnum'} = $new_custnum;
1153 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1154 my $error = $new_cust_pkg->replace($cust_pkg,
1155 options => { $cust_pkg->options },
1158 $dbh->rollback if $oldAutoCommit;
1163 my @cancelled_cust_pkg = $self->all_pkgs;
1164 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1165 my $error = $cust_pkg->delete;
1167 $dbh->rollback if $oldAutoCommit;
1172 #cust_tax_adjustment in financials?
1173 #cust_pay_pending? ouch
1175 foreach my $table (qw(
1176 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1177 cust_location cust_main_note cust_tax_adjustment
1178 cust_pay_void cust_pay_batch queue cust_tax_exempt
1180 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1181 my $error = $record->delete;
1183 $dbh->rollback if $oldAutoCommit;
1189 my $sth = $dbh->prepare(
1190 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1192 my $errstr = $dbh->errstr;
1193 $dbh->rollback if $oldAutoCommit;
1196 $sth->execute($self->custnum) or do {
1197 my $errstr = $sth->errstr;
1198 $dbh->rollback if $oldAutoCommit;
1204 my $ticket_dbh = '';
1205 if ($conf->config('ticket_system') eq 'RT_Internal') {
1207 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1208 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1209 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1210 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1213 if ( $ticket_dbh ) {
1215 my $ticket_sth = $ticket_dbh->prepare(
1216 'DELETE FROM Links WHERE Target = ?'
1218 my $errstr = $ticket_dbh->errstr;
1219 $dbh->rollback if $oldAutoCommit;
1222 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1224 my $errstr = $ticket_sth->errstr;
1225 $dbh->rollback if $oldAutoCommit;
1229 #check and see if the customer is the only link on the ticket, and
1230 #if so, set the ticket to deleted status in RT?
1231 #maybe someday, for now this will at least fix tickets not displaying
1235 #delete the customer record
1237 my $error = $self->SUPER::delete;
1239 $dbh->rollback if $oldAutoCommit;
1243 # cust_main exports!
1245 #my $export_args = $options{'export_args'} || [];
1248 map qsearch( 'part_export', {exportnum=>$_} ),
1249 $conf->config('cust_main-exports'); #, $agentnum
1251 foreach my $part_export ( @part_export ) {
1252 my $error = $part_export->export_delete( $self ); #, @$export_args);
1254 $dbh->rollback if $oldAutoCommit;
1255 return "exporting to ". $part_export->exporttype.
1256 " (transaction rolled back): $error";
1260 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1265 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1267 This merges this customer into the provided new custnum, and then deletes the
1268 customer. If there is an error, returns the error, otherwise returns false.
1270 The source customer's name, company name, phone numbers, agent,
1271 referring customer, customer class, advertising source, order taker, and
1272 billing information (except balance) are discarded.
1274 All packages are moved to the target customer. Packages with package locations
1275 are preserved. Packages without package locations are moved to a new package
1276 location with the source customer's service/shipping address.
1278 All invoices, statements, payments, credits and refunds are moved to the target
1279 customer. The source customer's balance is added to the target customer.
1281 All notes, attachments, tickets and customer tags are moved to the target
1284 Change history is not currently moved.
1289 my( $self, $new_custnum, %opt ) = @_;
1291 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1293 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1294 or return "Invalid new customer number: $new_custnum";
1296 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1297 if $self->agentnum != $new_cust_main->agentnum
1298 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1300 local $SIG{HUP} = 'IGNORE';
1301 local $SIG{INT} = 'IGNORE';
1302 local $SIG{QUIT} = 'IGNORE';
1303 local $SIG{TERM} = 'IGNORE';
1304 local $SIG{TSTP} = 'IGNORE';
1305 local $SIG{PIPE} = 'IGNORE';
1307 my $oldAutoCommit = $FS::UID::AutoCommit;
1308 local $FS::UID::AutoCommit = 0;
1311 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1312 $dbh->rollback if $oldAutoCommit;
1313 return "Can't merge a master agent customer";
1316 #use FS::access_user
1317 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1318 $dbh->rollback if $oldAutoCommit;
1319 return "Can't merge a master employee customer";
1322 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1323 'status' => { op=>'!=', value=>'done' },
1327 $dbh->rollback if $oldAutoCommit;
1328 return "Can't merge a customer with pending payments";
1331 tie my %financial_tables, 'Tie::IxHash',
1332 'cust_bill' => 'invoices',
1333 'cust_bill_void' => 'voided invoices',
1334 'cust_statement' => 'statements',
1335 'cust_credit' => 'credits',
1336 'cust_credit_void' => 'voided credits',
1337 'cust_pay' => 'payments',
1338 'cust_pay_void' => 'voided payments',
1339 'cust_refund' => 'refunds',
1342 foreach my $table ( keys %financial_tables ) {
1344 my @records = $self->$table();
1346 foreach my $record ( @records ) {
1347 $record->custnum($new_custnum);
1348 my $error = $record->replace;
1350 $dbh->rollback if $oldAutoCommit;
1351 return "Error merging ". $financial_tables{$table}. ": $error\n";
1357 my $name = $self->ship_name; #?
1359 my $locationnum = '';
1360 foreach my $cust_pkg ( $self->all_pkgs ) {
1361 $cust_pkg->custnum($new_custnum);
1363 unless ( $cust_pkg->locationnum ) {
1364 unless ( $locationnum ) {
1365 my $cust_location = new FS::cust_location {
1366 $self->location_hash,
1367 'custnum' => $new_custnum,
1369 my $error = $cust_location->insert;
1371 $dbh->rollback if $oldAutoCommit;
1374 $locationnum = $cust_location->locationnum;
1376 $cust_pkg->locationnum($locationnum);
1379 my $error = $cust_pkg->replace;
1381 $dbh->rollback if $oldAutoCommit;
1385 # add customer (ship) name to svc_phone.phone_name if blank
1386 my @cust_svc = $cust_pkg->cust_svc;
1387 foreach my $cust_svc (@cust_svc) {
1388 my($label, $value, $svcdb) = $cust_svc->label;
1389 next unless $svcdb eq 'svc_phone';
1390 my $svc_phone = $cust_svc->svc_x;
1391 next if $svc_phone->phone_name;
1392 $svc_phone->phone_name($name);
1393 my $error = $svc_phone->replace;
1395 $dbh->rollback if $oldAutoCommit;
1403 # cust_tax_exempt (texas tax exemptions)
1404 # cust_recon (some sort of not-well understood thing for OnPac)
1406 #these are moved over
1407 foreach my $table (qw(
1408 cust_tag cust_location contact cust_attachment cust_main_note
1409 cust_tax_adjustment cust_pay_batch queue
1411 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1412 $record->custnum($new_custnum);
1413 my $error = $record->replace;
1415 $dbh->rollback if $oldAutoCommit;
1421 #these aren't preserved
1422 foreach my $table (qw(
1423 cust_main_exemption cust_main_invoice
1425 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1426 my $error = $record->delete;
1428 $dbh->rollback if $oldAutoCommit;
1435 my $sth = $dbh->prepare(
1436 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1438 my $errstr = $dbh->errstr;
1439 $dbh->rollback if $oldAutoCommit;
1442 $sth->execute($new_custnum, $self->custnum) or do {
1443 my $errstr = $sth->errstr;
1444 $dbh->rollback if $oldAutoCommit;
1450 my $ticket_dbh = '';
1451 if ($conf->config('ticket_system') eq 'RT_Internal') {
1453 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1454 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1455 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1456 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1459 if ( $ticket_dbh ) {
1461 my $ticket_sth = $ticket_dbh->prepare(
1462 'UPDATE Links SET Target = ? WHERE Target = ?'
1464 my $errstr = $ticket_dbh->errstr;
1465 $dbh->rollback if $oldAutoCommit;
1468 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1469 'freeside://freeside/cust_main/'.$self->custnum)
1471 my $errstr = $ticket_sth->errstr;
1472 $dbh->rollback if $oldAutoCommit;
1478 #delete the customer record
1480 my $error = $self->delete;
1482 $dbh->rollback if $oldAutoCommit;
1486 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1491 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1493 Replaces the OLD_RECORD with this one in the database. If there is an error,
1494 returns the error, otherwise returns false.
1496 To change the customer's address, set the pseudo-fields C<bill_location> and
1497 C<ship_location>. The address will still only change if at least one of the
1498 address fields differs from the existing values.
1500 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1501 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1502 expected and rollback the entire transaction; it is not necessary to call
1503 check_invoicing_list first. Here's an example:
1505 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1507 Currently available options are: I<tax_exemption>.
1509 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1510 of tax names and exemption numbers. FS::cust_main_exemption records will be
1511 deleted and inserted as appropriate.
1518 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1520 : $self->replace_old;
1524 warn "$me replace called\n"
1527 my $curuser = $FS::CurrentUser::CurrentUser;
1528 if ( $self->payby eq 'COMP'
1529 && $self->payby ne $old->payby
1530 && ! $curuser->access_right('Complimentary customer')
1533 return "You are not permitted to create complimentary accounts.";
1536 local($ignore_expired_card) = 1
1537 if $old->payby =~ /^(CARD|DCRD)$/
1538 && $self->payby =~ /^(CARD|DCRD)$/
1539 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1541 local($ignore_banned_card) = 1
1542 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1543 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1544 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1546 if ( $self->payby =~ /^(CARD|DCRD)$/
1547 && $old->payinfo ne $self->payinfo
1548 && $old->paymask ne $self->paymask )
1550 my $error = $self->check_payinfo_cardtype;
1551 return $error if $error;
1553 if ( $conf->exists('business-onlinepayment-verification') ) {
1554 #need to standardize paydate for this, false laziness with check
1556 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1557 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1558 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1559 ( $m, $y ) = ( $2, "19$1" );
1560 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1561 ( $m, $y ) = ( $3, "20$2" );
1563 return "Illegal expiration date: ". $self->paydate;
1565 $m = sprintf('%02d',$m);
1566 $self->paydate("$y-$m-01");
1568 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
1569 return $error if $error;
1573 return "Invoicing locale is required"
1576 && $conf->exists('cust_main-require_locale');
1578 local $SIG{HUP} = 'IGNORE';
1579 local $SIG{INT} = 'IGNORE';
1580 local $SIG{QUIT} = 'IGNORE';
1581 local $SIG{TERM} = 'IGNORE';
1582 local $SIG{TSTP} = 'IGNORE';
1583 local $SIG{PIPE} = 'IGNORE';
1585 my $oldAutoCommit = $FS::UID::AutoCommit;
1586 local $FS::UID::AutoCommit = 0;
1589 for my $l (qw(bill_location ship_location)) {
1590 my $old_loc = $old->$l;
1591 my $new_loc = $self->$l;
1593 # find the existing location if there is one
1594 $new_loc->set('custnum' => $self->custnum);
1595 my $error = $new_loc->find_or_insert;
1597 $dbh->rollback if $oldAutoCommit;
1600 $self->set($l.'num', $new_loc->locationnum);
1603 # replace the customer record
1604 my $error = $self->SUPER::replace($old);
1607 $dbh->rollback if $oldAutoCommit;
1611 # now move packages to the new service location
1612 $self->set('ship_location', ''); #flush cache
1613 if ( $old->ship_locationnum and # should only be null during upgrade...
1614 $old->ship_locationnum != $self->ship_locationnum ) {
1615 $error = $old->ship_location->move_to($self->ship_location);
1617 $dbh->rollback if $oldAutoCommit;
1621 # don't move packages based on the billing location, but
1622 # disable it if it's no longer in use
1623 if ( $old->bill_locationnum and
1624 $old->bill_locationnum != $self->bill_locationnum ) {
1625 $error = $old->bill_location->disable_if_unused;
1627 $dbh->rollback if $oldAutoCommit;
1632 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1633 my $invoicing_list = shift @param;
1634 $error = $self->check_invoicing_list( $invoicing_list );
1636 $dbh->rollback if $oldAutoCommit;
1639 $self->invoicing_list( $invoicing_list );
1642 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1644 #this could be more efficient than deleting and re-inserting, if it matters
1645 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1646 my $error = $cust_tag->delete;
1648 $dbh->rollback if $oldAutoCommit;
1652 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1653 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1654 'custnum' => $self->custnum };
1655 my $error = $cust_tag->insert;
1657 $dbh->rollback if $oldAutoCommit;
1664 my %options = @param;
1666 my $tax_exemption = delete $options{'tax_exemption'};
1667 if ( $tax_exemption ) {
1669 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1670 if ref($tax_exemption) eq 'ARRAY';
1672 my %cust_main_exemption =
1673 map { $_->taxname => $_ }
1674 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1676 foreach my $taxname ( keys %$tax_exemption ) {
1678 if ( $cust_main_exemption{$taxname} &&
1679 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1682 delete $cust_main_exemption{$taxname};
1686 my $cust_main_exemption = new FS::cust_main_exemption {
1687 'custnum' => $self->custnum,
1688 'taxname' => $taxname,
1689 'exempt_number' => $tax_exemption->{$taxname},
1691 my $error = $cust_main_exemption->insert;
1693 $dbh->rollback if $oldAutoCommit;
1694 return "inserting cust_main_exemption (transaction rolled back): $error";
1698 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1699 my $error = $cust_main_exemption->delete;
1701 $dbh->rollback if $oldAutoCommit;
1702 return "deleting cust_main_exemption (transaction rolled back): $error";
1708 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1709 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1710 && $self->get('payinfo') !~ /^99\d{14}$/
1712 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1717 # card/check/lec info has changed, want to retry realtime_ invoice events
1718 my $error = $self->retry_realtime;
1720 $dbh->rollback if $oldAutoCommit;
1725 unless ( $import || $skip_fuzzyfiles ) {
1726 $error = $self->queue_fuzzyfiles_update;
1728 $dbh->rollback if $oldAutoCommit;
1729 return "updating fuzzy search cache: $error";
1733 # tax district update in cust_location
1735 # cust_main exports!
1737 my $export_args = $options{'export_args'} || [];
1740 map qsearch( 'part_export', {exportnum=>$_} ),
1741 $conf->config('cust_main-exports'); #, $agentnum
1743 foreach my $part_export ( @part_export ) {
1744 my $error = $part_export->export_replace( $self, $old, @$export_args);
1746 $dbh->rollback if $oldAutoCommit;
1747 return "exporting to ". $part_export->exporttype.
1748 " (transaction rolled back): $error";
1752 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1757 =item queue_fuzzyfiles_update
1759 Used by insert & replace to update the fuzzy search cache
1763 use FS::cust_main::Search;
1764 sub queue_fuzzyfiles_update {
1767 local $SIG{HUP} = 'IGNORE';
1768 local $SIG{INT} = 'IGNORE';
1769 local $SIG{QUIT} = 'IGNORE';
1770 local $SIG{TERM} = 'IGNORE';
1771 local $SIG{TSTP} = 'IGNORE';
1772 local $SIG{PIPE} = 'IGNORE';
1774 my $oldAutoCommit = $FS::UID::AutoCommit;
1775 local $FS::UID::AutoCommit = 0;
1778 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1779 my $queue = new FS::queue {
1780 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1782 my @args = "cust_main.$field", $self->get($field);
1783 my $error = $queue->insert( @args );
1785 $dbh->rollback if $oldAutoCommit;
1786 return "queueing job (transaction rolled back): $error";
1790 my @locations = $self->bill_location;
1791 push @locations, $self->ship_location if $self->has_ship_address;
1792 foreach my $location (@locations) {
1793 my $queue = new FS::queue {
1794 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1796 my @args = 'cust_location.address1', $location->address1;
1797 my $error = $queue->insert( @args );
1799 $dbh->rollback if $oldAutoCommit;
1800 return "queueing job (transaction rolled back): $error";
1804 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1811 Checks all fields to make sure this is a valid customer record. If there is
1812 an error, returns the error, otherwise returns false. Called by the insert
1813 and replace methods.
1820 warn "$me check BEFORE: \n". $self->_dump
1824 $self->ut_numbern('custnum')
1825 || $self->ut_number('agentnum')
1826 || $self->ut_textn('agent_custid')
1827 || $self->ut_number('refnum')
1828 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1829 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1830 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1831 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1832 || $self->ut_textn('custbatch')
1833 || $self->ut_name('last')
1834 || $self->ut_name('first')
1835 || $self->ut_snumbern('signupdate')
1836 || $self->ut_snumbern('birthdate')
1837 || $self->ut_namen('spouse_last')
1838 || $self->ut_namen('spouse_first')
1839 || $self->ut_snumbern('spouse_birthdate')
1840 || $self->ut_snumbern('anniversary_date')
1841 || $self->ut_textn('company')
1842 || $self->ut_textn('ship_company')
1843 || $self->ut_anything('comments')
1844 || $self->ut_numbern('referral_custnum')
1845 || $self->ut_textn('stateid')
1846 || $self->ut_textn('stateid_state')
1847 || $self->ut_textn('invoice_terms')
1848 || $self->ut_floatn('cdr_termination_percentage')
1849 || $self->ut_floatn('credit_limit')
1850 || $self->ut_numbern('billday')
1851 || $self->ut_numbern('prorate_day')
1852 || $self->ut_flag('edit_subject')
1853 || $self->ut_flag('calling_list_exempt')
1854 || $self->ut_flag('invoice_noemail')
1855 || $self->ut_flag('message_noemail')
1856 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1857 || $self->ut_flag('invoice_ship_address')
1860 foreach (qw(company ship_company)) {
1861 my $company = $self->get($_);
1862 $company =~ s/^\s+//;
1863 $company =~ s/\s+$//;
1864 $company =~ s/\s+/ /g;
1865 $self->set($_, $company);
1868 #barf. need message catalogs. i18n. etc.
1869 $error .= "Please select an advertising source."
1870 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1871 return $error if $error;
1873 return "Unknown agent"
1874 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1876 return "Unknown refnum"
1877 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1879 return "Unknown referring custnum: ". $self->referral_custnum
1880 unless ! $self->referral_custnum
1881 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1883 if ( $self->ss eq '' ) {
1888 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1889 or return "Illegal social security number: ". $self->ss;
1890 $self->ss("$1-$2-$3");
1893 #turn off invoice_ship_address if ship & bill are the same
1894 if ($self->bill_locationnum eq $self->ship_locationnum) {
1895 $self->invoice_ship_address('');
1898 # cust_main_county verification now handled by cust_location check
1901 $self->ut_phonen('daytime', $self->country)
1902 || $self->ut_phonen('night', $self->country)
1903 || $self->ut_phonen('fax', $self->country)
1904 || $self->ut_phonen('mobile', $self->country)
1906 return $error if $error;
1908 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1910 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1913 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1915 : FS::Msgcat::_gettext('daytime');
1916 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1918 : FS::Msgcat::_gettext('night');
1920 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1922 : FS::Msgcat::_gettext('mobile');
1924 return "$daytime_label, $night_label or $mobile_label is required"
1928 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1929 # or return "Illegal payby: ". $self->payby;
1931 FS::payby->can_payby($self->table, $self->payby)
1932 or return "Illegal payby: ". $self->payby;
1934 $error = $self->ut_numbern('paystart_month')
1935 || $self->ut_numbern('paystart_year')
1936 || $self->ut_numbern('payissue')
1937 || $self->ut_textn('paytype')
1939 return $error if $error;
1941 if ( $self->payip eq '' ) {
1944 $error = $self->ut_ip('payip');
1945 return $error if $error;
1948 # If it is encrypted and the private key is not availaible then we can't
1949 # check the credit card.
1950 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1952 # Need some kind of global flag to accept invalid cards, for testing
1954 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1956 my $payinfo = $self->payinfo;
1957 $payinfo =~ s/\D//g;
1958 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1959 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1961 $self->payinfo($payinfo);
1963 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1965 return gettext('unknown_card_type')
1966 if $self->payinfo !~ /^99\d{14}$/ #token
1967 && cardtype($self->payinfo) eq "Unknown";
1969 unless ( $ignore_banned_card ) {
1970 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1972 if ( $ban->bantype eq 'warn' ) {
1973 #or others depending on value of $ban->reason ?
1974 return '_duplicate_card'.
1975 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1976 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1977 ' (ban# '. $ban->bannum. ')'
1978 unless $self->override_ban_warn;
1980 return 'Banned credit card: banned on '.
1981 time2str('%a %h %o at %r', $ban->_date).
1982 ' by '. $ban->otaker.
1983 ' (ban# '. $ban->bannum. ')';
1988 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1989 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1990 $self->paycvv =~ /^(\d{4})$/
1991 or return "CVV2 (CID) for American Express cards is four digits.";
1994 $self->paycvv =~ /^(\d{3})$/
1995 or return "CVV2 (CVC2/CID) is three digits.";
2002 my $cardtype = cardtype($payinfo);
2003 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2005 return "Start date or issue number is required for $cardtype cards"
2006 unless $self->paystart_month && $self->paystart_year or $self->payissue;
2008 return "Start month must be between 1 and 12"
2009 if $self->paystart_month
2010 and $self->paystart_month < 1 || $self->paystart_month > 12;
2012 return "Start year must be 1990 or later"
2013 if $self->paystart_year
2014 and $self->paystart_year < 1990;
2016 return "Issue number must be beween 1 and 99"
2018 and $self->payissue < 1 || $self->payissue > 99;
2021 $self->paystart_month('');
2022 $self->paystart_year('');
2023 $self->payissue('');
2026 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2028 my $payinfo = $self->payinfo;
2029 $payinfo =~ s/[^\d\@\.]//g;
2030 if ( $conf->config('echeck-country') eq 'CA' ) {
2031 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2032 or return 'invalid echeck account@branch.bank';
2033 $payinfo = "$1\@$2.$3";
2034 } elsif ( $conf->config('echeck-country') eq 'US' ) {
2035 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2036 $payinfo = "$1\@$2";
2038 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2039 $payinfo = "$1\@$2";
2041 $self->payinfo($payinfo);
2044 unless ( $ignore_banned_card ) {
2045 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2047 if ( $ban->bantype eq 'warn' ) {
2048 #or others depending on value of $ban->reason ?
2049 return '_duplicate_ach' unless $self->override_ban_warn;
2051 return 'Banned ACH account: banned on '.
2052 time2str('%a %h %o at %r', $ban->_date).
2053 ' by '. $ban->otaker.
2054 ' (ban# '. $ban->bannum. ')';
2059 } elsif ( $self->payby eq 'LECB' ) {
2061 my $payinfo = $self->payinfo;
2062 $payinfo =~ s/\D//g;
2063 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2065 $self->payinfo($payinfo);
2068 } elsif ( $self->payby eq 'BILL' ) {
2070 $error = $self->ut_textn('payinfo');
2071 return "Illegal P.O. number: ". $self->payinfo if $error;
2074 } elsif ( $self->payby eq 'COMP' ) {
2076 my $curuser = $FS::CurrentUser::CurrentUser;
2077 if ( ! $self->custnum
2078 && ! $curuser->access_right('Complimentary customer')
2081 return "You are not permitted to create complimentary accounts."
2084 $error = $self->ut_textn('payinfo');
2085 return "Illegal comp account issuer: ". $self->payinfo if $error;
2088 } elsif ( $self->payby eq 'PREPAY' ) {
2090 my $payinfo = $self->payinfo;
2091 $payinfo =~ s/\W//g; #anything else would just confuse things
2092 $self->payinfo($payinfo);
2093 $error = $self->ut_alpha('payinfo');
2094 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2095 return "Unknown prepayment identifier"
2096 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2101 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2102 return "Expiration date required"
2103 # shouldn't payinfo_check do this?
2104 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2108 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2109 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2110 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2111 ( $m, $y ) = ( $2, "19$1" );
2112 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2113 ( $m, $y ) = ( $3, "20$2" );
2115 return "Illegal expiration date: ". $self->paydate;
2117 $m = sprintf('%02d',$m);
2118 $self->paydate("$y-$m-01");
2119 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2120 return gettext('expired_card')
2122 && !$ignore_expired_card
2123 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2126 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2127 ( ! $conf->exists('require_cardname')
2128 || $self->payby !~ /^(CARD|DCRD)$/ )
2130 $self->payname( $self->first. " ". $self->getfield('last') );
2133 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2134 $self->payname =~ /^([\w \,\.\-\']*)$/
2135 or return gettext('illegal_name'). " payname: ". $self->payname;
2138 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2139 or return gettext('illegal_name'). " payname: ". $self->payname;
2145 return "Please select an invoicing locale"
2148 && $conf->exists('cust_main-require_locale');
2150 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2151 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2155 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2157 warn "$me check AFTER: \n". $self->_dump
2160 $self->SUPER::check;
2163 sub check_payinfo_cardtype {
2166 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
2168 my $payinfo = $self->payinfo;
2169 $payinfo =~ s/\D//g;
2171 return '' if $payinfo =~ /^99\d{14}$/; #token
2173 my %bop_card_types = map { $_=>1 } values %{ card_types() };
2174 my $cardtype = cardtype($payinfo);
2176 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
2184 Additional checks for replace only.
2189 my ($new,$old) = @_;
2190 #preserve old value if global config is set
2191 if ($old && $conf->exists('invoice-ship_address')) {
2192 $new->invoice_ship_address($old->invoice_ship_address);
2199 Returns a list of fields which have ship_ duplicates.
2204 qw( last first company
2206 address1 address2 city county state zip country
2208 daytime night fax mobile
2212 =item has_ship_address
2214 Returns true if this customer record has a separate shipping address.
2218 sub has_ship_address {
2220 $self->bill_locationnum != $self->ship_locationnum;
2225 Returns a list of key/value pairs, with the following keys: address1,
2226 adddress2, city, county, state, zip, country, district, and geocode. The
2227 shipping address is used if present.
2233 $self->ship_location->location_hash;
2238 Returns all locations (see L<FS::cust_location>) for this customer.
2244 qsearch('cust_location', { 'custnum' => $self->custnum,
2245 'prospectnum' => '' } );
2250 Returns all contacts (see L<FS::contact>) for this customer.
2254 #already used :/ sub contact {
2257 qsearch('contact', { 'custnum' => $self->custnum } );
2262 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2263 and L<FS::cust_pkg>) for this customer, except those on hold.
2265 Returns a list: an empty list on success or a list of errors.
2271 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2276 Unsuspends all suspended packages in the on-hold state (those without setup
2277 dates) for this customer.
2283 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2288 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2290 Returns a list: an empty list on success or a list of errors.
2296 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2299 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2301 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2302 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2303 of a list of pkgparts; the hashref has the following keys:
2307 =item pkgparts - listref of pkgparts
2309 =item (other options are passed to the suspend method)
2314 Returns a list: an empty list on success or a list of errors.
2318 sub suspend_if_pkgpart {
2320 my (@pkgparts, %opt);
2321 if (ref($_[0]) eq 'HASH'){
2322 @pkgparts = @{$_[0]{pkgparts}};
2327 grep { $_->suspend(%opt) }
2328 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2329 $self->unsuspended_pkgs;
2332 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2334 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2335 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2336 instead of a list of pkgparts; the hashref has the following keys:
2340 =item pkgparts - listref of pkgparts
2342 =item (other options are passed to the suspend method)
2346 Returns a list: an empty list on success or a list of errors.
2350 sub suspend_unless_pkgpart {
2352 my (@pkgparts, %opt);
2353 if (ref($_[0]) eq 'HASH'){
2354 @pkgparts = @{$_[0]{pkgparts}};
2359 grep { $_->suspend(%opt) }
2360 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2361 $self->unsuspended_pkgs;
2364 =item cancel [ OPTION => VALUE ... ]
2366 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2367 The cancellation time will be now.
2371 Always returns a list: an empty list on success or a list of errors.
2378 warn "$me cancel called on customer ". $self->custnum. " with options ".
2379 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2381 my @pkgs = $self->ncancelled_pkgs;
2383 $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2386 =item cancel_pkgs OPTIONS
2388 Cancels a specified list of packages. OPTIONS can include:
2392 =item cust_pkg - an arrayref of the packages. Required.
2394 =item time - the cancellation time, used to calculate final bills and
2395 unused-time credits if any. Will be passed through to the bill() and
2396 FS::cust_pkg::cancel() methods.
2398 =item quiet - can be set true to supress email cancellation notices.
2400 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a
2401 reasonnum of an existing reason, or passing a hashref will create a new reason.
2402 The hashref should have the following keys:
2403 typenum - Reason type (see L<FS::reason_type>)
2404 reason - Text of the new reason.
2406 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2407 for the individual packages, parallel to the C<cust_pkg> argument. The
2408 reason and reason_otaker arguments will be taken from those objects.
2410 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2412 =item nobill - can be set true to skip billing if it might otherwise be done.
2417 my( $self, %opt ) = @_;
2419 # we're going to cancel services, which is not reversible
2420 # but on 3.x, don't strictly enforce this
2421 warn "cancel_pkgs should not be run inside a transaction"
2422 if $FS::UID::AutoCommit == 0;
2424 local $FS::UID::AutoCommit = 0;
2426 return ( 'access denied' )
2427 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2429 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2431 #should try decryption (we might have the private key)
2432 # and if not maybe queue a job for the server that does?
2433 return ( "Can't (yet) ban encrypted credit cards" )
2434 if $self->is_encrypted($self->payinfo);
2436 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2437 my $error = $ban->insert;
2445 my @pkgs = @{ delete $opt{'cust_pkg'} };
2446 my $cancel_time = $opt{'time'} || time;
2448 # bill all packages first, so we don't lose usage, service counts for
2449 # bulk billing, etc.
2450 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2452 my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2454 'time' => $cancel_time );
2456 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2458 return ( "Error billing during cancellation: $error" );
2463 $FS::UID::AutoCommit = 1;
2465 # now cancel all services, the same way we would for individual packages.
2466 # if any of them fail, cancel the rest anyway.
2467 my @cust_svc = map { $_->cust_svc } @pkgs;
2468 my @sorted_cust_svc =
2470 sort { $a->[1] <=> $b->[1] }
2471 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2473 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2476 foreach my $cust_svc (@sorted_cust_svc) {
2477 my $part_svc = $cust_svc->part_svc;
2478 next if ( defined($part_svc) and $part_svc->preserve );
2479 my $error = $cust_svc->cancel; # immediate cancel, no date option
2480 push @errors, $error if $error;
2486 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2487 $self->custnum. "\n"
2491 if ($opt{'cust_pkg_reason'}) {
2492 @cprs = @{ delete $opt{'cust_pkg_reason'} };
2498 my $cpr = shift @cprs;
2500 $lopt{'reason'} = $cpr->reasonnum;
2501 $lopt{'reason_otaker'} = $cpr->otaker;
2503 warn "no reason found when canceling package ".$_->pkgnum."\n";
2504 # we're not actually required to pass a reason to cust_pkg::cancel,
2505 # but if we're getting to this point, something has gone awry.
2506 $null_reason ||= FS::reason->new_or_existing(
2507 reason => 'unknown reason',
2508 type => 'Cancel Reason',
2511 $lopt{'reason'} = $null_reason->reasonnum;
2512 $lopt{'reason_otaker'} = $FS::CurrentUser::CurrentUser->username;
2515 my $error = $_->cancel(%lopt);
2516 push @errors, 'pkgnum '.$_->pkgnum.': '.$error if $error;
2522 sub _banned_pay_hashref {
2533 'payby' => $payby2ban{$self->payby},
2534 'payinfo' => $self->payinfo,
2535 #don't ever *search* on reason! #'reason' =>
2539 sub _new_banned_pay_hashref {
2541 my $hr = $self->_banned_pay_hashref;
2542 $hr->{payinfo} = md5_base64($hr->{payinfo});
2548 Returns all notes (see L<FS::cust_main_note>) for this customer.
2553 my($self,$orderby_classnum) = (shift,shift);
2554 my $orderby = "sticky DESC, _date DESC";
2555 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2556 qsearch( 'cust_main_note',
2557 { 'custnum' => $self->custnum },
2559 "ORDER BY $orderby",
2565 Returns the agent (see L<FS::agent>) for this customer.
2571 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2576 Returns the agent name (see L<FS::agent>) for this customer.
2582 $self->agent->agent;
2587 Returns any tags associated with this customer, as FS::cust_tag objects,
2588 or an empty list if there are no tags.
2594 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2599 Returns any tags associated with this customer, as FS::part_tag objects,
2600 or an empty list if there are no tags.
2606 map $_->part_tag, $self->cust_tag;
2612 Returns the customer class, as an FS::cust_class object, or the empty string
2613 if there is no customer class.
2619 if ( $self->classnum ) {
2620 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2628 Returns the customer category name, or the empty string if there is no customer
2635 my $cust_class = $self->cust_class;
2637 ? $cust_class->categoryname
2643 Returns the customer class name, or the empty string if there is no customer
2650 my $cust_class = $self->cust_class;
2652 ? $cust_class->classname
2656 =item BILLING METHODS
2658 Documentation on billing methods has been moved to
2659 L<FS::cust_main::Billing>.
2661 =item REALTIME BILLING METHODS
2663 Documentation on realtime billing methods has been moved to
2664 L<FS::cust_main::Billing_Realtime>.
2668 Removes the I<paycvv> field from the database directly.
2670 If there is an error, returns the error, otherwise returns false.
2676 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2677 or return dbh->errstr;
2678 $sth->execute($self->custnum)
2679 or return $sth->errstr;
2684 =item batch_card OPTION => VALUE...
2686 Adds a payment for this invoice to the pending credit card batch (see
2687 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2688 runs the payment using a realtime gateway.
2690 Options may include:
2692 B<amount>: the amount to be paid; defaults to the customer's balance minus
2693 any payments in transit.
2695 B<payby>: the payment method; defaults to cust_main.payby
2697 B<realtime>: runs this as a realtime payment instead of adding it to a
2700 B<invnum>: sets cust_pay_batch.invnum.
2702 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2703 the billing address for the payment; defaults to the customer's billing
2706 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2707 date, and name; defaults to those fields in cust_main.
2712 my ($self, %options) = @_;
2715 if (exists($options{amount})) {
2716 $amount = $options{amount};
2718 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2721 warn(sprintf("Customer balance %.2f - in transit amount %.2f is <= 0.\n",
2723 $self->in_transit_payments
2728 my $invnum = delete $options{invnum};
2729 my $payby = $options{payby} || $self->payby; #still dubious
2731 if ($options{'realtime'}) {
2732 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2738 my $oldAutoCommit = $FS::UID::AutoCommit;
2739 local $FS::UID::AutoCommit = 0;
2742 #this needs to handle mysql as well as Pg, like svc_acct.pm
2743 #(make it into a common function if folks need to do batching with mysql)
2744 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2745 or return "Cannot lock pay_batch: " . $dbh->errstr;
2749 'payby' => FS::payby->payby2payment($payby),
2751 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2753 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2755 unless ( $pay_batch ) {
2756 $pay_batch = new FS::pay_batch \%pay_batch;
2757 my $error = $pay_batch->insert;
2759 $dbh->rollback if $oldAutoCommit;
2760 die "error creating new batch: $error\n";
2764 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2765 'batchnum' => $pay_batch->batchnum,
2766 'custnum' => $self->custnum,
2769 foreach (qw( address1 address2 city state zip country latitude longitude
2770 payby payinfo paydate payname ))
2772 $options{$_} = '' unless exists($options{$_});
2775 my $loc = $self->bill_location;
2777 my $cust_pay_batch = new FS::cust_pay_batch ( {
2778 'batchnum' => $pay_batch->batchnum,
2779 'invnum' => $invnum || 0, # is there a better value?
2780 # this field should be
2782 # cust_bill_pay_batch now
2783 'custnum' => $self->custnum,
2784 'last' => $self->getfield('last'),
2785 'first' => $self->getfield('first'),
2786 'address1' => $options{address1} || $loc->address1,
2787 'address2' => $options{address2} || $loc->address2,
2788 'city' => $options{city} || $loc->city,
2789 'state' => $options{state} || $loc->state,
2790 'zip' => $options{zip} || $loc->zip,
2791 'country' => $options{country} || $loc->country,
2792 'payby' => $options{payby} || $self->payby,
2793 'payinfo' => $options{payinfo} || $self->payinfo,
2794 'exp' => $options{paydate} || $self->paydate,
2795 'payname' => $options{payname} || $self->payname,
2796 'amount' => $amount, # consolidating
2799 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2800 if $old_cust_pay_batch;
2803 if ($old_cust_pay_batch) {
2804 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2806 $error = $cust_pay_batch->insert;
2810 $dbh->rollback if $oldAutoCommit;
2814 my $unapplied = $self->total_unapplied_credits
2815 + $self->total_unapplied_payments
2816 + $self->in_transit_payments;
2817 foreach my $cust_bill ($self->open_cust_bill) {
2818 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2819 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2820 'invnum' => $cust_bill->invnum,
2821 'paybatchnum' => $cust_pay_batch->paybatchnum,
2822 'amount' => $cust_bill->owed,
2825 if ($unapplied >= $cust_bill_pay_batch->amount){
2826 $unapplied -= $cust_bill_pay_batch->amount;
2829 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2830 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2832 $error = $cust_bill_pay_batch->insert;
2834 $dbh->rollback if $oldAutoCommit;
2839 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2845 Returns the total owed for this customer on all invoices
2846 (see L<FS::cust_bill/owed>).
2852 $self->total_owed_date(2145859200); #12/31/2037
2855 =item total_owed_date TIME
2857 Returns the total owed for this customer on all invoices with date earlier than
2858 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2859 see L<Time::Local> and L<Date::Parse> for conversion functions.
2863 sub total_owed_date {
2867 my $custnum = $self->custnum;
2869 my $owed_sql = FS::cust_bill->owed_sql;
2872 SELECT SUM($owed_sql) FROM cust_bill
2873 WHERE custnum = $custnum
2877 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2881 =item total_owed_pkgnum PKGNUM
2883 Returns the total owed on all invoices for this customer's specific package
2884 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2888 sub total_owed_pkgnum {
2889 my( $self, $pkgnum ) = @_;
2890 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2893 =item total_owed_date_pkgnum TIME PKGNUM
2895 Returns the total owed for this customer's specific package when using
2896 experimental package balances on all invoices with date earlier than
2897 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2898 see L<Time::Local> and L<Date::Parse> for conversion functions.
2902 sub total_owed_date_pkgnum {
2903 my( $self, $time, $pkgnum ) = @_;
2906 foreach my $cust_bill (
2907 grep { $_->_date <= $time }
2908 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2910 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2912 sprintf( "%.2f", $total_bill );
2918 Returns the total amount of all payments.
2925 $total += $_->paid foreach $self->cust_pay;
2926 sprintf( "%.2f", $total );
2929 =item total_unapplied_credits
2931 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2932 customer. See L<FS::cust_credit/credited>.
2934 =item total_credited
2936 Old name for total_unapplied_credits. Don't use.
2940 sub total_credited {
2941 #carp "total_credited deprecated, use total_unapplied_credits";
2942 shift->total_unapplied_credits(@_);
2945 sub total_unapplied_credits {
2948 my $custnum = $self->custnum;
2950 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2953 SELECT SUM($unapplied_sql) FROM cust_credit
2954 WHERE custnum = $custnum
2957 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2961 =item total_unapplied_credits_pkgnum PKGNUM
2963 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2964 customer. See L<FS::cust_credit/credited>.
2968 sub total_unapplied_credits_pkgnum {
2969 my( $self, $pkgnum ) = @_;
2970 my $total_credit = 0;
2971 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2972 sprintf( "%.2f", $total_credit );
2976 =item total_unapplied_payments
2978 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2979 See L<FS::cust_pay/unapplied>.
2983 sub total_unapplied_payments {
2986 my $custnum = $self->custnum;
2988 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2991 SELECT SUM($unapplied_sql) FROM cust_pay
2992 WHERE custnum = $custnum
2995 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2999 =item total_unapplied_payments_pkgnum PKGNUM
3001 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
3002 specific package when using experimental package balances. See
3003 L<FS::cust_pay/unapplied>.
3007 sub total_unapplied_payments_pkgnum {
3008 my( $self, $pkgnum ) = @_;
3009 my $total_unapplied = 0;
3010 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
3011 sprintf( "%.2f", $total_unapplied );
3015 =item total_unapplied_refunds
3017 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3018 customer. See L<FS::cust_refund/unapplied>.
3022 sub total_unapplied_refunds {
3024 my $custnum = $self->custnum;
3026 my $unapplied_sql = FS::cust_refund->unapplied_sql;
3029 SELECT SUM($unapplied_sql) FROM cust_refund
3030 WHERE custnum = $custnum
3033 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3039 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3040 total_unapplied_credits minus total_unapplied_payments).
3046 $self->balance_date_range;
3049 =item balance_date TIME
3051 Returns the balance for this customer, only considering invoices with date
3052 earlier than TIME (total_owed_date minus total_credited minus
3053 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3054 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3061 $self->balance_date_range(shift);
3064 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3066 Returns the balance for this customer, optionally considering invoices with
3067 date earlier than START_TIME, and not later than END_TIME
3068 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3070 Times are specified as SQL fragments or numeric
3071 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
3072 L<Date::Parse> for conversion functions. The empty string can be passed
3073 to disable that time constraint completely.
3075 Accepts the same options as L<balance_date_sql>:
3079 =item unapplied_date
3081 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)
3085 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
3086 time will be ignored. Note that START_TIME and END_TIME only limit the date
3087 range for invoices and I<unapplied> payments, credits, and refunds.
3093 sub balance_date_range {
3095 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3096 ') FROM cust_main WHERE custnum='. $self->custnum;
3097 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
3100 =item balance_pkgnum PKGNUM
3102 Returns the balance for this customer's specific package when using
3103 experimental package balances (total_owed plus total_unrefunded, minus
3104 total_unapplied_credits minus total_unapplied_payments)
3108 sub balance_pkgnum {
3109 my( $self, $pkgnum ) = @_;
3112 $self->total_owed_pkgnum($pkgnum)
3113 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3114 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
3115 - $self->total_unapplied_credits_pkgnum($pkgnum)
3116 - $self->total_unapplied_payments_pkgnum($pkgnum)
3120 =item in_transit_payments
3122 Returns the total of requests for payments for this customer pending in
3123 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3127 sub in_transit_payments {
3129 my $in_transit_payments = 0;
3130 foreach my $pay_batch ( qsearch('pay_batch', {
3133 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3134 'batchnum' => $pay_batch->batchnum,
3135 'custnum' => $self->custnum,
3138 $in_transit_payments += $cust_pay_batch->amount;
3141 sprintf( "%.2f", $in_transit_payments );
3146 Returns a hash of useful information for making a payment.
3156 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3157 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3158 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3162 For credit card transactions:
3174 For electronic check transactions:
3189 $return{balance} = $self->balance;
3191 $return{payname} = $self->payname
3192 || ( $self->first. ' '. $self->get('last') );
3194 $return{$_} = $self->bill_location->$_
3195 for qw(address1 address2 city state zip);
3197 $return{payby} = $self->payby;
3198 $return{stateid_state} = $self->stateid_state;
3200 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3201 $return{card_type} = cardtype($self->payinfo);
3202 $return{payinfo} = $self->paymask;
3204 @return{'month', 'year'} = $self->paydate_monthyear;
3208 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3209 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3210 $return{payinfo1} = $payinfo1;
3211 $return{payinfo2} = $payinfo2;
3212 $return{paytype} = $self->paytype;
3213 $return{paystate} = $self->paystate;
3217 #doubleclick protection
3219 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3225 =item paydate_monthyear
3227 Returns a two-element list consisting of the month and year of this customer's
3228 paydate (credit card expiration date for CARD customers)
3232 sub paydate_monthyear {
3234 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3236 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3245 Returns the exact time in seconds corresponding to the payment method
3246 expiration date. For CARD/DCRD customers this is the end of the month;
3247 for others (COMP is the only other payby that uses paydate) it's the start.
3248 Returns 0 if the paydate is empty or set to the far future.
3254 my ($month, $year) = $self->paydate_monthyear;
3255 return 0 if !$year or $year >= 2037;
3256 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3258 if ( $month == 13 ) {
3262 return timelocal(0,0,0,1,$month-1,$year) - 1;
3265 return timelocal(0,0,0,1,$month-1,$year);
3269 =item paydate_epoch_sql
3271 Class method. Returns an SQL expression to obtain the payment expiration date
3272 as a number of seconds.
3276 # Special expiration date behavior for non-CARD/DCRD customers has been
3277 # carefully preserved. Do we really use that?
3278 sub paydate_epoch_sql {
3280 my $table = shift || 'cust_main';
3281 my ($case1, $case2);
3282 if ( driver_name eq 'Pg' ) {
3283 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3284 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3286 elsif ( lc(driver_name) eq 'mysql' ) {
3287 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3288 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3291 return "CASE WHEN $table.payby IN('CARD','DCRD')
3297 =item tax_exemption TAXNAME
3302 my( $self, $taxname ) = @_;
3304 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3305 'taxname' => $taxname,
3310 =item cust_main_exemption
3314 sub cust_main_exemption {
3316 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3319 =item invoicing_list [ ARRAYREF ]
3321 If an arguement is given, sets these email addresses as invoice recipients
3322 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3323 (except as warnings), so use check_invoicing_list first.
3325 Returns a list of email addresses (with svcnum entries expanded).
3327 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3328 check it without disturbing anything by passing nothing.
3330 This interface may change in the future.
3334 sub invoicing_list {
3335 my( $self, $arrayref ) = @_;
3338 my @cust_main_invoice;
3339 if ( $self->custnum ) {
3340 @cust_main_invoice =
3341 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3343 @cust_main_invoice = ();
3345 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3346 #warn $cust_main_invoice->destnum;
3347 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3348 #warn $cust_main_invoice->destnum;
3349 my $error = $cust_main_invoice->delete;
3350 warn $error if $error;
3353 if ( $self->custnum ) {
3354 @cust_main_invoice =
3355 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3357 @cust_main_invoice = ();
3359 my %seen = map { $_->address => 1 } @cust_main_invoice;
3360 foreach my $address ( @{$arrayref} ) {
3361 next if exists $seen{$address} && $seen{$address};
3362 $seen{$address} = 1;
3363 my $cust_main_invoice = new FS::cust_main_invoice ( {
3364 'custnum' => $self->custnum,
3367 my $error = $cust_main_invoice->insert;
3368 warn $error if $error;
3372 if ( $self->custnum ) {
3374 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3381 =item check_invoicing_list ARRAYREF
3383 Checks these arguements as valid input for the invoicing_list method. If there
3384 is an error, returns the error, otherwise returns false.
3388 sub check_invoicing_list {
3389 my( $self, $arrayref ) = @_;
3391 foreach my $address ( @$arrayref ) {
3393 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3394 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3397 my $cust_main_invoice = new FS::cust_main_invoice ( {
3398 'custnum' => $self->custnum,
3401 my $error = $self->custnum
3402 ? $cust_main_invoice->check
3403 : $cust_main_invoice->checkdest
3405 return $error if $error;
3409 return "Email address required"
3410 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3411 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3416 =item set_default_invoicing_list
3418 Sets the invoicing list to all accounts associated with this customer,
3419 overwriting any previous invoicing list.
3423 sub set_default_invoicing_list {
3425 $self->invoicing_list($self->all_emails);
3430 Returns the email addresses of all accounts provisioned for this customer.
3437 foreach my $cust_pkg ( $self->all_pkgs ) {
3438 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3440 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3441 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3443 $list{$_}=1 foreach map { $_->email } @svc_acct;
3448 =item invoicing_list_addpost
3450 Adds postal invoicing to this customer. If this customer is already configured
3451 to receive postal invoices, does nothing.
3455 sub invoicing_list_addpost {
3457 return if grep { $_ eq 'POST' } $self->invoicing_list;
3458 my @invoicing_list = $self->invoicing_list;
3459 push @invoicing_list, 'POST';
3460 $self->invoicing_list(\@invoicing_list);
3463 =item invoicing_list_emailonly
3465 Returns the list of email invoice recipients (invoicing_list without non-email
3466 destinations such as POST and FAX).
3470 sub invoicing_list_emailonly {
3472 warn "$me invoicing_list_emailonly called"
3474 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3477 =item invoicing_list_emailonly_scalar
3479 Returns the list of email invoice recipients (invoicing_list without non-email
3480 destinations such as POST and FAX) as a comma-separated scalar.
3484 sub invoicing_list_emailonly_scalar {
3486 warn "$me invoicing_list_emailonly_scalar called"
3488 join(', ', $self->invoicing_list_emailonly);
3491 =item contact_list [ CLASSNUM, ... ]
3493 Returns a list of contacts (L<FS::contact> objects) for the customer. If
3494 a list of contact classnums is given, returns only contacts in those
3495 classes. If '0' is given, also returns contacts with no class.
3497 If no arguments are given, returns all contacts for the customer.
3505 select => 'contact.*',
3506 extra_sql => ' WHERE contact.custnum = '.$self->custnum,
3513 push @orwhere, 'contact.classnum is null';
3514 } elsif ( /^\d+$/ ) {
3515 push @classnums, $_;
3517 die "bad classnum argument '$_'";
3522 push @orwhere, 'contact.classnum IN ('.join(',', @classnums).')';
3525 $search->{extra_sql} .= ' AND (' .
3526 join(' OR ', map "( $_ )", @orwhere) .
3533 =item contact_list_email [ CLASSNUM, ... ]
3535 Same as L</contact_list>, but returns email destinations instead of contact
3536 objects. Also accepts 'invoice' as an argument, in which case this will also
3537 return the invoice email address if any.
3541 sub contact_list_email {
3549 push @classnums, $_;
3553 # if the only argument passed was 'invoice' then no classnums are
3554 # intended, so skip this.
3556 my @contacts = $self->contact_list(@classnums);
3557 foreach my $contact (@contacts) {
3558 foreach my $contact_email ($contact->contact_email) {
3559 # unlike on 4.x, we have a separate list of invoice email
3561 # make sure they're not redundant with contact emails
3562 my $dest = $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3563 $emails{ $contact_email->emailaddress } = $dest;
3567 if ( $and_invoice ) {
3568 foreach my $email ($self->invoicing_list_emailonly) {
3569 my $dest = $self->name_short . ' <' . $email . '>';
3570 $emails{ $email } ||= $dest;
3576 =item referral_custnum_cust_main
3578 Returns the customer who referred this customer (or the empty string, if
3579 this customer was not referred).
3581 Note the difference with referral_cust_main method: This method,
3582 referral_custnum_cust_main returns the single customer (if any) who referred
3583 this customer, while referral_cust_main returns an array of customers referred
3588 sub referral_custnum_cust_main {
3590 return '' unless $self->referral_custnum;
3591 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3594 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3596 Returns an array of customers referred by this customer (referral_custnum set
3597 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3598 customers referred by customers referred by this customer and so on, inclusive.
3599 The default behavior is DEPTH 1 (no recursion).
3601 Note the difference with referral_custnum_cust_main method: This method,
3602 referral_cust_main, returns an array of customers referred BY this customer,
3603 while referral_custnum_cust_main returns the single customer (if any) who
3604 referred this customer.
3608 sub referral_cust_main {
3610 my $depth = @_ ? shift : 1;
3611 my $exclude = @_ ? shift : {};
3614 map { $exclude->{$_->custnum}++; $_; }
3615 grep { ! $exclude->{ $_->custnum } }
3616 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3620 map { $_->referral_cust_main($depth-1, $exclude) }
3627 =item referral_cust_main_ncancelled
3629 Same as referral_cust_main, except only returns customers with uncancelled
3634 sub referral_cust_main_ncancelled {
3636 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3639 =item referral_cust_pkg [ DEPTH ]
3641 Like referral_cust_main, except returns a flat list of all unsuspended (and
3642 uncancelled) packages for each customer. The number of items in this list may
3643 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3647 sub referral_cust_pkg {
3649 my $depth = @_ ? shift : 1;
3651 map { $_->unsuspended_pkgs }
3652 grep { $_->unsuspended_pkgs }
3653 $self->referral_cust_main($depth);
3656 =item referring_cust_main
3658 Returns the single cust_main record for the customer who referred this customer
3659 (referral_custnum), or false.
3663 sub referring_cust_main {
3665 return '' unless $self->referral_custnum;
3666 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3669 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3671 Applies a credit to this customer. If there is an error, returns the error,
3672 otherwise returns false.
3674 REASON can be a text string, an FS::reason object, or a scalar reference to
3675 a reasonnum. If a text string, it will be automatically inserted as a new
3676 reason, and a 'reason_type' option must be passed to indicate the
3677 FS::reason_type for the new reason.
3679 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3680 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3681 I<commission_pkgnum>.
3683 Any other options are passed to FS::cust_credit::insert.
3688 my( $self, $amount, $reason, %options ) = @_;
3690 my $cust_credit = new FS::cust_credit {
3691 'custnum' => $self->custnum,
3692 'amount' => $amount,
3695 if ( ref($reason) ) {
3697 if ( ref($reason) eq 'SCALAR' ) {
3698 $cust_credit->reasonnum( $$reason );
3700 $cust_credit->reasonnum( $reason->reasonnum );
3704 $cust_credit->set('reason', $reason)
3707 $cust_credit->$_( delete $options{$_} )
3708 foreach grep exists($options{$_}),
3709 qw( addlinfo eventnum ),
3710 map "commission_$_", qw( agentnum salesnum pkgnum );
3712 $cust_credit->insert(%options);
3716 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3718 Creates a one-time charge for this customer. If there is an error, returns
3719 the error, otherwise returns false.
3721 New-style, with a hashref of options:
3723 my $error = $cust_main->charge(
3727 'start_date' => str2time('7/4/2009'),
3728 'pkg' => 'Description',
3729 'comment' => 'Comment',
3730 'additional' => [], #extra invoice detail
3731 'classnum' => 1, #pkg_class
3733 'setuptax' => '', # or 'Y' for tax exempt
3735 'locationnum'=> 1234, # optional
3738 'taxclass' => 'Tax class',
3741 'taxproduct' => 2, #part_pkg_taxproduct
3742 'override' => {}, #XXX describe
3744 #will be filled in with the new object
3745 'cust_pkg_ref' => \$cust_pkg,
3747 #generate an invoice immediately
3749 'invoice_terms' => '', #with these terms
3755 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3759 #super false laziness w/quotation::charge
3762 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3763 my ( $pkg, $comment, $additional );
3764 my ( $setuptax, $taxclass ); #internal taxes
3765 my ( $taxproduct, $override ); #vendor (CCH) taxes
3767 my $separate_bill = '';
3768 my $cust_pkg_ref = '';
3769 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3771 if ( ref( $_[0] ) ) {
3772 $amount = $_[0]->{amount};
3773 $setup_cost = $_[0]->{setup_cost};
3774 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3775 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3776 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3777 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3778 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3779 : '$'. sprintf("%.2f",$amount);
3780 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3781 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3782 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3783 $additional = $_[0]->{additional} || [];
3784 $taxproduct = $_[0]->{taxproductnum};
3785 $override = { '' => $_[0]->{tax_override} };
3786 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3787 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3788 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3789 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3790 $separate_bill = $_[0]->{separate_bill} || '';
3796 $pkg = @_ ? shift : 'One-time charge';
3797 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3799 $taxclass = @_ ? shift : '';
3803 local $SIG{HUP} = 'IGNORE';
3804 local $SIG{INT} = 'IGNORE';
3805 local $SIG{QUIT} = 'IGNORE';
3806 local $SIG{TERM} = 'IGNORE';
3807 local $SIG{TSTP} = 'IGNORE';
3808 local $SIG{PIPE} = 'IGNORE';
3810 my $oldAutoCommit = $FS::UID::AutoCommit;
3811 local $FS::UID::AutoCommit = 0;
3814 my $part_pkg = new FS::part_pkg ( {
3816 'comment' => $comment,
3820 'classnum' => ( $classnum ? $classnum : '' ),
3821 'setuptax' => $setuptax,
3822 'taxclass' => $taxclass,
3823 'taxproductnum' => $taxproduct,
3824 'setup_cost' => $setup_cost,
3827 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3828 ( 0 .. @$additional - 1 )
3830 'additional_count' => scalar(@$additional),
3831 'setup_fee' => $amount,
3834 my $error = $part_pkg->insert( options => \%options,
3835 tax_overrides => $override,
3838 $dbh->rollback if $oldAutoCommit;
3842 my $pkgpart = $part_pkg->pkgpart;
3843 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3844 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3845 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3846 $error = $type_pkgs->insert;
3848 $dbh->rollback if $oldAutoCommit;
3853 my $cust_pkg = new FS::cust_pkg ( {
3854 'custnum' => $self->custnum,
3855 'pkgpart' => $pkgpart,
3856 'quantity' => $quantity,
3857 'start_date' => $start_date,
3858 'no_auto' => $no_auto,
3859 'separate_bill' => $separate_bill,
3860 'locationnum'=> $locationnum,
3863 $error = $cust_pkg->insert;
3865 $dbh->rollback if $oldAutoCommit;
3867 } elsif ( $cust_pkg_ref ) {
3868 ${$cust_pkg_ref} = $cust_pkg;
3872 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3873 'pkg_list' => [ $cust_pkg ],
3876 $dbh->rollback if $oldAutoCommit;
3881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3886 #=item charge_postal_fee
3888 #Applies a one time charge this customer. If there is an error,
3889 #returns the error, returns the cust_pkg charge object or false
3890 #if there was no charge.
3894 # This should be a customer event. For that to work requires that bill
3895 # also be a customer event.
3897 sub charge_postal_fee {
3900 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3901 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3903 my $cust_pkg = new FS::cust_pkg ( {
3904 'custnum' => $self->custnum,
3905 'pkgpart' => $pkgpart,
3909 my $error = $cust_pkg->insert;
3910 $error ? $error : $cust_pkg;
3913 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3915 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3917 Optionally, a list or hashref of additional arguments to the qsearch call can
3924 my $opt = ref($_[0]) ? shift : { @_ };
3926 #return $self->num_cust_bill unless wantarray || keys %$opt;
3928 $opt->{'table'} = 'cust_bill';
3929 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3930 $opt->{'hashref'}{'custnum'} = $self->custnum;
3931 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3933 map { $_ } #behavior of sort undefined in scalar context
3934 sort { $a->_date <=> $b->_date }
3938 =item open_cust_bill
3940 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3945 sub open_cust_bill {
3949 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3955 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3957 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3961 sub legacy_cust_bill {
3964 #return $self->num_legacy_cust_bill unless wantarray;
3966 map { $_ } #behavior of sort undefined in scalar context
3967 sort { $a->_date <=> $b->_date }
3968 qsearch({ 'table' => 'legacy_cust_bill',
3969 'hashref' => { 'custnum' => $self->custnum, },
3970 'order_by' => 'ORDER BY _date ASC',
3974 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3976 Returns all the statements (see L<FS::cust_statement>) for this customer.
3978 Optionally, a list or hashref of additional arguments to the qsearch call can
3983 =item cust_bill_void
3985 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3989 sub cust_bill_void {
3992 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3993 sort { $a->_date <=> $b->_date }
3994 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3997 sub cust_statement {
3999 my $opt = ref($_[0]) ? shift : { @_ };
4001 #return $self->num_cust_statement unless wantarray || keys %$opt;
4003 $opt->{'table'} = 'cust_statement';
4004 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4005 $opt->{'hashref'}{'custnum'} = $self->custnum;
4006 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
4008 map { $_ } #behavior of sort undefined in scalar context
4009 sort { $a->_date <=> $b->_date }
4013 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
4015 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
4017 Optionally, a list or hashref of additional arguments to the qsearch call can
4018 be passed following the SVCDB.
4025 if ( ! $svcdb =~ /^svc_\w+$/ ) {
4026 warn "$me svc_x requires a svcdb";
4029 my $opt = ref($_[0]) ? shift : { @_ };
4031 $opt->{'table'} = $svcdb;
4032 $opt->{'addl_from'} =
4033 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
4034 ($opt->{'addl_from'} || '');
4036 my $custnum = $self->custnum;
4037 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
4038 my $where = "cust_pkg.custnum = $custnum";
4040 my $extra_sql = $opt->{'extra_sql'} || '';
4041 if ( keys %{ $opt->{'hashref'} } ) {
4042 $extra_sql = " AND $where $extra_sql";
4045 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
4046 $extra_sql = "WHERE $where AND $1";
4049 $extra_sql = "WHERE $where $extra_sql";
4052 $opt->{'extra_sql'} = $extra_sql;
4057 # required for use as an eventtable;
4060 $self->svc_x('svc_acct', @_);
4065 Returns all the credits (see L<FS::cust_credit>) for this customer.
4071 map { $_ } #return $self->num_cust_credit unless wantarray;
4072 sort { $a->_date <=> $b->_date }
4073 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4076 =item cust_credit_pkgnum
4078 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
4079 package when using experimental package balances.
4083 sub cust_credit_pkgnum {
4084 my( $self, $pkgnum ) = @_;
4085 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
4086 sort { $a->_date <=> $b->_date }
4087 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
4088 'pkgnum' => $pkgnum,
4093 =item cust_credit_void
4095 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
4099 sub cust_credit_void {
4102 sort { $a->_date <=> $b->_date }
4103 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
4108 Returns all the payments (see L<FS::cust_pay>) for this customer.
4114 my $opt = ref($_[0]) ? shift : { @_ };
4116 return $self->num_cust_pay unless wantarray || keys %$opt;
4118 $opt->{'table'} = 'cust_pay';
4119 $opt->{'hashref'}{'custnum'} = $self->custnum;
4121 map { $_ } #behavior of sort undefined in scalar context
4122 sort { $a->_date <=> $b->_date }
4129 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
4130 called automatically when the cust_pay method is used in a scalar context.
4136 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
4137 my $sth = dbh->prepare($sql) or die dbh->errstr;
4138 $sth->execute($self->custnum) or die $sth->errstr;
4139 $sth->fetchrow_arrayref->[0];
4142 =item unapplied_cust_pay
4144 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
4148 sub unapplied_cust_pay {
4152 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
4158 =item cust_pay_pkgnum
4160 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
4161 package when using experimental package balances.
4165 sub cust_pay_pkgnum {
4166 my( $self, $pkgnum ) = @_;
4167 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
4168 sort { $a->_date <=> $b->_date }
4169 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
4170 'pkgnum' => $pkgnum,
4177 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4183 map { $_ } #return $self->num_cust_pay_void unless wantarray;
4184 sort { $a->_date <=> $b->_date }
4185 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4188 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4190 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
4192 Optionally, a list or hashref of additional arguments to the qsearch call can
4197 sub cust_pay_batch {
4199 my $opt = ref($_[0]) ? shift : { @_ };
4201 #return $self->num_cust_statement unless wantarray || keys %$opt;
4203 $opt->{'table'} = 'cust_pay_batch';
4204 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4205 $opt->{'hashref'}{'custnum'} = $self->custnum;
4206 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
4208 map { $_ } #behavior of sort undefined in scalar context
4209 sort { $a->paybatchnum <=> $b->paybatchnum }
4213 =item cust_pay_pending
4215 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
4216 (without status "done").
4220 sub cust_pay_pending {
4222 return $self->num_cust_pay_pending unless wantarray;
4223 sort { $a->_date <=> $b->_date }
4224 qsearch( 'cust_pay_pending', {
4225 'custnum' => $self->custnum,
4226 'status' => { op=>'!=', value=>'done' },
4231 =item cust_pay_pending_attempt
4233 Returns all payment attempts / declined payments for this customer, as pending
4234 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
4235 a corresponding payment (see L<FS::cust_pay>).
4239 sub cust_pay_pending_attempt {
4241 return $self->num_cust_pay_pending_attempt unless wantarray;
4242 sort { $a->_date <=> $b->_date }
4243 qsearch( 'cust_pay_pending', {
4244 'custnum' => $self->custnum,
4251 =item num_cust_pay_pending
4253 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4254 customer (without status "done"). Also called automatically when the
4255 cust_pay_pending method is used in a scalar context.
4259 sub num_cust_pay_pending {
4262 " SELECT COUNT(*) FROM cust_pay_pending ".
4263 " WHERE custnum = ? AND status != 'done' ",
4268 =item num_cust_pay_pending_attempt
4270 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4271 customer, with status "done" but without a corresp. Also called automatically when the
4272 cust_pay_pending method is used in a scalar context.
4276 sub num_cust_pay_pending_attempt {
4279 " SELECT COUNT(*) FROM cust_pay_pending ".
4280 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4287 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4293 map { $_ } #return $self->num_cust_refund unless wantarray;
4294 sort { $a->_date <=> $b->_date }
4295 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4298 =item display_custnum
4300 Returns the displayed customer number for this customer: agent_custid if
4301 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4305 sub display_custnum {
4308 return $self->agent_custid
4309 if $default_agent_custid && $self->agent_custid;
4311 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4315 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
4316 } elsif ( $custnum_display_length ) {
4317 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
4319 return $self->custnum;
4325 Returns a name string for this customer, either "Company (Last, First)" or
4332 my $name = $self->contact;
4333 $name = $self->company. " ($name)" if $self->company;
4337 =item service_contact
4339 Returns the L<FS::contact> object for this customer that has the 'Service'
4340 contact class, or undef if there is no such contact. Deprecated; don't use
4345 sub service_contact {
4347 if ( !exists($self->{service_contact}) ) {
4348 my $classnum = $self->scalar_sql(
4349 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4350 ) || 0; #if it's zero, qsearchs will return nothing
4351 $self->{service_contact} = qsearchs('contact', {
4352 'classnum' => $classnum, 'custnum' => $self->custnum
4355 $self->{service_contact};
4360 Returns a name string for this (service/shipping) contact, either
4361 "Company (Last, First)" or "Last, First".
4368 my $name = $self->ship_contact;
4369 $name = $self->company. " ($name)" if $self->company;
4375 Returns a name string for this customer, either "Company" or "First Last".
4381 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4384 =item ship_name_short
4386 Returns a name string for this (service/shipping) contact, either "Company"
4391 sub ship_name_short {
4393 $self->service_contact
4394 ? $self->ship_contact_firstlast
4400 Returns this customer's full (billing) contact name only, "Last, First"
4406 $self->get('last'). ', '. $self->first;
4411 Returns this customer's full (shipping) contact name only, "Last, First"
4417 my $contact = $self->service_contact || $self;
4418 $contact->get('last') . ', ' . $contact->get('first');
4421 =item contact_firstlast
4423 Returns this customers full (billing) contact name only, "First Last".
4427 sub contact_firstlast {
4429 $self->first. ' '. $self->get('last');
4432 =item ship_contact_firstlast
4434 Returns this customer's full (shipping) contact name only, "First Last".
4438 sub ship_contact_firstlast {
4440 my $contact = $self->service_contact || $self;
4441 $contact->get('first') . ' '. $contact->get('last');
4444 sub bill_country_full {
4446 $self->bill_location->country_full;
4449 sub ship_country_full {
4451 $self->ship_location->country_full;
4454 =item county_state_county [ PREFIX ]
4456 Returns a string consisting of just the county, state and country.
4460 sub county_state_country {
4463 if ( @_ && $_[0] && $self->has_ship_address ) {
4464 $locationnum = $self->ship_locationnum;
4466 $locationnum = $self->bill_locationnum;
4468 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4469 $cust_location->county_state_country;
4472 =item geocode DATA_VENDOR
4474 Returns a value for the customer location as encoded by DATA_VENDOR.
4475 Currently this only makes sense for "CCH" as DATA_VENDOR.
4483 Returns a status string for this customer, currently:
4487 =item prospect - No packages have ever been ordered
4489 =item ordered - Recurring packages all are new (not yet billed).
4491 =item active - One or more recurring packages is active
4493 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4495 =item suspended - All non-cancelled recurring packages are suspended
4497 =item cancelled - All recurring packages are cancelled
4501 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4502 cust_main-status_module configuration option.
4506 sub status { shift->cust_status(@_); }
4510 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
4511 for my $status ( FS::cust_main->statuses() ) {
4512 my $method = $status.'_sql';
4513 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4514 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4515 $sth->execute( ($self->custnum) x $numnum )
4516 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4517 if ( $sth->fetchrow_arrayref->[0] ) {
4518 $self->hashref->{cust_status} = $status;
4524 =item is_status_delay_cancel
4526 Returns true if customer status is 'suspended'
4527 and all suspended cust_pkg return true for
4528 cust_pkg->is_status_delay_cancel.
4530 This is not a real status, this only meant for hacking display
4531 values, because otherwise treating the customer as suspended is
4532 really the whole point of the delay_cancel option.
4536 sub is_status_delay_cancel {
4538 return 0 unless $self->status eq 'suspended';
4539 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4540 return 0 unless $cust_pkg->is_status_delay_cancel;
4545 =item ucfirst_cust_status
4547 =item ucfirst_status
4549 Returns the status with the first character capitalized.
4553 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4555 sub ucfirst_cust_status {
4557 ucfirst($self->cust_status);
4562 Returns a hex triplet color string for this customer's status.
4566 sub statuscolor { shift->cust_statuscolor(@_); }
4568 sub cust_statuscolor {
4570 __PACKAGE__->statuscolors->{$self->cust_status};
4573 =item tickets [ STATUS ]
4575 Returns an array of hashes representing the customer's RT tickets.
4577 An optional status (or arrayref or hashref of statuses) may be specified.
4583 my $status = ( @_ && $_[0] ) ? shift : '';
4585 my $num = $conf->config('cust_main-max_tickets') || 10;
4588 if ( $conf->config('ticket_system') ) {
4589 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4591 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4600 foreach my $priority (
4601 $conf->config('ticket_system-custom_priority_field-values'), ''
4603 last if scalar(@tickets) >= $num;
4605 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4606 $num - scalar(@tickets),
4617 =item appointments [ STATUS ]
4619 Returns an array of hashes representing the customer's RT tickets which
4626 my $status = ( @_ && $_[0] ) ? shift : '';
4628 return () unless $conf->config('ticket_system');
4630 my $queueid = $conf->config('ticket_system-appointment-queueid');
4632 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4641 # Return services representing svc_accts in customer support packages
4642 sub support_services {
4644 my %packages = map { $_ => 1 } $conf->config('support_packages');
4646 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4647 grep { $_->part_svc->svcdb eq 'svc_acct' }
4648 map { $_->cust_svc }
4649 grep { exists $packages{ $_->pkgpart } }
4650 $self->ncancelled_pkgs;
4654 # Return a list of latitude/longitude for one of the services (if any)
4655 sub service_coordinates {
4659 grep { $_->latitude && $_->longitude }
4661 map { $_->cust_svc }
4662 $self->ncancelled_pkgs;
4664 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4669 Returns a masked version of the named field
4674 my ($self,$field) = @_;
4678 'x'x(length($self->getfield($field))-4).
4679 substr($self->getfield($field), (length($self->getfield($field))-4));
4683 =item payment_history
4685 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4686 cust_credit and cust_refund objects. Each hashref has the following fields:
4688 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4690 I<date> - value of _date field, unix timestamp
4692 I<date_pretty> - user-friendly date
4694 I<description> - user-friendly description of item
4696 I<amount> - impact of item on user's balance
4697 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4698 Not to be confused with the native 'amount' field in cust_credit, see below.
4700 I<amount_pretty> - includes money char
4702 I<balance> - customer balance, chronologically as of this item
4704 I<balance_pretty> - includes money char
4706 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4708 I<paid> - amount paid for cust_pay records, undef for other types
4710 I<credit> - amount credited for cust_credit records, undef for other types.
4711 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4713 I<refund> - amount refunded for cust_refund records, undef for other types
4715 The four table-specific keys always have positive values, whether they reflect charges or payments.
4717 The following options may be passed to this method:
4719 I<line_items> - if true, returns charges ('Line item') rather than invoices
4721 I<start_date> - unix timestamp, only include records on or after.
4722 If specified, an item of type 'Previous' will also be included.
4723 It does not have table-specific fields.
4725 I<end_date> - unix timestamp, only include records before
4727 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4729 I<conf> - optional already-loaded FS::Conf object.
4733 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4734 # and also for sending customer statements, which should both be kept customer-friendly.
4735 # If you add anything that shouldn't be passed on through the API or exposed
4736 # to customers, add a new option to include it, don't include it by default
4737 sub payment_history {
4739 my $opt = ref($_[0]) ? $_[0] : { @_ };
4741 my $conf = $$opt{'conf'} || new FS::Conf;
4742 my $money_char = $conf->config("money_char") || '$',
4744 #first load entire history,
4745 #need previous to calculate previous balance
4746 #loading after end_date shouldn't hurt too much?
4748 if ( $$opt{'line_items'} ) {
4750 foreach my $cust_bill ( $self->cust_bill ) {
4753 'type' => 'Line item',
4754 'description' => $_->desc( $self->locale ).
4755 ( $_->sdate && $_->edate
4756 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4757 ' To '. time2str('%d-%b-%Y', $_->edate)
4760 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4761 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4762 'date' => $cust_bill->_date,
4763 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4765 foreach $cust_bill->cust_bill_pkg;
4772 'type' => 'Invoice',
4773 'description' => 'Invoice #'. $_->display_invnum,
4774 'amount' => sprintf('%.2f', $_->charged ),
4775 'charged' => sprintf('%.2f', $_->charged ),
4776 'date' => $_->_date,
4777 'date_pretty' => $self->time2str_local('short', $_->_date ),
4779 foreach $self->cust_bill;
4784 'type' => 'Payment',
4785 'description' => 'Payment', #XXX type
4786 'amount' => sprintf('%.2f', 0 - $_->paid ),
4787 'paid' => sprintf('%.2f', $_->paid ),
4788 'date' => $_->_date,
4789 'date_pretty' => $self->time2str_local('short', $_->_date ),
4791 foreach $self->cust_pay;
4795 'description' => 'Credit', #more info?
4796 'amount' => sprintf('%.2f', 0 -$_->amount ),
4797 'credit' => sprintf('%.2f', $_->amount ),
4798 'date' => $_->_date,
4799 'date_pretty' => $self->time2str_local('short', $_->_date ),
4801 foreach $self->cust_credit;
4805 'description' => 'Refund', #more info? type, like payment?
4806 'amount' => $_->refund,
4807 'refund' => $_->refund,
4808 'date' => $_->_date,
4809 'date_pretty' => $self->time2str_local('short', $_->_date ),
4811 foreach $self->cust_refund;
4813 #put it all in chronological order
4814 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4816 #calculate balance, filter items outside date range
4820 foreach my $item (@history) {
4821 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4822 $balance += $$item{'amount'};
4823 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4824 $previous += $$item{'amount'};
4827 $$item{'balance'} = sprintf("%.2f",$balance);
4828 foreach my $key ( qw(amount balance) ) {
4829 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4834 # start with previous balance, if there was one
4837 'type' => 'Previous',
4838 'description' => 'Previous balance',
4839 'amount' => sprintf("%.2f",$previous),
4840 'balance' => sprintf("%.2f",$previous),
4841 'date' => $$opt{'start_date'},
4842 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4844 #false laziness with above
4845 foreach my $key ( qw(amount balance) ) {
4846 $$item{$key.'_pretty'} = $$item{$key};
4847 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4849 unshift(@out,$item);
4852 @out = reverse @history if $$opt{'reverse_sort'};
4859 =head1 CLASS METHODS
4865 Class method that returns the list of possible status strings for customers
4866 (see L<the status method|/status>). For example:
4868 @statuses = FS::cust_main->statuses();
4874 keys %{ $self->statuscolors };
4877 =item cust_status_sql
4879 Returns an SQL fragment to determine the status of a cust_main record, as a
4884 sub cust_status_sql {
4886 for my $status ( FS::cust_main->statuses() ) {
4887 my $method = $status.'_sql';
4888 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4897 Returns an SQL expression identifying prospective cust_main records (customers
4898 with no packages ever ordered)
4902 use vars qw($select_count_pkgs);
4903 $select_count_pkgs =
4904 "SELECT COUNT(*) FROM cust_pkg
4905 WHERE cust_pkg.custnum = cust_main.custnum";
4907 sub select_count_pkgs_sql {
4912 " 0 = ( $select_count_pkgs ) ";
4917 Returns an SQL expression identifying ordered cust_main records (customers with
4918 no active packages, but recurring packages not yet setup or one time charges
4924 FS::cust_main->none_active_sql.
4925 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4930 Returns an SQL expression identifying active cust_main records (customers with
4931 active recurring packages).
4936 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4939 =item none_active_sql
4941 Returns an SQL expression identifying cust_main records with no active
4942 recurring packages. This includes customers of status prospect, ordered,
4943 inactive, and suspended.
4947 sub none_active_sql {
4948 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4953 Returns an SQL expression identifying inactive cust_main records (customers with
4954 no active recurring packages, but otherwise unsuspended/uncancelled).
4959 FS::cust_main->none_active_sql.
4960 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4966 Returns an SQL expression identifying suspended cust_main records.
4971 sub suspended_sql { susp_sql(@_); }
4973 FS::cust_main->none_active_sql.
4974 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4980 Returns an SQL expression identifying cancelled cust_main records.
4984 sub cancel_sql { shift->cancelled_sql(@_); }
4987 =item uncancelled_sql
4989 Returns an SQL expression identifying un-cancelled cust_main records.
4993 sub uncancelled_sql { uncancel_sql(@_); }
4996 "( NOT (".$self->cancelled_sql.") )"; #sensitive to cust_main-status_module
5001 Returns an SQL fragment to retreive the balance.
5006 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5007 WHERE cust_bill.custnum = cust_main.custnum )
5008 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5009 WHERE cust_pay.custnum = cust_main.custnum )
5010 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5011 WHERE cust_credit.custnum = cust_main.custnum )
5012 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5013 WHERE cust_refund.custnum = cust_main.custnum )
5016 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
5018 Returns an SQL fragment to retreive the balance for this customer, optionally
5019 considering invoices with date earlier than START_TIME, and not
5020 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5021 total_unapplied_payments).
5023 Times are specified as SQL fragments or numeric
5024 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5025 L<Date::Parse> for conversion functions. The empty string can be passed
5026 to disable that time constraint completely.
5028 Available options are:
5032 =item unapplied_date
5034 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)
5039 set to true to remove all customer comparison clauses, for totals
5044 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5049 JOIN clause (typically used with the total option)
5053 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
5054 time will be ignored. Note that START_TIME and END_TIME only limit the date
5055 range for invoices and I<unapplied> payments, credits, and refunds.
5061 sub balance_date_sql {
5062 my( $class, $start, $end, %opt ) = @_;
5064 my $cutoff = $opt{'cutoff'};
5066 my $owed = FS::cust_bill->owed_sql($cutoff);
5067 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
5068 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
5069 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5071 my $j = $opt{'join'} || '';
5073 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5074 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5075 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5076 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5078 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5079 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5080 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5081 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5086 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
5088 Returns an SQL fragment to retreive the total unapplied payments for this
5089 customer, only considering payments with date earlier than START_TIME, and
5090 optionally not later than END_TIME.
5092 Times are specified as SQL fragments or numeric
5093 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5094 L<Date::Parse> for conversion functions. The empty string can be passed
5095 to disable that time constraint completely.
5097 Available options are:
5101 sub unapplied_payments_date_sql {
5102 my( $class, $start, $end, %opt ) = @_;
5104 my $cutoff = $opt{'cutoff'};
5106 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5108 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
5109 'unapplied_date'=>1 );
5111 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
5114 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5116 Helper method for balance_date_sql; name (and usage) subject to change
5117 (suggestions welcome).
5119 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5120 cust_refund, cust_credit or cust_pay).
5122 If TABLE is "cust_bill" or the unapplied_date option is true, only
5123 considers records with date earlier than START_TIME, and optionally not
5124 later than END_TIME .
5128 sub _money_table_where {
5129 my( $class, $table, $start, $end, %opt ) = @_;
5132 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5133 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5134 push @where, "$table._date <= $start" if defined($start) && length($start);
5135 push @where, "$table._date > $end" if defined($end) && length($end);
5137 push @where, @{$opt{'where'}} if $opt{'where'};
5138 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5144 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5145 use FS::cust_main::Search;
5148 FS::cust_main::Search->search(@_);
5163 #warn join('-',keys %$param);
5164 my $fh = $param->{filehandle};
5165 my $agentnum = $param->{agentnum};
5166 my $format = $param->{format};
5168 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
5171 if ( $format eq 'simple' ) {
5172 @fields = qw( custnum agent_custid amount pkg );
5174 die "unknown format $format";
5177 eval "use Text::CSV_XS;";
5180 my $csv = new Text::CSV_XS;
5187 local $SIG{HUP} = 'IGNORE';
5188 local $SIG{INT} = 'IGNORE';
5189 local $SIG{QUIT} = 'IGNORE';
5190 local $SIG{TERM} = 'IGNORE';
5191 local $SIG{TSTP} = 'IGNORE';
5192 local $SIG{PIPE} = 'IGNORE';
5194 my $oldAutoCommit = $FS::UID::AutoCommit;
5195 local $FS::UID::AutoCommit = 0;
5198 #while ( $columns = $csv->getline($fh) ) {
5200 while ( defined($line=<$fh>) ) {
5202 $csv->parse($line) or do {
5203 $dbh->rollback if $oldAutoCommit;
5204 return "can't parse: ". $csv->error_input();
5207 my @columns = $csv->fields();
5208 #warn join('-',@columns);
5211 foreach my $field ( @fields ) {
5212 $row{$field} = shift @columns;
5215 if ( $row{custnum} && $row{agent_custid} ) {
5216 dbh->rollback if $oldAutoCommit;
5217 return "can't specify custnum with agent_custid $row{agent_custid}";
5221 if ( $row{agent_custid} && $agentnum ) {
5222 %hash = ( 'agent_custid' => $row{agent_custid},
5223 'agentnum' => $agentnum,
5227 if ( $row{custnum} ) {
5228 %hash = ( 'custnum' => $row{custnum} );
5231 unless ( scalar(keys %hash) ) {
5232 $dbh->rollback if $oldAutoCommit;
5233 return "can't find customer without custnum or agent_custid and agentnum";
5236 my $cust_main = qsearchs('cust_main', { %hash } );
5237 unless ( $cust_main ) {
5238 $dbh->rollback if $oldAutoCommit;
5239 my $custnum = $row{custnum} || $row{agent_custid};
5240 return "unknown custnum $custnum";
5243 if ( $row{'amount'} > 0 ) {
5244 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5246 $dbh->rollback if $oldAutoCommit;
5250 } elsif ( $row{'amount'} < 0 ) {
5251 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5254 $dbh->rollback if $oldAutoCommit;
5264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5266 return "Empty file!" unless $imported;
5272 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5274 Deprecated. Use event notification and message templates
5275 (L<FS::msg_template>) instead.
5277 Sends a templated email notification to the customer (see L<Text::Template>).
5279 OPTIONS is a hash and may include
5281 I<from> - the email sender (default is invoice_from)
5283 I<to> - comma-separated scalar or arrayref of recipients
5284 (default is invoicing_list)
5286 I<subject> - The subject line of the sent email notification
5287 (default is "Notice from company_name")
5289 I<extra_fields> - a hashref of name/value pairs which will be substituted
5292 The following variables are vavailable in the template.
5294 I<$first> - the customer first name
5295 I<$last> - the customer last name
5296 I<$company> - the customer company
5297 I<$payby> - a description of the method of payment for the customer
5298 # would be nice to use FS::payby::shortname
5299 I<$payinfo> - the account information used to collect for this customer
5300 I<$expdate> - the expiration of the customer payment in seconds from epoch
5305 my ($self, $template, %options) = @_;
5307 return unless $conf->exists($template);
5309 my $from = $conf->invoice_from_full($self->agentnum)
5310 if $conf->exists('invoice_from', $self->agentnum);
5311 $from = $options{from} if exists($options{from});
5313 my $to = join(',', $self->invoicing_list_emailonly);
5314 $to = $options{to} if exists($options{to});
5316 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5317 if $conf->exists('company_name', $self->agentnum);
5318 $subject = $options{subject} if exists($options{subject});
5320 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5321 SOURCE => [ map "$_\n",
5322 $conf->config($template)]
5324 or die "can't create new Text::Template object: Text::Template::ERROR";
5325 $notify_template->compile()
5326 or die "can't compile template: Text::Template::ERROR";
5328 $FS::notify_template::_template::company_name =
5329 $conf->config('company_name', $self->agentnum);
5330 $FS::notify_template::_template::company_address =
5331 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5333 my $paydate = $self->paydate || '2037-12-31';
5334 $FS::notify_template::_template::first = $self->first;
5335 $FS::notify_template::_template::last = $self->last;
5336 $FS::notify_template::_template::company = $self->company;
5337 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5338 my $payby = $self->payby;
5339 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5340 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5342 #credit cards expire at the end of the month/year of their exp date
5343 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5344 $FS::notify_template::_template::payby = 'credit card';
5345 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5346 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5348 }elsif ($payby eq 'COMP') {
5349 $FS::notify_template::_template::payby = 'complimentary account';
5351 $FS::notify_template::_template::payby = 'current method';
5353 $FS::notify_template::_template::expdate = $expire_time;
5355 for (keys %{$options{extra_fields}}){
5357 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5360 send_email(from => $from,
5362 subject => $subject,
5363 body => $notify_template->fill_in( PACKAGE =>
5364 'FS::notify_template::_template' ),
5369 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5371 Generates a templated notification to the customer (see L<Text::Template>).
5373 OPTIONS is a hash and may include
5375 I<extra_fields> - a hashref of name/value pairs which will be substituted
5376 into the template. These values may override values mentioned below
5377 and those from the customer record.
5379 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5381 The following variables are available in the template instead of or in addition
5382 to the fields of the customer record.
5384 I<$payby> - a description of the method of payment for the customer
5385 # would be nice to use FS::payby::shortname
5386 I<$payinfo> - the masked account information used to collect for this customer
5387 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5388 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5392 # a lot like cust_bill::print_latex
5393 sub generate_letter {
5394 my ($self, $template, %options) = @_;
5396 warn "Template $template does not exist" && return
5397 unless $conf->exists($template) || $options{'template_text'};
5399 my $template_source = $options{'template_text'}
5400 ? [ $options{'template_text'} ]
5401 : [ map "$_\n", $conf->config($template) ];
5403 my $letter_template = new Text::Template
5405 SOURCE => $template_source,
5406 DELIMITERS => [ '[@--', '--@]' ],
5408 or die "can't create new Text::Template object: Text::Template::ERROR";
5410 $letter_template->compile()
5411 or die "can't compile template: Text::Template::ERROR";
5413 my %letter_data = map { $_ => $self->$_ } $self->fields;
5414 $letter_data{payinfo} = $self->mask_payinfo;
5416 #my $paydate = $self->paydate || '2037-12-31';
5417 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5419 my $payby = $self->payby;
5420 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5421 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5423 #credit cards expire at the end of the month/year of their exp date
5424 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5425 $letter_data{payby} = 'credit card';
5426 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5427 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5429 }elsif ($payby eq 'COMP') {
5430 $letter_data{payby} = 'complimentary account';
5432 $letter_data{payby} = 'current method';
5434 $letter_data{expdate} = $expire_time;
5436 for (keys %{$options{extra_fields}}){
5437 $letter_data{$_} = $options{extra_fields}->{$_};
5440 unless(exists($letter_data{returnaddress})){
5441 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5442 $self->agent_template)
5444 if ( length($retadd) ) {
5445 $letter_data{returnaddress} = $retadd;
5446 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5447 $letter_data{returnaddress} =
5448 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5452 ( $conf->config('company_name', $self->agentnum),
5453 $conf->config('company_address', $self->agentnum),
5457 $letter_data{returnaddress} = '~';
5461 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5463 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5465 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5467 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5471 ) or die "can't open temp file: $!\n";
5472 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5473 or die "can't write temp file: $!\n";
5475 $letter_data{'logo_file'} = $lh->filename;
5477 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5481 ) or die "can't open temp file: $!\n";
5483 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5485 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5486 return ($1, $letter_data{'logo_file'});
5490 =item print_ps TEMPLATE
5492 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5498 my($file, $lfile) = $self->generate_letter(@_);
5499 my $ps = FS::Misc::generate_ps($file);
5500 unlink($file.'.tex');
5506 =item print TEMPLATE
5508 Prints the filled in template.
5510 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5514 sub queueable_print {
5517 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5518 or die "invalid customer number: " . $opt{custnum};
5520 my $error = $self->print( { 'template' => $opt{template} } );
5521 die $error if $error;
5525 my ($self, $template) = (shift, shift);
5527 [ $self->print_ps($template) ],
5528 'agentnum' => $self->agentnum,
5532 #these three subs should just go away once agent stuff is all config overrides
5534 sub agent_template {
5536 $self->_agent_plandata('agent_templatename');
5539 sub agent_invoice_from {
5541 $self->_agent_plandata('agent_invoice_from');
5544 sub _agent_plandata {
5545 my( $self, $option ) = @_;
5547 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5548 #agent-specific Conf
5550 use FS::part_event::Condition;
5552 my $agentnum = $self->agentnum;
5554 my $regexp = regexp_sql();
5556 my $part_event_option =
5558 'select' => 'part_event_option.*',
5559 'table' => 'part_event_option',
5561 LEFT JOIN part_event USING ( eventpart )
5562 LEFT JOIN part_event_option AS peo_agentnum
5563 ON ( part_event.eventpart = peo_agentnum.eventpart
5564 AND peo_agentnum.optionname = 'agentnum'
5565 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5567 LEFT JOIN part_event_condition
5568 ON ( part_event.eventpart = part_event_condition.eventpart
5569 AND part_event_condition.conditionname = 'cust_bill_age'
5571 LEFT JOIN part_event_condition_option
5572 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5573 AND part_event_condition_option.optionname = 'age'
5576 #'hashref' => { 'optionname' => $option },
5577 #'hashref' => { 'part_event_option.optionname' => $option },
5579 " WHERE part_event_option.optionname = ". dbh->quote($option).
5580 " AND action = 'cust_bill_send_agent' ".
5581 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5582 " AND peo_agentnum.optionname = 'agentnum' ".
5583 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5585 CASE WHEN part_event_condition_option.optionname IS NULL
5587 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5589 , part_event.weight".
5593 unless ( $part_event_option ) {
5594 return $self->agent->invoice_template || ''
5595 if $option eq 'agent_templatename';
5599 $part_event_option->optionvalue;
5603 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5605 Subroutine (not a method), designed to be called from the queue.
5607 Takes a list of options and values.
5609 Pulls up the customer record via the custnum option and calls bill_and_collect.
5614 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5616 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5617 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5619 #without this errors don't get rolled back
5620 $args{'fatal'} = 1; # runs from job queue, will be caught
5622 $cust_main->bill_and_collect( %args );
5625 sub process_bill_and_collect {
5627 my $param = thaw(decode_base64(shift));
5628 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5629 or die "custnum '$param->{custnum}' not found!\n";
5630 $param->{'job'} = $job;
5631 $param->{'fatal'} = 1; # runs from job queue, will be caught
5632 $param->{'retry'} = 1;
5634 $cust_main->bill_and_collect( %$param );
5637 #starting to take quite a while for big dbs
5638 # (JRNL: journaled so it only happens once per database)
5639 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5640 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5641 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5642 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5643 # JRNL leading/trailing spaces in first, last, company
5644 # - otaker upgrade? journal and call it good? (double check to make sure
5645 # we're not still setting otaker here)
5647 #only going to get worse with new location stuff...
5649 sub _upgrade_data { #class method
5650 my ($class, %opts) = @_;
5653 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5656 #this seems to be the only expensive one.. why does it take so long?
5657 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5659 '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';
5660 FS::upgrade_journal->set_done('cust_main__signupdate');
5663 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5665 # fix yyyy-m-dd formatted paydates
5666 if ( driver_name =~ /^mysql/i ) {
5668 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5669 } else { # the SQL standard
5671 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5673 FS::upgrade_journal->set_done('cust_main__paydate');
5676 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5678 push @statements, #fix the weird BILL with a cc# in payinfo problem
5680 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5682 FS::upgrade_journal->set_done('cust_main__payinfo');
5687 foreach my $sql ( @statements ) {
5688 my $sth = dbh->prepare($sql) or die dbh->errstr;
5689 $sth->execute or die $sth->errstr;
5690 #warn ( (time - $t). " seconds\n" );
5694 local($ignore_expired_card) = 1;
5695 local($ignore_banned_card) = 1;
5696 local($skip_fuzzyfiles) = 1;
5697 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5699 FS::cust_main::Location->_upgrade_data(%opts);
5701 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5703 foreach my $cust_main ( qsearch({
5704 'table' => 'cust_main',
5706 'extra_sql' => 'WHERE '.
5708 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5709 qw( first last company )
5712 my $error = $cust_main->replace;
5713 die $error if $error;
5716 FS::upgrade_journal->set_done('cust_main__trimspaces');
5720 $class->_upgrade_otaker(%opts);
5730 The delete method should possibly take an FS::cust_main object reference
5731 instead of a scalar customer number.
5733 Bill and collect options should probably be passed as references instead of a
5736 There should probably be a configuration file with a list of allowed credit
5739 No multiple currency support (probably a larger project than just this module).
5741 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5743 Birthdates rely on negative epoch values.
5745 The payby for card/check batches is broken. With mixed batching, bad
5748 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5752 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5753 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5754 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.