5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6 FS::cust_main::NationalID
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
12 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
17 use vars qw( $DEBUG $me $conf
20 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
31 use Digest::MD5 qw(md5_base64);
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
37 use FS::UID qw( getotaker dbh driver_name );
38 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
39 use FS::Misc qw( generate_email send_email generate_ps do_print );
40 use FS::Msgcat qw(gettext);
47 use FS::cust_bill_void;
48 use FS::legacy_cust_bill;
50 use FS::cust_pay_pending;
51 use FS::cust_pay_void;
52 use FS::cust_pay_batch;
55 use FS::part_referral;
56 use FS::cust_main_county;
57 use FS::cust_location;
59 use FS::cust_main_exemption;
60 use FS::cust_tax_adjustment;
61 use FS::cust_tax_location;
63 use FS::cust_main_invoice;
65 use FS::prepay_credit;
71 use FS::payment_gateway;
72 use FS::agent_payment_gateway;
74 use FS::cust_main_note;
75 use FS::cust_attachment;
78 use FS::upgrade_journal;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 $me = '[FS::cust_main]';
87 $ignore_expired_card = 0;
88 $ignore_banned_card = 0;
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub {
99 install_callback FS::UID sub {
100 $conf = new FS::Conf;
101 #yes, need it for stuff below (prolly should be cached)
106 my ( $hashref, $cache ) = @_;
107 if ( exists $hashref->{'pkgnum'} ) {
108 #@{ $self->{'_pkgnum'} } = ();
109 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110 $self->{'_pkgnum'} = $subcache;
111 #push @{ $self->{'_pkgnum'} },
112 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
118 FS::cust_main - Object methods for cust_main records
124 $record = new FS::cust_main \%hash;
125 $record = new FS::cust_main { 'column' => 'value' };
127 $error = $record->insert;
129 $error = $new_record->replace($old_record);
131 $error = $record->delete;
133 $error = $record->check;
135 @cust_pkg = $record->all_pkgs;
137 @cust_pkg = $record->ncancelled_pkgs;
139 @cust_pkg = $record->suspended_pkgs;
141 $error = $record->bill;
142 $error = $record->bill %options;
143 $error = $record->bill 'time' => $time;
145 $error = $record->collect;
146 $error = $record->collect %options;
147 $error = $record->collect 'invoice_time' => $time,
152 An FS::cust_main object represents a customer. FS::cust_main inherits from
153 FS::Record. The following fields are currently supported:
159 Primary key (assigned automatically for new customers)
163 Agent (see L<FS::agent>)
167 Advertising source (see L<FS::part_referral>)
179 Cocial security number (optional)
203 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
207 Payment Information (See L<FS::payinfo_Mixin> for data format)
211 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
215 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
219 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
223 Start date month (maestro/solo cards only)
227 Start date year (maestro/solo cards only)
231 Issue number (maestro/solo cards only)
235 Name on card or billing name
239 IP address from which payment information was received
243 Tax exempt, empty or `Y'
247 Order taker (see L<FS::access_user>)
253 =item referral_custnum
255 Referring customer number
259 Enable individual CDR spooling, empty or `Y'
263 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
267 Discourage individual CDR printing, empty or `Y'
271 Allow self-service editing of ticket subjects, empty or 'Y'
273 =item calling_list_exempt
275 Do not call, empty or 'Y'
277 =item invoice_ship_address
279 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
289 Creates a new customer. To add the customer to the database, see L<"insert">.
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to. You can ask the object for a copy with the I<hash> method.
296 sub table { 'cust_main'; }
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
300 Adds this customer to the database. If there is an error, returns the error,
301 otherwise returns false.
303 Usually the customer's location will not yet exist in the database, and
304 the C<bill_location> and C<ship_location> pseudo-fields must be set to
305 uninserted L<FS::cust_location> objects. These will be inserted and linked
306 (in both directions) to the new customer record. If they're references
307 to the same object, they will become the same location.
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back. Passing an empty
312 hash reference is equivalent to not supplying this parameter. There should be
313 a better explanation of this, but until then, here's an example:
316 tie %hash, 'Tie::RefHash'; #this part is important
318 $cust_pkg => [ $svc_acct ],
321 $cust_main->insert( \%hash );
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">). Errors return as
325 expected and rollback the entire transaction; it is not necessary to call
326 check_invoicing_list first. The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct. Here's an example:
330 $cust_main->insert( {}, [ $email, 'POST' ] );
332 Currently available options are: I<depend_jobnum>, I<noexport>,
333 I<tax_exemption> and I<prospectnum>.
335 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
336 on the supplied jobnum (they will not run until the specific job completes).
337 This can be used to defer provisioning until some action completes (such
338 as running the customer's credit card successfully).
340 The I<noexport> option is deprecated. If I<noexport> is set true, no
341 provisioning jobs (exports) are scheduled. (You can schedule them later with
342 the B<reexport> method.)
344 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
345 of tax names and exemption numbers. FS::cust_main_exemption records will be
346 created and inserted.
348 If I<prospectnum> is set, moves contacts and locations from that prospect.
354 my $cust_pkgs = @_ ? shift : {};
355 my $invoicing_list = @_ ? shift : '';
357 warn "$me insert called with options ".
358 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
361 local $SIG{HUP} = 'IGNORE';
362 local $SIG{INT} = 'IGNORE';
363 local $SIG{QUIT} = 'IGNORE';
364 local $SIG{TERM} = 'IGNORE';
365 local $SIG{TSTP} = 'IGNORE';
366 local $SIG{PIPE} = 'IGNORE';
368 my $oldAutoCommit = $FS::UID::AutoCommit;
369 local $FS::UID::AutoCommit = 0;
372 my $prepay_identifier = '';
373 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
375 if ( $self->payby eq 'PREPAY' ) {
377 $self->payby('BILL');
378 $prepay_identifier = $self->payinfo;
381 warn " looking up prepaid card $prepay_identifier\n"
384 my $error = $self->get_prepay( $prepay_identifier,
385 'amount_ref' => \$amount,
386 'seconds_ref' => \$seconds,
387 'upbytes_ref' => \$upbytes,
388 'downbytes_ref' => \$downbytes,
389 'totalbytes_ref' => \$totalbytes,
392 $dbh->rollback if $oldAutoCommit;
393 #return "error applying prepaid card (transaction rolled back): $error";
397 $payby = 'PREP' if $amount;
399 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
402 $self->payby('BILL');
403 $amount = $self->paid;
408 foreach my $l (qw(bill_location ship_location)) {
410 my $loc = delete $self->hashref->{$l} or return "$l not set";
412 if ( !$loc->locationnum ) {
413 # warn the location that we're going to insert it with no custnum
414 $loc->set(custnum_pending => 1);
415 warn " inserting $l\n"
417 my $error = $loc->insert;
419 $dbh->rollback if $oldAutoCommit;
420 my $label = $l eq 'ship_location' ? 'service' : 'billing';
421 return "$error (in $label location)";
424 } elsif ( $loc->prospectnum ) {
426 $loc->prospectnum('');
427 $loc->set(custnum_pending => 1);
428 my $error = $loc->replace;
430 $dbh->rollback if $oldAutoCommit;
431 my $label = $l eq 'ship_location' ? 'service' : 'billing';
432 return "$error (moving $label location)";
435 } elsif ( ($loc->custnum || 0) > 0 ) {
436 # then it somehow belongs to another customer--shouldn't happen
437 $dbh->rollback if $oldAutoCommit;
438 return "$l belongs to customer ".$loc->custnum;
440 # else it already belongs to this customer
441 # (happens when ship_location is identical to bill_location)
443 $self->set($l.'num', $loc->locationnum);
445 if ( $self->get($l.'num') eq '' ) {
446 $dbh->rollback if $oldAutoCommit;
451 warn " inserting $self\n"
454 $self->signupdate(time) unless $self->signupdate;
456 $self->auto_agent_custid()
457 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
459 my $error = $self->SUPER::insert;
461 $dbh->rollback if $oldAutoCommit;
462 #return "inserting cust_main record (transaction rolled back): $error";
466 # now set cust_location.custnum
467 foreach my $l (qw(bill_location ship_location)) {
468 warn " setting $l.custnum\n"
471 unless ( $loc->custnum ) {
472 $loc->set(custnum => $self->custnum);
473 $error ||= $loc->replace;
477 $dbh->rollback if $oldAutoCommit;
478 return "error setting $l custnum: $error";
482 warn " setting invoicing list\n"
485 if ( $invoicing_list ) {
486 $error = $self->check_invoicing_list( $invoicing_list );
488 $dbh->rollback if $oldAutoCommit;
489 #return "checking invoicing_list (transaction rolled back): $error";
492 $self->invoicing_list( $invoicing_list );
495 warn " setting customer tags\n"
498 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
499 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
500 'custnum' => $self->custnum };
501 my $error = $cust_tag->insert;
503 $dbh->rollback if $oldAutoCommit;
508 my $prospectnum = delete $options{'prospectnum'};
509 if ( $prospectnum ) {
511 warn " moving contacts and locations from prospect $prospectnum\n"
515 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
516 unless ( $prospect_main ) {
517 $dbh->rollback if $oldAutoCommit;
518 return "Unknown prospectnum $prospectnum";
520 $prospect_main->custnum($self->custnum);
521 $prospect_main->disabled('Y');
522 my $error = $prospect_main->replace;
524 $dbh->rollback if $oldAutoCommit;
528 my @contact = $prospect_main->contact;
529 my @cust_location = $prospect_main->cust_location;
530 my @qual = $prospect_main->qual;
532 foreach my $r ( @contact, @cust_location, @qual ) {
534 $r->custnum($self->custnum);
535 my $error = $r->replace;
537 $dbh->rollback if $oldAutoCommit;
544 warn " setting contacts\n"
547 if ( my $contact = delete $options{'contact'} ) {
549 foreach my $c ( @$contact ) {
550 $c->custnum($self->custnum);
551 my $error = $c->insert;
553 $dbh->rollback if $oldAutoCommit;
559 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
561 my $error = $self->process_o2m( 'table' => 'contact',
562 'fields' => FS::contact->cgi_contact_fields,
563 'params' => $contact_params,
566 $dbh->rollback if $oldAutoCommit;
571 warn " setting cust_main_exemption\n"
574 my $tax_exemption = delete $options{'tax_exemption'};
575 if ( $tax_exemption ) {
577 $tax_exemption = { map { $_ => '' } @$tax_exemption }
578 if ref($tax_exemption) eq 'ARRAY';
580 foreach my $taxname ( keys %$tax_exemption ) {
581 my $cust_main_exemption = new FS::cust_main_exemption {
582 'custnum' => $self->custnum,
583 'taxname' => $taxname,
584 'exempt_number' => $tax_exemption->{$taxname},
586 my $error = $cust_main_exemption->insert;
588 $dbh->rollback if $oldAutoCommit;
589 return "inserting cust_main_exemption (transaction rolled back): $error";
594 warn " ordering packages\n"
597 $error = $self->order_pkgs( $cust_pkgs,
599 'seconds_ref' => \$seconds,
600 'upbytes_ref' => \$upbytes,
601 'downbytes_ref' => \$downbytes,
602 'totalbytes_ref' => \$totalbytes,
605 $dbh->rollback if $oldAutoCommit;
610 $dbh->rollback if $oldAutoCommit;
611 return "No svc_acct record to apply pre-paid time";
613 if ( $upbytes || $downbytes || $totalbytes ) {
614 $dbh->rollback if $oldAutoCommit;
615 return "No svc_acct record to apply pre-paid data";
619 warn " inserting initial $payby payment of $amount\n"
621 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
623 $dbh->rollback if $oldAutoCommit;
624 return "inserting payment (transaction rolled back): $error";
628 unless ( $import || $skip_fuzzyfiles ) {
629 warn " queueing fuzzyfiles update\n"
631 $error = $self->queue_fuzzyfiles_update;
633 $dbh->rollback if $oldAutoCommit;
634 return "updating fuzzy search cache: $error";
638 # FS::geocode_Mixin::after_insert or something?
639 if ( $conf->config('tax_district_method') and !$import ) {
640 # if anything non-empty, try to look it up
641 my $queue = new FS::queue {
642 'job' => 'FS::geocode_Mixin::process_district_update',
643 'custnum' => $self->custnum,
645 my $error = $queue->insert( ref($self), $self->custnum );
647 $dbh->rollback if $oldAutoCommit;
648 return "queueing tax district update: $error";
653 warn " exporting\n" if $DEBUG > 1;
655 my $export_args = $options{'export_args'} || [];
658 map qsearch( 'part_export', {exportnum=>$_} ),
659 $conf->config('cust_main-exports'); #, $agentnum
661 foreach my $part_export ( @part_export ) {
662 my $error = $part_export->export_insert($self, @$export_args);
664 $dbh->rollback if $oldAutoCommit;
665 return "exporting to ". $part_export->exporttype.
666 " (transaction rolled back): $error";
670 #foreach my $depend_jobnum ( @$depend_jobnums ) {
671 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
673 # foreach my $jobnum ( @jobnums ) {
674 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
675 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
677 # my $error = $queue->depend_insert($depend_jobnum);
679 # $dbh->rollback if $oldAutoCommit;
680 # return "error queuing job dependancy: $error";
687 #if ( exists $options{'jobnums'} ) {
688 # push @{ $options{'jobnums'} }, @jobnums;
691 warn " insert complete; committing transaction\n"
694 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
699 use File::CounterFile;
700 sub auto_agent_custid {
703 my $format = $conf->config('cust_main-auto_agent_custid');
705 if ( $format eq '1YMMXXXXXXXX' ) {
707 my $counter = new File::CounterFile 'cust_main.agent_custid';
710 my $ym = 100000000000 + time2str('%y%m00000000', time);
711 if ( $ym > $counter->value ) {
712 $counter->{'value'} = $agent_custid = $ym;
713 $counter->{'updated'} = 1;
715 $agent_custid = $counter->inc;
721 die "Unknown cust_main-auto_agent_custid format: $format";
724 $self->agent_custid($agent_custid);
728 =item PACKAGE METHODS
730 Documentation on customer package methods has been moved to
731 L<FS::cust_main::Packages>.
733 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
735 Recharges this (existing) customer with the specified prepaid card (see
736 L<FS::prepay_credit>), specified either by I<identifier> or as an
737 FS::prepay_credit object. If there is an error, returns the error, otherwise
740 Optionally, five scalar references can be passed as well. They will have their
741 values filled in with the amount, number of seconds, and number of upload,
742 download, and total bytes applied by this prepaid card.
746 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
747 #the only place that uses these args
748 sub recharge_prepay {
749 my( $self, $prepay_credit, $amountref, $secondsref,
750 $upbytesref, $downbytesref, $totalbytesref ) = @_;
752 local $SIG{HUP} = 'IGNORE';
753 local $SIG{INT} = 'IGNORE';
754 local $SIG{QUIT} = 'IGNORE';
755 local $SIG{TERM} = 'IGNORE';
756 local $SIG{TSTP} = 'IGNORE';
757 local $SIG{PIPE} = 'IGNORE';
759 my $oldAutoCommit = $FS::UID::AutoCommit;
760 local $FS::UID::AutoCommit = 0;
763 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
765 my $error = $self->get_prepay( $prepay_credit,
766 'amount_ref' => \$amount,
767 'seconds_ref' => \$seconds,
768 'upbytes_ref' => \$upbytes,
769 'downbytes_ref' => \$downbytes,
770 'totalbytes_ref' => \$totalbytes,
772 || $self->increment_seconds($seconds)
773 || $self->increment_upbytes($upbytes)
774 || $self->increment_downbytes($downbytes)
775 || $self->increment_totalbytes($totalbytes)
776 || $self->insert_cust_pay_prepay( $amount,
778 ? $prepay_credit->identifier
783 $dbh->rollback if $oldAutoCommit;
787 if ( defined($amountref) ) { $$amountref = $amount; }
788 if ( defined($secondsref) ) { $$secondsref = $seconds; }
789 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
790 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
791 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
793 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
798 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
800 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
801 specified either by I<identifier> or as an FS::prepay_credit object.
803 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
804 incremented by the values of the prepaid card.
806 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
807 check or set this customer's I<agentnum>.
809 If there is an error, returns the error, otherwise returns false.
815 my( $self, $prepay_credit, %opt ) = @_;
817 local $SIG{HUP} = 'IGNORE';
818 local $SIG{INT} = 'IGNORE';
819 local $SIG{QUIT} = 'IGNORE';
820 local $SIG{TERM} = 'IGNORE';
821 local $SIG{TSTP} = 'IGNORE';
822 local $SIG{PIPE} = 'IGNORE';
824 my $oldAutoCommit = $FS::UID::AutoCommit;
825 local $FS::UID::AutoCommit = 0;
828 unless ( ref($prepay_credit) ) {
830 my $identifier = $prepay_credit;
832 $prepay_credit = qsearchs(
834 { 'identifier' => $identifier },
839 unless ( $prepay_credit ) {
840 $dbh->rollback if $oldAutoCommit;
841 return "Invalid prepaid card: ". $identifier;
846 if ( $prepay_credit->agentnum ) {
847 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
848 $dbh->rollback if $oldAutoCommit;
849 return "prepaid card not valid for agent ". $self->agentnum;
851 $self->agentnum($prepay_credit->agentnum);
854 my $error = $prepay_credit->delete;
856 $dbh->rollback if $oldAutoCommit;
857 return "removing prepay_credit (transaction rolled back): $error";
860 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
861 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
863 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
868 =item increment_upbytes SECONDS
870 Updates this customer's single or primary account (see L<FS::svc_acct>) by
871 the specified number of upbytes. If there is an error, returns the error,
872 otherwise returns false.
876 sub increment_upbytes {
877 _increment_column( shift, 'upbytes', @_);
880 =item increment_downbytes SECONDS
882 Updates this customer's single or primary account (see L<FS::svc_acct>) by
883 the specified number of downbytes. If there is an error, returns the error,
884 otherwise returns false.
888 sub increment_downbytes {
889 _increment_column( shift, 'downbytes', @_);
892 =item increment_totalbytes SECONDS
894 Updates this customer's single or primary account (see L<FS::svc_acct>) by
895 the specified number of totalbytes. If there is an error, returns the error,
896 otherwise returns false.
900 sub increment_totalbytes {
901 _increment_column( shift, 'totalbytes', @_);
904 =item increment_seconds SECONDS
906 Updates this customer's single or primary account (see L<FS::svc_acct>) by
907 the specified number of seconds. If there is an error, returns the error,
908 otherwise returns false.
912 sub increment_seconds {
913 _increment_column( shift, 'seconds', @_);
916 =item _increment_column AMOUNT
918 Updates this customer's single or primary account (see L<FS::svc_acct>) by
919 the specified number of seconds or bytes. If there is an error, returns
920 the error, otherwise returns false.
924 sub _increment_column {
925 my( $self, $column, $amount ) = @_;
926 warn "$me increment_column called: $column, $amount\n"
929 return '' unless $amount;
931 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
932 $self->ncancelled_pkgs;
935 return 'No packages with primary or single services found'.
936 ' to apply pre-paid time';
937 } elsif ( scalar(@cust_pkg) > 1 ) {
938 #maybe have a way to specify the package/account?
939 return 'Multiple packages found to apply pre-paid time';
942 my $cust_pkg = $cust_pkg[0];
943 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
947 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
950 return 'No account found to apply pre-paid time';
951 } elsif ( scalar(@cust_svc) > 1 ) {
952 return 'Multiple accounts found to apply pre-paid time';
955 my $svc_acct = $cust_svc[0]->svc_x;
956 warn " found service svcnum ". $svc_acct->pkgnum.
957 ' ('. $svc_acct->email. ")\n"
960 $column = "increment_$column";
961 $svc_acct->$column($amount);
965 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
967 Inserts a prepayment in the specified amount for this customer. An optional
968 second argument can specify the prepayment identifier for tracking purposes.
969 If there is an error, returns the error, otherwise returns false.
973 sub insert_cust_pay_prepay {
974 shift->insert_cust_pay('PREP', @_);
977 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
979 Inserts a cash payment in the specified amount for this customer. An optional
980 second argument can specify the payment identifier for tracking purposes.
981 If there is an error, returns the error, otherwise returns false.
985 sub insert_cust_pay_cash {
986 shift->insert_cust_pay('CASH', @_);
989 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
991 Inserts a Western Union payment in the specified amount for this customer. An
992 optional second argument can specify the prepayment identifier for tracking
993 purposes. If there is an error, returns the error, otherwise returns false.
997 sub insert_cust_pay_west {
998 shift->insert_cust_pay('WEST', @_);
1001 sub insert_cust_pay {
1002 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1003 my $payinfo = scalar(@_) ? shift : '';
1005 my $cust_pay = new FS::cust_pay {
1006 'custnum' => $self->custnum,
1007 'paid' => sprintf('%.2f', $amount),
1008 #'_date' => #date the prepaid card was purchased???
1010 'payinfo' => $payinfo,
1018 This method is deprecated. See the I<depend_jobnum> option to the insert and
1019 order_pkgs methods for a better way to defer provisioning.
1021 Re-schedules all exports by calling the B<reexport> method of all associated
1022 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1023 otherwise returns false.
1030 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1031 "use the depend_jobnum option to insert or order_pkgs to delay export";
1033 local $SIG{HUP} = 'IGNORE';
1034 local $SIG{INT} = 'IGNORE';
1035 local $SIG{QUIT} = 'IGNORE';
1036 local $SIG{TERM} = 'IGNORE';
1037 local $SIG{TSTP} = 'IGNORE';
1038 local $SIG{PIPE} = 'IGNORE';
1040 my $oldAutoCommit = $FS::UID::AutoCommit;
1041 local $FS::UID::AutoCommit = 0;
1044 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1045 my $error = $cust_pkg->reexport;
1047 $dbh->rollback if $oldAutoCommit;
1052 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1057 =item delete [ OPTION => VALUE ... ]
1059 This deletes the customer. If there is an error, returns the error, otherwise
1062 This will completely remove all traces of the customer record. This is not
1063 what you want when a customer cancels service; for that, cancel all of the
1064 customer's packages (see L</cancel>).
1066 If the customer has any uncancelled packages, you need to pass a new (valid)
1067 customer number for those packages to be transferred to, as the "new_customer"
1068 option. Cancelled packages will be deleted. Did I mention that this is NOT
1069 what you want when a customer cancels service and that you really should be
1070 looking at L<FS::cust_pkg/cancel>?
1072 You can't delete a customer with invoices (see L<FS::cust_bill>),
1073 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1074 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1075 set the "delete_financials" option to a true value.
1080 my( $self, %opt ) = @_;
1082 local $SIG{HUP} = 'IGNORE';
1083 local $SIG{INT} = 'IGNORE';
1084 local $SIG{QUIT} = 'IGNORE';
1085 local $SIG{TERM} = 'IGNORE';
1086 local $SIG{TSTP} = 'IGNORE';
1087 local $SIG{PIPE} = 'IGNORE';
1089 my $oldAutoCommit = $FS::UID::AutoCommit;
1090 local $FS::UID::AutoCommit = 0;
1093 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1094 $dbh->rollback if $oldAutoCommit;
1095 return "Can't delete a master agent customer";
1098 #use FS::access_user
1099 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1100 $dbh->rollback if $oldAutoCommit;
1101 return "Can't delete a master employee customer";
1104 tie my %financial_tables, 'Tie::IxHash',
1105 'cust_bill' => 'invoices',
1106 'cust_statement' => 'statements',
1107 'cust_credit' => 'credits',
1108 'cust_pay' => 'payments',
1109 'cust_refund' => 'refunds',
1112 foreach my $table ( keys %financial_tables ) {
1114 my @records = $self->$table();
1116 if ( @records && ! $opt{'delete_financials'} ) {
1117 $dbh->rollback if $oldAutoCommit;
1118 return "Can't delete a customer with ". $financial_tables{$table};
1121 foreach my $record ( @records ) {
1122 my $error = $record->delete;
1124 $dbh->rollback if $oldAutoCommit;
1125 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1131 my @cust_pkg = $self->ncancelled_pkgs;
1133 my $new_custnum = $opt{'new_custnum'};
1134 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1135 $dbh->rollback if $oldAutoCommit;
1136 return "Invalid new customer number: $new_custnum";
1138 foreach my $cust_pkg ( @cust_pkg ) {
1139 my %hash = $cust_pkg->hash;
1140 $hash{'custnum'} = $new_custnum;
1141 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1142 my $error = $new_cust_pkg->replace($cust_pkg,
1143 options => { $cust_pkg->options },
1146 $dbh->rollback if $oldAutoCommit;
1151 my @cancelled_cust_pkg = $self->all_pkgs;
1152 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1153 my $error = $cust_pkg->delete;
1155 $dbh->rollback if $oldAutoCommit;
1160 #cust_tax_adjustment in financials?
1161 #cust_pay_pending? ouch
1163 foreach my $table (qw(
1164 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1165 cust_location cust_main_note cust_tax_adjustment
1166 cust_pay_void cust_pay_batch queue cust_tax_exempt
1168 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1169 my $error = $record->delete;
1171 $dbh->rollback if $oldAutoCommit;
1177 my $sth = $dbh->prepare(
1178 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1180 my $errstr = $dbh->errstr;
1181 $dbh->rollback if $oldAutoCommit;
1184 $sth->execute($self->custnum) or do {
1185 my $errstr = $sth->errstr;
1186 $dbh->rollback if $oldAutoCommit;
1192 my $ticket_dbh = '';
1193 if ($conf->config('ticket_system') eq 'RT_Internal') {
1195 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1196 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1197 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1198 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1201 if ( $ticket_dbh ) {
1203 my $ticket_sth = $ticket_dbh->prepare(
1204 'DELETE FROM Links WHERE Target = ?'
1206 my $errstr = $ticket_dbh->errstr;
1207 $dbh->rollback if $oldAutoCommit;
1210 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1212 my $errstr = $ticket_sth->errstr;
1213 $dbh->rollback if $oldAutoCommit;
1217 #check and see if the customer is the only link on the ticket, and
1218 #if so, set the ticket to deleted status in RT?
1219 #maybe someday, for now this will at least fix tickets not displaying
1223 #delete the customer record
1225 my $error = $self->SUPER::delete;
1227 $dbh->rollback if $oldAutoCommit;
1231 # cust_main exports!
1233 #my $export_args = $options{'export_args'} || [];
1236 map qsearch( 'part_export', {exportnum=>$_} ),
1237 $conf->config('cust_main-exports'); #, $agentnum
1239 foreach my $part_export ( @part_export ) {
1240 my $error = $part_export->export_delete( $self ); #, @$export_args);
1242 $dbh->rollback if $oldAutoCommit;
1243 return "exporting to ". $part_export->exporttype.
1244 " (transaction rolled back): $error";
1248 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1253 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1255 This merges this customer into the provided new custnum, and then deletes the
1256 customer. If there is an error, returns the error, otherwise returns false.
1258 The source customer's name, company name, phone numbers, agent,
1259 referring customer, customer class, advertising source, order taker, and
1260 billing information (except balance) are discarded.
1262 All packages are moved to the target customer. Packages with package locations
1263 are preserved. Packages without package locations are moved to a new package
1264 location with the source customer's service/shipping address.
1266 All invoices, statements, payments, credits and refunds are moved to the target
1267 customer. The source customer's balance is added to the target customer.
1269 All notes, attachments, tickets and customer tags are moved to the target
1272 Change history is not currently moved.
1277 my( $self, $new_custnum, %opt ) = @_;
1279 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1281 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1282 or return "Invalid new customer number: $new_custnum";
1284 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1285 if $self->agentnum != $new_cust_main->agentnum
1286 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1288 local $SIG{HUP} = 'IGNORE';
1289 local $SIG{INT} = 'IGNORE';
1290 local $SIG{QUIT} = 'IGNORE';
1291 local $SIG{TERM} = 'IGNORE';
1292 local $SIG{TSTP} = 'IGNORE';
1293 local $SIG{PIPE} = 'IGNORE';
1295 my $oldAutoCommit = $FS::UID::AutoCommit;
1296 local $FS::UID::AutoCommit = 0;
1299 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1300 $dbh->rollback if $oldAutoCommit;
1301 return "Can't merge a master agent customer";
1304 #use FS::access_user
1305 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1306 $dbh->rollback if $oldAutoCommit;
1307 return "Can't merge a master employee customer";
1310 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1311 'status' => { op=>'!=', value=>'done' },
1315 $dbh->rollback if $oldAutoCommit;
1316 return "Can't merge a customer with pending payments";
1319 tie my %financial_tables, 'Tie::IxHash',
1320 'cust_bill' => 'invoices',
1321 'cust_bill_void' => 'voided invoices',
1322 'cust_statement' => 'statements',
1323 'cust_credit' => 'credits',
1324 'cust_credit_void' => 'voided credits',
1325 'cust_pay' => 'payments',
1326 'cust_pay_void' => 'voided payments',
1327 'cust_refund' => 'refunds',
1330 foreach my $table ( keys %financial_tables ) {
1332 my @records = $self->$table();
1334 foreach my $record ( @records ) {
1335 $record->custnum($new_custnum);
1336 my $error = $record->replace;
1338 $dbh->rollback if $oldAutoCommit;
1339 return "Error merging ". $financial_tables{$table}. ": $error\n";
1345 my $name = $self->ship_name; #?
1347 my $locationnum = '';
1348 foreach my $cust_pkg ( $self->all_pkgs ) {
1349 $cust_pkg->custnum($new_custnum);
1351 unless ( $cust_pkg->locationnum ) {
1352 unless ( $locationnum ) {
1353 my $cust_location = new FS::cust_location {
1354 $self->location_hash,
1355 'custnum' => $new_custnum,
1357 my $error = $cust_location->insert;
1359 $dbh->rollback if $oldAutoCommit;
1362 $locationnum = $cust_location->locationnum;
1364 $cust_pkg->locationnum($locationnum);
1367 my $error = $cust_pkg->replace;
1369 $dbh->rollback if $oldAutoCommit;
1373 # add customer (ship) name to svc_phone.phone_name if blank
1374 my @cust_svc = $cust_pkg->cust_svc;
1375 foreach my $cust_svc (@cust_svc) {
1376 my($label, $value, $svcdb) = $cust_svc->label;
1377 next unless $svcdb eq 'svc_phone';
1378 my $svc_phone = $cust_svc->svc_x;
1379 next if $svc_phone->phone_name;
1380 $svc_phone->phone_name($name);
1381 my $error = $svc_phone->replace;
1383 $dbh->rollback if $oldAutoCommit;
1391 # cust_tax_exempt (texas tax exemptions)
1392 # cust_recon (some sort of not-well understood thing for OnPac)
1394 #these are moved over
1395 foreach my $table (qw(
1396 cust_tag cust_location contact cust_attachment cust_main_note
1397 cust_tax_adjustment cust_pay_batch queue
1399 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1400 $record->custnum($new_custnum);
1401 my $error = $record->replace;
1403 $dbh->rollback if $oldAutoCommit;
1409 #these aren't preserved
1410 foreach my $table (qw(
1411 cust_main_exemption cust_main_invoice
1413 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1414 my $error = $record->delete;
1416 $dbh->rollback if $oldAutoCommit;
1423 my $sth = $dbh->prepare(
1424 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1426 my $errstr = $dbh->errstr;
1427 $dbh->rollback if $oldAutoCommit;
1430 $sth->execute($new_custnum, $self->custnum) or do {
1431 my $errstr = $sth->errstr;
1432 $dbh->rollback if $oldAutoCommit;
1438 my $ticket_dbh = '';
1439 if ($conf->config('ticket_system') eq 'RT_Internal') {
1441 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1442 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1443 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1444 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1447 if ( $ticket_dbh ) {
1449 my $ticket_sth = $ticket_dbh->prepare(
1450 'UPDATE Links SET Target = ? WHERE Target = ?'
1452 my $errstr = $ticket_dbh->errstr;
1453 $dbh->rollback if $oldAutoCommit;
1456 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1457 'freeside://freeside/cust_main/'.$self->custnum)
1459 my $errstr = $ticket_sth->errstr;
1460 $dbh->rollback if $oldAutoCommit;
1466 #delete the customer record
1468 my $error = $self->delete;
1470 $dbh->rollback if $oldAutoCommit;
1474 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1479 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1481 Replaces the OLD_RECORD with this one in the database. If there is an error,
1482 returns the error, otherwise returns false.
1484 To change the customer's address, set the pseudo-fields C<bill_location> and
1485 C<ship_location>. The address will still only change if at least one of the
1486 address fields differs from the existing values.
1488 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1489 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1490 expected and rollback the entire transaction; it is not necessary to call
1491 check_invoicing_list first. Here's an example:
1493 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1495 Currently available options are: I<tax_exemption>.
1497 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1498 of tax names and exemption numbers. FS::cust_main_exemption records will be
1499 deleted and inserted as appropriate.
1506 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1508 : $self->replace_old;
1512 warn "$me replace called\n"
1515 my $curuser = $FS::CurrentUser::CurrentUser;
1516 if ( $self->payby eq 'COMP'
1517 && $self->payby ne $old->payby
1518 && ! $curuser->access_right('Complimentary customer')
1521 return "You are not permitted to create complimentary accounts.";
1524 local($ignore_expired_card) = 1
1525 if $old->payby =~ /^(CARD|DCRD)$/
1526 && $self->payby =~ /^(CARD|DCRD)$/
1527 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1529 local($ignore_banned_card) = 1
1530 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1531 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1532 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1534 return "Invoicing locale is required"
1537 && $conf->exists('cust_main-require_locale');
1539 local $SIG{HUP} = 'IGNORE';
1540 local $SIG{INT} = 'IGNORE';
1541 local $SIG{QUIT} = 'IGNORE';
1542 local $SIG{TERM} = 'IGNORE';
1543 local $SIG{TSTP} = 'IGNORE';
1544 local $SIG{PIPE} = 'IGNORE';
1546 my $oldAutoCommit = $FS::UID::AutoCommit;
1547 local $FS::UID::AutoCommit = 0;
1550 for my $l (qw(bill_location ship_location)) {
1551 my $old_loc = $old->$l;
1552 my $new_loc = $self->$l;
1554 # find the existing location if there is one
1555 $new_loc->set('custnum' => $self->custnum);
1556 my $error = $new_loc->find_or_insert;
1558 $dbh->rollback if $oldAutoCommit;
1561 $self->set($l.'num', $new_loc->locationnum);
1564 # replace the customer record
1565 my $error = $self->SUPER::replace($old);
1568 $dbh->rollback if $oldAutoCommit;
1572 # now move packages to the new service location
1573 $self->set('ship_location', ''); #flush cache
1574 if ( $old->ship_locationnum and # should only be null during upgrade...
1575 $old->ship_locationnum != $self->ship_locationnum ) {
1576 $error = $old->ship_location->move_to($self->ship_location);
1578 $dbh->rollback if $oldAutoCommit;
1582 # don't move packages based on the billing location, but
1583 # disable it if it's no longer in use
1584 if ( $old->bill_locationnum and
1585 $old->bill_locationnum != $self->bill_locationnum ) {
1586 $error = $old->bill_location->disable_if_unused;
1588 $dbh->rollback if $oldAutoCommit;
1593 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1594 my $invoicing_list = shift @param;
1595 $error = $self->check_invoicing_list( $invoicing_list );
1597 $dbh->rollback if $oldAutoCommit;
1600 $self->invoicing_list( $invoicing_list );
1603 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1605 #this could be more efficient than deleting and re-inserting, if it matters
1606 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1607 my $error = $cust_tag->delete;
1609 $dbh->rollback if $oldAutoCommit;
1613 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1614 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1615 'custnum' => $self->custnum };
1616 my $error = $cust_tag->insert;
1618 $dbh->rollback if $oldAutoCommit;
1625 my %options = @param;
1627 my $tax_exemption = delete $options{'tax_exemption'};
1628 if ( $tax_exemption ) {
1630 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1631 if ref($tax_exemption) eq 'ARRAY';
1633 my %cust_main_exemption =
1634 map { $_->taxname => $_ }
1635 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1637 foreach my $taxname ( keys %$tax_exemption ) {
1639 if ( $cust_main_exemption{$taxname} &&
1640 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1643 delete $cust_main_exemption{$taxname};
1647 my $cust_main_exemption = new FS::cust_main_exemption {
1648 'custnum' => $self->custnum,
1649 'taxname' => $taxname,
1650 'exempt_number' => $tax_exemption->{$taxname},
1652 my $error = $cust_main_exemption->insert;
1654 $dbh->rollback if $oldAutoCommit;
1655 return "inserting cust_main_exemption (transaction rolled back): $error";
1659 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1660 my $error = $cust_main_exemption->delete;
1662 $dbh->rollback if $oldAutoCommit;
1663 return "deleting cust_main_exemption (transaction rolled back): $error";
1669 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1670 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1671 && $self->get('payinfo') !~ /^99\d{14}$/
1673 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1678 # card/check/lec info has changed, want to retry realtime_ invoice events
1679 my $error = $self->retry_realtime;
1681 $dbh->rollback if $oldAutoCommit;
1686 unless ( $import || $skip_fuzzyfiles ) {
1687 $error = $self->queue_fuzzyfiles_update;
1689 $dbh->rollback if $oldAutoCommit;
1690 return "updating fuzzy search cache: $error";
1694 # tax district update in cust_location
1696 # cust_main exports!
1698 my $export_args = $options{'export_args'} || [];
1701 map qsearch( 'part_export', {exportnum=>$_} ),
1702 $conf->config('cust_main-exports'); #, $agentnum
1704 foreach my $part_export ( @part_export ) {
1705 my $error = $part_export->export_replace( $self, $old, @$export_args);
1707 $dbh->rollback if $oldAutoCommit;
1708 return "exporting to ". $part_export->exporttype.
1709 " (transaction rolled back): $error";
1713 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1718 =item queue_fuzzyfiles_update
1720 Used by insert & replace to update the fuzzy search cache
1724 use FS::cust_main::Search;
1725 sub queue_fuzzyfiles_update {
1728 local $SIG{HUP} = 'IGNORE';
1729 local $SIG{INT} = 'IGNORE';
1730 local $SIG{QUIT} = 'IGNORE';
1731 local $SIG{TERM} = 'IGNORE';
1732 local $SIG{TSTP} = 'IGNORE';
1733 local $SIG{PIPE} = 'IGNORE';
1735 my $oldAutoCommit = $FS::UID::AutoCommit;
1736 local $FS::UID::AutoCommit = 0;
1739 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1740 my $queue = new FS::queue {
1741 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1743 my @args = "cust_main.$field", $self->get($field);
1744 my $error = $queue->insert( @args );
1746 $dbh->rollback if $oldAutoCommit;
1747 return "queueing job (transaction rolled back): $error";
1751 my @locations = $self->bill_location;
1752 push @locations, $self->ship_location if $self->has_ship_address;
1753 foreach my $location (@locations) {
1754 my $queue = new FS::queue {
1755 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1757 my @args = 'cust_location.address1', $location->address1;
1758 my $error = $queue->insert( @args );
1760 $dbh->rollback if $oldAutoCommit;
1761 return "queueing job (transaction rolled back): $error";
1765 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1772 Checks all fields to make sure this is a valid customer record. If there is
1773 an error, returns the error, otherwise returns false. Called by the insert
1774 and replace methods.
1781 warn "$me check BEFORE: \n". $self->_dump
1785 $self->ut_numbern('custnum')
1786 || $self->ut_number('agentnum')
1787 || $self->ut_textn('agent_custid')
1788 || $self->ut_number('refnum')
1789 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1790 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1791 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1792 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1793 || $self->ut_textn('custbatch')
1794 || $self->ut_name('last')
1795 || $self->ut_name('first')
1796 || $self->ut_snumbern('signupdate')
1797 || $self->ut_snumbern('birthdate')
1798 || $self->ut_namen('spouse_last')
1799 || $self->ut_namen('spouse_first')
1800 || $self->ut_snumbern('spouse_birthdate')
1801 || $self->ut_snumbern('anniversary_date')
1802 || $self->ut_textn('company')
1803 || $self->ut_textn('ship_company')
1804 || $self->ut_anything('comments')
1805 || $self->ut_numbern('referral_custnum')
1806 || $self->ut_textn('stateid')
1807 || $self->ut_textn('stateid_state')
1808 || $self->ut_textn('invoice_terms')
1809 || $self->ut_floatn('cdr_termination_percentage')
1810 || $self->ut_floatn('credit_limit')
1811 || $self->ut_numbern('billday')
1812 || $self->ut_numbern('prorate_day')
1813 || $self->ut_flag('edit_subject')
1814 || $self->ut_flag('calling_list_exempt')
1815 || $self->ut_flag('invoice_noemail')
1816 || $self->ut_flag('message_noemail')
1817 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1818 || $self->ut_flag('invoice_ship_address')
1821 foreach (qw(company ship_company)) {
1822 my $company = $self->get($_);
1823 $company =~ s/^\s+//;
1824 $company =~ s/\s+$//;
1825 $company =~ s/\s+/ /g;
1826 $self->set($_, $company);
1829 #barf. need message catalogs. i18n. etc.
1830 $error .= "Please select an advertising source."
1831 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1832 return $error if $error;
1834 return "Unknown agent"
1835 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1837 return "Unknown refnum"
1838 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1840 return "Unknown referring custnum: ". $self->referral_custnum
1841 unless ! $self->referral_custnum
1842 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1844 if ( $self->ss eq '' ) {
1849 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1850 or return "Illegal social security number: ". $self->ss;
1851 $self->ss("$1-$2-$3");
1854 #turn off invoice_ship_address if ship & bill are the same
1855 if ($self->bill_locationnum eq $self->ship_locationnum) {
1856 $self->invoice_ship_address('');
1859 # cust_main_county verification now handled by cust_location check
1862 $self->ut_phonen('daytime', $self->country)
1863 || $self->ut_phonen('night', $self->country)
1864 || $self->ut_phonen('fax', $self->country)
1865 || $self->ut_phonen('mobile', $self->country)
1867 return $error if $error;
1869 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1871 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1874 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1876 : FS::Msgcat::_gettext('daytime');
1877 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1879 : FS::Msgcat::_gettext('night');
1881 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1883 : FS::Msgcat::_gettext('mobile');
1885 return "$daytime_label, $night_label or $mobile_label is required"
1889 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1890 # or return "Illegal payby: ". $self->payby;
1892 FS::payby->can_payby($self->table, $self->payby)
1893 or return "Illegal payby: ". $self->payby;
1895 $error = $self->ut_numbern('paystart_month')
1896 || $self->ut_numbern('paystart_year')
1897 || $self->ut_numbern('payissue')
1898 || $self->ut_textn('paytype')
1900 return $error if $error;
1902 if ( $self->payip eq '' ) {
1905 $error = $self->ut_ip('payip');
1906 return $error if $error;
1909 # If it is encrypted and the private key is not availaible then we can't
1910 # check the credit card.
1911 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1913 # Need some kind of global flag to accept invalid cards, for testing
1915 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1917 my $payinfo = $self->payinfo;
1918 $payinfo =~ s/\D//g;
1919 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1920 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1922 $self->payinfo($payinfo);
1924 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1926 return gettext('unknown_card_type')
1927 if $self->payinfo !~ /^99\d{14}$/ #token
1928 && cardtype($self->payinfo) eq "Unknown";
1930 unless ( $ignore_banned_card ) {
1931 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1933 if ( $ban->bantype eq 'warn' ) {
1934 #or others depending on value of $ban->reason ?
1935 return '_duplicate_card'.
1936 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1937 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1938 ' (ban# '. $ban->bannum. ')'
1939 unless $self->override_ban_warn;
1941 return 'Banned credit card: banned on '.
1942 time2str('%a %h %o at %r', $ban->_date).
1943 ' by '. $ban->otaker.
1944 ' (ban# '. $ban->bannum. ')';
1949 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1950 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1951 $self->paycvv =~ /^(\d{4})$/
1952 or return "CVV2 (CID) for American Express cards is four digits.";
1955 $self->paycvv =~ /^(\d{3})$/
1956 or return "CVV2 (CVC2/CID) is three digits.";
1963 my $cardtype = cardtype($payinfo);
1964 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1966 return "Start date or issue number is required for $cardtype cards"
1967 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1969 return "Start month must be between 1 and 12"
1970 if $self->paystart_month
1971 and $self->paystart_month < 1 || $self->paystart_month > 12;
1973 return "Start year must be 1990 or later"
1974 if $self->paystart_year
1975 and $self->paystart_year < 1990;
1977 return "Issue number must be beween 1 and 99"
1979 and $self->payissue < 1 || $self->payissue > 99;
1982 $self->paystart_month('');
1983 $self->paystart_year('');
1984 $self->payissue('');
1987 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1989 my $payinfo = $self->payinfo;
1990 $payinfo =~ s/[^\d\@\.]//g;
1991 if ( $conf->config('echeck-country') eq 'CA' ) {
1992 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1993 or return 'invalid echeck account@branch.bank';
1994 $payinfo = "$1\@$2.$3";
1995 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1996 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1997 $payinfo = "$1\@$2";
1999 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2000 $payinfo = "$1\@$2";
2002 $self->payinfo($payinfo);
2005 unless ( $ignore_banned_card ) {
2006 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2008 if ( $ban->bantype eq 'warn' ) {
2009 #or others depending on value of $ban->reason ?
2010 return '_duplicate_ach' unless $self->override_ban_warn;
2012 return 'Banned ACH account: banned on '.
2013 time2str('%a %h %o at %r', $ban->_date).
2014 ' by '. $ban->otaker.
2015 ' (ban# '. $ban->bannum. ')';
2020 } elsif ( $self->payby eq 'LECB' ) {
2022 my $payinfo = $self->payinfo;
2023 $payinfo =~ s/\D//g;
2024 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2026 $self->payinfo($payinfo);
2029 } elsif ( $self->payby eq 'BILL' ) {
2031 $error = $self->ut_textn('payinfo');
2032 return "Illegal P.O. number: ". $self->payinfo if $error;
2035 } elsif ( $self->payby eq 'COMP' ) {
2037 my $curuser = $FS::CurrentUser::CurrentUser;
2038 if ( ! $self->custnum
2039 && ! $curuser->access_right('Complimentary customer')
2042 return "You are not permitted to create complimentary accounts."
2045 $error = $self->ut_textn('payinfo');
2046 return "Illegal comp account issuer: ". $self->payinfo if $error;
2049 } elsif ( $self->payby eq 'PREPAY' ) {
2051 my $payinfo = $self->payinfo;
2052 $payinfo =~ s/\W//g; #anything else would just confuse things
2053 $self->payinfo($payinfo);
2054 $error = $self->ut_alpha('payinfo');
2055 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2056 return "Unknown prepayment identifier"
2057 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2062 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2063 return "Expiration date required"
2064 # shouldn't payinfo_check do this?
2065 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2069 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2070 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2071 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2072 ( $m, $y ) = ( $2, "19$1" );
2073 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2074 ( $m, $y ) = ( $3, "20$2" );
2076 return "Illegal expiration date: ". $self->paydate;
2078 $m = sprintf('%02d',$m);
2079 $self->paydate("$y-$m-01");
2080 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2081 return gettext('expired_card')
2083 && !$ignore_expired_card
2084 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2087 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2088 ( ! $conf->exists('require_cardname')
2089 || $self->payby !~ /^(CARD|DCRD)$/ )
2091 $self->payname( $self->first. " ". $self->getfield('last') );
2094 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2095 $self->payname =~ /^([\w \,\.\-\']*)$/
2096 or return gettext('illegal_name'). " payname: ". $self->payname;
2099 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2100 or return gettext('illegal_name'). " payname: ". $self->payname;
2106 return "Please select an invoicing locale"
2109 && $conf->exists('cust_main-require_locale');
2111 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2112 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2116 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2118 warn "$me check AFTER: \n". $self->_dump
2121 $self->SUPER::check;
2126 Additional checks for replace only.
2131 my ($new,$old) = @_;
2132 #preserve old value if global config is set
2133 if ($old && $conf->exists('invoice-ship_address')) {
2134 $new->invoice_ship_address($old->invoice_ship_address);
2141 Returns a list of fields which have ship_ duplicates.
2146 qw( last first company
2148 address1 address2 city county state zip country
2150 daytime night fax mobile
2154 =item has_ship_address
2156 Returns true if this customer record has a separate shipping address.
2160 sub has_ship_address {
2162 $self->bill_locationnum != $self->ship_locationnum;
2167 Returns a list of key/value pairs, with the following keys: address1,
2168 adddress2, city, county, state, zip, country, district, and geocode. The
2169 shipping address is used if present.
2175 $self->ship_location->location_hash;
2180 Returns all locations (see L<FS::cust_location>) for this customer.
2186 qsearch('cust_location', { 'custnum' => $self->custnum,
2187 'prospectnum' => '' } );
2192 Returns all contacts (see L<FS::contact>) for this customer.
2196 #already used :/ sub contact {
2199 qsearch('contact', { 'custnum' => $self->custnum } );
2204 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2205 and L<FS::cust_pkg>) for this customer, except those on hold.
2207 Returns a list: an empty list on success or a list of errors.
2213 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2218 Unsuspends all suspended packages in the on-hold state (those without setup
2219 dates) for this customer.
2225 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2230 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2232 Returns a list: an empty list on success or a list of errors.
2238 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2241 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2243 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2244 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2245 of a list of pkgparts; the hashref has the following keys:
2249 =item pkgparts - listref of pkgparts
2251 =item (other options are passed to the suspend method)
2256 Returns a list: an empty list on success or a list of errors.
2260 sub suspend_if_pkgpart {
2262 my (@pkgparts, %opt);
2263 if (ref($_[0]) eq 'HASH'){
2264 @pkgparts = @{$_[0]{pkgparts}};
2269 grep { $_->suspend(%opt) }
2270 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2271 $self->unsuspended_pkgs;
2274 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2276 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2277 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2278 instead of a list of pkgparts; the hashref has the following keys:
2282 =item pkgparts - listref of pkgparts
2284 =item (other options are passed to the suspend method)
2288 Returns a list: an empty list on success or a list of errors.
2292 sub suspend_unless_pkgpart {
2294 my (@pkgparts, %opt);
2295 if (ref($_[0]) eq 'HASH'){
2296 @pkgparts = @{$_[0]{pkgparts}};
2301 grep { $_->suspend(%opt) }
2302 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2303 $self->unsuspended_pkgs;
2306 =item cancel [ OPTION => VALUE ... ]
2308 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2310 Available options are:
2314 =item quiet - can be set true to supress email cancellation notices.
2316 =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.
2318 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2320 =item nobill - can be set true to skip billing if it might otherwise be done.
2324 Always returns a list: an empty list on success or a list of errors.
2328 # nb that dates are not specified as valid options to this method
2331 my( $self, %opt ) = @_;
2333 warn "$me cancel called on customer ". $self->custnum. " with options ".
2334 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2337 return ( 'access denied' )
2338 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2340 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2342 #should try decryption (we might have the private key)
2343 # and if not maybe queue a job for the server that does?
2344 return ( "Can't (yet) ban encrypted credit cards" )
2345 if $self->is_encrypted($self->payinfo);
2347 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2348 my $error = $ban->insert;
2349 return ( $error ) if $error;
2353 my @pkgs = $self->ncancelled_pkgs;
2355 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2357 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2358 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2362 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2363 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2366 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2369 sub _banned_pay_hashref {
2380 'payby' => $payby2ban{$self->payby},
2381 'payinfo' => $self->payinfo,
2382 #don't ever *search* on reason! #'reason' =>
2386 sub _new_banned_pay_hashref {
2388 my $hr = $self->_banned_pay_hashref;
2389 $hr->{payinfo} = md5_base64($hr->{payinfo});
2395 Returns all notes (see L<FS::cust_main_note>) for this customer.
2400 my($self,$orderby_classnum) = (shift,shift);
2401 my $orderby = "sticky DESC, _date DESC";
2402 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2403 qsearch( 'cust_main_note',
2404 { 'custnum' => $self->custnum },
2406 "ORDER BY $orderby",
2412 Returns the agent (see L<FS::agent>) for this customer.
2418 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2423 Returns the agent name (see L<FS::agent>) for this customer.
2429 $self->agent->agent;
2434 Returns any tags associated with this customer, as FS::cust_tag objects,
2435 or an empty list if there are no tags.
2441 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2446 Returns any tags associated with this customer, as FS::part_tag objects,
2447 or an empty list if there are no tags.
2453 map $_->part_tag, $self->cust_tag;
2459 Returns the customer class, as an FS::cust_class object, or the empty string
2460 if there is no customer class.
2466 if ( $self->classnum ) {
2467 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2475 Returns the customer category name, or the empty string if there is no customer
2482 my $cust_class = $self->cust_class;
2484 ? $cust_class->categoryname
2490 Returns the customer class name, or the empty string if there is no customer
2497 my $cust_class = $self->cust_class;
2499 ? $cust_class->classname
2503 =item BILLING METHODS
2505 Documentation on billing methods has been moved to
2506 L<FS::cust_main::Billing>.
2508 =item REALTIME BILLING METHODS
2510 Documentation on realtime billing methods has been moved to
2511 L<FS::cust_main::Billing_Realtime>.
2515 Removes the I<paycvv> field from the database directly.
2517 If there is an error, returns the error, otherwise returns false.
2523 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2524 or return dbh->errstr;
2525 $sth->execute($self->custnum)
2526 or return $sth->errstr;
2531 =item batch_card OPTION => VALUE...
2533 Adds a payment for this invoice to the pending credit card batch (see
2534 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2535 runs the payment using a realtime gateway.
2537 Options may include:
2539 B<amount>: the amount to be paid; defaults to the customer's balance minus
2540 any payments in transit.
2542 B<payby>: the payment method; defaults to cust_main.payby
2544 B<realtime>: runs this as a realtime payment instead of adding it to a
2547 B<invnum>: sets cust_pay_batch.invnum.
2549 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2550 the billing address for the payment; defaults to the customer's billing
2553 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2554 date, and name; defaults to those fields in cust_main.
2559 my ($self, %options) = @_;
2562 if (exists($options{amount})) {
2563 $amount = $options{amount};
2565 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2567 return '' unless $amount > 0;
2569 my $invnum = delete $options{invnum};
2570 my $payby = $options{payby} || $self->payby; #still dubious
2572 if ($options{'realtime'}) {
2573 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2579 my $oldAutoCommit = $FS::UID::AutoCommit;
2580 local $FS::UID::AutoCommit = 0;
2583 #this needs to handle mysql as well as Pg, like svc_acct.pm
2584 #(make it into a common function if folks need to do batching with mysql)
2585 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2586 or return "Cannot lock pay_batch: " . $dbh->errstr;
2590 'payby' => FS::payby->payby2payment($payby),
2592 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2594 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2596 unless ( $pay_batch ) {
2597 $pay_batch = new FS::pay_batch \%pay_batch;
2598 my $error = $pay_batch->insert;
2600 $dbh->rollback if $oldAutoCommit;
2601 die "error creating new batch: $error\n";
2605 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2606 'batchnum' => $pay_batch->batchnum,
2607 'custnum' => $self->custnum,
2610 foreach (qw( address1 address2 city state zip country latitude longitude
2611 payby payinfo paydate payname ))
2613 $options{$_} = '' unless exists($options{$_});
2616 my $loc = $self->bill_location;
2618 my $cust_pay_batch = new FS::cust_pay_batch ( {
2619 'batchnum' => $pay_batch->batchnum,
2620 'invnum' => $invnum || 0, # is there a better value?
2621 # this field should be
2623 # cust_bill_pay_batch now
2624 'custnum' => $self->custnum,
2625 'last' => $self->getfield('last'),
2626 'first' => $self->getfield('first'),
2627 'address1' => $options{address1} || $loc->address1,
2628 'address2' => $options{address2} || $loc->address2,
2629 'city' => $options{city} || $loc->city,
2630 'state' => $options{state} || $loc->state,
2631 'zip' => $options{zip} || $loc->zip,
2632 'country' => $options{country} || $loc->country,
2633 'payby' => $options{payby} || $self->payby,
2634 'payinfo' => $options{payinfo} || $self->payinfo,
2635 'exp' => $options{paydate} || $self->paydate,
2636 'payname' => $options{payname} || $self->payname,
2637 'amount' => $amount, # consolidating
2640 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2641 if $old_cust_pay_batch;
2644 if ($old_cust_pay_batch) {
2645 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2647 $error = $cust_pay_batch->insert;
2651 $dbh->rollback if $oldAutoCommit;
2655 my $unapplied = $self->total_unapplied_credits
2656 + $self->total_unapplied_payments
2657 + $self->in_transit_payments;
2658 foreach my $cust_bill ($self->open_cust_bill) {
2659 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2660 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2661 'invnum' => $cust_bill->invnum,
2662 'paybatchnum' => $cust_pay_batch->paybatchnum,
2663 'amount' => $cust_bill->owed,
2666 if ($unapplied >= $cust_bill_pay_batch->amount){
2667 $unapplied -= $cust_bill_pay_batch->amount;
2670 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2671 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2673 $error = $cust_bill_pay_batch->insert;
2675 $dbh->rollback if $oldAutoCommit;
2680 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2686 Returns the total owed for this customer on all invoices
2687 (see L<FS::cust_bill/owed>).
2693 $self->total_owed_date(2145859200); #12/31/2037
2696 =item total_owed_date TIME
2698 Returns the total owed for this customer on all invoices with date earlier than
2699 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2700 see L<Time::Local> and L<Date::Parse> for conversion functions.
2704 sub total_owed_date {
2708 my $custnum = $self->custnum;
2710 my $owed_sql = FS::cust_bill->owed_sql;
2713 SELECT SUM($owed_sql) FROM cust_bill
2714 WHERE custnum = $custnum
2718 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2722 =item total_owed_pkgnum PKGNUM
2724 Returns the total owed on all invoices for this customer's specific package
2725 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2729 sub total_owed_pkgnum {
2730 my( $self, $pkgnum ) = @_;
2731 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2734 =item total_owed_date_pkgnum TIME PKGNUM
2736 Returns the total owed for this customer's specific package when using
2737 experimental package balances on all invoices with date earlier than
2738 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2739 see L<Time::Local> and L<Date::Parse> for conversion functions.
2743 sub total_owed_date_pkgnum {
2744 my( $self, $time, $pkgnum ) = @_;
2747 foreach my $cust_bill (
2748 grep { $_->_date <= $time }
2749 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2751 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2753 sprintf( "%.2f", $total_bill );
2759 Returns the total amount of all payments.
2766 $total += $_->paid foreach $self->cust_pay;
2767 sprintf( "%.2f", $total );
2770 =item total_unapplied_credits
2772 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2773 customer. See L<FS::cust_credit/credited>.
2775 =item total_credited
2777 Old name for total_unapplied_credits. Don't use.
2781 sub total_credited {
2782 #carp "total_credited deprecated, use total_unapplied_credits";
2783 shift->total_unapplied_credits(@_);
2786 sub total_unapplied_credits {
2789 my $custnum = $self->custnum;
2791 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2794 SELECT SUM($unapplied_sql) FROM cust_credit
2795 WHERE custnum = $custnum
2798 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2802 =item total_unapplied_credits_pkgnum PKGNUM
2804 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2805 customer. See L<FS::cust_credit/credited>.
2809 sub total_unapplied_credits_pkgnum {
2810 my( $self, $pkgnum ) = @_;
2811 my $total_credit = 0;
2812 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2813 sprintf( "%.2f", $total_credit );
2817 =item total_unapplied_payments
2819 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2820 See L<FS::cust_pay/unapplied>.
2824 sub total_unapplied_payments {
2827 my $custnum = $self->custnum;
2829 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2832 SELECT SUM($unapplied_sql) FROM cust_pay
2833 WHERE custnum = $custnum
2836 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2840 =item total_unapplied_payments_pkgnum PKGNUM
2842 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2843 specific package when using experimental package balances. See
2844 L<FS::cust_pay/unapplied>.
2848 sub total_unapplied_payments_pkgnum {
2849 my( $self, $pkgnum ) = @_;
2850 my $total_unapplied = 0;
2851 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2852 sprintf( "%.2f", $total_unapplied );
2856 =item total_unapplied_refunds
2858 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2859 customer. See L<FS::cust_refund/unapplied>.
2863 sub total_unapplied_refunds {
2865 my $custnum = $self->custnum;
2867 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2870 SELECT SUM($unapplied_sql) FROM cust_refund
2871 WHERE custnum = $custnum
2874 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2880 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2881 total_unapplied_credits minus total_unapplied_payments).
2887 $self->balance_date_range;
2890 =item balance_date TIME
2892 Returns the balance for this customer, only considering invoices with date
2893 earlier than TIME (total_owed_date minus total_credited minus
2894 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2895 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2902 $self->balance_date_range(shift);
2905 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2907 Returns the balance for this customer, optionally considering invoices with
2908 date earlier than START_TIME, and not later than END_TIME
2909 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2911 Times are specified as SQL fragments or numeric
2912 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2913 L<Date::Parse> for conversion functions. The empty string can be passed
2914 to disable that time constraint completely.
2916 Accepts the same options as L<balance_date_sql>:
2920 =item unapplied_date
2922 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)
2926 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2927 time will be ignored. Note that START_TIME and END_TIME only limit the date
2928 range for invoices and I<unapplied> payments, credits, and refunds.
2934 sub balance_date_range {
2936 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2937 ') FROM cust_main WHERE custnum='. $self->custnum;
2938 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2941 =item balance_pkgnum PKGNUM
2943 Returns the balance for this customer's specific package when using
2944 experimental package balances (total_owed plus total_unrefunded, minus
2945 total_unapplied_credits minus total_unapplied_payments)
2949 sub balance_pkgnum {
2950 my( $self, $pkgnum ) = @_;
2953 $self->total_owed_pkgnum($pkgnum)
2954 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2955 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2956 - $self->total_unapplied_credits_pkgnum($pkgnum)
2957 - $self->total_unapplied_payments_pkgnum($pkgnum)
2961 =item in_transit_payments
2963 Returns the total of requests for payments for this customer pending in
2964 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2968 sub in_transit_payments {
2970 my $in_transit_payments = 0;
2971 foreach my $pay_batch ( qsearch('pay_batch', {
2974 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2975 'batchnum' => $pay_batch->batchnum,
2976 'custnum' => $self->custnum,
2978 $in_transit_payments += $cust_pay_batch->amount;
2981 sprintf( "%.2f", $in_transit_payments );
2986 Returns a hash of useful information for making a payment.
2996 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2997 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2998 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3002 For credit card transactions:
3014 For electronic check transactions:
3029 $return{balance} = $self->balance;
3031 $return{payname} = $self->payname
3032 || ( $self->first. ' '. $self->get('last') );
3034 $return{$_} = $self->bill_location->$_
3035 for qw(address1 address2 city state zip);
3037 $return{payby} = $self->payby;
3038 $return{stateid_state} = $self->stateid_state;
3040 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3041 $return{card_type} = cardtype($self->payinfo);
3042 $return{payinfo} = $self->paymask;
3044 @return{'month', 'year'} = $self->paydate_monthyear;
3048 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3049 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3050 $return{payinfo1} = $payinfo1;
3051 $return{payinfo2} = $payinfo2;
3052 $return{paytype} = $self->paytype;
3053 $return{paystate} = $self->paystate;
3057 #doubleclick protection
3059 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3065 =item paydate_monthyear
3067 Returns a two-element list consisting of the month and year of this customer's
3068 paydate (credit card expiration date for CARD customers)
3072 sub paydate_monthyear {
3074 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3076 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3085 Returns the exact time in seconds corresponding to the payment method
3086 expiration date. For CARD/DCRD customers this is the end of the month;
3087 for others (COMP is the only other payby that uses paydate) it's the start.
3088 Returns 0 if the paydate is empty or set to the far future.
3094 my ($month, $year) = $self->paydate_monthyear;
3095 return 0 if !$year or $year >= 2037;
3096 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3098 if ( $month == 13 ) {
3102 return timelocal(0,0,0,1,$month-1,$year) - 1;
3105 return timelocal(0,0,0,1,$month-1,$year);
3109 =item paydate_epoch_sql
3111 Class method. Returns an SQL expression to obtain the payment expiration date
3112 as a number of seconds.
3116 # Special expiration date behavior for non-CARD/DCRD customers has been
3117 # carefully preserved. Do we really use that?
3118 sub paydate_epoch_sql {
3120 my $table = shift || 'cust_main';
3121 my ($case1, $case2);
3122 if ( driver_name eq 'Pg' ) {
3123 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3124 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3126 elsif ( lc(driver_name) eq 'mysql' ) {
3127 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3128 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3131 return "CASE WHEN $table.payby IN('CARD','DCRD')
3137 =item tax_exemption TAXNAME
3142 my( $self, $taxname ) = @_;
3144 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3145 'taxname' => $taxname,
3150 =item cust_main_exemption
3154 sub cust_main_exemption {
3156 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3159 =item invoicing_list [ ARRAYREF ]
3161 If an arguement is given, sets these email addresses as invoice recipients
3162 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3163 (except as warnings), so use check_invoicing_list first.
3165 Returns a list of email addresses (with svcnum entries expanded).
3167 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3168 check it without disturbing anything by passing nothing.
3170 This interface may change in the future.
3174 sub invoicing_list {
3175 my( $self, $arrayref ) = @_;
3178 my @cust_main_invoice;
3179 if ( $self->custnum ) {
3180 @cust_main_invoice =
3181 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3183 @cust_main_invoice = ();
3185 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3186 #warn $cust_main_invoice->destnum;
3187 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3188 #warn $cust_main_invoice->destnum;
3189 my $error = $cust_main_invoice->delete;
3190 warn $error if $error;
3193 if ( $self->custnum ) {
3194 @cust_main_invoice =
3195 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3197 @cust_main_invoice = ();
3199 my %seen = map { $_->address => 1 } @cust_main_invoice;
3200 foreach my $address ( @{$arrayref} ) {
3201 next if exists $seen{$address} && $seen{$address};
3202 $seen{$address} = 1;
3203 my $cust_main_invoice = new FS::cust_main_invoice ( {
3204 'custnum' => $self->custnum,
3207 my $error = $cust_main_invoice->insert;
3208 warn $error if $error;
3212 if ( $self->custnum ) {
3214 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3221 =item check_invoicing_list ARRAYREF
3223 Checks these arguements as valid input for the invoicing_list method. If there
3224 is an error, returns the error, otherwise returns false.
3228 sub check_invoicing_list {
3229 my( $self, $arrayref ) = @_;
3231 foreach my $address ( @$arrayref ) {
3233 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3234 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3237 my $cust_main_invoice = new FS::cust_main_invoice ( {
3238 'custnum' => $self->custnum,
3241 my $error = $self->custnum
3242 ? $cust_main_invoice->check
3243 : $cust_main_invoice->checkdest
3245 return $error if $error;
3249 return "Email address required"
3250 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3251 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3256 =item set_default_invoicing_list
3258 Sets the invoicing list to all accounts associated with this customer,
3259 overwriting any previous invoicing list.
3263 sub set_default_invoicing_list {
3265 $self->invoicing_list($self->all_emails);
3270 Returns the email addresses of all accounts provisioned for this customer.
3277 foreach my $cust_pkg ( $self->all_pkgs ) {
3278 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3280 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3281 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3283 $list{$_}=1 foreach map { $_->email } @svc_acct;
3288 =item invoicing_list_addpost
3290 Adds postal invoicing to this customer. If this customer is already configured
3291 to receive postal invoices, does nothing.
3295 sub invoicing_list_addpost {
3297 return if grep { $_ eq 'POST' } $self->invoicing_list;
3298 my @invoicing_list = $self->invoicing_list;
3299 push @invoicing_list, 'POST';
3300 $self->invoicing_list(\@invoicing_list);
3303 =item invoicing_list_emailonly
3305 Returns the list of email invoice recipients (invoicing_list without non-email
3306 destinations such as POST and FAX).
3310 sub invoicing_list_emailonly {
3312 warn "$me invoicing_list_emailonly called"
3314 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3317 =item invoicing_list_emailonly_scalar
3319 Returns the list of email invoice recipients (invoicing_list without non-email
3320 destinations such as POST and FAX) as a comma-separated scalar.
3324 sub invoicing_list_emailonly_scalar {
3326 warn "$me invoicing_list_emailonly_scalar called"
3328 join(', ', $self->invoicing_list_emailonly);
3331 =item referral_custnum_cust_main
3333 Returns the customer who referred this customer (or the empty string, if
3334 this customer was not referred).
3336 Note the difference with referral_cust_main method: This method,
3337 referral_custnum_cust_main returns the single customer (if any) who referred
3338 this customer, while referral_cust_main returns an array of customers referred
3343 sub referral_custnum_cust_main {
3345 return '' unless $self->referral_custnum;
3346 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3349 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3351 Returns an array of customers referred by this customer (referral_custnum set
3352 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3353 customers referred by customers referred by this customer and so on, inclusive.
3354 The default behavior is DEPTH 1 (no recursion).
3356 Note the difference with referral_custnum_cust_main method: This method,
3357 referral_cust_main, returns an array of customers referred BY this customer,
3358 while referral_custnum_cust_main returns the single customer (if any) who
3359 referred this customer.
3363 sub referral_cust_main {
3365 my $depth = @_ ? shift : 1;
3366 my $exclude = @_ ? shift : {};
3369 map { $exclude->{$_->custnum}++; $_; }
3370 grep { ! $exclude->{ $_->custnum } }
3371 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3375 map { $_->referral_cust_main($depth-1, $exclude) }
3382 =item referral_cust_main_ncancelled
3384 Same as referral_cust_main, except only returns customers with uncancelled
3389 sub referral_cust_main_ncancelled {
3391 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3394 =item referral_cust_pkg [ DEPTH ]
3396 Like referral_cust_main, except returns a flat list of all unsuspended (and
3397 uncancelled) packages for each customer. The number of items in this list may
3398 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3402 sub referral_cust_pkg {
3404 my $depth = @_ ? shift : 1;
3406 map { $_->unsuspended_pkgs }
3407 grep { $_->unsuspended_pkgs }
3408 $self->referral_cust_main($depth);
3411 =item referring_cust_main
3413 Returns the single cust_main record for the customer who referred this customer
3414 (referral_custnum), or false.
3418 sub referring_cust_main {
3420 return '' unless $self->referral_custnum;
3421 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3424 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3426 Applies a credit to this customer. If there is an error, returns the error,
3427 otherwise returns false.
3429 REASON can be a text string, an FS::reason object, or a scalar reference to
3430 a reasonnum. If a text string, it will be automatically inserted as a new
3431 reason, and a 'reason_type' option must be passed to indicate the
3432 FS::reason_type for the new reason.
3434 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3435 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3436 I<commission_pkgnum>.
3438 Any other options are passed to FS::cust_credit::insert.
3443 my( $self, $amount, $reason, %options ) = @_;
3445 my $cust_credit = new FS::cust_credit {
3446 'custnum' => $self->custnum,
3447 'amount' => $amount,
3450 if ( ref($reason) ) {
3452 if ( ref($reason) eq 'SCALAR' ) {
3453 $cust_credit->reasonnum( $$reason );
3455 $cust_credit->reasonnum( $reason->reasonnum );
3459 $cust_credit->set('reason', $reason)
3462 $cust_credit->$_( delete $options{$_} )
3463 foreach grep exists($options{$_}),
3464 qw( addlinfo eventnum ),
3465 map "commission_$_", qw( agentnum salesnum pkgnum );
3467 $cust_credit->insert(%options);
3471 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3473 Creates a one-time charge for this customer. If there is an error, returns
3474 the error, otherwise returns false.
3476 New-style, with a hashref of options:
3478 my $error = $cust_main->charge(
3482 'start_date' => str2time('7/4/2009'),
3483 'pkg' => 'Description',
3484 'comment' => 'Comment',
3485 'additional' => [], #extra invoice detail
3486 'classnum' => 1, #pkg_class
3488 'setuptax' => '', # or 'Y' for tax exempt
3490 'locationnum'=> 1234, # optional
3493 'taxclass' => 'Tax class',
3496 'taxproduct' => 2, #part_pkg_taxproduct
3497 'override' => {}, #XXX describe
3499 #will be filled in with the new object
3500 'cust_pkg_ref' => \$cust_pkg,
3502 #generate an invoice immediately
3504 'invoice_terms' => '', #with these terms
3510 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3514 #super false laziness w/quotation::charge
3517 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3518 my ( $pkg, $comment, $additional );
3519 my ( $setuptax, $taxclass ); #internal taxes
3520 my ( $taxproduct, $override ); #vendor (CCH) taxes
3522 my $separate_bill = '';
3523 my $cust_pkg_ref = '';
3524 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3526 if ( ref( $_[0] ) ) {
3527 $amount = $_[0]->{amount};
3528 $setup_cost = $_[0]->{setup_cost};
3529 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3530 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3531 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3532 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3533 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3534 : '$'. sprintf("%.2f",$amount);
3535 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3536 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3537 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3538 $additional = $_[0]->{additional} || [];
3539 $taxproduct = $_[0]->{taxproductnum};
3540 $override = { '' => $_[0]->{tax_override} };
3541 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3542 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3543 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3544 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3545 $separate_bill = $_[0]->{separate_bill} || '';
3551 $pkg = @_ ? shift : 'One-time charge';
3552 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3554 $taxclass = @_ ? shift : '';
3558 local $SIG{HUP} = 'IGNORE';
3559 local $SIG{INT} = 'IGNORE';
3560 local $SIG{QUIT} = 'IGNORE';
3561 local $SIG{TERM} = 'IGNORE';
3562 local $SIG{TSTP} = 'IGNORE';
3563 local $SIG{PIPE} = 'IGNORE';
3565 my $oldAutoCommit = $FS::UID::AutoCommit;
3566 local $FS::UID::AutoCommit = 0;
3569 my $part_pkg = new FS::part_pkg ( {
3571 'comment' => $comment,
3575 'classnum' => ( $classnum ? $classnum : '' ),
3576 'setuptax' => $setuptax,
3577 'taxclass' => $taxclass,
3578 'taxproductnum' => $taxproduct,
3579 'setup_cost' => $setup_cost,
3582 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3583 ( 0 .. @$additional - 1 )
3585 'additional_count' => scalar(@$additional),
3586 'setup_fee' => $amount,
3589 my $error = $part_pkg->insert( options => \%options,
3590 tax_overrides => $override,
3593 $dbh->rollback if $oldAutoCommit;
3597 my $pkgpart = $part_pkg->pkgpart;
3598 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3599 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3600 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3601 $error = $type_pkgs->insert;
3603 $dbh->rollback if $oldAutoCommit;
3608 my $cust_pkg = new FS::cust_pkg ( {
3609 'custnum' => $self->custnum,
3610 'pkgpart' => $pkgpart,
3611 'quantity' => $quantity,
3612 'start_date' => $start_date,
3613 'no_auto' => $no_auto,
3614 'separate_bill' => $separate_bill,
3615 'locationnum'=> $locationnum,
3618 $error = $cust_pkg->insert;
3620 $dbh->rollback if $oldAutoCommit;
3622 } elsif ( $cust_pkg_ref ) {
3623 ${$cust_pkg_ref} = $cust_pkg;
3627 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3628 'pkg_list' => [ $cust_pkg ],
3631 $dbh->rollback if $oldAutoCommit;
3636 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3641 #=item charge_postal_fee
3643 #Applies a one time charge this customer. If there is an error,
3644 #returns the error, returns the cust_pkg charge object or false
3645 #if there was no charge.
3649 # This should be a customer event. For that to work requires that bill
3650 # also be a customer event.
3652 sub charge_postal_fee {
3655 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3656 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3658 my $cust_pkg = new FS::cust_pkg ( {
3659 'custnum' => $self->custnum,
3660 'pkgpart' => $pkgpart,
3664 my $error = $cust_pkg->insert;
3665 $error ? $error : $cust_pkg;
3668 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3670 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3672 Optionally, a list or hashref of additional arguments to the qsearch call can
3679 my $opt = ref($_[0]) ? shift : { @_ };
3681 #return $self->num_cust_bill unless wantarray || keys %$opt;
3683 $opt->{'table'} = 'cust_bill';
3684 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3685 $opt->{'hashref'}{'custnum'} = $self->custnum;
3686 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3688 map { $_ } #behavior of sort undefined in scalar context
3689 sort { $a->_date <=> $b->_date }
3693 =item open_cust_bill
3695 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3700 sub open_cust_bill {
3704 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3710 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3712 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3716 sub legacy_cust_bill {
3719 #return $self->num_legacy_cust_bill unless wantarray;
3721 map { $_ } #behavior of sort undefined in scalar context
3722 sort { $a->_date <=> $b->_date }
3723 qsearch({ 'table' => 'legacy_cust_bill',
3724 'hashref' => { 'custnum' => $self->custnum, },
3725 'order_by' => 'ORDER BY _date ASC',
3729 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3731 Returns all the statements (see L<FS::cust_statement>) for this customer.
3733 Optionally, a list or hashref of additional arguments to the qsearch call can
3738 =item cust_bill_void
3740 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3744 sub cust_bill_void {
3747 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3748 sort { $a->_date <=> $b->_date }
3749 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3752 sub cust_statement {
3754 my $opt = ref($_[0]) ? shift : { @_ };
3756 #return $self->num_cust_statement unless wantarray || keys %$opt;
3758 $opt->{'table'} = 'cust_statement';
3759 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3760 $opt->{'hashref'}{'custnum'} = $self->custnum;
3761 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3763 map { $_ } #behavior of sort undefined in scalar context
3764 sort { $a->_date <=> $b->_date }
3768 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3770 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3772 Optionally, a list or hashref of additional arguments to the qsearch call can
3773 be passed following the SVCDB.
3780 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3781 warn "$me svc_x requires a svcdb";
3784 my $opt = ref($_[0]) ? shift : { @_ };
3786 $opt->{'table'} = $svcdb;
3787 $opt->{'addl_from'} =
3788 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3789 ($opt->{'addl_from'} || '');
3791 my $custnum = $self->custnum;
3792 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3793 my $where = "cust_pkg.custnum = $custnum";
3795 my $extra_sql = $opt->{'extra_sql'} || '';
3796 if ( keys %{ $opt->{'hashref'} } ) {
3797 $extra_sql = " AND $where $extra_sql";
3800 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3801 $extra_sql = "WHERE $where AND $1";
3804 $extra_sql = "WHERE $where $extra_sql";
3807 $opt->{'extra_sql'} = $extra_sql;
3812 # required for use as an eventtable;
3815 $self->svc_x('svc_acct', @_);
3820 Returns all the credits (see L<FS::cust_credit>) for this customer.
3826 map { $_ } #return $self->num_cust_credit unless wantarray;
3827 sort { $a->_date <=> $b->_date }
3828 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3831 =item cust_credit_pkgnum
3833 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3834 package when using experimental package balances.
3838 sub cust_credit_pkgnum {
3839 my( $self, $pkgnum ) = @_;
3840 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3841 sort { $a->_date <=> $b->_date }
3842 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3843 'pkgnum' => $pkgnum,
3848 =item cust_credit_void
3850 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3854 sub cust_credit_void {
3857 sort { $a->_date <=> $b->_date }
3858 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3863 Returns all the payments (see L<FS::cust_pay>) for this customer.
3869 my $opt = ref($_[0]) ? shift : { @_ };
3871 return $self->num_cust_pay unless wantarray || keys %$opt;
3873 $opt->{'table'} = 'cust_pay';
3874 $opt->{'hashref'}{'custnum'} = $self->custnum;
3876 map { $_ } #behavior of sort undefined in scalar context
3877 sort { $a->_date <=> $b->_date }
3884 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3885 called automatically when the cust_pay method is used in a scalar context.
3891 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3892 my $sth = dbh->prepare($sql) or die dbh->errstr;
3893 $sth->execute($self->custnum) or die $sth->errstr;
3894 $sth->fetchrow_arrayref->[0];
3897 =item unapplied_cust_pay
3899 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3903 sub unapplied_cust_pay {
3907 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3913 =item cust_pay_pkgnum
3915 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3916 package when using experimental package balances.
3920 sub cust_pay_pkgnum {
3921 my( $self, $pkgnum ) = @_;
3922 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3923 sort { $a->_date <=> $b->_date }
3924 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3925 'pkgnum' => $pkgnum,
3932 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3938 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3939 sort { $a->_date <=> $b->_date }
3940 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3943 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3945 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3947 Optionally, a list or hashref of additional arguments to the qsearch call can
3952 sub cust_pay_batch {
3954 my $opt = ref($_[0]) ? shift : { @_ };
3956 #return $self->num_cust_statement unless wantarray || keys %$opt;
3958 $opt->{'table'} = 'cust_pay_batch';
3959 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3960 $opt->{'hashref'}{'custnum'} = $self->custnum;
3961 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3963 map { $_ } #behavior of sort undefined in scalar context
3964 sort { $a->paybatchnum <=> $b->paybatchnum }
3968 =item cust_pay_pending
3970 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3971 (without status "done").
3975 sub cust_pay_pending {
3977 return $self->num_cust_pay_pending unless wantarray;
3978 sort { $a->_date <=> $b->_date }
3979 qsearch( 'cust_pay_pending', {
3980 'custnum' => $self->custnum,
3981 'status' => { op=>'!=', value=>'done' },
3986 =item cust_pay_pending_attempt
3988 Returns all payment attempts / declined payments for this customer, as pending
3989 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3990 a corresponding payment (see L<FS::cust_pay>).
3994 sub cust_pay_pending_attempt {
3996 return $self->num_cust_pay_pending_attempt unless wantarray;
3997 sort { $a->_date <=> $b->_date }
3998 qsearch( 'cust_pay_pending', {
3999 'custnum' => $self->custnum,
4006 =item num_cust_pay_pending
4008 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4009 customer (without status "done"). Also called automatically when the
4010 cust_pay_pending method is used in a scalar context.
4014 sub num_cust_pay_pending {
4017 " SELECT COUNT(*) FROM cust_pay_pending ".
4018 " WHERE custnum = ? AND status != 'done' ",
4023 =item num_cust_pay_pending_attempt
4025 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4026 customer, with status "done" but without a corresp. Also called automatically when the
4027 cust_pay_pending method is used in a scalar context.
4031 sub num_cust_pay_pending_attempt {
4034 " SELECT COUNT(*) FROM cust_pay_pending ".
4035 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4042 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4048 map { $_ } #return $self->num_cust_refund unless wantarray;
4049 sort { $a->_date <=> $b->_date }
4050 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4053 =item display_custnum
4055 Returns the displayed customer number for this customer: agent_custid if
4056 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4060 sub display_custnum {
4063 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4064 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
4065 if ( $special eq 'CoStAg' ) {
4066 $prefix = uc( join('',
4068 ($self->state =~ /^(..)/),
4069 $prefix || ($self->agent->agent =~ /^(..)/)
4072 elsif ( $special eq 'CoStCl' ) {
4073 $prefix = uc( join('',
4075 ($self->state =~ /^(..)/),
4076 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
4079 # add any others here if needed
4082 my $length = $conf->config('cust_main-custnum-display_length');
4083 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
4084 return $self->agent_custid;
4085 } elsif ( $prefix ) {
4086 $length = 8 if !defined($length);
4088 sprintf('%0'.$length.'d', $self->custnum)
4089 } elsif ( $length ) {
4090 return sprintf('%0'.$length.'d', $self->custnum);
4092 return $self->custnum;
4098 Returns a name string for this customer, either "Company (Last, First)" or
4105 my $name = $self->contact;
4106 $name = $self->company. " ($name)" if $self->company;
4110 =item service_contact
4112 Returns the L<FS::contact> object for this customer that has the 'Service'
4113 contact class, or undef if there is no such contact. Deprecated; don't use
4118 sub service_contact {
4120 if ( !exists($self->{service_contact}) ) {
4121 my $classnum = $self->scalar_sql(
4122 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4123 ) || 0; #if it's zero, qsearchs will return nothing
4124 $self->{service_contact} = qsearchs('contact', {
4125 'classnum' => $classnum, 'custnum' => $self->custnum
4128 $self->{service_contact};
4133 Returns a name string for this (service/shipping) contact, either
4134 "Company (Last, First)" or "Last, First".
4141 my $name = $self->ship_contact;
4142 $name = $self->company. " ($name)" if $self->company;
4148 Returns a name string for this customer, either "Company" or "First Last".
4154 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4157 =item ship_name_short
4159 Returns a name string for this (service/shipping) contact, either "Company"
4164 sub ship_name_short {
4166 $self->service_contact
4167 ? $self->ship_contact_firstlast
4173 Returns this customer's full (billing) contact name only, "Last, First"
4179 $self->get('last'). ', '. $self->first;
4184 Returns this customer's full (shipping) contact name only, "Last, First"
4190 my $contact = $self->service_contact || $self;
4191 $contact->get('last') . ', ' . $contact->get('first');
4194 =item contact_firstlast
4196 Returns this customers full (billing) contact name only, "First Last".
4200 sub contact_firstlast {
4202 $self->first. ' '. $self->get('last');
4205 =item ship_contact_firstlast
4207 Returns this customer's full (shipping) contact name only, "First Last".
4211 sub ship_contact_firstlast {
4213 my $contact = $self->service_contact || $self;
4214 $contact->get('first') . ' '. $contact->get('last');
4217 #XXX this doesn't work in 3.x+
4220 #Returns this customer's full country name
4226 # code2country($self->country);
4229 sub bill_country_full {
4231 code2country($self->bill_location->country);
4234 sub ship_country_full {
4236 code2country($self->ship_location->country);
4239 =item county_state_county [ PREFIX ]
4241 Returns a string consisting of just the county, state and country.
4245 sub county_state_country {
4248 if ( @_ && $_[0] && $self->has_ship_address ) {
4249 $locationnum = $self->ship_locationnum;
4251 $locationnum = $self->bill_locationnum;
4253 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4254 $cust_location->county_state_country;
4257 =item geocode DATA_VENDOR
4259 Returns a value for the customer location as encoded by DATA_VENDOR.
4260 Currently this only makes sense for "CCH" as DATA_VENDOR.
4268 Returns a status string for this customer, currently:
4272 =item prospect - No packages have ever been ordered
4274 =item ordered - Recurring packages all are new (not yet billed).
4276 =item active - One or more recurring packages is active
4278 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4280 =item suspended - All non-cancelled recurring packages are suspended
4282 =item cancelled - All recurring packages are cancelled
4286 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4287 cust_main-status_module configuration option.
4291 sub status { shift->cust_status(@_); }
4295 for my $status ( FS::cust_main->statuses() ) {
4296 my $method = $status.'_sql';
4297 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4298 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4299 $sth->execute( ($self->custnum) x $numnum )
4300 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4301 return $status if $sth->fetchrow_arrayref->[0];
4305 =item is_status_delay_cancel
4307 Returns true if customer status is 'suspended'
4308 and all suspended cust_pkg return true for
4309 cust_pkg->is_status_delay_cancel.
4311 This is not a real status, this only meant for hacking display
4312 values, because otherwise treating the customer as suspended is
4313 really the whole point of the delay_cancel option.
4317 sub is_status_delay_cancel {
4319 return 0 unless $self->status eq 'suspended';
4320 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4321 return 0 unless $cust_pkg->is_status_delay_cancel;
4326 =item ucfirst_cust_status
4328 =item ucfirst_status
4330 Returns the status with the first character capitalized.
4334 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4336 sub ucfirst_cust_status {
4338 ucfirst($self->cust_status);
4343 Returns a hex triplet color string for this customer's status.
4347 sub statuscolor { shift->cust_statuscolor(@_); }
4349 sub cust_statuscolor {
4351 __PACKAGE__->statuscolors->{$self->cust_status};
4354 =item tickets [ STATUS ]
4356 Returns an array of hashes representing the customer's RT tickets.
4358 An optional status (or arrayref or hashref of statuses) may be specified.
4364 my $status = ( @_ && $_[0] ) ? shift : '';
4366 my $num = $conf->config('cust_main-max_tickets') || 10;
4369 if ( $conf->config('ticket_system') ) {
4370 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4372 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4381 foreach my $priority (
4382 $conf->config('ticket_system-custom_priority_field-values'), ''
4384 last if scalar(@tickets) >= $num;
4386 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4387 $num - scalar(@tickets),
4398 # Return services representing svc_accts in customer support packages
4399 sub support_services {
4401 my %packages = map { $_ => 1 } $conf->config('support_packages');
4403 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4404 grep { $_->part_svc->svcdb eq 'svc_acct' }
4405 map { $_->cust_svc }
4406 grep { exists $packages{ $_->pkgpart } }
4407 $self->ncancelled_pkgs;
4411 # Return a list of latitude/longitude for one of the services (if any)
4412 sub service_coordinates {
4416 grep { $_->latitude && $_->longitude }
4418 map { $_->cust_svc }
4419 $self->ncancelled_pkgs;
4421 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4426 Returns a masked version of the named field
4431 my ($self,$field) = @_;
4435 'x'x(length($self->getfield($field))-4).
4436 substr($self->getfield($field), (length($self->getfield($field))-4));
4442 =head1 CLASS METHODS
4448 Class method that returns the list of possible status strings for customers
4449 (see L<the status method|/status>). For example:
4451 @statuses = FS::cust_main->statuses();
4457 keys %{ $self->statuscolors };
4460 =item cust_status_sql
4462 Returns an SQL fragment to determine the status of a cust_main record, as a
4467 sub cust_status_sql {
4469 for my $status ( FS::cust_main->statuses() ) {
4470 my $method = $status.'_sql';
4471 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4480 Returns an SQL expression identifying prospective cust_main records (customers
4481 with no packages ever ordered)
4485 use vars qw($select_count_pkgs);
4486 $select_count_pkgs =
4487 "SELECT COUNT(*) FROM cust_pkg
4488 WHERE cust_pkg.custnum = cust_main.custnum";
4490 sub select_count_pkgs_sql {
4495 " 0 = ( $select_count_pkgs ) ";
4500 Returns an SQL expression identifying ordered cust_main records (customers with
4501 no active packages, but recurring packages not yet setup or one time charges
4507 FS::cust_main->none_active_sql.
4508 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4513 Returns an SQL expression identifying active cust_main records (customers with
4514 active recurring packages).
4519 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4522 =item none_active_sql
4524 Returns an SQL expression identifying cust_main records with no active
4525 recurring packages. This includes customers of status prospect, ordered,
4526 inactive, and suspended.
4530 sub none_active_sql {
4531 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4536 Returns an SQL expression identifying inactive cust_main records (customers with
4537 no active recurring packages, but otherwise unsuspended/uncancelled).
4542 FS::cust_main->none_active_sql.
4543 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4549 Returns an SQL expression identifying suspended cust_main records.
4554 sub suspended_sql { susp_sql(@_); }
4556 FS::cust_main->none_active_sql.
4557 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4563 Returns an SQL expression identifying cancelled cust_main records.
4567 sub cancel_sql { shift->cancelled_sql(@_); }
4570 =item uncancelled_sql
4572 Returns an SQL expression identifying un-cancelled cust_main records.
4576 sub uncancelled_sql { uncancel_sql(@_); }
4577 sub uncancel_sql { "
4578 ( 0 < ( $select_count_pkgs
4579 AND ( cust_pkg.cancel IS NULL
4580 OR cust_pkg.cancel = 0
4583 OR 0 = ( $select_count_pkgs )
4589 Returns an SQL fragment to retreive the balance.
4594 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4595 WHERE cust_bill.custnum = cust_main.custnum )
4596 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4597 WHERE cust_pay.custnum = cust_main.custnum )
4598 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4599 WHERE cust_credit.custnum = cust_main.custnum )
4600 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4601 WHERE cust_refund.custnum = cust_main.custnum )
4604 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4606 Returns an SQL fragment to retreive the balance for this customer, optionally
4607 considering invoices with date earlier than START_TIME, and not
4608 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4609 total_unapplied_payments).
4611 Times are specified as SQL fragments or numeric
4612 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4613 L<Date::Parse> for conversion functions. The empty string can be passed
4614 to disable that time constraint completely.
4616 Available options are:
4620 =item unapplied_date
4622 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)
4627 set to true to remove all customer comparison clauses, for totals
4632 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4637 JOIN clause (typically used with the total option)
4641 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4642 time will be ignored. Note that START_TIME and END_TIME only limit the date
4643 range for invoices and I<unapplied> payments, credits, and refunds.
4649 sub balance_date_sql {
4650 my( $class, $start, $end, %opt ) = @_;
4652 my $cutoff = $opt{'cutoff'};
4654 my $owed = FS::cust_bill->owed_sql($cutoff);
4655 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4656 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4657 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4659 my $j = $opt{'join'} || '';
4661 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4662 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4663 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4664 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4666 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4667 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4668 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4669 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4674 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4676 Returns an SQL fragment to retreive the total unapplied payments for this
4677 customer, only considering payments with date earlier than START_TIME, and
4678 optionally not later than END_TIME.
4680 Times are specified as SQL fragments or numeric
4681 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4682 L<Date::Parse> for conversion functions. The empty string can be passed
4683 to disable that time constraint completely.
4685 Available options are:
4689 sub unapplied_payments_date_sql {
4690 my( $class, $start, $end, %opt ) = @_;
4692 my $cutoff = $opt{'cutoff'};
4694 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4696 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4697 'unapplied_date'=>1 );
4699 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4702 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4704 Helper method for balance_date_sql; name (and usage) subject to change
4705 (suggestions welcome).
4707 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4708 cust_refund, cust_credit or cust_pay).
4710 If TABLE is "cust_bill" or the unapplied_date option is true, only
4711 considers records with date earlier than START_TIME, and optionally not
4712 later than END_TIME .
4716 sub _money_table_where {
4717 my( $class, $table, $start, $end, %opt ) = @_;
4720 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4721 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4722 push @where, "$table._date <= $start" if defined($start) && length($start);
4723 push @where, "$table._date > $end" if defined($end) && length($end);
4725 push @where, @{$opt{'where'}} if $opt{'where'};
4726 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4732 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4733 use FS::cust_main::Search;
4736 FS::cust_main::Search->search(@_);
4751 #warn join('-',keys %$param);
4752 my $fh = $param->{filehandle};
4753 my $agentnum = $param->{agentnum};
4754 my $format = $param->{format};
4756 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4759 if ( $format eq 'simple' ) {
4760 @fields = qw( custnum agent_custid amount pkg );
4762 die "unknown format $format";
4765 eval "use Text::CSV_XS;";
4768 my $csv = new Text::CSV_XS;
4775 local $SIG{HUP} = 'IGNORE';
4776 local $SIG{INT} = 'IGNORE';
4777 local $SIG{QUIT} = 'IGNORE';
4778 local $SIG{TERM} = 'IGNORE';
4779 local $SIG{TSTP} = 'IGNORE';
4780 local $SIG{PIPE} = 'IGNORE';
4782 my $oldAutoCommit = $FS::UID::AutoCommit;
4783 local $FS::UID::AutoCommit = 0;
4786 #while ( $columns = $csv->getline($fh) ) {
4788 while ( defined($line=<$fh>) ) {
4790 $csv->parse($line) or do {
4791 $dbh->rollback if $oldAutoCommit;
4792 return "can't parse: ". $csv->error_input();
4795 my @columns = $csv->fields();
4796 #warn join('-',@columns);
4799 foreach my $field ( @fields ) {
4800 $row{$field} = shift @columns;
4803 if ( $row{custnum} && $row{agent_custid} ) {
4804 dbh->rollback if $oldAutoCommit;
4805 return "can't specify custnum with agent_custid $row{agent_custid}";
4809 if ( $row{agent_custid} && $agentnum ) {
4810 %hash = ( 'agent_custid' => $row{agent_custid},
4811 'agentnum' => $agentnum,
4815 if ( $row{custnum} ) {
4816 %hash = ( 'custnum' => $row{custnum} );
4819 unless ( scalar(keys %hash) ) {
4820 $dbh->rollback if $oldAutoCommit;
4821 return "can't find customer without custnum or agent_custid and agentnum";
4824 my $cust_main = qsearchs('cust_main', { %hash } );
4825 unless ( $cust_main ) {
4826 $dbh->rollback if $oldAutoCommit;
4827 my $custnum = $row{custnum} || $row{agent_custid};
4828 return "unknown custnum $custnum";
4831 if ( $row{'amount'} > 0 ) {
4832 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4834 $dbh->rollback if $oldAutoCommit;
4838 } elsif ( $row{'amount'} < 0 ) {
4839 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4842 $dbh->rollback if $oldAutoCommit;
4852 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4854 return "Empty file!" unless $imported;
4860 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4862 Deprecated. Use event notification and message templates
4863 (L<FS::msg_template>) instead.
4865 Sends a templated email notification to the customer (see L<Text::Template>).
4867 OPTIONS is a hash and may include
4869 I<from> - the email sender (default is invoice_from)
4871 I<to> - comma-separated scalar or arrayref of recipients
4872 (default is invoicing_list)
4874 I<subject> - The subject line of the sent email notification
4875 (default is "Notice from company_name")
4877 I<extra_fields> - a hashref of name/value pairs which will be substituted
4880 The following variables are vavailable in the template.
4882 I<$first> - the customer first name
4883 I<$last> - the customer last name
4884 I<$company> - the customer company
4885 I<$payby> - a description of the method of payment for the customer
4886 # would be nice to use FS::payby::shortname
4887 I<$payinfo> - the account information used to collect for this customer
4888 I<$expdate> - the expiration of the customer payment in seconds from epoch
4893 my ($self, $template, %options) = @_;
4895 return unless $conf->exists($template);
4897 my $from = $conf->invoice_from_full($self->agentnum)
4898 if $conf->exists('invoice_from', $self->agentnum);
4899 $from = $options{from} if exists($options{from});
4901 my $to = join(',', $self->invoicing_list_emailonly);
4902 $to = $options{to} if exists($options{to});
4904 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4905 if $conf->exists('company_name', $self->agentnum);
4906 $subject = $options{subject} if exists($options{subject});
4908 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4909 SOURCE => [ map "$_\n",
4910 $conf->config($template)]
4912 or die "can't create new Text::Template object: Text::Template::ERROR";
4913 $notify_template->compile()
4914 or die "can't compile template: Text::Template::ERROR";
4916 $FS::notify_template::_template::company_name =
4917 $conf->config('company_name', $self->agentnum);
4918 $FS::notify_template::_template::company_address =
4919 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4921 my $paydate = $self->paydate || '2037-12-31';
4922 $FS::notify_template::_template::first = $self->first;
4923 $FS::notify_template::_template::last = $self->last;
4924 $FS::notify_template::_template::company = $self->company;
4925 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4926 my $payby = $self->payby;
4927 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4928 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4930 #credit cards expire at the end of the month/year of their exp date
4931 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4932 $FS::notify_template::_template::payby = 'credit card';
4933 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4934 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4936 }elsif ($payby eq 'COMP') {
4937 $FS::notify_template::_template::payby = 'complimentary account';
4939 $FS::notify_template::_template::payby = 'current method';
4941 $FS::notify_template::_template::expdate = $expire_time;
4943 for (keys %{$options{extra_fields}}){
4945 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4948 send_email(from => $from,
4950 subject => $subject,
4951 body => $notify_template->fill_in( PACKAGE =>
4952 'FS::notify_template::_template' ),
4957 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4959 Generates a templated notification to the customer (see L<Text::Template>).
4961 OPTIONS is a hash and may include
4963 I<extra_fields> - a hashref of name/value pairs which will be substituted
4964 into the template. These values may override values mentioned below
4965 and those from the customer record.
4967 The following variables are available in the template instead of or in addition
4968 to the fields of the customer record.
4970 I<$payby> - a description of the method of payment for the customer
4971 # would be nice to use FS::payby::shortname
4972 I<$payinfo> - the masked account information used to collect for this customer
4973 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4974 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4978 # a lot like cust_bill::print_latex
4979 sub generate_letter {
4980 my ($self, $template, %options) = @_;
4982 return unless $conf->exists($template);
4984 my $letter_template = new Text::Template
4986 SOURCE => [ map "$_\n", $conf->config($template)],
4987 DELIMITERS => [ '[@--', '--@]' ],
4989 or die "can't create new Text::Template object: Text::Template::ERROR";
4991 $letter_template->compile()
4992 or die "can't compile template: Text::Template::ERROR";
4994 my %letter_data = map { $_ => $self->$_ } $self->fields;
4995 $letter_data{payinfo} = $self->mask_payinfo;
4997 #my $paydate = $self->paydate || '2037-12-31';
4998 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5000 my $payby = $self->payby;
5001 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5002 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5004 #credit cards expire at the end of the month/year of their exp date
5005 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5006 $letter_data{payby} = 'credit card';
5007 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5008 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5010 }elsif ($payby eq 'COMP') {
5011 $letter_data{payby} = 'complimentary account';
5013 $letter_data{payby} = 'current method';
5015 $letter_data{expdate} = $expire_time;
5017 for (keys %{$options{extra_fields}}){
5018 $letter_data{$_} = $options{extra_fields}->{$_};
5021 unless(exists($letter_data{returnaddress})){
5022 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5023 $self->agent_template)
5025 if ( length($retadd) ) {
5026 $letter_data{returnaddress} = $retadd;
5027 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5028 $letter_data{returnaddress} =
5029 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5033 ( $conf->config('company_name', $self->agentnum),
5034 $conf->config('company_address', $self->agentnum),
5038 $letter_data{returnaddress} = '~';
5042 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5044 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5046 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5048 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5052 ) or die "can't open temp file: $!\n";
5053 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5054 or die "can't write temp file: $!\n";
5056 $letter_data{'logo_file'} = $lh->filename;
5058 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5062 ) or die "can't open temp file: $!\n";
5064 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5066 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5067 return ($1, $letter_data{'logo_file'});
5071 =item print_ps TEMPLATE
5073 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5079 my($file, $lfile) = $self->generate_letter(@_);
5080 my $ps = FS::Misc::generate_ps($file);
5081 unlink($file.'.tex');
5087 =item print TEMPLATE
5089 Prints the filled in template.
5091 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5095 sub queueable_print {
5098 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5099 or die "invalid customer number: " . $opt{custnum};
5101 my $error = $self->print( { 'template' => $opt{template} } );
5102 die $error if $error;
5106 my ($self, $template) = (shift, shift);
5108 [ $self->print_ps($template) ],
5109 'agentnum' => $self->agentnum,
5113 #these three subs should just go away once agent stuff is all config overrides
5115 sub agent_template {
5117 $self->_agent_plandata('agent_templatename');
5120 sub agent_invoice_from {
5122 $self->_agent_plandata('agent_invoice_from');
5125 sub _agent_plandata {
5126 my( $self, $option ) = @_;
5128 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5129 #agent-specific Conf
5131 use FS::part_event::Condition;
5133 my $agentnum = $self->agentnum;
5135 my $regexp = regexp_sql();
5137 my $part_event_option =
5139 'select' => 'part_event_option.*',
5140 'table' => 'part_event_option',
5142 LEFT JOIN part_event USING ( eventpart )
5143 LEFT JOIN part_event_option AS peo_agentnum
5144 ON ( part_event.eventpart = peo_agentnum.eventpart
5145 AND peo_agentnum.optionname = 'agentnum'
5146 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5148 LEFT JOIN part_event_condition
5149 ON ( part_event.eventpart = part_event_condition.eventpart
5150 AND part_event_condition.conditionname = 'cust_bill_age'
5152 LEFT JOIN part_event_condition_option
5153 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5154 AND part_event_condition_option.optionname = 'age'
5157 #'hashref' => { 'optionname' => $option },
5158 #'hashref' => { 'part_event_option.optionname' => $option },
5160 " WHERE part_event_option.optionname = ". dbh->quote($option).
5161 " AND action = 'cust_bill_send_agent' ".
5162 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5163 " AND peo_agentnum.optionname = 'agentnum' ".
5164 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5166 CASE WHEN part_event_condition_option.optionname IS NULL
5168 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5170 , part_event.weight".
5174 unless ( $part_event_option ) {
5175 return $self->agent->invoice_template || ''
5176 if $option eq 'agent_templatename';
5180 $part_event_option->optionvalue;
5184 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5186 Subroutine (not a method), designed to be called from the queue.
5188 Takes a list of options and values.
5190 Pulls up the customer record via the custnum option and calls bill_and_collect.
5195 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5197 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5198 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5200 #without this errors don't get rolled back
5201 $args{'fatal'} = 1; # runs from job queue, will be caught
5203 $cust_main->bill_and_collect( %args );
5206 sub process_bill_and_collect {
5208 my $param = thaw(decode_base64(shift));
5209 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5210 or die "custnum '$param->{custnum}' not found!\n";
5211 $param->{'job'} = $job;
5212 $param->{'fatal'} = 1; # runs from job queue, will be caught
5213 $param->{'retry'} = 1;
5215 $cust_main->bill_and_collect( %$param );
5218 #starting to take quite a while for big dbs
5219 # (JRNL: journaled so it only happens once per database)
5220 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5221 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5222 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5223 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5224 # JRNL leading/trailing spaces in first, last, company
5225 # - otaker upgrade? journal and call it good? (double check to make sure
5226 # we're not still setting otaker here)
5228 #only going to get worse with new location stuff...
5230 sub _upgrade_data { #class method
5231 my ($class, %opts) = @_;
5234 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5237 #this seems to be the only expensive one.. why does it take so long?
5238 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5240 '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';
5241 FS::upgrade_journal->set_done('cust_main__signupdate');
5244 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5246 # fix yyyy-m-dd formatted paydates
5247 if ( driver_name =~ /^mysql/i ) {
5249 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5250 } else { # the SQL standard
5252 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5254 FS::upgrade_journal->set_done('cust_main__paydate');
5257 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5259 push @statements, #fix the weird BILL with a cc# in payinfo problem
5261 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5263 FS::upgrade_journal->set_done('cust_main__payinfo');
5268 foreach my $sql ( @statements ) {
5269 my $sth = dbh->prepare($sql) or die dbh->errstr;
5270 $sth->execute or die $sth->errstr;
5271 #warn ( (time - $t). " seconds\n" );
5275 local($ignore_expired_card) = 1;
5276 local($ignore_banned_card) = 1;
5277 local($skip_fuzzyfiles) = 1;
5278 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5280 FS::cust_main::Location->_upgrade_data(%opts);
5282 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5284 foreach my $cust_main ( qsearch({
5285 'table' => 'cust_main',
5287 'extra_sql' => 'WHERE '.
5289 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5290 qw( first last company )
5293 my $error = $cust_main->replace;
5294 die $error if $error;
5297 FS::upgrade_journal->set_done('cust_main__trimspaces');
5301 $class->_upgrade_otaker(%opts);
5311 The delete method should possibly take an FS::cust_main object reference
5312 instead of a scalar customer number.
5314 Bill and collect options should probably be passed as references instead of a
5317 There should probably be a configuration file with a list of allowed credit
5320 No multiple currency support (probably a larger project than just this module).
5322 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5324 Birthdates rely on negative epoch values.
5326 The payby for card/check batches is broken. With mixed batching, bad
5329 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5333 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5334 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5335 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.