5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6 FS::cust_main::NationalID
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
12 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
17 use vars qw( $DEBUG $me $conf $default_agent_custid $custnum_display_length
20 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
31 use Digest::MD5 qw(md5_base64);
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
36 use FS::UID qw( getotaker dbh driver_name );
37 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
38 use FS::Misc qw( generate_email send_email generate_ps do_print money_pretty card_types );
39 use FS::Msgcat qw(gettext);
46 use FS::cust_bill_void;
47 use FS::legacy_cust_bill;
49 use FS::cust_pay_pending;
50 use FS::cust_pay_void;
51 use FS::cust_pay_batch;
54 use FS::part_referral;
55 use FS::cust_main_county;
56 use FS::cust_location;
58 use FS::cust_main_exemption;
59 use FS::cust_tax_adjustment;
60 use FS::cust_tax_location;
62 use FS::cust_main_invoice;
64 use FS::prepay_credit;
70 use FS::payment_gateway;
71 use FS::agent_payment_gateway;
73 use FS::cust_main_note;
74 use FS::cust_attachment;
77 use FS::upgrade_journal;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 $me = '[FS::cust_main]';
87 $ignore_expired_card = 0;
88 $ignore_banned_card = 0;
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub {
99 install_callback FS::UID sub {
100 $conf = new FS::Conf;
101 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
102 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
107 my ( $hashref, $cache ) = @_;
108 if ( exists $hashref->{'pkgnum'} ) {
109 #@{ $self->{'_pkgnum'} } = ();
110 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
111 $self->{'_pkgnum'} = $subcache;
112 #push @{ $self->{'_pkgnum'} },
113 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
119 FS::cust_main - Object methods for cust_main records
125 $record = new FS::cust_main \%hash;
126 $record = new FS::cust_main { 'column' => 'value' };
128 $error = $record->insert;
130 $error = $new_record->replace($old_record);
132 $error = $record->delete;
134 $error = $record->check;
136 @cust_pkg = $record->all_pkgs;
138 @cust_pkg = $record->ncancelled_pkgs;
140 @cust_pkg = $record->suspended_pkgs;
142 $error = $record->bill;
143 $error = $record->bill %options;
144 $error = $record->bill 'time' => $time;
146 $error = $record->collect;
147 $error = $record->collect %options;
148 $error = $record->collect 'invoice_time' => $time,
153 An FS::cust_main object represents a customer. FS::cust_main inherits from
154 FS::Record. The following fields are currently supported:
160 Primary key (assigned automatically for new customers)
164 Agent (see L<FS::agent>)
168 Advertising source (see L<FS::part_referral>)
180 Cocial security number (optional)
204 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
208 Payment Information (See L<FS::payinfo_Mixin> for data format)
212 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
216 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
220 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
224 Start date month (maestro/solo cards only)
228 Start date year (maestro/solo cards only)
232 Issue number (maestro/solo cards only)
236 Name on card or billing name
240 IP address from which payment information was received
244 The credit card type (deduced from the card number).
248 Tax exempt, empty or `Y'
252 Order taker (see L<FS::access_user>)
258 =item referral_custnum
260 Referring customer number
264 Enable individual CDR spooling, empty or `Y'
268 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
272 Discourage individual CDR printing, empty or `Y'
276 Allow self-service editing of ticket subjects, empty or 'Y'
278 =item calling_list_exempt
280 Do not call, empty or 'Y'
282 =item invoice_ship_address
284 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
294 Creates a new customer. To add the customer to the database, see L<"insert">.
296 Note that this stores the hash reference, not a distinct copy of the hash it
297 points to. You can ask the object for a copy with the I<hash> method.
301 sub table { 'cust_main'; }
303 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
305 Adds this customer to the database. If there is an error, returns the error,
306 otherwise returns false.
308 Usually the customer's location will not yet exist in the database, and
309 the C<bill_location> and C<ship_location> pseudo-fields must be set to
310 uninserted L<FS::cust_location> objects. These will be inserted and linked
311 (in both directions) to the new customer record. If they're references
312 to the same object, they will become the same location.
314 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
315 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
316 are inserted atomicly, or the transaction is rolled back. Passing an empty
317 hash reference is equivalent to not supplying this parameter. There should be
318 a better explanation of this, but until then, here's an example:
321 tie %hash, 'Tie::RefHash'; #this part is important
323 $cust_pkg => [ $svc_acct ],
326 $cust_main->insert( \%hash );
328 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
329 be set as the invoicing list (see L<"invoicing_list">). Errors return as
330 expected and rollback the entire transaction; it is not necessary to call
331 check_invoicing_list first. The invoicing_list is set after the records in the
332 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
333 invoicing_list destination to the newly-created svc_acct. Here's an example:
335 $cust_main->insert( {}, [ $email, 'POST' ] );
337 Currently available options are: I<depend_jobnum>, I<noexport>,
338 I<tax_exemption> and I<prospectnum>.
340 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
341 on the supplied jobnum (they will not run until the specific job completes).
342 This can be used to defer provisioning until some action completes (such
343 as running the customer's credit card successfully).
345 The I<noexport> option is deprecated. If I<noexport> is set true, no
346 provisioning jobs (exports) are scheduled. (You can schedule them later with
347 the B<reexport> method.)
349 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
350 of tax names and exemption numbers. FS::cust_main_exemption records will be
351 created and inserted.
353 If I<prospectnum> is set, moves contacts and locations from that prospect.
359 my $cust_pkgs = @_ ? shift : {};
360 my $invoicing_list = @_ ? shift : '';
362 warn "$me insert called with options ".
363 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
366 local $SIG{HUP} = 'IGNORE';
367 local $SIG{INT} = 'IGNORE';
368 local $SIG{QUIT} = 'IGNORE';
369 local $SIG{TERM} = 'IGNORE';
370 local $SIG{TSTP} = 'IGNORE';
371 local $SIG{PIPE} = 'IGNORE';
373 my $oldAutoCommit = $FS::UID::AutoCommit;
374 local $FS::UID::AutoCommit = 0;
377 my $prepay_identifier = '';
378 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
380 if ( $self->payby eq 'PREPAY' ) {
382 $self->payby('BILL');
383 $prepay_identifier = $self->payinfo;
386 warn " looking up prepaid card $prepay_identifier\n"
389 my $error = $self->get_prepay( $prepay_identifier,
390 'amount_ref' => \$amount,
391 'seconds_ref' => \$seconds,
392 'upbytes_ref' => \$upbytes,
393 'downbytes_ref' => \$downbytes,
394 'totalbytes_ref' => \$totalbytes,
397 $dbh->rollback if $oldAutoCommit;
398 #return "error applying prepaid card (transaction rolled back): $error";
402 $payby = 'PREP' if $amount;
404 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
407 $self->payby('BILL');
408 $amount = $self->paid;
413 foreach my $l (qw(bill_location ship_location)) {
415 my $loc = delete $self->hashref->{$l} or return "$l not set";
417 if ( !$loc->locationnum ) {
418 # warn the location that we're going to insert it with no custnum
419 $loc->set(custnum_pending => 1);
420 warn " inserting $l\n"
422 my $error = $loc->insert;
424 $dbh->rollback if $oldAutoCommit;
425 my $label = $l eq 'ship_location' ? 'service' : 'billing';
426 return "$error (in $label location)";
429 } elsif ( $loc->prospectnum ) {
431 $loc->prospectnum('');
432 $loc->set(custnum_pending => 1);
433 my $error = $loc->replace;
435 $dbh->rollback if $oldAutoCommit;
436 my $label = $l eq 'ship_location' ? 'service' : 'billing';
437 return "$error (moving $label location)";
440 } elsif ( ($loc->custnum || 0) > 0 ) {
441 # then it somehow belongs to another customer--shouldn't happen
442 $dbh->rollback if $oldAutoCommit;
443 return "$l belongs to customer ".$loc->custnum;
445 # else it already belongs to this customer
446 # (happens when ship_location is identical to bill_location)
448 $self->set($l.'num', $loc->locationnum);
450 if ( $self->get($l.'num') eq '' ) {
451 $dbh->rollback if $oldAutoCommit;
456 warn " inserting $self\n"
459 $self->signupdate(time) unless $self->signupdate;
461 $self->auto_agent_custid()
462 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
464 my $error = $self->check_payinfo_cardtype
465 || $self->SUPER::insert;
467 $dbh->rollback if $oldAutoCommit;
468 #return "inserting cust_main record (transaction rolled back): $error";
472 # now set cust_location.custnum
473 foreach my $l (qw(bill_location ship_location)) {
474 warn " setting $l.custnum\n"
477 unless ( $loc->custnum ) {
478 $loc->set(custnum => $self->custnum);
479 $error ||= $loc->replace;
483 $dbh->rollback if $oldAutoCommit;
484 return "error setting $l custnum: $error";
488 warn " setting invoicing list\n"
491 if ( $invoicing_list ) {
492 $error = $self->check_invoicing_list( $invoicing_list );
494 $dbh->rollback if $oldAutoCommit;
495 #return "checking invoicing_list (transaction rolled back): $error";
498 $self->invoicing_list( $invoicing_list );
501 warn " setting customer tags\n"
504 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
505 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
506 'custnum' => $self->custnum };
507 my $error = $cust_tag->insert;
509 $dbh->rollback if $oldAutoCommit;
514 my $prospectnum = delete $options{'prospectnum'};
515 if ( $prospectnum ) {
517 warn " moving contacts and locations from prospect $prospectnum\n"
521 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
522 unless ( $prospect_main ) {
523 $dbh->rollback if $oldAutoCommit;
524 return "Unknown prospectnum $prospectnum";
526 $prospect_main->custnum($self->custnum);
527 $prospect_main->disabled('Y');
528 my $error = $prospect_main->replace;
530 $dbh->rollback if $oldAutoCommit;
534 my @contact = $prospect_main->contact;
535 my @cust_location = $prospect_main->cust_location;
536 my @qual = $prospect_main->qual;
538 foreach my $r ( @contact, @cust_location, @qual ) {
540 $r->custnum($self->custnum);
541 my $error = $r->replace;
543 $dbh->rollback if $oldAutoCommit;
550 # validate card (needs custnum already set)
551 if ( $self->payby =~ /^(CARD|DCRD)$/
552 && $conf->exists('business-onlinepayment-verification') ) {
553 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
555 $dbh->rollback if $oldAutoCommit;
560 warn " setting contacts\n"
563 if ( my $contact = delete $options{'contact'} ) {
565 foreach my $c ( @$contact ) {
566 $c->custnum($self->custnum);
567 my $error = $c->insert;
569 $dbh->rollback if $oldAutoCommit;
575 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
577 my $error = $self->process_o2m( 'table' => 'contact',
578 'fields' => FS::contact->cgi_contact_fields,
579 'params' => $contact_params,
582 $dbh->rollback if $oldAutoCommit;
587 warn " setting cust_main_exemption\n"
590 my $tax_exemption = delete $options{'tax_exemption'};
591 if ( $tax_exemption ) {
593 $tax_exemption = { map { $_ => '' } @$tax_exemption }
594 if ref($tax_exemption) eq 'ARRAY';
596 foreach my $taxname ( keys %$tax_exemption ) {
597 my $cust_main_exemption = new FS::cust_main_exemption {
598 'custnum' => $self->custnum,
599 'taxname' => $taxname,
600 'exempt_number' => $tax_exemption->{$taxname},
602 my $error = $cust_main_exemption->insert;
604 $dbh->rollback if $oldAutoCommit;
605 return "inserting cust_main_exemption (transaction rolled back): $error";
610 warn " ordering packages\n"
613 $error = $self->order_pkgs( $cust_pkgs,
615 'seconds_ref' => \$seconds,
616 'upbytes_ref' => \$upbytes,
617 'downbytes_ref' => \$downbytes,
618 'totalbytes_ref' => \$totalbytes,
621 $dbh->rollback if $oldAutoCommit;
626 $dbh->rollback if $oldAutoCommit;
627 return "No svc_acct record to apply pre-paid time";
629 if ( $upbytes || $downbytes || $totalbytes ) {
630 $dbh->rollback if $oldAutoCommit;
631 return "No svc_acct record to apply pre-paid data";
635 warn " inserting initial $payby payment of $amount\n"
637 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
639 $dbh->rollback if $oldAutoCommit;
640 return "inserting payment (transaction rolled back): $error";
644 unless ( $import || $skip_fuzzyfiles ) {
645 warn " queueing fuzzyfiles update\n"
647 $error = $self->queue_fuzzyfiles_update;
649 $dbh->rollback if $oldAutoCommit;
650 return "updating fuzzy search cache: $error";
654 # FS::geocode_Mixin::after_insert or something?
655 if ( $conf->config('tax_district_method') and !$import ) {
656 # if anything non-empty, try to look it up
657 my $queue = new FS::queue {
658 'job' => 'FS::geocode_Mixin::process_district_update',
659 'custnum' => $self->custnum,
661 my $error = $queue->insert( ref($self), $self->custnum );
663 $dbh->rollback if $oldAutoCommit;
664 return "queueing tax district update: $error";
669 warn " exporting\n" if $DEBUG > 1;
671 my $export_args = $options{'export_args'} || [];
674 map qsearch( 'part_export', {exportnum=>$_} ),
675 $conf->config('cust_main-exports'); #, $agentnum
677 foreach my $part_export ( @part_export ) {
678 my $error = $part_export->export_insert($self, @$export_args);
680 $dbh->rollback if $oldAutoCommit;
681 return "exporting to ". $part_export->exporttype.
682 " (transaction rolled back): $error";
686 #foreach my $depend_jobnum ( @$depend_jobnums ) {
687 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
689 # foreach my $jobnum ( @jobnums ) {
690 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
691 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
693 # my $error = $queue->depend_insert($depend_jobnum);
695 # $dbh->rollback if $oldAutoCommit;
696 # return "error queuing job dependancy: $error";
703 #if ( exists $options{'jobnums'} ) {
704 # push @{ $options{'jobnums'} }, @jobnums;
707 warn " insert complete; committing transaction\n"
710 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
715 use File::CounterFile;
716 sub auto_agent_custid {
719 my $format = $conf->config('cust_main-auto_agent_custid');
721 if ( $format eq '1YMMXXXXXXXX' ) {
723 my $counter = new File::CounterFile 'cust_main.agent_custid';
726 my $ym = 100000000000 + time2str('%y%m00000000', time);
727 if ( $ym > $counter->value ) {
728 $counter->{'value'} = $agent_custid = $ym;
729 $counter->{'updated'} = 1;
731 $agent_custid = $counter->inc;
737 die "Unknown cust_main-auto_agent_custid format: $format";
740 $self->agent_custid($agent_custid);
744 =item PACKAGE METHODS
746 Documentation on customer package methods has been moved to
747 L<FS::cust_main::Packages>.
749 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
751 Recharges this (existing) customer with the specified prepaid card (see
752 L<FS::prepay_credit>), specified either by I<identifier> or as an
753 FS::prepay_credit object. If there is an error, returns the error, otherwise
756 Optionally, five scalar references can be passed as well. They will have their
757 values filled in with the amount, number of seconds, and number of upload,
758 download, and total bytes applied by this prepaid card.
762 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
763 #the only place that uses these args
764 sub recharge_prepay {
765 my( $self, $prepay_credit, $amountref, $secondsref,
766 $upbytesref, $downbytesref, $totalbytesref ) = @_;
768 local $SIG{HUP} = 'IGNORE';
769 local $SIG{INT} = 'IGNORE';
770 local $SIG{QUIT} = 'IGNORE';
771 local $SIG{TERM} = 'IGNORE';
772 local $SIG{TSTP} = 'IGNORE';
773 local $SIG{PIPE} = 'IGNORE';
775 my $oldAutoCommit = $FS::UID::AutoCommit;
776 local $FS::UID::AutoCommit = 0;
779 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
781 my $error = $self->get_prepay( $prepay_credit,
782 'amount_ref' => \$amount,
783 'seconds_ref' => \$seconds,
784 'upbytes_ref' => \$upbytes,
785 'downbytes_ref' => \$downbytes,
786 'totalbytes_ref' => \$totalbytes,
788 || $self->increment_seconds($seconds)
789 || $self->increment_upbytes($upbytes)
790 || $self->increment_downbytes($downbytes)
791 || $self->increment_totalbytes($totalbytes)
792 || $self->insert_cust_pay_prepay( $amount,
794 ? $prepay_credit->identifier
799 $dbh->rollback if $oldAutoCommit;
803 if ( defined($amountref) ) { $$amountref = $amount; }
804 if ( defined($secondsref) ) { $$secondsref = $seconds; }
805 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
806 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
807 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
809 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
814 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
816 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
817 specified either by I<identifier> or as an FS::prepay_credit object.
819 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
820 incremented by the values of the prepaid card.
822 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
823 check or set this customer's I<agentnum>.
825 If there is an error, returns the error, otherwise returns false.
831 my( $self, $prepay_credit, %opt ) = @_;
833 local $SIG{HUP} = 'IGNORE';
834 local $SIG{INT} = 'IGNORE';
835 local $SIG{QUIT} = 'IGNORE';
836 local $SIG{TERM} = 'IGNORE';
837 local $SIG{TSTP} = 'IGNORE';
838 local $SIG{PIPE} = 'IGNORE';
840 my $oldAutoCommit = $FS::UID::AutoCommit;
841 local $FS::UID::AutoCommit = 0;
844 unless ( ref($prepay_credit) ) {
846 my $identifier = $prepay_credit;
848 $prepay_credit = qsearchs(
850 { 'identifier' => $identifier },
855 unless ( $prepay_credit ) {
856 $dbh->rollback if $oldAutoCommit;
857 return "Invalid prepaid card: ". $identifier;
862 if ( $prepay_credit->agentnum ) {
863 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
864 $dbh->rollback if $oldAutoCommit;
865 return "prepaid card not valid for agent ". $self->agentnum;
867 $self->agentnum($prepay_credit->agentnum);
870 my $error = $prepay_credit->delete;
872 $dbh->rollback if $oldAutoCommit;
873 return "removing prepay_credit (transaction rolled back): $error";
876 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
877 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
879 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
884 =item increment_upbytes SECONDS
886 Updates this customer's single or primary account (see L<FS::svc_acct>) by
887 the specified number of upbytes. If there is an error, returns the error,
888 otherwise returns false.
892 sub increment_upbytes {
893 _increment_column( shift, 'upbytes', @_);
896 =item increment_downbytes SECONDS
898 Updates this customer's single or primary account (see L<FS::svc_acct>) by
899 the specified number of downbytes. If there is an error, returns the error,
900 otherwise returns false.
904 sub increment_downbytes {
905 _increment_column( shift, 'downbytes', @_);
908 =item increment_totalbytes SECONDS
910 Updates this customer's single or primary account (see L<FS::svc_acct>) by
911 the specified number of totalbytes. If there is an error, returns the error,
912 otherwise returns false.
916 sub increment_totalbytes {
917 _increment_column( shift, 'totalbytes', @_);
920 =item increment_seconds SECONDS
922 Updates this customer's single or primary account (see L<FS::svc_acct>) by
923 the specified number of seconds. If there is an error, returns the error,
924 otherwise returns false.
928 sub increment_seconds {
929 _increment_column( shift, 'seconds', @_);
932 =item _increment_column AMOUNT
934 Updates this customer's single or primary account (see L<FS::svc_acct>) by
935 the specified number of seconds or bytes. If there is an error, returns
936 the error, otherwise returns false.
940 sub _increment_column {
941 my( $self, $column, $amount ) = @_;
942 warn "$me increment_column called: $column, $amount\n"
945 return '' unless $amount;
947 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
948 $self->ncancelled_pkgs;
951 return 'No packages with primary or single services found'.
952 ' to apply pre-paid time';
953 } elsif ( scalar(@cust_pkg) > 1 ) {
954 #maybe have a way to specify the package/account?
955 return 'Multiple packages found to apply pre-paid time';
958 my $cust_pkg = $cust_pkg[0];
959 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
963 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
966 return 'No account found to apply pre-paid time';
967 } elsif ( scalar(@cust_svc) > 1 ) {
968 return 'Multiple accounts found to apply pre-paid time';
971 my $svc_acct = $cust_svc[0]->svc_x;
972 warn " found service svcnum ". $svc_acct->pkgnum.
973 ' ('. $svc_acct->email. ")\n"
976 $column = "increment_$column";
977 $svc_acct->$column($amount);
981 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
983 Inserts a prepayment in the specified amount for this customer. An optional
984 second argument can specify the prepayment identifier for tracking purposes.
985 If there is an error, returns the error, otherwise returns false.
989 sub insert_cust_pay_prepay {
990 shift->insert_cust_pay('PREP', @_);
993 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
995 Inserts a cash payment in the specified amount for this customer. An optional
996 second argument can specify the payment identifier for tracking purposes.
997 If there is an error, returns the error, otherwise returns false.
1001 sub insert_cust_pay_cash {
1002 shift->insert_cust_pay('CASH', @_);
1005 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1007 Inserts a Western Union payment in the specified amount for this customer. An
1008 optional second argument can specify the prepayment identifier for tracking
1009 purposes. If there is an error, returns the error, otherwise returns false.
1013 sub insert_cust_pay_west {
1014 shift->insert_cust_pay('WEST', @_);
1017 sub insert_cust_pay {
1018 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1019 my $payinfo = scalar(@_) ? shift : '';
1021 my $cust_pay = new FS::cust_pay {
1022 'custnum' => $self->custnum,
1023 'paid' => sprintf('%.2f', $amount),
1024 #'_date' => #date the prepaid card was purchased???
1026 'payinfo' => $payinfo,
1034 This method is deprecated. See the I<depend_jobnum> option to the insert and
1035 order_pkgs methods for a better way to defer provisioning.
1037 Re-schedules all exports by calling the B<reexport> method of all associated
1038 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1039 otherwise returns false.
1046 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1047 "use the depend_jobnum option to insert or order_pkgs to delay export";
1049 local $SIG{HUP} = 'IGNORE';
1050 local $SIG{INT} = 'IGNORE';
1051 local $SIG{QUIT} = 'IGNORE';
1052 local $SIG{TERM} = 'IGNORE';
1053 local $SIG{TSTP} = 'IGNORE';
1054 local $SIG{PIPE} = 'IGNORE';
1056 my $oldAutoCommit = $FS::UID::AutoCommit;
1057 local $FS::UID::AutoCommit = 0;
1060 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1061 my $error = $cust_pkg->reexport;
1063 $dbh->rollback if $oldAutoCommit;
1068 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1073 =item delete [ OPTION => VALUE ... ]
1075 This deletes the customer. If there is an error, returns the error, otherwise
1078 This will completely remove all traces of the customer record. This is not
1079 what you want when a customer cancels service; for that, cancel all of the
1080 customer's packages (see L</cancel>).
1082 If the customer has any uncancelled packages, you need to pass a new (valid)
1083 customer number for those packages to be transferred to, as the "new_customer"
1084 option. Cancelled packages will be deleted. Did I mention that this is NOT
1085 what you want when a customer cancels service and that you really should be
1086 looking at L<FS::cust_pkg/cancel>?
1088 You can't delete a customer with invoices (see L<FS::cust_bill>),
1089 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1090 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1091 set the "delete_financials" option to a true value.
1096 my( $self, %opt ) = @_;
1098 local $SIG{HUP} = 'IGNORE';
1099 local $SIG{INT} = 'IGNORE';
1100 local $SIG{QUIT} = 'IGNORE';
1101 local $SIG{TERM} = 'IGNORE';
1102 local $SIG{TSTP} = 'IGNORE';
1103 local $SIG{PIPE} = 'IGNORE';
1105 my $oldAutoCommit = $FS::UID::AutoCommit;
1106 local $FS::UID::AutoCommit = 0;
1109 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1110 $dbh->rollback if $oldAutoCommit;
1111 return "Can't delete a master agent customer";
1114 #use FS::access_user
1115 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1116 $dbh->rollback if $oldAutoCommit;
1117 return "Can't delete a master employee customer";
1120 tie my %financial_tables, 'Tie::IxHash',
1121 'cust_bill' => 'invoices',
1122 'cust_statement' => 'statements',
1123 'cust_credit' => 'credits',
1124 'cust_pay' => 'payments',
1125 'cust_refund' => 'refunds',
1128 foreach my $table ( keys %financial_tables ) {
1130 my @records = $self->$table();
1132 if ( @records && ! $opt{'delete_financials'} ) {
1133 $dbh->rollback if $oldAutoCommit;
1134 return "Can't delete a customer with ". $financial_tables{$table};
1137 foreach my $record ( @records ) {
1138 my $error = $record->delete;
1140 $dbh->rollback if $oldAutoCommit;
1141 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1147 my @cust_pkg = $self->ncancelled_pkgs;
1149 my $new_custnum = $opt{'new_custnum'};
1150 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1151 $dbh->rollback if $oldAutoCommit;
1152 return "Invalid new customer number: $new_custnum";
1154 foreach my $cust_pkg ( @cust_pkg ) {
1155 my %hash = $cust_pkg->hash;
1156 $hash{'custnum'} = $new_custnum;
1157 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1158 my $error = $new_cust_pkg->replace($cust_pkg,
1159 options => { $cust_pkg->options },
1162 $dbh->rollback if $oldAutoCommit;
1167 my @cancelled_cust_pkg = $self->all_pkgs;
1168 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1169 my $error = $cust_pkg->delete;
1171 $dbh->rollback if $oldAutoCommit;
1176 #cust_tax_adjustment in financials?
1177 #cust_pay_pending? ouch
1179 foreach my $table (qw(
1180 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1181 cust_location cust_main_note cust_tax_adjustment
1182 cust_pay_void cust_pay_batch queue cust_tax_exempt
1184 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1185 my $error = $record->delete;
1187 $dbh->rollback if $oldAutoCommit;
1193 my $sth = $dbh->prepare(
1194 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1196 my $errstr = $dbh->errstr;
1197 $dbh->rollback if $oldAutoCommit;
1200 $sth->execute($self->custnum) or do {
1201 my $errstr = $sth->errstr;
1202 $dbh->rollback if $oldAutoCommit;
1208 my $ticket_dbh = '';
1209 if ($conf->config('ticket_system') eq 'RT_Internal') {
1211 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1212 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1213 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1214 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1217 if ( $ticket_dbh ) {
1219 my $ticket_sth = $ticket_dbh->prepare(
1220 'DELETE FROM Links WHERE Target = ?'
1222 my $errstr = $ticket_dbh->errstr;
1223 $dbh->rollback if $oldAutoCommit;
1226 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1228 my $errstr = $ticket_sth->errstr;
1229 $dbh->rollback if $oldAutoCommit;
1233 #check and see if the customer is the only link on the ticket, and
1234 #if so, set the ticket to deleted status in RT?
1235 #maybe someday, for now this will at least fix tickets not displaying
1239 #delete the customer record
1241 my $error = $self->SUPER::delete;
1243 $dbh->rollback if $oldAutoCommit;
1247 # cust_main exports!
1249 #my $export_args = $options{'export_args'} || [];
1252 map qsearch( 'part_export', {exportnum=>$_} ),
1253 $conf->config('cust_main-exports'); #, $agentnum
1255 foreach my $part_export ( @part_export ) {
1256 my $error = $part_export->export_delete( $self ); #, @$export_args);
1258 $dbh->rollback if $oldAutoCommit;
1259 return "exporting to ". $part_export->exporttype.
1260 " (transaction rolled back): $error";
1264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1269 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1271 This merges this customer into the provided new custnum, and then deletes the
1272 customer. If there is an error, returns the error, otherwise returns false.
1274 The source customer's name, company name, phone numbers, agent,
1275 referring customer, customer class, advertising source, order taker, and
1276 billing information (except balance) are discarded.
1278 All packages are moved to the target customer. Packages with package locations
1279 are preserved. Packages without package locations are moved to a new package
1280 location with the source customer's service/shipping address.
1282 All invoices, statements, payments, credits and refunds are moved to the target
1283 customer. The source customer's balance is added to the target customer.
1285 All notes, attachments, tickets and customer tags are moved to the target
1288 Change history is not currently moved.
1293 my( $self, $new_custnum, %opt ) = @_;
1295 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1297 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1298 or return "Invalid new customer number: $new_custnum";
1300 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1301 if $self->agentnum != $new_cust_main->agentnum
1302 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1304 local $SIG{HUP} = 'IGNORE';
1305 local $SIG{INT} = 'IGNORE';
1306 local $SIG{QUIT} = 'IGNORE';
1307 local $SIG{TERM} = 'IGNORE';
1308 local $SIG{TSTP} = 'IGNORE';
1309 local $SIG{PIPE} = 'IGNORE';
1311 my $oldAutoCommit = $FS::UID::AutoCommit;
1312 local $FS::UID::AutoCommit = 0;
1315 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1316 $dbh->rollback if $oldAutoCommit;
1317 return "Can't merge a master agent customer";
1320 #use FS::access_user
1321 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1322 $dbh->rollback if $oldAutoCommit;
1323 return "Can't merge a master employee customer";
1326 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1327 'status' => { op=>'!=', value=>'done' },
1331 $dbh->rollback if $oldAutoCommit;
1332 return "Can't merge a customer with pending payments";
1335 tie my %financial_tables, 'Tie::IxHash',
1336 'cust_bill' => 'invoices',
1337 'cust_bill_void' => 'voided invoices',
1338 'cust_statement' => 'statements',
1339 'cust_credit' => 'credits',
1340 'cust_credit_void' => 'voided credits',
1341 'cust_pay' => 'payments',
1342 'cust_pay_void' => 'voided payments',
1343 'cust_refund' => 'refunds',
1346 foreach my $table ( keys %financial_tables ) {
1348 my @records = $self->$table();
1350 foreach my $record ( @records ) {
1351 $record->custnum($new_custnum);
1352 my $error = $record->replace;
1354 $dbh->rollback if $oldAutoCommit;
1355 return "Error merging ". $financial_tables{$table}. ": $error\n";
1361 my $name = $self->ship_name; #?
1363 my $locationnum = '';
1364 foreach my $cust_pkg ( $self->all_pkgs ) {
1365 $cust_pkg->custnum($new_custnum);
1367 unless ( $cust_pkg->locationnum ) {
1368 unless ( $locationnum ) {
1369 my $cust_location = new FS::cust_location {
1370 $self->location_hash,
1371 'custnum' => $new_custnum,
1373 my $error = $cust_location->insert;
1375 $dbh->rollback if $oldAutoCommit;
1378 $locationnum = $cust_location->locationnum;
1380 $cust_pkg->locationnum($locationnum);
1383 my $error = $cust_pkg->replace;
1385 $dbh->rollback if $oldAutoCommit;
1389 # add customer (ship) name to svc_phone.phone_name if blank
1390 my @cust_svc = $cust_pkg->cust_svc;
1391 foreach my $cust_svc (@cust_svc) {
1392 my($label, $value, $svcdb) = $cust_svc->label;
1393 next unless $svcdb eq 'svc_phone';
1394 my $svc_phone = $cust_svc->svc_x;
1395 next if $svc_phone->phone_name;
1396 $svc_phone->phone_name($name);
1397 my $error = $svc_phone->replace;
1399 $dbh->rollback if $oldAutoCommit;
1407 # cust_tax_exempt (texas tax exemptions)
1408 # cust_recon (some sort of not-well understood thing for OnPac)
1410 #these are moved over
1411 foreach my $table (qw(
1412 cust_tag cust_location contact cust_attachment cust_main_note
1413 cust_tax_adjustment cust_pay_batch queue
1415 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1416 $record->custnum($new_custnum);
1417 my $error = $record->replace;
1419 $dbh->rollback if $oldAutoCommit;
1425 #these aren't preserved
1426 foreach my $table (qw(
1427 cust_main_exemption cust_main_invoice
1429 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1430 my $error = $record->delete;
1432 $dbh->rollback if $oldAutoCommit;
1439 my $sth = $dbh->prepare(
1440 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1442 my $errstr = $dbh->errstr;
1443 $dbh->rollback if $oldAutoCommit;
1446 $sth->execute($new_custnum, $self->custnum) or do {
1447 my $errstr = $sth->errstr;
1448 $dbh->rollback if $oldAutoCommit;
1454 my $ticket_dbh = '';
1455 if ($conf->config('ticket_system') eq 'RT_Internal') {
1457 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1458 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1459 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1460 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1463 if ( $ticket_dbh ) {
1465 my $ticket_sth = $ticket_dbh->prepare(
1466 'UPDATE Links SET Target = ? WHERE Target = ?'
1468 my $errstr = $ticket_dbh->errstr;
1469 $dbh->rollback if $oldAutoCommit;
1472 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1473 'freeside://freeside/cust_main/'.$self->custnum)
1475 my $errstr = $ticket_sth->errstr;
1476 $dbh->rollback if $oldAutoCommit;
1482 #delete the customer record
1484 my $error = $self->delete;
1486 $dbh->rollback if $oldAutoCommit;
1490 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1495 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1497 Replaces the OLD_RECORD with this one in the database. If there is an error,
1498 returns the error, otherwise returns false.
1500 To change the customer's address, set the pseudo-fields C<bill_location> and
1501 C<ship_location>. The address will still only change if at least one of the
1502 address fields differs from the existing values.
1504 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1505 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1506 expected and rollback the entire transaction; it is not necessary to call
1507 check_invoicing_list first. Here's an example:
1509 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1511 Currently available options are: I<tax_exemption>.
1513 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1514 of tax names and exemption numbers. FS::cust_main_exemption records will be
1515 deleted and inserted as appropriate.
1522 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1524 : $self->replace_old;
1528 warn "$me replace called\n"
1531 my $curuser = $FS::CurrentUser::CurrentUser;
1532 if ( $self->payby eq 'COMP'
1533 && $self->payby ne $old->payby
1534 && ! $curuser->access_right('Complimentary customer')
1537 return "You are not permitted to create complimentary accounts.";
1540 local($ignore_expired_card) = 1
1541 if $old->payby =~ /^(CARD|DCRD)$/
1542 && $self->payby =~ /^(CARD|DCRD)$/
1543 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1545 local($ignore_banned_card) = 1
1546 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1547 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1548 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1550 if ( $self->payby =~ /^(CARD|DCRD)$/
1551 && $old->payinfo ne $self->payinfo
1552 && $old->paymask ne $self->paymask )
1554 my $error = $self->check_payinfo_cardtype;
1555 return $error if $error;
1557 if ( $conf->exists('business-onlinepayment-verification') ) {
1558 #need to standardize paydate for this, false laziness with check
1560 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1561 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1562 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1563 ( $m, $y ) = ( $2, "19$1" );
1564 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1565 ( $m, $y ) = ( $3, "20$2" );
1567 return "Illegal expiration date: ". $self->paydate;
1569 $m = sprintf('%02d',$m);
1570 $self->paydate("$y-$m-01");
1572 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
1573 return $error if $error;
1577 return "Invoicing locale is required"
1580 && $conf->exists('cust_main-require_locale');
1582 local $SIG{HUP} = 'IGNORE';
1583 local $SIG{INT} = 'IGNORE';
1584 local $SIG{QUIT} = 'IGNORE';
1585 local $SIG{TERM} = 'IGNORE';
1586 local $SIG{TSTP} = 'IGNORE';
1587 local $SIG{PIPE} = 'IGNORE';
1589 my $oldAutoCommit = $FS::UID::AutoCommit;
1590 local $FS::UID::AutoCommit = 0;
1593 for my $l (qw(bill_location ship_location)) {
1594 my $old_loc = $old->$l;
1595 my $new_loc = $self->$l;
1597 # find the existing location if there is one
1598 $new_loc->set('custnum' => $self->custnum);
1599 my $error = $new_loc->find_or_insert;
1601 $dbh->rollback if $oldAutoCommit;
1604 $self->set($l.'num', $new_loc->locationnum);
1607 # replace the customer record
1608 my $error = $self->SUPER::replace($old);
1611 $dbh->rollback if $oldAutoCommit;
1615 # now move packages to the new service location
1616 $self->set('ship_location', ''); #flush cache
1617 if ( $old->ship_locationnum and # should only be null during upgrade...
1618 $old->ship_locationnum != $self->ship_locationnum ) {
1619 $error = $old->ship_location->move_to($self->ship_location);
1621 $dbh->rollback if $oldAutoCommit;
1625 # don't move packages based on the billing location, but
1626 # disable it if it's no longer in use
1627 if ( $old->bill_locationnum and
1628 $old->bill_locationnum != $self->bill_locationnum ) {
1629 $error = $old->bill_location->disable_if_unused;
1631 $dbh->rollback if $oldAutoCommit;
1636 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1637 my $invoicing_list = shift @param;
1638 $error = $self->check_invoicing_list( $invoicing_list );
1640 $dbh->rollback if $oldAutoCommit;
1643 $self->invoicing_list( $invoicing_list );
1646 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1648 #this could be more efficient than deleting and re-inserting, if it matters
1649 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1650 my $error = $cust_tag->delete;
1652 $dbh->rollback if $oldAutoCommit;
1656 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1657 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1658 'custnum' => $self->custnum };
1659 my $error = $cust_tag->insert;
1661 $dbh->rollback if $oldAutoCommit;
1668 my %options = @param;
1670 my $tax_exemption = delete $options{'tax_exemption'};
1671 if ( $tax_exemption ) {
1673 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1674 if ref($tax_exemption) eq 'ARRAY';
1676 my %cust_main_exemption =
1677 map { $_->taxname => $_ }
1678 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1680 foreach my $taxname ( keys %$tax_exemption ) {
1682 if ( $cust_main_exemption{$taxname} &&
1683 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1686 delete $cust_main_exemption{$taxname};
1690 my $cust_main_exemption = new FS::cust_main_exemption {
1691 'custnum' => $self->custnum,
1692 'taxname' => $taxname,
1693 'exempt_number' => $tax_exemption->{$taxname},
1695 my $error = $cust_main_exemption->insert;
1697 $dbh->rollback if $oldAutoCommit;
1698 return "inserting cust_main_exemption (transaction rolled back): $error";
1702 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1703 my $error = $cust_main_exemption->delete;
1705 $dbh->rollback if $oldAutoCommit;
1706 return "deleting cust_main_exemption (transaction rolled back): $error";
1712 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1713 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1714 && $self->get('payinfo') !~ /^99\d{14}$/
1716 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1721 # card/check/lec info has changed, want to retry realtime_ invoice events
1722 my $error = $self->retry_realtime;
1724 $dbh->rollback if $oldAutoCommit;
1729 unless ( $import || $skip_fuzzyfiles ) {
1730 $error = $self->queue_fuzzyfiles_update;
1732 $dbh->rollback if $oldAutoCommit;
1733 return "updating fuzzy search cache: $error";
1737 # tax district update in cust_location
1739 # cust_main exports!
1741 my $export_args = $options{'export_args'} || [];
1744 map qsearch( 'part_export', {exportnum=>$_} ),
1745 $conf->config('cust_main-exports'); #, $agentnum
1747 foreach my $part_export ( @part_export ) {
1748 my $error = $part_export->export_replace( $self, $old, @$export_args);
1750 $dbh->rollback if $oldAutoCommit;
1751 return "exporting to ". $part_export->exporttype.
1752 " (transaction rolled back): $error";
1756 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1761 =item queue_fuzzyfiles_update
1763 Used by insert & replace to update the fuzzy search cache
1767 use FS::cust_main::Search;
1768 sub queue_fuzzyfiles_update {
1771 local $SIG{HUP} = 'IGNORE';
1772 local $SIG{INT} = 'IGNORE';
1773 local $SIG{QUIT} = 'IGNORE';
1774 local $SIG{TERM} = 'IGNORE';
1775 local $SIG{TSTP} = 'IGNORE';
1776 local $SIG{PIPE} = 'IGNORE';
1778 my $oldAutoCommit = $FS::UID::AutoCommit;
1779 local $FS::UID::AutoCommit = 0;
1782 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1783 my $queue = new FS::queue {
1784 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1786 my @args = "cust_main.$field", $self->get($field);
1787 my $error = $queue->insert( @args );
1789 $dbh->rollback if $oldAutoCommit;
1790 return "queueing job (transaction rolled back): $error";
1794 my @locations = $self->bill_location;
1795 push @locations, $self->ship_location if $self->has_ship_address;
1796 foreach my $location (@locations) {
1797 my $queue = new FS::queue {
1798 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1800 my @args = 'cust_location.address1', $location->address1;
1801 my $error = $queue->insert( @args );
1803 $dbh->rollback if $oldAutoCommit;
1804 return "queueing job (transaction rolled back): $error";
1808 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1815 Checks all fields to make sure this is a valid customer record. If there is
1816 an error, returns the error, otherwise returns false. Called by the insert
1817 and replace methods.
1824 warn "$me check BEFORE: \n". $self->_dump
1828 $self->ut_numbern('custnum')
1829 || $self->ut_number('agentnum')
1830 || $self->ut_textn('agent_custid')
1831 || $self->ut_number('refnum')
1832 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1833 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1834 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1835 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1836 || $self->ut_textn('custbatch')
1837 || $self->ut_name('last')
1838 || $self->ut_name('first')
1839 || $self->ut_snumbern('signupdate')
1840 || $self->ut_snumbern('birthdate')
1841 || $self->ut_namen('spouse_last')
1842 || $self->ut_namen('spouse_first')
1843 || $self->ut_snumbern('spouse_birthdate')
1844 || $self->ut_snumbern('anniversary_date')
1845 || $self->ut_textn('company')
1846 || $self->ut_textn('ship_company')
1847 || $self->ut_anything('comments')
1848 || $self->ut_numbern('referral_custnum')
1849 || $self->ut_textn('stateid')
1850 || $self->ut_textn('stateid_state')
1851 || $self->ut_textn('invoice_terms')
1852 || $self->ut_floatn('cdr_termination_percentage')
1853 || $self->ut_floatn('credit_limit')
1854 || $self->ut_numbern('billday')
1855 || $self->ut_numbern('prorate_day')
1856 || $self->ut_flag('force_prorate_day')
1857 || $self->ut_flag('edit_subject')
1858 || $self->ut_flag('calling_list_exempt')
1859 || $self->ut_flag('invoice_noemail')
1860 || $self->ut_flag('message_noemail')
1861 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1862 || $self->ut_flag('invoice_ship_address')
1865 foreach (qw(company ship_company)) {
1866 my $company = $self->get($_);
1867 $company =~ s/^\s+//;
1868 $company =~ s/\s+$//;
1869 $company =~ s/\s+/ /g;
1870 $self->set($_, $company);
1873 #barf. need message catalogs. i18n. etc.
1874 $error .= "Please select an advertising source."
1875 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1876 return $error if $error;
1878 return "Unknown agent"
1879 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1881 return "Unknown refnum"
1882 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1884 return "Unknown referring custnum: ". $self->referral_custnum
1885 unless ! $self->referral_custnum
1886 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1888 if ( $self->ss eq '' ) {
1893 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1894 or return "Illegal social security number: ". $self->ss;
1895 $self->ss("$1-$2-$3");
1898 #turn off invoice_ship_address if ship & bill are the same
1899 if ($self->bill_locationnum eq $self->ship_locationnum) {
1900 $self->invoice_ship_address('');
1903 # cust_main_county verification now handled by cust_location check
1906 $self->ut_phonen('daytime', $self->country)
1907 || $self->ut_phonen('night', $self->country)
1908 || $self->ut_phonen('fax', $self->country)
1909 || $self->ut_phonen('mobile', $self->country)
1911 return $error if $error;
1913 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1915 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1918 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1920 : FS::Msgcat::_gettext('daytime');
1921 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1923 : FS::Msgcat::_gettext('night');
1925 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1927 : FS::Msgcat::_gettext('mobile');
1929 return "$daytime_label, $night_label or $mobile_label is required"
1933 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1934 # or return "Illegal payby: ". $self->payby;
1936 FS::payby->can_payby($self->table, $self->payby)
1937 or return "Illegal payby: ". $self->payby;
1939 $error = $self->ut_numbern('paystart_month')
1940 || $self->ut_numbern('paystart_year')
1941 || $self->ut_numbern('payissue')
1942 || $self->ut_textn('paytype')
1944 return $error if $error;
1946 if ( $self->payip eq '' ) {
1949 $error = $self->ut_ip('payip');
1950 return $error if $error;
1953 # If it is encrypted and the private key is not availaible then we can't
1954 # check the credit card.
1955 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1957 # Need some kind of global flag to accept invalid cards, for testing
1959 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1961 my $payinfo = $self->payinfo;
1962 $payinfo =~ s/\D//g;
1963 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1964 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1966 $self->payinfo($payinfo);
1968 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1970 my $cardtype = cardtype($payinfo);
1971 $cardtype = 'Tokenized' if $self->payinfo =~ /^99\d{14}$/; # token
1973 return gettext('unknown_card_type') if $cardtype eq 'Unknown';
1975 $self->set('paycardtype', $cardtype);
1977 unless ( $ignore_banned_card ) {
1978 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1980 if ( $ban->bantype eq 'warn' ) {
1981 #or others depending on value of $ban->reason ?
1982 return '_duplicate_card'.
1983 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1984 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1985 ' (ban# '. $ban->bannum. ')'
1986 unless $self->override_ban_warn;
1988 return 'Banned credit card: banned on '.
1989 time2str('%a %h %o at %r', $ban->_date).
1990 ' by '. $ban->otaker.
1991 ' (ban# '. $ban->bannum. ')';
1996 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1997 if ( $cardtype eq 'American Express card' ) {
1998 $self->paycvv =~ /^(\d{4})$/
1999 or return "CVV2 (CID) for American Express cards is four digits.";
2002 $self->paycvv =~ /^(\d{3})$/
2003 or return "CVV2 (CVC2/CID) is three digits.";
2010 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2012 return "Start date or issue number is required for $cardtype cards"
2013 unless $self->paystart_month && $self->paystart_year or $self->payissue;
2015 return "Start month must be between 1 and 12"
2016 if $self->paystart_month
2017 and $self->paystart_month < 1 || $self->paystart_month > 12;
2019 return "Start year must be 1990 or later"
2020 if $self->paystart_year
2021 and $self->paystart_year < 1990;
2023 return "Issue number must be beween 1 and 99"
2025 and $self->payissue < 1 || $self->payissue > 99;
2028 $self->paystart_month('');
2029 $self->paystart_year('');
2030 $self->payissue('');
2033 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2035 my $payinfo = $self->payinfo;
2036 $payinfo =~ s/[^\d\@\.]//g;
2037 if ( $conf->config('echeck-country') eq 'CA' ) {
2038 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2039 or return 'invalid echeck account@branch.bank';
2040 $payinfo = "$1\@$2.$3";
2041 } elsif ( $conf->config('echeck-country') eq 'US' ) {
2042 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2043 $payinfo = "$1\@$2";
2045 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2046 $payinfo = "$1\@$2";
2048 $self->payinfo($payinfo);
2051 unless ( $ignore_banned_card ) {
2052 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2054 if ( $ban->bantype eq 'warn' ) {
2055 #or others depending on value of $ban->reason ?
2056 return '_duplicate_ach' unless $self->override_ban_warn;
2058 return 'Banned ACH account: banned on '.
2059 time2str('%a %h %o at %r', $ban->_date).
2060 ' by '. $ban->otaker.
2061 ' (ban# '. $ban->bannum. ')';
2066 } elsif ( $self->payby eq 'LECB' ) {
2068 my $payinfo = $self->payinfo;
2069 $payinfo =~ s/\D//g;
2070 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2072 $self->payinfo($payinfo);
2075 } elsif ( $self->payby eq 'BILL' ) {
2077 $error = $self->ut_textn('payinfo');
2078 return "Illegal P.O. number: ". $self->payinfo if $error;
2081 } elsif ( $self->payby eq 'COMP' ) {
2083 my $curuser = $FS::CurrentUser::CurrentUser;
2084 if ( ! $self->custnum
2085 && ! $curuser->access_right('Complimentary customer')
2088 return "You are not permitted to create complimentary accounts."
2091 $error = $self->ut_textn('payinfo');
2092 return "Illegal comp account issuer: ". $self->payinfo if $error;
2095 } elsif ( $self->payby eq 'PREPAY' ) {
2097 my $payinfo = $self->payinfo;
2098 $payinfo =~ s/\W//g; #anything else would just confuse things
2099 $self->payinfo($payinfo);
2100 $error = $self->ut_alpha('payinfo');
2101 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2102 return "Unknown prepayment identifier"
2103 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2106 } elsif ( $self->payby =~ /^CARD|DCRD$/ and $self->paymask ) {
2107 # either ignoring invalid cards, or we can't decrypt the payinfo, but
2108 # try to detect the card type anyway. this never returns failure, so
2109 # the contract of $ignore_invalid_cards is maintained.
2110 $self->set('paycardtype', cardtype($self->paymask));
2113 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2114 return "Expiration date required"
2115 # shouldn't payinfo_check do this?
2116 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2120 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2121 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2122 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2123 ( $m, $y ) = ( $2, "19$1" );
2124 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2125 ( $m, $y ) = ( $3, "20$2" );
2127 return "Illegal expiration date: ". $self->paydate;
2129 $m = sprintf('%02d',$m);
2130 $self->paydate("$y-$m-01");
2131 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2132 return gettext('expired_card')
2134 && !$ignore_expired_card
2135 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2138 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2139 ( ! $conf->exists('require_cardname')
2140 || $self->payby !~ /^(CARD|DCRD)$/ )
2142 $self->payname( $self->first. " ". $self->getfield('last') );
2145 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2146 $self->payname =~ /^([\w \,\.\-\']*)$/
2147 or return gettext('illegal_name'). " payname: ". $self->payname;
2150 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2151 or return gettext('illegal_name'). " payname: ". $self->payname;
2157 return "Please select an invoicing locale"
2160 && $conf->exists('cust_main-require_locale');
2162 return "Please select a customer class"
2163 if ! $self->classnum
2164 && $conf->exists('cust_main-require_classnum');
2166 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2167 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2171 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2173 warn "$me check AFTER: \n". $self->_dump
2176 $self->SUPER::check;
2179 sub check_payinfo_cardtype {
2182 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
2184 my $payinfo = $self->payinfo;
2185 $payinfo =~ s/\D//g;
2187 if ( $payinfo =~ /^99\d{14}$/ ) {
2188 $self->set('paycardtype', 'Tokenized');
2192 my %bop_card_types = map { $_=>1 } values %{ card_types() };
2193 my $cardtype = cardtype($payinfo);
2194 $self->set('paycardtype', $cardtype);
2196 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
2204 Additional checks for replace only.
2209 my ($new,$old) = @_;
2210 #preserve old value if global config is set
2211 if ($old && $conf->exists('invoice-ship_address')) {
2212 $new->invoice_ship_address($old->invoice_ship_address);
2219 Returns a list of fields which have ship_ duplicates.
2224 qw( last first company
2226 address1 address2 city county state zip country
2228 daytime night fax mobile
2232 =item has_ship_address
2234 Returns true if this customer record has a separate shipping address.
2238 sub has_ship_address {
2240 $self->bill_locationnum != $self->ship_locationnum;
2245 Returns a list of key/value pairs, with the following keys: address1,
2246 adddress2, city, county, state, zip, country, district, and geocode. The
2247 shipping address is used if present.
2253 $self->ship_location->location_hash;
2258 Returns all locations (see L<FS::cust_location>) for this customer.
2264 qsearch('cust_location', { 'custnum' => $self->custnum,
2265 'prospectnum' => '' } );
2270 Returns all contacts (see L<FS::contact>) for this customer.
2274 #already used :/ sub contact {
2277 qsearch('contact', { 'custnum' => $self->custnum } );
2282 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2283 and L<FS::cust_pkg>) for this customer, except those on hold.
2285 Returns a list: an empty list on success or a list of errors.
2291 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2296 Unsuspends all suspended packages in the on-hold state (those without setup
2297 dates) for this customer.
2303 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2308 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2310 Returns a list: an empty list on success or a list of errors.
2316 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2319 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2321 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2322 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2323 of a list of pkgparts; the hashref has the following keys:
2327 =item pkgparts - listref of pkgparts
2329 =item (other options are passed to the suspend method)
2334 Returns a list: an empty list on success or a list of errors.
2338 sub suspend_if_pkgpart {
2340 my (@pkgparts, %opt);
2341 if (ref($_[0]) eq 'HASH'){
2342 @pkgparts = @{$_[0]{pkgparts}};
2347 grep { $_->suspend(%opt) }
2348 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2349 $self->unsuspended_pkgs;
2352 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2354 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2355 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2356 instead of a list of pkgparts; the hashref has the following keys:
2360 =item pkgparts - listref of pkgparts
2362 =item (other options are passed to the suspend method)
2366 Returns a list: an empty list on success or a list of errors.
2370 sub suspend_unless_pkgpart {
2372 my (@pkgparts, %opt);
2373 if (ref($_[0]) eq 'HASH'){
2374 @pkgparts = @{$_[0]{pkgparts}};
2379 grep { $_->suspend(%opt) }
2380 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2381 $self->unsuspended_pkgs;
2384 =item cancel [ OPTION => VALUE ... ]
2386 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2387 The cancellation time will be now.
2391 Always returns a list: an empty list on success or a list of errors.
2398 warn "$me cancel called on customer ". $self->custnum. " with options ".
2399 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2401 my @pkgs = $self->ncancelled_pkgs;
2403 $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2406 =item cancel_pkgs OPTIONS
2408 Cancels a specified list of packages. OPTIONS can include:
2412 =item cust_pkg - an arrayref of the packages. Required.
2414 =item time - the cancellation time, used to calculate final bills and
2415 unused-time credits if any. Will be passed through to the bill() and
2416 FS::cust_pkg::cancel() methods.
2418 =item quiet - can be set true to supress email cancellation notices.
2420 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a
2421 reasonnum of an existing reason, or passing a hashref will create a new reason.
2422 The hashref should have the following keys:
2423 typenum - Reason type (see L<FS::reason_type>)
2424 reason - Text of the new reason.
2426 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2427 for the individual packages, parallel to the C<cust_pkg> argument. The
2428 reason and reason_otaker arguments will be taken from those objects.
2430 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2432 =item nobill - can be set true to skip billing if it might otherwise be done.
2437 my( $self, %opt ) = @_;
2439 # we're going to cancel services, which is not reversible
2440 # but on 3.x, don't strictly enforce this
2441 warn "cancel_pkgs should not be run inside a transaction"
2442 if $FS::UID::AutoCommit == 0;
2444 local $FS::UID::AutoCommit = 0;
2446 return ( 'access denied' )
2447 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2449 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2451 #should try decryption (we might have the private key)
2452 # and if not maybe queue a job for the server that does?
2453 return ( "Can't (yet) ban encrypted credit cards" )
2454 if $self->is_encrypted($self->payinfo);
2456 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2457 my $error = $ban->insert;
2465 my @pkgs = @{ delete $opt{'cust_pkg'} };
2466 my $cancel_time = $opt{'time'} || time;
2468 # bill all packages first, so we don't lose usage, service counts for
2469 # bulk billing, etc.
2470 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2472 my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2474 'time' => $cancel_time );
2476 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2478 return ( "Error billing during cancellation: $error" );
2483 $FS::UID::AutoCommit = 1;
2485 # now cancel all services, the same way we would for individual packages.
2486 # if any of them fail, cancel the rest anyway.
2487 my @cust_svc = map { $_->cust_svc } @pkgs;
2488 my @sorted_cust_svc =
2490 sort { $a->[1] <=> $b->[1] }
2491 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2493 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2496 foreach my $cust_svc (@sorted_cust_svc) {
2497 my $part_svc = $cust_svc->part_svc;
2498 next if ( defined($part_svc) and $part_svc->preserve );
2499 my $error = $cust_svc->cancel; # immediate cancel, no date option
2500 push @errors, $error if $error;
2506 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2507 $self->custnum. "\n"
2511 if ($opt{'cust_pkg_reason'}) {
2512 @cprs = @{ delete $opt{'cust_pkg_reason'} };
2518 my $cpr = shift @cprs;
2520 $lopt{'reason'} = $cpr->reasonnum;
2521 $lopt{'reason_otaker'} = $cpr->otaker;
2523 warn "no reason found when canceling package ".$_->pkgnum."\n";
2524 $lopt{'reason'} = '';
2527 my $error = $_->cancel(%lopt);
2528 push @errors, 'pkgnum '.$_->pkgnum.': '.$error if $error;
2534 sub _banned_pay_hashref {
2545 'payby' => $payby2ban{$self->payby},
2546 'payinfo' => $self->payinfo,
2547 #don't ever *search* on reason! #'reason' =>
2551 sub _new_banned_pay_hashref {
2553 my $hr = $self->_banned_pay_hashref;
2554 $hr->{payinfo} = md5_base64($hr->{payinfo});
2560 Returns all notes (see L<FS::cust_main_note>) for this customer.
2565 my($self,$orderby_classnum) = (shift,shift);
2566 my $orderby = "sticky DESC, _date DESC";
2567 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2568 qsearch( 'cust_main_note',
2569 { 'custnum' => $self->custnum },
2571 "ORDER BY $orderby",
2577 Returns the agent (see L<FS::agent>) for this customer.
2583 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2588 Returns the agent name (see L<FS::agent>) for this customer.
2594 $self->agent->agent;
2599 Returns any tags associated with this customer, as FS::cust_tag objects,
2600 or an empty list if there are no tags.
2606 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2611 Returns any tags associated with this customer, as FS::part_tag objects,
2612 or an empty list if there are no tags.
2618 map $_->part_tag, $self->cust_tag;
2624 Returns the customer class, as an FS::cust_class object, or the empty string
2625 if there is no customer class.
2631 if ( $self->classnum ) {
2632 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2640 Returns the customer category name, or the empty string if there is no customer
2647 my $cust_class = $self->cust_class;
2649 ? $cust_class->categoryname
2655 Returns the customer class name, or the empty string if there is no customer
2662 my $cust_class = $self->cust_class;
2664 ? $cust_class->classname
2668 =item BILLING METHODS
2670 Documentation on billing methods has been moved to
2671 L<FS::cust_main::Billing>.
2673 =item REALTIME BILLING METHODS
2675 Documentation on realtime billing methods has been moved to
2676 L<FS::cust_main::Billing_Realtime>.
2680 Removes the I<paycvv> field from the database directly.
2682 If there is an error, returns the error, otherwise returns false.
2688 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2689 or return dbh->errstr;
2690 $sth->execute($self->custnum)
2691 or return $sth->errstr;
2696 =item batch_card OPTION => VALUE...
2698 Adds a payment for this invoice to the pending credit card batch (see
2699 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2700 runs the payment using a realtime gateway.
2702 Options may include:
2704 B<amount>: the amount to be paid; defaults to the customer's balance minus
2705 any payments in transit.
2707 B<payby>: the payment method; defaults to cust_main.payby
2709 B<realtime>: runs this as a realtime payment instead of adding it to a
2712 B<invnum>: sets cust_pay_batch.invnum.
2714 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2715 the billing address for the payment; defaults to the customer's billing
2718 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2719 date, and name; defaults to those fields in cust_main.
2724 my ($self, %options) = @_;
2727 if (exists($options{amount})) {
2728 $amount = $options{amount};
2730 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2733 warn(sprintf("Customer balance %.2f - in transit amount %.2f is <= 0.\n",
2735 $self->in_transit_payments
2740 my $invnum = delete $options{invnum};
2741 my $payby = $options{payby} || $self->payby; #still dubious
2743 if ($options{'realtime'}) {
2744 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2750 my $oldAutoCommit = $FS::UID::AutoCommit;
2751 local $FS::UID::AutoCommit = 0;
2754 #this needs to handle mysql as well as Pg, like svc_acct.pm
2755 #(make it into a common function if folks need to do batching with mysql)
2756 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2757 or return "Cannot lock pay_batch: " . $dbh->errstr;
2761 'payby' => FS::payby->payby2payment($payby),
2763 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2765 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2767 unless ( $pay_batch ) {
2768 $pay_batch = new FS::pay_batch \%pay_batch;
2769 my $error = $pay_batch->insert;
2771 $dbh->rollback if $oldAutoCommit;
2772 die "error creating new batch: $error\n";
2776 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2777 'batchnum' => $pay_batch->batchnum,
2778 'custnum' => $self->custnum,
2781 foreach (qw( address1 address2 city state zip country latitude longitude
2782 payby payinfo paydate payname ))
2784 $options{$_} = '' unless exists($options{$_});
2787 my $loc = $self->bill_location;
2789 my $cust_pay_batch = new FS::cust_pay_batch ( {
2790 'batchnum' => $pay_batch->batchnum,
2791 'invnum' => $invnum || 0, # is there a better value?
2792 # this field should be
2794 # cust_bill_pay_batch now
2795 'custnum' => $self->custnum,
2796 'last' => $self->getfield('last'),
2797 'first' => $self->getfield('first'),
2798 'address1' => $options{address1} || $loc->address1,
2799 'address2' => $options{address2} || $loc->address2,
2800 'city' => $options{city} || $loc->city,
2801 'state' => $options{state} || $loc->state,
2802 'zip' => $options{zip} || $loc->zip,
2803 'country' => $options{country} || $loc->country,
2804 'payby' => $options{payby} || $self->payby,
2805 'payinfo' => $options{payinfo} || $self->payinfo,
2806 'exp' => $options{paydate} || $self->paydate,
2807 'payname' => $options{payname} || $self->payname,
2808 'amount' => $amount, # consolidating
2811 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2812 if $old_cust_pay_batch;
2815 if ($old_cust_pay_batch) {
2816 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2818 $error = $cust_pay_batch->insert;
2822 $dbh->rollback if $oldAutoCommit;
2826 my $unapplied = $self->total_unapplied_credits
2827 + $self->total_unapplied_payments
2828 + $self->in_transit_payments;
2829 foreach my $cust_bill ($self->open_cust_bill) {
2830 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2831 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2832 'invnum' => $cust_bill->invnum,
2833 'paybatchnum' => $cust_pay_batch->paybatchnum,
2834 'amount' => $cust_bill->owed,
2837 if ($unapplied >= $cust_bill_pay_batch->amount){
2838 $unapplied -= $cust_bill_pay_batch->amount;
2841 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2842 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2844 $error = $cust_bill_pay_batch->insert;
2846 $dbh->rollback if $oldAutoCommit;
2851 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2857 Returns the total owed for this customer on all invoices
2858 (see L<FS::cust_bill/owed>).
2864 $self->total_owed_date(2145859200); #12/31/2037
2867 =item total_owed_date TIME
2869 Returns the total owed for this customer on all invoices with date earlier than
2870 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2871 see L<Time::Local> and L<Date::Parse> for conversion functions.
2875 sub total_owed_date {
2879 my $custnum = $self->custnum;
2881 my $owed_sql = FS::cust_bill->owed_sql;
2884 SELECT SUM($owed_sql) FROM cust_bill
2885 WHERE custnum = $custnum
2889 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2893 =item total_owed_pkgnum PKGNUM
2895 Returns the total owed on all invoices for this customer's specific package
2896 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2900 sub total_owed_pkgnum {
2901 my( $self, $pkgnum ) = @_;
2902 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2905 =item total_owed_date_pkgnum TIME PKGNUM
2907 Returns the total owed for this customer's specific package when using
2908 experimental package balances on all invoices with date earlier than
2909 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2910 see L<Time::Local> and L<Date::Parse> for conversion functions.
2914 sub total_owed_date_pkgnum {
2915 my( $self, $time, $pkgnum ) = @_;
2918 foreach my $cust_bill (
2919 grep { $_->_date <= $time }
2920 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2922 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2924 sprintf( "%.2f", $total_bill );
2930 Returns the total amount of all payments.
2937 $total += $_->paid foreach $self->cust_pay;
2938 sprintf( "%.2f", $total );
2941 =item total_unapplied_credits
2943 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2944 customer. See L<FS::cust_credit/credited>.
2946 =item total_credited
2948 Old name for total_unapplied_credits. Don't use.
2952 sub total_credited {
2953 #carp "total_credited deprecated, use total_unapplied_credits";
2954 shift->total_unapplied_credits(@_);
2957 sub total_unapplied_credits {
2960 my $custnum = $self->custnum;
2962 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2965 SELECT SUM($unapplied_sql) FROM cust_credit
2966 WHERE custnum = $custnum
2969 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2973 =item total_unapplied_credits_pkgnum PKGNUM
2975 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2976 customer. See L<FS::cust_credit/credited>.
2980 sub total_unapplied_credits_pkgnum {
2981 my( $self, $pkgnum ) = @_;
2982 my $total_credit = 0;
2983 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2984 sprintf( "%.2f", $total_credit );
2988 =item total_unapplied_payments
2990 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2991 See L<FS::cust_pay/unapplied>.
2995 sub total_unapplied_payments {
2998 my $custnum = $self->custnum;
3000 my $unapplied_sql = FS::cust_pay->unapplied_sql;
3003 SELECT SUM($unapplied_sql) FROM cust_pay
3004 WHERE custnum = $custnum
3007 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3011 =item total_unapplied_payments_pkgnum PKGNUM
3013 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
3014 specific package when using experimental package balances. See
3015 L<FS::cust_pay/unapplied>.
3019 sub total_unapplied_payments_pkgnum {
3020 my( $self, $pkgnum ) = @_;
3021 my $total_unapplied = 0;
3022 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
3023 sprintf( "%.2f", $total_unapplied );
3027 =item total_unapplied_refunds
3029 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3030 customer. See L<FS::cust_refund/unapplied>.
3034 sub total_unapplied_refunds {
3036 my $custnum = $self->custnum;
3038 my $unapplied_sql = FS::cust_refund->unapplied_sql;
3041 SELECT SUM($unapplied_sql) FROM cust_refund
3042 WHERE custnum = $custnum
3045 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3051 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3052 total_unapplied_credits minus total_unapplied_payments).
3058 $self->balance_date_range;
3061 =item balance_date TIME
3063 Returns the balance for this customer, only considering invoices with date
3064 earlier than TIME (total_owed_date minus total_credited minus
3065 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3066 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3073 $self->balance_date_range(shift);
3076 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3078 Returns the balance for this customer, optionally considering invoices with
3079 date earlier than START_TIME, and not later than END_TIME
3080 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3082 Times are specified as SQL fragments or numeric
3083 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
3084 L<Date::Parse> for conversion functions. The empty string can be passed
3085 to disable that time constraint completely.
3087 Accepts the same options as L<balance_date_sql>:
3091 =item unapplied_date
3093 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)
3097 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
3098 time will be ignored. Note that START_TIME and END_TIME only limit the date
3099 range for invoices and I<unapplied> payments, credits, and refunds.
3105 sub balance_date_range {
3107 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3108 ') FROM cust_main WHERE custnum='. $self->custnum;
3109 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
3112 =item balance_pkgnum PKGNUM
3114 Returns the balance for this customer's specific package when using
3115 experimental package balances (total_owed plus total_unrefunded, minus
3116 total_unapplied_credits minus total_unapplied_payments)
3120 sub balance_pkgnum {
3121 my( $self, $pkgnum ) = @_;
3124 $self->total_owed_pkgnum($pkgnum)
3125 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3126 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
3127 - $self->total_unapplied_credits_pkgnum($pkgnum)
3128 - $self->total_unapplied_payments_pkgnum($pkgnum)
3132 =item in_transit_payments
3134 Returns the total of requests for payments for this customer pending in
3135 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3139 sub in_transit_payments {
3141 my $in_transit_payments = 0;
3142 foreach my $pay_batch ( qsearch('pay_batch', {
3145 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3146 'batchnum' => $pay_batch->batchnum,
3147 'custnum' => $self->custnum,
3150 $in_transit_payments += $cust_pay_batch->amount;
3153 sprintf( "%.2f", $in_transit_payments );
3158 Returns a hash of useful information for making a payment.
3168 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3169 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3170 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3174 For credit card transactions:
3186 For electronic check transactions:
3201 $return{balance} = $self->balance;
3203 $return{payname} = $self->payname
3204 || ( $self->first. ' '. $self->get('last') );
3206 $return{$_} = $self->bill_location->$_
3207 for qw(address1 address2 city state zip);
3209 $return{payby} = $self->payby;
3210 $return{stateid_state} = $self->stateid_state;
3212 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3213 $return{card_type} = cardtype($self->payinfo);
3214 $return{payinfo} = $self->paymask;
3216 @return{'month', 'year'} = $self->paydate_monthyear;
3220 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3221 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3222 $return{payinfo1} = $payinfo1;
3223 $return{payinfo2} = $payinfo2;
3224 $return{paytype} = $self->paytype;
3225 $return{paystate} = $self->paystate;
3229 #doubleclick protection
3231 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3237 =item paydate_monthyear
3239 Returns a two-element list consisting of the month and year of this customer's
3240 paydate (credit card expiration date for CARD customers)
3244 sub paydate_monthyear {
3246 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3248 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3257 Returns the exact time in seconds corresponding to the payment method
3258 expiration date. For CARD/DCRD customers this is the end of the month;
3259 for others (COMP is the only other payby that uses paydate) it's the start.
3260 Returns 0 if the paydate is empty or set to the far future.
3266 my ($month, $year) = $self->paydate_monthyear;
3267 return 0 if !$year or $year >= 2037;
3268 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3270 if ( $month == 13 ) {
3274 return timelocal(0,0,0,1,$month-1,$year) - 1;
3277 return timelocal(0,0,0,1,$month-1,$year);
3281 =item paydate_epoch_sql
3283 Class method. Returns an SQL expression to obtain the payment expiration date
3284 as a number of seconds.
3288 # Special expiration date behavior for non-CARD/DCRD customers has been
3289 # carefully preserved. Do we really use that?
3290 sub paydate_epoch_sql {
3292 my $table = shift || 'cust_main';
3293 my ($case1, $case2);
3294 if ( driver_name eq 'Pg' ) {
3295 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3296 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3298 elsif ( lc(driver_name) eq 'mysql' ) {
3299 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3300 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3303 return "CASE WHEN $table.payby IN('CARD','DCRD')
3309 =item tax_exemption TAXNAME
3314 my( $self, $taxname ) = @_;
3316 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3317 'taxname' => $taxname,
3322 =item cust_main_exemption
3326 sub cust_main_exemption {
3328 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3331 =item invoicing_list [ ARRAYREF ]
3333 If an arguement is given, sets these email addresses as invoice recipients
3334 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3335 (except as warnings), so use check_invoicing_list first.
3337 Returns a list of email addresses (with svcnum entries expanded).
3339 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3340 check it without disturbing anything by passing nothing.
3342 This interface may change in the future.
3346 sub invoicing_list {
3347 my( $self, $arrayref ) = @_;
3350 my @cust_main_invoice;
3351 if ( $self->custnum ) {
3352 @cust_main_invoice =
3353 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3355 @cust_main_invoice = ();
3357 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3358 #warn $cust_main_invoice->destnum;
3359 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3360 #warn $cust_main_invoice->destnum;
3361 my $error = $cust_main_invoice->delete;
3362 warn $error if $error;
3365 if ( $self->custnum ) {
3366 @cust_main_invoice =
3367 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3369 @cust_main_invoice = ();
3371 my %seen = map { $_->address => 1 } @cust_main_invoice;
3372 foreach my $address ( @{$arrayref} ) {
3373 next if exists $seen{$address} && $seen{$address};
3374 $seen{$address} = 1;
3375 my $cust_main_invoice = new FS::cust_main_invoice ( {
3376 'custnum' => $self->custnum,
3379 my $error = $cust_main_invoice->insert;
3380 warn $error if $error;
3384 if ( $self->custnum ) {
3386 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3393 =item check_invoicing_list ARRAYREF
3395 Checks these arguements as valid input for the invoicing_list method. If there
3396 is an error, returns the error, otherwise returns false.
3400 sub check_invoicing_list {
3401 my( $self, $arrayref ) = @_;
3403 foreach my $address ( @$arrayref ) {
3405 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3406 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3409 my $cust_main_invoice = new FS::cust_main_invoice ( {
3410 'custnum' => $self->custnum,
3413 my $error = $self->custnum
3414 ? $cust_main_invoice->check
3415 : $cust_main_invoice->checkdest
3417 return $error if $error;
3421 return "Email address required"
3422 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3423 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3428 =item set_default_invoicing_list
3430 Sets the invoicing list to all accounts associated with this customer,
3431 overwriting any previous invoicing list.
3435 sub set_default_invoicing_list {
3437 $self->invoicing_list($self->all_emails);
3442 Returns the email addresses of all accounts provisioned for this customer.
3449 foreach my $cust_pkg ( $self->all_pkgs ) {
3450 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3452 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3453 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3455 $list{$_}=1 foreach map { $_->email } @svc_acct;
3460 =item invoicing_list_addpost
3462 Adds postal invoicing to this customer. If this customer is already configured
3463 to receive postal invoices, does nothing.
3467 sub invoicing_list_addpost {
3469 return if grep { $_ eq 'POST' } $self->invoicing_list;
3470 my @invoicing_list = $self->invoicing_list;
3471 push @invoicing_list, 'POST';
3472 $self->invoicing_list(\@invoicing_list);
3475 =item invoicing_list_emailonly
3477 Returns the list of email invoice recipients (invoicing_list without non-email
3478 destinations such as POST and FAX).
3482 sub invoicing_list_emailonly {
3484 warn "$me invoicing_list_emailonly called"
3486 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3489 =item invoicing_list_emailonly_scalar
3491 Returns the list of email invoice recipients (invoicing_list without non-email
3492 destinations such as POST and FAX) as a comma-separated scalar.
3496 sub invoicing_list_emailonly_scalar {
3498 warn "$me invoicing_list_emailonly_scalar called"
3500 join(', ', $self->invoicing_list_emailonly);
3503 =item contact_list [ CLASSNUM, ... ]
3505 Returns a list of contacts (L<FS::contact> objects) for the customer. If
3506 a list of contact classnums is given, returns only contacts in those
3507 classes. If '0' is given, also returns contacts with no class.
3509 If no arguments are given, returns all contacts for the customer.
3517 select => 'contact.*',
3518 extra_sql => ' WHERE contact.custnum = '.$self->custnum,
3525 push @orwhere, 'contact.classnum is null';
3526 } elsif ( /^\d+$/ ) {
3527 push @classnums, $_;
3529 die "bad classnum argument '$_'";
3534 push @orwhere, 'contact.classnum IN ('.join(',', @classnums).')';
3537 $search->{extra_sql} .= ' AND (' .
3538 join(' OR ', map "( $_ )", @orwhere) .
3545 =item contact_list_email [ CLASSNUM, ... ]
3547 Same as L</contact_list>, but returns email destinations instead of contact
3548 objects. Also accepts 'invoice' as an argument, in which case this will also
3549 return the invoice email address if any.
3553 sub contact_list_email {
3561 push @classnums, $_;
3565 # if the only argument passed was 'invoice' then no classnums are
3566 # intended, so skip this.
3568 my @contacts = $self->contact_list(@classnums);
3569 foreach my $contact (@contacts) {
3570 foreach my $contact_email ($contact->contact_email) {
3571 # unlike on 4.x, we have a separate list of invoice email
3573 # make sure they're not redundant with contact emails
3574 my $dest = $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3575 $emails{ $contact_email->emailaddress } = $dest;
3579 if ( $and_invoice ) {
3580 foreach my $email ($self->invoicing_list_emailonly) {
3581 my $dest = $self->name_short . ' <' . $email . '>';
3582 $emails{ $email } ||= $dest;
3588 =item referral_custnum_cust_main
3590 Returns the customer who referred this customer (or the empty string, if
3591 this customer was not referred).
3593 Note the difference with referral_cust_main method: This method,
3594 referral_custnum_cust_main returns the single customer (if any) who referred
3595 this customer, while referral_cust_main returns an array of customers referred
3600 sub referral_custnum_cust_main {
3602 return '' unless $self->referral_custnum;
3603 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3606 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3608 Returns an array of customers referred by this customer (referral_custnum set
3609 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3610 customers referred by customers referred by this customer and so on, inclusive.
3611 The default behavior is DEPTH 1 (no recursion).
3613 Note the difference with referral_custnum_cust_main method: This method,
3614 referral_cust_main, returns an array of customers referred BY this customer,
3615 while referral_custnum_cust_main returns the single customer (if any) who
3616 referred this customer.
3620 sub referral_cust_main {
3622 my $depth = @_ ? shift : 1;
3623 my $exclude = @_ ? shift : {};
3626 map { $exclude->{$_->custnum}++; $_; }
3627 grep { ! $exclude->{ $_->custnum } }
3628 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3632 map { $_->referral_cust_main($depth-1, $exclude) }
3639 =item referral_cust_main_ncancelled
3641 Same as referral_cust_main, except only returns customers with uncancelled
3646 sub referral_cust_main_ncancelled {
3648 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3651 =item referral_cust_pkg [ DEPTH ]
3653 Like referral_cust_main, except returns a flat list of all unsuspended (and
3654 uncancelled) packages for each customer. The number of items in this list may
3655 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3659 sub referral_cust_pkg {
3661 my $depth = @_ ? shift : 1;
3663 map { $_->unsuspended_pkgs }
3664 grep { $_->unsuspended_pkgs }
3665 $self->referral_cust_main($depth);
3668 =item referring_cust_main
3670 Returns the single cust_main record for the customer who referred this customer
3671 (referral_custnum), or false.
3675 sub referring_cust_main {
3677 return '' unless $self->referral_custnum;
3678 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3681 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3683 Applies a credit to this customer. If there is an error, returns the error,
3684 otherwise returns false.
3686 REASON can be a text string, an FS::reason object, or a scalar reference to
3687 a reasonnum. If a text string, it will be automatically inserted as a new
3688 reason, and a 'reason_type' option must be passed to indicate the
3689 FS::reason_type for the new reason.
3691 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3692 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3693 I<commission_pkgnum>.
3695 Any other options are passed to FS::cust_credit::insert.
3700 my( $self, $amount, $reason, %options ) = @_;
3702 my $cust_credit = new FS::cust_credit {
3703 'custnum' => $self->custnum,
3704 'amount' => $amount,
3707 if ( ref($reason) ) {
3709 if ( ref($reason) eq 'SCALAR' ) {
3710 $cust_credit->reasonnum( $$reason );
3712 $cust_credit->reasonnum( $reason->reasonnum );
3716 $cust_credit->set('reason', $reason)
3719 $cust_credit->$_( delete $options{$_} )
3720 foreach grep exists($options{$_}),
3721 qw( addlinfo eventnum ),
3722 map "commission_$_", qw( agentnum salesnum pkgnum );
3724 $cust_credit->insert(%options);
3728 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3730 Creates a one-time charge for this customer. If there is an error, returns
3731 the error, otherwise returns false.
3733 New-style, with a hashref of options:
3735 my $error = $cust_main->charge(
3739 'start_date' => str2time('7/4/2009'),
3740 'pkg' => 'Description',
3741 'comment' => 'Comment',
3742 'additional' => [], #extra invoice detail
3743 'classnum' => 1, #pkg_class
3745 'setuptax' => '', # or 'Y' for tax exempt
3747 'locationnum'=> 1234, # optional
3750 'taxclass' => 'Tax class',
3753 'taxproduct' => 2, #part_pkg_taxproduct
3754 'override' => {}, #XXX describe
3756 #will be filled in with the new object
3757 'cust_pkg_ref' => \$cust_pkg,
3759 #generate an invoice immediately
3761 'invoice_terms' => '', #with these terms
3767 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3771 #super false laziness w/quotation::charge
3774 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3775 my ( $pkg, $comment, $additional );
3776 my ( $setuptax, $taxclass ); #internal taxes
3777 my ( $taxproduct, $override ); #vendor (CCH) taxes
3779 my $separate_bill = '';
3780 my $cust_pkg_ref = '';
3781 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3783 if ( ref( $_[0] ) ) {
3784 $amount = $_[0]->{amount};
3785 $setup_cost = $_[0]->{setup_cost};
3786 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3787 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3788 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3789 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3790 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3791 : '$'. sprintf("%.2f",$amount);
3792 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3793 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3794 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3795 $additional = $_[0]->{additional} || [];
3796 $taxproduct = $_[0]->{taxproductnum};
3797 $override = { '' => $_[0]->{tax_override} };
3798 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3799 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3800 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3801 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3802 $separate_bill = $_[0]->{separate_bill} || '';
3808 $pkg = @_ ? shift : 'One-time charge';
3809 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3811 $taxclass = @_ ? shift : '';
3815 local $SIG{HUP} = 'IGNORE';
3816 local $SIG{INT} = 'IGNORE';
3817 local $SIG{QUIT} = 'IGNORE';
3818 local $SIG{TERM} = 'IGNORE';
3819 local $SIG{TSTP} = 'IGNORE';
3820 local $SIG{PIPE} = 'IGNORE';
3822 my $oldAutoCommit = $FS::UID::AutoCommit;
3823 local $FS::UID::AutoCommit = 0;
3826 my $part_pkg = new FS::part_pkg ( {
3828 'comment' => $comment,
3832 'classnum' => ( $classnum ? $classnum : '' ),
3833 'setuptax' => $setuptax,
3834 'taxclass' => $taxclass,
3835 'taxproductnum' => $taxproduct,
3836 'setup_cost' => $setup_cost,
3839 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3840 ( 0 .. @$additional - 1 )
3842 'additional_count' => scalar(@$additional),
3843 'setup_fee' => $amount,
3846 my $error = $part_pkg->insert( options => \%options,
3847 tax_overrides => $override,
3850 $dbh->rollback if $oldAutoCommit;
3854 my $pkgpart = $part_pkg->pkgpart;
3855 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3856 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3857 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3858 $error = $type_pkgs->insert;
3860 $dbh->rollback if $oldAutoCommit;
3865 my $cust_pkg = new FS::cust_pkg ( {
3866 'custnum' => $self->custnum,
3867 'pkgpart' => $pkgpart,
3868 'quantity' => $quantity,
3869 'start_date' => $start_date,
3870 'no_auto' => $no_auto,
3871 'separate_bill' => $separate_bill,
3872 'locationnum'=> $locationnum,
3875 $error = $cust_pkg->insert;
3877 $dbh->rollback if $oldAutoCommit;
3879 } elsif ( $cust_pkg_ref ) {
3880 ${$cust_pkg_ref} = $cust_pkg;
3884 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3885 'pkg_list' => [ $cust_pkg ],
3888 $dbh->rollback if $oldAutoCommit;
3893 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3898 #=item charge_postal_fee
3900 #Applies a one time charge this customer. If there is an error,
3901 #returns the error, returns the cust_pkg charge object or false
3902 #if there was no charge.
3906 # This should be a customer event. For that to work requires that bill
3907 # also be a customer event.
3909 sub charge_postal_fee {
3912 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3913 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3915 my $cust_pkg = new FS::cust_pkg ( {
3916 'custnum' => $self->custnum,
3917 'pkgpart' => $pkgpart,
3921 my $error = $cust_pkg->insert;
3922 $error ? $error : $cust_pkg;
3925 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3927 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3929 Optionally, a list or hashref of additional arguments to the qsearch call can
3936 my $opt = ref($_[0]) ? shift : { @_ };
3938 #return $self->num_cust_bill unless wantarray || keys %$opt;
3940 $opt->{'table'} = 'cust_bill';
3941 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3942 $opt->{'hashref'}{'custnum'} = $self->custnum;
3943 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3945 map { $_ } #behavior of sort undefined in scalar context
3946 sort { $a->_date <=> $b->_date }
3950 =item open_cust_bill
3952 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3957 sub open_cust_bill {
3961 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3967 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3969 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3973 sub legacy_cust_bill {
3976 #return $self->num_legacy_cust_bill unless wantarray;
3978 map { $_ } #behavior of sort undefined in scalar context
3979 sort { $a->_date <=> $b->_date }
3980 qsearch({ 'table' => 'legacy_cust_bill',
3981 'hashref' => { 'custnum' => $self->custnum, },
3982 'order_by' => 'ORDER BY _date ASC',
3986 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3988 Returns all the statements (see L<FS::cust_statement>) for this customer.
3990 Optionally, a list or hashref of additional arguments to the qsearch call can
3995 =item cust_bill_void
3997 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
4001 sub cust_bill_void {
4004 map { $_ } #return $self->num_cust_bill_void unless wantarray;
4005 sort { $a->_date <=> $b->_date }
4006 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
4009 sub cust_statement {
4011 my $opt = ref($_[0]) ? shift : { @_ };
4013 #return $self->num_cust_statement unless wantarray || keys %$opt;
4015 $opt->{'table'} = 'cust_statement';
4016 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4017 $opt->{'hashref'}{'custnum'} = $self->custnum;
4018 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
4020 map { $_ } #behavior of sort undefined in scalar context
4021 sort { $a->_date <=> $b->_date }
4025 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
4027 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
4029 Optionally, a list or hashref of additional arguments to the qsearch call can
4030 be passed following the SVCDB.
4037 if ( ! $svcdb =~ /^svc_\w+$/ ) {
4038 warn "$me svc_x requires a svcdb";
4041 my $opt = ref($_[0]) ? shift : { @_ };
4043 $opt->{'table'} = $svcdb;
4044 $opt->{'addl_from'} =
4045 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
4046 ($opt->{'addl_from'} || '');
4048 my $custnum = $self->custnum;
4049 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
4050 my $where = "cust_pkg.custnum = $custnum";
4052 my $extra_sql = $opt->{'extra_sql'} || '';
4053 if ( keys %{ $opt->{'hashref'} } ) {
4054 $extra_sql = " AND $where $extra_sql";
4057 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
4058 $extra_sql = "WHERE $where AND $1";
4061 $extra_sql = "WHERE $where $extra_sql";
4064 $opt->{'extra_sql'} = $extra_sql;
4069 # required for use as an eventtable;
4072 $self->svc_x('svc_acct', @_);
4077 Returns all the credits (see L<FS::cust_credit>) for this customer.
4083 map { $_ } #return $self->num_cust_credit unless wantarray;
4084 sort { $a->_date <=> $b->_date }
4085 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4088 =item cust_credit_pkgnum
4090 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
4091 package when using experimental package balances.
4095 sub cust_credit_pkgnum {
4096 my( $self, $pkgnum ) = @_;
4097 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
4098 sort { $a->_date <=> $b->_date }
4099 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
4100 'pkgnum' => $pkgnum,
4105 =item cust_credit_void
4107 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
4111 sub cust_credit_void {
4114 sort { $a->_date <=> $b->_date }
4115 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
4120 Returns all the payments (see L<FS::cust_pay>) for this customer.
4126 my $opt = ref($_[0]) ? shift : { @_ };
4128 return $self->num_cust_pay unless wantarray || keys %$opt;
4130 $opt->{'table'} = 'cust_pay';
4131 $opt->{'hashref'}{'custnum'} = $self->custnum;
4133 map { $_ } #behavior of sort undefined in scalar context
4134 sort { $a->_date <=> $b->_date }
4141 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
4142 called automatically when the cust_pay method is used in a scalar context.
4148 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
4149 my $sth = dbh->prepare($sql) or die dbh->errstr;
4150 $sth->execute($self->custnum) or die $sth->errstr;
4151 $sth->fetchrow_arrayref->[0];
4154 =item unapplied_cust_pay
4156 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
4160 sub unapplied_cust_pay {
4164 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
4170 =item cust_pay_pkgnum
4172 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
4173 package when using experimental package balances.
4177 sub cust_pay_pkgnum {
4178 my( $self, $pkgnum ) = @_;
4179 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
4180 sort { $a->_date <=> $b->_date }
4181 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
4182 'pkgnum' => $pkgnum,
4189 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4195 map { $_ } #return $self->num_cust_pay_void unless wantarray;
4196 sort { $a->_date <=> $b->_date }
4197 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4200 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4202 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
4204 Optionally, a list or hashref of additional arguments to the qsearch call can
4209 sub cust_pay_batch {
4211 my $opt = ref($_[0]) ? shift : { @_ };
4213 #return $self->num_cust_statement unless wantarray || keys %$opt;
4215 $opt->{'table'} = 'cust_pay_batch';
4216 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4217 $opt->{'hashref'}{'custnum'} = $self->custnum;
4218 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
4220 map { $_ } #behavior of sort undefined in scalar context
4221 sort { $a->paybatchnum <=> $b->paybatchnum }
4225 =item cust_pay_pending
4227 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
4228 (without status "done").
4232 sub cust_pay_pending {
4234 return $self->num_cust_pay_pending unless wantarray;
4235 sort { $a->_date <=> $b->_date }
4236 qsearch( 'cust_pay_pending', {
4237 'custnum' => $self->custnum,
4238 'status' => { op=>'!=', value=>'done' },
4243 =item cust_pay_pending_attempt
4245 Returns all payment attempts / declined payments for this customer, as pending
4246 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
4247 a corresponding payment (see L<FS::cust_pay>).
4251 sub cust_pay_pending_attempt {
4253 return $self->num_cust_pay_pending_attempt unless wantarray;
4254 sort { $a->_date <=> $b->_date }
4255 qsearch( 'cust_pay_pending', {
4256 'custnum' => $self->custnum,
4263 =item num_cust_pay_pending
4265 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4266 customer (without status "done"). Also called automatically when the
4267 cust_pay_pending method is used in a scalar context.
4271 sub num_cust_pay_pending {
4274 " SELECT COUNT(*) FROM cust_pay_pending ".
4275 " WHERE custnum = ? AND status != 'done' ",
4280 =item num_cust_pay_pending_attempt
4282 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4283 customer, with status "done" but without a corresp. Also called automatically when the
4284 cust_pay_pending method is used in a scalar context.
4288 sub num_cust_pay_pending_attempt {
4291 " SELECT COUNT(*) FROM cust_pay_pending ".
4292 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4299 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4305 map { $_ } #return $self->num_cust_refund unless wantarray;
4306 sort { $a->_date <=> $b->_date }
4307 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4310 =item display_custnum
4312 Returns the displayed customer number for this customer: agent_custid if
4313 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4317 sub display_custnum {
4320 return $self->agent_custid
4321 if $default_agent_custid && $self->agent_custid;
4323 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4327 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
4328 } elsif ( $custnum_display_length ) {
4329 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
4331 return $self->custnum;
4337 Returns a name string for this customer, either "Company (Last, First)" or
4344 my $name = $self->contact;
4345 $name = $self->company. " ($name)" if $self->company;
4349 =item service_contact
4351 Returns the L<FS::contact> object for this customer that has the 'Service'
4352 contact class, or undef if there is no such contact. Deprecated; don't use
4357 sub service_contact {
4359 if ( !exists($self->{service_contact}) ) {
4360 my $classnum = $self->scalar_sql(
4361 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4362 ) || 0; #if it's zero, qsearchs will return nothing
4363 $self->{service_contact} = qsearchs('contact', {
4364 'classnum' => $classnum, 'custnum' => $self->custnum
4367 $self->{service_contact};
4372 Returns a name string for this (service/shipping) contact, either
4373 "Company (Last, First)" or "Last, First".
4380 my $name = $self->ship_contact;
4381 $name = $self->company. " ($name)" if $self->company;
4387 Returns a name string for this customer, either "Company" or "First Last".
4393 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4396 =item ship_name_short
4398 Returns a name string for this (service/shipping) contact, either "Company"
4403 sub ship_name_short {
4405 $self->service_contact
4406 ? $self->ship_contact_firstlast
4412 Returns this customer's full (billing) contact name only, "Last, First"
4418 $self->get('last'). ', '. $self->first;
4423 Returns this customer's full (shipping) contact name only, "Last, First"
4429 my $contact = $self->service_contact || $self;
4430 $contact->get('last') . ', ' . $contact->get('first');
4433 =item contact_firstlast
4435 Returns this customers full (billing) contact name only, "First Last".
4439 sub contact_firstlast {
4441 $self->first. ' '. $self->get('last');
4444 =item ship_contact_firstlast
4446 Returns this customer's full (shipping) contact name only, "First Last".
4450 sub ship_contact_firstlast {
4452 my $contact = $self->service_contact || $self;
4453 $contact->get('first') . ' '. $contact->get('last');
4456 sub bill_country_full {
4458 $self->bill_location->country_full;
4461 sub ship_country_full {
4463 $self->ship_location->country_full;
4466 =item county_state_county [ PREFIX ]
4468 Returns a string consisting of just the county, state and country.
4472 sub county_state_country {
4475 if ( @_ && $_[0] && $self->has_ship_address ) {
4476 $locationnum = $self->ship_locationnum;
4478 $locationnum = $self->bill_locationnum;
4480 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4481 $cust_location->county_state_country;
4484 =item geocode DATA_VENDOR
4486 Returns a value for the customer location as encoded by DATA_VENDOR.
4487 Currently this only makes sense for "CCH" as DATA_VENDOR.
4495 Returns a status string for this customer, currently:
4499 =item prospect - No packages have ever been ordered
4501 =item ordered - Recurring packages all are new (not yet billed).
4503 =item active - One or more recurring packages is active
4505 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4507 =item suspended - All non-cancelled recurring packages are suspended
4509 =item cancelled - All recurring packages are cancelled
4513 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4514 cust_main-status_module configuration option.
4518 sub status { shift->cust_status(@_); }
4522 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
4523 for my $status ( FS::cust_main->statuses() ) {
4524 my $method = $status.'_sql';
4525 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4526 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4527 $sth->execute( ($self->custnum) x $numnum )
4528 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4529 if ( $sth->fetchrow_arrayref->[0] ) {
4530 $self->hashref->{cust_status} = $status;
4536 =item is_status_delay_cancel
4538 Returns true if customer status is 'suspended'
4539 and all suspended cust_pkg return true for
4540 cust_pkg->is_status_delay_cancel.
4542 This is not a real status, this only meant for hacking display
4543 values, because otherwise treating the customer as suspended is
4544 really the whole point of the delay_cancel option.
4548 sub is_status_delay_cancel {
4550 return 0 unless $self->status eq 'suspended';
4551 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4552 return 0 unless $cust_pkg->is_status_delay_cancel;
4557 =item ucfirst_cust_status
4559 =item ucfirst_status
4561 Returns the status with the first character capitalized.
4565 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4567 sub ucfirst_cust_status {
4569 ucfirst($self->cust_status);
4574 Returns a hex triplet color string for this customer's status.
4578 sub statuscolor { shift->cust_statuscolor(@_); }
4580 sub cust_statuscolor {
4582 __PACKAGE__->statuscolors->{$self->cust_status};
4585 =item tickets [ STATUS ]
4587 Returns an array of hashes representing the customer's RT tickets.
4589 An optional status (or arrayref or hashref of statuses) may be specified.
4595 my $status = ( @_ && $_[0] ) ? shift : '';
4597 my $num = $conf->config('cust_main-max_tickets') || 10;
4600 if ( $conf->config('ticket_system') ) {
4601 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4603 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4612 foreach my $priority (
4613 $conf->config('ticket_system-custom_priority_field-values'), ''
4615 last if scalar(@tickets) >= $num;
4617 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4618 $num - scalar(@tickets),
4629 =item appointments [ STATUS ]
4631 Returns an array of hashes representing the customer's RT tickets which
4638 my $status = ( @_ && $_[0] ) ? shift : '';
4640 return () unless $conf->config('ticket_system');
4642 my $queueid = $conf->config('ticket_system-appointment-queueid');
4644 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4653 # Return services representing svc_accts in customer support packages
4654 sub support_services {
4656 my %packages = map { $_ => 1 } $conf->config('support_packages');
4658 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4659 grep { $_->part_svc->svcdb eq 'svc_acct' }
4660 map { $_->cust_svc }
4661 grep { exists $packages{ $_->pkgpart } }
4662 $self->ncancelled_pkgs;
4666 # Return a list of latitude/longitude for one of the services (if any)
4667 sub service_coordinates {
4671 grep { $_->latitude && $_->longitude }
4673 map { $_->cust_svc }
4674 $self->ncancelled_pkgs;
4676 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4681 Returns a masked version of the named field
4686 my ($self,$field) = @_;
4690 'x'x(length($self->getfield($field))-4).
4691 substr($self->getfield($field), (length($self->getfield($field))-4));
4695 =item payment_history
4697 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4698 cust_credit and cust_refund objects. Each hashref has the following fields:
4700 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4702 I<date> - value of _date field, unix timestamp
4704 I<date_pretty> - user-friendly date
4706 I<description> - user-friendly description of item
4708 I<amount> - impact of item on user's balance
4709 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4710 Not to be confused with the native 'amount' field in cust_credit, see below.
4712 I<amount_pretty> - includes money char
4714 I<balance> - customer balance, chronologically as of this item
4716 I<balance_pretty> - includes money char
4718 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4720 I<paid> - amount paid for cust_pay records, undef for other types
4722 I<credit> - amount credited for cust_credit records, undef for other types.
4723 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4725 I<refund> - amount refunded for cust_refund records, undef for other types
4727 The four table-specific keys always have positive values, whether they reflect charges or payments.
4729 The following options may be passed to this method:
4731 I<line_items> - if true, returns charges ('Line item') rather than invoices
4733 I<start_date> - unix timestamp, only include records on or after.
4734 If specified, an item of type 'Previous' will also be included.
4735 It does not have table-specific fields.
4737 I<end_date> - unix timestamp, only include records before
4739 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4741 I<conf> - optional already-loaded FS::Conf object.
4745 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4746 # and also for sending customer statements, which should both be kept customer-friendly.
4747 # If you add anything that shouldn't be passed on through the API or exposed
4748 # to customers, add a new option to include it, don't include it by default
4749 sub payment_history {
4751 my $opt = ref($_[0]) ? $_[0] : { @_ };
4753 my $conf = $$opt{'conf'} || new FS::Conf;
4754 my $money_char = $conf->config("money_char") || '$',
4756 #first load entire history,
4757 #need previous to calculate previous balance
4758 #loading after end_date shouldn't hurt too much?
4760 if ( $$opt{'line_items'} ) {
4762 foreach my $cust_bill ( $self->cust_bill ) {
4765 'type' => 'Line item',
4766 'description' => $_->desc( $self->locale ).
4767 ( $_->sdate && $_->edate
4768 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4769 ' To '. time2str('%d-%b-%Y', $_->edate)
4772 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4773 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4774 'date' => $cust_bill->_date,
4775 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4777 foreach $cust_bill->cust_bill_pkg;
4784 'type' => 'Invoice',
4785 'description' => 'Invoice #'. $_->display_invnum,
4786 'amount' => sprintf('%.2f', $_->charged ),
4787 'charged' => sprintf('%.2f', $_->charged ),
4788 'date' => $_->_date,
4789 'date_pretty' => $self->time2str_local('short', $_->_date ),
4791 foreach $self->cust_bill;
4796 'type' => 'Payment',
4797 'description' => 'Payment', #XXX type
4798 'amount' => sprintf('%.2f', 0 - $_->paid ),
4799 'paid' => sprintf('%.2f', $_->paid ),
4800 'date' => $_->_date,
4801 'date_pretty' => $self->time2str_local('short', $_->_date ),
4803 foreach $self->cust_pay;
4807 'description' => 'Credit', #more info?
4808 'amount' => sprintf('%.2f', 0 -$_->amount ),
4809 'credit' => sprintf('%.2f', $_->amount ),
4810 'date' => $_->_date,
4811 'date_pretty' => $self->time2str_local('short', $_->_date ),
4813 foreach $self->cust_credit;
4817 'description' => 'Refund', #more info? type, like payment?
4818 'amount' => $_->refund,
4819 'refund' => $_->refund,
4820 'date' => $_->_date,
4821 'date_pretty' => $self->time2str_local('short', $_->_date ),
4823 foreach $self->cust_refund;
4825 #put it all in chronological order
4826 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4828 #calculate balance, filter items outside date range
4832 foreach my $item (@history) {
4833 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4834 $balance += $$item{'amount'};
4835 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4836 $previous += $$item{'amount'};
4839 $$item{'balance'} = sprintf("%.2f",$balance);
4840 foreach my $key ( qw(amount balance) ) {
4841 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4846 # start with previous balance, if there was one
4849 'type' => 'Previous',
4850 'description' => 'Previous balance',
4851 'amount' => sprintf("%.2f",$previous),
4852 'balance' => sprintf("%.2f",$previous),
4853 'date' => $$opt{'start_date'},
4854 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4856 #false laziness with above
4857 foreach my $key ( qw(amount balance) ) {
4858 $$item{$key.'_pretty'} = $$item{$key};
4859 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4861 unshift(@out,$item);
4864 @out = reverse @history if $$opt{'reverse_sort'};
4871 =head1 CLASS METHODS
4877 Class method that returns the list of possible status strings for customers
4878 (see L<the status method|/status>). For example:
4880 @statuses = FS::cust_main->statuses();
4886 keys %{ $self->statuscolors };
4889 =item cust_status_sql
4891 Returns an SQL fragment to determine the status of a cust_main record, as a
4896 sub cust_status_sql {
4898 for my $status ( FS::cust_main->statuses() ) {
4899 my $method = $status.'_sql';
4900 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4909 Returns an SQL expression identifying prospective cust_main records (customers
4910 with no packages ever ordered)
4914 use vars qw($select_count_pkgs);
4915 $select_count_pkgs =
4916 "SELECT COUNT(*) FROM cust_pkg
4917 WHERE cust_pkg.custnum = cust_main.custnum";
4919 sub select_count_pkgs_sql {
4924 " 0 = ( $select_count_pkgs ) ";
4929 Returns an SQL expression identifying ordered cust_main records (customers with
4930 no active packages, but recurring packages not yet setup or one time charges
4936 FS::cust_main->none_active_sql.
4937 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4942 Returns an SQL expression identifying active cust_main records (customers with
4943 active recurring packages).
4948 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4951 =item none_active_sql
4953 Returns an SQL expression identifying cust_main records with no active
4954 recurring packages. This includes customers of status prospect, ordered,
4955 inactive, and suspended.
4959 sub none_active_sql {
4960 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4965 Returns an SQL expression identifying inactive cust_main records (customers with
4966 no active recurring packages, but otherwise unsuspended/uncancelled).
4971 FS::cust_main->none_active_sql.
4972 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4978 Returns an SQL expression identifying suspended cust_main records.
4983 sub suspended_sql { susp_sql(@_); }
4985 FS::cust_main->none_active_sql.
4986 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4992 Returns an SQL expression identifying cancelled cust_main records.
4996 sub cancel_sql { shift->cancelled_sql(@_); }
4999 =item uncancelled_sql
5001 Returns an SQL expression identifying un-cancelled cust_main records.
5005 sub uncancelled_sql { uncancel_sql(@_); }
5008 "( NOT (".$self->cancelled_sql.") )"; #sensitive to cust_main-status_module
5013 Returns an SQL fragment to retreive the balance.
5018 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5019 WHERE cust_bill.custnum = cust_main.custnum )
5020 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5021 WHERE cust_pay.custnum = cust_main.custnum )
5022 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5023 WHERE cust_credit.custnum = cust_main.custnum )
5024 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5025 WHERE cust_refund.custnum = cust_main.custnum )
5028 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
5030 Returns an SQL fragment to retreive the balance for this customer, optionally
5031 considering invoices with date earlier than START_TIME, and not
5032 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5033 total_unapplied_payments).
5035 Times are specified as SQL fragments or numeric
5036 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5037 L<Date::Parse> for conversion functions. The empty string can be passed
5038 to disable that time constraint completely.
5040 Available options are:
5044 =item unapplied_date
5046 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)
5051 set to true to remove all customer comparison clauses, for totals
5056 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5061 JOIN clause (typically used with the total option)
5065 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
5066 time will be ignored. Note that START_TIME and END_TIME only limit the date
5067 range for invoices and I<unapplied> payments, credits, and refunds.
5073 sub balance_date_sql {
5074 my( $class, $start, $end, %opt ) = @_;
5076 my $cutoff = $opt{'cutoff'};
5078 my $owed = FS::cust_bill->owed_sql($cutoff);
5079 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
5080 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
5081 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5083 my $j = $opt{'join'} || '';
5085 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5086 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5087 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5088 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5090 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5091 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5092 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5093 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5098 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
5100 Returns an SQL fragment to retreive the total unapplied payments for this
5101 customer, only considering payments with date earlier than START_TIME, and
5102 optionally not later than END_TIME.
5104 Times are specified as SQL fragments or numeric
5105 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5106 L<Date::Parse> for conversion functions. The empty string can be passed
5107 to disable that time constraint completely.
5109 Available options are:
5113 sub unapplied_payments_date_sql {
5114 my( $class, $start, $end, %opt ) = @_;
5116 my $cutoff = $opt{'cutoff'};
5118 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5120 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
5121 'unapplied_date'=>1 );
5123 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
5126 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5128 Helper method for balance_date_sql; name (and usage) subject to change
5129 (suggestions welcome).
5131 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5132 cust_refund, cust_credit or cust_pay).
5134 If TABLE is "cust_bill" or the unapplied_date option is true, only
5135 considers records with date earlier than START_TIME, and optionally not
5136 later than END_TIME .
5140 sub _money_table_where {
5141 my( $class, $table, $start, $end, %opt ) = @_;
5144 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5145 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5146 push @where, "$table._date <= $start" if defined($start) && length($start);
5147 push @where, "$table._date > $end" if defined($end) && length($end);
5149 push @where, @{$opt{'where'}} if $opt{'where'};
5150 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5156 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5157 use FS::cust_main::Search;
5160 FS::cust_main::Search->search(@_);
5175 #warn join('-',keys %$param);
5176 my $fh = $param->{filehandle};
5177 my $agentnum = $param->{agentnum};
5178 my $format = $param->{format};
5180 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
5183 if ( $format eq 'simple' ) {
5184 @fields = qw( custnum agent_custid amount pkg );
5186 die "unknown format $format";
5189 eval "use Text::CSV_XS;";
5192 my $csv = new Text::CSV_XS;
5199 local $SIG{HUP} = 'IGNORE';
5200 local $SIG{INT} = 'IGNORE';
5201 local $SIG{QUIT} = 'IGNORE';
5202 local $SIG{TERM} = 'IGNORE';
5203 local $SIG{TSTP} = 'IGNORE';
5204 local $SIG{PIPE} = 'IGNORE';
5206 my $oldAutoCommit = $FS::UID::AutoCommit;
5207 local $FS::UID::AutoCommit = 0;
5210 #while ( $columns = $csv->getline($fh) ) {
5212 while ( defined($line=<$fh>) ) {
5214 $csv->parse($line) or do {
5215 $dbh->rollback if $oldAutoCommit;
5216 return "can't parse: ". $csv->error_input();
5219 my @columns = $csv->fields();
5220 #warn join('-',@columns);
5223 foreach my $field ( @fields ) {
5224 $row{$field} = shift @columns;
5227 if ( $row{custnum} && $row{agent_custid} ) {
5228 dbh->rollback if $oldAutoCommit;
5229 return "can't specify custnum with agent_custid $row{agent_custid}";
5233 if ( $row{agent_custid} && $agentnum ) {
5234 %hash = ( 'agent_custid' => $row{agent_custid},
5235 'agentnum' => $agentnum,
5239 if ( $row{custnum} ) {
5240 %hash = ( 'custnum' => $row{custnum} );
5243 unless ( scalar(keys %hash) ) {
5244 $dbh->rollback if $oldAutoCommit;
5245 return "can't find customer without custnum or agent_custid and agentnum";
5248 my $cust_main = qsearchs('cust_main', { %hash } );
5249 unless ( $cust_main ) {
5250 $dbh->rollback if $oldAutoCommit;
5251 my $custnum = $row{custnum} || $row{agent_custid};
5252 return "unknown custnum $custnum";
5255 if ( $row{'amount'} > 0 ) {
5256 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5258 $dbh->rollback if $oldAutoCommit;
5262 } elsif ( $row{'amount'} < 0 ) {
5263 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5266 $dbh->rollback if $oldAutoCommit;
5276 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5278 return "Empty file!" unless $imported;
5284 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5286 Deprecated. Use event notification and message templates
5287 (L<FS::msg_template>) instead.
5289 Sends a templated email notification to the customer (see L<Text::Template>).
5291 OPTIONS is a hash and may include
5293 I<from> - the email sender (default is invoice_from)
5295 I<to> - comma-separated scalar or arrayref of recipients
5296 (default is invoicing_list)
5298 I<subject> - The subject line of the sent email notification
5299 (default is "Notice from company_name")
5301 I<extra_fields> - a hashref of name/value pairs which will be substituted
5304 The following variables are vavailable in the template.
5306 I<$first> - the customer first name
5307 I<$last> - the customer last name
5308 I<$company> - the customer company
5309 I<$payby> - a description of the method of payment for the customer
5310 # would be nice to use FS::payby::shortname
5311 I<$payinfo> - the account information used to collect for this customer
5312 I<$expdate> - the expiration of the customer payment in seconds from epoch
5317 my ($self, $template, %options) = @_;
5319 return unless $conf->exists($template);
5321 my $from = $conf->invoice_from_full($self->agentnum)
5322 if $conf->exists('invoice_from', $self->agentnum);
5323 $from = $options{from} if exists($options{from});
5325 my $to = join(',', $self->invoicing_list_emailonly);
5326 $to = $options{to} if exists($options{to});
5328 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5329 if $conf->exists('company_name', $self->agentnum);
5330 $subject = $options{subject} if exists($options{subject});
5332 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5333 SOURCE => [ map "$_\n",
5334 $conf->config($template)]
5336 or die "can't create new Text::Template object: Text::Template::ERROR";
5337 $notify_template->compile()
5338 or die "can't compile template: Text::Template::ERROR";
5340 $FS::notify_template::_template::company_name =
5341 $conf->config('company_name', $self->agentnum);
5342 $FS::notify_template::_template::company_address =
5343 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5345 my $paydate = $self->paydate || '2037-12-31';
5346 $FS::notify_template::_template::first = $self->first;
5347 $FS::notify_template::_template::last = $self->last;
5348 $FS::notify_template::_template::company = $self->company;
5349 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5350 my $payby = $self->payby;
5351 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5352 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5354 #credit cards expire at the end of the month/year of their exp date
5355 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5356 $FS::notify_template::_template::payby = 'credit card';
5357 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5358 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5360 }elsif ($payby eq 'COMP') {
5361 $FS::notify_template::_template::payby = 'complimentary account';
5363 $FS::notify_template::_template::payby = 'current method';
5365 $FS::notify_template::_template::expdate = $expire_time;
5367 for (keys %{$options{extra_fields}}){
5369 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5372 send_email(from => $from,
5374 subject => $subject,
5375 body => $notify_template->fill_in( PACKAGE =>
5376 'FS::notify_template::_template' ),
5381 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5383 Generates a templated notification to the customer (see L<Text::Template>).
5385 OPTIONS is a hash and may include
5387 I<extra_fields> - a hashref of name/value pairs which will be substituted
5388 into the template. These values may override values mentioned below
5389 and those from the customer record.
5391 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5393 The following variables are available in the template instead of or in addition
5394 to the fields of the customer record.
5396 I<$payby> - a description of the method of payment for the customer
5397 # would be nice to use FS::payby::shortname
5398 I<$payinfo> - the masked account information used to collect for this customer
5399 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5400 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5404 # a lot like cust_bill::print_latex
5405 sub generate_letter {
5406 my ($self, $template, %options) = @_;
5408 warn "Template $template does not exist" && return
5409 unless $conf->exists($template) || $options{'template_text'};
5411 my $template_source = $options{'template_text'}
5412 ? [ $options{'template_text'} ]
5413 : [ map "$_\n", $conf->config($template) ];
5415 my $letter_template = new Text::Template
5417 SOURCE => $template_source,
5418 DELIMITERS => [ '[@--', '--@]' ],
5420 or die "can't create new Text::Template object: Text::Template::ERROR";
5422 $letter_template->compile()
5423 or die "can't compile template: Text::Template::ERROR";
5425 my %letter_data = map { $_ => $self->$_ } $self->fields;
5426 $letter_data{payinfo} = $self->mask_payinfo;
5428 #my $paydate = $self->paydate || '2037-12-31';
5429 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5431 my $payby = $self->payby;
5432 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5433 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5435 #credit cards expire at the end of the month/year of their exp date
5436 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5437 $letter_data{payby} = 'credit card';
5438 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5439 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5441 }elsif ($payby eq 'COMP') {
5442 $letter_data{payby} = 'complimentary account';
5444 $letter_data{payby} = 'current method';
5446 $letter_data{expdate} = $expire_time;
5448 for (keys %{$options{extra_fields}}){
5449 $letter_data{$_} = $options{extra_fields}->{$_};
5452 unless(exists($letter_data{returnaddress})){
5453 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5454 $self->agent_template)
5456 if ( length($retadd) ) {
5457 $letter_data{returnaddress} = $retadd;
5458 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5459 $letter_data{returnaddress} =
5460 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5464 ( $conf->config('company_name', $self->agentnum),
5465 $conf->config('company_address', $self->agentnum),
5469 $letter_data{returnaddress} = '~';
5473 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5475 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5477 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5479 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5483 ) or die "can't open temp file: $!\n";
5484 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5485 or die "can't write temp file: $!\n";
5487 $letter_data{'logo_file'} = $lh->filename;
5489 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5493 ) or die "can't open temp file: $!\n";
5495 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5497 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5498 return ($1, $letter_data{'logo_file'});
5502 =item print_ps TEMPLATE
5504 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5510 my($file, $lfile) = $self->generate_letter(@_);
5511 my $ps = FS::Misc::generate_ps($file);
5512 unlink($file.'.tex');
5518 =item print TEMPLATE
5520 Prints the filled in template.
5522 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5526 sub queueable_print {
5529 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5530 or die "invalid customer number: " . $opt{custnum};
5532 my $error = $self->print( { 'template' => $opt{template} } );
5533 die $error if $error;
5537 my ($self, $template) = (shift, shift);
5539 [ $self->print_ps($template) ],
5540 'agentnum' => $self->agentnum,
5544 #these three subs should just go away once agent stuff is all config overrides
5546 sub agent_template {
5548 $self->_agent_plandata('agent_templatename');
5551 sub agent_invoice_from {
5553 $self->_agent_plandata('agent_invoice_from');
5556 sub _agent_plandata {
5557 my( $self, $option ) = @_;
5559 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5560 #agent-specific Conf
5562 use FS::part_event::Condition;
5564 my $agentnum = $self->agentnum;
5566 my $regexp = regexp_sql();
5568 my $part_event_option =
5570 'select' => 'part_event_option.*',
5571 'table' => 'part_event_option',
5573 LEFT JOIN part_event USING ( eventpart )
5574 LEFT JOIN part_event_option AS peo_agentnum
5575 ON ( part_event.eventpart = peo_agentnum.eventpart
5576 AND peo_agentnum.optionname = 'agentnum'
5577 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5579 LEFT JOIN part_event_condition
5580 ON ( part_event.eventpart = part_event_condition.eventpart
5581 AND part_event_condition.conditionname = 'cust_bill_age'
5583 LEFT JOIN part_event_condition_option
5584 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5585 AND part_event_condition_option.optionname = 'age'
5588 #'hashref' => { 'optionname' => $option },
5589 #'hashref' => { 'part_event_option.optionname' => $option },
5591 " WHERE part_event_option.optionname = ". dbh->quote($option).
5592 " AND action = 'cust_bill_send_agent' ".
5593 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5594 " AND peo_agentnum.optionname = 'agentnum' ".
5595 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5597 CASE WHEN part_event_condition_option.optionname IS NULL
5599 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5601 , part_event.weight".
5605 unless ( $part_event_option ) {
5606 return $self->agent->invoice_template || ''
5607 if $option eq 'agent_templatename';
5611 $part_event_option->optionvalue;
5615 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5617 Subroutine (not a method), designed to be called from the queue.
5619 Takes a list of options and values.
5621 Pulls up the customer record via the custnum option and calls bill_and_collect.
5626 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5628 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5629 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5631 #without this errors don't get rolled back
5632 $args{'fatal'} = 1; # runs from job queue, will be caught
5634 $cust_main->bill_and_collect( %args );
5637 sub process_bill_and_collect {
5639 my $param = thaw(decode_base64(shift));
5640 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5641 or die "custnum '$param->{custnum}' not found!\n";
5642 $param->{'job'} = $job;
5643 $param->{'fatal'} = 1; # runs from job queue, will be caught
5644 $param->{'retry'} = 1;
5646 $cust_main->bill_and_collect( %$param );
5649 #starting to take quite a while for big dbs
5650 # (JRNL: journaled so it only happens once per database)
5651 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5652 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5653 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5654 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5655 # JRNL leading/trailing spaces in first, last, company
5656 # - otaker upgrade? journal and call it good? (double check to make sure
5657 # we're not still setting otaker here)
5659 #only going to get worse with new location stuff...
5661 sub _upgrade_data { #class method
5662 my ($class, %opts) = @_;
5665 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5668 #this seems to be the only expensive one.. why does it take so long?
5669 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5671 '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';
5672 FS::upgrade_journal->set_done('cust_main__signupdate');
5675 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5677 # fix yyyy-m-dd formatted paydates
5678 if ( driver_name =~ /^mysql/i ) {
5680 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5681 } else { # the SQL standard
5683 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5685 FS::upgrade_journal->set_done('cust_main__paydate');
5688 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5690 push @statements, #fix the weird BILL with a cc# in payinfo problem
5692 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5694 FS::upgrade_journal->set_done('cust_main__payinfo');
5699 foreach my $sql ( @statements ) {
5700 my $sth = dbh->prepare($sql) or die dbh->errstr;
5701 $sth->execute or die $sth->errstr;
5702 #warn ( (time - $t). " seconds\n" );
5706 local($ignore_expired_card) = 1;
5707 local($ignore_banned_card) = 1;
5708 local($skip_fuzzyfiles) = 1;
5709 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5711 FS::cust_main::Location->_upgrade_data(%opts);
5713 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5715 foreach my $cust_main ( qsearch({
5716 'table' => 'cust_main',
5718 'extra_sql' => 'WHERE '.
5720 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5721 qw( first last company )
5724 my $error = $cust_main->replace;
5725 die $error if $error;
5728 FS::upgrade_journal->set_done('cust_main__trimspaces');
5732 $class->_upgrade_otaker(%opts);
5742 The delete method should possibly take an FS::cust_main object reference
5743 instead of a scalar customer number.
5745 Bill and collect options should probably be passed as references instead of a
5748 There should probably be a configuration file with a list of allowed credit
5751 No multiple currency support (probably a larger project than just this module).
5753 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5755 Birthdates rely on negative epoch values.
5757 The payby for card/check batches is broken. With mixed batching, bad
5760 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5764 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5765 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5766 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.