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::payinfo_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 FS::UID qw( dbh driver_name );
32 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
34 use FS::Misc qw( generate_ps do_print money_pretty );
35 use FS::Msgcat qw(gettext);
42 use FS::cust_bill_void;
43 use FS::legacy_cust_bill;
45 use FS::cust_pay_pending;
46 use FS::cust_pay_void;
47 use FS::cust_pay_batch;
50 use FS::part_referral;
51 use FS::cust_main_county;
52 use FS::cust_location;
55 use FS::cust_main_exemption;
56 use FS::cust_tax_adjustment;
57 use FS::cust_tax_location;
58 use FS::agent_currency;
59 use FS::cust_main_invoice;
61 use FS::prepay_credit;
67 use FS::payment_gateway;
68 use FS::agent_payment_gateway;
70 use FS::cust_main_note;
71 use FS::cust_attachment;
74 use FS::upgrade_journal;
79 # 1 is mostly method/subroutine entry and options
80 # 2 traces progress of some operations
81 # 3 is even more information including possibly sensitive data
83 our $me = '[FS::cust_main]';
86 our $ignore_expired_card = 0;
87 our $ignore_banned_card = 0;
88 our $ignore_invalid_card = 0;
90 our $skip_fuzzyfiles = 0;
92 our $ucfirst_nowarn = 0;
94 #this info is in cust_payby as of 4.x
95 #this and the fields themselves can be removed in 5.x
96 our @encrypted_fields = ('payinfo', 'paycvv');
97 sub nohistory_fields { ('payinfo', 'paycvv'); }
100 #ask FS::UID to run this stuff for us later
101 #$FS::UID::callback{'FS::cust_main'} = sub {
102 install_callback FS::UID sub {
103 $conf = new FS::Conf;
104 #yes, need it for stuff below (prolly should be cached)
105 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
110 my ( $hashref, $cache ) = @_;
111 if ( exists $hashref->{'pkgnum'} ) {
112 #@{ $self->{'_pkgnum'} } = ();
113 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
114 $self->{'_pkgnum'} = $subcache;
115 #push @{ $self->{'_pkgnum'} },
116 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
122 FS::cust_main - Object methods for cust_main records
128 $record = new FS::cust_main \%hash;
129 $record = new FS::cust_main { 'column' => 'value' };
131 $error = $record->insert;
133 $error = $new_record->replace($old_record);
135 $error = $record->delete;
137 $error = $record->check;
139 @cust_pkg = $record->all_pkgs;
141 @cust_pkg = $record->ncancelled_pkgs;
143 @cust_pkg = $record->suspended_pkgs;
145 $error = $record->bill;
146 $error = $record->bill %options;
147 $error = $record->bill 'time' => $time;
149 $error = $record->collect;
150 $error = $record->collect %options;
151 $error = $record->collect 'invoice_time' => $time,
156 An FS::cust_main object represents a customer. FS::cust_main inherits from
157 FS::Record. The following fields are currently supported:
163 Primary key (assigned automatically for new customers)
167 Agent (see L<FS::agent>)
171 Advertising source (see L<FS::part_referral>)
183 Cocial security number (optional)
207 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
211 Payment Information (See L<FS::payinfo_Mixin> for data format)
215 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
219 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
223 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
227 Start date month (maestro/solo cards only)
231 Start date year (maestro/solo cards only)
235 Issue number (maestro/solo cards only)
239 Name on card or billing name
243 IP address from which payment information was received
247 Tax exempt, empty or `Y'
251 Order taker (see L<FS::access_user>)
257 =item referral_custnum
259 Referring customer number
263 Enable individual CDR spooling, empty or `Y'
267 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
271 Discourage individual CDR printing, empty or `Y'
275 Allow self-service editing of ticket subjects, empty or 'Y'
277 =item calling_list_exempt
279 Do not call, empty or 'Y'
281 =item invoice_ship_address
283 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
293 Creates a new customer. To add the customer to the database, see L<"insert">.
295 Note that this stores the hash reference, not a distinct copy of the hash it
296 points to. You can ask the object for a copy with the I<hash> method.
300 sub table { 'cust_main'; }
302 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
304 Adds this customer to the database. If there is an error, returns the error,
305 otherwise returns false.
307 Usually the customer's location will not yet exist in the database, and
308 the C<bill_location> and C<ship_location> pseudo-fields must be set to
309 uninserted L<FS::cust_location> objects. These will be inserted and linked
310 (in both directions) to the new customer record. If they're references
311 to the same object, they will become the same location.
313 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
314 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
315 are inserted atomicly, or the transaction is rolled back. Passing an empty
316 hash reference is equivalent to not supplying this parameter. There should be
317 a better explanation of this, but until then, here's an example:
320 tie %hash, 'Tie::RefHash'; #this part is important
322 $cust_pkg => [ $svc_acct ],
325 $cust_main->insert( \%hash );
327 INVOICING_LIST_ARYREF: No longer supported.
329 Currently available options are: I<depend_jobnum>, I<noexport>,
330 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
332 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
333 on the supplied jobnum (they will not run until the specific job completes).
334 This can be used to defer provisioning until some action completes (such
335 as running the customer's credit card successfully).
337 The I<noexport> option is deprecated. If I<noexport> is set true, no
338 provisioning jobs (exports) are scheduled. (You can schedule them later with
339 the B<reexport> method.)
341 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
342 of tax names and exemption numbers. FS::cust_main_exemption records will be
343 created and inserted.
345 If I<prospectnum> is set, moves contacts and locations from that prospect.
347 If I<contact> is set to an arrayref of FS::contact objects, those will be
350 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
351 unset), inserts those new contacts with this new customer. Handles CGI
352 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
354 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
355 new stored payment records with this new customer. Handles CGI parameters
356 for an "m2" multiple entry field as passed by edit/cust_main.cgi
362 my $cust_pkgs = @_ ? shift : {};
364 if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
365 warn "cust_main::insert using deprecated invoicing list argument";
366 $invoicing_list = shift;
369 warn "$me insert called with options ".
370 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
373 local $SIG{HUP} = 'IGNORE';
374 local $SIG{INT} = 'IGNORE';
375 local $SIG{QUIT} = 'IGNORE';
376 local $SIG{TERM} = 'IGNORE';
377 local $SIG{TSTP} = 'IGNORE';
378 local $SIG{PIPE} = 'IGNORE';
380 my $oldAutoCommit = $FS::UID::AutoCommit;
381 local $FS::UID::AutoCommit = 0;
384 my $prepay_identifier = '';
385 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
387 if ( $self->payby eq 'PREPAY' ) {
389 $self->payby(''); #'BILL');
390 $prepay_identifier = $self->payinfo;
393 warn " looking up prepaid card $prepay_identifier\n"
396 my $error = $self->get_prepay( $prepay_identifier,
397 'amount_ref' => \$amount,
398 'seconds_ref' => \$seconds,
399 'upbytes_ref' => \$upbytes,
400 'downbytes_ref' => \$downbytes,
401 'totalbytes_ref' => \$totalbytes,
404 $dbh->rollback if $oldAutoCommit;
405 #return "error applying prepaid card (transaction rolled back): $error";
409 $payby = 'PREP' if $amount;
411 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
414 $self->payby(''); #'BILL');
415 $amount = $self->paid;
420 foreach my $l (qw(bill_location ship_location)) {
422 my $loc = delete $self->hashref->{$l} or next;
424 if ( !$loc->locationnum ) {
425 # warn the location that we're going to insert it with no custnum
426 $loc->set(custnum_pending => 1);
427 warn " inserting $l\n"
429 my $error = $loc->insert;
431 $dbh->rollback if $oldAutoCommit;
432 my $label = $l eq 'ship_location' ? 'service' : 'billing';
433 return "$error (in $label location)";
436 } elsif ( $loc->prospectnum ) {
438 $loc->prospectnum('');
439 $loc->set(custnum_pending => 1);
440 my $error = $loc->replace;
442 $dbh->rollback if $oldAutoCommit;
443 my $label = $l eq 'ship_location' ? 'service' : 'billing';
444 return "$error (moving $label location)";
447 } elsif ( ($loc->custnum || 0) > 0 ) {
448 # then it somehow belongs to another customer--shouldn't happen
449 $dbh->rollback if $oldAutoCommit;
450 return "$l belongs to customer ".$loc->custnum;
452 # else it already belongs to this customer
453 # (happens when ship_location is identical to bill_location)
455 $self->set($l.'num', $loc->locationnum);
457 if ( $self->get($l.'num') eq '' ) {
458 $dbh->rollback if $oldAutoCommit;
463 warn " inserting $self\n"
466 $self->signupdate(time) unless $self->signupdate;
468 $self->auto_agent_custid()
469 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
471 my $error = $self->SUPER::insert;
473 $dbh->rollback if $oldAutoCommit;
474 #return "inserting cust_main record (transaction rolled back): $error";
478 # now set cust_location.custnum
479 foreach my $l (qw(bill_location ship_location)) {
480 warn " setting $l.custnum\n"
482 my $loc = $self->$l or next;
483 unless ( $loc->custnum ) {
484 $loc->set(custnum => $self->custnum);
485 $error ||= $loc->replace;
489 $dbh->rollback if $oldAutoCommit;
490 return "error setting $l custnum: $error";
494 warn " setting customer tags\n"
497 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
498 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
499 'custnum' => $self->custnum };
500 my $error = $cust_tag->insert;
502 $dbh->rollback if $oldAutoCommit;
507 my $prospectnum = delete $options{'prospectnum'};
508 if ( $prospectnum ) {
510 warn " moving contacts and locations from prospect $prospectnum\n"
514 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
515 unless ( $prospect_main ) {
516 $dbh->rollback if $oldAutoCommit;
517 return "Unknown prospectnum $prospectnum";
519 $prospect_main->custnum($self->custnum);
520 $prospect_main->disabled('Y');
521 my $error = $prospect_main->replace;
523 $dbh->rollback if $oldAutoCommit;
527 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
528 my $cust_contact = new FS::cust_contact {
529 'custnum' => $self->custnum,
530 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
532 my $error = $cust_contact->insert
533 || $prospect_contact->delete;
535 $dbh->rollback if $oldAutoCommit;
540 my @cust_location = $prospect_main->cust_location;
541 my @qual = $prospect_main->qual;
543 foreach my $r ( @cust_location, @qual ) {
545 $r->custnum($self->custnum);
546 my $error = $r->replace;
548 $dbh->rollback if $oldAutoCommit;
555 warn " setting contacts\n"
558 $invoicing_list ||= $options{'invoicing_list'};
559 if ( $invoicing_list ) {
561 $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
564 foreach my $dest (@$invoicing_list ) {
565 if ($dest eq 'POST') {
566 $self->set('postal_invoice', 'Y');
569 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
570 if ( $contact_email ) {
571 my $cust_contact = FS::cust_contact->new({
572 contactnum => $contact_email->contactnum,
573 custnum => $self->custnum,
575 $cust_contact->set('invoice_dest', 'Y');
576 my $error = $cust_contact->contactnum ?
577 $cust_contact->replace : $cust_contact->insert;
579 $dbh->rollback if $oldAutoCommit;
580 return "$error (linking to email address $dest)";
584 # this email address is not yet linked to any contact
585 $email .= ',' if length($email);
591 my $contact = FS::contact->new({
592 'custnum' => $self->get('custnum'),
593 'last' => $self->get('last'),
594 'first' => $self->get('first'),
595 'emailaddress' => $email,
596 'invoice_dest' => 'Y', # yes, you can set this via the contact
598 my $error = $contact->insert;
600 $dbh->rollback if $oldAutoCommit;
606 if ( my $contact = delete $options{'contact'} ) {
608 foreach my $c ( @$contact ) {
609 $c->custnum($self->custnum);
610 my $error = $c->insert;
612 $dbh->rollback if $oldAutoCommit;
618 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
620 my $error = $self->process_o2m( 'table' => 'contact',
621 'fields' => FS::contact->cgi_contact_fields,
622 'params' => $contact_params,
625 $dbh->rollback if $oldAutoCommit;
630 warn " setting cust_payby\n"
633 if ( $options{cust_payby} ) {
635 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
636 $cust_payby->custnum($self->custnum);
637 my $error = $cust_payby->insert;
639 $dbh->rollback if $oldAutoCommit;
644 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
646 my $error = $self->process_o2m(
647 'table' => 'cust_payby',
648 'fields' => FS::cust_payby->cgi_cust_payby_fields,
649 'params' => $cust_payby_params,
650 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
653 $dbh->rollback if $oldAutoCommit;
659 warn " setting cust_main_exemption\n"
662 my $tax_exemption = delete $options{'tax_exemption'};
663 if ( $tax_exemption ) {
665 $tax_exemption = { map { $_ => '' } @$tax_exemption }
666 if ref($tax_exemption) eq 'ARRAY';
668 foreach my $taxname ( keys %$tax_exemption ) {
669 my $cust_main_exemption = new FS::cust_main_exemption {
670 'custnum' => $self->custnum,
671 'taxname' => $taxname,
672 'exempt_number' => $tax_exemption->{$taxname},
674 my $error = $cust_main_exemption->insert;
676 $dbh->rollback if $oldAutoCommit;
677 return "inserting cust_main_exemption (transaction rolled back): $error";
682 warn " ordering packages\n"
685 $error = $self->order_pkgs( $cust_pkgs,
687 'seconds_ref' => \$seconds,
688 'upbytes_ref' => \$upbytes,
689 'downbytes_ref' => \$downbytes,
690 'totalbytes_ref' => \$totalbytes,
693 $dbh->rollback if $oldAutoCommit;
698 $dbh->rollback if $oldAutoCommit;
699 return "No svc_acct record to apply pre-paid time";
701 if ( $upbytes || $downbytes || $totalbytes ) {
702 $dbh->rollback if $oldAutoCommit;
703 return "No svc_acct record to apply pre-paid data";
707 warn " inserting initial $payby payment of $amount\n"
709 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
711 $dbh->rollback if $oldAutoCommit;
712 return "inserting payment (transaction rolled back): $error";
716 unless ( $import || $skip_fuzzyfiles ) {
717 warn " queueing fuzzyfiles update\n"
719 $error = $self->queue_fuzzyfiles_update;
721 $dbh->rollback if $oldAutoCommit;
722 return "updating fuzzy search cache: $error";
726 # FS::geocode_Mixin::after_insert or something?
727 if ( $conf->config('tax_district_method') and !$import ) {
728 # if anything non-empty, try to look it up
729 my $queue = new FS::queue {
730 'job' => 'FS::geocode_Mixin::process_district_update',
731 'custnum' => $self->custnum,
733 my $error = $queue->insert( ref($self), $self->custnum );
735 $dbh->rollback if $oldAutoCommit;
736 return "queueing tax district update: $error";
741 warn " exporting\n" if $DEBUG > 1;
743 my $export_args = $options{'export_args'} || [];
746 map qsearch( 'part_export', {exportnum=>$_} ),
747 $conf->config('cust_main-exports'); #, $agentnum
749 foreach my $part_export ( @part_export ) {
750 my $error = $part_export->export_insert($self, @$export_args);
752 $dbh->rollback if $oldAutoCommit;
753 return "exporting to ". $part_export->exporttype.
754 " (transaction rolled back): $error";
758 #foreach my $depend_jobnum ( @$depend_jobnums ) {
759 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
761 # foreach my $jobnum ( @jobnums ) {
762 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
763 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
765 # my $error = $queue->depend_insert($depend_jobnum);
767 # $dbh->rollback if $oldAutoCommit;
768 # return "error queuing job dependancy: $error";
775 #if ( exists $options{'jobnums'} ) {
776 # push @{ $options{'jobnums'} }, @jobnums;
779 warn " insert complete; committing transaction\n"
782 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
787 use File::CounterFile;
788 sub auto_agent_custid {
791 my $format = $conf->config('cust_main-auto_agent_custid');
793 if ( $format eq '1YMMXXXXXXXX' ) {
795 my $counter = new File::CounterFile 'cust_main.agent_custid';
798 my $ym = 100000000000 + time2str('%y%m00000000', time);
799 if ( $ym > $counter->value ) {
800 $counter->{'value'} = $agent_custid = $ym;
801 $counter->{'updated'} = 1;
803 $agent_custid = $counter->inc;
809 die "Unknown cust_main-auto_agent_custid format: $format";
812 $self->agent_custid($agent_custid);
816 =item PACKAGE METHODS
818 Documentation on customer package methods has been moved to
819 L<FS::cust_main::Packages>.
821 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
823 Recharges this (existing) customer with the specified prepaid card (see
824 L<FS::prepay_credit>), specified either by I<identifier> or as an
825 FS::prepay_credit object. If there is an error, returns the error, otherwise
828 Optionally, five scalar references can be passed as well. They will have their
829 values filled in with the amount, number of seconds, and number of upload,
830 download, and total bytes applied by this prepaid card.
834 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
835 #the only place that uses these args
836 sub recharge_prepay {
837 my( $self, $prepay_credit, $amountref, $secondsref,
838 $upbytesref, $downbytesref, $totalbytesref ) = @_;
840 local $SIG{HUP} = 'IGNORE';
841 local $SIG{INT} = 'IGNORE';
842 local $SIG{QUIT} = 'IGNORE';
843 local $SIG{TERM} = 'IGNORE';
844 local $SIG{TSTP} = 'IGNORE';
845 local $SIG{PIPE} = 'IGNORE';
847 my $oldAutoCommit = $FS::UID::AutoCommit;
848 local $FS::UID::AutoCommit = 0;
851 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
853 my $error = $self->get_prepay( $prepay_credit,
854 'amount_ref' => \$amount,
855 'seconds_ref' => \$seconds,
856 'upbytes_ref' => \$upbytes,
857 'downbytes_ref' => \$downbytes,
858 'totalbytes_ref' => \$totalbytes,
860 || $self->increment_seconds($seconds)
861 || $self->increment_upbytes($upbytes)
862 || $self->increment_downbytes($downbytes)
863 || $self->increment_totalbytes($totalbytes)
864 || $self->insert_cust_pay_prepay( $amount,
866 ? $prepay_credit->identifier
871 $dbh->rollback if $oldAutoCommit;
875 if ( defined($amountref) ) { $$amountref = $amount; }
876 if ( defined($secondsref) ) { $$secondsref = $seconds; }
877 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
878 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
879 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
886 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
888 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
889 specified either by I<identifier> or as an FS::prepay_credit object.
891 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
892 incremented by the values of the prepaid card.
894 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
895 check or set this customer's I<agentnum>.
897 If there is an error, returns the error, otherwise returns false.
903 my( $self, $prepay_credit, %opt ) = @_;
905 local $SIG{HUP} = 'IGNORE';
906 local $SIG{INT} = 'IGNORE';
907 local $SIG{QUIT} = 'IGNORE';
908 local $SIG{TERM} = 'IGNORE';
909 local $SIG{TSTP} = 'IGNORE';
910 local $SIG{PIPE} = 'IGNORE';
912 my $oldAutoCommit = $FS::UID::AutoCommit;
913 local $FS::UID::AutoCommit = 0;
916 unless ( ref($prepay_credit) ) {
918 my $identifier = $prepay_credit;
920 $prepay_credit = qsearchs(
922 { 'identifier' => $identifier },
927 unless ( $prepay_credit ) {
928 $dbh->rollback if $oldAutoCommit;
929 return "Invalid prepaid card: ". $identifier;
934 if ( $prepay_credit->agentnum ) {
935 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
936 $dbh->rollback if $oldAutoCommit;
937 return "prepaid card not valid for agent ". $self->agentnum;
939 $self->agentnum($prepay_credit->agentnum);
942 my $error = $prepay_credit->delete;
944 $dbh->rollback if $oldAutoCommit;
945 return "removing prepay_credit (transaction rolled back): $error";
948 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
949 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
951 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
956 =item increment_upbytes SECONDS
958 Updates this customer's single or primary account (see L<FS::svc_acct>) by
959 the specified number of upbytes. If there is an error, returns the error,
960 otherwise returns false.
964 sub increment_upbytes {
965 _increment_column( shift, 'upbytes', @_);
968 =item increment_downbytes SECONDS
970 Updates this customer's single or primary account (see L<FS::svc_acct>) by
971 the specified number of downbytes. If there is an error, returns the error,
972 otherwise returns false.
976 sub increment_downbytes {
977 _increment_column( shift, 'downbytes', @_);
980 =item increment_totalbytes SECONDS
982 Updates this customer's single or primary account (see L<FS::svc_acct>) by
983 the specified number of totalbytes. If there is an error, returns the error,
984 otherwise returns false.
988 sub increment_totalbytes {
989 _increment_column( shift, 'totalbytes', @_);
992 =item increment_seconds SECONDS
994 Updates this customer's single or primary account (see L<FS::svc_acct>) by
995 the specified number of seconds. If there is an error, returns the error,
996 otherwise returns false.
1000 sub increment_seconds {
1001 _increment_column( shift, 'seconds', @_);
1004 =item _increment_column AMOUNT
1006 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1007 the specified number of seconds or bytes. If there is an error, returns
1008 the error, otherwise returns false.
1012 sub _increment_column {
1013 my( $self, $column, $amount ) = @_;
1014 warn "$me increment_column called: $column, $amount\n"
1017 return '' unless $amount;
1019 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1020 $self->ncancelled_pkgs;
1022 if ( ! @cust_pkg ) {
1023 return 'No packages with primary or single services found'.
1024 ' to apply pre-paid time';
1025 } elsif ( scalar(@cust_pkg) > 1 ) {
1026 #maybe have a way to specify the package/account?
1027 return 'Multiple packages found to apply pre-paid time';
1030 my $cust_pkg = $cust_pkg[0];
1031 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1035 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1037 if ( ! @cust_svc ) {
1038 return 'No account found to apply pre-paid time';
1039 } elsif ( scalar(@cust_svc) > 1 ) {
1040 return 'Multiple accounts found to apply pre-paid time';
1043 my $svc_acct = $cust_svc[0]->svc_x;
1044 warn " found service svcnum ". $svc_acct->pkgnum.
1045 ' ('. $svc_acct->email. ")\n"
1048 $column = "increment_$column";
1049 $svc_acct->$column($amount);
1053 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1055 Inserts a prepayment in the specified amount for this customer. An optional
1056 second argument can specify the prepayment identifier for tracking purposes.
1057 If there is an error, returns the error, otherwise returns false.
1061 sub insert_cust_pay_prepay {
1062 shift->insert_cust_pay('PREP', @_);
1065 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1067 Inserts a cash payment in the specified amount for this customer. An optional
1068 second argument can specify the payment identifier for tracking purposes.
1069 If there is an error, returns the error, otherwise returns false.
1073 sub insert_cust_pay_cash {
1074 shift->insert_cust_pay('CASH', @_);
1077 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1079 Inserts a Western Union payment in the specified amount for this customer. An
1080 optional second argument can specify the prepayment identifier for tracking
1081 purposes. If there is an error, returns the error, otherwise returns false.
1085 sub insert_cust_pay_west {
1086 shift->insert_cust_pay('WEST', @_);
1089 sub insert_cust_pay {
1090 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1091 my $payinfo = scalar(@_) ? shift : '';
1093 my $cust_pay = new FS::cust_pay {
1094 'custnum' => $self->custnum,
1095 'paid' => sprintf('%.2f', $amount),
1096 #'_date' => #date the prepaid card was purchased???
1098 'payinfo' => $payinfo,
1104 =item delete [ OPTION => VALUE ... ]
1106 This deletes the customer. If there is an error, returns the error, otherwise
1109 This will completely remove all traces of the customer record. This is not
1110 what you want when a customer cancels service; for that, cancel all of the
1111 customer's packages (see L</cancel>).
1113 If the customer has any uncancelled packages, you need to pass a new (valid)
1114 customer number for those packages to be transferred to, as the "new_customer"
1115 option. Cancelled packages will be deleted. Did I mention that this is NOT
1116 what you want when a customer cancels service and that you really should be
1117 looking at L<FS::cust_pkg/cancel>?
1119 You can't delete a customer with invoices (see L<FS::cust_bill>),
1120 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1121 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1122 set the "delete_financials" option to a true value.
1127 my( $self, %opt ) = @_;
1129 local $SIG{HUP} = 'IGNORE';
1130 local $SIG{INT} = 'IGNORE';
1131 local $SIG{QUIT} = 'IGNORE';
1132 local $SIG{TERM} = 'IGNORE';
1133 local $SIG{TSTP} = 'IGNORE';
1134 local $SIG{PIPE} = 'IGNORE';
1136 my $oldAutoCommit = $FS::UID::AutoCommit;
1137 local $FS::UID::AutoCommit = 0;
1140 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1141 $dbh->rollback if $oldAutoCommit;
1142 return "Can't delete a master agent customer";
1145 #use FS::access_user
1146 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1147 $dbh->rollback if $oldAutoCommit;
1148 return "Can't delete a master employee customer";
1151 tie my %financial_tables, 'Tie::IxHash',
1152 'cust_bill' => 'invoices',
1153 'cust_statement' => 'statements',
1154 'cust_credit' => 'credits',
1155 'cust_pay' => 'payments',
1156 'cust_refund' => 'refunds',
1159 foreach my $table ( keys %financial_tables ) {
1161 my @records = $self->$table();
1163 if ( @records && ! $opt{'delete_financials'} ) {
1164 $dbh->rollback if $oldAutoCommit;
1165 return "Can't delete a customer with ". $financial_tables{$table};
1168 foreach my $record ( @records ) {
1169 my $error = $record->delete;
1171 $dbh->rollback if $oldAutoCommit;
1172 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1178 my @cust_pkg = $self->ncancelled_pkgs;
1180 my $new_custnum = $opt{'new_custnum'};
1181 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1182 $dbh->rollback if $oldAutoCommit;
1183 return "Invalid new customer number: $new_custnum";
1185 foreach my $cust_pkg ( @cust_pkg ) {
1186 my %hash = $cust_pkg->hash;
1187 $hash{'custnum'} = $new_custnum;
1188 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1189 my $error = $new_cust_pkg->replace($cust_pkg,
1190 options => { $cust_pkg->options },
1193 $dbh->rollback if $oldAutoCommit;
1198 my @cancelled_cust_pkg = $self->all_pkgs;
1199 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1200 my $error = $cust_pkg->delete;
1202 $dbh->rollback if $oldAutoCommit;
1207 #cust_tax_adjustment in financials?
1208 #cust_pay_pending? ouch
1209 foreach my $table (qw(
1210 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1211 cust_payby cust_location cust_main_note cust_tax_adjustment
1212 cust_pay_void cust_pay_batch queue cust_tax_exempt
1214 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1215 my $error = $record->delete;
1217 $dbh->rollback if $oldAutoCommit;
1223 my $sth = $dbh->prepare(
1224 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1226 my $errstr = $dbh->errstr;
1227 $dbh->rollback if $oldAutoCommit;
1230 $sth->execute($self->custnum) or do {
1231 my $errstr = $sth->errstr;
1232 $dbh->rollback if $oldAutoCommit;
1238 my $ticket_dbh = '';
1239 if ($conf->config('ticket_system') eq 'RT_Internal') {
1241 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1242 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1243 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1244 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1247 if ( $ticket_dbh ) {
1249 my $ticket_sth = $ticket_dbh->prepare(
1250 'DELETE FROM Links WHERE Target = ?'
1252 my $errstr = $ticket_dbh->errstr;
1253 $dbh->rollback if $oldAutoCommit;
1256 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1258 my $errstr = $ticket_sth->errstr;
1259 $dbh->rollback if $oldAutoCommit;
1263 #check and see if the customer is the only link on the ticket, and
1264 #if so, set the ticket to deleted status in RT?
1265 #maybe someday, for now this will at least fix tickets not displaying
1269 #delete the customer record
1271 my $error = $self->SUPER::delete;
1273 $dbh->rollback if $oldAutoCommit;
1277 # cust_main exports!
1279 #my $export_args = $options{'export_args'} || [];
1282 map qsearch( 'part_export', {exportnum=>$_} ),
1283 $conf->config('cust_main-exports'); #, $agentnum
1285 foreach my $part_export ( @part_export ) {
1286 my $error = $part_export->export_delete( $self ); #, @$export_args);
1288 $dbh->rollback if $oldAutoCommit;
1289 return "exporting to ". $part_export->exporttype.
1290 " (transaction rolled back): $error";
1294 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1299 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1301 Replaces the OLD_RECORD with this one in the database. If there is an error,
1302 returns the error, otherwise returns false.
1304 To change the customer's address, set the pseudo-fields C<bill_location> and
1305 C<ship_location>. The address will still only change if at least one of the
1306 address fields differs from the existing values.
1308 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1309 set as the contact email address for a default contact with the same name as
1312 Currently available options are: I<tax_exemption>, I<cust_payby_params>,
1313 I<contact_params>, I<invoicing_list>.
1315 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1316 of tax names and exemption numbers. FS::cust_main_exemption records will be
1317 deleted and inserted as appropriate.
1319 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1320 groups (describing the customer's payment methods and contacts, respectively)
1321 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1322 and L<FS::contact> for the fields these can contain.
1324 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1325 should be used instead if possible.
1332 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1334 : $self->replace_old;
1338 warn "$me replace called\n"
1341 my $curuser = $FS::CurrentUser::CurrentUser;
1342 return "You are not permitted to create complimentary accounts."
1343 if $self->complimentary eq 'Y'
1344 && $self->complimentary ne $old->complimentary
1345 && ! $curuser->access_right('Complimentary customer');
1347 local($ignore_expired_card) = 1
1348 if $old->payby =~ /^(CARD|DCRD)$/
1349 && $self->payby =~ /^(CARD|DCRD)$/
1350 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1352 local($ignore_banned_card) = 1
1353 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1354 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1355 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1357 return "Invoicing locale is required"
1360 && $conf->exists('cust_main-require_locale');
1362 local $SIG{HUP} = 'IGNORE';
1363 local $SIG{INT} = 'IGNORE';
1364 local $SIG{QUIT} = 'IGNORE';
1365 local $SIG{TERM} = 'IGNORE';
1366 local $SIG{TSTP} = 'IGNORE';
1367 local $SIG{PIPE} = 'IGNORE';
1369 my $oldAutoCommit = $FS::UID::AutoCommit;
1370 local $FS::UID::AutoCommit = 0;
1373 for my $l (qw(bill_location ship_location)) {
1374 #my $old_loc = $old->$l;
1375 my $new_loc = $self->$l or next;
1377 # find the existing location if there is one
1378 $new_loc->set('custnum' => $self->custnum);
1379 my $error = $new_loc->find_or_insert;
1381 $dbh->rollback if $oldAutoCommit;
1384 $self->set($l.'num', $new_loc->locationnum);
1388 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1389 warn "cust_main::replace: using deprecated invoicing list argument";
1390 $invoicing_list = shift @param;
1393 my %options = @param;
1395 $invoicing_list ||= $options{invoicing_list};
1397 my @contacts = map { $_->contact } $self->cust_contact;
1398 # find a contact that matches the customer's name
1399 my ($implicit_contact) = grep { $_->first eq $old->get('first')
1400 and $_->last eq $old->get('last') }
1402 $implicit_contact ||= FS::contact->new({
1403 'custnum' => $self->custnum,
1404 'locationnum' => $self->get('bill_locationnum'),
1407 # for any of these that are already contact emails, link to the existing
1409 if ( $invoicing_list ) {
1412 # kind of like process_m2m on these, except:
1413 # - the other side is two tables in a join
1414 # - and we might have to create new contact_emails
1415 # - and possibly a new contact
1417 # Find existing invoice emails that aren't on the implicit contact.
1418 # Any of these that are not on the new invoicing list will be removed.
1419 my %old_email_cust_contact;
1420 foreach my $cust_contact ($self->cust_contact) {
1421 next if !$cust_contact->invoice_dest;
1422 next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1424 foreach my $contact_email ($cust_contact->contact->contact_email) {
1425 $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1429 foreach my $dest (@$invoicing_list) {
1431 if ($dest eq 'POST') {
1433 $self->set('postal_invoice', 'Y');
1435 } elsif ( exists($old_email_cust_contact{$dest}) ) {
1437 delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1441 # See if it belongs to some other contact; if so, link it.
1442 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1444 and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1445 my $cust_contact = qsearchs('cust_contact', {
1446 contactnum => $contact_email->contactnum,
1447 custnum => $self->custnum,
1448 }) || FS::cust_contact->new({
1449 contactnum => $contact_email->contactnum,
1450 custnum => $self->custnum,
1452 $cust_contact->set('invoice_dest', 'Y');
1453 my $error = $cust_contact->custcontactnum ?
1454 $cust_contact->replace : $cust_contact->insert;
1456 $dbh->rollback if $oldAutoCommit;
1457 return "$error (linking to email address $dest)";
1461 # This email address is not yet linked to any contact, so it will
1462 # be added to the implicit contact.
1463 $email .= ',' if length($email);
1469 foreach my $remove_dest (keys %old_email_cust_contact) {
1470 my $cust_contact = $old_email_cust_contact{$remove_dest};
1471 # These were not in the list of requested destinations, so take them off.
1472 $cust_contact->set('invoice_dest', '');
1473 my $error = $cust_contact->replace;
1475 $dbh->rollback if $oldAutoCommit;
1476 return "$error (unlinking email address $remove_dest)";
1480 # make sure it keeps up with the changed customer name, if any
1481 $implicit_contact->set('last', $self->get('last'));
1482 $implicit_contact->set('first', $self->get('first'));
1483 $implicit_contact->set('emailaddress', $email);
1484 $implicit_contact->set('invoice_dest', 'Y');
1485 $implicit_contact->set('custnum', $self->custnum);
1488 if ( $implicit_contact->contactnum ) {
1489 $error = $implicit_contact->replace;
1490 } elsif ( length($email) ) { # don't create a new contact if not needed
1491 $error = $implicit_contact->insert;
1495 $dbh->rollback if $oldAutoCommit;
1496 return "$error (adding email address $email)";
1501 # replace the customer record
1502 my $error = $self->SUPER::replace($old);
1505 $dbh->rollback if $oldAutoCommit;
1509 # now move packages to the new service location
1510 $self->set('ship_location', ''); #flush cache
1511 if ( $old->ship_locationnum and # should only be null during upgrade...
1512 $old->ship_locationnum != $self->ship_locationnum ) {
1513 $error = $old->ship_location->move_to($self->ship_location);
1515 $dbh->rollback if $oldAutoCommit;
1519 # don't move packages based on the billing location, but
1520 # disable it if it's no longer in use
1521 if ( $old->bill_locationnum and
1522 $old->bill_locationnum != $self->bill_locationnum ) {
1523 $error = $old->bill_location->disable_if_unused;
1525 $dbh->rollback if $oldAutoCommit;
1530 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1532 #this could be more efficient than deleting and re-inserting, if it matters
1533 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1534 my $error = $cust_tag->delete;
1536 $dbh->rollback if $oldAutoCommit;
1540 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1541 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1542 'custnum' => $self->custnum };
1543 my $error = $cust_tag->insert;
1545 $dbh->rollback if $oldAutoCommit;
1552 my $tax_exemption = delete $options{'tax_exemption'};
1553 if ( $tax_exemption ) {
1555 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1556 if ref($tax_exemption) eq 'ARRAY';
1558 my %cust_main_exemption =
1559 map { $_->taxname => $_ }
1560 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1562 foreach my $taxname ( keys %$tax_exemption ) {
1564 if ( $cust_main_exemption{$taxname} &&
1565 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1568 delete $cust_main_exemption{$taxname};
1572 my $cust_main_exemption = new FS::cust_main_exemption {
1573 'custnum' => $self->custnum,
1574 'taxname' => $taxname,
1575 'exempt_number' => $tax_exemption->{$taxname},
1577 my $error = $cust_main_exemption->insert;
1579 $dbh->rollback if $oldAutoCommit;
1580 return "inserting cust_main_exemption (transaction rolled back): $error";
1584 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1585 my $error = $cust_main_exemption->delete;
1587 $dbh->rollback if $oldAutoCommit;
1588 return "deleting cust_main_exemption (transaction rolled back): $error";
1594 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1596 my $error = $self->process_o2m(
1597 'table' => 'cust_payby',
1598 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1599 'params' => $cust_payby_params,
1600 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1603 $dbh->rollback if $oldAutoCommit;
1609 if ( my $contact_params = delete $options{'contact_params'} ) {
1611 # this can potentially replace contacts that were created by the
1612 # invoicing list argument, but the UI shouldn't allow both of them
1615 my $error = $self->process_o2m(
1616 'table' => 'contact',
1617 'fields' => FS::contact->cgi_contact_fields,
1618 'params' => $contact_params,
1621 $dbh->rollback if $oldAutoCommit;
1627 unless ( $import || $skip_fuzzyfiles ) {
1628 $error = $self->queue_fuzzyfiles_update;
1630 $dbh->rollback if $oldAutoCommit;
1631 return "updating fuzzy search cache: $error";
1635 # tax district update in cust_location
1637 # cust_main exports!
1639 my $export_args = $options{'export_args'} || [];
1642 map qsearch( 'part_export', {exportnum=>$_} ),
1643 $conf->config('cust_main-exports'); #, $agentnum
1645 foreach my $part_export ( @part_export ) {
1646 my $error = $part_export->export_replace( $self, $old, @$export_args);
1648 $dbh->rollback if $oldAutoCommit;
1649 return "exporting to ". $part_export->exporttype.
1650 " (transaction rolled back): $error";
1654 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1659 =item queue_fuzzyfiles_update
1661 Used by insert & replace to update the fuzzy search cache
1665 use FS::cust_main::Search;
1666 sub queue_fuzzyfiles_update {
1669 local $SIG{HUP} = 'IGNORE';
1670 local $SIG{INT} = 'IGNORE';
1671 local $SIG{QUIT} = 'IGNORE';
1672 local $SIG{TERM} = 'IGNORE';
1673 local $SIG{TSTP} = 'IGNORE';
1674 local $SIG{PIPE} = 'IGNORE';
1676 my $oldAutoCommit = $FS::UID::AutoCommit;
1677 local $FS::UID::AutoCommit = 0;
1680 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1681 my $queue = new FS::queue {
1682 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1684 my @args = "cust_main.$field", $self->get($field);
1685 my $error = $queue->insert( @args );
1687 $dbh->rollback if $oldAutoCommit;
1688 return "queueing job (transaction rolled back): $error";
1693 push @locations, $self->bill_location if $self->bill_locationnum;
1694 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1695 foreach my $location (@locations) {
1696 my $queue = new FS::queue {
1697 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1699 my @args = 'cust_location.address1', $location->address1;
1700 my $error = $queue->insert( @args );
1702 $dbh->rollback if $oldAutoCommit;
1703 return "queueing job (transaction rolled back): $error";
1707 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1714 Checks all fields to make sure this is a valid customer record. If there is
1715 an error, returns the error, otherwise returns false. Called by the insert
1716 and replace methods.
1723 warn "$me check BEFORE: \n". $self->_dump
1727 $self->ut_numbern('custnum')
1728 || $self->ut_number('agentnum')
1729 || $self->ut_textn('agent_custid')
1730 || $self->ut_number('refnum')
1731 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1732 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1733 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1734 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1735 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1736 || $self->ut_textn('custbatch')
1737 || $self->ut_name('last')
1738 || $self->ut_name('first')
1739 || $self->ut_snumbern('signupdate')
1740 || $self->ut_snumbern('birthdate')
1741 || $self->ut_namen('spouse_last')
1742 || $self->ut_namen('spouse_first')
1743 || $self->ut_snumbern('spouse_birthdate')
1744 || $self->ut_snumbern('anniversary_date')
1745 || $self->ut_textn('company')
1746 || $self->ut_textn('ship_company')
1747 || $self->ut_anything('comments')
1748 || $self->ut_numbern('referral_custnum')
1749 || $self->ut_textn('stateid')
1750 || $self->ut_textn('stateid_state')
1751 || $self->ut_textn('invoice_terms')
1752 || $self->ut_floatn('cdr_termination_percentage')
1753 || $self->ut_floatn('credit_limit')
1754 || $self->ut_numbern('billday')
1755 || $self->ut_numbern('prorate_day')
1756 || $self->ut_flag('edit_subject')
1757 || $self->ut_flag('calling_list_exempt')
1758 || $self->ut_flag('invoice_noemail')
1759 || $self->ut_flag('message_noemail')
1760 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1761 || $self->ut_currencyn('currency')
1762 || $self->ut_alphan('po_number')
1763 || $self->ut_enum('complimentary', [ '', 'Y' ])
1764 || $self->ut_flag('invoice_ship_address')
1765 || $self->ut_flag('invoice_dest')
1768 foreach (qw(company ship_company)) {
1769 my $company = $self->get($_);
1770 $company =~ s/^\s+//;
1771 $company =~ s/\s+$//;
1772 $company =~ s/\s+/ /g;
1773 $self->set($_, $company);
1776 #barf. need message catalogs. i18n. etc.
1777 $error .= "Please select an advertising source."
1778 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1779 return $error if $error;
1781 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1782 or return "Unknown agent";
1784 if ( $self->currency ) {
1785 my $agent_currency = qsearchs( 'agent_currency', {
1786 'agentnum' => $agent->agentnum,
1787 'currency' => $self->currency,
1789 or return "Agent ". $agent->agent.
1790 " not permitted to offer ". $self->currency. " invoicing";
1793 return "Unknown refnum"
1794 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1796 return "Unknown referring custnum: ". $self->referral_custnum
1797 unless ! $self->referral_custnum
1798 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1800 if ( $self->ss eq '' ) {
1805 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1806 or return "Illegal social security number: ". $self->ss;
1807 $self->ss("$1-$2-$3");
1810 #turn off invoice_ship_address if ship & bill are the same
1811 if ($self->bill_locationnum eq $self->ship_locationnum) {
1812 $self->invoice_ship_address('');
1815 # cust_main_county verification now handled by cust_location check
1818 $self->ut_phonen('daytime', $self->country)
1819 || $self->ut_phonen('night', $self->country)
1820 || $self->ut_phonen('fax', $self->country)
1821 || $self->ut_phonen('mobile', $self->country)
1823 return $error if $error;
1825 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1827 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1830 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1832 : FS::Msgcat::_gettext('daytime');
1833 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1835 : FS::Msgcat::_gettext('night');
1837 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1839 : FS::Msgcat::_gettext('mobile');
1841 return "$daytime_label, $night_label or $mobile_label is required"
1845 ### start of stuff moved to cust_payby
1846 # then mostly kept here to support upgrades (can remove in 5.x)
1847 # but modified to allow everything to be empty
1849 if ( $self->payby ) {
1850 FS::payby->can_payby($self->table, $self->payby)
1851 or return "Illegal payby: ". $self->payby;
1856 $error = $self->ut_numbern('paystart_month')
1857 || $self->ut_numbern('paystart_year')
1858 || $self->ut_numbern('payissue')
1859 || $self->ut_textn('paytype')
1861 return $error if $error;
1863 if ( $self->payip eq '' ) {
1866 $error = $self->ut_ip('payip');
1867 return $error if $error;
1870 # If it is encrypted and the private key is not availaible then we can't
1871 # check the credit card.
1872 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1874 # Need some kind of global flag to accept invalid cards, for testing
1876 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1877 $self->payby =~ /^(CARD|DCRD)$/ ) {
1879 my $payinfo = $self->payinfo;
1880 $payinfo =~ s/\D//g;
1881 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1882 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1884 $self->payinfo($payinfo);
1886 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1888 return gettext('unknown_card_type')
1889 if $self->payinfo !~ /^99\d{14}$/ #token
1890 && cardtype($self->payinfo) eq "Unknown";
1892 unless ( $ignore_banned_card ) {
1893 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1895 if ( $ban->bantype eq 'warn' ) {
1896 #or others depending on value of $ban->reason ?
1897 return '_duplicate_card'.
1898 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1899 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1900 ' (ban# '. $ban->bannum. ')'
1901 unless $self->override_ban_warn;
1903 return 'Banned credit card: banned on '.
1904 time2str('%a %h %o at %r', $ban->_date).
1905 ' by '. $ban->otaker.
1906 ' (ban# '. $ban->bannum. ')';
1911 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1912 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1913 $self->paycvv =~ /^(\d{4})$/
1914 or return "CVV2 (CID) for American Express cards is four digits.";
1917 $self->paycvv =~ /^(\d{3})$/
1918 or return "CVV2 (CVC2/CID) is three digits.";
1925 my $cardtype = cardtype($payinfo);
1926 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1928 return "Start date or issue number is required for $cardtype cards"
1929 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1931 return "Start month must be between 1 and 12"
1932 if $self->paystart_month
1933 and $self->paystart_month < 1 || $self->paystart_month > 12;
1935 return "Start year must be 1990 or later"
1936 if $self->paystart_year
1937 and $self->paystart_year < 1990;
1939 return "Issue number must be beween 1 and 99"
1941 and $self->payissue < 1 || $self->payissue > 99;
1944 $self->paystart_month('');
1945 $self->paystart_year('');
1946 $self->payissue('');
1949 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1950 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1952 my $payinfo = $self->payinfo;
1953 $payinfo =~ s/[^\d\@\.]//g;
1954 if ( $conf->config('echeck-country') eq 'CA' ) {
1955 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1956 or return 'invalid echeck account@branch.bank';
1957 $payinfo = "$1\@$2.$3";
1958 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1959 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1960 $payinfo = "$1\@$2";
1962 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1963 $payinfo = "$1\@$2";
1965 $self->payinfo($payinfo);
1968 unless ( $ignore_banned_card ) {
1969 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1971 if ( $ban->bantype eq 'warn' ) {
1972 #or others depending on value of $ban->reason ?
1973 return '_duplicate_ach' unless $self->override_ban_warn;
1975 return 'Banned ACH account: banned on '.
1976 time2str('%a %h %o at %r', $ban->_date).
1977 ' by '. $ban->otaker.
1978 ' (ban# '. $ban->bannum. ')';
1983 } elsif ( $self->payby eq 'LECB' ) {
1985 my $payinfo = $self->payinfo;
1986 $payinfo =~ s/\D//g;
1987 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1989 $self->payinfo($payinfo);
1992 } elsif ( $self->payby eq 'BILL' ) {
1994 $error = $self->ut_textn('payinfo');
1995 return "Illegal P.O. number: ". $self->payinfo if $error;
1998 } elsif ( $self->payby eq 'COMP' ) {
2000 my $curuser = $FS::CurrentUser::CurrentUser;
2001 if ( ! $self->custnum
2002 && ! $curuser->access_right('Complimentary customer')
2005 return "You are not permitted to create complimentary accounts."
2008 $error = $self->ut_textn('payinfo');
2009 return "Illegal comp account issuer: ". $self->payinfo if $error;
2012 } elsif ( $self->payby eq 'PREPAY' ) {
2014 my $payinfo = $self->payinfo;
2015 $payinfo =~ s/\W//g; #anything else would just confuse things
2016 $self->payinfo($payinfo);
2017 $error = $self->ut_alpha('payinfo');
2018 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2019 return "Unknown prepayment identifier"
2020 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2025 return "You are not permitted to create complimentary accounts."
2027 && $self->complimentary eq 'Y'
2028 && ! $FS::CurrentUser::CurrentUser->access_right('Complimentary customer');
2030 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2031 return "Expiration date required"
2032 # shouldn't payinfo_check do this?
2033 unless ! $self->payby
2034 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2038 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2039 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2040 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2041 ( $m, $y ) = ( $2, "19$1" );
2042 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2043 ( $m, $y ) = ( $3, "20$2" );
2045 return "Illegal expiration date: ". $self->paydate;
2047 $m = sprintf('%02d',$m);
2048 $self->paydate("$y-$m-01");
2049 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2050 return gettext('expired_card')
2052 && !$ignore_expired_card
2053 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2056 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2057 ( ! $conf->exists('require_cardname')
2058 || $self->payby !~ /^(CARD|DCRD)$/ )
2060 $self->payname( $self->first. " ". $self->getfield('last') );
2063 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2064 $self->payname =~ /^([\w \,\.\-\']*)$/
2065 or return gettext('illegal_name'). " payname: ". $self->payname;
2068 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2069 or return gettext('illegal_name'). " payname: ". $self->payname;
2075 ### end of stuff moved to cust_payby
2077 return "Please select an invoicing locale"
2080 && $conf->exists('cust_main-require_locale');
2082 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2083 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2087 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2089 warn "$me check AFTER: \n". $self->_dump
2092 $self->SUPER::check;
2097 Additional checks for replace only.
2102 my ($new,$old) = @_;
2103 #preserve old value if global config is set
2104 if ($old && $conf->exists('invoice-ship_address')) {
2105 $new->invoice_ship_address($old->invoice_ship_address);
2112 Returns a list of fields which have ship_ duplicates.
2117 qw( last first company
2119 address1 address2 city county state zip country
2121 daytime night fax mobile
2125 =item has_ship_address
2127 Returns true if this customer record has a separate shipping address.
2131 sub has_ship_address {
2133 $self->bill_locationnum != $self->ship_locationnum;
2138 Returns a list of key/value pairs, with the following keys: address1,
2139 adddress2, city, county, state, zip, country, district, and geocode. The
2140 shipping address is used if present.
2146 $self->ship_location->location_hash;
2151 Returns all locations (see L<FS::cust_location>) for this customer.
2157 qsearch('cust_location', { 'custnum' => $self->custnum,
2158 'prospectnum' => '' } );
2163 Returns all contact associations (see L<FS::cust_contact>) for this customer.
2169 qsearch('cust_contact', { 'custnum' => $self->custnum } );
2172 =item cust_payby PAYBY
2174 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2176 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
2177 Does not validate PAYBY.
2185 'table' => 'cust_payby',
2186 'hashref' => { 'custnum' => $self->custnum },
2187 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
2189 $search->{'extra_sql'} = ' AND payby IN ( ' . join(',', map { dbh->quote($_) } @payby) . ' ) '
2195 =item has_cust_payby_auto
2197 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
2201 sub has_cust_payby_auto {
2204 'table' => 'cust_payby',
2205 'hashref' => { 'custnum' => $self->custnum, },
2206 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2207 'order_by' => 'LIMIT 1',
2214 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2215 and L<FS::cust_pkg>) for this customer, except those on hold.
2217 Returns a list: an empty list on success or a list of errors.
2223 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2228 Unsuspends all suspended packages in the on-hold state (those without setup
2229 dates) for this customer.
2235 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2240 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2242 Returns a list: an empty list on success or a list of errors.
2248 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2251 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2253 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2254 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2255 of a list of pkgparts; the hashref has the following keys:
2259 =item pkgparts - listref of pkgparts
2261 =item (other options are passed to the suspend method)
2266 Returns a list: an empty list on success or a list of errors.
2270 sub suspend_if_pkgpart {
2272 my (@pkgparts, %opt);
2273 if (ref($_[0]) eq 'HASH'){
2274 @pkgparts = @{$_[0]{pkgparts}};
2279 grep { $_->suspend(%opt) }
2280 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2281 $self->unsuspended_pkgs;
2284 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2286 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2287 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2288 instead of a list of pkgparts; the hashref has the following keys:
2292 =item pkgparts - listref of pkgparts
2294 =item (other options are passed to the suspend method)
2298 Returns a list: an empty list on success or a list of errors.
2302 sub suspend_unless_pkgpart {
2304 my (@pkgparts, %opt);
2305 if (ref($_[0]) eq 'HASH'){
2306 @pkgparts = @{$_[0]{pkgparts}};
2311 grep { $_->suspend(%opt) }
2312 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2313 $self->unsuspended_pkgs;
2316 =item cancel [ OPTION => VALUE ... ]
2318 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2320 Available options are:
2324 =item quiet - can be set true to supress email cancellation notices.
2326 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
2328 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2330 =item nobill - can be set true to skip billing if it might otherwise be done.
2334 Always returns a list: an empty list on success or a list of errors.
2338 # nb that dates are not specified as valid options to this method
2341 my( $self, %opt ) = @_;
2343 warn "$me cancel called on customer ". $self->custnum. " with options ".
2344 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2347 return ( 'access denied' )
2348 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2350 if ( $opt{'ban'} ) {
2352 foreach my $cust_payby ( $self->cust_payby ) {
2354 #well, if they didn't get decrypted on search, then we don't have to
2355 # try again... queue a job for the server that does have decryption
2356 # capability if we're in a paranoid multi-server implementation?
2357 return ( "Can't (yet) ban encrypted credit cards" )
2358 if $cust_payby->is_encrypted($cust_payby->payinfo);
2360 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2361 my $error = $ban->insert;
2362 return ( $error ) if $error;
2368 my @pkgs = $self->ncancelled_pkgs;
2370 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2372 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2373 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2377 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2378 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2381 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2384 sub _banned_pay_hashref {
2395 'payby' => $payby2ban{$self->payby},
2396 'payinfo' => $self->payinfo,
2397 #don't ever *search* on reason! #'reason' =>
2403 Returns all notes (see L<FS::cust_main_note>) for this customer.
2408 my($self,$orderby_classnum) = (shift,shift);
2409 my $orderby = "sticky DESC, _date DESC";
2410 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2411 qsearch( 'cust_main_note',
2412 { 'custnum' => $self->custnum },
2414 "ORDER BY $orderby",
2420 Returns the agent (see L<FS::agent>) for this customer.
2424 Returns the agent name (see L<FS::agent>) for this customer.
2430 $self->agent->agent;
2435 Returns any tags associated with this customer, as FS::cust_tag objects,
2436 or an empty list if there are no tags.
2440 Returns any tags associated with this customer, as FS::part_tag objects,
2441 or an empty list if there are no tags.
2447 map $_->part_tag, $self->cust_tag;
2453 Returns the customer class, as an FS::cust_class object, or the empty string
2454 if there is no customer class.
2458 Returns the customer category name, or the empty string if there is no customer
2465 my $cust_class = $self->cust_class;
2467 ? $cust_class->categoryname
2473 Returns the customer class name, or the empty string if there is no customer
2480 my $cust_class = $self->cust_class;
2482 ? $cust_class->classname
2488 Returns the external tax status, as an FS::tax_status object, or the empty
2489 string if there is no tax status.
2495 if ( $self->taxstatusnum ) {
2496 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2504 Returns the tax status code if there is one.
2510 my $tax_status = $self->tax_status;
2512 ? $tax_status->taxstatus
2516 =item BILLING METHODS
2518 Documentation on billing methods has been moved to
2519 L<FS::cust_main::Billing>.
2521 =item REALTIME BILLING METHODS
2523 Documentation on realtime billing methods has been moved to
2524 L<FS::cust_main::Billing_Realtime>.
2528 Removes the I<paycvv> field from the database directly.
2530 If there is an error, returns the error, otherwise returns false.
2536 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2537 or return dbh->errstr;
2538 $sth->execute($self->custnum)
2539 or return $sth->errstr;
2546 Returns the total owed for this customer on all invoices
2547 (see L<FS::cust_bill/owed>).
2553 $self->total_owed_date(2145859200); #12/31/2037
2556 =item total_owed_date TIME
2558 Returns the total owed for this customer on all invoices with date earlier than
2559 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2560 see L<Time::Local> and L<Date::Parse> for conversion functions.
2564 sub total_owed_date {
2568 my $custnum = $self->custnum;
2570 my $owed_sql = FS::cust_bill->owed_sql;
2573 SELECT SUM($owed_sql) FROM cust_bill
2574 WHERE custnum = $custnum
2578 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2582 =item total_owed_pkgnum PKGNUM
2584 Returns the total owed on all invoices for this customer's specific package
2585 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2589 sub total_owed_pkgnum {
2590 my( $self, $pkgnum ) = @_;
2591 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2594 =item total_owed_date_pkgnum TIME PKGNUM
2596 Returns the total owed for this customer's specific package when using
2597 experimental package balances on all invoices with date earlier than
2598 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2599 see L<Time::Local> and L<Date::Parse> for conversion functions.
2603 sub total_owed_date_pkgnum {
2604 my( $self, $time, $pkgnum ) = @_;
2607 foreach my $cust_bill (
2608 grep { $_->_date <= $time }
2609 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2611 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2613 sprintf( "%.2f", $total_bill );
2619 Returns the total amount of all payments.
2626 $total += $_->paid foreach $self->cust_pay;
2627 sprintf( "%.2f", $total );
2630 =item total_unapplied_credits
2632 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2633 customer. See L<FS::cust_credit/credited>.
2635 =item total_credited
2637 Old name for total_unapplied_credits. Don't use.
2641 sub total_credited {
2642 #carp "total_credited deprecated, use total_unapplied_credits";
2643 shift->total_unapplied_credits(@_);
2646 sub total_unapplied_credits {
2649 my $custnum = $self->custnum;
2651 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2654 SELECT SUM($unapplied_sql) FROM cust_credit
2655 WHERE custnum = $custnum
2658 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2662 =item total_unapplied_credits_pkgnum PKGNUM
2664 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2665 customer. See L<FS::cust_credit/credited>.
2669 sub total_unapplied_credits_pkgnum {
2670 my( $self, $pkgnum ) = @_;
2671 my $total_credit = 0;
2672 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2673 sprintf( "%.2f", $total_credit );
2677 =item total_unapplied_payments
2679 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2680 See L<FS::cust_pay/unapplied>.
2684 sub total_unapplied_payments {
2687 my $custnum = $self->custnum;
2689 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2692 SELECT SUM($unapplied_sql) FROM cust_pay
2693 WHERE custnum = $custnum
2696 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2700 =item total_unapplied_payments_pkgnum PKGNUM
2702 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2703 specific package when using experimental package balances. See
2704 L<FS::cust_pay/unapplied>.
2708 sub total_unapplied_payments_pkgnum {
2709 my( $self, $pkgnum ) = @_;
2710 my $total_unapplied = 0;
2711 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2712 sprintf( "%.2f", $total_unapplied );
2716 =item total_unapplied_refunds
2718 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2719 customer. See L<FS::cust_refund/unapplied>.
2723 sub total_unapplied_refunds {
2725 my $custnum = $self->custnum;
2727 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2730 SELECT SUM($unapplied_sql) FROM cust_refund
2731 WHERE custnum = $custnum
2734 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2740 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2741 total_unapplied_credits minus total_unapplied_payments).
2747 $self->balance_date_range;
2750 =item balance_date TIME
2752 Returns the balance for this customer, only considering invoices with date
2753 earlier than TIME (total_owed_date minus total_credited minus
2754 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2755 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2762 $self->balance_date_range(shift);
2765 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2767 Returns the balance for this customer, optionally considering invoices with
2768 date earlier than START_TIME, and not later than END_TIME
2769 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2771 Times are specified as SQL fragments or numeric
2772 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2773 L<Date::Parse> for conversion functions. The empty string can be passed
2774 to disable that time constraint completely.
2776 Accepts the same options as L<balance_date_sql>:
2780 =item unapplied_date
2782 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)
2786 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2787 time will be ignored. Note that START_TIME and END_TIME only limit the date
2788 range for invoices and I<unapplied> payments, credits, and refunds.
2794 sub balance_date_range {
2796 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2797 ') FROM cust_main WHERE custnum='. $self->custnum;
2798 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2801 =item balance_pkgnum PKGNUM
2803 Returns the balance for this customer's specific package when using
2804 experimental package balances (total_owed plus total_unrefunded, minus
2805 total_unapplied_credits minus total_unapplied_payments)
2809 sub balance_pkgnum {
2810 my( $self, $pkgnum ) = @_;
2813 $self->total_owed_pkgnum($pkgnum)
2814 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2815 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2816 - $self->total_unapplied_credits_pkgnum($pkgnum)
2817 - $self->total_unapplied_payments_pkgnum($pkgnum)
2823 Returns a hash of useful information for making a payment.
2833 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2834 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2835 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2839 For credit card transactions:
2851 For electronic check transactions:
2866 $return{balance} = $self->balance;
2868 $return{payname} = $self->payname
2869 || ( $self->first. ' '. $self->get('last') );
2871 $return{$_} = $self->bill_location->$_
2872 for qw(address1 address2 city state zip);
2874 $return{payby} = $self->payby;
2875 $return{stateid_state} = $self->stateid_state;
2877 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2878 $return{card_type} = cardtype($self->payinfo);
2879 $return{payinfo} = $self->paymask;
2881 @return{'month', 'year'} = $self->paydate_monthyear;
2885 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2886 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2887 $return{payinfo1} = $payinfo1;
2888 $return{payinfo2} = $payinfo2;
2889 $return{paytype} = $self->paytype;
2890 $return{paystate} = $self->paystate;
2894 #doubleclick protection
2896 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2904 Returns the exact time in seconds corresponding to the payment method
2905 expiration date. For CARD/DCRD customers this is the end of the month;
2906 for others (COMP is the only other payby that uses paydate) it's the start.
2907 Returns 0 if the paydate is empty or set to the far future.
2913 my ($month, $year) = $self->paydate_monthyear;
2914 return 0 if !$year or $year >= 2037;
2915 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2917 if ( $month == 13 ) {
2921 return timelocal(0,0,0,1,$month-1,$year) - 1;
2924 return timelocal(0,0,0,1,$month-1,$year);
2928 =item paydate_epoch_sql
2930 Class method. Returns an SQL expression to obtain the payment expiration date
2931 as a number of seconds.
2935 # Special expiration date behavior for non-CARD/DCRD customers has been
2936 # carefully preserved. Do we really use that?
2937 sub paydate_epoch_sql {
2939 my $table = shift || 'cust_main';
2940 my ($case1, $case2);
2941 if ( driver_name eq 'Pg' ) {
2942 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2943 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2945 elsif ( lc(driver_name) eq 'mysql' ) {
2946 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2947 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2950 return "CASE WHEN $table.payby IN('CARD','DCRD')
2956 =item tax_exemption TAXNAME
2961 my( $self, $taxname ) = @_;
2963 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2964 'taxname' => $taxname,
2969 =item cust_main_exemption
2971 =item invoicing_list
2973 Returns a list of email addresses (with svcnum entries expanded), and the word
2974 'POST' if the customer receives postal invoices.
2978 sub invoicing_list {
2979 my( $self, $arrayref ) = @_;
2982 warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
2985 my @emails = $self->invoicing_list_emailonly;
2986 push @emails, 'POST' if $self->get('postal_invoice');
2991 =item check_invoicing_list ARRAYREF
2993 Checks these arguements as valid input for the invoicing_list method. If there
2994 is an error, returns the error, otherwise returns false.
2998 sub check_invoicing_list {
2999 my( $self, $arrayref ) = @_;
3001 foreach my $address ( @$arrayref ) {
3003 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3004 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3007 my $cust_main_invoice = new FS::cust_main_invoice ( {
3008 'custnum' => $self->custnum,
3011 my $error = $self->custnum
3012 ? $cust_main_invoice->check
3013 : $cust_main_invoice->checkdest
3015 return $error if $error;
3019 return "Email address required"
3020 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3021 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3028 Returns the email addresses of all accounts provisioned for this customer.
3035 foreach my $cust_pkg ( $self->all_pkgs ) {
3036 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3038 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3039 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3041 $list{$_}=1 foreach map { $_->email } @svc_acct;
3046 =item invoicing_list_addpost
3048 Adds postal invoicing to this customer. If this customer is already configured
3049 to receive postal invoices, does nothing.
3053 sub invoicing_list_addpost {
3055 if ( $self->get('postal_invoice') eq '' ) {
3056 $self->set('postal_invoice', 'Y');
3057 my $error = $self->replace;
3058 warn $error if $error; # should fail harder, but this is traditional
3062 =item invoicing_list_emailonly
3064 Returns the list of email invoice recipients (invoicing_list without non-email
3065 destinations such as POST and FAX).
3069 sub invoicing_list_emailonly {
3071 warn "$me invoicing_list_emailonly called"
3073 return () if !$self->custnum; # not yet inserted
3074 return map { $_->emailaddress }
3076 table => 'cust_contact',
3077 select => 'emailaddress',
3078 addl_from => ' JOIN contact USING (contactnum) '.
3079 ' JOIN contact_email USING (contactnum)',
3080 hashref => { 'custnum' => $self->custnum, },
3081 extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
3085 =item invoicing_list_emailonly_scalar
3087 Returns the list of email invoice recipients (invoicing_list without non-email
3088 destinations such as POST and FAX) as a comma-separated scalar.
3092 sub invoicing_list_emailonly_scalar {
3094 warn "$me invoicing_list_emailonly_scalar called"
3096 join(', ', $self->invoicing_list_emailonly);
3099 =item referral_custnum_cust_main
3101 Returns the customer who referred this customer (or the empty string, if
3102 this customer was not referred).
3104 Note the difference with referral_cust_main method: This method,
3105 referral_custnum_cust_main returns the single customer (if any) who referred
3106 this customer, while referral_cust_main returns an array of customers referred
3111 sub referral_custnum_cust_main {
3113 return '' unless $self->referral_custnum;
3114 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3117 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3119 Returns an array of customers referred by this customer (referral_custnum set
3120 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3121 customers referred by customers referred by this customer and so on, inclusive.
3122 The default behavior is DEPTH 1 (no recursion).
3124 Note the difference with referral_custnum_cust_main method: This method,
3125 referral_cust_main, returns an array of customers referred BY this customer,
3126 while referral_custnum_cust_main returns the single customer (if any) who
3127 referred this customer.
3131 sub referral_cust_main {
3133 my $depth = @_ ? shift : 1;
3134 my $exclude = @_ ? shift : {};
3137 map { $exclude->{$_->custnum}++; $_; }
3138 grep { ! $exclude->{ $_->custnum } }
3139 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3143 map { $_->referral_cust_main($depth-1, $exclude) }
3150 =item referral_cust_main_ncancelled
3152 Same as referral_cust_main, except only returns customers with uncancelled
3157 sub referral_cust_main_ncancelled {
3159 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3162 =item referral_cust_pkg [ DEPTH ]
3164 Like referral_cust_main, except returns a flat list of all unsuspended (and
3165 uncancelled) packages for each customer. The number of items in this list may
3166 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3170 sub referral_cust_pkg {
3172 my $depth = @_ ? shift : 1;
3174 map { $_->unsuspended_pkgs }
3175 grep { $_->unsuspended_pkgs }
3176 $self->referral_cust_main($depth);
3179 =item referring_cust_main
3181 Returns the single cust_main record for the customer who referred this customer
3182 (referral_custnum), or false.
3186 sub referring_cust_main {
3188 return '' unless $self->referral_custnum;
3189 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3192 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3194 Applies a credit to this customer. If there is an error, returns the error,
3195 otherwise returns false.
3197 REASON can be a text string, an FS::reason object, or a scalar reference to
3198 a reasonnum. If a text string, it will be automatically inserted as a new
3199 reason, and a 'reason_type' option must be passed to indicate the
3200 FS::reason_type for the new reason.
3202 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3203 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3204 I<commission_pkgnum>.
3206 Any other options are passed to FS::cust_credit::insert.
3211 my( $self, $amount, $reason, %options ) = @_;
3213 my $cust_credit = new FS::cust_credit {
3214 'custnum' => $self->custnum,
3215 'amount' => $amount,
3218 if ( ref($reason) ) {
3220 if ( ref($reason) eq 'SCALAR' ) {
3221 $cust_credit->reasonnum( $$reason );
3223 $cust_credit->reasonnum( $reason->reasonnum );
3227 $cust_credit->set('reason', $reason)
3230 $cust_credit->$_( delete $options{$_} )
3231 foreach grep exists($options{$_}),
3232 qw( addlinfo eventnum ),
3233 map "commission_$_", qw( agentnum salesnum pkgnum );
3235 $cust_credit->insert(%options);
3239 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3241 Creates a one-time charge for this customer. If there is an error, returns
3242 the error, otherwise returns false.
3244 New-style, with a hashref of options:
3246 my $error = $cust_main->charge(
3250 'start_date' => str2time('7/4/2009'),
3251 'pkg' => 'Description',
3252 'comment' => 'Comment',
3253 'additional' => [], #extra invoice detail
3254 'classnum' => 1, #pkg_class
3256 'setuptax' => '', # or 'Y' for tax exempt
3258 'locationnum'=> 1234, # optional
3261 'taxclass' => 'Tax class',
3264 'taxproduct' => 2, #part_pkg_taxproduct
3265 'override' => {}, #XXX describe
3267 #will be filled in with the new object
3268 'cust_pkg_ref' => \$cust_pkg,
3270 #generate an invoice immediately
3272 'invoice_terms' => '', #with these terms
3278 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3282 #super false laziness w/quotation::charge
3285 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3286 my ( $pkg, $comment, $additional );
3287 my ( $setuptax, $taxclass ); #internal taxes
3288 my ( $taxproduct, $override ); #vendor (CCH) taxes
3290 my $separate_bill = '';
3291 my $cust_pkg_ref = '';
3292 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3294 if ( ref( $_[0] ) ) {
3295 $amount = $_[0]->{amount};
3296 $setup_cost = $_[0]->{setup_cost};
3297 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3298 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3299 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3300 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3301 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3302 : '$'. sprintf("%.2f",$amount);
3303 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3304 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3305 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3306 $additional = $_[0]->{additional} || [];
3307 $taxproduct = $_[0]->{taxproductnum};
3308 $override = { '' => $_[0]->{tax_override} };
3309 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3310 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3311 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3312 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3313 $separate_bill = $_[0]->{separate_bill} || '';
3319 $pkg = @_ ? shift : 'One-time charge';
3320 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3322 $taxclass = @_ ? shift : '';
3326 local $SIG{HUP} = 'IGNORE';
3327 local $SIG{INT} = 'IGNORE';
3328 local $SIG{QUIT} = 'IGNORE';
3329 local $SIG{TERM} = 'IGNORE';
3330 local $SIG{TSTP} = 'IGNORE';
3331 local $SIG{PIPE} = 'IGNORE';
3333 my $oldAutoCommit = $FS::UID::AutoCommit;
3334 local $FS::UID::AutoCommit = 0;
3337 my $part_pkg = new FS::part_pkg ( {
3339 'comment' => $comment,
3343 'classnum' => ( $classnum ? $classnum : '' ),
3344 'setuptax' => $setuptax,
3345 'taxclass' => $taxclass,
3346 'taxproductnum' => $taxproduct,
3347 'setup_cost' => $setup_cost,
3350 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3351 ( 0 .. @$additional - 1 )
3353 'additional_count' => scalar(@$additional),
3354 'setup_fee' => $amount,
3357 my $error = $part_pkg->insert( options => \%options,
3358 tax_overrides => $override,
3361 $dbh->rollback if $oldAutoCommit;
3365 my $pkgpart = $part_pkg->pkgpart;
3366 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3367 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3368 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3369 $error = $type_pkgs->insert;
3371 $dbh->rollback if $oldAutoCommit;
3376 my $cust_pkg = new FS::cust_pkg ( {
3377 'custnum' => $self->custnum,
3378 'pkgpart' => $pkgpart,
3379 'quantity' => $quantity,
3380 'start_date' => $start_date,
3381 'no_auto' => $no_auto,
3382 'separate_bill' => $separate_bill,
3383 'locationnum'=> $locationnum,
3386 $error = $cust_pkg->insert;
3388 $dbh->rollback if $oldAutoCommit;
3390 } elsif ( $cust_pkg_ref ) {
3391 ${$cust_pkg_ref} = $cust_pkg;
3395 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3396 'pkg_list' => [ $cust_pkg ],
3399 $dbh->rollback if $oldAutoCommit;
3404 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3409 #=item charge_postal_fee
3411 #Applies a one time charge this customer. If there is an error,
3412 #returns the error, returns the cust_pkg charge object or false
3413 #if there was no charge.
3417 # This should be a customer event. For that to work requires that bill
3418 # also be a customer event.
3420 sub charge_postal_fee {
3423 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3424 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3426 my $cust_pkg = new FS::cust_pkg ( {
3427 'custnum' => $self->custnum,
3428 'pkgpart' => $pkgpart,
3432 my $error = $cust_pkg->insert;
3433 $error ? $error : $cust_pkg;
3436 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3438 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3440 Optionally, a list or hashref of additional arguments to the qsearch call can
3447 my $opt = ref($_[0]) ? shift : { @_ };
3449 #return $self->num_cust_bill unless wantarray || keys %$opt;
3451 $opt->{'table'} = 'cust_bill';
3452 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3453 $opt->{'hashref'}{'custnum'} = $self->custnum;
3454 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3456 map { $_ } #behavior of sort undefined in scalar context
3457 sort { $a->_date <=> $b->_date }
3461 =item open_cust_bill
3463 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3468 sub open_cust_bill {
3472 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3478 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3480 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3484 sub legacy_cust_bill {
3487 #return $self->num_legacy_cust_bill unless wantarray;
3489 map { $_ } #behavior of sort undefined in scalar context
3490 sort { $a->_date <=> $b->_date }
3491 qsearch({ 'table' => 'legacy_cust_bill',
3492 'hashref' => { 'custnum' => $self->custnum, },
3493 'order_by' => 'ORDER BY _date ASC',
3497 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3499 Returns all the statements (see L<FS::cust_statement>) for this customer.
3501 Optionally, a list or hashref of additional arguments to the qsearch call can
3506 =item cust_bill_void
3508 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3512 sub cust_bill_void {
3515 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3516 sort { $a->_date <=> $b->_date }
3517 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3520 sub cust_statement {
3522 my $opt = ref($_[0]) ? shift : { @_ };
3524 #return $self->num_cust_statement unless wantarray || keys %$opt;
3526 $opt->{'table'} = 'cust_statement';
3527 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3528 $opt->{'hashref'}{'custnum'} = $self->custnum;
3529 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3531 map { $_ } #behavior of sort undefined in scalar context
3532 sort { $a->_date <=> $b->_date }
3536 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3538 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3540 Optionally, a list or hashref of additional arguments to the qsearch call can
3541 be passed following the SVCDB.
3548 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3549 warn "$me svc_x requires a svcdb";
3552 my $opt = ref($_[0]) ? shift : { @_ };
3554 $opt->{'table'} = $svcdb;
3555 $opt->{'addl_from'} =
3556 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3557 ($opt->{'addl_from'} || '');
3559 my $custnum = $self->custnum;
3560 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3561 my $where = "cust_pkg.custnum = $custnum";
3563 my $extra_sql = $opt->{'extra_sql'} || '';
3564 if ( keys %{ $opt->{'hashref'} } ) {
3565 $extra_sql = " AND $where $extra_sql";
3568 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3569 $extra_sql = "WHERE $where AND $1";
3572 $extra_sql = "WHERE $where $extra_sql";
3575 $opt->{'extra_sql'} = $extra_sql;
3580 # required for use as an eventtable;
3583 $self->svc_x('svc_acct', @_);
3588 Returns all the credits (see L<FS::cust_credit>) for this customer.
3594 map { $_ } #return $self->num_cust_credit unless wantarray;
3595 sort { $a->_date <=> $b->_date }
3596 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3599 =item cust_credit_pkgnum
3601 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3602 package when using experimental package balances.
3606 sub cust_credit_pkgnum {
3607 my( $self, $pkgnum ) = @_;
3608 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3609 sort { $a->_date <=> $b->_date }
3610 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3611 'pkgnum' => $pkgnum,
3616 =item cust_credit_void
3618 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3622 sub cust_credit_void {
3625 sort { $a->_date <=> $b->_date }
3626 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3631 Returns all the payments (see L<FS::cust_pay>) for this customer.
3637 my $opt = ref($_[0]) ? shift : { @_ };
3639 return $self->num_cust_pay unless wantarray || keys %$opt;
3641 $opt->{'table'} = 'cust_pay';
3642 $opt->{'hashref'}{'custnum'} = $self->custnum;
3644 map { $_ } #behavior of sort undefined in scalar context
3645 sort { $a->_date <=> $b->_date }
3652 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3653 called automatically when the cust_pay method is used in a scalar context.
3659 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3660 my $sth = dbh->prepare($sql) or die dbh->errstr;
3661 $sth->execute($self->custnum) or die $sth->errstr;
3662 $sth->fetchrow_arrayref->[0];
3665 =item unapplied_cust_pay
3667 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3671 sub unapplied_cust_pay {
3675 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3681 =item cust_pay_pkgnum
3683 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3684 package when using experimental package balances.
3688 sub cust_pay_pkgnum {
3689 my( $self, $pkgnum ) = @_;
3690 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3691 sort { $a->_date <=> $b->_date }
3692 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3693 'pkgnum' => $pkgnum,
3700 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3706 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3707 sort { $a->_date <=> $b->_date }
3708 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3711 =item cust_pay_pending
3713 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3714 (without status "done").
3718 sub cust_pay_pending {
3720 return $self->num_cust_pay_pending unless wantarray;
3721 sort { $a->_date <=> $b->_date }
3722 qsearch( 'cust_pay_pending', {
3723 'custnum' => $self->custnum,
3724 'status' => { op=>'!=', value=>'done' },
3729 =item cust_pay_pending_attempt
3731 Returns all payment attempts / declined payments for this customer, as pending
3732 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3733 a corresponding payment (see L<FS::cust_pay>).
3737 sub cust_pay_pending_attempt {
3739 return $self->num_cust_pay_pending_attempt unless wantarray;
3740 sort { $a->_date <=> $b->_date }
3741 qsearch( 'cust_pay_pending', {
3742 'custnum' => $self->custnum,
3749 =item num_cust_pay_pending
3751 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3752 customer (without status "done"). Also called automatically when the
3753 cust_pay_pending method is used in a scalar context.
3757 sub num_cust_pay_pending {
3760 " SELECT COUNT(*) FROM cust_pay_pending ".
3761 " WHERE custnum = ? AND status != 'done' ",
3766 =item num_cust_pay_pending_attempt
3768 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3769 customer, with status "done" but without a corresp. Also called automatically when the
3770 cust_pay_pending method is used in a scalar context.
3774 sub num_cust_pay_pending_attempt {
3777 " SELECT COUNT(*) FROM cust_pay_pending ".
3778 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3785 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3791 map { $_ } #return $self->num_cust_refund unless wantarray;
3792 sort { $a->_date <=> $b->_date }
3793 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3796 =item display_custnum
3798 Returns the displayed customer number for this customer: agent_custid if
3799 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3803 sub display_custnum {
3806 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3807 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3808 if ( $special eq 'CoStAg' ) {
3809 $prefix = uc( join('',
3811 ($self->state =~ /^(..)/),
3812 $prefix || ($self->agent->agent =~ /^(..)/)
3815 elsif ( $special eq 'CoStCl' ) {
3816 $prefix = uc( join('',
3818 ($self->state =~ /^(..)/),
3819 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3822 # add any others here if needed
3825 my $length = $conf->config('cust_main-custnum-display_length');
3826 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3827 return $self->agent_custid;
3828 } elsif ( $prefix ) {
3829 $length = 8 if !defined($length);
3831 sprintf('%0'.$length.'d', $self->custnum)
3832 } elsif ( $length ) {
3833 return sprintf('%0'.$length.'d', $self->custnum);
3835 return $self->custnum;
3841 Returns a name string for this customer, either "Company (Last, First)" or
3848 my $name = $self->contact;
3849 $name = $self->company. " ($name)" if $self->company;
3853 =item service_contact
3855 Returns the L<FS::contact> object for this customer that has the 'Service'
3856 contact class, or undef if there is no such contact. Deprecated; don't use
3861 sub service_contact {
3863 if ( !exists($self->{service_contact}) ) {
3864 my $classnum = $self->scalar_sql(
3865 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3866 ) || 0; #if it's zero, qsearchs will return nothing
3867 my $cust_contact = qsearchs('cust_contact', {
3868 'classnum' => $classnum,
3869 'custnum' => $self->custnum,
3871 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3873 $self->{service_contact};
3878 Returns a name string for this (service/shipping) contact, either
3879 "Company (Last, First)" or "Last, First".
3886 my $name = $self->ship_contact;
3887 $name = $self->company. " ($name)" if $self->company;
3893 Returns a name string for this customer, either "Company" or "First Last".
3899 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3902 =item ship_name_short
3904 Returns a name string for this (service/shipping) contact, either "Company"
3909 sub ship_name_short {
3911 $self->service_contact
3912 ? $self->ship_contact_firstlast
3918 Returns this customer's full (billing) contact name only, "Last, First"
3924 $self->get('last'). ', '. $self->first;
3929 Returns this customer's full (shipping) contact name only, "Last, First"
3935 my $contact = $self->service_contact || $self;
3936 $contact->get('last') . ', ' . $contact->get('first');
3939 =item contact_firstlast
3941 Returns this customers full (billing) contact name only, "First Last".
3945 sub contact_firstlast {
3947 $self->first. ' '. $self->get('last');
3950 =item ship_contact_firstlast
3952 Returns this customer's full (shipping) contact name only, "First Last".
3956 sub ship_contact_firstlast {
3958 my $contact = $self->service_contact || $self;
3959 $contact->get('first') . ' '. $contact->get('last');
3962 sub bill_country_full {
3964 $self->bill_location->country_full;
3967 sub ship_country_full {
3969 $self->ship_location->country_full;
3972 =item county_state_county [ PREFIX ]
3974 Returns a string consisting of just the county, state and country.
3978 sub county_state_country {
3981 if ( @_ && $_[0] && $self->has_ship_address ) {
3982 $locationnum = $self->ship_locationnum;
3984 $locationnum = $self->bill_locationnum;
3986 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3987 $cust_location->county_state_country;
3990 =item geocode DATA_VENDOR
3992 Returns a value for the customer location as encoded by DATA_VENDOR.
3993 Currently this only makes sense for "CCH" as DATA_VENDOR.
4001 Returns a status string for this customer, currently:
4007 No packages have ever been ordered. Displayed as "No packages".
4011 Recurring packages all are new (not yet billed).
4015 One or more recurring packages is active.
4019 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
4023 All non-cancelled recurring packages are suspended.
4027 All recurring packages are cancelled.
4031 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4032 cust_main-status_module configuration option.
4036 sub status { shift->cust_status(@_); }
4040 for my $status ( FS::cust_main->statuses() ) {
4041 my $method = $status.'_sql';
4042 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4043 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4044 $sth->execute( ($self->custnum) x $numnum )
4045 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4046 return $status if $sth->fetchrow_arrayref->[0];
4050 =item is_status_delay_cancel
4052 Returns true if customer status is 'suspended'
4053 and all suspended cust_pkg return true for
4054 cust_pkg->is_status_delay_cancel.
4056 This is not a real status, this only meant for hacking display
4057 values, because otherwise treating the customer as suspended is
4058 really the whole point of the delay_cancel option.
4062 sub is_status_delay_cancel {
4064 return 0 unless $self->status eq 'suspended';
4065 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4066 return 0 unless $cust_pkg->is_status_delay_cancel;
4071 =item ucfirst_cust_status
4073 =item ucfirst_status
4075 Deprecated, use the cust_status_label method instead.
4077 Returns the status with the first character capitalized.
4081 sub ucfirst_status {
4082 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4083 local($ucfirst_nowarn) = 1;
4084 shift->ucfirst_cust_status(@_);
4087 sub ucfirst_cust_status {
4088 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4090 ucfirst($self->cust_status);
4093 =item cust_status_label
4097 Returns the display label for this status.
4101 sub status_label { shift->cust_status_label(@_); }
4103 sub cust_status_label {
4105 __PACKAGE__->statuslabels->{$self->cust_status};
4110 Returns a hex triplet color string for this customer's status.
4114 sub statuscolor { shift->cust_statuscolor(@_); }
4116 sub cust_statuscolor {
4118 __PACKAGE__->statuscolors->{$self->cust_status};
4121 =item tickets [ STATUS ]
4123 Returns an array of hashes representing the customer's RT tickets.
4125 An optional status (or arrayref or hashref of statuses) may be specified.
4131 my $status = ( @_ && $_[0] ) ? shift : '';
4133 my $num = $conf->config('cust_main-max_tickets') || 10;
4136 if ( $conf->config('ticket_system') ) {
4137 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4139 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4148 foreach my $priority (
4149 $conf->config('ticket_system-custom_priority_field-values'), ''
4151 last if scalar(@tickets) >= $num;
4153 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4154 $num - scalar(@tickets),
4165 =item appointments [ STATUS ]
4167 Returns an array of hashes representing the customer's RT tickets which
4174 my $status = ( @_ && $_[0] ) ? shift : '';
4176 return () unless $conf->config('ticket_system');
4178 my $queueid = $conf->config('ticket_system-appointment-queueid');
4180 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4189 # Return services representing svc_accts in customer support packages
4190 sub support_services {
4192 my %packages = map { $_ => 1 } $conf->config('support_packages');
4194 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4195 grep { $_->part_svc->svcdb eq 'svc_acct' }
4196 map { $_->cust_svc }
4197 grep { exists $packages{ $_->pkgpart } }
4198 $self->ncancelled_pkgs;
4202 # Return a list of latitude/longitude for one of the services (if any)
4203 sub service_coordinates {
4207 grep { $_->latitude && $_->longitude }
4209 map { $_->cust_svc }
4210 $self->ncancelled_pkgs;
4212 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4217 Returns a masked version of the named field
4222 my ($self,$field) = @_;
4226 'x'x(length($self->getfield($field))-4).
4227 substr($self->getfield($field), (length($self->getfield($field))-4));
4231 =item payment_history
4233 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4234 cust_credit and cust_refund objects. Each hashref has the following fields:
4236 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4238 I<date> - value of _date field, unix timestamp
4240 I<date_pretty> - user-friendly date
4242 I<description> - user-friendly description of item
4244 I<amount> - impact of item on user's balance
4245 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4246 Not to be confused with the native 'amount' field in cust_credit, see below.
4248 I<amount_pretty> - includes money char
4250 I<balance> - customer balance, chronologically as of this item
4252 I<balance_pretty> - includes money char
4254 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4256 I<paid> - amount paid for cust_pay records, undef for other types
4258 I<credit> - amount credited for cust_credit records, undef for other types.
4259 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4261 I<refund> - amount refunded for cust_refund records, undef for other types
4263 The four table-specific keys always have positive values, whether they reflect charges or payments.
4265 The following options may be passed to this method:
4267 I<line_items> - if true, returns charges ('Line item') rather than invoices
4269 I<start_date> - unix timestamp, only include records on or after.
4270 If specified, an item of type 'Previous' will also be included.
4271 It does not have table-specific fields.
4273 I<end_date> - unix timestamp, only include records before
4275 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4277 I<conf> - optional already-loaded FS::Conf object.
4281 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4282 # and also for sending customer statements, which should both be kept customer-friendly.
4283 # If you add anything that shouldn't be passed on through the API or exposed
4284 # to customers, add a new option to include it, don't include it by default
4285 sub payment_history {
4287 my $opt = ref($_[0]) ? $_[0] : { @_ };
4289 my $conf = $$opt{'conf'} || new FS::Conf;
4290 my $money_char = $conf->config("money_char") || '$',
4292 #first load entire history,
4293 #need previous to calculate previous balance
4294 #loading after end_date shouldn't hurt too much?
4296 if ( $$opt{'line_items'} ) {
4298 foreach my $cust_bill ( $self->cust_bill ) {
4301 'type' => 'Line item',
4302 'description' => $_->desc( $self->locale ).
4303 ( $_->sdate && $_->edate
4304 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4305 ' To '. time2str('%d-%b-%Y', $_->edate)
4308 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4309 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4310 'date' => $cust_bill->_date,
4311 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4313 foreach $cust_bill->cust_bill_pkg;
4320 'type' => 'Invoice',
4321 'description' => 'Invoice #'. $_->display_invnum,
4322 'amount' => sprintf('%.2f', $_->charged ),
4323 'charged' => sprintf('%.2f', $_->charged ),
4324 'date' => $_->_date,
4325 'date_pretty' => $self->time2str_local('short', $_->_date ),
4327 foreach $self->cust_bill;
4332 'type' => 'Payment',
4333 'description' => 'Payment', #XXX type
4334 'amount' => sprintf('%.2f', 0 - $_->paid ),
4335 'paid' => sprintf('%.2f', $_->paid ),
4336 'date' => $_->_date,
4337 'date_pretty' => $self->time2str_local('short', $_->_date ),
4339 foreach $self->cust_pay;
4343 'description' => 'Credit', #more info?
4344 'amount' => sprintf('%.2f', 0 -$_->amount ),
4345 'credit' => sprintf('%.2f', $_->amount ),
4346 'date' => $_->_date,
4347 'date_pretty' => $self->time2str_local('short', $_->_date ),
4349 foreach $self->cust_credit;
4353 'description' => 'Refund', #more info? type, like payment?
4354 'amount' => $_->refund,
4355 'refund' => $_->refund,
4356 'date' => $_->_date,
4357 'date_pretty' => $self->time2str_local('short', $_->_date ),
4359 foreach $self->cust_refund;
4361 #put it all in chronological order
4362 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4364 #calculate balance, filter items outside date range
4368 foreach my $item (@history) {
4369 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4370 $balance += $$item{'amount'};
4371 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4372 $previous += $$item{'amount'};
4375 $$item{'balance'} = sprintf("%.2f",$balance);
4376 foreach my $key ( qw(amount balance) ) {
4377 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4382 # start with previous balance, if there was one
4385 'type' => 'Previous',
4386 'description' => 'Previous balance',
4387 'amount' => sprintf("%.2f",$previous),
4388 'balance' => sprintf("%.2f",$previous),
4389 'date' => $$opt{'start_date'},
4390 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4392 #false laziness with above
4393 foreach my $key ( qw(amount balance) ) {
4394 $$item{$key.'_pretty'} = $$item{$key};
4395 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4397 unshift(@out,$item);
4400 @out = reverse @history if $$opt{'reverse_sort'};
4405 =item save_cust_payby
4407 Saves a new cust_payby for this customer, replacing an existing entry only
4408 in select circumstances. Does not validate input.
4410 If auto is specified, marks this as the customer's primary method (weight 1)
4411 and changes existing primary methods for that payby to secondary methods (weight 2.)
4412 If bill_location is specified with auto, also sets location in cust_main.
4414 Will not insert complete duplicates of existing records, or records in which the
4415 only difference from an existing record is to turn off automatic payment (will
4416 return without error.) Will replace existing records in which the only difference
4417 is to add a value to a previously empty preserved field and/or turn on automatic payment.
4418 Fields marked as preserved are optional, and existing values will not be overwritten with
4419 blanks when replacing.
4421 Accepts the following named parameters:
4423 payment_payby - either CARD or CHEK
4425 auto - save as an automatic payment type (CARD/CHEK if true, DCRD/DCHK if false)
4429 paymask - optional, but should be specified for anything that might be tokenized, will be preserved when replacing
4433 payip - optional, will be preserved when replacing
4435 paydate - CARD only, required
4437 bill_location - CARD only, required, FS::cust_location object
4439 paystart_month - CARD only, optional, will be preserved when replacing
4441 paystart_year - CARD only, optional, will be preserved when replacing
4443 payissue - CARD only, optional, will be preserved when replacing
4445 paycvv - CARD only, only used if conf cvv-save is set appropriately
4449 paystate - CHEK only
4453 #The code for this option is in place, but it's not currently used
4455 # replace - existing cust_payby object to be replaced (must match custnum)
4457 # stateid/stateid_state/ss are not currently supported in cust_payby,
4458 # might not even work properly in 4.x, but will need to work here if ever added
4460 sub save_cust_payby {
4464 my $old = $opt{'replace'};
4465 my $new = new FS::cust_payby { $old ? $old->hash : () };
4466 return "Customer number does not match" if $new->custnum and $new->custnum != $self->custnum;
4467 $new->set( 'custnum' => $self->custnum );
4469 my $payby = $opt{'payment_payby'};
4470 return "Bad payby" unless grep(/^$payby$/,('CARD','CHEK'));
4472 # don't allow turning off auto when replacing
4473 $opt{'auto'} ||= 1 if $old and $old->payby !~ /^D/;
4475 my @check_existing; # payby relevant to this payment_payby
4477 # set payby based on auto
4478 if ( $payby eq 'CARD' ) {
4479 $new->set( 'payby' => ( $opt{'auto'} ? 'CARD' : 'DCRD' ) );
4480 @check_existing = qw( CARD DCRD );
4481 } elsif ( $payby eq 'CHEK' ) {
4482 $new->set( 'payby' => ( $opt{'auto'} ? 'CHEK' : 'DCHK' ) );
4483 @check_existing = qw( CHEK DCHK );
4486 # every automatic payment type added here will be marked primary
4487 $new->set( 'weight' => $opt{'auto'} ? 1 : '' );
4490 $new->payinfo($opt{'payinfo'}); # sets default paymask, but not if it's already tokenized
4491 $new->paymask($opt{'paymask'}) if $opt{'paymask'}; # in case it's been tokenized, override with loaded paymask
4492 $new->set( 'payname' => $opt{'payname'} );
4493 $new->set( 'payip' => $opt{'payip'} ); # will be preserved below
4495 my $conf = new FS::Conf;
4497 # compare to FS::cust_main::realtime_bop - check both to make sure working correctly
4498 if ( $payby eq 'CARD' &&
4499 grep { $_ eq cardtype($opt{'payinfo'}) } $conf->config('cvv-save') ) {
4500 $new->set( 'paycvv' => $opt{'paycvv'} );
4502 $new->set( 'paycvv' => '');
4505 local $SIG{HUP} = 'IGNORE';
4506 local $SIG{INT} = 'IGNORE';
4507 local $SIG{QUIT} = 'IGNORE';
4508 local $SIG{TERM} = 'IGNORE';
4509 local $SIG{TSTP} = 'IGNORE';
4510 local $SIG{PIPE} = 'IGNORE';
4512 my $oldAutoCommit = $FS::UID::AutoCommit;
4513 local $FS::UID::AutoCommit = 0;
4516 # set fields specific to payment_payby
4517 if ( $payby eq 'CARD' ) {
4518 if ($opt{'bill_location'}) {
4519 $opt{'bill_location'}->set('custnum' => $self->custnum);
4520 my $error = $opt{'bill_location'}->find_or_insert;
4522 $dbh->rollback if $oldAutoCommit;
4525 $new->set( 'locationnum' => $opt{'bill_location'}->locationnum );
4527 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
4528 $new->set( $field => $opt{$field} );
4531 foreach my $field ( qw(paytype paystate) ) {
4532 $new->set( $field => $opt{$field} );
4536 # other cust_payby to compare this to
4537 my @existing = $self->cust_payby(@check_existing);
4539 # fields that can overwrite blanks with values, but not values with blanks
4540 my @preserve = qw( paymask locationnum paystart_month paystart_year payissue payip );
4542 my $skip_cust_payby = 0; # true if we don't need to save or reweight cust_payby
4544 # generally, we don't want to overwrite existing cust_payby with this,
4545 # but we can replace if we're only marking it auto or adding a preserved field
4546 # and we can avoid saving a total duplicate or merely turning off auto
4548 foreach my $cust_payby (@existing) {
4549 # check fields that absolutely should not change
4550 foreach my $field ($new->fields) {
4551 next if grep(/^$field$/, qw( custpaybynum payby weight ) );
4552 next if grep(/^$field$/, @preserve );
4553 next PAYBYLOOP unless $new->get($field) eq $cust_payby->get($field);
4555 # now check fields that can replace if one value is blank
4557 foreach my $field (@preserve) {
4559 ( $new->get($field) and !$cust_payby->get($field) ) or
4560 ( $cust_payby->get($field) and !$new->get($field) )
4562 # prevention of overwriting values with blanks happens farther below
4564 } elsif ( $new->get($field) ne $cust_payby->get($field) ) {
4568 unless ( $replace ) {
4569 # nearly identical, now check weight
4570 if ($new->get('weight') eq $cust_payby->get('weight') or !$new->get('weight')) {
4571 # ignore identical cust_payby, and ignore attempts to turn off auto
4572 # no need to save or re-weight cust_payby (but still need to update/commit $self)
4573 $skip_cust_payby = 1;
4576 # otherwise, only change is to mark this as primary
4578 # if we got this far, we're definitely replacing
4585 $new->set( 'custpaybynum' => $old->custpaybynum );
4586 # don't turn off automatic payment (but allow it to be turned on)
4587 if ($new->payby =~ /^D/ and $new->payby ne $old->payby) {
4589 $new->set( 'payby' => $old->payby );
4590 $new->set( 'weight' => 1 );
4592 # make sure we're not overwriting values with blanks
4593 foreach my $field (@preserve) {
4594 if ( $old->get($field) and !$new->get($field) ) {
4595 $new->set( $field => $old->get($field) );
4600 # only overwrite cust_main bill_location if auto
4601 if ($opt{'auto'} && $opt{'bill_location'}) {
4602 $self->set('bill_location' => $opt{'bill_location'});
4603 my $error = $self->replace;
4605 $dbh->rollback if $oldAutoCommit;
4610 # done with everything except reweighting and saving cust_payby
4611 # still need to commit changes to cust_main and cust_location
4612 if ($skip_cust_payby) {
4613 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4617 # re-weight existing primary cust_pay for this payby
4619 foreach my $cust_payby (@existing) {
4620 # relies on cust_payby return order
4621 last unless $cust_payby->payby !~ /^D/;
4622 last if $cust_payby->weight > 1;
4623 next if $new->custpaybynum eq $cust_payby->custpaybynum;
4624 $cust_payby->set( 'weight' => 2 );
4625 my $error = $cust_payby->replace;
4627 $dbh->rollback if $oldAutoCommit;
4628 return "Error reweighting cust_payby: $error";
4633 # finally, save cust_payby
4634 my $error = $old ? $new->replace($old) : $new->insert;
4636 $dbh->rollback if $oldAutoCommit;
4640 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4647 =head1 CLASS METHODS
4653 Class method that returns the list of possible status strings for customers
4654 (see L<the status method|/status>). For example:
4656 @statuses = FS::cust_main->statuses();
4662 keys %{ $self->statuscolors };
4665 =item cust_status_sql
4667 Returns an SQL fragment to determine the status of a cust_main record, as a
4672 sub cust_status_sql {
4674 for my $status ( FS::cust_main->statuses() ) {
4675 my $method = $status.'_sql';
4676 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4685 Returns an SQL expression identifying prospective cust_main records (customers
4686 with no packages ever ordered)
4690 use vars qw($select_count_pkgs);
4691 $select_count_pkgs =
4692 "SELECT COUNT(*) FROM cust_pkg
4693 WHERE cust_pkg.custnum = cust_main.custnum";
4695 sub select_count_pkgs_sql {
4700 " 0 = ( $select_count_pkgs ) ";
4705 Returns an SQL expression identifying ordered cust_main records (customers with
4706 no active packages, but recurring packages not yet setup or one time charges
4712 FS::cust_main->none_active_sql.
4713 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4718 Returns an SQL expression identifying active cust_main records (customers with
4719 active recurring packages).
4724 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4727 =item none_active_sql
4729 Returns an SQL expression identifying cust_main records with no active
4730 recurring packages. This includes customers of status prospect, ordered,
4731 inactive, and suspended.
4735 sub none_active_sql {
4736 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4741 Returns an SQL expression identifying inactive cust_main records (customers with
4742 no active recurring packages, but otherwise unsuspended/uncancelled).
4747 FS::cust_main->none_active_sql.
4748 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4754 Returns an SQL expression identifying suspended cust_main records.
4759 sub suspended_sql { susp_sql(@_); }
4761 FS::cust_main->none_active_sql.
4762 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4768 Returns an SQL expression identifying cancelled cust_main records.
4772 sub cancel_sql { shift->cancelled_sql(@_); }
4775 =item uncancelled_sql
4777 Returns an SQL expression identifying un-cancelled cust_main records.
4781 sub uncancelled_sql { uncancel_sql(@_); }
4782 sub uncancel_sql { "
4783 ( 0 < ( $select_count_pkgs
4784 AND ( cust_pkg.cancel IS NULL
4785 OR cust_pkg.cancel = 0
4788 OR 0 = ( $select_count_pkgs )
4794 Returns an SQL fragment to retreive the balance.
4799 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4800 WHERE cust_bill.custnum = cust_main.custnum )
4801 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4802 WHERE cust_pay.custnum = cust_main.custnum )
4803 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4804 WHERE cust_credit.custnum = cust_main.custnum )
4805 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4806 WHERE cust_refund.custnum = cust_main.custnum )
4809 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4811 Returns an SQL fragment to retreive the balance for this customer, optionally
4812 considering invoices with date earlier than START_TIME, and not
4813 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4814 total_unapplied_payments).
4816 Times are specified as SQL fragments or numeric
4817 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4818 L<Date::Parse> for conversion functions. The empty string can be passed
4819 to disable that time constraint completely.
4821 Available options are:
4825 =item unapplied_date
4827 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)
4832 set to true to remove all customer comparison clauses, for totals
4837 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4842 JOIN clause (typically used with the total option)
4846 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4847 time will be ignored. Note that START_TIME and END_TIME only limit the date
4848 range for invoices and I<unapplied> payments, credits, and refunds.
4854 sub balance_date_sql {
4855 my( $class, $start, $end, %opt ) = @_;
4857 my $cutoff = $opt{'cutoff'};
4859 my $owed = FS::cust_bill->owed_sql($cutoff);
4860 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4861 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4862 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4864 my $j = $opt{'join'} || '';
4866 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4867 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4868 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4869 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4871 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4872 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4873 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4874 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4879 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4881 Returns an SQL fragment to retreive the total unapplied payments for this
4882 customer, only considering payments with date earlier than START_TIME, and
4883 optionally not later than END_TIME.
4885 Times are specified as SQL fragments or numeric
4886 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4887 L<Date::Parse> for conversion functions. The empty string can be passed
4888 to disable that time constraint completely.
4890 Available options are:
4894 sub unapplied_payments_date_sql {
4895 my( $class, $start, $end, %opt ) = @_;
4897 my $cutoff = $opt{'cutoff'};
4899 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4901 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4902 'unapplied_date'=>1 );
4904 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4907 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4909 Helper method for balance_date_sql; name (and usage) subject to change
4910 (suggestions welcome).
4912 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4913 cust_refund, cust_credit or cust_pay).
4915 If TABLE is "cust_bill" or the unapplied_date option is true, only
4916 considers records with date earlier than START_TIME, and optionally not
4917 later than END_TIME .
4921 sub _money_table_where {
4922 my( $class, $table, $start, $end, %opt ) = @_;
4925 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4926 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4927 push @where, "$table._date <= $start" if defined($start) && length($start);
4928 push @where, "$table._date > $end" if defined($end) && length($end);
4930 push @where, @{$opt{'where'}} if $opt{'where'};
4931 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4937 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4938 use FS::cust_main::Search;
4941 FS::cust_main::Search->search(@_);
4950 #=item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4952 #Deprecated. Use event notification and message templates
4953 #(L<FS::msg_template>) instead.
4955 #Sends a templated email notification to the customer (see L<Text::Template>).
4957 #OPTIONS is a hash and may include
4959 #I<from> - the email sender (default is invoice_from)
4961 #I<to> - comma-separated scalar or arrayref of recipients
4962 # (default is invoicing_list)
4964 #I<subject> - The subject line of the sent email notification
4965 # (default is "Notice from company_name")
4967 #I<extra_fields> - a hashref of name/value pairs which will be substituted
4970 #The following variables are vavailable in the template.
4972 #I<$first> - the customer first name
4973 #I<$last> - the customer last name
4974 #I<$company> - the customer company
4975 #I<$payby> - a description of the method of payment for the customer
4976 # # would be nice to use FS::payby::shortname
4977 #I<$payinfo> - the account information used to collect for this customer
4978 #I<$expdate> - the expiration of the customer payment in seconds from epoch
4983 # my ($self, $template, %options) = @_;
4985 # return unless $conf->exists($template);
4987 # my $from = $conf->invoice_from_full($self->agentnum)
4988 # if $conf->exists('invoice_from', $self->agentnum);
4989 # $from = $options{from} if exists($options{from});
4991 # my $to = join(',', $self->invoicing_list_emailonly);
4992 # $to = $options{to} if exists($options{to});
4994 # my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4995 # if $conf->exists('company_name', $self->agentnum);
4996 # $subject = $options{subject} if exists($options{subject});
4998 # my $notify_template = new Text::Template (TYPE => 'ARRAY',
4999 # SOURCE => [ map "$_\n",
5000 # $conf->config($template)]
5002 # or die "can't create new Text::Template object: Text::Template::ERROR";
5003 # $notify_template->compile()
5004 # or die "can't compile template: Text::Template::ERROR";
5006 # $FS::notify_template::_template::company_name =
5007 # $conf->config('company_name', $self->agentnum);
5008 # $FS::notify_template::_template::company_address =
5009 # join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5011 # my $paydate = $self->paydate || '2037-12-31';
5012 # $FS::notify_template::_template::first = $self->first;
5013 # $FS::notify_template::_template::last = $self->last;
5014 # $FS::notify_template::_template::company = $self->company;
5015 # $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5016 # my $payby = $self->payby;
5017 # my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5018 # my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5020 # #credit cards expire at the end of the month/year of their exp date
5021 # if ($payby eq 'CARD' || $payby eq 'DCRD') {
5022 # $FS::notify_template::_template::payby = 'credit card';
5023 # ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5024 # $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5026 # }elsif ($payby eq 'COMP') {
5027 # $FS::notify_template::_template::payby = 'complimentary account';
5029 # $FS::notify_template::_template::payby = 'current method';
5031 # $FS::notify_template::_template::expdate = $expire_time;
5033 # for (keys %{$options{extra_fields}}){
5035 # ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5038 # send_email(from => $from,
5040 # subject => $subject,
5041 # body => $notify_template->fill_in( PACKAGE =>
5042 # 'FS::notify_template::_template' ),
5047 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5049 Generates a templated notification to the customer (see L<Text::Template>).
5051 OPTIONS is a hash and may include
5053 I<extra_fields> - a hashref of name/value pairs which will be substituted
5054 into the template. These values may override values mentioned below
5055 and those from the customer record.
5057 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5059 The following variables are available in the template instead of or in addition
5060 to the fields of the customer record.
5062 I<$payby> - a description of the method of payment for the customer
5063 # would be nice to use FS::payby::shortname
5064 I<$payinfo> - the masked account information used to collect for this customer
5065 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5066 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5070 # a lot like cust_bill::print_latex
5071 sub generate_letter {
5072 my ($self, $template, %options) = @_;
5074 warn "Template $template does not exist" && return
5075 unless $conf->exists($template) || $options{'template_text'};
5077 my $template_source = $options{'template_text'}
5078 ? [ $options{'template_text'} ]
5079 : [ map "$_\n", $conf->config($template) ];
5081 my $letter_template = new Text::Template
5083 SOURCE => $template_source,
5084 DELIMITERS => [ '[@--', '--@]' ],
5086 or die "can't create new Text::Template object: Text::Template::ERROR";
5088 $letter_template->compile()
5089 or die "can't compile template: Text::Template::ERROR";
5091 my %letter_data = map { $_ => $self->$_ } $self->fields;
5092 $letter_data{payinfo} = $self->mask_payinfo;
5094 #my $paydate = $self->paydate || '2037-12-31';
5095 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5097 my $payby = $self->payby;
5098 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5099 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5101 #credit cards expire at the end of the month/year of their exp date
5102 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5103 $letter_data{payby} = 'credit card';
5104 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5105 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5107 }elsif ($payby eq 'COMP') {
5108 $letter_data{payby} = 'complimentary account';
5110 $letter_data{payby} = 'current method';
5112 $letter_data{expdate} = $expire_time;
5114 for (keys %{$options{extra_fields}}){
5115 $letter_data{$_} = $options{extra_fields}->{$_};
5118 unless(exists($letter_data{returnaddress})){
5119 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5120 $self->agent_template)
5122 if ( length($retadd) ) {
5123 $letter_data{returnaddress} = $retadd;
5124 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5125 $letter_data{returnaddress} =
5126 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5130 ( $conf->config('company_name', $self->agentnum),
5131 $conf->config('company_address', $self->agentnum),
5135 $letter_data{returnaddress} = '~';
5139 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5141 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5143 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5145 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5149 ) or die "can't open temp file: $!\n";
5150 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5151 or die "can't write temp file: $!\n";
5153 $letter_data{'logo_file'} = $lh->filename;
5155 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5159 ) or die "can't open temp file: $!\n";
5161 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5163 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5164 return ($1, $letter_data{'logo_file'});
5168 =item print_ps TEMPLATE
5170 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5176 my($file, $lfile) = $self->generate_letter(@_);
5177 my $ps = FS::Misc::generate_ps($file);
5178 unlink($file.'.tex');
5184 =item print TEMPLATE
5186 Prints the filled in template.
5188 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5192 sub queueable_print {
5195 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5196 or die "invalid customer number: " . $opt{custnum};
5198 #do not backport this change to 3.x
5199 # my $error = $self->print( { 'template' => $opt{template} } );
5200 my $error = $self->print( $opt{'template'} );
5201 die $error if $error;
5205 my ($self, $template) = (shift, shift);
5207 [ $self->print_ps($template) ],
5208 'agentnum' => $self->agentnum,
5212 #these three subs should just go away once agent stuff is all config overrides
5214 sub agent_template {
5216 $self->_agent_plandata('agent_templatename');
5219 sub agent_invoice_from {
5221 $self->_agent_plandata('agent_invoice_from');
5224 sub _agent_plandata {
5225 my( $self, $option ) = @_;
5227 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5228 #agent-specific Conf
5230 use FS::part_event::Condition;
5232 my $agentnum = $self->agentnum;
5234 my $regexp = regexp_sql();
5236 my $part_event_option =
5238 'select' => 'part_event_option.*',
5239 'table' => 'part_event_option',
5241 LEFT JOIN part_event USING ( eventpart )
5242 LEFT JOIN part_event_option AS peo_agentnum
5243 ON ( part_event.eventpart = peo_agentnum.eventpart
5244 AND peo_agentnum.optionname = 'agentnum'
5245 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5247 LEFT JOIN part_event_condition
5248 ON ( part_event.eventpart = part_event_condition.eventpart
5249 AND part_event_condition.conditionname = 'cust_bill_age'
5251 LEFT JOIN part_event_condition_option
5252 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5253 AND part_event_condition_option.optionname = 'age'
5256 #'hashref' => { 'optionname' => $option },
5257 #'hashref' => { 'part_event_option.optionname' => $option },
5259 " WHERE part_event_option.optionname = ". dbh->quote($option).
5260 " AND action = 'cust_bill_send_agent' ".
5261 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5262 " AND peo_agentnum.optionname = 'agentnum' ".
5263 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5265 CASE WHEN part_event_condition_option.optionname IS NULL
5267 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5269 , part_event.weight".
5273 unless ( $part_event_option ) {
5274 return $self->agent->invoice_template || ''
5275 if $option eq 'agent_templatename';
5279 $part_event_option->optionvalue;
5283 sub process_o2m_qsearch {
5286 return qsearch($table, @_) unless $table eq 'contact';
5288 my $hashref = shift;
5289 my %hash = %$hashref;
5290 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5291 or die 'guru meditation #4343';
5293 qsearch({ 'table' => 'contact',
5294 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5295 'hashref' => \%hash,
5296 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5297 " cust_contact.custnum = $custnum "
5301 sub process_o2m_qsearchs {
5304 return qsearchs($table, @_) unless $table eq 'contact';
5306 my $hashref = shift;
5307 my %hash = %$hashref;
5308 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5309 or die 'guru meditation #2121';
5311 qsearchs({ 'table' => 'contact',
5312 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5313 'hashref' => \%hash,
5314 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5315 " cust_contact.custnum = $custnum "
5319 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5321 Subroutine (not a method), designed to be called from the queue.
5323 Takes a list of options and values.
5325 Pulls up the customer record via the custnum option and calls bill_and_collect.
5330 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5332 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5333 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5335 #without this errors don't get rolled back
5336 $args{'fatal'} = 1; # runs from job queue, will be caught
5338 $cust_main->bill_and_collect( %args );
5341 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5343 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5344 C<collect> part. This is used in batch tax calculation, where invoice
5345 generation and collection events have to be completely separated.
5349 sub queued_collect {
5351 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5353 $cust_main->collect(%args);
5356 sub process_bill_and_collect {
5359 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5360 or die "custnum '$param->{custnum}' not found!\n";
5361 $param->{'job'} = $job;
5362 $param->{'fatal'} = 1; # runs from job queue, will be caught
5363 $param->{'retry'} = 1;
5365 $cust_main->bill_and_collect( %$param );
5368 #starting to take quite a while for big dbs
5369 # (JRNL: journaled so it only happens once per database)
5370 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5371 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5372 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5373 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5374 # JRNL leading/trailing spaces in first, last, company
5375 # JRNL migrate to cust_payby
5376 # - otaker upgrade? journal and call it good? (double check to make sure
5377 # we're not still setting otaker here)
5379 #only going to get worse with new location stuff...
5381 sub _upgrade_data { #class method
5382 my ($class, %opts) = @_;
5385 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5388 #this seems to be the only expensive one.. why does it take so long?
5389 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5391 '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';
5392 FS::upgrade_journal->set_done('cust_main__signupdate');
5395 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5397 # fix yyyy-m-dd formatted paydates
5398 if ( driver_name =~ /^mysql/i ) {
5400 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5401 } else { # the SQL standard
5403 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5405 FS::upgrade_journal->set_done('cust_main__paydate');
5408 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5410 push @statements, #fix the weird BILL with a cc# in payinfo problem
5412 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5414 FS::upgrade_journal->set_done('cust_main__payinfo');
5419 foreach my $sql ( @statements ) {
5420 my $sth = dbh->prepare($sql) or die dbh->errstr;
5421 $sth->execute or die $sth->errstr;
5422 #warn ( (time - $t). " seconds\n" );
5426 local($ignore_expired_card) = 1;
5427 local($ignore_banned_card) = 1;
5428 local($skip_fuzzyfiles) = 1;
5429 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5431 FS::cust_main::Location->_upgrade_data(%opts);
5433 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5435 foreach my $cust_main ( qsearch({
5436 'table' => 'cust_main',
5438 'extra_sql' => 'WHERE '.
5440 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5441 qw( first last company )
5444 my $error = $cust_main->replace;
5445 die $error if $error;
5448 FS::upgrade_journal->set_done('cust_main__trimspaces');
5452 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5454 #we don't want to decrypt them, just stuff them as-is into cust_payby
5455 local(@encrypted_fields) = ();
5457 local($FS::cust_payby::ignore_expired_card) = 1;
5458 local($FS::cust_payby::ignore_banned_card) = 1;
5460 my @payfields = qw( payby payinfo paycvv paymask
5461 paydate paystart_month paystart_year payissue
5462 payname paystate paytype payip
5465 my $search = new FS::Cursor {
5466 'table' => 'cust_main',
5467 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5470 while (my $cust_main = $search->fetch) {
5472 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
5474 my $cust_payby = new FS::cust_payby {
5475 'custnum' => $cust_main->custnum,
5477 map { $_ => $cust_main->$_(); } @payfields
5480 my $error = $cust_payby->insert;
5481 die $error if $error;
5485 # at the time we do this, also migrate paytype into cust_pay_batch
5486 # so that batches that are open before the migration can still be
5488 my @cust_pay_batch = qsearch('cust_pay_batch', {
5489 'custnum' => $cust_main->custnum,
5493 foreach my $cust_pay_batch (@cust_pay_batch) {
5494 $cust_pay_batch->set('paytype', $cust_main->get('paytype'));
5495 my $error = $cust_pay_batch->replace;
5496 die "$error (setting cust_pay_batch.paytype)" if $error;
5499 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
5501 $cust_main->invoice_attn( $cust_main->payname )
5502 if $cust_main->payby eq 'BILL' && $cust_main->payname;
5503 $cust_main->po_number( $cust_main->payinfo )
5504 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
5506 $cust_main->setfield($_, '') foreach @payfields;
5507 my $error = $cust_main->replace;
5508 die "Error upgradging payment information for custnum ".
5509 $cust_main->custnum. ": $error"
5514 FS::upgrade_journal->set_done('cust_main__cust_payby');
5517 $class->_upgrade_otaker(%opts);
5527 The delete method should possibly take an FS::cust_main object reference
5528 instead of a scalar customer number.
5530 Bill and collect options should probably be passed as references instead of a
5533 There should probably be a configuration file with a list of allowed credit
5536 No multiple currency support (probably a larger project than just this module).
5538 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5540 Birthdates rely on negative epoch values.
5542 The payby for card/check batches is broken. With mixed batching, bad
5545 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5549 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5550 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5551 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.