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;
79 # 1 is mostly method/subroutine entry and options
80 # 2 traces progress of some operations
81 # 3 is even more information including possibly sensitive data
83 $me = '[FS::cust_main]';
86 $ignore_expired_card = 0;
87 $ignore_banned_card = 0;
91 @encrypted_fields = ('payinfo', 'paycvv');
92 sub nohistory_fields { ('payinfo', 'paycvv'); }
94 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
96 #ask FS::UID to run this stuff for us later
97 #$FS::UID::callback{'FS::cust_main'} = sub {
98 install_callback FS::UID sub {
100 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
101 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
106 my ( $hashref, $cache ) = @_;
107 if ( exists $hashref->{'pkgnum'} ) {
108 #@{ $self->{'_pkgnum'} } = ();
109 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110 $self->{'_pkgnum'} = $subcache;
111 #push @{ $self->{'_pkgnum'} },
112 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
118 FS::cust_main - Object methods for cust_main records
124 $record = new FS::cust_main \%hash;
125 $record = new FS::cust_main { 'column' => 'value' };
127 $error = $record->insert;
129 $error = $new_record->replace($old_record);
131 $error = $record->delete;
133 $error = $record->check;
135 @cust_pkg = $record->all_pkgs;
137 @cust_pkg = $record->ncancelled_pkgs;
139 @cust_pkg = $record->suspended_pkgs;
141 $error = $record->bill;
142 $error = $record->bill %options;
143 $error = $record->bill 'time' => $time;
145 $error = $record->collect;
146 $error = $record->collect %options;
147 $error = $record->collect 'invoice_time' => $time,
152 An FS::cust_main object represents a customer. FS::cust_main inherits from
153 FS::Record. The following fields are currently supported:
159 Primary key (assigned automatically for new customers)
163 Agent (see L<FS::agent>)
167 Advertising source (see L<FS::part_referral>)
179 Cocial security number (optional)
203 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
207 Payment Information (See L<FS::payinfo_Mixin> for data format)
211 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
215 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
219 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
223 Start date month (maestro/solo cards only)
227 Start date year (maestro/solo cards only)
231 Issue number (maestro/solo cards only)
235 Name on card or billing name
239 IP address from which payment information was received
243 Tax exempt, empty or `Y'
247 Order taker (see L<FS::access_user>)
253 =item referral_custnum
255 Referring customer number
259 Enable individual CDR spooling, empty or `Y'
263 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
267 Discourage individual CDR printing, empty or `Y'
271 Allow self-service editing of ticket subjects, empty or 'Y'
273 =item calling_list_exempt
275 Do not call, empty or 'Y'
277 =item invoice_ship_address
279 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
289 Creates a new customer. To add the customer to the database, see L<"insert">.
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to. You can ask the object for a copy with the I<hash> method.
296 sub table { 'cust_main'; }
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
300 Adds this customer to the database. If there is an error, returns the error,
301 otherwise returns false.
303 Usually the customer's location will not yet exist in the database, and
304 the C<bill_location> and C<ship_location> pseudo-fields must be set to
305 uninserted L<FS::cust_location> objects. These will be inserted and linked
306 (in both directions) to the new customer record. If they're references
307 to the same object, they will become the same location.
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back. Passing an empty
312 hash reference is equivalent to not supplying this parameter. There should be
313 a better explanation of this, but until then, here's an example:
316 tie %hash, 'Tie::RefHash'; #this part is important
318 $cust_pkg => [ $svc_acct ],
321 $cust_main->insert( \%hash );
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">). Errors return as
325 expected and rollback the entire transaction; it is not necessary to call
326 check_invoicing_list first. The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct. Here's an example:
330 $cust_main->insert( {}, [ $email, 'POST' ] );
332 Currently available options are: I<depend_jobnum>, I<noexport>,
333 I<tax_exemption> and I<prospectnum>.
335 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
336 on the supplied jobnum (they will not run until the specific job completes).
337 This can be used to defer provisioning until some action completes (such
338 as running the customer's credit card successfully).
340 The I<noexport> option is deprecated. If I<noexport> is set true, no
341 provisioning jobs (exports) are scheduled. (You can schedule them later with
342 the B<reexport> method.)
344 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
345 of tax names and exemption numbers. FS::cust_main_exemption records will be
346 created and inserted.
348 If I<prospectnum> is set, moves contacts and locations from that prospect.
354 my $cust_pkgs = @_ ? shift : {};
355 my $invoicing_list = @_ ? shift : '';
357 warn "$me insert called with options ".
358 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
361 local $SIG{HUP} = 'IGNORE';
362 local $SIG{INT} = 'IGNORE';
363 local $SIG{QUIT} = 'IGNORE';
364 local $SIG{TERM} = 'IGNORE';
365 local $SIG{TSTP} = 'IGNORE';
366 local $SIG{PIPE} = 'IGNORE';
368 my $oldAutoCommit = $FS::UID::AutoCommit;
369 local $FS::UID::AutoCommit = 0;
372 my $prepay_identifier = '';
373 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
375 if ( $self->payby eq 'PREPAY' ) {
377 $self->payby('BILL');
378 $prepay_identifier = $self->payinfo;
381 warn " looking up prepaid card $prepay_identifier\n"
384 my $error = $self->get_prepay( $prepay_identifier,
385 'amount_ref' => \$amount,
386 'seconds_ref' => \$seconds,
387 'upbytes_ref' => \$upbytes,
388 'downbytes_ref' => \$downbytes,
389 'totalbytes_ref' => \$totalbytes,
392 $dbh->rollback if $oldAutoCommit;
393 #return "error applying prepaid card (transaction rolled back): $error";
397 $payby = 'PREP' if $amount;
399 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
402 $self->payby('BILL');
403 $amount = $self->paid;
408 foreach my $l (qw(bill_location ship_location)) {
410 my $loc = delete $self->hashref->{$l} or return "$l not set";
412 if ( !$loc->locationnum ) {
413 # warn the location that we're going to insert it with no custnum
414 $loc->set(custnum_pending => 1);
415 warn " inserting $l\n"
417 my $error = $loc->insert;
419 $dbh->rollback if $oldAutoCommit;
420 my $label = $l eq 'ship_location' ? 'service' : 'billing';
421 return "$error (in $label location)";
424 } elsif ( $loc->prospectnum ) {
426 $loc->prospectnum('');
427 $loc->set(custnum_pending => 1);
428 my $error = $loc->replace;
430 $dbh->rollback if $oldAutoCommit;
431 my $label = $l eq 'ship_location' ? 'service' : 'billing';
432 return "$error (moving $label location)";
435 } elsif ( ($loc->custnum || 0) > 0 ) {
436 # then it somehow belongs to another customer--shouldn't happen
437 $dbh->rollback if $oldAutoCommit;
438 return "$l belongs to customer ".$loc->custnum;
440 # else it already belongs to this customer
441 # (happens when ship_location is identical to bill_location)
443 $self->set($l.'num', $loc->locationnum);
445 if ( $self->get($l.'num') eq '' ) {
446 $dbh->rollback if $oldAutoCommit;
451 warn " inserting $self\n"
454 $self->signupdate(time) unless $self->signupdate;
456 $self->auto_agent_custid()
457 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
459 my $error = $self->check_payinfo_cardtype
460 || $self->SUPER::insert;
462 $dbh->rollback if $oldAutoCommit;
463 #return "inserting cust_main record (transaction rolled back): $error";
467 # now set cust_location.custnum
468 foreach my $l (qw(bill_location ship_location)) {
469 warn " setting $l.custnum\n"
472 unless ( $loc->custnum ) {
473 $loc->set(custnum => $self->custnum);
474 $error ||= $loc->replace;
478 $dbh->rollback if $oldAutoCommit;
479 return "error setting $l custnum: $error";
483 warn " setting invoicing list\n"
486 if ( $invoicing_list ) {
487 $error = $self->check_invoicing_list( $invoicing_list );
489 $dbh->rollback if $oldAutoCommit;
490 #return "checking invoicing_list (transaction rolled back): $error";
493 $self->invoicing_list( $invoicing_list );
496 warn " setting customer tags\n"
499 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
500 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
501 'custnum' => $self->custnum };
502 my $error = $cust_tag->insert;
504 $dbh->rollback if $oldAutoCommit;
509 my $prospectnum = delete $options{'prospectnum'};
510 if ( $prospectnum ) {
512 warn " moving contacts and locations from prospect $prospectnum\n"
516 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
517 unless ( $prospect_main ) {
518 $dbh->rollback if $oldAutoCommit;
519 return "Unknown prospectnum $prospectnum";
521 $prospect_main->custnum($self->custnum);
522 $prospect_main->disabled('Y');
523 my $error = $prospect_main->replace;
525 $dbh->rollback if $oldAutoCommit;
529 my @contact = $prospect_main->contact;
530 my @cust_location = $prospect_main->cust_location;
531 my @qual = $prospect_main->qual;
533 foreach my $r ( @contact, @cust_location, @qual ) {
535 $r->custnum($self->custnum);
536 my $error = $r->replace;
538 $dbh->rollback if $oldAutoCommit;
545 # validate card (needs custnum already set)
546 if ( $self->payby =~ /^(CARD|DCRD)$/
547 && $conf->exists('business-onlinepayment-verification') ) {
548 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
550 $dbh->rollback if $oldAutoCommit;
555 warn " setting contacts\n"
558 if ( my $contact = delete $options{'contact'} ) {
560 foreach my $c ( @$contact ) {
561 $c->custnum($self->custnum);
562 my $error = $c->insert;
564 $dbh->rollback if $oldAutoCommit;
570 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
572 my $error = $self->process_o2m( 'table' => 'contact',
573 'fields' => FS::contact->cgi_contact_fields,
574 'params' => $contact_params,
577 $dbh->rollback if $oldAutoCommit;
582 warn " setting cust_main_exemption\n"
585 my $tax_exemption = delete $options{'tax_exemption'};
586 if ( $tax_exemption ) {
588 $tax_exemption = { map { $_ => '' } @$tax_exemption }
589 if ref($tax_exemption) eq 'ARRAY';
591 foreach my $taxname ( keys %$tax_exemption ) {
592 my $cust_main_exemption = new FS::cust_main_exemption {
593 'custnum' => $self->custnum,
594 'taxname' => $taxname,
595 'exempt_number' => $tax_exemption->{$taxname},
597 my $error = $cust_main_exemption->insert;
599 $dbh->rollback if $oldAutoCommit;
600 return "inserting cust_main_exemption (transaction rolled back): $error";
605 warn " ordering packages\n"
608 $error = $self->order_pkgs( $cust_pkgs,
610 'seconds_ref' => \$seconds,
611 'upbytes_ref' => \$upbytes,
612 'downbytes_ref' => \$downbytes,
613 'totalbytes_ref' => \$totalbytes,
616 $dbh->rollback if $oldAutoCommit;
621 $dbh->rollback if $oldAutoCommit;
622 return "No svc_acct record to apply pre-paid time";
624 if ( $upbytes || $downbytes || $totalbytes ) {
625 $dbh->rollback if $oldAutoCommit;
626 return "No svc_acct record to apply pre-paid data";
630 warn " inserting initial $payby payment of $amount\n"
632 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
634 $dbh->rollback if $oldAutoCommit;
635 return "inserting payment (transaction rolled back): $error";
639 unless ( $import || $skip_fuzzyfiles ) {
640 warn " queueing fuzzyfiles update\n"
642 $error = $self->queue_fuzzyfiles_update;
644 $dbh->rollback if $oldAutoCommit;
645 return "updating fuzzy search cache: $error";
649 # FS::geocode_Mixin::after_insert or something?
650 if ( $conf->config('tax_district_method') and !$import ) {
651 # if anything non-empty, try to look it up
652 my $queue = new FS::queue {
653 'job' => 'FS::geocode_Mixin::process_district_update',
654 'custnum' => $self->custnum,
656 my $error = $queue->insert( ref($self), $self->custnum );
658 $dbh->rollback if $oldAutoCommit;
659 return "queueing tax district update: $error";
664 warn " exporting\n" if $DEBUG > 1;
666 my $export_args = $options{'export_args'} || [];
669 map qsearch( 'part_export', {exportnum=>$_} ),
670 $conf->config('cust_main-exports'); #, $agentnum
672 foreach my $part_export ( @part_export ) {
673 my $error = $part_export->export_insert($self, @$export_args);
675 $dbh->rollback if $oldAutoCommit;
676 return "exporting to ". $part_export->exporttype.
677 " (transaction rolled back): $error";
681 #foreach my $depend_jobnum ( @$depend_jobnums ) {
682 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
684 # foreach my $jobnum ( @jobnums ) {
685 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
686 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
688 # my $error = $queue->depend_insert($depend_jobnum);
690 # $dbh->rollback if $oldAutoCommit;
691 # return "error queuing job dependancy: $error";
698 #if ( exists $options{'jobnums'} ) {
699 # push @{ $options{'jobnums'} }, @jobnums;
702 warn " insert complete; committing transaction\n"
705 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
710 use File::CounterFile;
711 sub auto_agent_custid {
714 my $format = $conf->config('cust_main-auto_agent_custid');
716 if ( $format eq '1YMMXXXXXXXX' ) {
718 my $counter = new File::CounterFile 'cust_main.agent_custid';
721 my $ym = 100000000000 + time2str('%y%m00000000', time);
722 if ( $ym > $counter->value ) {
723 $counter->{'value'} = $agent_custid = $ym;
724 $counter->{'updated'} = 1;
726 $agent_custid = $counter->inc;
732 die "Unknown cust_main-auto_agent_custid format: $format";
735 $self->agent_custid($agent_custid);
739 =item PACKAGE METHODS
741 Documentation on customer package methods has been moved to
742 L<FS::cust_main::Packages>.
744 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
746 Recharges this (existing) customer with the specified prepaid card (see
747 L<FS::prepay_credit>), specified either by I<identifier> or as an
748 FS::prepay_credit object. If there is an error, returns the error, otherwise
751 Optionally, five scalar references can be passed as well. They will have their
752 values filled in with the amount, number of seconds, and number of upload,
753 download, and total bytes applied by this prepaid card.
757 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
758 #the only place that uses these args
759 sub recharge_prepay {
760 my( $self, $prepay_credit, $amountref, $secondsref,
761 $upbytesref, $downbytesref, $totalbytesref ) = @_;
763 local $SIG{HUP} = 'IGNORE';
764 local $SIG{INT} = 'IGNORE';
765 local $SIG{QUIT} = 'IGNORE';
766 local $SIG{TERM} = 'IGNORE';
767 local $SIG{TSTP} = 'IGNORE';
768 local $SIG{PIPE} = 'IGNORE';
770 my $oldAutoCommit = $FS::UID::AutoCommit;
771 local $FS::UID::AutoCommit = 0;
774 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
776 my $error = $self->get_prepay( $prepay_credit,
777 'amount_ref' => \$amount,
778 'seconds_ref' => \$seconds,
779 'upbytes_ref' => \$upbytes,
780 'downbytes_ref' => \$downbytes,
781 'totalbytes_ref' => \$totalbytes,
783 || $self->increment_seconds($seconds)
784 || $self->increment_upbytes($upbytes)
785 || $self->increment_downbytes($downbytes)
786 || $self->increment_totalbytes($totalbytes)
787 || $self->insert_cust_pay_prepay( $amount,
789 ? $prepay_credit->identifier
794 $dbh->rollback if $oldAutoCommit;
798 if ( defined($amountref) ) { $$amountref = $amount; }
799 if ( defined($secondsref) ) { $$secondsref = $seconds; }
800 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
801 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
802 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
804 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
809 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
811 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
812 specified either by I<identifier> or as an FS::prepay_credit object.
814 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
815 incremented by the values of the prepaid card.
817 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
818 check or set this customer's I<agentnum>.
820 If there is an error, returns the error, otherwise returns false.
826 my( $self, $prepay_credit, %opt ) = @_;
828 local $SIG{HUP} = 'IGNORE';
829 local $SIG{INT} = 'IGNORE';
830 local $SIG{QUIT} = 'IGNORE';
831 local $SIG{TERM} = 'IGNORE';
832 local $SIG{TSTP} = 'IGNORE';
833 local $SIG{PIPE} = 'IGNORE';
835 my $oldAutoCommit = $FS::UID::AutoCommit;
836 local $FS::UID::AutoCommit = 0;
839 unless ( ref($prepay_credit) ) {
841 my $identifier = $prepay_credit;
843 $prepay_credit = qsearchs(
845 { 'identifier' => $identifier },
850 unless ( $prepay_credit ) {
851 $dbh->rollback if $oldAutoCommit;
852 return "Invalid prepaid card: ". $identifier;
857 if ( $prepay_credit->agentnum ) {
858 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
859 $dbh->rollback if $oldAutoCommit;
860 return "prepaid card not valid for agent ". $self->agentnum;
862 $self->agentnum($prepay_credit->agentnum);
865 my $error = $prepay_credit->delete;
867 $dbh->rollback if $oldAutoCommit;
868 return "removing prepay_credit (transaction rolled back): $error";
871 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
872 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
874 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
879 =item increment_upbytes SECONDS
881 Updates this customer's single or primary account (see L<FS::svc_acct>) by
882 the specified number of upbytes. If there is an error, returns the error,
883 otherwise returns false.
887 sub increment_upbytes {
888 _increment_column( shift, 'upbytes', @_);
891 =item increment_downbytes SECONDS
893 Updates this customer's single or primary account (see L<FS::svc_acct>) by
894 the specified number of downbytes. If there is an error, returns the error,
895 otherwise returns false.
899 sub increment_downbytes {
900 _increment_column( shift, 'downbytes', @_);
903 =item increment_totalbytes SECONDS
905 Updates this customer's single or primary account (see L<FS::svc_acct>) by
906 the specified number of totalbytes. If there is an error, returns the error,
907 otherwise returns false.
911 sub increment_totalbytes {
912 _increment_column( shift, 'totalbytes', @_);
915 =item increment_seconds SECONDS
917 Updates this customer's single or primary account (see L<FS::svc_acct>) by
918 the specified number of seconds. If there is an error, returns the error,
919 otherwise returns false.
923 sub increment_seconds {
924 _increment_column( shift, 'seconds', @_);
927 =item _increment_column AMOUNT
929 Updates this customer's single or primary account (see L<FS::svc_acct>) by
930 the specified number of seconds or bytes. If there is an error, returns
931 the error, otherwise returns false.
935 sub _increment_column {
936 my( $self, $column, $amount ) = @_;
937 warn "$me increment_column called: $column, $amount\n"
940 return '' unless $amount;
942 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
943 $self->ncancelled_pkgs;
946 return 'No packages with primary or single services found'.
947 ' to apply pre-paid time';
948 } elsif ( scalar(@cust_pkg) > 1 ) {
949 #maybe have a way to specify the package/account?
950 return 'Multiple packages found to apply pre-paid time';
953 my $cust_pkg = $cust_pkg[0];
954 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
958 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
961 return 'No account found to apply pre-paid time';
962 } elsif ( scalar(@cust_svc) > 1 ) {
963 return 'Multiple accounts found to apply pre-paid time';
966 my $svc_acct = $cust_svc[0]->svc_x;
967 warn " found service svcnum ". $svc_acct->pkgnum.
968 ' ('. $svc_acct->email. ")\n"
971 $column = "increment_$column";
972 $svc_acct->$column($amount);
976 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
978 Inserts a prepayment in the specified amount for this customer. An optional
979 second argument can specify the prepayment identifier for tracking purposes.
980 If there is an error, returns the error, otherwise returns false.
984 sub insert_cust_pay_prepay {
985 shift->insert_cust_pay('PREP', @_);
988 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
990 Inserts a cash payment in the specified amount for this customer. An optional
991 second argument can specify the payment identifier for tracking purposes.
992 If there is an error, returns the error, otherwise returns false.
996 sub insert_cust_pay_cash {
997 shift->insert_cust_pay('CASH', @_);
1000 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1002 Inserts a Western Union payment in the specified amount for this customer. An
1003 optional second argument can specify the prepayment identifier for tracking
1004 purposes. If there is an error, returns the error, otherwise returns false.
1008 sub insert_cust_pay_west {
1009 shift->insert_cust_pay('WEST', @_);
1012 sub insert_cust_pay {
1013 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1014 my $payinfo = scalar(@_) ? shift : '';
1016 my $cust_pay = new FS::cust_pay {
1017 'custnum' => $self->custnum,
1018 'paid' => sprintf('%.2f', $amount),
1019 #'_date' => #date the prepaid card was purchased???
1021 'payinfo' => $payinfo,
1029 This method is deprecated. See the I<depend_jobnum> option to the insert and
1030 order_pkgs methods for a better way to defer provisioning.
1032 Re-schedules all exports by calling the B<reexport> method of all associated
1033 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1034 otherwise returns false.
1041 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1042 "use the depend_jobnum option to insert or order_pkgs to delay export";
1044 local $SIG{HUP} = 'IGNORE';
1045 local $SIG{INT} = 'IGNORE';
1046 local $SIG{QUIT} = 'IGNORE';
1047 local $SIG{TERM} = 'IGNORE';
1048 local $SIG{TSTP} = 'IGNORE';
1049 local $SIG{PIPE} = 'IGNORE';
1051 my $oldAutoCommit = $FS::UID::AutoCommit;
1052 local $FS::UID::AutoCommit = 0;
1055 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1056 my $error = $cust_pkg->reexport;
1058 $dbh->rollback if $oldAutoCommit;
1063 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1068 =item delete [ OPTION => VALUE ... ]
1070 This deletes the customer. If there is an error, returns the error, otherwise
1073 This will completely remove all traces of the customer record. This is not
1074 what you want when a customer cancels service; for that, cancel all of the
1075 customer's packages (see L</cancel>).
1077 If the customer has any uncancelled packages, you need to pass a new (valid)
1078 customer number for those packages to be transferred to, as the "new_customer"
1079 option. Cancelled packages will be deleted. Did I mention that this is NOT
1080 what you want when a customer cancels service and that you really should be
1081 looking at L<FS::cust_pkg/cancel>?
1083 You can't delete a customer with invoices (see L<FS::cust_bill>),
1084 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1085 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1086 set the "delete_financials" option to a true value.
1091 my( $self, %opt ) = @_;
1093 local $SIG{HUP} = 'IGNORE';
1094 local $SIG{INT} = 'IGNORE';
1095 local $SIG{QUIT} = 'IGNORE';
1096 local $SIG{TERM} = 'IGNORE';
1097 local $SIG{TSTP} = 'IGNORE';
1098 local $SIG{PIPE} = 'IGNORE';
1100 my $oldAutoCommit = $FS::UID::AutoCommit;
1101 local $FS::UID::AutoCommit = 0;
1104 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1105 $dbh->rollback if $oldAutoCommit;
1106 return "Can't delete a master agent customer";
1109 #use FS::access_user
1110 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1111 $dbh->rollback if $oldAutoCommit;
1112 return "Can't delete a master employee customer";
1115 tie my %financial_tables, 'Tie::IxHash',
1116 'cust_bill' => 'invoices',
1117 'cust_statement' => 'statements',
1118 'cust_credit' => 'credits',
1119 'cust_pay' => 'payments',
1120 'cust_refund' => 'refunds',
1123 foreach my $table ( keys %financial_tables ) {
1125 my @records = $self->$table();
1127 if ( @records && ! $opt{'delete_financials'} ) {
1128 $dbh->rollback if $oldAutoCommit;
1129 return "Can't delete a customer with ". $financial_tables{$table};
1132 foreach my $record ( @records ) {
1133 my $error = $record->delete;
1135 $dbh->rollback if $oldAutoCommit;
1136 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1142 my @cust_pkg = $self->ncancelled_pkgs;
1144 my $new_custnum = $opt{'new_custnum'};
1145 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1146 $dbh->rollback if $oldAutoCommit;
1147 return "Invalid new customer number: $new_custnum";
1149 foreach my $cust_pkg ( @cust_pkg ) {
1150 my %hash = $cust_pkg->hash;
1151 $hash{'custnum'} = $new_custnum;
1152 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1153 my $error = $new_cust_pkg->replace($cust_pkg,
1154 options => { $cust_pkg->options },
1157 $dbh->rollback if $oldAutoCommit;
1162 my @cancelled_cust_pkg = $self->all_pkgs;
1163 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1164 my $error = $cust_pkg->delete;
1166 $dbh->rollback if $oldAutoCommit;
1171 #cust_tax_adjustment in financials?
1172 #cust_pay_pending? ouch
1174 foreach my $table (qw(
1175 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1176 cust_location cust_main_note cust_tax_adjustment
1177 cust_pay_void cust_pay_batch queue cust_tax_exempt
1179 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1180 my $error = $record->delete;
1182 $dbh->rollback if $oldAutoCommit;
1188 my $sth = $dbh->prepare(
1189 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1191 my $errstr = $dbh->errstr;
1192 $dbh->rollback if $oldAutoCommit;
1195 $sth->execute($self->custnum) or do {
1196 my $errstr = $sth->errstr;
1197 $dbh->rollback if $oldAutoCommit;
1203 my $ticket_dbh = '';
1204 if ($conf->config('ticket_system') eq 'RT_Internal') {
1206 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1207 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1208 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1209 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1212 if ( $ticket_dbh ) {
1214 my $ticket_sth = $ticket_dbh->prepare(
1215 'DELETE FROM Links WHERE Target = ?'
1217 my $errstr = $ticket_dbh->errstr;
1218 $dbh->rollback if $oldAutoCommit;
1221 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1223 my $errstr = $ticket_sth->errstr;
1224 $dbh->rollback if $oldAutoCommit;
1228 #check and see if the customer is the only link on the ticket, and
1229 #if so, set the ticket to deleted status in RT?
1230 #maybe someday, for now this will at least fix tickets not displaying
1234 #delete the customer record
1236 my $error = $self->SUPER::delete;
1238 $dbh->rollback if $oldAutoCommit;
1242 # cust_main exports!
1244 #my $export_args = $options{'export_args'} || [];
1247 map qsearch( 'part_export', {exportnum=>$_} ),
1248 $conf->config('cust_main-exports'); #, $agentnum
1250 foreach my $part_export ( @part_export ) {
1251 my $error = $part_export->export_delete( $self ); #, @$export_args);
1253 $dbh->rollback if $oldAutoCommit;
1254 return "exporting to ". $part_export->exporttype.
1255 " (transaction rolled back): $error";
1259 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1264 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1266 This merges this customer into the provided new custnum, and then deletes the
1267 customer. If there is an error, returns the error, otherwise returns false.
1269 The source customer's name, company name, phone numbers, agent,
1270 referring customer, customer class, advertising source, order taker, and
1271 billing information (except balance) are discarded.
1273 All packages are moved to the target customer. Packages with package locations
1274 are preserved. Packages without package locations are moved to a new package
1275 location with the source customer's service/shipping address.
1277 All invoices, statements, payments, credits and refunds are moved to the target
1278 customer. The source customer's balance is added to the target customer.
1280 All notes, attachments, tickets and customer tags are moved to the target
1283 Change history is not currently moved.
1288 my( $self, $new_custnum, %opt ) = @_;
1290 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1292 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1293 or return "Invalid new customer number: $new_custnum";
1295 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1296 if $self->agentnum != $new_cust_main->agentnum
1297 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1299 local $SIG{HUP} = 'IGNORE';
1300 local $SIG{INT} = 'IGNORE';
1301 local $SIG{QUIT} = 'IGNORE';
1302 local $SIG{TERM} = 'IGNORE';
1303 local $SIG{TSTP} = 'IGNORE';
1304 local $SIG{PIPE} = 'IGNORE';
1306 my $oldAutoCommit = $FS::UID::AutoCommit;
1307 local $FS::UID::AutoCommit = 0;
1310 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1311 $dbh->rollback if $oldAutoCommit;
1312 return "Can't merge a master agent customer";
1315 #use FS::access_user
1316 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1317 $dbh->rollback if $oldAutoCommit;
1318 return "Can't merge a master employee customer";
1321 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1322 'status' => { op=>'!=', value=>'done' },
1326 $dbh->rollback if $oldAutoCommit;
1327 return "Can't merge a customer with pending payments";
1330 tie my %financial_tables, 'Tie::IxHash',
1331 'cust_bill' => 'invoices',
1332 'cust_bill_void' => 'voided invoices',
1333 'cust_statement' => 'statements',
1334 'cust_credit' => 'credits',
1335 'cust_credit_void' => 'voided credits',
1336 'cust_pay' => 'payments',
1337 'cust_pay_void' => 'voided payments',
1338 'cust_refund' => 'refunds',
1341 foreach my $table ( keys %financial_tables ) {
1343 my @records = $self->$table();
1345 foreach my $record ( @records ) {
1346 $record->custnum($new_custnum);
1347 my $error = $record->replace;
1349 $dbh->rollback if $oldAutoCommit;
1350 return "Error merging ". $financial_tables{$table}. ": $error\n";
1356 my $name = $self->ship_name; #?
1358 my $locationnum = '';
1359 foreach my $cust_pkg ( $self->all_pkgs ) {
1360 $cust_pkg->custnum($new_custnum);
1362 unless ( $cust_pkg->locationnum ) {
1363 unless ( $locationnum ) {
1364 my $cust_location = new FS::cust_location {
1365 $self->location_hash,
1366 'custnum' => $new_custnum,
1368 my $error = $cust_location->insert;
1370 $dbh->rollback if $oldAutoCommit;
1373 $locationnum = $cust_location->locationnum;
1375 $cust_pkg->locationnum($locationnum);
1378 my $error = $cust_pkg->replace;
1380 $dbh->rollback if $oldAutoCommit;
1384 # add customer (ship) name to svc_phone.phone_name if blank
1385 my @cust_svc = $cust_pkg->cust_svc;
1386 foreach my $cust_svc (@cust_svc) {
1387 my($label, $value, $svcdb) = $cust_svc->label;
1388 next unless $svcdb eq 'svc_phone';
1389 my $svc_phone = $cust_svc->svc_x;
1390 next if $svc_phone->phone_name;
1391 $svc_phone->phone_name($name);
1392 my $error = $svc_phone->replace;
1394 $dbh->rollback if $oldAutoCommit;
1402 # cust_tax_exempt (texas tax exemptions)
1403 # cust_recon (some sort of not-well understood thing for OnPac)
1405 #these are moved over
1406 foreach my $table (qw(
1407 cust_tag cust_location contact cust_attachment cust_main_note
1408 cust_tax_adjustment cust_pay_batch queue
1410 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1411 $record->custnum($new_custnum);
1412 my $error = $record->replace;
1414 $dbh->rollback if $oldAutoCommit;
1420 #these aren't preserved
1421 foreach my $table (qw(
1422 cust_main_exemption cust_main_invoice
1424 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1425 my $error = $record->delete;
1427 $dbh->rollback if $oldAutoCommit;
1434 my $sth = $dbh->prepare(
1435 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1437 my $errstr = $dbh->errstr;
1438 $dbh->rollback if $oldAutoCommit;
1441 $sth->execute($new_custnum, $self->custnum) or do {
1442 my $errstr = $sth->errstr;
1443 $dbh->rollback if $oldAutoCommit;
1449 my $ticket_dbh = '';
1450 if ($conf->config('ticket_system') eq 'RT_Internal') {
1452 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1453 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1454 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1455 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1458 if ( $ticket_dbh ) {
1460 my $ticket_sth = $ticket_dbh->prepare(
1461 'UPDATE Links SET Target = ? WHERE Target = ?'
1463 my $errstr = $ticket_dbh->errstr;
1464 $dbh->rollback if $oldAutoCommit;
1467 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1468 'freeside://freeside/cust_main/'.$self->custnum)
1470 my $errstr = $ticket_sth->errstr;
1471 $dbh->rollback if $oldAutoCommit;
1477 #delete the customer record
1479 my $error = $self->delete;
1481 $dbh->rollback if $oldAutoCommit;
1485 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1490 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1492 Replaces the OLD_RECORD with this one in the database. If there is an error,
1493 returns the error, otherwise returns false.
1495 To change the customer's address, set the pseudo-fields C<bill_location> and
1496 C<ship_location>. The address will still only change if at least one of the
1497 address fields differs from the existing values.
1499 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1500 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1501 expected and rollback the entire transaction; it is not necessary to call
1502 check_invoicing_list first. Here's an example:
1504 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1506 Currently available options are: I<tax_exemption>.
1508 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1509 of tax names and exemption numbers. FS::cust_main_exemption records will be
1510 deleted and inserted as appropriate.
1517 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1519 : $self->replace_old;
1523 warn "$me replace called\n"
1526 my $curuser = $FS::CurrentUser::CurrentUser;
1527 if ( $self->payby eq 'COMP'
1528 && $self->payby ne $old->payby
1529 && ! $curuser->access_right('Complimentary customer')
1532 return "You are not permitted to create complimentary accounts.";
1535 local($ignore_expired_card) = 1
1536 if $old->payby =~ /^(CARD|DCRD)$/
1537 && $self->payby =~ /^(CARD|DCRD)$/
1538 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1540 local($ignore_banned_card) = 1
1541 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1542 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1543 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1545 if ( $self->payby =~ /^(CARD|DCRD)$/
1546 && $old->payinfo ne $self->payinfo
1547 && $old->paymask ne $self->paymask )
1549 my $error = $self->check_payinfo_cardtype;
1550 return $error if $error;
1552 if ( $conf->exists('business-onlinepayment-verification') ) {
1553 #need to standardize paydate for this, false laziness with check
1555 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1556 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1557 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1558 ( $m, $y ) = ( $2, "19$1" );
1559 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1560 ( $m, $y ) = ( $3, "20$2" );
1562 return "Illegal expiration date: ". $self->paydate;
1564 $m = sprintf('%02d',$m);
1565 $self->paydate("$y-$m-01");
1567 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
1568 return $error if $error;
1572 return "Invoicing locale is required"
1575 && $conf->exists('cust_main-require_locale');
1577 local $SIG{HUP} = 'IGNORE';
1578 local $SIG{INT} = 'IGNORE';
1579 local $SIG{QUIT} = 'IGNORE';
1580 local $SIG{TERM} = 'IGNORE';
1581 local $SIG{TSTP} = 'IGNORE';
1582 local $SIG{PIPE} = 'IGNORE';
1584 my $oldAutoCommit = $FS::UID::AutoCommit;
1585 local $FS::UID::AutoCommit = 0;
1588 for my $l (qw(bill_location ship_location)) {
1589 my $old_loc = $old->$l;
1590 my $new_loc = $self->$l;
1592 # find the existing location if there is one
1593 $new_loc->set('custnum' => $self->custnum);
1594 my $error = $new_loc->find_or_insert;
1596 $dbh->rollback if $oldAutoCommit;
1599 $self->set($l.'num', $new_loc->locationnum);
1602 # replace the customer record
1603 my $error = $self->SUPER::replace($old);
1606 $dbh->rollback if $oldAutoCommit;
1610 # now move packages to the new service location
1611 $self->set('ship_location', ''); #flush cache
1612 if ( $old->ship_locationnum and # should only be null during upgrade...
1613 $old->ship_locationnum != $self->ship_locationnum ) {
1614 $error = $old->ship_location->move_to($self->ship_location);
1616 $dbh->rollback if $oldAutoCommit;
1620 # don't move packages based on the billing location, but
1621 # disable it if it's no longer in use
1622 if ( $old->bill_locationnum and
1623 $old->bill_locationnum != $self->bill_locationnum ) {
1624 $error = $old->bill_location->disable_if_unused;
1626 $dbh->rollback if $oldAutoCommit;
1631 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1632 my $invoicing_list = shift @param;
1633 $error = $self->check_invoicing_list( $invoicing_list );
1635 $dbh->rollback if $oldAutoCommit;
1638 $self->invoicing_list( $invoicing_list );
1641 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1643 #this could be more efficient than deleting and re-inserting, if it matters
1644 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1645 my $error = $cust_tag->delete;
1647 $dbh->rollback if $oldAutoCommit;
1651 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1652 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1653 'custnum' => $self->custnum };
1654 my $error = $cust_tag->insert;
1656 $dbh->rollback if $oldAutoCommit;
1663 my %options = @param;
1665 my $tax_exemption = delete $options{'tax_exemption'};
1666 if ( $tax_exemption ) {
1668 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1669 if ref($tax_exemption) eq 'ARRAY';
1671 my %cust_main_exemption =
1672 map { $_->taxname => $_ }
1673 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1675 foreach my $taxname ( keys %$tax_exemption ) {
1677 if ( $cust_main_exemption{$taxname} &&
1678 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1681 delete $cust_main_exemption{$taxname};
1685 my $cust_main_exemption = new FS::cust_main_exemption {
1686 'custnum' => $self->custnum,
1687 'taxname' => $taxname,
1688 'exempt_number' => $tax_exemption->{$taxname},
1690 my $error = $cust_main_exemption->insert;
1692 $dbh->rollback if $oldAutoCommit;
1693 return "inserting cust_main_exemption (transaction rolled back): $error";
1697 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1698 my $error = $cust_main_exemption->delete;
1700 $dbh->rollback if $oldAutoCommit;
1701 return "deleting cust_main_exemption (transaction rolled back): $error";
1707 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1708 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1709 && $self->get('payinfo') !~ /^99\d{14}$/
1711 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1716 # card/check/lec info has changed, want to retry realtime_ invoice events
1717 my $error = $self->retry_realtime;
1719 $dbh->rollback if $oldAutoCommit;
1724 unless ( $import || $skip_fuzzyfiles ) {
1725 $error = $self->queue_fuzzyfiles_update;
1727 $dbh->rollback if $oldAutoCommit;
1728 return "updating fuzzy search cache: $error";
1732 # tax district update in cust_location
1734 # cust_main exports!
1736 my $export_args = $options{'export_args'} || [];
1739 map qsearch( 'part_export', {exportnum=>$_} ),
1740 $conf->config('cust_main-exports'); #, $agentnum
1742 foreach my $part_export ( @part_export ) {
1743 my $error = $part_export->export_replace( $self, $old, @$export_args);
1745 $dbh->rollback if $oldAutoCommit;
1746 return "exporting to ". $part_export->exporttype.
1747 " (transaction rolled back): $error";
1751 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1756 =item queue_fuzzyfiles_update
1758 Used by insert & replace to update the fuzzy search cache
1762 use FS::cust_main::Search;
1763 sub queue_fuzzyfiles_update {
1766 local $SIG{HUP} = 'IGNORE';
1767 local $SIG{INT} = 'IGNORE';
1768 local $SIG{QUIT} = 'IGNORE';
1769 local $SIG{TERM} = 'IGNORE';
1770 local $SIG{TSTP} = 'IGNORE';
1771 local $SIG{PIPE} = 'IGNORE';
1773 my $oldAutoCommit = $FS::UID::AutoCommit;
1774 local $FS::UID::AutoCommit = 0;
1777 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1778 my $queue = new FS::queue {
1779 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1781 my @args = "cust_main.$field", $self->get($field);
1782 my $error = $queue->insert( @args );
1784 $dbh->rollback if $oldAutoCommit;
1785 return "queueing job (transaction rolled back): $error";
1789 my @locations = $self->bill_location;
1790 push @locations, $self->ship_location if $self->has_ship_address;
1791 foreach my $location (@locations) {
1792 my $queue = new FS::queue {
1793 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1795 my @args = 'cust_location.address1', $location->address1;
1796 my $error = $queue->insert( @args );
1798 $dbh->rollback if $oldAutoCommit;
1799 return "queueing job (transaction rolled back): $error";
1803 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1810 Checks all fields to make sure this is a valid customer record. If there is
1811 an error, returns the error, otherwise returns false. Called by the insert
1812 and replace methods.
1819 warn "$me check BEFORE: \n". $self->_dump
1823 $self->ut_numbern('custnum')
1824 || $self->ut_number('agentnum')
1825 || $self->ut_textn('agent_custid')
1826 || $self->ut_number('refnum')
1827 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1828 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1829 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1830 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1831 || $self->ut_textn('custbatch')
1832 || $self->ut_name('last')
1833 || $self->ut_name('first')
1834 || $self->ut_snumbern('signupdate')
1835 || $self->ut_snumbern('birthdate')
1836 || $self->ut_namen('spouse_last')
1837 || $self->ut_namen('spouse_first')
1838 || $self->ut_snumbern('spouse_birthdate')
1839 || $self->ut_snumbern('anniversary_date')
1840 || $self->ut_textn('company')
1841 || $self->ut_textn('ship_company')
1842 || $self->ut_anything('comments')
1843 || $self->ut_numbern('referral_custnum')
1844 || $self->ut_textn('stateid')
1845 || $self->ut_textn('stateid_state')
1846 || $self->ut_textn('invoice_terms')
1847 || $self->ut_floatn('cdr_termination_percentage')
1848 || $self->ut_floatn('credit_limit')
1849 || $self->ut_numbern('billday')
1850 || $self->ut_numbern('prorate_day')
1851 || $self->ut_flag('edit_subject')
1852 || $self->ut_flag('calling_list_exempt')
1853 || $self->ut_flag('invoice_noemail')
1854 || $self->ut_flag('message_noemail')
1855 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1856 || $self->ut_flag('invoice_ship_address')
1859 foreach (qw(company ship_company)) {
1860 my $company = $self->get($_);
1861 $company =~ s/^\s+//;
1862 $company =~ s/\s+$//;
1863 $company =~ s/\s+/ /g;
1864 $self->set($_, $company);
1867 #barf. need message catalogs. i18n. etc.
1868 $error .= "Please select an advertising source."
1869 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1870 return $error if $error;
1872 return "Unknown agent"
1873 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1875 return "Unknown refnum"
1876 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1878 return "Unknown referring custnum: ". $self->referral_custnum
1879 unless ! $self->referral_custnum
1880 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1882 if ( $self->ss eq '' ) {
1887 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1888 or return "Illegal social security number: ". $self->ss;
1889 $self->ss("$1-$2-$3");
1892 #turn off invoice_ship_address if ship & bill are the same
1893 if ($self->bill_locationnum eq $self->ship_locationnum) {
1894 $self->invoice_ship_address('');
1897 # cust_main_county verification now handled by cust_location check
1900 $self->ut_phonen('daytime', $self->country)
1901 || $self->ut_phonen('night', $self->country)
1902 || $self->ut_phonen('fax', $self->country)
1903 || $self->ut_phonen('mobile', $self->country)
1905 return $error if $error;
1907 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1909 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1912 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1914 : FS::Msgcat::_gettext('daytime');
1915 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1917 : FS::Msgcat::_gettext('night');
1919 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1921 : FS::Msgcat::_gettext('mobile');
1923 return "$daytime_label, $night_label or $mobile_label is required"
1927 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1928 # or return "Illegal payby: ". $self->payby;
1930 FS::payby->can_payby($self->table, $self->payby)
1931 or return "Illegal payby: ". $self->payby;
1933 $error = $self->ut_numbern('paystart_month')
1934 || $self->ut_numbern('paystart_year')
1935 || $self->ut_numbern('payissue')
1936 || $self->ut_textn('paytype')
1938 return $error if $error;
1940 if ( $self->payip eq '' ) {
1943 $error = $self->ut_ip('payip');
1944 return $error if $error;
1947 # If it is encrypted and the private key is not availaible then we can't
1948 # check the credit card.
1949 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1951 # Need some kind of global flag to accept invalid cards, for testing
1953 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1955 my $payinfo = $self->payinfo;
1956 $payinfo =~ s/\D//g;
1957 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1958 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1960 $self->payinfo($payinfo);
1962 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1964 return gettext('unknown_card_type')
1965 if $self->payinfo !~ /^99\d{14}$/ #token
1966 && cardtype($self->payinfo) eq "Unknown";
1968 unless ( $ignore_banned_card ) {
1969 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1971 if ( $ban->bantype eq 'warn' ) {
1972 #or others depending on value of $ban->reason ?
1973 return '_duplicate_card'.
1974 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1975 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1976 ' (ban# '. $ban->bannum. ')'
1977 unless $self->override_ban_warn;
1979 return 'Banned credit card: banned on '.
1980 time2str('%a %h %o at %r', $ban->_date).
1981 ' by '. $ban->otaker.
1982 ' (ban# '. $ban->bannum. ')';
1987 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1988 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1989 $self->paycvv =~ /^(\d{4})$/
1990 or return "CVV2 (CID) for American Express cards is four digits.";
1993 $self->paycvv =~ /^(\d{3})$/
1994 or return "CVV2 (CVC2/CID) is three digits.";
2001 my $cardtype = cardtype($payinfo);
2002 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2004 return "Start date or issue number is required for $cardtype cards"
2005 unless $self->paystart_month && $self->paystart_year or $self->payissue;
2007 return "Start month must be between 1 and 12"
2008 if $self->paystart_month
2009 and $self->paystart_month < 1 || $self->paystart_month > 12;
2011 return "Start year must be 1990 or later"
2012 if $self->paystart_year
2013 and $self->paystart_year < 1990;
2015 return "Issue number must be beween 1 and 99"
2017 and $self->payissue < 1 || $self->payissue > 99;
2020 $self->paystart_month('');
2021 $self->paystart_year('');
2022 $self->payissue('');
2025 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2027 my $payinfo = $self->payinfo;
2028 $payinfo =~ s/[^\d\@\.]//g;
2029 if ( $conf->config('echeck-country') eq 'CA' ) {
2030 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2031 or return 'invalid echeck account@branch.bank';
2032 $payinfo = "$1\@$2.$3";
2033 } elsif ( $conf->config('echeck-country') eq 'US' ) {
2034 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2035 $payinfo = "$1\@$2";
2037 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2038 $payinfo = "$1\@$2";
2040 $self->payinfo($payinfo);
2043 unless ( $ignore_banned_card ) {
2044 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2046 if ( $ban->bantype eq 'warn' ) {
2047 #or others depending on value of $ban->reason ?
2048 return '_duplicate_ach' unless $self->override_ban_warn;
2050 return 'Banned ACH account: banned on '.
2051 time2str('%a %h %o at %r', $ban->_date).
2052 ' by '. $ban->otaker.
2053 ' (ban# '. $ban->bannum. ')';
2058 } elsif ( $self->payby eq 'LECB' ) {
2060 my $payinfo = $self->payinfo;
2061 $payinfo =~ s/\D//g;
2062 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2064 $self->payinfo($payinfo);
2067 } elsif ( $self->payby eq 'BILL' ) {
2069 $error = $self->ut_textn('payinfo');
2070 return "Illegal P.O. number: ". $self->payinfo if $error;
2073 } elsif ( $self->payby eq 'COMP' ) {
2075 my $curuser = $FS::CurrentUser::CurrentUser;
2076 if ( ! $self->custnum
2077 && ! $curuser->access_right('Complimentary customer')
2080 return "You are not permitted to create complimentary accounts."
2083 $error = $self->ut_textn('payinfo');
2084 return "Illegal comp account issuer: ". $self->payinfo if $error;
2087 } elsif ( $self->payby eq 'PREPAY' ) {
2089 my $payinfo = $self->payinfo;
2090 $payinfo =~ s/\W//g; #anything else would just confuse things
2091 $self->payinfo($payinfo);
2092 $error = $self->ut_alpha('payinfo');
2093 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2094 return "Unknown prepayment identifier"
2095 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2100 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2101 return "Expiration date required"
2102 # shouldn't payinfo_check do this?
2103 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2107 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2108 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2109 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2110 ( $m, $y ) = ( $2, "19$1" );
2111 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2112 ( $m, $y ) = ( $3, "20$2" );
2114 return "Illegal expiration date: ". $self->paydate;
2116 $m = sprintf('%02d',$m);
2117 $self->paydate("$y-$m-01");
2118 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2119 return gettext('expired_card')
2121 && !$ignore_expired_card
2122 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2125 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2126 ( ! $conf->exists('require_cardname')
2127 || $self->payby !~ /^(CARD|DCRD)$/ )
2129 $self->payname( $self->first. " ". $self->getfield('last') );
2132 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2133 $self->payname =~ /^([\w \,\.\-\']*)$/
2134 or return gettext('illegal_name'). " payname: ". $self->payname;
2137 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2138 or return gettext('illegal_name'). " payname: ". $self->payname;
2144 return "Please select an invoicing locale"
2147 && $conf->exists('cust_main-require_locale');
2149 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2150 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2154 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2156 warn "$me check AFTER: \n". $self->_dump
2159 $self->SUPER::check;
2162 sub check_payinfo_cardtype {
2165 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
2167 my $payinfo = $self->payinfo;
2168 $payinfo =~ s/\D//g;
2170 return '' if $payinfo =~ /^99\d{14}$/; #token
2172 my %bop_card_types = map { $_=>1 } values %{ card_types() };
2173 my $cardtype = cardtype($payinfo);
2175 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
2183 Additional checks for replace only.
2188 my ($new,$old) = @_;
2189 #preserve old value if global config is set
2190 if ($old && $conf->exists('invoice-ship_address')) {
2191 $new->invoice_ship_address($old->invoice_ship_address);
2198 Returns a list of fields which have ship_ duplicates.
2203 qw( last first company
2205 address1 address2 city county state zip country
2207 daytime night fax mobile
2211 =item has_ship_address
2213 Returns true if this customer record has a separate shipping address.
2217 sub has_ship_address {
2219 $self->bill_locationnum != $self->ship_locationnum;
2224 Returns a list of key/value pairs, with the following keys: address1,
2225 adddress2, city, county, state, zip, country, district, and geocode. The
2226 shipping address is used if present.
2232 $self->ship_location->location_hash;
2237 Returns all locations (see L<FS::cust_location>) for this customer.
2243 qsearch('cust_location', { 'custnum' => $self->custnum,
2244 'prospectnum' => '' } );
2249 Returns all contacts (see L<FS::contact>) for this customer.
2253 #already used :/ sub contact {
2256 qsearch('contact', { 'custnum' => $self->custnum } );
2261 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2262 and L<FS::cust_pkg>) for this customer, except those on hold.
2264 Returns a list: an empty list on success or a list of errors.
2270 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2275 Unsuspends all suspended packages in the on-hold state (those without setup
2276 dates) for this customer.
2282 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2287 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2289 Returns a list: an empty list on success or a list of errors.
2295 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2298 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2300 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2301 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2302 of a list of pkgparts; the hashref has the following keys:
2306 =item pkgparts - listref of pkgparts
2308 =item (other options are passed to the suspend method)
2313 Returns a list: an empty list on success or a list of errors.
2317 sub suspend_if_pkgpart {
2319 my (@pkgparts, %opt);
2320 if (ref($_[0]) eq 'HASH'){
2321 @pkgparts = @{$_[0]{pkgparts}};
2326 grep { $_->suspend(%opt) }
2327 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2328 $self->unsuspended_pkgs;
2331 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2333 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2334 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2335 instead of a list of pkgparts; the hashref has the following keys:
2339 =item pkgparts - listref of pkgparts
2341 =item (other options are passed to the suspend method)
2345 Returns a list: an empty list on success or a list of errors.
2349 sub suspend_unless_pkgpart {
2351 my (@pkgparts, %opt);
2352 if (ref($_[0]) eq 'HASH'){
2353 @pkgparts = @{$_[0]{pkgparts}};
2358 grep { $_->suspend(%opt) }
2359 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2360 $self->unsuspended_pkgs;
2363 =item cancel [ OPTION => VALUE ... ]
2365 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2367 Available options are:
2371 =item quiet - can be set true to supress email cancellation notices.
2373 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
2375 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2377 =item nobill - can be set true to skip billing if it might otherwise be done.
2381 Always returns a list: an empty list on success or a list of errors.
2385 # nb that dates are not specified as valid options to this method
2388 my( $self, %opt ) = @_;
2390 my $oldAutoCommit = $FS::UID::AutoCommit;
2391 local $FS::UID::AutoCommit = 0;
2393 warn "$me cancel called on customer ". $self->custnum. " with options ".
2394 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2397 return ( 'access denied' )
2398 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2400 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2402 #should try decryption (we might have the private key)
2403 # and if not maybe queue a job for the server that does?
2404 return ( "Can't (yet) ban encrypted credit cards" )
2405 if $self->is_encrypted($self->payinfo);
2407 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2408 my $error = $ban->insert;
2410 dbh->rollback if $oldAutoCommit;
2416 my @pkgs = $self->ncancelled_pkgs;
2418 # bill all packages first, so we don't lose usage, service counts for
2419 # bulk billing, etc.
2420 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2422 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2424 # we should return an error and exit in this case, yes?
2425 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2426 dbh->rollback if $oldAutoCommit;
2427 return ( "Error billing during cancellation: $error" );
2432 # now cancel all services, the same way we would for individual packages
2433 my @cust_svc = map { $_->cust_svc } @pkgs;
2434 my @sorted_cust_svc =
2436 sort { $a->[1] <=> $b->[1] }
2437 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
2440 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2443 foreach my $cust_svc (@sorted_cust_svc) {
2444 my $part_svc = $cust_svc->part_svc;
2445 next if ( defined($part_svc) and $part_svc->preserve );
2446 my $error = $cust_svc->cancel; # immediate cancel, no date option
2447 push @errors, $error if $error;
2450 # then we won't get to the point of canceling packages
2451 dbh->rollback if $oldAutoCommit;
2455 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2456 $self->custnum. "\n"
2459 @errors = grep { $_ } map { $_->cancel(%opt) } @pkgs;
2461 dbh->rollback if $oldAutoCommit;
2468 sub _banned_pay_hashref {
2479 'payby' => $payby2ban{$self->payby},
2480 'payinfo' => $self->payinfo,
2481 #don't ever *search* on reason! #'reason' =>
2485 sub _new_banned_pay_hashref {
2487 my $hr = $self->_banned_pay_hashref;
2488 $hr->{payinfo} = md5_base64($hr->{payinfo});
2494 Returns all notes (see L<FS::cust_main_note>) for this customer.
2499 my($self,$orderby_classnum) = (shift,shift);
2500 my $orderby = "sticky DESC, _date DESC";
2501 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2502 qsearch( 'cust_main_note',
2503 { 'custnum' => $self->custnum },
2505 "ORDER BY $orderby",
2511 Returns the agent (see L<FS::agent>) for this customer.
2517 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2522 Returns the agent name (see L<FS::agent>) for this customer.
2528 $self->agent->agent;
2533 Returns any tags associated with this customer, as FS::cust_tag objects,
2534 or an empty list if there are no tags.
2540 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2545 Returns any tags associated with this customer, as FS::part_tag objects,
2546 or an empty list if there are no tags.
2552 map $_->part_tag, $self->cust_tag;
2558 Returns the customer class, as an FS::cust_class object, or the empty string
2559 if there is no customer class.
2565 if ( $self->classnum ) {
2566 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2574 Returns the customer category name, or the empty string if there is no customer
2581 my $cust_class = $self->cust_class;
2583 ? $cust_class->categoryname
2589 Returns the customer class name, or the empty string if there is no customer
2596 my $cust_class = $self->cust_class;
2598 ? $cust_class->classname
2602 =item BILLING METHODS
2604 Documentation on billing methods has been moved to
2605 L<FS::cust_main::Billing>.
2607 =item REALTIME BILLING METHODS
2609 Documentation on realtime billing methods has been moved to
2610 L<FS::cust_main::Billing_Realtime>.
2614 Removes the I<paycvv> field from the database directly.
2616 If there is an error, returns the error, otherwise returns false.
2622 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2623 or return dbh->errstr;
2624 $sth->execute($self->custnum)
2625 or return $sth->errstr;
2630 =item batch_card OPTION => VALUE...
2632 Adds a payment for this invoice to the pending credit card batch (see
2633 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2634 runs the payment using a realtime gateway.
2636 Options may include:
2638 B<amount>: the amount to be paid; defaults to the customer's balance minus
2639 any payments in transit.
2641 B<payby>: the payment method; defaults to cust_main.payby
2643 B<realtime>: runs this as a realtime payment instead of adding it to a
2646 B<invnum>: sets cust_pay_batch.invnum.
2648 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2649 the billing address for the payment; defaults to the customer's billing
2652 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2653 date, and name; defaults to those fields in cust_main.
2658 my ($self, %options) = @_;
2661 if (exists($options{amount})) {
2662 $amount = $options{amount};
2664 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2667 warn(sprintf("Customer balance %.2f - in transit amount %.2f is <= 0.\n",
2669 $self->in_transit_payments
2674 my $invnum = delete $options{invnum};
2675 my $payby = $options{payby} || $self->payby; #still dubious
2677 if ($options{'realtime'}) {
2678 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2684 my $oldAutoCommit = $FS::UID::AutoCommit;
2685 local $FS::UID::AutoCommit = 0;
2688 #this needs to handle mysql as well as Pg, like svc_acct.pm
2689 #(make it into a common function if folks need to do batching with mysql)
2690 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2691 or return "Cannot lock pay_batch: " . $dbh->errstr;
2695 'payby' => FS::payby->payby2payment($payby),
2697 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2699 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2701 unless ( $pay_batch ) {
2702 $pay_batch = new FS::pay_batch \%pay_batch;
2703 my $error = $pay_batch->insert;
2705 $dbh->rollback if $oldAutoCommit;
2706 die "error creating new batch: $error\n";
2710 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2711 'batchnum' => $pay_batch->batchnum,
2712 'custnum' => $self->custnum,
2715 foreach (qw( address1 address2 city state zip country latitude longitude
2716 payby payinfo paydate payname ))
2718 $options{$_} = '' unless exists($options{$_});
2721 my $loc = $self->bill_location;
2723 my $cust_pay_batch = new FS::cust_pay_batch ( {
2724 'batchnum' => $pay_batch->batchnum,
2725 'invnum' => $invnum || 0, # is there a better value?
2726 # this field should be
2728 # cust_bill_pay_batch now
2729 'custnum' => $self->custnum,
2730 'last' => $self->getfield('last'),
2731 'first' => $self->getfield('first'),
2732 'address1' => $options{address1} || $loc->address1,
2733 'address2' => $options{address2} || $loc->address2,
2734 'city' => $options{city} || $loc->city,
2735 'state' => $options{state} || $loc->state,
2736 'zip' => $options{zip} || $loc->zip,
2737 'country' => $options{country} || $loc->country,
2738 'payby' => $options{payby} || $self->payby,
2739 'payinfo' => $options{payinfo} || $self->payinfo,
2740 'exp' => $options{paydate} || $self->paydate,
2741 'payname' => $options{payname} || $self->payname,
2742 'amount' => $amount, # consolidating
2745 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2746 if $old_cust_pay_batch;
2749 if ($old_cust_pay_batch) {
2750 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2752 $error = $cust_pay_batch->insert;
2756 $dbh->rollback if $oldAutoCommit;
2760 my $unapplied = $self->total_unapplied_credits
2761 + $self->total_unapplied_payments
2762 + $self->in_transit_payments;
2763 foreach my $cust_bill ($self->open_cust_bill) {
2764 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2765 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2766 'invnum' => $cust_bill->invnum,
2767 'paybatchnum' => $cust_pay_batch->paybatchnum,
2768 'amount' => $cust_bill->owed,
2771 if ($unapplied >= $cust_bill_pay_batch->amount){
2772 $unapplied -= $cust_bill_pay_batch->amount;
2775 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2776 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2778 $error = $cust_bill_pay_batch->insert;
2780 $dbh->rollback if $oldAutoCommit;
2785 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2791 Returns the total owed for this customer on all invoices
2792 (see L<FS::cust_bill/owed>).
2798 $self->total_owed_date(2145859200); #12/31/2037
2801 =item total_owed_date TIME
2803 Returns the total owed for this customer on all invoices with date earlier than
2804 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2805 see L<Time::Local> and L<Date::Parse> for conversion functions.
2809 sub total_owed_date {
2813 my $custnum = $self->custnum;
2815 my $owed_sql = FS::cust_bill->owed_sql;
2818 SELECT SUM($owed_sql) FROM cust_bill
2819 WHERE custnum = $custnum
2823 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2827 =item total_owed_pkgnum PKGNUM
2829 Returns the total owed on all invoices for this customer's specific package
2830 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2834 sub total_owed_pkgnum {
2835 my( $self, $pkgnum ) = @_;
2836 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2839 =item total_owed_date_pkgnum TIME PKGNUM
2841 Returns the total owed for this customer's specific package when using
2842 experimental package balances on all invoices with date earlier than
2843 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2844 see L<Time::Local> and L<Date::Parse> for conversion functions.
2848 sub total_owed_date_pkgnum {
2849 my( $self, $time, $pkgnum ) = @_;
2852 foreach my $cust_bill (
2853 grep { $_->_date <= $time }
2854 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2856 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2858 sprintf( "%.2f", $total_bill );
2864 Returns the total amount of all payments.
2871 $total += $_->paid foreach $self->cust_pay;
2872 sprintf( "%.2f", $total );
2875 =item total_unapplied_credits
2877 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2878 customer. See L<FS::cust_credit/credited>.
2880 =item total_credited
2882 Old name for total_unapplied_credits. Don't use.
2886 sub total_credited {
2887 #carp "total_credited deprecated, use total_unapplied_credits";
2888 shift->total_unapplied_credits(@_);
2891 sub total_unapplied_credits {
2894 my $custnum = $self->custnum;
2896 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2899 SELECT SUM($unapplied_sql) FROM cust_credit
2900 WHERE custnum = $custnum
2903 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2907 =item total_unapplied_credits_pkgnum PKGNUM
2909 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2910 customer. See L<FS::cust_credit/credited>.
2914 sub total_unapplied_credits_pkgnum {
2915 my( $self, $pkgnum ) = @_;
2916 my $total_credit = 0;
2917 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2918 sprintf( "%.2f", $total_credit );
2922 =item total_unapplied_payments
2924 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2925 See L<FS::cust_pay/unapplied>.
2929 sub total_unapplied_payments {
2932 my $custnum = $self->custnum;
2934 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2937 SELECT SUM($unapplied_sql) FROM cust_pay
2938 WHERE custnum = $custnum
2941 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2945 =item total_unapplied_payments_pkgnum PKGNUM
2947 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2948 specific package when using experimental package balances. See
2949 L<FS::cust_pay/unapplied>.
2953 sub total_unapplied_payments_pkgnum {
2954 my( $self, $pkgnum ) = @_;
2955 my $total_unapplied = 0;
2956 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2957 sprintf( "%.2f", $total_unapplied );
2961 =item total_unapplied_refunds
2963 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2964 customer. See L<FS::cust_refund/unapplied>.
2968 sub total_unapplied_refunds {
2970 my $custnum = $self->custnum;
2972 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2975 SELECT SUM($unapplied_sql) FROM cust_refund
2976 WHERE custnum = $custnum
2979 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2985 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2986 total_unapplied_credits minus total_unapplied_payments).
2992 $self->balance_date_range;
2995 =item balance_date TIME
2997 Returns the balance for this customer, only considering invoices with date
2998 earlier than TIME (total_owed_date minus total_credited minus
2999 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3000 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3007 $self->balance_date_range(shift);
3010 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3012 Returns the balance for this customer, optionally considering invoices with
3013 date earlier than START_TIME, and not later than END_TIME
3014 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3016 Times are specified as SQL fragments or numeric
3017 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
3018 L<Date::Parse> for conversion functions. The empty string can be passed
3019 to disable that time constraint completely.
3021 Accepts the same options as L<balance_date_sql>:
3025 =item unapplied_date
3027 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)
3031 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
3032 time will be ignored. Note that START_TIME and END_TIME only limit the date
3033 range for invoices and I<unapplied> payments, credits, and refunds.
3039 sub balance_date_range {
3041 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3042 ') FROM cust_main WHERE custnum='. $self->custnum;
3043 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
3046 =item balance_pkgnum PKGNUM
3048 Returns the balance for this customer's specific package when using
3049 experimental package balances (total_owed plus total_unrefunded, minus
3050 total_unapplied_credits minus total_unapplied_payments)
3054 sub balance_pkgnum {
3055 my( $self, $pkgnum ) = @_;
3058 $self->total_owed_pkgnum($pkgnum)
3059 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3060 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
3061 - $self->total_unapplied_credits_pkgnum($pkgnum)
3062 - $self->total_unapplied_payments_pkgnum($pkgnum)
3066 =item in_transit_payments
3068 Returns the total of requests for payments for this customer pending in
3069 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3073 sub in_transit_payments {
3075 my $in_transit_payments = 0;
3076 foreach my $pay_batch ( qsearch('pay_batch', {
3079 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3080 'batchnum' => $pay_batch->batchnum,
3081 'custnum' => $self->custnum,
3084 $in_transit_payments += $cust_pay_batch->amount;
3087 sprintf( "%.2f", $in_transit_payments );
3092 Returns a hash of useful information for making a payment.
3102 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3103 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3104 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3108 For credit card transactions:
3120 For electronic check transactions:
3135 $return{balance} = $self->balance;
3137 $return{payname} = $self->payname
3138 || ( $self->first. ' '. $self->get('last') );
3140 $return{$_} = $self->bill_location->$_
3141 for qw(address1 address2 city state zip);
3143 $return{payby} = $self->payby;
3144 $return{stateid_state} = $self->stateid_state;
3146 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3147 $return{card_type} = cardtype($self->payinfo);
3148 $return{payinfo} = $self->paymask;
3150 @return{'month', 'year'} = $self->paydate_monthyear;
3154 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3155 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3156 $return{payinfo1} = $payinfo1;
3157 $return{payinfo2} = $payinfo2;
3158 $return{paytype} = $self->paytype;
3159 $return{paystate} = $self->paystate;
3163 #doubleclick protection
3165 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3171 =item paydate_monthyear
3173 Returns a two-element list consisting of the month and year of this customer's
3174 paydate (credit card expiration date for CARD customers)
3178 sub paydate_monthyear {
3180 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3182 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3191 Returns the exact time in seconds corresponding to the payment method
3192 expiration date. For CARD/DCRD customers this is the end of the month;
3193 for others (COMP is the only other payby that uses paydate) it's the start.
3194 Returns 0 if the paydate is empty or set to the far future.
3200 my ($month, $year) = $self->paydate_monthyear;
3201 return 0 if !$year or $year >= 2037;
3202 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3204 if ( $month == 13 ) {
3208 return timelocal(0,0,0,1,$month-1,$year) - 1;
3211 return timelocal(0,0,0,1,$month-1,$year);
3215 =item paydate_epoch_sql
3217 Class method. Returns an SQL expression to obtain the payment expiration date
3218 as a number of seconds.
3222 # Special expiration date behavior for non-CARD/DCRD customers has been
3223 # carefully preserved. Do we really use that?
3224 sub paydate_epoch_sql {
3226 my $table = shift || 'cust_main';
3227 my ($case1, $case2);
3228 if ( driver_name eq 'Pg' ) {
3229 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3230 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3232 elsif ( lc(driver_name) eq 'mysql' ) {
3233 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3234 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3237 return "CASE WHEN $table.payby IN('CARD','DCRD')
3243 =item tax_exemption TAXNAME
3248 my( $self, $taxname ) = @_;
3250 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3251 'taxname' => $taxname,
3256 =item cust_main_exemption
3260 sub cust_main_exemption {
3262 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3265 =item invoicing_list [ ARRAYREF ]
3267 If an arguement is given, sets these email addresses as invoice recipients
3268 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3269 (except as warnings), so use check_invoicing_list first.
3271 Returns a list of email addresses (with svcnum entries expanded).
3273 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3274 check it without disturbing anything by passing nothing.
3276 This interface may change in the future.
3280 sub invoicing_list {
3281 my( $self, $arrayref ) = @_;
3284 my @cust_main_invoice;
3285 if ( $self->custnum ) {
3286 @cust_main_invoice =
3287 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3289 @cust_main_invoice = ();
3291 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3292 #warn $cust_main_invoice->destnum;
3293 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3294 #warn $cust_main_invoice->destnum;
3295 my $error = $cust_main_invoice->delete;
3296 warn $error if $error;
3299 if ( $self->custnum ) {
3300 @cust_main_invoice =
3301 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3303 @cust_main_invoice = ();
3305 my %seen = map { $_->address => 1 } @cust_main_invoice;
3306 foreach my $address ( @{$arrayref} ) {
3307 next if exists $seen{$address} && $seen{$address};
3308 $seen{$address} = 1;
3309 my $cust_main_invoice = new FS::cust_main_invoice ( {
3310 'custnum' => $self->custnum,
3313 my $error = $cust_main_invoice->insert;
3314 warn $error if $error;
3318 if ( $self->custnum ) {
3320 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3327 =item check_invoicing_list ARRAYREF
3329 Checks these arguements as valid input for the invoicing_list method. If there
3330 is an error, returns the error, otherwise returns false.
3334 sub check_invoicing_list {
3335 my( $self, $arrayref ) = @_;
3337 foreach my $address ( @$arrayref ) {
3339 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3340 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3343 my $cust_main_invoice = new FS::cust_main_invoice ( {
3344 'custnum' => $self->custnum,
3347 my $error = $self->custnum
3348 ? $cust_main_invoice->check
3349 : $cust_main_invoice->checkdest
3351 return $error if $error;
3355 return "Email address required"
3356 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3357 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3362 =item set_default_invoicing_list
3364 Sets the invoicing list to all accounts associated with this customer,
3365 overwriting any previous invoicing list.
3369 sub set_default_invoicing_list {
3371 $self->invoicing_list($self->all_emails);
3376 Returns the email addresses of all accounts provisioned for this customer.
3383 foreach my $cust_pkg ( $self->all_pkgs ) {
3384 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3386 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3387 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3389 $list{$_}=1 foreach map { $_->email } @svc_acct;
3394 =item invoicing_list_addpost
3396 Adds postal invoicing to this customer. If this customer is already configured
3397 to receive postal invoices, does nothing.
3401 sub invoicing_list_addpost {
3403 return if grep { $_ eq 'POST' } $self->invoicing_list;
3404 my @invoicing_list = $self->invoicing_list;
3405 push @invoicing_list, 'POST';
3406 $self->invoicing_list(\@invoicing_list);
3409 =item invoicing_list_emailonly
3411 Returns the list of email invoice recipients (invoicing_list without non-email
3412 destinations such as POST and FAX).
3416 sub invoicing_list_emailonly {
3418 warn "$me invoicing_list_emailonly called"
3420 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3423 =item invoicing_list_emailonly_scalar
3425 Returns the list of email invoice recipients (invoicing_list without non-email
3426 destinations such as POST and FAX) as a comma-separated scalar.
3430 sub invoicing_list_emailonly_scalar {
3432 warn "$me invoicing_list_emailonly_scalar called"
3434 join(', ', $self->invoicing_list_emailonly);
3437 =item contact_list [ CLASSNUM, ... ]
3439 Returns a list of contacts (L<FS::contact> objects) for the customer. If
3440 a list of contact classnums is given, returns only contacts in those
3441 classes. If '0' is given, also returns contacts with no class.
3443 If no arguments are given, returns all contacts for the customer.
3451 select => 'contact.*',
3452 extra_sql => ' WHERE contact.custnum = '.$self->custnum,
3459 push @orwhere, 'contact.classnum is null';
3460 } elsif ( /^\d+$/ ) {
3461 push @classnums, $_;
3463 die "bad classnum argument '$_'";
3468 push @orwhere, 'contact.classnum IN ('.join(',', @classnums).')';
3471 $search->{extra_sql} .= ' AND (' .
3472 join(' OR ', map "( $_ )", @orwhere) .
3479 =item contact_list_email [ CLASSNUM, ... ]
3481 Same as L</contact_list>, but returns email destinations instead of contact
3482 objects. Also accepts 'invoice' as an argument, in which case this will also
3483 return the invoice email address if any.
3487 sub contact_list_email {
3495 push @classnums, $_;
3499 # if the only argument passed was 'invoice' then no classnums are
3500 # intended, so skip this.
3502 my @contacts = $self->contact_list(@classnums);
3503 foreach my $contact (@contacts) {
3504 foreach my $contact_email ($contact->contact_email) {
3505 # unlike on 4.x, we have a separate list of invoice email
3507 # make sure they're not redundant with contact emails
3508 my $dest = $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3509 $emails{ $contact_email->emailaddress } = $dest;
3513 if ( $and_invoice ) {
3514 foreach my $email ($self->invoicing_list_emailonly) {
3515 my $dest = $self->name_short . ' <' . $email . '>';
3516 $emails{ $email } ||= $dest;
3522 =item referral_custnum_cust_main
3524 Returns the customer who referred this customer (or the empty string, if
3525 this customer was not referred).
3527 Note the difference with referral_cust_main method: This method,
3528 referral_custnum_cust_main returns the single customer (if any) who referred
3529 this customer, while referral_cust_main returns an array of customers referred
3534 sub referral_custnum_cust_main {
3536 return '' unless $self->referral_custnum;
3537 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3540 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3542 Returns an array of customers referred by this customer (referral_custnum set
3543 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3544 customers referred by customers referred by this customer and so on, inclusive.
3545 The default behavior is DEPTH 1 (no recursion).
3547 Note the difference with referral_custnum_cust_main method: This method,
3548 referral_cust_main, returns an array of customers referred BY this customer,
3549 while referral_custnum_cust_main returns the single customer (if any) who
3550 referred this customer.
3554 sub referral_cust_main {
3556 my $depth = @_ ? shift : 1;
3557 my $exclude = @_ ? shift : {};
3560 map { $exclude->{$_->custnum}++; $_; }
3561 grep { ! $exclude->{ $_->custnum } }
3562 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3566 map { $_->referral_cust_main($depth-1, $exclude) }
3573 =item referral_cust_main_ncancelled
3575 Same as referral_cust_main, except only returns customers with uncancelled
3580 sub referral_cust_main_ncancelled {
3582 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3585 =item referral_cust_pkg [ DEPTH ]
3587 Like referral_cust_main, except returns a flat list of all unsuspended (and
3588 uncancelled) packages for each customer. The number of items in this list may
3589 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3593 sub referral_cust_pkg {
3595 my $depth = @_ ? shift : 1;
3597 map { $_->unsuspended_pkgs }
3598 grep { $_->unsuspended_pkgs }
3599 $self->referral_cust_main($depth);
3602 =item referring_cust_main
3604 Returns the single cust_main record for the customer who referred this customer
3605 (referral_custnum), or false.
3609 sub referring_cust_main {
3611 return '' unless $self->referral_custnum;
3612 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3615 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3617 Applies a credit to this customer. If there is an error, returns the error,
3618 otherwise returns false.
3620 REASON can be a text string, an FS::reason object, or a scalar reference to
3621 a reasonnum. If a text string, it will be automatically inserted as a new
3622 reason, and a 'reason_type' option must be passed to indicate the
3623 FS::reason_type for the new reason.
3625 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3626 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3627 I<commission_pkgnum>.
3629 Any other options are passed to FS::cust_credit::insert.
3634 my( $self, $amount, $reason, %options ) = @_;
3636 my $cust_credit = new FS::cust_credit {
3637 'custnum' => $self->custnum,
3638 'amount' => $amount,
3641 if ( ref($reason) ) {
3643 if ( ref($reason) eq 'SCALAR' ) {
3644 $cust_credit->reasonnum( $$reason );
3646 $cust_credit->reasonnum( $reason->reasonnum );
3650 $cust_credit->set('reason', $reason)
3653 $cust_credit->$_( delete $options{$_} )
3654 foreach grep exists($options{$_}),
3655 qw( addlinfo eventnum ),
3656 map "commission_$_", qw( agentnum salesnum pkgnum );
3658 $cust_credit->insert(%options);
3662 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3664 Creates a one-time charge for this customer. If there is an error, returns
3665 the error, otherwise returns false.
3667 New-style, with a hashref of options:
3669 my $error = $cust_main->charge(
3673 'start_date' => str2time('7/4/2009'),
3674 'pkg' => 'Description',
3675 'comment' => 'Comment',
3676 'additional' => [], #extra invoice detail
3677 'classnum' => 1, #pkg_class
3679 'setuptax' => '', # or 'Y' for tax exempt
3681 'locationnum'=> 1234, # optional
3684 'taxclass' => 'Tax class',
3687 'taxproduct' => 2, #part_pkg_taxproduct
3688 'override' => {}, #XXX describe
3690 #will be filled in with the new object
3691 'cust_pkg_ref' => \$cust_pkg,
3693 #generate an invoice immediately
3695 'invoice_terms' => '', #with these terms
3701 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3705 #super false laziness w/quotation::charge
3708 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3709 my ( $pkg, $comment, $additional );
3710 my ( $setuptax, $taxclass ); #internal taxes
3711 my ( $taxproduct, $override ); #vendor (CCH) taxes
3713 my $separate_bill = '';
3714 my $cust_pkg_ref = '';
3715 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3717 if ( ref( $_[0] ) ) {
3718 $amount = $_[0]->{amount};
3719 $setup_cost = $_[0]->{setup_cost};
3720 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3721 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3722 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3723 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3724 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3725 : '$'. sprintf("%.2f",$amount);
3726 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3727 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3728 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3729 $additional = $_[0]->{additional} || [];
3730 $taxproduct = $_[0]->{taxproductnum};
3731 $override = { '' => $_[0]->{tax_override} };
3732 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3733 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3734 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3735 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3736 $separate_bill = $_[0]->{separate_bill} || '';
3742 $pkg = @_ ? shift : 'One-time charge';
3743 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3745 $taxclass = @_ ? shift : '';
3749 local $SIG{HUP} = 'IGNORE';
3750 local $SIG{INT} = 'IGNORE';
3751 local $SIG{QUIT} = 'IGNORE';
3752 local $SIG{TERM} = 'IGNORE';
3753 local $SIG{TSTP} = 'IGNORE';
3754 local $SIG{PIPE} = 'IGNORE';
3756 my $oldAutoCommit = $FS::UID::AutoCommit;
3757 local $FS::UID::AutoCommit = 0;
3760 my $part_pkg = new FS::part_pkg ( {
3762 'comment' => $comment,
3766 'classnum' => ( $classnum ? $classnum : '' ),
3767 'setuptax' => $setuptax,
3768 'taxclass' => $taxclass,
3769 'taxproductnum' => $taxproduct,
3770 'setup_cost' => $setup_cost,
3773 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3774 ( 0 .. @$additional - 1 )
3776 'additional_count' => scalar(@$additional),
3777 'setup_fee' => $amount,
3780 my $error = $part_pkg->insert( options => \%options,
3781 tax_overrides => $override,
3784 $dbh->rollback if $oldAutoCommit;
3788 my $pkgpart = $part_pkg->pkgpart;
3789 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3790 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3791 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3792 $error = $type_pkgs->insert;
3794 $dbh->rollback if $oldAutoCommit;
3799 my $cust_pkg = new FS::cust_pkg ( {
3800 'custnum' => $self->custnum,
3801 'pkgpart' => $pkgpart,
3802 'quantity' => $quantity,
3803 'start_date' => $start_date,
3804 'no_auto' => $no_auto,
3805 'separate_bill' => $separate_bill,
3806 'locationnum'=> $locationnum,
3809 $error = $cust_pkg->insert;
3811 $dbh->rollback if $oldAutoCommit;
3813 } elsif ( $cust_pkg_ref ) {
3814 ${$cust_pkg_ref} = $cust_pkg;
3818 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3819 'pkg_list' => [ $cust_pkg ],
3822 $dbh->rollback if $oldAutoCommit;
3827 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3832 #=item charge_postal_fee
3834 #Applies a one time charge this customer. If there is an error,
3835 #returns the error, returns the cust_pkg charge object or false
3836 #if there was no charge.
3840 # This should be a customer event. For that to work requires that bill
3841 # also be a customer event.
3843 sub charge_postal_fee {
3846 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3847 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3849 my $cust_pkg = new FS::cust_pkg ( {
3850 'custnum' => $self->custnum,
3851 'pkgpart' => $pkgpart,
3855 my $error = $cust_pkg->insert;
3856 $error ? $error : $cust_pkg;
3859 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3861 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3863 Optionally, a list or hashref of additional arguments to the qsearch call can
3870 my $opt = ref($_[0]) ? shift : { @_ };
3872 #return $self->num_cust_bill unless wantarray || keys %$opt;
3874 $opt->{'table'} = 'cust_bill';
3875 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3876 $opt->{'hashref'}{'custnum'} = $self->custnum;
3877 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3879 map { $_ } #behavior of sort undefined in scalar context
3880 sort { $a->_date <=> $b->_date }
3884 =item open_cust_bill
3886 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3891 sub open_cust_bill {
3895 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3901 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3903 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3907 sub legacy_cust_bill {
3910 #return $self->num_legacy_cust_bill unless wantarray;
3912 map { $_ } #behavior of sort undefined in scalar context
3913 sort { $a->_date <=> $b->_date }
3914 qsearch({ 'table' => 'legacy_cust_bill',
3915 'hashref' => { 'custnum' => $self->custnum, },
3916 'order_by' => 'ORDER BY _date ASC',
3920 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3922 Returns all the statements (see L<FS::cust_statement>) for this customer.
3924 Optionally, a list or hashref of additional arguments to the qsearch call can
3929 =item cust_bill_void
3931 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3935 sub cust_bill_void {
3938 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3939 sort { $a->_date <=> $b->_date }
3940 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3943 sub cust_statement {
3945 my $opt = ref($_[0]) ? shift : { @_ };
3947 #return $self->num_cust_statement unless wantarray || keys %$opt;
3949 $opt->{'table'} = 'cust_statement';
3950 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3951 $opt->{'hashref'}{'custnum'} = $self->custnum;
3952 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3954 map { $_ } #behavior of sort undefined in scalar context
3955 sort { $a->_date <=> $b->_date }
3959 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3961 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3963 Optionally, a list or hashref of additional arguments to the qsearch call can
3964 be passed following the SVCDB.
3971 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3972 warn "$me svc_x requires a svcdb";
3975 my $opt = ref($_[0]) ? shift : { @_ };
3977 $opt->{'table'} = $svcdb;
3978 $opt->{'addl_from'} =
3979 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3980 ($opt->{'addl_from'} || '');
3982 my $custnum = $self->custnum;
3983 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3984 my $where = "cust_pkg.custnum = $custnum";
3986 my $extra_sql = $opt->{'extra_sql'} || '';
3987 if ( keys %{ $opt->{'hashref'} } ) {
3988 $extra_sql = " AND $where $extra_sql";
3991 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3992 $extra_sql = "WHERE $where AND $1";
3995 $extra_sql = "WHERE $where $extra_sql";
3998 $opt->{'extra_sql'} = $extra_sql;
4003 # required for use as an eventtable;
4006 $self->svc_x('svc_acct', @_);
4011 Returns all the credits (see L<FS::cust_credit>) for this customer.
4017 map { $_ } #return $self->num_cust_credit unless wantarray;
4018 sort { $a->_date <=> $b->_date }
4019 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4022 =item cust_credit_pkgnum
4024 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
4025 package when using experimental package balances.
4029 sub cust_credit_pkgnum {
4030 my( $self, $pkgnum ) = @_;
4031 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
4032 sort { $a->_date <=> $b->_date }
4033 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
4034 'pkgnum' => $pkgnum,
4039 =item cust_credit_void
4041 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
4045 sub cust_credit_void {
4048 sort { $a->_date <=> $b->_date }
4049 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
4054 Returns all the payments (see L<FS::cust_pay>) for this customer.
4060 my $opt = ref($_[0]) ? shift : { @_ };
4062 return $self->num_cust_pay unless wantarray || keys %$opt;
4064 $opt->{'table'} = 'cust_pay';
4065 $opt->{'hashref'}{'custnum'} = $self->custnum;
4067 map { $_ } #behavior of sort undefined in scalar context
4068 sort { $a->_date <=> $b->_date }
4075 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
4076 called automatically when the cust_pay method is used in a scalar context.
4082 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
4083 my $sth = dbh->prepare($sql) or die dbh->errstr;
4084 $sth->execute($self->custnum) or die $sth->errstr;
4085 $sth->fetchrow_arrayref->[0];
4088 =item unapplied_cust_pay
4090 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
4094 sub unapplied_cust_pay {
4098 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
4104 =item cust_pay_pkgnum
4106 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
4107 package when using experimental package balances.
4111 sub cust_pay_pkgnum {
4112 my( $self, $pkgnum ) = @_;
4113 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
4114 sort { $a->_date <=> $b->_date }
4115 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
4116 'pkgnum' => $pkgnum,
4123 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4129 map { $_ } #return $self->num_cust_pay_void unless wantarray;
4130 sort { $a->_date <=> $b->_date }
4131 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4134 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4136 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
4138 Optionally, a list or hashref of additional arguments to the qsearch call can
4143 sub cust_pay_batch {
4145 my $opt = ref($_[0]) ? shift : { @_ };
4147 #return $self->num_cust_statement unless wantarray || keys %$opt;
4149 $opt->{'table'} = 'cust_pay_batch';
4150 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4151 $opt->{'hashref'}{'custnum'} = $self->custnum;
4152 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
4154 map { $_ } #behavior of sort undefined in scalar context
4155 sort { $a->paybatchnum <=> $b->paybatchnum }
4159 =item cust_pay_pending
4161 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
4162 (without status "done").
4166 sub cust_pay_pending {
4168 return $self->num_cust_pay_pending unless wantarray;
4169 sort { $a->_date <=> $b->_date }
4170 qsearch( 'cust_pay_pending', {
4171 'custnum' => $self->custnum,
4172 'status' => { op=>'!=', value=>'done' },
4177 =item cust_pay_pending_attempt
4179 Returns all payment attempts / declined payments for this customer, as pending
4180 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
4181 a corresponding payment (see L<FS::cust_pay>).
4185 sub cust_pay_pending_attempt {
4187 return $self->num_cust_pay_pending_attempt unless wantarray;
4188 sort { $a->_date <=> $b->_date }
4189 qsearch( 'cust_pay_pending', {
4190 'custnum' => $self->custnum,
4197 =item num_cust_pay_pending
4199 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4200 customer (without status "done"). Also called automatically when the
4201 cust_pay_pending method is used in a scalar context.
4205 sub num_cust_pay_pending {
4208 " SELECT COUNT(*) FROM cust_pay_pending ".
4209 " WHERE custnum = ? AND status != 'done' ",
4214 =item num_cust_pay_pending_attempt
4216 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4217 customer, with status "done" but without a corresp. Also called automatically when the
4218 cust_pay_pending method is used in a scalar context.
4222 sub num_cust_pay_pending_attempt {
4225 " SELECT COUNT(*) FROM cust_pay_pending ".
4226 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4233 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4239 map { $_ } #return $self->num_cust_refund unless wantarray;
4240 sort { $a->_date <=> $b->_date }
4241 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4244 =item display_custnum
4246 Returns the displayed customer number for this customer: agent_custid if
4247 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4251 sub display_custnum {
4254 return $self->agent_custid
4255 if $default_agent_custid && $self->agent_custid;
4257 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4261 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
4262 } elsif ( $custnum_display_length ) {
4263 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
4265 return $self->custnum;
4271 Returns a name string for this customer, either "Company (Last, First)" or
4278 my $name = $self->contact;
4279 $name = $self->company. " ($name)" if $self->company;
4283 =item service_contact
4285 Returns the L<FS::contact> object for this customer that has the 'Service'
4286 contact class, or undef if there is no such contact. Deprecated; don't use
4291 sub service_contact {
4293 if ( !exists($self->{service_contact}) ) {
4294 my $classnum = $self->scalar_sql(
4295 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4296 ) || 0; #if it's zero, qsearchs will return nothing
4297 $self->{service_contact} = qsearchs('contact', {
4298 'classnum' => $classnum, 'custnum' => $self->custnum
4301 $self->{service_contact};
4306 Returns a name string for this (service/shipping) contact, either
4307 "Company (Last, First)" or "Last, First".
4314 my $name = $self->ship_contact;
4315 $name = $self->company. " ($name)" if $self->company;
4321 Returns a name string for this customer, either "Company" or "First Last".
4327 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4330 =item ship_name_short
4332 Returns a name string for this (service/shipping) contact, either "Company"
4337 sub ship_name_short {
4339 $self->service_contact
4340 ? $self->ship_contact_firstlast
4346 Returns this customer's full (billing) contact name only, "Last, First"
4352 $self->get('last'). ', '. $self->first;
4357 Returns this customer's full (shipping) contact name only, "Last, First"
4363 my $contact = $self->service_contact || $self;
4364 $contact->get('last') . ', ' . $contact->get('first');
4367 =item contact_firstlast
4369 Returns this customers full (billing) contact name only, "First Last".
4373 sub contact_firstlast {
4375 $self->first. ' '. $self->get('last');
4378 =item ship_contact_firstlast
4380 Returns this customer's full (shipping) contact name only, "First Last".
4384 sub ship_contact_firstlast {
4386 my $contact = $self->service_contact || $self;
4387 $contact->get('first') . ' '. $contact->get('last');
4390 sub bill_country_full {
4392 $self->bill_location->country_full;
4395 sub ship_country_full {
4397 $self->ship_location->country_full;
4400 =item county_state_county [ PREFIX ]
4402 Returns a string consisting of just the county, state and country.
4406 sub county_state_country {
4409 if ( @_ && $_[0] && $self->has_ship_address ) {
4410 $locationnum = $self->ship_locationnum;
4412 $locationnum = $self->bill_locationnum;
4414 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4415 $cust_location->county_state_country;
4418 =item geocode DATA_VENDOR
4420 Returns a value for the customer location as encoded by DATA_VENDOR.
4421 Currently this only makes sense for "CCH" as DATA_VENDOR.
4429 Returns a status string for this customer, currently:
4433 =item prospect - No packages have ever been ordered
4435 =item ordered - Recurring packages all are new (not yet billed).
4437 =item active - One or more recurring packages is active
4439 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4441 =item suspended - All non-cancelled recurring packages are suspended
4443 =item cancelled - All recurring packages are cancelled
4447 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4448 cust_main-status_module configuration option.
4452 sub status { shift->cust_status(@_); }
4456 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
4457 for my $status ( FS::cust_main->statuses() ) {
4458 my $method = $status.'_sql';
4459 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4460 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4461 $sth->execute( ($self->custnum) x $numnum )
4462 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4463 if ( $sth->fetchrow_arrayref->[0] ) {
4464 $self->hashref->{cust_status} = $status;
4470 =item is_status_delay_cancel
4472 Returns true if customer status is 'suspended'
4473 and all suspended cust_pkg return true for
4474 cust_pkg->is_status_delay_cancel.
4476 This is not a real status, this only meant for hacking display
4477 values, because otherwise treating the customer as suspended is
4478 really the whole point of the delay_cancel option.
4482 sub is_status_delay_cancel {
4484 return 0 unless $self->status eq 'suspended';
4485 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4486 return 0 unless $cust_pkg->is_status_delay_cancel;
4491 =item ucfirst_cust_status
4493 =item ucfirst_status
4495 Returns the status with the first character capitalized.
4499 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4501 sub ucfirst_cust_status {
4503 ucfirst($self->cust_status);
4508 Returns a hex triplet color string for this customer's status.
4512 sub statuscolor { shift->cust_statuscolor(@_); }
4514 sub cust_statuscolor {
4516 __PACKAGE__->statuscolors->{$self->cust_status};
4519 =item tickets [ STATUS ]
4521 Returns an array of hashes representing the customer's RT tickets.
4523 An optional status (or arrayref or hashref of statuses) may be specified.
4529 my $status = ( @_ && $_[0] ) ? shift : '';
4531 my $num = $conf->config('cust_main-max_tickets') || 10;
4534 if ( $conf->config('ticket_system') ) {
4535 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4537 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4546 foreach my $priority (
4547 $conf->config('ticket_system-custom_priority_field-values'), ''
4549 last if scalar(@tickets) >= $num;
4551 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4552 $num - scalar(@tickets),
4563 =item appointments [ STATUS ]
4565 Returns an array of hashes representing the customer's RT tickets which
4572 my $status = ( @_ && $_[0] ) ? shift : '';
4574 return () unless $conf->config('ticket_system');
4576 my $queueid = $conf->config('ticket_system-appointment-queueid');
4578 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4587 # Return services representing svc_accts in customer support packages
4588 sub support_services {
4590 my %packages = map { $_ => 1 } $conf->config('support_packages');
4592 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4593 grep { $_->part_svc->svcdb eq 'svc_acct' }
4594 map { $_->cust_svc }
4595 grep { exists $packages{ $_->pkgpart } }
4596 $self->ncancelled_pkgs;
4600 # Return a list of latitude/longitude for one of the services (if any)
4601 sub service_coordinates {
4605 grep { $_->latitude && $_->longitude }
4607 map { $_->cust_svc }
4608 $self->ncancelled_pkgs;
4610 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4615 Returns a masked version of the named field
4620 my ($self,$field) = @_;
4624 'x'x(length($self->getfield($field))-4).
4625 substr($self->getfield($field), (length($self->getfield($field))-4));
4629 =item payment_history
4631 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4632 cust_credit and cust_refund objects. Each hashref has the following fields:
4634 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4636 I<date> - value of _date field, unix timestamp
4638 I<date_pretty> - user-friendly date
4640 I<description> - user-friendly description of item
4642 I<amount> - impact of item on user's balance
4643 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4644 Not to be confused with the native 'amount' field in cust_credit, see below.
4646 I<amount_pretty> - includes money char
4648 I<balance> - customer balance, chronologically as of this item
4650 I<balance_pretty> - includes money char
4652 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4654 I<paid> - amount paid for cust_pay records, undef for other types
4656 I<credit> - amount credited for cust_credit records, undef for other types.
4657 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4659 I<refund> - amount refunded for cust_refund records, undef for other types
4661 The four table-specific keys always have positive values, whether they reflect charges or payments.
4663 The following options may be passed to this method:
4665 I<line_items> - if true, returns charges ('Line item') rather than invoices
4667 I<start_date> - unix timestamp, only include records on or after.
4668 If specified, an item of type 'Previous' will also be included.
4669 It does not have table-specific fields.
4671 I<end_date> - unix timestamp, only include records before
4673 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4675 I<conf> - optional already-loaded FS::Conf object.
4679 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4680 # and also for sending customer statements, which should both be kept customer-friendly.
4681 # If you add anything that shouldn't be passed on through the API or exposed
4682 # to customers, add a new option to include it, don't include it by default
4683 sub payment_history {
4685 my $opt = ref($_[0]) ? $_[0] : { @_ };
4687 my $conf = $$opt{'conf'} || new FS::Conf;
4688 my $money_char = $conf->config("money_char") || '$',
4690 #first load entire history,
4691 #need previous to calculate previous balance
4692 #loading after end_date shouldn't hurt too much?
4694 if ( $$opt{'line_items'} ) {
4696 foreach my $cust_bill ( $self->cust_bill ) {
4699 'type' => 'Line item',
4700 'description' => $_->desc( $self->locale ).
4701 ( $_->sdate && $_->edate
4702 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4703 ' To '. time2str('%d-%b-%Y', $_->edate)
4706 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4707 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4708 'date' => $cust_bill->_date,
4709 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4711 foreach $cust_bill->cust_bill_pkg;
4718 'type' => 'Invoice',
4719 'description' => 'Invoice #'. $_->display_invnum,
4720 'amount' => sprintf('%.2f', $_->charged ),
4721 'charged' => sprintf('%.2f', $_->charged ),
4722 'date' => $_->_date,
4723 'date_pretty' => $self->time2str_local('short', $_->_date ),
4725 foreach $self->cust_bill;
4730 'type' => 'Payment',
4731 'description' => 'Payment', #XXX type
4732 'amount' => sprintf('%.2f', 0 - $_->paid ),
4733 'paid' => sprintf('%.2f', $_->paid ),
4734 'date' => $_->_date,
4735 'date_pretty' => $self->time2str_local('short', $_->_date ),
4737 foreach $self->cust_pay;
4741 'description' => 'Credit', #more info?
4742 'amount' => sprintf('%.2f', 0 -$_->amount ),
4743 'credit' => sprintf('%.2f', $_->amount ),
4744 'date' => $_->_date,
4745 'date_pretty' => $self->time2str_local('short', $_->_date ),
4747 foreach $self->cust_credit;
4751 'description' => 'Refund', #more info? type, like payment?
4752 'amount' => $_->refund,
4753 'refund' => $_->refund,
4754 'date' => $_->_date,
4755 'date_pretty' => $self->time2str_local('short', $_->_date ),
4757 foreach $self->cust_refund;
4759 #put it all in chronological order
4760 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4762 #calculate balance, filter items outside date range
4766 foreach my $item (@history) {
4767 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4768 $balance += $$item{'amount'};
4769 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4770 $previous += $$item{'amount'};
4773 $$item{'balance'} = sprintf("%.2f",$balance);
4774 foreach my $key ( qw(amount balance) ) {
4775 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4780 # start with previous balance, if there was one
4783 'type' => 'Previous',
4784 'description' => 'Previous balance',
4785 'amount' => sprintf("%.2f",$previous),
4786 'balance' => sprintf("%.2f",$previous),
4787 'date' => $$opt{'start_date'},
4788 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4790 #false laziness with above
4791 foreach my $key ( qw(amount balance) ) {
4792 $$item{$key.'_pretty'} = $$item{$key};
4793 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4795 unshift(@out,$item);
4798 @out = reverse @history if $$opt{'reverse_sort'};
4805 =head1 CLASS METHODS
4811 Class method that returns the list of possible status strings for customers
4812 (see L<the status method|/status>). For example:
4814 @statuses = FS::cust_main->statuses();
4820 keys %{ $self->statuscolors };
4823 =item cust_status_sql
4825 Returns an SQL fragment to determine the status of a cust_main record, as a
4830 sub cust_status_sql {
4832 for my $status ( FS::cust_main->statuses() ) {
4833 my $method = $status.'_sql';
4834 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4843 Returns an SQL expression identifying prospective cust_main records (customers
4844 with no packages ever ordered)
4848 use vars qw($select_count_pkgs);
4849 $select_count_pkgs =
4850 "SELECT COUNT(*) FROM cust_pkg
4851 WHERE cust_pkg.custnum = cust_main.custnum";
4853 sub select_count_pkgs_sql {
4858 " 0 = ( $select_count_pkgs ) ";
4863 Returns an SQL expression identifying ordered cust_main records (customers with
4864 no active packages, but recurring packages not yet setup or one time charges
4870 FS::cust_main->none_active_sql.
4871 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4876 Returns an SQL expression identifying active cust_main records (customers with
4877 active recurring packages).
4882 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4885 =item none_active_sql
4887 Returns an SQL expression identifying cust_main records with no active
4888 recurring packages. This includes customers of status prospect, ordered,
4889 inactive, and suspended.
4893 sub none_active_sql {
4894 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4899 Returns an SQL expression identifying inactive cust_main records (customers with
4900 no active recurring packages, but otherwise unsuspended/uncancelled).
4905 FS::cust_main->none_active_sql.
4906 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4912 Returns an SQL expression identifying suspended cust_main records.
4917 sub suspended_sql { susp_sql(@_); }
4919 FS::cust_main->none_active_sql.
4920 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4926 Returns an SQL expression identifying cancelled cust_main records.
4930 sub cancel_sql { shift->cancelled_sql(@_); }
4933 =item uncancelled_sql
4935 Returns an SQL expression identifying un-cancelled cust_main records.
4939 sub uncancelled_sql { uncancel_sql(@_); }
4940 sub uncancel_sql { "
4941 ( 0 < ( $select_count_pkgs
4942 AND ( cust_pkg.cancel IS NULL
4943 OR cust_pkg.cancel = 0
4946 OR 0 = ( $select_count_pkgs )
4952 Returns an SQL fragment to retreive the balance.
4957 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4958 WHERE cust_bill.custnum = cust_main.custnum )
4959 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4960 WHERE cust_pay.custnum = cust_main.custnum )
4961 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4962 WHERE cust_credit.custnum = cust_main.custnum )
4963 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4964 WHERE cust_refund.custnum = cust_main.custnum )
4967 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4969 Returns an SQL fragment to retreive the balance for this customer, optionally
4970 considering invoices with date earlier than START_TIME, and not
4971 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4972 total_unapplied_payments).
4974 Times are specified as SQL fragments or numeric
4975 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4976 L<Date::Parse> for conversion functions. The empty string can be passed
4977 to disable that time constraint completely.
4979 Available options are:
4983 =item unapplied_date
4985 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)
4990 set to true to remove all customer comparison clauses, for totals
4995 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5000 JOIN clause (typically used with the total option)
5004 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
5005 time will be ignored. Note that START_TIME and END_TIME only limit the date
5006 range for invoices and I<unapplied> payments, credits, and refunds.
5012 sub balance_date_sql {
5013 my( $class, $start, $end, %opt ) = @_;
5015 my $cutoff = $opt{'cutoff'};
5017 my $owed = FS::cust_bill->owed_sql($cutoff);
5018 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
5019 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
5020 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5022 my $j = $opt{'join'} || '';
5024 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5025 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5026 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5027 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5029 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5030 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5031 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5032 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5037 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
5039 Returns an SQL fragment to retreive the total unapplied payments for this
5040 customer, only considering payments with date earlier than START_TIME, and
5041 optionally not later than END_TIME.
5043 Times are specified as SQL fragments or numeric
5044 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5045 L<Date::Parse> for conversion functions. The empty string can be passed
5046 to disable that time constraint completely.
5048 Available options are:
5052 sub unapplied_payments_date_sql {
5053 my( $class, $start, $end, %opt ) = @_;
5055 my $cutoff = $opt{'cutoff'};
5057 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5059 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
5060 'unapplied_date'=>1 );
5062 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
5065 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5067 Helper method for balance_date_sql; name (and usage) subject to change
5068 (suggestions welcome).
5070 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5071 cust_refund, cust_credit or cust_pay).
5073 If TABLE is "cust_bill" or the unapplied_date option is true, only
5074 considers records with date earlier than START_TIME, and optionally not
5075 later than END_TIME .
5079 sub _money_table_where {
5080 my( $class, $table, $start, $end, %opt ) = @_;
5083 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5084 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5085 push @where, "$table._date <= $start" if defined($start) && length($start);
5086 push @where, "$table._date > $end" if defined($end) && length($end);
5088 push @where, @{$opt{'where'}} if $opt{'where'};
5089 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5095 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5096 use FS::cust_main::Search;
5099 FS::cust_main::Search->search(@_);
5114 #warn join('-',keys %$param);
5115 my $fh = $param->{filehandle};
5116 my $agentnum = $param->{agentnum};
5117 my $format = $param->{format};
5119 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
5122 if ( $format eq 'simple' ) {
5123 @fields = qw( custnum agent_custid amount pkg );
5125 die "unknown format $format";
5128 eval "use Text::CSV_XS;";
5131 my $csv = new Text::CSV_XS;
5138 local $SIG{HUP} = 'IGNORE';
5139 local $SIG{INT} = 'IGNORE';
5140 local $SIG{QUIT} = 'IGNORE';
5141 local $SIG{TERM} = 'IGNORE';
5142 local $SIG{TSTP} = 'IGNORE';
5143 local $SIG{PIPE} = 'IGNORE';
5145 my $oldAutoCommit = $FS::UID::AutoCommit;
5146 local $FS::UID::AutoCommit = 0;
5149 #while ( $columns = $csv->getline($fh) ) {
5151 while ( defined($line=<$fh>) ) {
5153 $csv->parse($line) or do {
5154 $dbh->rollback if $oldAutoCommit;
5155 return "can't parse: ". $csv->error_input();
5158 my @columns = $csv->fields();
5159 #warn join('-',@columns);
5162 foreach my $field ( @fields ) {
5163 $row{$field} = shift @columns;
5166 if ( $row{custnum} && $row{agent_custid} ) {
5167 dbh->rollback if $oldAutoCommit;
5168 return "can't specify custnum with agent_custid $row{agent_custid}";
5172 if ( $row{agent_custid} && $agentnum ) {
5173 %hash = ( 'agent_custid' => $row{agent_custid},
5174 'agentnum' => $agentnum,
5178 if ( $row{custnum} ) {
5179 %hash = ( 'custnum' => $row{custnum} );
5182 unless ( scalar(keys %hash) ) {
5183 $dbh->rollback if $oldAutoCommit;
5184 return "can't find customer without custnum or agent_custid and agentnum";
5187 my $cust_main = qsearchs('cust_main', { %hash } );
5188 unless ( $cust_main ) {
5189 $dbh->rollback if $oldAutoCommit;
5190 my $custnum = $row{custnum} || $row{agent_custid};
5191 return "unknown custnum $custnum";
5194 if ( $row{'amount'} > 0 ) {
5195 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5197 $dbh->rollback if $oldAutoCommit;
5201 } elsif ( $row{'amount'} < 0 ) {
5202 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5205 $dbh->rollback if $oldAutoCommit;
5215 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5217 return "Empty file!" unless $imported;
5223 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5225 Deprecated. Use event notification and message templates
5226 (L<FS::msg_template>) instead.
5228 Sends a templated email notification to the customer (see L<Text::Template>).
5230 OPTIONS is a hash and may include
5232 I<from> - the email sender (default is invoice_from)
5234 I<to> - comma-separated scalar or arrayref of recipients
5235 (default is invoicing_list)
5237 I<subject> - The subject line of the sent email notification
5238 (default is "Notice from company_name")
5240 I<extra_fields> - a hashref of name/value pairs which will be substituted
5243 The following variables are vavailable in the template.
5245 I<$first> - the customer first name
5246 I<$last> - the customer last name
5247 I<$company> - the customer company
5248 I<$payby> - a description of the method of payment for the customer
5249 # would be nice to use FS::payby::shortname
5250 I<$payinfo> - the account information used to collect for this customer
5251 I<$expdate> - the expiration of the customer payment in seconds from epoch
5256 my ($self, $template, %options) = @_;
5258 return unless $conf->exists($template);
5260 my $from = $conf->invoice_from_full($self->agentnum)
5261 if $conf->exists('invoice_from', $self->agentnum);
5262 $from = $options{from} if exists($options{from});
5264 my $to = join(',', $self->invoicing_list_emailonly);
5265 $to = $options{to} if exists($options{to});
5267 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5268 if $conf->exists('company_name', $self->agentnum);
5269 $subject = $options{subject} if exists($options{subject});
5271 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5272 SOURCE => [ map "$_\n",
5273 $conf->config($template)]
5275 or die "can't create new Text::Template object: Text::Template::ERROR";
5276 $notify_template->compile()
5277 or die "can't compile template: Text::Template::ERROR";
5279 $FS::notify_template::_template::company_name =
5280 $conf->config('company_name', $self->agentnum);
5281 $FS::notify_template::_template::company_address =
5282 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5284 my $paydate = $self->paydate || '2037-12-31';
5285 $FS::notify_template::_template::first = $self->first;
5286 $FS::notify_template::_template::last = $self->last;
5287 $FS::notify_template::_template::company = $self->company;
5288 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5289 my $payby = $self->payby;
5290 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5291 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5293 #credit cards expire at the end of the month/year of their exp date
5294 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5295 $FS::notify_template::_template::payby = 'credit card';
5296 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5297 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5299 }elsif ($payby eq 'COMP') {
5300 $FS::notify_template::_template::payby = 'complimentary account';
5302 $FS::notify_template::_template::payby = 'current method';
5304 $FS::notify_template::_template::expdate = $expire_time;
5306 for (keys %{$options{extra_fields}}){
5308 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5311 send_email(from => $from,
5313 subject => $subject,
5314 body => $notify_template->fill_in( PACKAGE =>
5315 'FS::notify_template::_template' ),
5320 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5322 Generates a templated notification to the customer (see L<Text::Template>).
5324 OPTIONS is a hash and may include
5326 I<extra_fields> - a hashref of name/value pairs which will be substituted
5327 into the template. These values may override values mentioned below
5328 and those from the customer record.
5330 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5332 The following variables are available in the template instead of or in addition
5333 to the fields of the customer record.
5335 I<$payby> - a description of the method of payment for the customer
5336 # would be nice to use FS::payby::shortname
5337 I<$payinfo> - the masked account information used to collect for this customer
5338 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5339 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5343 # a lot like cust_bill::print_latex
5344 sub generate_letter {
5345 my ($self, $template, %options) = @_;
5347 warn "Template $template does not exist" && return
5348 unless $conf->exists($template) || $options{'template_text'};
5350 my $template_source = $options{'template_text'}
5351 ? [ $options{'template_text'} ]
5352 : [ map "$_\n", $conf->config($template) ];
5354 my $letter_template = new Text::Template
5356 SOURCE => $template_source,
5357 DELIMITERS => [ '[@--', '--@]' ],
5359 or die "can't create new Text::Template object: Text::Template::ERROR";
5361 $letter_template->compile()
5362 or die "can't compile template: Text::Template::ERROR";
5364 my %letter_data = map { $_ => $self->$_ } $self->fields;
5365 $letter_data{payinfo} = $self->mask_payinfo;
5367 #my $paydate = $self->paydate || '2037-12-31';
5368 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5370 my $payby = $self->payby;
5371 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5372 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5374 #credit cards expire at the end of the month/year of their exp date
5375 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5376 $letter_data{payby} = 'credit card';
5377 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5378 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5380 }elsif ($payby eq 'COMP') {
5381 $letter_data{payby} = 'complimentary account';
5383 $letter_data{payby} = 'current method';
5385 $letter_data{expdate} = $expire_time;
5387 for (keys %{$options{extra_fields}}){
5388 $letter_data{$_} = $options{extra_fields}->{$_};
5391 unless(exists($letter_data{returnaddress})){
5392 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5393 $self->agent_template)
5395 if ( length($retadd) ) {
5396 $letter_data{returnaddress} = $retadd;
5397 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5398 $letter_data{returnaddress} =
5399 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5403 ( $conf->config('company_name', $self->agentnum),
5404 $conf->config('company_address', $self->agentnum),
5408 $letter_data{returnaddress} = '~';
5412 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5414 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5416 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5418 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5422 ) or die "can't open temp file: $!\n";
5423 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5424 or die "can't write temp file: $!\n";
5426 $letter_data{'logo_file'} = $lh->filename;
5428 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5432 ) or die "can't open temp file: $!\n";
5434 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5436 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5437 return ($1, $letter_data{'logo_file'});
5441 =item print_ps TEMPLATE
5443 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5449 my($file, $lfile) = $self->generate_letter(@_);
5450 my $ps = FS::Misc::generate_ps($file);
5451 unlink($file.'.tex');
5457 =item print TEMPLATE
5459 Prints the filled in template.
5461 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5465 sub queueable_print {
5468 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5469 or die "invalid customer number: " . $opt{custnum};
5471 my $error = $self->print( { 'template' => $opt{template} } );
5472 die $error if $error;
5476 my ($self, $template) = (shift, shift);
5478 [ $self->print_ps($template) ],
5479 'agentnum' => $self->agentnum,
5483 #these three subs should just go away once agent stuff is all config overrides
5485 sub agent_template {
5487 $self->_agent_plandata('agent_templatename');
5490 sub agent_invoice_from {
5492 $self->_agent_plandata('agent_invoice_from');
5495 sub _agent_plandata {
5496 my( $self, $option ) = @_;
5498 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5499 #agent-specific Conf
5501 use FS::part_event::Condition;
5503 my $agentnum = $self->agentnum;
5505 my $regexp = regexp_sql();
5507 my $part_event_option =
5509 'select' => 'part_event_option.*',
5510 'table' => 'part_event_option',
5512 LEFT JOIN part_event USING ( eventpart )
5513 LEFT JOIN part_event_option AS peo_agentnum
5514 ON ( part_event.eventpart = peo_agentnum.eventpart
5515 AND peo_agentnum.optionname = 'agentnum'
5516 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5518 LEFT JOIN part_event_condition
5519 ON ( part_event.eventpart = part_event_condition.eventpart
5520 AND part_event_condition.conditionname = 'cust_bill_age'
5522 LEFT JOIN part_event_condition_option
5523 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5524 AND part_event_condition_option.optionname = 'age'
5527 #'hashref' => { 'optionname' => $option },
5528 #'hashref' => { 'part_event_option.optionname' => $option },
5530 " WHERE part_event_option.optionname = ". dbh->quote($option).
5531 " AND action = 'cust_bill_send_agent' ".
5532 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5533 " AND peo_agentnum.optionname = 'agentnum' ".
5534 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5536 CASE WHEN part_event_condition_option.optionname IS NULL
5538 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5540 , part_event.weight".
5544 unless ( $part_event_option ) {
5545 return $self->agent->invoice_template || ''
5546 if $option eq 'agent_templatename';
5550 $part_event_option->optionvalue;
5554 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5556 Subroutine (not a method), designed to be called from the queue.
5558 Takes a list of options and values.
5560 Pulls up the customer record via the custnum option and calls bill_and_collect.
5565 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5567 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5568 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5570 #without this errors don't get rolled back
5571 $args{'fatal'} = 1; # runs from job queue, will be caught
5573 $cust_main->bill_and_collect( %args );
5576 sub process_bill_and_collect {
5578 my $param = thaw(decode_base64(shift));
5579 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5580 or die "custnum '$param->{custnum}' not found!\n";
5581 $param->{'job'} = $job;
5582 $param->{'fatal'} = 1; # runs from job queue, will be caught
5583 $param->{'retry'} = 1;
5585 $cust_main->bill_and_collect( %$param );
5588 #starting to take quite a while for big dbs
5589 # (JRNL: journaled so it only happens once per database)
5590 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5591 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5592 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5593 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5594 # JRNL leading/trailing spaces in first, last, company
5595 # - otaker upgrade? journal and call it good? (double check to make sure
5596 # we're not still setting otaker here)
5598 #only going to get worse with new location stuff...
5600 sub _upgrade_data { #class method
5601 my ($class, %opts) = @_;
5604 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5607 #this seems to be the only expensive one.. why does it take so long?
5608 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5610 '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';
5611 FS::upgrade_journal->set_done('cust_main__signupdate');
5614 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5616 # fix yyyy-m-dd formatted paydates
5617 if ( driver_name =~ /^mysql/i ) {
5619 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5620 } else { # the SQL standard
5622 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5624 FS::upgrade_journal->set_done('cust_main__paydate');
5627 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5629 push @statements, #fix the weird BILL with a cc# in payinfo problem
5631 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5633 FS::upgrade_journal->set_done('cust_main__payinfo');
5638 foreach my $sql ( @statements ) {
5639 my $sth = dbh->prepare($sql) or die dbh->errstr;
5640 $sth->execute or die $sth->errstr;
5641 #warn ( (time - $t). " seconds\n" );
5645 local($ignore_expired_card) = 1;
5646 local($ignore_banned_card) = 1;
5647 local($skip_fuzzyfiles) = 1;
5648 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5650 FS::cust_main::Location->_upgrade_data(%opts);
5652 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5654 foreach my $cust_main ( qsearch({
5655 'table' => 'cust_main',
5657 'extra_sql' => 'WHERE '.
5659 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5660 qw( first last company )
5663 my $error = $cust_main->replace;
5664 die $error if $error;
5667 FS::upgrade_journal->set_done('cust_main__trimspaces');
5671 $class->_upgrade_otaker(%opts);
5681 The delete method should possibly take an FS::cust_main object reference
5682 instead of a scalar customer number.
5684 Bill and collect options should probably be passed as references instead of a
5687 There should probably be a configuration file with a list of allowed credit
5690 No multiple currency support (probably a larger project than just this module).
5692 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5694 Birthdates rely on negative epoch values.
5696 The payby for card/check batches is broken. With mixed batching, bad
5699 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5703 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5704 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5705 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.