2 use base qw( FS::cust_main::Packages
4 FS::cust_main::NationalID
6 FS::cust_main::Billing_Realtime
7 FS::cust_main::Billing_Batch
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
14 FS::otaker_Mixin FS::cust_main_Mixin
15 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
23 use Scalar::Util qw( blessed );
24 use Time::Local qw(timelocal);
29 use File::Temp; #qw( tempfile );
30 use Business::CreditCard 0.28;
31 use List::Util qw(min);
32 use FS::UID qw( dbh driver_name );
33 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_ps do_print money_pretty card_types );
36 use FS::Msgcat qw(gettext);
43 use FS::cust_bill_void;
44 use FS::legacy_cust_bill;
46 use FS::cust_pay_pending;
47 use FS::cust_pay_void;
48 use FS::cust_pay_batch;
51 use FS::part_referral;
52 use FS::cust_main_county;
53 use FS::cust_location;
56 use FS::cust_main_exemption;
57 use FS::cust_tax_adjustment;
58 use FS::cust_tax_location;
59 use FS::agent_currency;
60 use FS::cust_main_invoice;
62 use FS::prepay_credit;
68 use FS::payment_gateway;
69 use FS::agent_payment_gateway;
71 use FS::cust_main_note;
72 use FS::cust_attachment;
75 use FS::upgrade_journal;
81 # 1 is mostly method/subroutine entry and options
82 # 2 traces progress of some operations
83 # 3 is even more information including possibly sensitive data
85 our $me = '[FS::cust_main]';
88 our $ignore_expired_card = 0;
89 our $ignore_banned_card = 0;
90 our $ignore_invalid_card = 0;
92 our $skip_fuzzyfiles = 0;
94 our $ucfirst_nowarn = 0;
96 #this info is in cust_payby as of 4.x
97 #this and the fields themselves can be removed in 5.x
98 our @encrypted_fields = ('payinfo', 'paycvv');
99 sub nohistory_fields { ('payinfo', 'paycvv'); }
102 our $default_agent_custid;
103 our $custnum_display_length;
104 #ask FS::UID to run this stuff for us later
105 #$FS::UID::callback{'FS::cust_main'} = sub {
106 install_callback FS::UID sub {
107 $conf = new FS::Conf;
108 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
109 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
110 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
115 my ( $hashref, $cache ) = @_;
116 if ( exists $hashref->{'pkgnum'} ) {
117 #@{ $self->{'_pkgnum'} } = ();
118 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
119 $self->{'_pkgnum'} = $subcache;
120 #push @{ $self->{'_pkgnum'} },
121 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
127 FS::cust_main - Object methods for cust_main records
133 $record = new FS::cust_main \%hash;
134 $record = new FS::cust_main { 'column' => 'value' };
136 $error = $record->insert;
138 $error = $new_record->replace($old_record);
140 $error = $record->delete;
142 $error = $record->check;
144 @cust_pkg = $record->all_pkgs;
146 @cust_pkg = $record->ncancelled_pkgs;
148 @cust_pkg = $record->suspended_pkgs;
150 $error = $record->bill;
151 $error = $record->bill %options;
152 $error = $record->bill 'time' => $time;
154 $error = $record->collect;
155 $error = $record->collect %options;
156 $error = $record->collect 'invoice_time' => $time,
161 An FS::cust_main object represents a customer. FS::cust_main inherits from
162 FS::Record. The following fields are currently supported:
168 Primary key (assigned automatically for new customers)
172 Agent (see L<FS::agent>)
176 Advertising source (see L<FS::part_referral>)
188 Cocial security number (optional)
212 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
216 Payment Information (See L<FS::payinfo_Mixin> for data format)
220 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
224 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
228 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
232 Start date month (maestro/solo cards only)
236 Start date year (maestro/solo cards only)
240 Issue number (maestro/solo cards only)
244 Name on card or billing name
248 IP address from which payment information was received
252 Tax exempt, empty or `Y'
256 Order taker (see L<FS::access_user>)
262 =item referral_custnum
264 Referring customer number
268 Enable individual CDR spooling, empty or `Y'
272 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
276 Discourage individual CDR printing, empty or `Y'
280 Allow self-service editing of ticket subjects, empty or 'Y'
282 =item calling_list_exempt
284 Do not call, empty or 'Y'
286 =item invoice_ship_address
288 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
298 Creates a new customer. To add the customer to the database, see L<"insert">.
300 Note that this stores the hash reference, not a distinct copy of the hash it
301 points to. You can ask the object for a copy with the I<hash> method.
305 sub table { 'cust_main'; }
307 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
309 Adds this customer to the database. If there is an error, returns the error,
310 otherwise returns false.
312 Usually the customer's location will not yet exist in the database, and
313 the C<bill_location> and C<ship_location> pseudo-fields must be set to
314 uninserted L<FS::cust_location> objects. These will be inserted and linked
315 (in both directions) to the new customer record. If they're references
316 to the same object, they will become the same location.
318 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
319 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
320 are inserted atomicly, or the transaction is rolled back. Passing an empty
321 hash reference is equivalent to not supplying this parameter. There should be
322 a better explanation of this, but until then, here's an example:
325 tie %hash, 'Tie::RefHash'; #this part is important
327 $cust_pkg => [ $svc_acct ],
330 $cust_main->insert( \%hash );
332 INVOICING_LIST_ARYREF: No longer supported.
334 Currently available options are: I<depend_jobnum>, I<noexport>,
335 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
337 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
338 on the supplied jobnum (they will not run until the specific job completes).
339 This can be used to defer provisioning until some action completes (such
340 as running the customer's credit card successfully).
342 The I<noexport> option is deprecated. If I<noexport> is set true, no
343 provisioning jobs (exports) are scheduled. (You can schedule them later with
344 the B<reexport> method.)
346 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
347 of tax names and exemption numbers. FS::cust_main_exemption records will be
348 created and inserted.
350 If I<prospectnum> is set, moves contacts and locations from that prospect.
352 If I<contact> is set to an arrayref of FS::contact objects, those will be
355 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
356 unset), inserts those new contacts with this new customer. Handles CGI
357 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
359 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
360 new stored payment records with this new customer. Handles CGI parameters
361 for an "m2" multiple entry field as passed by edit/cust_main.cgi
367 my $cust_pkgs = @_ ? shift : {};
369 if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
370 warn "cust_main::insert using deprecated invoicing list argument";
371 $invoicing_list = shift;
374 warn "$me insert called with options ".
375 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
378 local $SIG{HUP} = 'IGNORE';
379 local $SIG{INT} = 'IGNORE';
380 local $SIG{QUIT} = 'IGNORE';
381 local $SIG{TERM} = 'IGNORE';
382 local $SIG{TSTP} = 'IGNORE';
383 local $SIG{PIPE} = 'IGNORE';
385 my $oldAutoCommit = $FS::UID::AutoCommit;
386 local $FS::UID::AutoCommit = 0;
389 my $prepay_identifier = '';
390 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
392 if ( $self->payby eq 'PREPAY' ) {
394 $self->payby(''); #'BILL');
395 $prepay_identifier = $self->payinfo;
398 warn " looking up prepaid card $prepay_identifier\n"
401 my $error = $self->get_prepay( $prepay_identifier,
402 'amount_ref' => \$amount,
403 'seconds_ref' => \$seconds,
404 'upbytes_ref' => \$upbytes,
405 'downbytes_ref' => \$downbytes,
406 'totalbytes_ref' => \$totalbytes,
409 $dbh->rollback if $oldAutoCommit;
410 #return "error applying prepaid card (transaction rolled back): $error";
414 $payby = 'PREP' if $amount;
416 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
419 $self->payby(''); #'BILL');
420 $amount = $self->paid;
425 foreach my $l (qw(bill_location ship_location)) {
427 my $loc = delete $self->hashref->{$l} or next;
429 if ( !$loc->locationnum ) {
430 # warn the location that we're going to insert it with no custnum
431 $loc->set(custnum_pending => 1);
432 warn " inserting $l\n"
434 my $error = $loc->insert;
436 $dbh->rollback if $oldAutoCommit;
437 my $label = $l eq 'ship_location' ? 'service' : 'billing';
438 return "$error (in $label location)";
441 } elsif ( $loc->prospectnum ) {
443 $loc->prospectnum('');
444 $loc->set(custnum_pending => 1);
445 my $error = $loc->replace;
447 $dbh->rollback if $oldAutoCommit;
448 my $label = $l eq 'ship_location' ? 'service' : 'billing';
449 return "$error (moving $label location)";
452 } elsif ( ($loc->custnum || 0) > 0 ) {
453 # then it somehow belongs to another customer--shouldn't happen
454 $dbh->rollback if $oldAutoCommit;
455 return "$l belongs to customer ".$loc->custnum;
457 # else it already belongs to this customer
458 # (happens when ship_location is identical to bill_location)
460 $self->set($l.'num', $loc->locationnum);
462 if ( $self->get($l.'num') eq '' ) {
463 $dbh->rollback if $oldAutoCommit;
468 warn " inserting $self\n"
471 $self->signupdate(time) unless $self->signupdate;
473 $self->auto_agent_custid()
474 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
476 my $error = $self->check_payinfo_cardtype
477 || $self->SUPER::insert;
479 $dbh->rollback if $oldAutoCommit;
480 #return "inserting cust_main record (transaction rolled back): $error";
484 # now set cust_location.custnum
485 foreach my $l (qw(bill_location ship_location)) {
486 warn " setting $l.custnum\n"
488 my $loc = $self->$l or next;
489 unless ( $loc->custnum ) {
490 $loc->set(custnum => $self->custnum);
491 $error ||= $loc->replace;
495 $dbh->rollback if $oldAutoCommit;
496 return "error setting $l custnum: $error";
500 warn " setting customer tags\n"
503 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
504 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
505 'custnum' => $self->custnum };
506 my $error = $cust_tag->insert;
508 $dbh->rollback if $oldAutoCommit;
513 my $prospectnum = delete $options{'prospectnum'};
514 if ( $prospectnum ) {
516 warn " moving contacts and locations from prospect $prospectnum\n"
520 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
521 unless ( $prospect_main ) {
522 $dbh->rollback if $oldAutoCommit;
523 return "Unknown prospectnum $prospectnum";
525 $prospect_main->custnum($self->custnum);
526 $prospect_main->disabled('Y');
527 my $error = $prospect_main->replace;
529 $dbh->rollback if $oldAutoCommit;
533 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
534 my $cust_contact = new FS::cust_contact {
535 'custnum' => $self->custnum,
536 'invoice_dest' => 'Y', # invoice_dest currently not set for prospect contacts
537 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
539 my $error = $cust_contact->insert
540 || $prospect_contact->delete;
542 $dbh->rollback if $oldAutoCommit;
547 my @cust_location = $prospect_main->cust_location;
548 my @qual = $prospect_main->qual;
550 foreach my $r ( @cust_location, @qual ) {
552 $r->custnum($self->custnum);
553 my $error = $r->replace;
555 $dbh->rollback if $oldAutoCommit;
559 # since we set invoice_dest on all migrated prospect contacts (for now),
560 # don't process invoicing_list.
561 delete $options{'invoicing_list'};
562 $invoicing_list = undef;
565 warn " setting contacts\n"
568 $invoicing_list ||= $options{'invoicing_list'};
569 if ( $invoicing_list ) {
571 $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
574 foreach my $dest (@$invoicing_list ) {
575 if ($dest eq 'POST') {
576 $self->set('postal_invoice', 'Y');
579 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
580 if ( $contact_email ) {
581 my $cust_contact = FS::cust_contact->new({
582 contactnum => $contact_email->contactnum,
583 custnum => $self->custnum,
585 $cust_contact->set('invoice_dest', 'Y');
586 my $error = $cust_contact->insert;
588 $dbh->rollback if $oldAutoCommit;
589 return "$error (linking to email address $dest)";
593 # this email address is not yet linked to any contact
594 $email .= ',' if length($email);
600 my $contact = FS::contact->new({
601 'custnum' => $self->get('custnum'),
602 'last' => $self->get('last'),
603 'first' => $self->get('first'),
604 'emailaddress' => $email,
605 'invoice_dest' => 'Y', # yes, you can set this via the contact
607 my $error = $contact->insert;
609 $dbh->rollback if $oldAutoCommit;
615 if ( my $contact = delete $options{'contact'} ) {
617 foreach my $c ( @$contact ) {
618 $c->custnum($self->custnum);
619 my $error = $c->insert;
621 $dbh->rollback if $oldAutoCommit;
627 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
629 my $error = $self->process_o2m( 'table' => 'contact',
630 'fields' => FS::contact->cgi_contact_fields,
631 'params' => $contact_params,
634 $dbh->rollback if $oldAutoCommit;
639 warn " setting cust_payby\n"
642 if ( $options{cust_payby} ) {
644 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
645 $cust_payby->custnum($self->custnum);
646 my $error = $cust_payby->insert;
648 $dbh->rollback if $oldAutoCommit;
653 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
655 my $error = $self->process_o2m(
656 'table' => 'cust_payby',
657 'fields' => FS::cust_payby->cgi_cust_payby_fields,
658 'params' => $cust_payby_params,
659 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
662 $dbh->rollback if $oldAutoCommit;
668 warn " setting cust_main_exemption\n"
671 my $tax_exemption = delete $options{'tax_exemption'};
672 if ( $tax_exemption ) {
674 $tax_exemption = { map { $_ => '' } @$tax_exemption }
675 if ref($tax_exemption) eq 'ARRAY';
677 foreach my $taxname ( keys %$tax_exemption ) {
678 my $cust_main_exemption = new FS::cust_main_exemption {
679 'custnum' => $self->custnum,
680 'taxname' => $taxname,
681 'exempt_number' => $tax_exemption->{$taxname},
683 my $error = $cust_main_exemption->insert;
685 $dbh->rollback if $oldAutoCommit;
686 return "inserting cust_main_exemption (transaction rolled back): $error";
691 warn " ordering packages\n"
694 $error = $self->order_pkgs( $cust_pkgs,
696 'seconds_ref' => \$seconds,
697 'upbytes_ref' => \$upbytes,
698 'downbytes_ref' => \$downbytes,
699 'totalbytes_ref' => \$totalbytes,
702 $dbh->rollback if $oldAutoCommit;
707 $dbh->rollback if $oldAutoCommit;
708 return "No svc_acct record to apply pre-paid time";
710 if ( $upbytes || $downbytes || $totalbytes ) {
711 $dbh->rollback if $oldAutoCommit;
712 return "No svc_acct record to apply pre-paid data";
716 warn " inserting initial $payby payment of $amount\n"
718 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
720 $dbh->rollback if $oldAutoCommit;
721 return "inserting payment (transaction rolled back): $error";
725 unless ( $import || $skip_fuzzyfiles ) {
726 warn " queueing fuzzyfiles update\n"
728 $error = $self->queue_fuzzyfiles_update;
730 $dbh->rollback if $oldAutoCommit;
731 return "updating fuzzy search cache: $error";
735 # FS::geocode_Mixin::after_insert or something?
736 if ( $conf->config('tax_district_method') and !$import ) {
737 # if anything non-empty, try to look it up
738 my $queue = new FS::queue {
739 'job' => 'FS::geocode_Mixin::process_district_update',
740 'custnum' => $self->custnum,
742 my $error = $queue->insert( ref($self), $self->custnum );
744 $dbh->rollback if $oldAutoCommit;
745 return "queueing tax district update: $error";
750 warn " exporting\n" if $DEBUG > 1;
752 my $export_args = $options{'export_args'} || [];
755 map qsearch( 'part_export', {exportnum=>$_} ),
756 $conf->config('cust_main-exports'); #, $agentnum
758 foreach my $part_export ( @part_export ) {
759 my $error = $part_export->export_insert($self, @$export_args);
761 $dbh->rollback if $oldAutoCommit;
762 return "exporting to ". $part_export->exporttype.
763 " (transaction rolled back): $error";
767 #foreach my $depend_jobnum ( @$depend_jobnums ) {
768 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
770 # foreach my $jobnum ( @jobnums ) {
771 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
772 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
774 # my $error = $queue->depend_insert($depend_jobnum);
776 # $dbh->rollback if $oldAutoCommit;
777 # return "error queuing job dependancy: $error";
784 #if ( exists $options{'jobnums'} ) {
785 # push @{ $options{'jobnums'} }, @jobnums;
788 warn " insert complete; committing transaction\n"
791 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
796 use File::CounterFile;
797 sub auto_agent_custid {
800 my $format = $conf->config('cust_main-auto_agent_custid');
802 if ( $format eq '1YMMXXXXXXXX' ) {
804 my $counter = new File::CounterFile 'cust_main.agent_custid';
807 my $ym = 100000000000 + time2str('%y%m00000000', time);
808 if ( $ym > $counter->value ) {
809 $counter->{'value'} = $agent_custid = $ym;
810 $counter->{'updated'} = 1;
812 $agent_custid = $counter->inc;
818 die "Unknown cust_main-auto_agent_custid format: $format";
821 $self->agent_custid($agent_custid);
825 =item PACKAGE METHODS
827 Documentation on customer package methods has been moved to
828 L<FS::cust_main::Packages>.
830 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
832 Recharges this (existing) customer with the specified prepaid card (see
833 L<FS::prepay_credit>), specified either by I<identifier> or as an
834 FS::prepay_credit object. If there is an error, returns the error, otherwise
837 Optionally, five scalar references can be passed as well. They will have their
838 values filled in with the amount, number of seconds, and number of upload,
839 download, and total bytes applied by this prepaid card.
843 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
844 #the only place that uses these args
845 sub recharge_prepay {
846 my( $self, $prepay_credit, $amountref, $secondsref,
847 $upbytesref, $downbytesref, $totalbytesref ) = @_;
849 local $SIG{HUP} = 'IGNORE';
850 local $SIG{INT} = 'IGNORE';
851 local $SIG{QUIT} = 'IGNORE';
852 local $SIG{TERM} = 'IGNORE';
853 local $SIG{TSTP} = 'IGNORE';
854 local $SIG{PIPE} = 'IGNORE';
856 my $oldAutoCommit = $FS::UID::AutoCommit;
857 local $FS::UID::AutoCommit = 0;
860 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
862 my $error = $self->get_prepay( $prepay_credit,
863 'amount_ref' => \$amount,
864 'seconds_ref' => \$seconds,
865 'upbytes_ref' => \$upbytes,
866 'downbytes_ref' => \$downbytes,
867 'totalbytes_ref' => \$totalbytes,
869 || $self->increment_seconds($seconds)
870 || $self->increment_upbytes($upbytes)
871 || $self->increment_downbytes($downbytes)
872 || $self->increment_totalbytes($totalbytes)
873 || $self->insert_cust_pay_prepay( $amount,
875 ? $prepay_credit->identifier
880 $dbh->rollback if $oldAutoCommit;
884 if ( defined($amountref) ) { $$amountref = $amount; }
885 if ( defined($secondsref) ) { $$secondsref = $seconds; }
886 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
887 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
888 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
890 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
895 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
897 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
898 specified either by I<identifier> or as an FS::prepay_credit object.
900 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
901 incremented by the values of the prepaid card.
903 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
904 check or set this customer's I<agentnum>.
906 If there is an error, returns the error, otherwise returns false.
912 my( $self, $prepay_credit, %opt ) = @_;
914 local $SIG{HUP} = 'IGNORE';
915 local $SIG{INT} = 'IGNORE';
916 local $SIG{QUIT} = 'IGNORE';
917 local $SIG{TERM} = 'IGNORE';
918 local $SIG{TSTP} = 'IGNORE';
919 local $SIG{PIPE} = 'IGNORE';
921 my $oldAutoCommit = $FS::UID::AutoCommit;
922 local $FS::UID::AutoCommit = 0;
925 unless ( ref($prepay_credit) ) {
927 my $identifier = $prepay_credit;
929 $prepay_credit = qsearchs(
931 { 'identifier' => $identifier },
936 unless ( $prepay_credit ) {
937 $dbh->rollback if $oldAutoCommit;
938 return "Invalid prepaid card: ". $identifier;
943 if ( $prepay_credit->agentnum ) {
944 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
945 $dbh->rollback if $oldAutoCommit;
946 return "prepaid card not valid for agent ". $self->agentnum;
948 $self->agentnum($prepay_credit->agentnum);
951 my $error = $prepay_credit->delete;
953 $dbh->rollback if $oldAutoCommit;
954 return "removing prepay_credit (transaction rolled back): $error";
957 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
958 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
960 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
965 =item increment_upbytes SECONDS
967 Updates this customer's single or primary account (see L<FS::svc_acct>) by
968 the specified number of upbytes. If there is an error, returns the error,
969 otherwise returns false.
973 sub increment_upbytes {
974 _increment_column( shift, 'upbytes', @_);
977 =item increment_downbytes SECONDS
979 Updates this customer's single or primary account (see L<FS::svc_acct>) by
980 the specified number of downbytes. If there is an error, returns the error,
981 otherwise returns false.
985 sub increment_downbytes {
986 _increment_column( shift, 'downbytes', @_);
989 =item increment_totalbytes SECONDS
991 Updates this customer's single or primary account (see L<FS::svc_acct>) by
992 the specified number of totalbytes. If there is an error, returns the error,
993 otherwise returns false.
997 sub increment_totalbytes {
998 _increment_column( shift, 'totalbytes', @_);
1001 =item increment_seconds SECONDS
1003 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1004 the specified number of seconds. If there is an error, returns the error,
1005 otherwise returns false.
1009 sub increment_seconds {
1010 _increment_column( shift, 'seconds', @_);
1013 =item _increment_column AMOUNT
1015 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1016 the specified number of seconds or bytes. If there is an error, returns
1017 the error, otherwise returns false.
1021 sub _increment_column {
1022 my( $self, $column, $amount ) = @_;
1023 warn "$me increment_column called: $column, $amount\n"
1026 return '' unless $amount;
1028 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1029 $self->ncancelled_pkgs;
1031 if ( ! @cust_pkg ) {
1032 return 'No packages with primary or single services found'.
1033 ' to apply pre-paid time';
1034 } elsif ( scalar(@cust_pkg) > 1 ) {
1035 #maybe have a way to specify the package/account?
1036 return 'Multiple packages found to apply pre-paid time';
1039 my $cust_pkg = $cust_pkg[0];
1040 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1044 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1046 if ( ! @cust_svc ) {
1047 return 'No account found to apply pre-paid time';
1048 } elsif ( scalar(@cust_svc) > 1 ) {
1049 return 'Multiple accounts found to apply pre-paid time';
1052 my $svc_acct = $cust_svc[0]->svc_x;
1053 warn " found service svcnum ". $svc_acct->pkgnum.
1054 ' ('. $svc_acct->email. ")\n"
1057 $column = "increment_$column";
1058 $svc_acct->$column($amount);
1062 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1064 Inserts a prepayment in the specified amount for this customer. An optional
1065 second argument can specify the prepayment identifier for tracking purposes.
1066 If there is an error, returns the error, otherwise returns false.
1070 sub insert_cust_pay_prepay {
1071 shift->insert_cust_pay('PREP', @_);
1074 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1076 Inserts a cash payment in the specified amount for this customer. An optional
1077 second argument can specify the payment identifier for tracking purposes.
1078 If there is an error, returns the error, otherwise returns false.
1082 sub insert_cust_pay_cash {
1083 shift->insert_cust_pay('CASH', @_);
1086 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1088 Inserts a Western Union payment in the specified amount for this customer. An
1089 optional second argument can specify the prepayment identifier for tracking
1090 purposes. If there is an error, returns the error, otherwise returns false.
1094 sub insert_cust_pay_west {
1095 shift->insert_cust_pay('WEST', @_);
1098 sub insert_cust_pay {
1099 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1100 my $payinfo = scalar(@_) ? shift : '';
1102 my $cust_pay = new FS::cust_pay {
1103 'custnum' => $self->custnum,
1104 'paid' => sprintf('%.2f', $amount),
1105 #'_date' => #date the prepaid card was purchased???
1107 'payinfo' => $payinfo,
1113 =item delete [ OPTION => VALUE ... ]
1115 This deletes the customer. If there is an error, returns the error, otherwise
1118 This will completely remove all traces of the customer record. This is not
1119 what you want when a customer cancels service; for that, cancel all of the
1120 customer's packages (see L</cancel>).
1122 If the customer has any uncancelled packages, you need to pass a new (valid)
1123 customer number for those packages to be transferred to, as the "new_customer"
1124 option. Cancelled packages will be deleted. Did I mention that this is NOT
1125 what you want when a customer cancels service and that you really should be
1126 looking at L<FS::cust_pkg/cancel>?
1128 You can't delete a customer with invoices (see L<FS::cust_bill>),
1129 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1130 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1131 set the "delete_financials" option to a true value.
1136 my( $self, %opt ) = @_;
1138 local $SIG{HUP} = 'IGNORE';
1139 local $SIG{INT} = 'IGNORE';
1140 local $SIG{QUIT} = 'IGNORE';
1141 local $SIG{TERM} = 'IGNORE';
1142 local $SIG{TSTP} = 'IGNORE';
1143 local $SIG{PIPE} = 'IGNORE';
1145 my $oldAutoCommit = $FS::UID::AutoCommit;
1146 local $FS::UID::AutoCommit = 0;
1149 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1150 $dbh->rollback if $oldAutoCommit;
1151 return "Can't delete a master agent customer";
1154 #use FS::access_user
1155 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1156 $dbh->rollback if $oldAutoCommit;
1157 return "Can't delete a master employee customer";
1160 tie my %financial_tables, 'Tie::IxHash',
1161 'cust_bill' => 'invoices',
1162 'cust_statement' => 'statements',
1163 'cust_credit' => 'credits',
1164 'cust_pay' => 'payments',
1165 'cust_refund' => 'refunds',
1168 foreach my $table ( keys %financial_tables ) {
1170 my @records = $self->$table();
1172 if ( @records && ! $opt{'delete_financials'} ) {
1173 $dbh->rollback if $oldAutoCommit;
1174 return "Can't delete a customer with ". $financial_tables{$table};
1177 foreach my $record ( @records ) {
1178 my $error = $record->delete;
1180 $dbh->rollback if $oldAutoCommit;
1181 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1187 my @cust_pkg = $self->ncancelled_pkgs;
1189 my $new_custnum = $opt{'new_custnum'};
1190 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1191 $dbh->rollback if $oldAutoCommit;
1192 return "Invalid new customer number: $new_custnum";
1194 foreach my $cust_pkg ( @cust_pkg ) {
1195 my %hash = $cust_pkg->hash;
1196 $hash{'custnum'} = $new_custnum;
1197 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1198 my $error = $new_cust_pkg->replace($cust_pkg,
1199 options => { $cust_pkg->options },
1202 $dbh->rollback if $oldAutoCommit;
1207 my @cancelled_cust_pkg = $self->all_pkgs;
1208 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1209 my $error = $cust_pkg->delete;
1211 $dbh->rollback if $oldAutoCommit;
1216 #cust_tax_adjustment in financials?
1217 #cust_pay_pending? ouch
1218 foreach my $table (qw(
1219 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1220 cust_payby cust_location cust_main_note cust_tax_adjustment
1221 cust_pay_void cust_pay_batch queue cust_tax_exempt
1223 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1224 my $error = $record->delete;
1226 $dbh->rollback if $oldAutoCommit;
1232 my $sth = $dbh->prepare(
1233 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1235 my $errstr = $dbh->errstr;
1236 $dbh->rollback if $oldAutoCommit;
1239 $sth->execute($self->custnum) or do {
1240 my $errstr = $sth->errstr;
1241 $dbh->rollback if $oldAutoCommit;
1247 my $ticket_dbh = '';
1248 if ($conf->config('ticket_system') eq 'RT_Internal') {
1250 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1251 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1252 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1253 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1256 if ( $ticket_dbh ) {
1258 my $ticket_sth = $ticket_dbh->prepare(
1259 'DELETE FROM Links WHERE Target = ?'
1261 my $errstr = $ticket_dbh->errstr;
1262 $dbh->rollback if $oldAutoCommit;
1265 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1267 my $errstr = $ticket_sth->errstr;
1268 $dbh->rollback if $oldAutoCommit;
1272 #check and see if the customer is the only link on the ticket, and
1273 #if so, set the ticket to deleted status in RT?
1274 #maybe someday, for now this will at least fix tickets not displaying
1278 #delete the customer record
1280 my $error = $self->SUPER::delete;
1282 $dbh->rollback if $oldAutoCommit;
1286 # cust_main exports!
1288 #my $export_args = $options{'export_args'} || [];
1291 map qsearch( 'part_export', {exportnum=>$_} ),
1292 $conf->config('cust_main-exports'); #, $agentnum
1294 foreach my $part_export ( @part_export ) {
1295 my $error = $part_export->export_delete( $self ); #, @$export_args);
1297 $dbh->rollback if $oldAutoCommit;
1298 return "exporting to ". $part_export->exporttype.
1299 " (transaction rolled back): $error";
1303 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1308 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1310 Replaces the OLD_RECORD with this one in the database. If there is an error,
1311 returns the error, otherwise returns false.
1313 To change the customer's address, set the pseudo-fields C<bill_location> and
1314 C<ship_location>. The address will still only change if at least one of the
1315 address fields differs from the existing values.
1317 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1318 set as the contact email address for a default contact with the same name as
1321 Currently available options are: I<tax_exemption>, I<cust_payby_params>,
1322 I<contact_params>, I<invoicing_list>.
1324 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1325 of tax names and exemption numbers. FS::cust_main_exemption records will be
1326 deleted and inserted as appropriate.
1328 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1329 groups (describing the customer's payment methods and contacts, respectively)
1330 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1331 and L<FS::contact> for the fields these can contain.
1333 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1334 should be used instead if possible.
1341 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1343 : $self->replace_old;
1347 warn "$me replace called\n"
1350 my $curuser = $FS::CurrentUser::CurrentUser;
1351 return "You are not permitted to create complimentary accounts."
1352 if $self->complimentary eq 'Y'
1353 && $self->complimentary ne $old->complimentary
1354 && ! $curuser->access_right('Complimentary customer');
1356 local($ignore_expired_card) = 1
1357 if $old->payby =~ /^(CARD|DCRD)$/
1358 && $self->payby =~ /^(CARD|DCRD)$/
1359 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1361 local($ignore_banned_card) = 1
1362 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1363 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1364 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1366 if ( $self->payby =~ /^(CARD|DCRD)$/
1367 && $old->payinfo ne $self->payinfo
1368 && $old->paymask ne $self->paymask )
1370 my $error = $self->check_payinfo_cardtype;
1371 return $error if $error;
1374 return "Invoicing locale is required"
1377 && $conf->exists('cust_main-require_locale');
1379 local $SIG{HUP} = 'IGNORE';
1380 local $SIG{INT} = 'IGNORE';
1381 local $SIG{QUIT} = 'IGNORE';
1382 local $SIG{TERM} = 'IGNORE';
1383 local $SIG{TSTP} = 'IGNORE';
1384 local $SIG{PIPE} = 'IGNORE';
1386 my $oldAutoCommit = $FS::UID::AutoCommit;
1387 local $FS::UID::AutoCommit = 0;
1390 for my $l (qw(bill_location ship_location)) {
1391 #my $old_loc = $old->$l;
1392 my $new_loc = $self->$l or next;
1394 # find the existing location if there is one
1395 $new_loc->set('custnum' => $self->custnum);
1396 my $error = $new_loc->find_or_insert;
1398 $dbh->rollback if $oldAutoCommit;
1401 $self->set($l.'num', $new_loc->locationnum);
1405 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1406 warn "cust_main::replace: using deprecated invoicing list argument";
1407 $invoicing_list = shift @param;
1410 my %options = @param;
1412 $invoicing_list ||= $options{invoicing_list};
1414 my @contacts = map { $_->contact } $self->cust_contact;
1415 # find a contact that matches the customer's name
1416 my ($implicit_contact) = grep { $_->first eq $old->get('first')
1417 and $_->last eq $old->get('last') }
1419 $implicit_contact ||= FS::contact->new({
1420 'custnum' => $self->custnum,
1421 'locationnum' => $self->get('bill_locationnum'),
1424 # for any of these that are already contact emails, link to the existing
1426 if ( $invoicing_list ) {
1429 # kind of like process_m2m on these, except:
1430 # - the other side is two tables in a join
1431 # - and we might have to create new contact_emails
1432 # - and possibly a new contact
1434 # Find existing invoice emails that aren't on the implicit contact.
1435 # Any of these that are not on the new invoicing list will be removed.
1436 my %old_email_cust_contact;
1437 foreach my $cust_contact ($self->cust_contact) {
1438 next if !$cust_contact->invoice_dest;
1439 next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1441 foreach my $contact_email ($cust_contact->contact->contact_email) {
1442 $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1446 foreach my $dest (@$invoicing_list) {
1448 if ($dest eq 'POST') {
1450 $self->set('postal_invoice', 'Y');
1452 } elsif ( exists($old_email_cust_contact{$dest}) ) {
1454 delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1458 # See if it belongs to some other contact; if so, link it.
1459 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1461 and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1462 my $cust_contact = qsearchs('cust_contact', {
1463 contactnum => $contact_email->contactnum,
1464 custnum => $self->custnum,
1465 }) || FS::cust_contact->new({
1466 contactnum => $contact_email->contactnum,
1467 custnum => $self->custnum,
1469 $cust_contact->set('invoice_dest', 'Y');
1470 my $error = $cust_contact->custcontactnum ?
1471 $cust_contact->replace : $cust_contact->insert;
1473 $dbh->rollback if $oldAutoCommit;
1474 return "$error (linking to email address $dest)";
1478 # This email address is not yet linked to any contact, so it will
1479 # be added to the implicit contact.
1480 $email .= ',' if length($email);
1486 foreach my $remove_dest (keys %old_email_cust_contact) {
1487 my $cust_contact = $old_email_cust_contact{$remove_dest};
1488 # These were not in the list of requested destinations, so take them off.
1489 $cust_contact->set('invoice_dest', '');
1490 my $error = $cust_contact->replace;
1492 $dbh->rollback if $oldAutoCommit;
1493 return "$error (unlinking email address $remove_dest)";
1497 # make sure it keeps up with the changed customer name, if any
1498 $implicit_contact->set('last', $self->get('last'));
1499 $implicit_contact->set('first', $self->get('first'));
1500 $implicit_contact->set('emailaddress', $email);
1501 $implicit_contact->set('invoice_dest', 'Y');
1502 $implicit_contact->set('custnum', $self->custnum);
1505 if ( $implicit_contact->contactnum ) {
1506 $error = $implicit_contact->replace;
1507 } elsif ( length($email) ) { # don't create a new contact if not needed
1508 $error = $implicit_contact->insert;
1512 $dbh->rollback if $oldAutoCommit;
1513 return "$error (adding email address $email)";
1518 # replace the customer record
1519 my $error = $self->SUPER::replace($old);
1522 $dbh->rollback if $oldAutoCommit;
1526 # now move packages to the new service location
1527 $self->set('ship_location', ''); #flush cache
1528 if ( $old->ship_locationnum and # should only be null during upgrade...
1529 $old->ship_locationnum != $self->ship_locationnum ) {
1530 $error = $old->ship_location->move_to($self->ship_location);
1532 $dbh->rollback if $oldAutoCommit;
1536 # don't move packages based on the billing location, but
1537 # disable it if it's no longer in use
1538 if ( $old->bill_locationnum and
1539 $old->bill_locationnum != $self->bill_locationnum ) {
1540 $error = $old->bill_location->disable_if_unused;
1542 $dbh->rollback if $oldAutoCommit;
1547 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1549 #this could be more efficient than deleting and re-inserting, if it matters
1550 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1551 my $error = $cust_tag->delete;
1553 $dbh->rollback if $oldAutoCommit;
1557 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1558 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1559 'custnum' => $self->custnum };
1560 my $error = $cust_tag->insert;
1562 $dbh->rollback if $oldAutoCommit;
1569 my $tax_exemption = delete $options{'tax_exemption'};
1570 if ( $tax_exemption ) {
1572 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1573 if ref($tax_exemption) eq 'ARRAY';
1575 my %cust_main_exemption =
1576 map { $_->taxname => $_ }
1577 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1579 foreach my $taxname ( keys %$tax_exemption ) {
1581 if ( $cust_main_exemption{$taxname} &&
1582 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1585 delete $cust_main_exemption{$taxname};
1589 my $cust_main_exemption = new FS::cust_main_exemption {
1590 'custnum' => $self->custnum,
1591 'taxname' => $taxname,
1592 'exempt_number' => $tax_exemption->{$taxname},
1594 my $error = $cust_main_exemption->insert;
1596 $dbh->rollback if $oldAutoCommit;
1597 return "inserting cust_main_exemption (transaction rolled back): $error";
1601 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1602 my $error = $cust_main_exemption->delete;
1604 $dbh->rollback if $oldAutoCommit;
1605 return "deleting cust_main_exemption (transaction rolled back): $error";
1611 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1613 my $error = $self->process_o2m(
1614 'table' => 'cust_payby',
1615 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1616 'params' => $cust_payby_params,
1617 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1620 $dbh->rollback if $oldAutoCommit;
1626 if ( my $contact_params = delete $options{'contact_params'} ) {
1628 # this can potentially replace contacts that were created by the
1629 # invoicing list argument, but the UI shouldn't allow both of them
1632 my $error = $self->process_o2m(
1633 'table' => 'contact',
1634 'fields' => FS::contact->cgi_contact_fields,
1635 'params' => $contact_params,
1638 $dbh->rollback if $oldAutoCommit;
1644 unless ( $import || $skip_fuzzyfiles ) {
1645 $error = $self->queue_fuzzyfiles_update;
1647 $dbh->rollback if $oldAutoCommit;
1648 return "updating fuzzy search cache: $error";
1652 # tax district update in cust_location
1654 # cust_main exports!
1656 my $export_args = $options{'export_args'} || [];
1659 map qsearch( 'part_export', {exportnum=>$_} ),
1660 $conf->config('cust_main-exports'); #, $agentnum
1662 foreach my $part_export ( @part_export ) {
1663 my $error = $part_export->export_replace( $self, $old, @$export_args);
1665 $dbh->rollback if $oldAutoCommit;
1666 return "exporting to ". $part_export->exporttype.
1667 " (transaction rolled back): $error";
1671 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1676 =item queue_fuzzyfiles_update
1678 Used by insert & replace to update the fuzzy search cache
1682 use FS::cust_main::Search;
1683 sub queue_fuzzyfiles_update {
1686 local $SIG{HUP} = 'IGNORE';
1687 local $SIG{INT} = 'IGNORE';
1688 local $SIG{QUIT} = 'IGNORE';
1689 local $SIG{TERM} = 'IGNORE';
1690 local $SIG{TSTP} = 'IGNORE';
1691 local $SIG{PIPE} = 'IGNORE';
1693 my $oldAutoCommit = $FS::UID::AutoCommit;
1694 local $FS::UID::AutoCommit = 0;
1697 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1698 my $queue = new FS::queue {
1699 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1701 my @args = "cust_main.$field", $self->get($field);
1702 my $error = $queue->insert( @args );
1704 $dbh->rollback if $oldAutoCommit;
1705 return "queueing job (transaction rolled back): $error";
1710 push @locations, $self->bill_location if $self->bill_locationnum;
1711 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1712 foreach my $location (@locations) {
1713 my $queue = new FS::queue {
1714 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1716 my @args = 'cust_location.address1', $location->address1;
1717 my $error = $queue->insert( @args );
1719 $dbh->rollback if $oldAutoCommit;
1720 return "queueing job (transaction rolled back): $error";
1724 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1731 Checks all fields to make sure this is a valid customer record. If there is
1732 an error, returns the error, otherwise returns false. Called by the insert
1733 and replace methods.
1740 warn "$me check BEFORE: \n". $self->_dump
1744 $self->ut_numbern('custnum')
1745 || $self->ut_number('agentnum')
1746 || $self->ut_textn('agent_custid')
1747 || $self->ut_number('refnum')
1748 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1749 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1750 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1751 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1752 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1753 || $self->ut_textn('custbatch')
1754 || $self->ut_name('last')
1755 || $self->ut_name('first')
1756 || $self->ut_snumbern('signupdate')
1757 || $self->ut_snumbern('birthdate')
1758 || $self->ut_namen('spouse_last')
1759 || $self->ut_namen('spouse_first')
1760 || $self->ut_snumbern('spouse_birthdate')
1761 || $self->ut_snumbern('anniversary_date')
1762 || $self->ut_textn('company')
1763 || $self->ut_textn('ship_company')
1764 || $self->ut_anything('comments')
1765 || $self->ut_numbern('referral_custnum')
1766 || $self->ut_textn('stateid')
1767 || $self->ut_textn('stateid_state')
1768 || $self->ut_textn('invoice_terms')
1769 || $self->ut_floatn('cdr_termination_percentage')
1770 || $self->ut_floatn('credit_limit')
1771 || $self->ut_numbern('billday')
1772 || $self->ut_numbern('prorate_day')
1773 || $self->ut_flag('edit_subject')
1774 || $self->ut_flag('calling_list_exempt')
1775 || $self->ut_flag('invoice_noemail')
1776 || $self->ut_flag('message_noemail')
1777 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1778 || $self->ut_currencyn('currency')
1779 || $self->ut_textn('po_number')
1780 || $self->ut_enum('complimentary', [ '', 'Y' ])
1781 || $self->ut_flag('invoice_ship_address')
1782 || $self->ut_flag('invoice_dest')
1785 foreach (qw(company ship_company)) {
1786 my $company = $self->get($_);
1787 $company =~ s/^\s+//;
1788 $company =~ s/\s+$//;
1789 $company =~ s/\s+/ /g;
1790 $self->set($_, $company);
1793 #barf. need message catalogs. i18n. etc.
1794 $error .= "Please select an advertising source."
1795 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1796 return $error if $error;
1798 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1799 or return "Unknown agent";
1801 if ( $self->currency ) {
1802 my $agent_currency = qsearchs( 'agent_currency', {
1803 'agentnum' => $agent->agentnum,
1804 'currency' => $self->currency,
1806 or return "Agent ". $agent->agent.
1807 " not permitted to offer ". $self->currency. " invoicing";
1810 return "Unknown refnum"
1811 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1813 return "Unknown referring custnum: ". $self->referral_custnum
1814 unless ! $self->referral_custnum
1815 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1817 if ( $self->ss eq '' ) {
1822 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1823 or return "Illegal social security number: ". $self->ss;
1824 $self->ss("$1-$2-$3");
1827 #turn off invoice_ship_address if ship & bill are the same
1828 if ($self->bill_locationnum eq $self->ship_locationnum) {
1829 $self->invoice_ship_address('');
1832 # cust_main_county verification now handled by cust_location check
1835 $self->ut_phonen('daytime', $self->country)
1836 || $self->ut_phonen('night', $self->country)
1837 || $self->ut_phonen('fax', $self->country)
1838 || $self->ut_phonen('mobile', $self->country)
1840 return $error if $error;
1842 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1844 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1847 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1849 : FS::Msgcat::_gettext('daytime');
1850 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1852 : FS::Msgcat::_gettext('night');
1854 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1856 : FS::Msgcat::_gettext('mobile');
1858 return "$daytime_label, $night_label or $mobile_label is required"
1862 return "Please select an invoicing locale"
1865 && $conf->exists('cust_main-require_locale');
1867 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1868 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1872 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1874 warn "$me check AFTER: \n". $self->_dump
1877 $self->SUPER::check;
1880 sub check_payinfo_cardtype {
1883 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
1885 my $payinfo = $self->payinfo;
1886 $payinfo =~ s/\D//g;
1888 return '' if $payinfo =~ /^99\d{14}$/; #token
1890 my %bop_card_types = map { $_=>1 } values %{ card_types() };
1891 my $cardtype = cardtype($payinfo);
1893 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
1901 Additional checks for replace only.
1906 my ($new,$old) = @_;
1907 #preserve old value if global config is set
1908 if ($old && $conf->exists('invoice-ship_address')) {
1909 $new->invoice_ship_address($old->invoice_ship_address);
1916 Returns a list of fields which have ship_ duplicates.
1921 qw( last first company
1923 address1 address2 city county state zip country
1925 daytime night fax mobile
1929 =item has_ship_address
1931 Returns true if this customer record has a separate shipping address.
1935 sub has_ship_address {
1937 $self->bill_locationnum != $self->ship_locationnum;
1942 Returns a list of key/value pairs, with the following keys: address1,
1943 adddress2, city, county, state, zip, country, district, and geocode. The
1944 shipping address is used if present.
1950 $self->ship_location->location_hash;
1955 Returns all locations (see L<FS::cust_location>) for this customer.
1962 'table' => 'cust_location',
1963 'hashref' => { 'custnum' => $self->custnum,
1964 'prospectnum' => '',
1966 'order_by' => 'ORDER BY country, LOWER(state), LOWER(city), LOWER(county), LOWER(address1), LOWER(address2)',
1972 Returns all contact associations (see L<FS::cust_contact>) for this customer.
1978 qsearch('cust_contact', { 'custnum' => $self->custnum } );
1981 =item cust_payby PAYBY
1983 Returns all payment methods (see L<FS::cust_payby>) for this customer.
1985 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
1986 Does not validate PAYBY.
1994 'table' => 'cust_payby',
1995 'hashref' => { 'custnum' => $self->custnum },
1996 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
1998 $search->{'extra_sql'} = ' AND payby IN ( '.
1999 join(',', map dbh->quote($_), @payby).
2006 =item has_cust_payby_auto
2008 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
2012 sub has_cust_payby_auto {
2015 'table' => 'cust_payby',
2016 'hashref' => { 'custnum' => $self->custnum, },
2017 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2018 'order_by' => 'LIMIT 1',
2025 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2026 and L<FS::cust_pkg>) for this customer, except those on hold.
2028 Returns a list: an empty list on success or a list of errors.
2034 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2039 Unsuspends all suspended packages in the on-hold state (those without setup
2040 dates) for this customer.
2046 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2051 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2053 Returns a list: an empty list on success or a list of errors.
2059 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2062 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2064 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2065 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2066 of a list of pkgparts; the hashref has the following keys:
2070 =item pkgparts - listref of pkgparts
2072 =item (other options are passed to the suspend method)
2077 Returns a list: an empty list on success or a list of errors.
2081 sub suspend_if_pkgpart {
2083 my (@pkgparts, %opt);
2084 if (ref($_[0]) eq 'HASH'){
2085 @pkgparts = @{$_[0]{pkgparts}};
2090 grep { $_->suspend(%opt) }
2091 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2092 $self->unsuspended_pkgs;
2095 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2097 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2098 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2099 instead of a list of pkgparts; the hashref has the following keys:
2103 =item pkgparts - listref of pkgparts
2105 =item (other options are passed to the suspend method)
2109 Returns a list: an empty list on success or a list of errors.
2113 sub suspend_unless_pkgpart {
2115 my (@pkgparts, %opt);
2116 if (ref($_[0]) eq 'HASH'){
2117 @pkgparts = @{$_[0]{pkgparts}};
2122 grep { $_->suspend(%opt) }
2123 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2124 $self->unsuspended_pkgs;
2127 =item cancel [ OPTION => VALUE ... ]
2129 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2130 The cancellation time will be now.
2134 Always returns a list: an empty list on success or a list of errors.
2141 warn "$me cancel called on customer ". $self->custnum. " with options ".
2142 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2144 my @pkgs = $self->ncancelled_pkgs;
2146 $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2149 =item cancel_pkgs OPTIONS
2151 Cancels a specified list of packages. OPTIONS can include:
2155 =item cust_pkg - an arrayref of the packages. Required.
2157 =item time - the cancellation time, used to calculate final bills and
2158 unused-time credits if any. Will be passed through to the bill() and
2159 FS::cust_pkg::cancel() methods.
2161 =item quiet - can be set true to supress email cancellation notices.
2163 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a
2164 reasonnum of an existing reason, or passing a hashref will create a new reason.
2165 The hashref should have the following keys:
2166 typenum - Reason type (see L<FS::reason_type>)
2167 reason - Text of the new reason.
2169 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2170 for the individual packages, parallel to the C<cust_pkg> argument. The
2171 reason and reason_otaker arguments will be taken from those objects.
2173 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2175 =item nobill - can be set true to skip billing if it might otherwise be done.
2180 my( $self, %opt ) = @_;
2182 # we're going to cancel services, which is not reversible
2183 die "cancel_pkgs cannot be run inside a transaction"
2184 if $FS::UID::AutoCommit == 0;
2186 local $FS::UID::AutoCommit = 0;
2188 return ( 'access denied' )
2189 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2191 if ( $opt{'ban'} ) {
2193 foreach my $cust_payby ( $self->cust_payby ) {
2195 #well, if they didn't get decrypted on search, then we don't have to
2196 # try again... queue a job for the server that does have decryption
2197 # capability if we're in a paranoid multi-server implementation?
2198 return ( "Can't (yet) ban encrypted credit cards" )
2199 if $cust_payby->is_encrypted($cust_payby->payinfo);
2201 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2202 my $error = $ban->insert;
2212 my @pkgs = @{ delete $opt{'cust_pkg'} };
2213 my $cancel_time = $opt{'time'} || time;
2215 # bill all packages first, so we don't lose usage, service counts for
2216 # bulk billing, etc.
2217 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2219 my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2221 'time' => $cancel_time );
2223 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2225 return ( "Error billing during cancellation: $error" );
2230 $FS::UID::AutoCommit = 1;
2232 # now cancel all services, the same way we would for individual packages.
2233 # if any of them fail, cancel the rest anyway.
2234 my @cust_svc = map { $_->cust_svc } @pkgs;
2235 my @sorted_cust_svc =
2237 sort { $a->[1] <=> $b->[1] }
2238 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2240 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2243 foreach my $cust_svc (@sorted_cust_svc) {
2244 my $part_svc = $cust_svc->part_svc;
2245 next if ( defined($part_svc) and $part_svc->preserve );
2246 my $error = $cust_svc->cancel; # immediate cancel, no date option
2247 push @errors, $error if $error;
2253 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2254 $self->custnum. "\n"
2258 if ($opt{'cust_pkg_reason'}) {
2259 @cprs = @{ delete $opt{'cust_pkg_reason'} };
2265 my $cpr = shift @cprs;
2267 $lopt{'reason'} = $cpr->reasonnum;
2268 $lopt{'reason_otaker'} = $cpr->otaker;
2270 warn "no reason found when canceling package ".$_->pkgnum."\n";
2271 # we're not actually required to pass a reason to cust_pkg::cancel,
2272 # but if we're getting to this point, something has gone awry.
2273 $null_reason ||= FS::reason->new_or_existing(
2274 reason => 'unknown reason',
2275 type => 'Cancel Reason',
2278 $lopt{'reason'} = $null_reason->reasonnum;
2279 $lopt{'reason_otaker'} = $FS::CurrentUser::CurrentUser->username;
2282 my $error = $_->cancel(%lopt);
2283 push @errors, 'pkgnum '.$_->pkgnum.': '.$error if $error;
2289 sub _banned_pay_hashref {
2290 die 'cust_main->_banned_pay_hashref deprecated';
2302 'payby' => $payby2ban{$self->payby},
2303 'payinfo' => $self->payinfo,
2304 #don't ever *search* on reason! #'reason' =>
2310 Returns all notes (see L<FS::cust_main_note>) for this customer.
2315 my($self,$orderby_classnum) = (shift,shift);
2316 my $orderby = "sticky DESC, _date DESC";
2317 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2318 qsearch( 'cust_main_note',
2319 { 'custnum' => $self->custnum },
2321 "ORDER BY $orderby",
2327 Returns the agent (see L<FS::agent>) for this customer.
2331 Returns the agent name (see L<FS::agent>) for this customer.
2337 $self->agent->agent;
2342 Returns any tags associated with this customer, as FS::cust_tag objects,
2343 or an empty list if there are no tags.
2347 Returns any tags associated with this customer, as FS::part_tag objects,
2348 or an empty list if there are no tags.
2354 map $_->part_tag, $self->cust_tag;
2360 Returns the customer class, as an FS::cust_class object, or the empty string
2361 if there is no customer class.
2365 Returns the customer category name, or the empty string if there is no customer
2372 my $cust_class = $self->cust_class;
2374 ? $cust_class->categoryname
2380 Returns the customer class name, or the empty string if there is no customer
2387 my $cust_class = $self->cust_class;
2389 ? $cust_class->classname
2395 Returns the external tax status, as an FS::tax_status object, or the empty
2396 string if there is no tax status.
2402 if ( $self->taxstatusnum ) {
2403 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2411 Returns the tax status code if there is one.
2417 my $tax_status = $self->tax_status;
2419 ? $tax_status->taxstatus
2423 =item BILLING METHODS
2425 Documentation on billing methods has been moved to
2426 L<FS::cust_main::Billing>.
2428 =item REALTIME BILLING METHODS
2430 Documentation on realtime billing methods has been moved to
2431 L<FS::cust_main::Billing_Realtime>.
2435 Removes the I<paycvv> field from the database directly.
2437 If there is an error, returns the error, otherwise returns false.
2439 DEPRECATED. Use L</remove_cvv_from_cust_payby> instead.
2444 die 'cust_main->remove_cvv deprecated';
2446 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2447 or return dbh->errstr;
2448 $sth->execute($self->custnum)
2449 or return $sth->errstr;
2456 Returns the total owed for this customer on all invoices
2457 (see L<FS::cust_bill/owed>).
2463 $self->total_owed_date(2145859200); #12/31/2037
2466 =item total_owed_date TIME
2468 Returns the total owed for this customer on all invoices with date earlier than
2469 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2470 see L<Time::Local> and L<Date::Parse> for conversion functions.
2474 sub total_owed_date {
2478 my $custnum = $self->custnum;
2480 my $owed_sql = FS::cust_bill->owed_sql;
2483 SELECT SUM($owed_sql) FROM cust_bill
2484 WHERE custnum = $custnum
2488 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2492 =item total_owed_pkgnum PKGNUM
2494 Returns the total owed on all invoices for this customer's specific package
2495 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2499 sub total_owed_pkgnum {
2500 my( $self, $pkgnum ) = @_;
2501 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2504 =item total_owed_date_pkgnum TIME PKGNUM
2506 Returns the total owed for this customer's specific package when using
2507 experimental package balances on all invoices with date earlier than
2508 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2509 see L<Time::Local> and L<Date::Parse> for conversion functions.
2513 sub total_owed_date_pkgnum {
2514 my( $self, $time, $pkgnum ) = @_;
2517 foreach my $cust_bill (
2518 grep { $_->_date <= $time }
2519 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2521 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2523 sprintf( "%.2f", $total_bill );
2529 Returns the total amount of all payments.
2536 $total += $_->paid foreach $self->cust_pay;
2537 sprintf( "%.2f", $total );
2540 =item total_unapplied_credits
2542 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2543 customer. See L<FS::cust_credit/credited>.
2545 =item total_credited
2547 Old name for total_unapplied_credits. Don't use.
2551 sub total_credited {
2552 #carp "total_credited deprecated, use total_unapplied_credits";
2553 shift->total_unapplied_credits(@_);
2556 sub total_unapplied_credits {
2559 my $custnum = $self->custnum;
2561 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2564 SELECT SUM($unapplied_sql) FROM cust_credit
2565 WHERE custnum = $custnum
2568 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2572 =item total_unapplied_credits_pkgnum PKGNUM
2574 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2575 customer. See L<FS::cust_credit/credited>.
2579 sub total_unapplied_credits_pkgnum {
2580 my( $self, $pkgnum ) = @_;
2581 my $total_credit = 0;
2582 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2583 sprintf( "%.2f", $total_credit );
2587 =item total_unapplied_payments
2589 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2590 See L<FS::cust_pay/unapplied>.
2594 sub total_unapplied_payments {
2597 my $custnum = $self->custnum;
2599 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2602 SELECT SUM($unapplied_sql) FROM cust_pay
2603 WHERE custnum = $custnum
2606 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2610 =item total_unapplied_payments_pkgnum PKGNUM
2612 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2613 specific package when using experimental package balances. See
2614 L<FS::cust_pay/unapplied>.
2618 sub total_unapplied_payments_pkgnum {
2619 my( $self, $pkgnum ) = @_;
2620 my $total_unapplied = 0;
2621 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2622 sprintf( "%.2f", $total_unapplied );
2626 =item total_unapplied_refunds
2628 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2629 customer. See L<FS::cust_refund/unapplied>.
2633 sub total_unapplied_refunds {
2635 my $custnum = $self->custnum;
2637 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2640 SELECT SUM($unapplied_sql) FROM cust_refund
2641 WHERE custnum = $custnum
2644 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2650 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2651 total_unapplied_credits minus total_unapplied_payments).
2657 $self->balance_date_range;
2660 =item balance_date TIME
2662 Returns the balance for this customer, only considering invoices with date
2663 earlier than TIME (total_owed_date minus total_credited minus
2664 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2665 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2672 $self->balance_date_range(shift);
2675 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2677 Returns the balance for this customer, optionally considering invoices with
2678 date earlier than START_TIME, and not later than END_TIME
2679 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2681 Times are specified as SQL fragments or numeric
2682 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2683 L<Date::Parse> for conversion functions. The empty string can be passed
2684 to disable that time constraint completely.
2686 Accepts the same options as L<balance_date_sql>:
2690 =item unapplied_date
2692 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)
2696 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2697 time will be ignored. Note that START_TIME and END_TIME only limit the date
2698 range for invoices and I<unapplied> payments, credits, and refunds.
2704 sub balance_date_range {
2706 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2707 ') FROM cust_main WHERE custnum='. $self->custnum;
2708 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2711 =item balance_pkgnum PKGNUM
2713 Returns the balance for this customer's specific package when using
2714 experimental package balances (total_owed plus total_unrefunded, minus
2715 total_unapplied_credits minus total_unapplied_payments)
2719 sub balance_pkgnum {
2720 my( $self, $pkgnum ) = @_;
2723 $self->total_owed_pkgnum($pkgnum)
2724 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2725 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2726 - $self->total_unapplied_credits_pkgnum($pkgnum)
2727 - $self->total_unapplied_payments_pkgnum($pkgnum)
2733 Returns a hash of useful information for making a payment.
2743 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2744 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2745 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2749 For credit card transactions:
2761 For electronic check transactions:
2771 #XXX i need to be updated for 4.x+
2777 $return{balance} = $self->balance;
2779 $return{payname} = $self->payname
2780 || ( $self->first. ' '. $self->get('last') );
2782 $return{$_} = $self->bill_location->$_
2783 for qw(address1 address2 city state zip);
2785 $return{payby} = $self->payby;
2786 $return{stateid_state} = $self->stateid_state;
2788 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2789 $return{card_type} = cardtype($self->payinfo);
2790 $return{payinfo} = $self->paymask;
2792 @return{'month', 'year'} = $self->paydate_monthyear;
2796 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2797 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2798 $return{payinfo1} = $payinfo1;
2799 $return{payinfo2} = $payinfo2;
2800 $return{paytype} = $self->paytype;
2801 $return{paystate} = $self->paystate;
2805 #doubleclick protection
2807 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2815 Returns the next payment expiration date for this customer. If they have no
2816 payment methods that will expire, returns 0.
2822 # filter out the ones that individually return 0, but then return 0 if
2823 # there are no results
2824 my @epochs = grep { $_ > 0 } map { $_->paydate_epoch } $self->cust_payby;
2825 min( @epochs ) || 0;
2828 =item paydate_epoch_sql
2830 Returns an SQL expression to get the next payment expiration date for a
2831 customer. Returns 2143260000 (2037-12-01) if there are no payment expiration
2832 dates, so that it's safe to test for "will it expire before date X" for any
2837 sub paydate_epoch_sql {
2839 my $paydate = FS::cust_payby->paydate_epoch_sql;
2840 "(SELECT COALESCE(MIN($paydate), 2143260000) FROM cust_payby WHERE cust_payby.custnum = cust_main.custnum)";
2844 my( $self, $taxname ) = @_;
2846 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2847 'taxname' => $taxname,
2852 =item cust_main_exemption
2854 =item invoicing_list
2856 Returns a list of email addresses (with svcnum entries expanded), and the word
2857 'POST' if the customer receives postal invoices.
2861 sub invoicing_list {
2862 my( $self, $arrayref ) = @_;
2865 warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
2868 my @emails = $self->invoicing_list_emailonly;
2869 push @emails, 'POST' if $self->get('postal_invoice');
2874 =item check_invoicing_list ARRAYREF
2876 Checks these arguements as valid input for the invoicing_list method. If there
2877 is an error, returns the error, otherwise returns false.
2881 sub check_invoicing_list {
2882 my( $self, $arrayref ) = @_;
2884 foreach my $address ( @$arrayref ) {
2886 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2887 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2890 my $cust_main_invoice = new FS::cust_main_invoice ( {
2891 'custnum' => $self->custnum,
2894 my $error = $self->custnum
2895 ? $cust_main_invoice->check
2896 : $cust_main_invoice->checkdest
2898 return $error if $error;
2902 return "Email address required"
2903 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2904 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2911 Returns the email addresses of all accounts provisioned for this customer.
2918 foreach my $cust_pkg ( $self->all_pkgs ) {
2919 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2921 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2922 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2924 $list{$_}=1 foreach map { $_->email } @svc_acct;
2929 =item invoicing_list_addpost
2931 Adds postal invoicing to this customer. If this customer is already configured
2932 to receive postal invoices, does nothing.
2936 sub invoicing_list_addpost {
2938 if ( $self->get('postal_invoice') eq '' ) {
2939 $self->set('postal_invoice', 'Y');
2940 my $error = $self->replace;
2941 warn $error if $error; # should fail harder, but this is traditional
2945 =item invoicing_list_emailonly
2947 Returns the list of email invoice recipients (invoicing_list without non-email
2948 destinations such as POST and FAX).
2952 sub invoicing_list_emailonly {
2954 warn "$me invoicing_list_emailonly called"
2956 return () if !$self->custnum; # not yet inserted
2957 return map { $_->emailaddress }
2959 table => 'cust_contact',
2960 select => 'emailaddress',
2961 addl_from => ' JOIN contact USING (contactnum) '.
2962 ' JOIN contact_email USING (contactnum)',
2963 hashref => { 'custnum' => $self->custnum, },
2964 extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
2968 =item invoicing_list_emailonly_scalar
2970 Returns the list of email invoice recipients (invoicing_list without non-email
2971 destinations such as POST and FAX) as a comma-separated scalar.
2975 sub invoicing_list_emailonly_scalar {
2977 warn "$me invoicing_list_emailonly_scalar called"
2979 join(', ', $self->invoicing_list_emailonly);
2982 =item contact_list [ CLASSNUM, ... ]
2984 Returns a list of contacts (L<FS::contact> objects) for the customer. If
2985 a list of contact classnums is given, returns only contacts in those
2986 classes. If the pseudo-classnum 'invoice' is given, returns contacts that
2987 are marked as invoice destinations. If '0' is given, also returns contacts
2990 If no arguments are given, returns all contacts for the customer.
2998 select => 'contact.*, cust_contact.invoice_dest',
2999 addl_from => ' JOIN cust_contact USING (contactnum)',
3000 extra_sql => ' WHERE cust_contact.custnum = '.$self->custnum,
3006 if ( $_ eq 'invoice' ) {
3007 push @orwhere, 'cust_contact.invoice_dest = \'Y\'';
3008 } elsif ( $_ eq '0' ) {
3009 push @orwhere, 'cust_contact.classnum is null';
3010 } elsif ( /^\d+$/ ) {
3011 push @classnums, $_;
3013 die "bad classnum argument '$_'";
3018 push @orwhere, 'cust_contact.classnum IN ('.join(',', @classnums).')';
3021 $search->{extra_sql} .= ' AND (' .
3022 join(' OR ', map "( $_ )", @orwhere) .
3029 =item contact_list_email [ CLASSNUM, ... ]
3031 Same as L</contact_list>, but returns email destinations instead of contact
3036 sub contact_list_email {
3038 my @contacts = $self->contact_list(@_);
3040 foreach my $contact (@contacts) {
3041 foreach my $contact_email ($contact->contact_email) {
3043 $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3049 =item referral_custnum_cust_main
3051 Returns the customer who referred this customer (or the empty string, if
3052 this customer was not referred).
3054 Note the difference with referral_cust_main method: This method,
3055 referral_custnum_cust_main returns the single customer (if any) who referred
3056 this customer, while referral_cust_main returns an array of customers referred
3061 sub referral_custnum_cust_main {
3063 return '' unless $self->referral_custnum;
3064 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3067 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3069 Returns an array of customers referred by this customer (referral_custnum set
3070 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3071 customers referred by customers referred by this customer and so on, inclusive.
3072 The default behavior is DEPTH 1 (no recursion).
3074 Note the difference with referral_custnum_cust_main method: This method,
3075 referral_cust_main, returns an array of customers referred BY this customer,
3076 while referral_custnum_cust_main returns the single customer (if any) who
3077 referred this customer.
3081 sub referral_cust_main {
3083 my $depth = @_ ? shift : 1;
3084 my $exclude = @_ ? shift : {};
3087 map { $exclude->{$_->custnum}++; $_; }
3088 grep { ! $exclude->{ $_->custnum } }
3089 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3093 map { $_->referral_cust_main($depth-1, $exclude) }
3100 =item referral_cust_main_ncancelled
3102 Same as referral_cust_main, except only returns customers with uncancelled
3107 sub referral_cust_main_ncancelled {
3109 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3112 =item referral_cust_pkg [ DEPTH ]
3114 Like referral_cust_main, except returns a flat list of all unsuspended (and
3115 uncancelled) packages for each customer. The number of items in this list may
3116 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3120 sub referral_cust_pkg {
3122 my $depth = @_ ? shift : 1;
3124 map { $_->unsuspended_pkgs }
3125 grep { $_->unsuspended_pkgs }
3126 $self->referral_cust_main($depth);
3129 =item referring_cust_main
3131 Returns the single cust_main record for the customer who referred this customer
3132 (referral_custnum), or false.
3136 sub referring_cust_main {
3138 return '' unless $self->referral_custnum;
3139 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3142 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3144 Applies a credit to this customer. If there is an error, returns the error,
3145 otherwise returns false.
3147 REASON can be a text string, an FS::reason object, or a scalar reference to
3148 a reasonnum. If a text string, it will be automatically inserted as a new
3149 reason, and a 'reason_type' option must be passed to indicate the
3150 FS::reason_type for the new reason.
3152 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3153 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3154 I<commission_pkgnum>.
3156 Any other options are passed to FS::cust_credit::insert.
3161 my( $self, $amount, $reason, %options ) = @_;
3163 my $cust_credit = new FS::cust_credit {
3164 'custnum' => $self->custnum,
3165 'amount' => $amount,
3168 if ( ref($reason) ) {
3170 if ( ref($reason) eq 'SCALAR' ) {
3171 $cust_credit->reasonnum( $$reason );
3173 $cust_credit->reasonnum( $reason->reasonnum );
3177 $cust_credit->set('reason', $reason)
3180 $cust_credit->$_( delete $options{$_} )
3181 foreach grep exists($options{$_}),
3182 qw( addlinfo eventnum ),
3183 map "commission_$_", qw( agentnum salesnum pkgnum );
3185 $cust_credit->insert(%options);
3189 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3191 Creates a one-time charge for this customer. If there is an error, returns
3192 the error, otherwise returns false.
3194 New-style, with a hashref of options:
3196 my $error = $cust_main->charge(
3200 'start_date' => str2time('7/4/2009'),
3201 'pkg' => 'Description',
3202 'comment' => 'Comment',
3203 'additional' => [], #extra invoice detail
3204 'classnum' => 1, #pkg_class
3206 'setuptax' => '', # or 'Y' for tax exempt
3208 'locationnum'=> 1234, # optional
3211 'taxclass' => 'Tax class',
3214 'taxproduct' => 2, #part_pkg_taxproduct
3215 'override' => {}, #XXX describe
3217 #will be filled in with the new object
3218 'cust_pkg_ref' => \$cust_pkg,
3220 #generate an invoice immediately
3222 'invoice_terms' => '', #with these terms
3228 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3232 #super false laziness w/quotation::charge
3235 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3236 my ( $pkg, $comment, $additional );
3237 my ( $setuptax, $taxclass ); #internal taxes
3238 my ( $taxproduct, $override ); #vendor (CCH) taxes
3240 my $separate_bill = '';
3241 my $cust_pkg_ref = '';
3242 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3244 if ( ref( $_[0] ) ) {
3245 $amount = $_[0]->{amount};
3246 $setup_cost = $_[0]->{setup_cost};
3247 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3248 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3249 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3250 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3251 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3252 : '$'. sprintf("%.2f",$amount);
3253 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3254 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3255 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3256 $additional = $_[0]->{additional} || [];
3257 $taxproduct = $_[0]->{taxproductnum};
3258 $override = { '' => $_[0]->{tax_override} };
3259 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3260 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3261 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3262 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3263 $separate_bill = $_[0]->{separate_bill} || '';
3269 $pkg = @_ ? shift : 'One-time charge';
3270 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3272 $taxclass = @_ ? shift : '';
3276 local $SIG{HUP} = 'IGNORE';
3277 local $SIG{INT} = 'IGNORE';
3278 local $SIG{QUIT} = 'IGNORE';
3279 local $SIG{TERM} = 'IGNORE';
3280 local $SIG{TSTP} = 'IGNORE';
3281 local $SIG{PIPE} = 'IGNORE';
3283 my $oldAutoCommit = $FS::UID::AutoCommit;
3284 local $FS::UID::AutoCommit = 0;
3287 my $part_pkg = new FS::part_pkg ( {
3289 'comment' => $comment,
3293 'classnum' => ( $classnum ? $classnum : '' ),
3294 'setuptax' => $setuptax,
3295 'taxclass' => $taxclass,
3296 'taxproductnum' => $taxproduct,
3297 'setup_cost' => $setup_cost,
3300 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3301 ( 0 .. @$additional - 1 )
3303 'additional_count' => scalar(@$additional),
3304 'setup_fee' => $amount,
3307 my $error = $part_pkg->insert( options => \%options,
3308 tax_overrides => $override,
3311 $dbh->rollback if $oldAutoCommit;
3315 my $pkgpart = $part_pkg->pkgpart;
3316 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3317 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3318 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3319 $error = $type_pkgs->insert;
3321 $dbh->rollback if $oldAutoCommit;
3326 my $cust_pkg = new FS::cust_pkg ( {
3327 'custnum' => $self->custnum,
3328 'pkgpart' => $pkgpart,
3329 'quantity' => $quantity,
3330 'start_date' => $start_date,
3331 'no_auto' => $no_auto,
3332 'separate_bill' => $separate_bill,
3333 'locationnum'=> $locationnum,
3336 $error = $cust_pkg->insert;
3338 $dbh->rollback if $oldAutoCommit;
3340 } elsif ( $cust_pkg_ref ) {
3341 ${$cust_pkg_ref} = $cust_pkg;
3345 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3346 'pkg_list' => [ $cust_pkg ],
3349 $dbh->rollback if $oldAutoCommit;
3354 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3359 #=item charge_postal_fee
3361 #Applies a one time charge this customer. If there is an error,
3362 #returns the error, returns the cust_pkg charge object or false
3363 #if there was no charge.
3367 # This should be a customer event. For that to work requires that bill
3368 # also be a customer event.
3370 sub charge_postal_fee {
3373 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3374 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3376 my $cust_pkg = new FS::cust_pkg ( {
3377 'custnum' => $self->custnum,
3378 'pkgpart' => $pkgpart,
3382 my $error = $cust_pkg->insert;
3383 $error ? $error : $cust_pkg;
3386 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3388 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3390 Optionally, a list or hashref of additional arguments to the qsearch call can
3397 my $opt = ref($_[0]) ? shift : { @_ };
3399 #return $self->num_cust_bill unless wantarray || keys %$opt;
3401 $opt->{'table'} = 'cust_bill';
3402 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3403 $opt->{'hashref'}{'custnum'} = $self->custnum;
3404 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3406 map { $_ } #behavior of sort undefined in scalar context
3407 sort { $a->_date <=> $b->_date }
3411 =item open_cust_bill
3413 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3418 sub open_cust_bill {
3422 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3428 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3430 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3434 sub legacy_cust_bill {
3437 #return $self->num_legacy_cust_bill unless wantarray;
3439 map { $_ } #behavior of sort undefined in scalar context
3440 sort { $a->_date <=> $b->_date }
3441 qsearch({ 'table' => 'legacy_cust_bill',
3442 'hashref' => { 'custnum' => $self->custnum, },
3443 'order_by' => 'ORDER BY _date ASC',
3447 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3449 Returns all the statements (see L<FS::cust_statement>) for this customer.
3451 Optionally, a list or hashref of additional arguments to the qsearch call can
3456 =item cust_bill_void
3458 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3462 sub cust_bill_void {
3465 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3466 sort { $a->_date <=> $b->_date }
3467 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3470 sub cust_statement {
3472 my $opt = ref($_[0]) ? shift : { @_ };
3474 #return $self->num_cust_statement unless wantarray || keys %$opt;
3476 $opt->{'table'} = 'cust_statement';
3477 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3478 $opt->{'hashref'}{'custnum'} = $self->custnum;
3479 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3481 map { $_ } #behavior of sort undefined in scalar context
3482 sort { $a->_date <=> $b->_date }
3486 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3488 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3490 Optionally, a list or hashref of additional arguments to the qsearch call can
3491 be passed following the SVCDB.
3498 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3499 warn "$me svc_x requires a svcdb";
3502 my $opt = ref($_[0]) ? shift : { @_ };
3504 $opt->{'table'} = $svcdb;
3505 $opt->{'addl_from'} =
3506 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3507 ($opt->{'addl_from'} || '');
3509 my $custnum = $self->custnum;
3510 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3511 my $where = "cust_pkg.custnum = $custnum";
3513 my $extra_sql = $opt->{'extra_sql'} || '';
3514 if ( keys %{ $opt->{'hashref'} } ) {
3515 $extra_sql = " AND $where $extra_sql";
3518 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3519 $extra_sql = "WHERE $where AND $1";
3522 $extra_sql = "WHERE $where $extra_sql";
3525 $opt->{'extra_sql'} = $extra_sql;
3530 # required for use as an eventtable;
3533 $self->svc_x('svc_acct', @_);
3538 Returns all the credits (see L<FS::cust_credit>) for this customer.
3545 #return $self->num_cust_credit unless wantarray;
3547 map { $_ } #behavior of sort undefined in scalar context
3548 sort { $a->_date <=> $b->_date }
3549 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3552 =item cust_credit_pkgnum
3554 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3555 package when using experimental package balances.
3559 sub cust_credit_pkgnum {
3560 my( $self, $pkgnum ) = @_;
3561 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3562 sort { $a->_date <=> $b->_date }
3563 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3564 'pkgnum' => $pkgnum,
3569 =item cust_credit_void
3571 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3575 sub cust_credit_void {
3578 sort { $a->_date <=> $b->_date }
3579 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3584 Returns all the payments (see L<FS::cust_pay>) for this customer.
3590 my $opt = ref($_[0]) ? shift : { @_ };
3592 return $self->num_cust_pay unless wantarray || keys %$opt;
3594 $opt->{'table'} = 'cust_pay';
3595 $opt->{'hashref'}{'custnum'} = $self->custnum;
3597 map { $_ } #behavior of sort undefined in scalar context
3598 sort { $a->_date <=> $b->_date }
3605 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3606 called automatically when the cust_pay method is used in a scalar context.
3612 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3613 my $sth = dbh->prepare($sql) or die dbh->errstr;
3614 $sth->execute($self->custnum) or die $sth->errstr;
3615 $sth->fetchrow_arrayref->[0];
3618 =item unapplied_cust_pay
3620 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3624 sub unapplied_cust_pay {
3628 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3634 =item cust_pay_pkgnum
3636 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3637 package when using experimental package balances.
3641 sub cust_pay_pkgnum {
3642 my( $self, $pkgnum ) = @_;
3643 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3644 sort { $a->_date <=> $b->_date }
3645 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3646 'pkgnum' => $pkgnum,
3653 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3659 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3660 sort { $a->_date <=> $b->_date }
3661 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3664 =item cust_pay_pending
3666 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3667 (without status "done").
3671 sub cust_pay_pending {
3673 return $self->num_cust_pay_pending unless wantarray;
3674 sort { $a->_date <=> $b->_date }
3675 qsearch( 'cust_pay_pending', {
3676 'custnum' => $self->custnum,
3677 'status' => { op=>'!=', value=>'done' },
3682 =item cust_pay_pending_attempt
3684 Returns all payment attempts / declined payments for this customer, as pending
3685 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3686 a corresponding payment (see L<FS::cust_pay>).
3690 sub cust_pay_pending_attempt {
3692 return $self->num_cust_pay_pending_attempt unless wantarray;
3693 sort { $a->_date <=> $b->_date }
3694 qsearch( 'cust_pay_pending', {
3695 'custnum' => $self->custnum,
3702 =item num_cust_pay_pending
3704 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3705 customer (without status "done"). Also called automatically when the
3706 cust_pay_pending method is used in a scalar context.
3710 sub num_cust_pay_pending {
3713 " SELECT COUNT(*) FROM cust_pay_pending ".
3714 " WHERE custnum = ? AND status != 'done' ",
3719 =item num_cust_pay_pending_attempt
3721 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3722 customer, with status "done" but without a corresp. Also called automatically when the
3723 cust_pay_pending method is used in a scalar context.
3727 sub num_cust_pay_pending_attempt {
3730 " SELECT COUNT(*) FROM cust_pay_pending ".
3731 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3738 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3744 map { $_ } #return $self->num_cust_refund unless wantarray;
3745 sort { $a->_date <=> $b->_date }
3746 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3749 =item display_custnum
3751 Returns the displayed customer number for this customer: agent_custid if
3752 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3756 sub display_custnum {
3759 return $self->agent_custid
3760 if $default_agent_custid && $self->agent_custid;
3762 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3766 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
3767 } elsif ( $custnum_display_length ) {
3768 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
3770 return $self->custnum;
3776 Returns a name string for this customer, either "Company (Last, First)" or
3783 my $name = $self->contact;
3784 $name = $self->company. " ($name)" if $self->company;
3788 =item service_contact
3790 Returns the L<FS::contact> object for this customer that has the 'Service'
3791 contact class, or undef if there is no such contact. Deprecated; don't use
3796 sub service_contact {
3798 if ( !exists($self->{service_contact}) ) {
3799 my $classnum = $self->scalar_sql(
3800 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3801 ) || 0; #if it's zero, qsearchs will return nothing
3802 my $cust_contact = qsearchs('cust_contact', {
3803 'classnum' => $classnum,
3804 'custnum' => $self->custnum,
3806 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3808 $self->{service_contact};
3813 Returns a name string for this (service/shipping) contact, either
3814 "Company (Last, First)" or "Last, First".
3821 my $name = $self->ship_contact;
3822 $name = $self->company. " ($name)" if $self->company;
3828 Returns a name string for this customer, either "Company" or "First Last".
3834 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3837 =item ship_name_short
3839 Returns a name string for this (service/shipping) contact, either "Company"
3844 sub ship_name_short {
3846 $self->service_contact
3847 ? $self->ship_contact_firstlast
3853 Returns this customer's full (billing) contact name only, "Last, First"
3859 $self->get('last'). ', '. $self->first;
3864 Returns this customer's full (shipping) contact name only, "Last, First"
3870 my $contact = $self->service_contact || $self;
3871 $contact->get('last') . ', ' . $contact->get('first');
3874 =item contact_firstlast
3876 Returns this customers full (billing) contact name only, "First Last".
3880 sub contact_firstlast {
3882 $self->first. ' '. $self->get('last');
3885 =item ship_contact_firstlast
3887 Returns this customer's full (shipping) contact name only, "First Last".
3891 sub ship_contact_firstlast {
3893 my $contact = $self->service_contact || $self;
3894 $contact->get('first') . ' '. $contact->get('last');
3897 sub bill_country_full {
3899 $self->bill_location->country_full;
3902 sub ship_country_full {
3904 $self->ship_location->country_full;
3907 =item county_state_county [ PREFIX ]
3909 Returns a string consisting of just the county, state and country.
3913 sub county_state_country {
3916 if ( @_ && $_[0] && $self->has_ship_address ) {
3917 $locationnum = $self->ship_locationnum;
3919 $locationnum = $self->bill_locationnum;
3921 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3922 $cust_location->county_state_country;
3925 =item geocode DATA_VENDOR
3927 Returns a value for the customer location as encoded by DATA_VENDOR.
3928 Currently this only makes sense for "CCH" as DATA_VENDOR.
3936 Returns a status string for this customer, currently:
3942 No packages have ever been ordered. Displayed as "No packages".
3946 Recurring packages all are new (not yet billed).
3950 One or more recurring packages is active.
3954 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3958 All non-cancelled recurring packages are suspended.
3962 All recurring packages are cancelled.
3966 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3967 cust_main-status_module configuration option.
3971 sub status { shift->cust_status(@_); }
3975 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
3976 for my $status ( FS::cust_main->statuses() ) {
3977 my $method = $status.'_sql';
3978 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3979 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3980 $sth->execute( ($self->custnum) x $numnum )
3981 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3982 if ( $sth->fetchrow_arrayref->[0] ) {
3983 $self->hashref->{cust_status} = $status;
3989 =item is_status_delay_cancel
3991 Returns true if customer status is 'suspended'
3992 and all suspended cust_pkg return true for
3993 cust_pkg->is_status_delay_cancel.
3995 This is not a real status, this only meant for hacking display
3996 values, because otherwise treating the customer as suspended is
3997 really the whole point of the delay_cancel option.
4001 sub is_status_delay_cancel {
4003 return 0 unless $self->status eq 'suspended';
4004 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4005 return 0 unless $cust_pkg->is_status_delay_cancel;
4010 =item ucfirst_cust_status
4012 =item ucfirst_status
4014 Deprecated, use the cust_status_label method instead.
4016 Returns the status with the first character capitalized.
4020 sub ucfirst_status {
4021 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4022 local($ucfirst_nowarn) = 1;
4023 shift->ucfirst_cust_status(@_);
4026 sub ucfirst_cust_status {
4027 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4029 ucfirst($self->cust_status);
4032 =item cust_status_label
4036 Returns the display label for this status.
4040 sub status_label { shift->cust_status_label(@_); }
4042 sub cust_status_label {
4044 __PACKAGE__->statuslabels->{$self->cust_status};
4049 Returns a hex triplet color string for this customer's status.
4053 sub statuscolor { shift->cust_statuscolor(@_); }
4055 sub cust_statuscolor {
4057 __PACKAGE__->statuscolors->{$self->cust_status};
4060 =item tickets [ STATUS ]
4062 Returns an array of hashes representing the customer's RT tickets.
4064 An optional status (or arrayref or hashref of statuses) may be specified.
4070 my $status = ( @_ && $_[0] ) ? shift : '';
4072 my $num = $conf->config('cust_main-max_tickets') || 10;
4075 if ( $conf->config('ticket_system') ) {
4076 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4078 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4087 foreach my $priority (
4088 $conf->config('ticket_system-custom_priority_field-values'), ''
4090 last if scalar(@tickets) >= $num;
4092 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4093 $num - scalar(@tickets),
4104 =item appointments [ STATUS ]
4106 Returns an array of hashes representing the customer's RT tickets which
4113 my $status = ( @_ && $_[0] ) ? shift : '';
4115 return () unless $conf->config('ticket_system');
4117 my $queueid = $conf->config('ticket_system-appointment-queueid');
4119 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4128 # Return services representing svc_accts in customer support packages
4129 sub support_services {
4131 my %packages = map { $_ => 1 } $conf->config('support_packages');
4133 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4134 grep { $_->part_svc->svcdb eq 'svc_acct' }
4135 map { $_->cust_svc }
4136 grep { exists $packages{ $_->pkgpart } }
4137 $self->ncancelled_pkgs;
4141 # Return a list of latitude/longitude for one of the services (if any)
4142 sub service_coordinates {
4146 grep { $_->latitude && $_->longitude }
4148 map { $_->cust_svc }
4149 $self->ncancelled_pkgs;
4151 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4156 Returns a masked version of the named field
4161 my ($self,$field) = @_;
4165 'x'x(length($self->getfield($field))-4).
4166 substr($self->getfield($field), (length($self->getfield($field))-4));
4170 =item payment_history
4172 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4173 cust_credit and cust_refund objects. Each hashref has the following fields:
4175 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4177 I<date> - value of _date field, unix timestamp
4179 I<date_pretty> - user-friendly date
4181 I<description> - user-friendly description of item
4183 I<amount> - impact of item on user's balance
4184 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4185 Not to be confused with the native 'amount' field in cust_credit, see below.
4187 I<amount_pretty> - includes money char
4189 I<balance> - customer balance, chronologically as of this item
4191 I<balance_pretty> - includes money char
4193 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4195 I<paid> - amount paid for cust_pay records, undef for other types
4197 I<credit> - amount credited for cust_credit records, undef for other types.
4198 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4200 I<refund> - amount refunded for cust_refund records, undef for other types
4202 The four table-specific keys always have positive values, whether they reflect charges or payments.
4204 The following options may be passed to this method:
4206 I<line_items> - if true, returns charges ('Line item') rather than invoices
4208 I<start_date> - unix timestamp, only include records on or after.
4209 If specified, an item of type 'Previous' will also be included.
4210 It does not have table-specific fields.
4212 I<end_date> - unix timestamp, only include records before
4214 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4216 I<conf> - optional already-loaded FS::Conf object.
4220 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4221 # and also for sending customer statements, which should both be kept customer-friendly.
4222 # If you add anything that shouldn't be passed on through the API or exposed
4223 # to customers, add a new option to include it, don't include it by default
4224 sub payment_history {
4226 my $opt = ref($_[0]) ? $_[0] : { @_ };
4228 my $conf = $$opt{'conf'} || new FS::Conf;
4229 my $money_char = $conf->config("money_char") || '$',
4231 #first load entire history,
4232 #need previous to calculate previous balance
4233 #loading after end_date shouldn't hurt too much?
4235 if ( $$opt{'line_items'} ) {
4237 foreach my $cust_bill ( $self->cust_bill ) {
4240 'type' => 'Line item',
4241 'description' => $_->desc( $self->locale ).
4242 ( $_->sdate && $_->edate
4243 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4244 ' To '. time2str('%d-%b-%Y', $_->edate)
4247 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4248 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4249 'date' => $cust_bill->_date,
4250 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4252 foreach $cust_bill->cust_bill_pkg;
4259 'type' => 'Invoice',
4260 'description' => 'Invoice #'. $_->display_invnum,
4261 'amount' => sprintf('%.2f', $_->charged ),
4262 'charged' => sprintf('%.2f', $_->charged ),
4263 'date' => $_->_date,
4264 'date_pretty' => $self->time2str_local('short', $_->_date ),
4266 foreach $self->cust_bill;
4271 'type' => 'Payment',
4272 'description' => 'Payment', #XXX type
4273 'amount' => sprintf('%.2f', 0 - $_->paid ),
4274 'paid' => sprintf('%.2f', $_->paid ),
4275 'date' => $_->_date,
4276 'date_pretty' => $self->time2str_local('short', $_->_date ),
4278 foreach $self->cust_pay;
4282 'description' => 'Credit', #more info?
4283 'amount' => sprintf('%.2f', 0 -$_->amount ),
4284 'credit' => sprintf('%.2f', $_->amount ),
4285 'date' => $_->_date,
4286 'date_pretty' => $self->time2str_local('short', $_->_date ),
4288 foreach $self->cust_credit;
4292 'description' => 'Refund', #more info? type, like payment?
4293 'amount' => $_->refund,
4294 'refund' => $_->refund,
4295 'date' => $_->_date,
4296 'date_pretty' => $self->time2str_local('short', $_->_date ),
4298 foreach $self->cust_refund;
4300 #put it all in chronological order
4301 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4303 #calculate balance, filter items outside date range
4307 foreach my $item (@history) {
4308 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4309 $balance += $$item{'amount'};
4310 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4311 $previous += $$item{'amount'};
4314 $$item{'balance'} = sprintf("%.2f",$balance);
4315 foreach my $key ( qw(amount balance) ) {
4316 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4321 # start with previous balance, if there was one
4324 'type' => 'Previous',
4325 'description' => 'Previous balance',
4326 'amount' => sprintf("%.2f",$previous),
4327 'balance' => sprintf("%.2f",$previous),
4328 'date' => $$opt{'start_date'},
4329 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4331 #false laziness with above
4332 foreach my $key ( qw(amount balance) ) {
4333 $$item{$key.'_pretty'} = $$item{$key};
4334 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4336 unshift(@out,$item);
4339 @out = reverse @history if $$opt{'reverse_sort'};
4344 =item save_cust_payby
4346 Saves a new cust_payby for this customer, replacing an existing entry only
4347 in select circumstances. Does not validate input.
4349 If auto is specified, marks this as the customer's primary method, or the
4350 specified weight. Existing payment methods have their weight incremented as
4353 If bill_location is specified with auto, also sets location in cust_main.
4355 Will not insert complete duplicates of existing records, or records in which the
4356 only difference from an existing record is to turn off automatic payment (will
4357 return without error.) Will replace existing records in which the only difference
4358 is to add a value to a previously empty preserved field and/or turn on automatic payment.
4359 Fields marked as preserved are optional, and existing values will not be overwritten with
4360 blanks when replacing.
4362 Accepts the following named parameters:
4372 save as an automatic payment type (CARD/CHEK if true, DCRD/DCHK if false)
4376 optional, set higher than 1 for secondary, etc.
4384 optional, but should be specified for anything that might be tokenized, will be preserved when replacing
4392 optional, will be preserved when replacing
4400 CARD only, required, FS::cust_location object
4402 =item paystart_month
4404 CARD only, optional, will be preserved when replacing
4408 CARD only, optional, will be preserved when replacing
4412 CARD only, optional, will be preserved when replacing
4416 CARD only, only used if conf cvv-save is set appropriately
4430 #The code for this option is in place, but it's not currently used
4434 # existing cust_payby object to be replaced (must match custnum)
4436 # stateid/stateid_state/ss are not currently supported in cust_payby,
4437 # might not even work properly in 4.x, but will need to work here if ever added
4439 sub save_cust_payby {
4443 my $old = $opt{'replace'};
4444 my $new = new FS::cust_payby { $old ? $old->hash : () };
4445 return "Customer number does not match" if $new->custnum and $new->custnum != $self->custnum;
4446 $new->set( 'custnum' => $self->custnum );
4448 my $payby = $opt{'payment_payby'};
4449 return "Bad payby" unless grep(/^$payby$/,('CARD','CHEK'));
4451 # don't allow turning off auto when replacing
4452 $opt{'auto'} ||= 1 if $old and $old->payby !~ /^D/;
4454 my @check_existing; # payby relevant to this payment_payby
4456 # set payby based on auto
4457 if ( $payby eq 'CARD' ) {
4458 $new->set( 'payby' => ( $opt{'auto'} ? 'CARD' : 'DCRD' ) );
4459 @check_existing = qw( CARD DCRD );
4460 } elsif ( $payby eq 'CHEK' ) {
4461 $new->set( 'payby' => ( $opt{'auto'} ? 'CHEK' : 'DCHK' ) );
4462 @check_existing = qw( CHEK DCHK );
4465 $new->set( 'weight' => $opt{'auto'} ? $opt{'weight'} : '' );
4468 $new->payinfo($opt{'payinfo'}); # sets default paymask, but not if it's already tokenized
4469 $new->paymask($opt{'paymask'}) if $opt{'paymask'}; # in case it's been tokenized, override with loaded paymask
4470 $new->set( 'payname' => $opt{'payname'} );
4471 $new->set( 'payip' => $opt{'payip'} ); # will be preserved below
4473 my $conf = new FS::Conf;
4475 # compare to FS::cust_main::realtime_bop - check both to make sure working correctly
4476 if ( $payby eq 'CARD' &&
4477 ( (grep { $_ eq cardtype($opt{'payinfo'}) } $conf->config('cvv-save'))
4478 || $conf->exists('business-onlinepayment-verification')
4481 $new->set( 'paycvv' => $opt{'paycvv'} );
4483 $new->set( 'paycvv' => '');
4486 local $SIG{HUP} = 'IGNORE';
4487 local $SIG{INT} = 'IGNORE';
4488 local $SIG{QUIT} = 'IGNORE';
4489 local $SIG{TERM} = 'IGNORE';
4490 local $SIG{TSTP} = 'IGNORE';
4491 local $SIG{PIPE} = 'IGNORE';
4493 my $oldAutoCommit = $FS::UID::AutoCommit;
4494 local $FS::UID::AutoCommit = 0;
4497 # set fields specific to payment_payby
4498 if ( $payby eq 'CARD' ) {
4499 if ($opt{'bill_location'}) {
4500 $opt{'bill_location'}->set('custnum' => $self->custnum);
4501 my $error = $opt{'bill_location'}->find_or_insert;
4503 $dbh->rollback if $oldAutoCommit;
4506 $new->set( 'locationnum' => $opt{'bill_location'}->locationnum );
4508 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
4509 $new->set( $field => $opt{$field} );
4512 foreach my $field ( qw(paytype paystate) ) {
4513 $new->set( $field => $opt{$field} );
4517 # other cust_payby to compare this to
4518 my @existing = $self->cust_payby(@check_existing);
4520 # fields that can overwrite blanks with values, but not values with blanks
4521 my @preserve = qw( paymask locationnum paystart_month paystart_year payissue payip );
4523 my $skip_cust_payby = 0; # true if we don't need to save or reweight cust_payby
4525 # generally, we don't want to overwrite existing cust_payby with this,
4526 # but we can replace if we're only marking it auto or adding a preserved field
4527 # and we can avoid saving a total duplicate or merely turning off auto
4529 foreach my $cust_payby (@existing) {
4530 # check fields that absolutely should not change
4531 foreach my $field ($new->fields) {
4532 next if grep(/^$field$/, qw( custpaybynum payby weight ) );
4533 next if grep(/^$field$/, @preserve );
4534 next PAYBYLOOP unless $new->get($field) eq $cust_payby->get($field);
4536 # now check fields that can replace if one value is blank
4538 foreach my $field (@preserve) {
4540 ( $new->get($field) and !$cust_payby->get($field) ) or
4541 ( $cust_payby->get($field) and !$new->get($field) )
4543 # prevention of overwriting values with blanks happens farther below
4545 } elsif ( $new->get($field) ne $cust_payby->get($field) ) {
4549 unless ( $replace ) {
4550 # nearly identical, now check weight
4551 if ($new->get('weight') eq $cust_payby->get('weight') or !$new->get('weight')) {
4552 # ignore identical cust_payby, and ignore attempts to turn off auto
4553 # no need to save or re-weight cust_payby (but still need to update/commit $self)
4554 $skip_cust_payby = 1;
4557 # otherwise, only change is to mark this as primary
4559 # if we got this far, we're definitely replacing
4566 $new->set( 'custpaybynum' => $old->custpaybynum );
4567 # don't turn off automatic payment (but allow it to be turned on)
4568 if ($new->payby =~ /^D/ and $new->payby ne $old->payby) {
4570 $new->set( 'payby' => $old->payby );
4571 $new->set( 'weight' => 1 );
4573 # make sure we're not overwriting values with blanks
4574 foreach my $field (@preserve) {
4575 if ( $old->get($field) and !$new->get($field) ) {
4576 $new->set( $field => $old->get($field) );
4581 # only overwrite cust_main bill_location if auto
4582 if ($opt{'auto'} && $opt{'bill_location'}) {
4583 $self->set('bill_location' => $opt{'bill_location'});
4584 my $error = $self->replace;
4586 $dbh->rollback if $oldAutoCommit;
4591 # done with everything except reweighting and saving cust_payby
4592 # still need to commit changes to cust_main and cust_location
4593 if ($skip_cust_payby) {
4594 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4598 # re-weight existing primary cust_pay for this payby
4600 foreach my $cust_payby (@existing) {
4601 # relies on cust_payby return order
4602 last unless $cust_payby->payby !~ /^D/;
4603 last if $cust_payby->weight > 1;
4604 next if $new->custpaybynum eq $cust_payby->custpaybynum;
4605 next if $cust_payby->weight < ($opt{'weight'} || 1);
4606 $cust_payby->weight( $cust_payby->weight + 1 );
4607 my $error = $cust_payby->replace;
4609 $dbh->rollback if $oldAutoCommit;
4610 return "Error reweighting cust_payby: $error";
4615 # finally, save cust_payby
4616 my $error = $old ? $new->replace($old) : $new->insert;
4618 $dbh->rollback if $oldAutoCommit;
4622 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4627 =item remove_cvv_from_cust_payby PAYINFO
4629 Removes paycvv from associated cust_payby with matching PAYINFO.
4633 sub remove_cvv_from_cust_payby {
4634 my ($self,$payinfo) = @_;
4636 my $oldAutoCommit = $FS::UID::AutoCommit;
4637 local $FS::UID::AutoCommit = 0;
4640 foreach my $cust_payby ( qsearch('cust_payby',{ custnum => $self->custnum }) ) {
4641 next unless $cust_payby->payinfo eq $payinfo; # can't qsearch on payinfo
4642 $cust_payby->paycvv('');
4643 my $error = $cust_payby->replace;
4645 $dbh->rollback if $oldAutoCommit;
4650 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4656 =head1 CLASS METHODS
4662 Class method that returns the list of possible status strings for customers
4663 (see L<the status method|/status>). For example:
4665 @statuses = FS::cust_main->statuses();
4671 keys %{ $self->statuscolors };
4674 =item cust_status_sql
4676 Returns an SQL fragment to determine the status of a cust_main record, as a
4681 sub cust_status_sql {
4683 for my $status ( FS::cust_main->statuses() ) {
4684 my $method = $status.'_sql';
4685 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4694 Returns an SQL expression identifying prospective cust_main records (customers
4695 with no packages ever ordered)
4699 use vars qw($select_count_pkgs);
4700 $select_count_pkgs =
4701 "SELECT COUNT(*) FROM cust_pkg
4702 WHERE cust_pkg.custnum = cust_main.custnum";
4704 sub select_count_pkgs_sql {
4709 " 0 = ( $select_count_pkgs ) ";
4714 Returns an SQL expression identifying ordered cust_main records (customers with
4715 no active packages, but recurring packages not yet setup or one time charges
4721 FS::cust_main->none_active_sql.
4722 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4727 Returns an SQL expression identifying active cust_main records (customers with
4728 active recurring packages).
4733 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4736 =item none_active_sql
4738 Returns an SQL expression identifying cust_main records with no active
4739 recurring packages. This includes customers of status prospect, ordered,
4740 inactive, and suspended.
4744 sub none_active_sql {
4745 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4750 Returns an SQL expression identifying inactive cust_main records (customers with
4751 no active recurring packages, but otherwise unsuspended/uncancelled).
4756 FS::cust_main->none_active_sql.
4757 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4763 Returns an SQL expression identifying suspended cust_main records.
4768 sub suspended_sql { susp_sql(@_); }
4770 FS::cust_main->none_active_sql.
4771 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4777 Returns an SQL expression identifying cancelled cust_main records.
4781 sub cancel_sql { shift->cancelled_sql(@_); }
4784 =item uncancelled_sql
4786 Returns an SQL expression identifying un-cancelled cust_main records.
4790 sub uncancelled_sql { uncancel_sql(@_); }
4793 "( NOT (".$self->cancelled_sql.") )"; #sensitive to cust_main-status_module
4798 Returns an SQL fragment to retreive the balance.
4803 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4804 WHERE cust_bill.custnum = cust_main.custnum )
4805 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4806 WHERE cust_pay.custnum = cust_main.custnum )
4807 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4808 WHERE cust_credit.custnum = cust_main.custnum )
4809 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4810 WHERE cust_refund.custnum = cust_main.custnum )
4813 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4815 Returns an SQL fragment to retreive the balance for this customer, optionally
4816 considering invoices with date earlier than START_TIME, and not
4817 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4818 total_unapplied_payments).
4820 Times are specified as SQL fragments or numeric
4821 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4822 L<Date::Parse> for conversion functions. The empty string can be passed
4823 to disable that time constraint completely.
4825 Available options are:
4829 =item unapplied_date
4831 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)
4836 set to true to remove all customer comparison clauses, for totals
4841 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4846 JOIN clause (typically used with the total option)
4850 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4851 time will be ignored. Note that START_TIME and END_TIME only limit the date
4852 range for invoices and I<unapplied> payments, credits, and refunds.
4858 sub balance_date_sql {
4859 my( $class, $start, $end, %opt ) = @_;
4861 my $cutoff = $opt{'cutoff'};
4863 my $owed = FS::cust_bill->owed_sql($cutoff);
4864 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4865 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4866 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4868 my $j = $opt{'join'} || '';
4870 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4871 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4872 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4873 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4875 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4876 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4877 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4878 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4883 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4885 Returns an SQL fragment to retreive the total unapplied payments for this
4886 customer, only considering payments with date earlier than START_TIME, and
4887 optionally not later than END_TIME.
4889 Times are specified as SQL fragments or numeric
4890 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4891 L<Date::Parse> for conversion functions. The empty string can be passed
4892 to disable that time constraint completely.
4894 Available options are:
4898 sub unapplied_payments_date_sql {
4899 my( $class, $start, $end, %opt ) = @_;
4901 my $cutoff = $opt{'cutoff'};
4903 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4905 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4906 'unapplied_date'=>1 );
4908 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4911 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4913 Helper method for balance_date_sql; name (and usage) subject to change
4914 (suggestions welcome).
4916 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4917 cust_refund, cust_credit or cust_pay).
4919 If TABLE is "cust_bill" or the unapplied_date option is true, only
4920 considers records with date earlier than START_TIME, and optionally not
4921 later than END_TIME .
4925 sub _money_table_where {
4926 my( $class, $table, $start, $end, %opt ) = @_;
4929 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4930 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4931 push @where, "$table._date <= $start" if defined($start) && length($start);
4932 push @where, "$table._date > $end" if defined($end) && length($end);
4934 push @where, @{$opt{'where'}} if $opt{'where'};
4935 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4941 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4942 use FS::cust_main::Search;
4945 FS::cust_main::Search->search(@_);
4954 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4956 Generates a templated notification to the customer (see L<Text::Template>).
4958 OPTIONS is a hash and may include
4960 I<extra_fields> - a hashref of name/value pairs which will be substituted
4961 into the template. These values may override values mentioned below
4962 and those from the customer record.
4964 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
4966 The following variables are available in the template instead of or in addition
4967 to the fields of the customer record.
4969 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4973 # a lot like cust_bill::print_latex
4974 sub generate_letter {
4975 my ($self, $template, %options) = @_;
4977 warn "Template $template does not exist" && return
4978 unless $conf->exists($template) || $options{'template_text'};
4980 my $template_source = $options{'template_text'}
4981 ? [ $options{'template_text'} ]
4982 : [ map "$_\n", $conf->config($template) ];
4984 my $letter_template = new Text::Template
4986 SOURCE => $template_source,
4987 DELIMITERS => [ '[@--', '--@]' ],
4989 or die "can't create new Text::Template object: Text::Template::ERROR";
4991 $letter_template->compile()
4992 or die "can't compile template: Text::Template::ERROR";
4994 my %letter_data = map { $_ => $self->$_ } $self->fields;
4996 for (keys %{$options{extra_fields}}){
4997 $letter_data{$_} = $options{extra_fields}->{$_};
5000 unless(exists($letter_data{returnaddress})){
5001 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5002 $self->agent_template)
5004 if ( length($retadd) ) {
5005 $letter_data{returnaddress} = $retadd;
5006 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5007 $letter_data{returnaddress} =
5008 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5012 ( $conf->config('company_name', $self->agentnum),
5013 $conf->config('company_address', $self->agentnum),
5017 $letter_data{returnaddress} = '~';
5021 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5023 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5025 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5027 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5031 ) or die "can't open temp file: $!\n";
5032 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5033 or die "can't write temp file: $!\n";
5035 $letter_data{'logo_file'} = $lh->filename;
5037 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5041 ) or die "can't open temp file: $!\n";
5043 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5045 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5046 return ($1, $letter_data{'logo_file'});
5050 =item print_ps TEMPLATE
5052 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5058 my($file, $lfile) = $self->generate_letter(@_);
5059 my $ps = FS::Misc::generate_ps($file);
5060 unlink($file.'.tex');
5066 =item print TEMPLATE
5068 Prints the filled in template.
5070 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5074 sub queueable_print {
5077 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5078 or die "invalid customer number: " . $opt{custnum};
5080 #do not backport this change to 3.x
5081 # my $error = $self->print( { 'template' => $opt{template} } );
5082 my $error = $self->print( $opt{'template'} );
5083 die $error if $error;
5087 my ($self, $template) = (shift, shift);
5089 [ $self->print_ps($template) ],
5090 'agentnum' => $self->agentnum,
5094 #these three subs should just go away once agent stuff is all config overrides
5096 sub agent_template {
5098 $self->_agent_plandata('agent_templatename');
5101 sub agent_invoice_from {
5103 $self->_agent_plandata('agent_invoice_from');
5106 sub _agent_plandata {
5107 my( $self, $option ) = @_;
5109 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5110 #agent-specific Conf
5112 use FS::part_event::Condition;
5114 my $agentnum = $self->agentnum;
5116 my $regexp = regexp_sql();
5118 my $part_event_option =
5120 'select' => 'part_event_option.*',
5121 'table' => 'part_event_option',
5123 LEFT JOIN part_event USING ( eventpart )
5124 LEFT JOIN part_event_option AS peo_agentnum
5125 ON ( part_event.eventpart = peo_agentnum.eventpart
5126 AND peo_agentnum.optionname = 'agentnum'
5127 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5129 LEFT JOIN part_event_condition
5130 ON ( part_event.eventpart = part_event_condition.eventpart
5131 AND part_event_condition.conditionname = 'cust_bill_age'
5133 LEFT JOIN part_event_condition_option
5134 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5135 AND part_event_condition_option.optionname = 'age'
5138 #'hashref' => { 'optionname' => $option },
5139 #'hashref' => { 'part_event_option.optionname' => $option },
5141 " WHERE part_event_option.optionname = ". dbh->quote($option).
5142 " AND action = 'cust_bill_send_agent' ".
5143 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5144 " AND peo_agentnum.optionname = 'agentnum' ".
5145 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5147 CASE WHEN part_event_condition_option.optionname IS NULL
5149 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5151 , part_event.weight".
5155 unless ( $part_event_option ) {
5156 return $self->agent->invoice_template || ''
5157 if $option eq 'agent_templatename';
5161 $part_event_option->optionvalue;
5165 sub process_o2m_qsearch {
5168 return qsearch($table, @_) unless $table eq 'contact';
5170 my $hashref = shift;
5171 my %hash = %$hashref;
5172 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5173 or die 'guru meditation #4343';
5175 qsearch({ 'table' => 'contact',
5176 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5177 'hashref' => \%hash,
5178 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5179 " cust_contact.custnum = $custnum "
5183 sub process_o2m_qsearchs {
5186 return qsearchs($table, @_) unless $table eq 'contact';
5188 my $hashref = shift;
5189 my %hash = %$hashref;
5190 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5191 or die 'guru meditation #2121';
5193 qsearchs({ 'table' => 'contact',
5194 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5195 'hashref' => \%hash,
5196 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5197 " cust_contact.custnum = $custnum "
5201 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5203 Subroutine (not a method), designed to be called from the queue.
5205 Takes a list of options and values.
5207 Pulls up the customer record via the custnum option and calls bill_and_collect.
5212 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5214 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5215 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5217 #without this errors don't get rolled back
5218 $args{'fatal'} = 1; # runs from job queue, will be caught
5220 $cust_main->bill_and_collect( %args );
5223 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5225 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5226 C<collect> part. This is used in batch tax calculation, where invoice
5227 generation and collection events have to be completely separated.
5231 sub queued_collect {
5233 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5235 $cust_main->collect(%args);
5238 sub process_bill_and_collect {
5241 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5242 or die "custnum '$param->{custnum}' not found!\n";
5243 $param->{'job'} = $job;
5244 $param->{'fatal'} = 1; # runs from job queue, will be caught
5245 $param->{'retry'} = 1;
5247 $cust_main->bill_and_collect( %$param );
5250 #starting to take quite a while for big dbs
5251 # (JRNL: journaled so it only happens once per database)
5252 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5253 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5254 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5255 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5256 # JRNL leading/trailing spaces in first, last, company
5257 # JRNL migrate to cust_payby
5258 # - otaker upgrade? journal and call it good? (double check to make sure
5259 # we're not still setting otaker here)
5261 #only going to get worse with new location stuff...
5263 sub _upgrade_data { #class method
5264 my ($class, %opts) = @_;
5266 my @statements = ();
5268 #this seems to be the only expensive one.. why does it take so long?
5269 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5271 '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';
5272 FS::upgrade_journal->set_done('cust_main__signupdate');
5276 foreach my $sql ( @statements ) {
5277 my $sth = dbh->prepare($sql) or die dbh->errstr;
5278 $sth->execute or die $sth->errstr;
5279 #warn ( (time - $t). " seconds\n" );
5283 local($ignore_expired_card) = 1;
5284 local($ignore_banned_card) = 1;
5285 local($skip_fuzzyfiles) = 1;
5286 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5288 FS::cust_main::Location->_upgrade_data(%opts);
5290 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5292 foreach my $cust_main ( qsearch({
5293 'table' => 'cust_main',
5295 'extra_sql' => 'WHERE '.
5297 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5298 qw( first last company )
5301 my $error = $cust_main->replace;
5302 die $error if $error;
5305 FS::upgrade_journal->set_done('cust_main__trimspaces');
5309 $class->_upgrade_otaker(%opts);
5319 The delete method should possibly take an FS::cust_main object reference
5320 instead of a scalar customer number.
5322 Bill and collect options should probably be passed as references instead of a
5325 There should probably be a configuration file with a list of allowed credit
5328 No multiple currency support (probably a larger project than just this module).
5330 Birthdates rely on negative epoch values.
5332 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5336 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5337 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5338 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.