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::Location
10 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
11 FS::geocode_Mixin FS::Quotable_Mixin
15 use vars qw( $DEBUG $me $conf
18 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
23 use Scalar::Util qw( blessed );
24 use Time::Local qw(timelocal);
25 use Storable qw(thaw);
29 use Digest::MD5 qw(md5_base64);
32 use File::Temp; #qw( tempfile );
33 use Business::CreditCard 0.28;
35 use FS::UID qw( dbh driver_name );
36 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
37 use FS::Misc qw( generate_email send_email generate_ps do_print );
38 use FS::Msgcat qw(gettext);
45 use FS::cust_bill_void;
46 use FS::legacy_cust_bill;
48 use FS::cust_pay_pending;
49 use FS::cust_pay_void;
50 use FS::cust_pay_batch;
53 use FS::part_referral;
54 use FS::cust_main_county;
55 use FS::cust_location;
57 use FS::cust_main_exemption;
58 use FS::cust_tax_adjustment;
59 use FS::cust_tax_location;
61 use FS::cust_main_invoice;
63 use FS::prepay_credit;
69 use FS::payment_gateway;
70 use FS::agent_payment_gateway;
72 use FS::cust_main_note;
73 use FS::cust_attachment;
76 use FS::upgrade_journal;
78 # 1 is mostly method/subroutine entry and options
79 # 2 traces progress of some operations
80 # 3 is even more information including possibly sensitive data
82 $me = '[FS::cust_main]';
85 $ignore_expired_card = 0;
86 $ignore_banned_card = 0;
90 @encrypted_fields = ('payinfo', 'paycvv');
91 sub nohistory_fields { ('payinfo', 'paycvv'); }
93 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
95 #ask FS::UID to run this stuff for us later
96 #$FS::UID::callback{'FS::cust_main'} = sub {
97 install_callback FS::UID sub {
99 #yes, need it for stuff below (prolly should be cached)
104 my ( $hashref, $cache ) = @_;
105 if ( exists $hashref->{'pkgnum'} ) {
106 #@{ $self->{'_pkgnum'} } = ();
107 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
108 $self->{'_pkgnum'} = $subcache;
109 #push @{ $self->{'_pkgnum'} },
110 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
116 FS::cust_main - Object methods for cust_main records
122 $record = new FS::cust_main \%hash;
123 $record = new FS::cust_main { 'column' => 'value' };
125 $error = $record->insert;
127 $error = $new_record->replace($old_record);
129 $error = $record->delete;
131 $error = $record->check;
133 @cust_pkg = $record->all_pkgs;
135 @cust_pkg = $record->ncancelled_pkgs;
137 @cust_pkg = $record->suspended_pkgs;
139 $error = $record->bill;
140 $error = $record->bill %options;
141 $error = $record->bill 'time' => $time;
143 $error = $record->collect;
144 $error = $record->collect %options;
145 $error = $record->collect 'invoice_time' => $time,
150 An FS::cust_main object represents a customer. FS::cust_main inherits from
151 FS::Record. The following fields are currently supported:
157 Primary key (assigned automatically for new customers)
161 Agent (see L<FS::agent>)
165 Advertising source (see L<FS::part_referral>)
177 Cocial security number (optional)
201 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
205 Payment Information (See L<FS::payinfo_Mixin> for data format)
209 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
213 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
217 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
221 Start date month (maestro/solo cards only)
225 Start date year (maestro/solo cards only)
229 Issue number (maestro/solo cards only)
233 Name on card or billing name
237 IP address from which payment information was received
241 Tax exempt, empty or `Y'
245 Order taker (see L<FS::access_user>)
251 =item referral_custnum
253 Referring customer number
257 Enable individual CDR spooling, empty or `Y'
261 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
265 Discourage individual CDR printing, empty or `Y'
269 Allow self-service editing of ticket subjects, empty or 'Y'
271 =item calling_list_exempt
273 Do not call, empty or 'Y'
283 Creates a new customer. To add the customer to the database, see L<"insert">.
285 Note that this stores the hash reference, not a distinct copy of the hash it
286 points to. You can ask the object for a copy with the I<hash> method.
290 sub table { 'cust_main'; }
292 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
294 Adds this customer to the database. If there is an error, returns the error,
295 otherwise returns false.
297 Usually the customer's location will not yet exist in the database, and
298 the C<bill_location> and C<ship_location> pseudo-fields must be set to
299 uninserted L<FS::cust_location> objects. These will be inserted and linked
300 (in both directions) to the new customer record. If they're references
301 to the same object, they will become the same location.
303 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
304 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
305 are inserted atomicly, or the transaction is rolled back. Passing an empty
306 hash reference is equivalent to not supplying this parameter. There should be
307 a better explanation of this, but until then, here's an example:
310 tie %hash, 'Tie::RefHash'; #this part is important
312 $cust_pkg => [ $svc_acct ],
315 $cust_main->insert( \%hash );
317 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
318 be set as the invoicing list (see L<"invoicing_list">). Errors return as
319 expected and rollback the entire transaction; it is not necessary to call
320 check_invoicing_list first. The invoicing_list is set after the records in the
321 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
322 invoicing_list destination to the newly-created svc_acct. Here's an example:
324 $cust_main->insert( {}, [ $email, 'POST' ] );
326 Currently available options are: I<depend_jobnum>, I<noexport>,
327 I<tax_exemption> and I<prospectnum>.
329 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
330 on the supplied jobnum (they will not run until the specific job completes).
331 This can be used to defer provisioning until some action completes (such
332 as running the customer's credit card successfully).
334 The I<noexport> option is deprecated. If I<noexport> is set true, no
335 provisioning jobs (exports) are scheduled. (You can schedule them later with
336 the B<reexport> method.)
338 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
339 of tax names and exemption numbers. FS::cust_main_exemption records will be
340 created and inserted.
342 If I<prospectnum> is set, moves contacts and locations from that prospect.
348 my $cust_pkgs = @_ ? shift : {};
349 my $invoicing_list = @_ ? shift : '';
351 warn "$me insert called with options ".
352 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
355 local $SIG{HUP} = 'IGNORE';
356 local $SIG{INT} = 'IGNORE';
357 local $SIG{QUIT} = 'IGNORE';
358 local $SIG{TERM} = 'IGNORE';
359 local $SIG{TSTP} = 'IGNORE';
360 local $SIG{PIPE} = 'IGNORE';
362 my $oldAutoCommit = $FS::UID::AutoCommit;
363 local $FS::UID::AutoCommit = 0;
366 my $prepay_identifier = '';
367 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
369 if ( $self->payby eq 'PREPAY' ) {
371 $self->payby('BILL');
372 $prepay_identifier = $self->payinfo;
375 warn " looking up prepaid card $prepay_identifier\n"
378 my $error = $self->get_prepay( $prepay_identifier,
379 'amount_ref' => \$amount,
380 'seconds_ref' => \$seconds,
381 'upbytes_ref' => \$upbytes,
382 'downbytes_ref' => \$downbytes,
383 'totalbytes_ref' => \$totalbytes,
386 $dbh->rollback if $oldAutoCommit;
387 #return "error applying prepaid card (transaction rolled back): $error";
391 $payby = 'PREP' if $amount;
393 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|PPAL)$/ ) {
396 $self->payby('BILL');
397 $amount = $self->paid;
402 foreach my $l (qw(bill_location ship_location)) {
403 my $loc = delete $self->hashref->{$l};
404 # XXX if we're moving a prospect's locations, do that here
409 if ( !$loc->locationnum ) {
410 # warn the location that we're going to insert it with no custnum
411 $loc->set(custnum_pending => 1);
412 warn " inserting $l\n"
414 my $error = $loc->insert;
416 $dbh->rollback if $oldAutoCommit;
417 my $label = $l eq 'ship_location' ? 'service' : 'billing';
418 return "$error (in $label location)";
421 elsif ( ($loc->custnum || 0) > 0 or $loc->prospectnum ) {
422 # then it somehow belongs to another customer--shouldn't happen
423 $dbh->rollback if $oldAutoCommit;
424 return "$l belongs to customer ".$loc->custnum;
426 # else it already belongs to this customer
427 # (happens when ship_location is identical to bill_location)
429 $self->set($l.'num', $loc->locationnum);
431 if ( $self->get($l.'num') eq '' ) {
432 $dbh->rollback if $oldAutoCommit;
437 warn " inserting $self\n"
440 $self->signupdate(time) unless $self->signupdate;
442 $self->auto_agent_custid()
443 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
445 my $error = $self->SUPER::insert;
447 $dbh->rollback if $oldAutoCommit;
448 #return "inserting cust_main record (transaction rolled back): $error";
452 # now set cust_location.custnum
453 foreach my $l (qw(bill_location ship_location)) {
454 warn " setting $l.custnum\n"
457 unless ( $loc->custnum ) {
458 $loc->set(custnum => $self->custnum);
459 $error ||= $loc->replace;
463 $dbh->rollback if $oldAutoCommit;
464 return "error setting $l custnum: $error";
468 warn " setting invoicing list\n"
471 if ( $invoicing_list ) {
472 $error = $self->check_invoicing_list( $invoicing_list );
474 $dbh->rollback if $oldAutoCommit;
475 #return "checking invoicing_list (transaction rolled back): $error";
478 $self->invoicing_list( $invoicing_list );
481 warn " setting customer tags\n"
484 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
485 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
486 'custnum' => $self->custnum };
487 my $error = $cust_tag->insert;
489 $dbh->rollback if $oldAutoCommit;
494 my $prospectnum = delete $options{'prospectnum'};
495 if ( $prospectnum ) {
497 warn " moving contacts and locations from prospect $prospectnum\n"
501 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
502 unless ( $prospect_main ) {
503 $dbh->rollback if $oldAutoCommit;
504 return "Unknown prospectnum $prospectnum";
506 $prospect_main->custnum($self->custnum);
507 $prospect_main->disabled('Y');
508 my $error = $prospect_main->replace;
510 $dbh->rollback if $oldAutoCommit;
514 my @contact = $prospect_main->contact;
515 my @cust_location = $prospect_main->cust_location;
516 my @qual = $prospect_main->qual;
518 foreach my $r ( @contact, @cust_location, @qual ) {
520 $r->custnum($self->custnum);
521 my $error = $r->replace;
523 $dbh->rollback if $oldAutoCommit;
530 warn " setting cust_main_exemption\n"
533 my $tax_exemption = delete $options{'tax_exemption'};
534 if ( $tax_exemption ) {
536 $tax_exemption = { map { $_ => '' } @$tax_exemption }
537 if ref($tax_exemption) eq 'ARRAY';
539 foreach my $taxname ( keys %$tax_exemption ) {
540 my $cust_main_exemption = new FS::cust_main_exemption {
541 'custnum' => $self->custnum,
542 'taxname' => $taxname,
543 'exempt_number' => $tax_exemption->{$taxname},
545 my $error = $cust_main_exemption->insert;
547 $dbh->rollback if $oldAutoCommit;
548 return "inserting cust_main_exemption (transaction rolled back): $error";
553 warn " ordering packages\n"
556 $error = $self->order_pkgs( $cust_pkgs,
558 'seconds_ref' => \$seconds,
559 'upbytes_ref' => \$upbytes,
560 'downbytes_ref' => \$downbytes,
561 'totalbytes_ref' => \$totalbytes,
564 $dbh->rollback if $oldAutoCommit;
569 $dbh->rollback if $oldAutoCommit;
570 return "No svc_acct record to apply pre-paid time";
572 if ( $upbytes || $downbytes || $totalbytes ) {
573 $dbh->rollback if $oldAutoCommit;
574 return "No svc_acct record to apply pre-paid data";
578 warn " inserting initial $payby payment of $amount\n"
580 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
582 $dbh->rollback if $oldAutoCommit;
583 return "inserting payment (transaction rolled back): $error";
587 unless ( $import || $skip_fuzzyfiles ) {
588 warn " queueing fuzzyfiles update\n"
590 $error = $self->queue_fuzzyfiles_update;
592 $dbh->rollback if $oldAutoCommit;
593 return "updating fuzzy search cache: $error";
597 # FS::geocode_Mixin::after_insert or something?
598 if ( $conf->config('tax_district_method') and !$import ) {
599 # if anything non-empty, try to look it up
600 my $queue = new FS::queue {
601 'job' => 'FS::geocode_Mixin::process_district_update',
602 'custnum' => $self->custnum,
604 my $error = $queue->insert( ref($self), $self->custnum );
606 $dbh->rollback if $oldAutoCommit;
607 return "queueing tax district update: $error";
612 warn " exporting\n" if $DEBUG > 1;
614 my $export_args = $options{'export_args'} || [];
617 map qsearch( 'part_export', {exportnum=>$_} ),
618 $conf->config('cust_main-exports'); #, $agentnum
620 foreach my $part_export ( @part_export ) {
621 my $error = $part_export->export_insert($self, @$export_args);
623 $dbh->rollback if $oldAutoCommit;
624 return "exporting to ". $part_export->exporttype.
625 " (transaction rolled back): $error";
629 #foreach my $depend_jobnum ( @$depend_jobnums ) {
630 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
632 # foreach my $jobnum ( @jobnums ) {
633 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
634 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
636 # my $error = $queue->depend_insert($depend_jobnum);
638 # $dbh->rollback if $oldAutoCommit;
639 # return "error queuing job dependancy: $error";
646 #if ( exists $options{'jobnums'} ) {
647 # push @{ $options{'jobnums'} }, @jobnums;
650 warn " insert complete; committing transaction\n"
653 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
658 use File::CounterFile;
659 sub auto_agent_custid {
662 my $format = $conf->config('cust_main-auto_agent_custid');
664 if ( $format eq '1YMMXXXXXXXX' ) {
666 my $counter = new File::CounterFile 'cust_main.agent_custid';
669 my $ym = 100000000000 + time2str('%y%m00000000', time);
670 if ( $ym > $counter->value ) {
671 $counter->{'value'} = $agent_custid = $ym;
672 $counter->{'updated'} = 1;
674 $agent_custid = $counter->inc;
680 die "Unknown cust_main-auto_agent_custid format: $format";
683 $self->agent_custid($agent_custid);
687 =item PACKAGE METHODS
689 Documentation on customer package methods has been moved to
690 L<FS::cust_main::Packages>.
692 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
694 Recharges this (existing) customer with the specified prepaid card (see
695 L<FS::prepay_credit>), specified either by I<identifier> or as an
696 FS::prepay_credit object. If there is an error, returns the error, otherwise
699 Optionally, five scalar references can be passed as well. They will have their
700 values filled in with the amount, number of seconds, and number of upload,
701 download, and total bytes applied by this prepaid card.
705 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
706 #the only place that uses these args
707 sub recharge_prepay {
708 my( $self, $prepay_credit, $amountref, $secondsref,
709 $upbytesref, $downbytesref, $totalbytesref ) = @_;
711 local $SIG{HUP} = 'IGNORE';
712 local $SIG{INT} = 'IGNORE';
713 local $SIG{QUIT} = 'IGNORE';
714 local $SIG{TERM} = 'IGNORE';
715 local $SIG{TSTP} = 'IGNORE';
716 local $SIG{PIPE} = 'IGNORE';
718 my $oldAutoCommit = $FS::UID::AutoCommit;
719 local $FS::UID::AutoCommit = 0;
722 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
724 my $error = $self->get_prepay( $prepay_credit,
725 'amount_ref' => \$amount,
726 'seconds_ref' => \$seconds,
727 'upbytes_ref' => \$upbytes,
728 'downbytes_ref' => \$downbytes,
729 'totalbytes_ref' => \$totalbytes,
731 || $self->increment_seconds($seconds)
732 || $self->increment_upbytes($upbytes)
733 || $self->increment_downbytes($downbytes)
734 || $self->increment_totalbytes($totalbytes)
735 || $self->insert_cust_pay_prepay( $amount,
737 ? $prepay_credit->identifier
742 $dbh->rollback if $oldAutoCommit;
746 if ( defined($amountref) ) { $$amountref = $amount; }
747 if ( defined($secondsref) ) { $$secondsref = $seconds; }
748 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
749 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
750 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
752 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
757 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
759 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
760 specified either by I<identifier> or as an FS::prepay_credit object.
762 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
763 incremented by the values of the prepaid card.
765 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
766 check or set this customer's I<agentnum>.
768 If there is an error, returns the error, otherwise returns false.
774 my( $self, $prepay_credit, %opt ) = @_;
776 local $SIG{HUP} = 'IGNORE';
777 local $SIG{INT} = 'IGNORE';
778 local $SIG{QUIT} = 'IGNORE';
779 local $SIG{TERM} = 'IGNORE';
780 local $SIG{TSTP} = 'IGNORE';
781 local $SIG{PIPE} = 'IGNORE';
783 my $oldAutoCommit = $FS::UID::AutoCommit;
784 local $FS::UID::AutoCommit = 0;
787 unless ( ref($prepay_credit) ) {
789 my $identifier = $prepay_credit;
791 $prepay_credit = qsearchs(
793 { 'identifier' => $identifier },
798 unless ( $prepay_credit ) {
799 $dbh->rollback if $oldAutoCommit;
800 return "Invalid prepaid card: ". $identifier;
805 if ( $prepay_credit->agentnum ) {
806 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
807 $dbh->rollback if $oldAutoCommit;
808 return "prepaid card not valid for agent ". $self->agentnum;
810 $self->agentnum($prepay_credit->agentnum);
813 my $error = $prepay_credit->delete;
815 $dbh->rollback if $oldAutoCommit;
816 return "removing prepay_credit (transaction rolled back): $error";
819 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
820 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
822 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
827 =item increment_upbytes SECONDS
829 Updates this customer's single or primary account (see L<FS::svc_acct>) by
830 the specified number of upbytes. If there is an error, returns the error,
831 otherwise returns false.
835 sub increment_upbytes {
836 _increment_column( shift, 'upbytes', @_);
839 =item increment_downbytes SECONDS
841 Updates this customer's single or primary account (see L<FS::svc_acct>) by
842 the specified number of downbytes. If there is an error, returns the error,
843 otherwise returns false.
847 sub increment_downbytes {
848 _increment_column( shift, 'downbytes', @_);
851 =item increment_totalbytes SECONDS
853 Updates this customer's single or primary account (see L<FS::svc_acct>) by
854 the specified number of totalbytes. If there is an error, returns the error,
855 otherwise returns false.
859 sub increment_totalbytes {
860 _increment_column( shift, 'totalbytes', @_);
863 =item increment_seconds SECONDS
865 Updates this customer's single or primary account (see L<FS::svc_acct>) by
866 the specified number of seconds. If there is an error, returns the error,
867 otherwise returns false.
871 sub increment_seconds {
872 _increment_column( shift, 'seconds', @_);
875 =item _increment_column AMOUNT
877 Updates this customer's single or primary account (see L<FS::svc_acct>) by
878 the specified number of seconds or bytes. If there is an error, returns
879 the error, otherwise returns false.
883 sub _increment_column {
884 my( $self, $column, $amount ) = @_;
885 warn "$me increment_column called: $column, $amount\n"
888 return '' unless $amount;
890 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
891 $self->ncancelled_pkgs;
894 return 'No packages with primary or single services found'.
895 ' to apply pre-paid time';
896 } elsif ( scalar(@cust_pkg) > 1 ) {
897 #maybe have a way to specify the package/account?
898 return 'Multiple packages found to apply pre-paid time';
901 my $cust_pkg = $cust_pkg[0];
902 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
906 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
909 return 'No account found to apply pre-paid time';
910 } elsif ( scalar(@cust_svc) > 1 ) {
911 return 'Multiple accounts found to apply pre-paid time';
914 my $svc_acct = $cust_svc[0]->svc_x;
915 warn " found service svcnum ". $svc_acct->pkgnum.
916 ' ('. $svc_acct->email. ")\n"
919 $column = "increment_$column";
920 $svc_acct->$column($amount);
924 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
926 Inserts a prepayment in the specified amount for this customer. An optional
927 second argument can specify the prepayment identifier for tracking purposes.
928 If there is an error, returns the error, otherwise returns false.
932 sub insert_cust_pay_prepay {
933 shift->insert_cust_pay('PREP', @_);
936 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
938 Inserts a cash payment in the specified amount for this customer. An optional
939 second argument can specify the payment identifier for tracking purposes.
940 If there is an error, returns the error, otherwise returns false.
944 sub insert_cust_pay_cash {
945 shift->insert_cust_pay('CASH', @_);
948 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
950 Inserts a Western Union payment in the specified amount for this customer. An
951 optional second argument can specify the prepayment identifier for tracking
952 purposes. If there is an error, returns the error, otherwise returns false.
956 sub insert_cust_pay_west {
957 shift->insert_cust_pay('WEST', @_);
960 sub insert_cust_pay {
961 my( $self, $payby, $amount ) = splice(@_, 0, 3);
962 my $payinfo = scalar(@_) ? shift : '';
964 my $cust_pay = new FS::cust_pay {
965 'custnum' => $self->custnum,
966 'paid' => sprintf('%.2f', $amount),
967 #'_date' => #date the prepaid card was purchased???
969 'payinfo' => $payinfo,
977 This method is deprecated. See the I<depend_jobnum> option to the insert and
978 order_pkgs methods for a better way to defer provisioning.
980 Re-schedules all exports by calling the B<reexport> method of all associated
981 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
982 otherwise returns false.
989 carp "WARNING: FS::cust_main::reexport is deprectated; ".
990 "use the depend_jobnum option to insert or order_pkgs to delay export";
992 local $SIG{HUP} = 'IGNORE';
993 local $SIG{INT} = 'IGNORE';
994 local $SIG{QUIT} = 'IGNORE';
995 local $SIG{TERM} = 'IGNORE';
996 local $SIG{TSTP} = 'IGNORE';
997 local $SIG{PIPE} = 'IGNORE';
999 my $oldAutoCommit = $FS::UID::AutoCommit;
1000 local $FS::UID::AutoCommit = 0;
1003 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1004 my $error = $cust_pkg->reexport;
1006 $dbh->rollback if $oldAutoCommit;
1011 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1016 =item delete [ OPTION => VALUE ... ]
1018 This deletes the customer. If there is an error, returns the error, otherwise
1021 This will completely remove all traces of the customer record. This is not
1022 what you want when a customer cancels service; for that, cancel all of the
1023 customer's packages (see L</cancel>).
1025 If the customer has any uncancelled packages, you need to pass a new (valid)
1026 customer number for those packages to be transferred to, as the "new_customer"
1027 option. Cancelled packages will be deleted. Did I mention that this is NOT
1028 what you want when a customer cancels service and that you really should be
1029 looking at L<FS::cust_pkg/cancel>?
1031 You can't delete a customer with invoices (see L<FS::cust_bill>),
1032 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1033 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1034 set the "delete_financials" option to a true value.
1039 my( $self, %opt ) = @_;
1041 local $SIG{HUP} = 'IGNORE';
1042 local $SIG{INT} = 'IGNORE';
1043 local $SIG{QUIT} = 'IGNORE';
1044 local $SIG{TERM} = 'IGNORE';
1045 local $SIG{TSTP} = 'IGNORE';
1046 local $SIG{PIPE} = 'IGNORE';
1048 my $oldAutoCommit = $FS::UID::AutoCommit;
1049 local $FS::UID::AutoCommit = 0;
1052 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1053 $dbh->rollback if $oldAutoCommit;
1054 return "Can't delete a master agent customer";
1057 #use FS::access_user
1058 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1059 $dbh->rollback if $oldAutoCommit;
1060 return "Can't delete a master employee customer";
1063 tie my %financial_tables, 'Tie::IxHash',
1064 'cust_bill' => 'invoices',
1065 'cust_statement' => 'statements',
1066 'cust_credit' => 'credits',
1067 'cust_pay' => 'payments',
1068 'cust_refund' => 'refunds',
1071 foreach my $table ( keys %financial_tables ) {
1073 my @records = $self->$table();
1075 if ( @records && ! $opt{'delete_financials'} ) {
1076 $dbh->rollback if $oldAutoCommit;
1077 return "Can't delete a customer with ". $financial_tables{$table};
1080 foreach my $record ( @records ) {
1081 my $error = $record->delete;
1083 $dbh->rollback if $oldAutoCommit;
1084 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1090 my @cust_pkg = $self->ncancelled_pkgs;
1092 my $new_custnum = $opt{'new_custnum'};
1093 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1094 $dbh->rollback if $oldAutoCommit;
1095 return "Invalid new customer number: $new_custnum";
1097 foreach my $cust_pkg ( @cust_pkg ) {
1098 my %hash = $cust_pkg->hash;
1099 $hash{'custnum'} = $new_custnum;
1100 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1101 my $error = $new_cust_pkg->replace($cust_pkg,
1102 options => { $cust_pkg->options },
1105 $dbh->rollback if $oldAutoCommit;
1110 my @cancelled_cust_pkg = $self->all_pkgs;
1111 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1112 my $error = $cust_pkg->delete;
1114 $dbh->rollback if $oldAutoCommit;
1119 #cust_tax_adjustment in financials?
1120 #cust_pay_pending? ouch
1122 foreach my $table (qw(
1123 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1124 cust_location cust_main_note cust_tax_adjustment
1125 cust_pay_void cust_pay_batch queue cust_tax_exempt
1127 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1128 my $error = $record->delete;
1130 $dbh->rollback if $oldAutoCommit;
1136 my $sth = $dbh->prepare(
1137 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1139 my $errstr = $dbh->errstr;
1140 $dbh->rollback if $oldAutoCommit;
1143 $sth->execute($self->custnum) or do {
1144 my $errstr = $sth->errstr;
1145 $dbh->rollback if $oldAutoCommit;
1151 my $ticket_dbh = '';
1152 if ($conf->config('ticket_system') eq 'RT_Internal') {
1154 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1155 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1156 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1157 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1160 if ( $ticket_dbh ) {
1162 my $ticket_sth = $ticket_dbh->prepare(
1163 'DELETE FROM Links WHERE Target = ?'
1165 my $errstr = $ticket_dbh->errstr;
1166 $dbh->rollback if $oldAutoCommit;
1169 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1171 my $errstr = $ticket_sth->errstr;
1172 $dbh->rollback if $oldAutoCommit;
1176 #check and see if the customer is the only link on the ticket, and
1177 #if so, set the ticket to deleted status in RT?
1178 #maybe someday, for now this will at least fix tickets not displaying
1182 #delete the customer record
1184 my $error = $self->SUPER::delete;
1186 $dbh->rollback if $oldAutoCommit;
1190 # cust_main exports!
1192 #my $export_args = $options{'export_args'} || [];
1195 map qsearch( 'part_export', {exportnum=>$_} ),
1196 $conf->config('cust_main-exports'); #, $agentnum
1198 foreach my $part_export ( @part_export ) {
1199 my $error = $part_export->export_delete( $self ); #, @$export_args);
1201 $dbh->rollback if $oldAutoCommit;
1202 return "exporting to ". $part_export->exporttype.
1203 " (transaction rolled back): $error";
1207 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1212 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1214 This merges this customer into the provided new custnum, and then deletes the
1215 customer. If there is an error, returns the error, otherwise returns false.
1217 The source customer's name, company name, phone numbers, agent,
1218 referring customer, customer class, advertising source, order taker, and
1219 billing information (except balance) are discarded.
1221 All packages are moved to the target customer. Packages with package locations
1222 are preserved. Packages without package locations are moved to a new package
1223 location with the source customer's service/shipping address.
1225 All invoices, statements, payments, credits and refunds are moved to the target
1226 customer. The source customer's balance is added to the target customer.
1228 All notes, attachments, tickets and customer tags are moved to the target
1231 Change history is not currently moved.
1236 my( $self, $new_custnum, %opt ) = @_;
1238 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1240 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1241 or return "Invalid new customer number: $new_custnum";
1243 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1244 if $self->agentnum != $new_cust_main->agentnum
1245 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1247 local $SIG{HUP} = 'IGNORE';
1248 local $SIG{INT} = 'IGNORE';
1249 local $SIG{QUIT} = 'IGNORE';
1250 local $SIG{TERM} = 'IGNORE';
1251 local $SIG{TSTP} = 'IGNORE';
1252 local $SIG{PIPE} = 'IGNORE';
1254 my $oldAutoCommit = $FS::UID::AutoCommit;
1255 local $FS::UID::AutoCommit = 0;
1258 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1259 $dbh->rollback if $oldAutoCommit;
1260 return "Can't merge a master agent customer";
1263 #use FS::access_user
1264 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1265 $dbh->rollback if $oldAutoCommit;
1266 return "Can't merge a master employee customer";
1269 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1270 'status' => { op=>'!=', value=>'done' },
1274 $dbh->rollback if $oldAutoCommit;
1275 return "Can't merge a customer with pending payments";
1278 tie my %financial_tables, 'Tie::IxHash',
1279 'cust_bill' => 'invoices',
1280 'cust_bill_void' => 'voided invoices',
1281 'cust_statement' => 'statements',
1282 'cust_credit' => 'credits',
1283 'cust_pay' => 'payments',
1284 'cust_pay_void' => 'voided payments',
1285 'cust_refund' => 'refunds',
1288 foreach my $table ( keys %financial_tables ) {
1290 my @records = $self->$table();
1292 foreach my $record ( @records ) {
1293 $record->custnum($new_custnum);
1294 my $error = $record->replace;
1296 $dbh->rollback if $oldAutoCommit;
1297 return "Error merging ". $financial_tables{$table}. ": $error\n";
1303 my $name = $self->ship_name; #?
1305 my $locationnum = '';
1306 foreach my $cust_pkg ( $self->all_pkgs ) {
1307 $cust_pkg->custnum($new_custnum);
1309 unless ( $cust_pkg->locationnum ) {
1310 unless ( $locationnum ) {
1311 my $cust_location = new FS::cust_location {
1312 $self->location_hash,
1313 'custnum' => $new_custnum,
1315 my $error = $cust_location->insert;
1317 $dbh->rollback if $oldAutoCommit;
1320 $locationnum = $cust_location->locationnum;
1322 $cust_pkg->locationnum($locationnum);
1325 my $error = $cust_pkg->replace;
1327 $dbh->rollback if $oldAutoCommit;
1331 # add customer (ship) name to svc_phone.phone_name if blank
1332 my @cust_svc = $cust_pkg->cust_svc;
1333 foreach my $cust_svc (@cust_svc) {
1334 my($label, $value, $svcdb) = $cust_svc->label;
1335 next unless $svcdb eq 'svc_phone';
1336 my $svc_phone = $cust_svc->svc_x;
1337 next if $svc_phone->phone_name;
1338 $svc_phone->phone_name($name);
1339 my $error = $svc_phone->replace;
1341 $dbh->rollback if $oldAutoCommit;
1349 # cust_tax_exempt (texas tax exemptions)
1350 # cust_recon (some sort of not-well understood thing for OnPac)
1352 #these are moved over
1353 foreach my $table (qw(
1354 cust_tag cust_location contact cust_attachment cust_main_note
1355 cust_tax_adjustment cust_pay_batch queue
1357 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1358 $record->custnum($new_custnum);
1359 my $error = $record->replace;
1361 $dbh->rollback if $oldAutoCommit;
1367 #these aren't preserved
1368 foreach my $table (qw(
1369 cust_main_exemption cust_main_invoice
1371 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1372 my $error = $record->delete;
1374 $dbh->rollback if $oldAutoCommit;
1381 my $sth = $dbh->prepare(
1382 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1384 my $errstr = $dbh->errstr;
1385 $dbh->rollback if $oldAutoCommit;
1388 $sth->execute($new_custnum, $self->custnum) or do {
1389 my $errstr = $sth->errstr;
1390 $dbh->rollback if $oldAutoCommit;
1396 my $ticket_dbh = '';
1397 if ($conf->config('ticket_system') eq 'RT_Internal') {
1399 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1400 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1401 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1402 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1405 if ( $ticket_dbh ) {
1407 my $ticket_sth = $ticket_dbh->prepare(
1408 'UPDATE Links SET Target = ? WHERE Target = ?'
1410 my $errstr = $ticket_dbh->errstr;
1411 $dbh->rollback if $oldAutoCommit;
1414 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1415 'freeside://freeside/cust_main/'.$self->custnum)
1417 my $errstr = $ticket_sth->errstr;
1418 $dbh->rollback if $oldAutoCommit;
1424 #delete the customer record
1426 my $error = $self->delete;
1428 $dbh->rollback if $oldAutoCommit;
1432 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1437 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1439 Replaces the OLD_RECORD with this one in the database. If there is an error,
1440 returns the error, otherwise returns false.
1442 To change the customer's address, set the pseudo-fields C<bill_location> and
1443 C<ship_location>. The address will still only change if at least one of the
1444 address fields differs from the existing values.
1446 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1447 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1448 expected and rollback the entire transaction; it is not necessary to call
1449 check_invoicing_list first. Here's an example:
1451 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1453 Currently available options are: I<tax_exemption>.
1455 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1456 of tax names and exemption numbers. FS::cust_main_exemption records will be
1457 deleted and inserted as appropriate.
1464 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1466 : $self->replace_old;
1470 warn "$me replace called\n"
1473 my $curuser = $FS::CurrentUser::CurrentUser;
1474 if ( $self->payby eq 'COMP'
1475 && $self->payby ne $old->payby
1476 && ! $curuser->access_right('Complimentary customer')
1479 return "You are not permitted to create complimentary accounts.";
1482 local($ignore_expired_card) = 1
1483 if $old->payby =~ /^(CARD|DCRD)$/
1484 && $self->payby =~ /^(CARD|DCRD)$/
1485 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1487 local($ignore_banned_card) = 1
1488 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1489 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1490 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1492 return "Invoicing locale is required"
1495 && $conf->exists('cust_main-require_locale');
1497 local $SIG{HUP} = 'IGNORE';
1498 local $SIG{INT} = 'IGNORE';
1499 local $SIG{QUIT} = 'IGNORE';
1500 local $SIG{TERM} = 'IGNORE';
1501 local $SIG{TSTP} = 'IGNORE';
1502 local $SIG{PIPE} = 'IGNORE';
1504 my $oldAutoCommit = $FS::UID::AutoCommit;
1505 local $FS::UID::AutoCommit = 0;
1508 for my $l (qw(bill_location ship_location)) {
1509 my $old_loc = $old->$l;
1510 my $new_loc = $self->$l;
1512 # find the existing location if there is one
1513 $new_loc->set('custnum' => $self->custnum);
1514 my $error = $new_loc->find_or_insert;
1516 $dbh->rollback if $oldAutoCommit;
1519 $self->set($l.'num', $new_loc->locationnum);
1522 # replace the customer record
1523 my $error = $self->SUPER::replace($old);
1526 $dbh->rollback if $oldAutoCommit;
1530 # now move packages to the new service location
1531 $self->set('ship_location', ''); #flush cache
1532 if ( $old->ship_locationnum and # should only be null during upgrade...
1533 $old->ship_locationnum != $self->ship_locationnum ) {
1534 $error = $old->ship_location->move_to($self->ship_location);
1536 $dbh->rollback if $oldAutoCommit;
1540 # don't move packages based on the billing location, but
1541 # disable it if it's no longer in use
1542 if ( $old->bill_locationnum and
1543 $old->bill_locationnum != $self->bill_locationnum ) {
1544 $error = $old->bill_location->disable_if_unused;
1546 $dbh->rollback if $oldAutoCommit;
1551 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1552 my $invoicing_list = shift @param;
1553 $error = $self->check_invoicing_list( $invoicing_list );
1555 $dbh->rollback if $oldAutoCommit;
1558 $self->invoicing_list( $invoicing_list );
1561 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1563 #this could be more efficient than deleting and re-inserting, if it matters
1564 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1565 my $error = $cust_tag->delete;
1567 $dbh->rollback if $oldAutoCommit;
1571 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1572 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1573 'custnum' => $self->custnum };
1574 my $error = $cust_tag->insert;
1576 $dbh->rollback if $oldAutoCommit;
1583 my %options = @param;
1585 my $tax_exemption = delete $options{'tax_exemption'};
1586 if ( $tax_exemption ) {
1588 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1589 if ref($tax_exemption) eq 'ARRAY';
1591 my %cust_main_exemption =
1592 map { $_->taxname => $_ }
1593 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1595 foreach my $taxname ( keys %$tax_exemption ) {
1597 if ( $cust_main_exemption{$taxname} &&
1598 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1601 delete $cust_main_exemption{$taxname};
1605 my $cust_main_exemption = new FS::cust_main_exemption {
1606 'custnum' => $self->custnum,
1607 'taxname' => $taxname,
1608 'exempt_number' => $tax_exemption->{$taxname},
1610 my $error = $cust_main_exemption->insert;
1612 $dbh->rollback if $oldAutoCommit;
1613 return "inserting cust_main_exemption (transaction rolled back): $error";
1617 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1618 my $error = $cust_main_exemption->delete;
1620 $dbh->rollback if $oldAutoCommit;
1621 return "deleting cust_main_exemption (transaction rolled back): $error";
1627 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1628 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1629 && $self->get('payinfo') !~ /^99\d{14}$/
1631 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1636 # card/check/lec info has changed, want to retry realtime_ invoice events
1637 my $error = $self->retry_realtime;
1639 $dbh->rollback if $oldAutoCommit;
1644 unless ( $import || $skip_fuzzyfiles ) {
1645 $error = $self->queue_fuzzyfiles_update;
1647 $dbh->rollback if $oldAutoCommit;
1648 return "updating fuzzy search cache: $error";
1652 # tax district update in cust_location
1654 # cust_main exports!
1656 my $export_args = $options{'export_args'} || [];
1659 map qsearch( 'part_export', {exportnum=>$_} ),
1660 $conf->config('cust_main-exports'); #, $agentnum
1662 foreach my $part_export ( @part_export ) {
1663 my $error = $part_export->export_replace( $self, $old, @$export_args);
1665 $dbh->rollback if $oldAutoCommit;
1666 return "exporting to ". $part_export->exporttype.
1667 " (transaction rolled back): $error";
1671 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1676 =item queue_fuzzyfiles_update
1678 Used by insert & replace to update the fuzzy search cache
1682 use FS::cust_main::Search;
1683 sub queue_fuzzyfiles_update {
1686 local $SIG{HUP} = 'IGNORE';
1687 local $SIG{INT} = 'IGNORE';
1688 local $SIG{QUIT} = 'IGNORE';
1689 local $SIG{TERM} = 'IGNORE';
1690 local $SIG{TSTP} = 'IGNORE';
1691 local $SIG{PIPE} = 'IGNORE';
1693 my $oldAutoCommit = $FS::UID::AutoCommit;
1694 local $FS::UID::AutoCommit = 0;
1697 my @locations = $self->bill_location;
1698 push @locations, $self->ship_location if $self->has_ship_address;
1699 foreach my $location (@locations) {
1700 my $queue = new FS::queue {
1701 'job' => 'FS::cust_main::Search::append_fuzzyfiles'
1703 my @args = map $location->get($_), @FS::cust_main::Search::fuzzyfields;
1704 my $error = $queue->insert( @args );
1706 $dbh->rollback if $oldAutoCommit;
1707 return "queueing job (transaction rolled back): $error";
1711 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1718 Checks all fields to make sure this is a valid customer record. If there is
1719 an error, returns the error, otherwise returns false. Called by the insert
1720 and replace methods.
1727 warn "$me check BEFORE: \n". $self->_dump
1731 $self->ut_numbern('custnum')
1732 || $self->ut_number('agentnum')
1733 || $self->ut_textn('agent_custid')
1734 || $self->ut_number('refnum')
1735 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1736 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1737 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1738 || $self->ut_textn('custbatch')
1739 || $self->ut_name('last')
1740 || $self->ut_name('first')
1741 || $self->ut_snumbern('signupdate')
1742 || $self->ut_snumbern('birthdate')
1743 || $self->ut_snumbern('spouse_birthdate')
1744 || $self->ut_snumbern('anniversary_date')
1745 || $self->ut_textn('company')
1746 || $self->ut_anything('comments')
1747 || $self->ut_numbern('referral_custnum')
1748 || $self->ut_textn('stateid')
1749 || $self->ut_textn('stateid_state')
1750 || $self->ut_textn('invoice_terms')
1751 || $self->ut_floatn('cdr_termination_percentage')
1752 || $self->ut_floatn('credit_limit')
1753 || $self->ut_numbern('billday')
1754 || $self->ut_numbern('prorate_day')
1755 || $self->ut_flag('edit_subject')
1756 || $self->ut_flag('calling_list_exempt')
1757 || $self->ut_flag('invoice_noemail')
1758 || $self->ut_flag('message_noemail')
1759 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1762 my $company = $self->company;
1763 $company =~ s/^\s+//;
1764 $company =~ s/\s+$//;
1765 $company =~ s/\s+/ /g;
1766 $self->company($company);
1768 #barf. need message catalogs. i18n. etc.
1769 $error .= "Please select an advertising source."
1770 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1771 return $error if $error;
1773 return "Unknown agent"
1774 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1776 return "Unknown refnum"
1777 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1779 return "Unknown referring custnum: ". $self->referral_custnum
1780 unless ! $self->referral_custnum
1781 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1783 if ( $self->ss eq '' ) {
1788 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1789 or return "Illegal social security number: ". $self->ss;
1790 $self->ss("$1-$2-$3");
1793 # cust_main_county verification now handled by cust_location check
1796 $self->ut_phonen('daytime', $self->country)
1797 || $self->ut_phonen('night', $self->country)
1798 || $self->ut_phonen('fax', $self->country)
1799 || $self->ut_phonen('mobile', $self->country)
1801 return $error if $error;
1803 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1805 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1808 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1810 : FS::Msgcat::_gettext('daytime');
1811 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1813 : FS::Msgcat::_gettext('night');
1815 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1817 : FS::Msgcat::_gettext('mobile');
1819 return "$daytime_label, $night_label or $mobile_label is required"
1823 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1824 # or return "Illegal payby: ". $self->payby;
1826 FS::payby->can_payby($self->table, $self->payby)
1827 or return "Illegal payby: ". $self->payby;
1829 $error = $self->ut_numbern('paystart_month')
1830 || $self->ut_numbern('paystart_year')
1831 || $self->ut_numbern('payissue')
1832 || $self->ut_textn('paytype')
1834 return $error if $error;
1836 if ( $self->payip eq '' ) {
1839 $error = $self->ut_ip('payip');
1840 return $error if $error;
1843 # If it is encrypted and the private key is not availaible then we can't
1844 # check the credit card.
1845 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1847 # Need some kind of global flag to accept invalid cards, for testing
1849 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1851 my $payinfo = $self->payinfo;
1852 $payinfo =~ s/\D//g;
1853 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1854 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1856 $self->payinfo($payinfo);
1858 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1860 return gettext('unknown_card_type')
1861 if $self->payinfo !~ /^99\d{14}$/ #token
1862 && cardtype($self->payinfo) eq "Unknown";
1864 unless ( $ignore_banned_card ) {
1865 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1867 if ( $ban->bantype eq 'warn' ) {
1868 #or others depending on value of $ban->reason ?
1869 return '_duplicate_card'.
1870 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1871 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1872 ' (ban# '. $ban->bannum. ')'
1873 unless $self->override_ban_warn;
1875 return 'Banned credit card: banned on '.
1876 time2str('%a %h %o at %r', $ban->_date).
1877 ' by '. $ban->otaker.
1878 ' (ban# '. $ban->bannum. ')';
1883 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1884 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1885 $self->paycvv =~ /^(\d{4})$/
1886 or return "CVV2 (CID) for American Express cards is four digits.";
1889 $self->paycvv =~ /^(\d{3})$/
1890 or return "CVV2 (CVC2/CID) is three digits.";
1897 my $cardtype = cardtype($payinfo);
1898 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1900 return "Start date or issue number is required for $cardtype cards"
1901 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1903 return "Start month must be between 1 and 12"
1904 if $self->paystart_month
1905 and $self->paystart_month < 1 || $self->paystart_month > 12;
1907 return "Start year must be 1990 or later"
1908 if $self->paystart_year
1909 and $self->paystart_year < 1990;
1911 return "Issue number must be beween 1 and 99"
1913 and $self->payissue < 1 || $self->payissue > 99;
1916 $self->paystart_month('');
1917 $self->paystart_year('');
1918 $self->payissue('');
1921 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1923 my $payinfo = $self->payinfo;
1924 $payinfo =~ s/[^\d\@\.]//g;
1925 if ( $conf->config('echeck-country') eq 'CA' ) {
1926 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1927 or return 'invalid echeck account@branch.bank';
1928 $payinfo = "$1\@$2.$3";
1929 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1930 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1931 $payinfo = "$1\@$2";
1933 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1934 $payinfo = "$1\@$2";
1936 $self->payinfo($payinfo);
1939 unless ( $ignore_banned_card ) {
1940 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1942 if ( $ban->bantype eq 'warn' ) {
1943 #or others depending on value of $ban->reason ?
1944 return '_duplicate_ach' unless $self->override_ban_warn;
1946 return 'Banned ACH account: banned on '.
1947 time2str('%a %h %o at %r', $ban->_date).
1948 ' by '. $ban->otaker.
1949 ' (ban# '. $ban->bannum. ')';
1954 } elsif ( $self->payby eq 'LECB' ) {
1956 my $payinfo = $self->payinfo;
1957 $payinfo =~ s/\D//g;
1958 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1960 $self->payinfo($payinfo);
1963 } elsif ( $self->payby eq 'BILL' ) {
1965 $error = $self->ut_textn('payinfo');
1966 return "Illegal P.O. number: ". $self->payinfo if $error;
1969 } elsif ( $self->payby eq 'COMP' ) {
1971 my $curuser = $FS::CurrentUser::CurrentUser;
1972 if ( ! $self->custnum
1973 && ! $curuser->access_right('Complimentary customer')
1976 return "You are not permitted to create complimentary accounts."
1979 $error = $self->ut_textn('payinfo');
1980 return "Illegal comp account issuer: ". $self->payinfo if $error;
1983 } elsif ( $self->payby eq 'PREPAY' ) {
1985 my $payinfo = $self->payinfo;
1986 $payinfo =~ s/\W//g; #anything else would just confuse things
1987 $self->payinfo($payinfo);
1988 $error = $self->ut_alpha('payinfo');
1989 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1990 return "Unknown prepayment identifier"
1991 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1996 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1997 return "Expiration date required"
1998 # shouldn't payinfo_check do this?
1999 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2003 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2004 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2005 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2006 ( $m, $y ) = ( $2, "19$1" );
2007 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2008 ( $m, $y ) = ( $3, "20$2" );
2010 return "Illegal expiration date: ". $self->paydate;
2012 $m = sprintf('%02d',$m);
2013 $self->paydate("$y-$m-01");
2014 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2015 return gettext('expired_card')
2017 && !$ignore_expired_card
2018 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2021 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2022 ( ! $conf->exists('require_cardname')
2023 || $self->payby !~ /^(CARD|DCRD)$/ )
2025 $self->payname( $self->first. " ". $self->getfield('last') );
2027 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2028 or return gettext('illegal_name'). " payname: ". $self->payname;
2032 return "Please select an invoicing locale"
2035 && $conf->exists('cust_main-require_locale');
2037 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2038 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2042 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2044 warn "$me check AFTER: \n". $self->_dump
2047 $self->SUPER::check;
2052 Returns a list of fields which have ship_ duplicates.
2057 qw( last first company
2058 address1 address2 city county state zip country
2060 daytime night fax mobile
2064 =item has_ship_address
2066 Returns true if this customer record has a separate shipping address.
2070 sub has_ship_address {
2072 $self->bill_locationnum != $self->ship_locationnum;
2077 Returns a list of key/value pairs, with the following keys: address1,
2078 adddress2, city, county, state, zip, country, district, and geocode. The
2079 shipping address is used if present.
2085 $self->ship_location->location_hash;
2090 Returns all locations (see L<FS::cust_location>) for this customer.
2096 qsearch('cust_location', { 'custnum' => $self->custnum,
2097 'prospectnum' => '' } );
2102 Returns all contacts (see L<FS::contact>) for this customer.
2106 #already used :/ sub contact {
2109 qsearch('contact', { 'custnum' => $self->custnum } );
2114 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2115 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2116 on success or a list of errors.
2122 grep { $_->unsuspend } $self->suspended_pkgs;
2127 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2129 Returns a list: an empty list on success or a list of errors.
2135 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2138 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2140 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2141 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2142 of a list of pkgparts; the hashref has the following keys:
2146 =item pkgparts - listref of pkgparts
2148 =item (other options are passed to the suspend method)
2153 Returns a list: an empty list on success or a list of errors.
2157 sub suspend_if_pkgpart {
2159 my (@pkgparts, %opt);
2160 if (ref($_[0]) eq 'HASH'){
2161 @pkgparts = @{$_[0]{pkgparts}};
2166 grep { $_->suspend(%opt) }
2167 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2168 $self->unsuspended_pkgs;
2171 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2173 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2174 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2175 instead of a list of pkgparts; the hashref has the following keys:
2179 =item pkgparts - listref of pkgparts
2181 =item (other options are passed to the suspend method)
2185 Returns a list: an empty list on success or a list of errors.
2189 sub suspend_unless_pkgpart {
2191 my (@pkgparts, %opt);
2192 if (ref($_[0]) eq 'HASH'){
2193 @pkgparts = @{$_[0]{pkgparts}};
2198 grep { $_->suspend(%opt) }
2199 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2200 $self->unsuspended_pkgs;
2203 =item cancel [ OPTION => VALUE ... ]
2205 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2207 Available options are:
2211 =item quiet - can be set true to supress email cancellation notices.
2213 =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.
2215 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2217 =item nobill - can be set true to skip billing if it might otherwise be done.
2221 Always returns a list: an empty list on success or a list of errors.
2225 # nb that dates are not specified as valid options to this method
2228 my( $self, %opt ) = @_;
2230 warn "$me cancel called on customer ". $self->custnum. " with options ".
2231 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2234 return ( 'access denied' )
2235 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2237 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2239 #should try decryption (we might have the private key)
2240 # and if not maybe queue a job for the server that does?
2241 return ( "Can't (yet) ban encrypted credit cards" )
2242 if $self->is_encrypted($self->payinfo);
2244 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2245 my $error = $ban->insert;
2246 return ( $error ) if $error;
2250 my @pkgs = $self->ncancelled_pkgs;
2252 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2254 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2255 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2259 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2260 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2263 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2266 sub _banned_pay_hashref {
2277 'payby' => $payby2ban{$self->payby},
2278 'payinfo' => $self->payinfo,
2279 #don't ever *search* on reason! #'reason' =>
2283 sub _new_banned_pay_hashref {
2285 my $hr = $self->_banned_pay_hashref;
2286 $hr->{payinfo} = md5_base64($hr->{payinfo});
2292 Returns all notes (see L<FS::cust_main_note>) for this customer.
2297 my($self,$orderby_classnum) = (shift,shift);
2298 my $orderby = "_DATE DESC";
2299 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2300 qsearch( 'cust_main_note',
2301 { 'custnum' => $self->custnum },
2303 "ORDER BY $orderby",
2309 Returns the agent (see L<FS::agent>) for this customer.
2315 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2320 Returns the agent name (see L<FS::agent>) for this customer.
2326 $self->agent->agent;
2331 Returns any tags associated with this customer, as FS::cust_tag objects,
2332 or an empty list if there are no tags.
2338 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2343 Returns any tags associated with this customer, as FS::part_tag objects,
2344 or an empty list if there are no tags.
2350 map $_->part_tag, $self->cust_tag;
2356 Returns the customer class, as an FS::cust_class object, or the empty string
2357 if there is no customer class.
2363 if ( $self->classnum ) {
2364 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2372 Returns the customer category name, or the empty string if there is no customer
2379 my $cust_class = $self->cust_class;
2381 ? $cust_class->categoryname
2387 Returns the customer class name, or the empty string if there is no customer
2394 my $cust_class = $self->cust_class;
2396 ? $cust_class->classname
2400 =item BILLING METHODS
2402 Documentation on billing methods has been moved to
2403 L<FS::cust_main::Billing>.
2405 =item REALTIME BILLING METHODS
2407 Documentation on realtime billing methods has been moved to
2408 L<FS::cust_main::Billing_Realtime>.
2412 Removes the I<paycvv> field from the database directly.
2414 If there is an error, returns the error, otherwise returns false.
2420 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2421 or return dbh->errstr;
2422 $sth->execute($self->custnum)
2423 or return $sth->errstr;
2428 =item batch_card OPTION => VALUE...
2430 Adds a payment for this invoice to the pending credit card batch (see
2431 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2432 runs the payment using a realtime gateway.
2434 Options may include:
2436 B<amount>: the amount to be paid; defaults to the customer's balance minus
2437 any payments in transit.
2439 B<payby>: the payment method; defaults to cust_main.payby
2441 B<realtime>: runs this as a realtime payment instead of adding it to a
2444 B<invnum>: sets cust_pay_batch.invnum.
2446 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2447 the billing address for the payment; defaults to the customer's billing
2450 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2451 date, and name; defaults to those fields in cust_main.
2456 my ($self, %options) = @_;
2459 if (exists($options{amount})) {
2460 $amount = $options{amount};
2462 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2464 return '' unless $amount > 0;
2466 my $invnum = delete $options{invnum};
2467 my $payby = $options{payby} || $self->payby; #still dubious
2469 if ($options{'realtime'}) {
2470 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2476 my $oldAutoCommit = $FS::UID::AutoCommit;
2477 local $FS::UID::AutoCommit = 0;
2480 #this needs to handle mysql as well as Pg, like svc_acct.pm
2481 #(make it into a common function if folks need to do batching with mysql)
2482 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2483 or return "Cannot lock pay_batch: " . $dbh->errstr;
2487 'payby' => FS::payby->payby2payment($payby),
2489 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2491 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2493 unless ( $pay_batch ) {
2494 $pay_batch = new FS::pay_batch \%pay_batch;
2495 my $error = $pay_batch->insert;
2497 $dbh->rollback if $oldAutoCommit;
2498 die "error creating new batch: $error\n";
2502 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2503 'batchnum' => $pay_batch->batchnum,
2504 'custnum' => $self->custnum,
2507 foreach (qw( address1 address2 city state zip country latitude longitude
2508 payby payinfo paydate payname ))
2510 $options{$_} = '' unless exists($options{$_});
2513 my $loc = $self->bill_location;
2515 my $cust_pay_batch = new FS::cust_pay_batch ( {
2516 'batchnum' => $pay_batch->batchnum,
2517 'invnum' => $invnum || 0, # is there a better value?
2518 # this field should be
2520 # cust_bill_pay_batch now
2521 'custnum' => $self->custnum,
2522 'last' => $self->getfield('last'),
2523 'first' => $self->getfield('first'),
2524 'address1' => $options{address1} || $loc->address1,
2525 'address2' => $options{address2} || $loc->address2,
2526 'city' => $options{city} || $loc->city,
2527 'state' => $options{state} || $loc->state,
2528 'zip' => $options{zip} || $loc->zip,
2529 'country' => $options{country} || $loc->country,
2530 'payby' => $options{payby} || $self->payby,
2531 'payinfo' => $options{payinfo} || $self->payinfo,
2532 'exp' => $options{paydate} || $self->paydate,
2533 'payname' => $options{payname} || $self->payname,
2534 'amount' => $amount, # consolidating
2537 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2538 if $old_cust_pay_batch;
2541 if ($old_cust_pay_batch) {
2542 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2544 $error = $cust_pay_batch->insert;
2548 $dbh->rollback if $oldAutoCommit;
2552 my $unapplied = $self->total_unapplied_credits
2553 + $self->total_unapplied_payments
2554 + $self->in_transit_payments;
2555 foreach my $cust_bill ($self->open_cust_bill) {
2556 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2557 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2558 'invnum' => $cust_bill->invnum,
2559 'paybatchnum' => $cust_pay_batch->paybatchnum,
2560 'amount' => $cust_bill->owed,
2563 if ($unapplied >= $cust_bill_pay_batch->amount){
2564 $unapplied -= $cust_bill_pay_batch->amount;
2567 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2568 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2570 $error = $cust_bill_pay_batch->insert;
2572 $dbh->rollback if $oldAutoCommit;
2577 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2583 Returns the total owed for this customer on all invoices
2584 (see L<FS::cust_bill/owed>).
2590 $self->total_owed_date(2145859200); #12/31/2037
2593 =item total_owed_date TIME
2595 Returns the total owed for this customer on all invoices with date earlier than
2596 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2597 see L<Time::Local> and L<Date::Parse> for conversion functions.
2601 sub total_owed_date {
2605 my $custnum = $self->custnum;
2607 my $owed_sql = FS::cust_bill->owed_sql;
2610 SELECT SUM($owed_sql) FROM cust_bill
2611 WHERE custnum = $custnum
2615 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2619 =item total_owed_pkgnum PKGNUM
2621 Returns the total owed on all invoices for this customer's specific package
2622 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2626 sub total_owed_pkgnum {
2627 my( $self, $pkgnum ) = @_;
2628 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2631 =item total_owed_date_pkgnum TIME PKGNUM
2633 Returns the total owed for this customer's specific package when using
2634 experimental package balances on all invoices with date earlier than
2635 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2636 see L<Time::Local> and L<Date::Parse> for conversion functions.
2640 sub total_owed_date_pkgnum {
2641 my( $self, $time, $pkgnum ) = @_;
2644 foreach my $cust_bill (
2645 grep { $_->_date <= $time }
2646 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2648 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2650 sprintf( "%.2f", $total_bill );
2656 Returns the total amount of all payments.
2663 $total += $_->paid foreach $self->cust_pay;
2664 sprintf( "%.2f", $total );
2667 =item total_unapplied_credits
2669 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2670 customer. See L<FS::cust_credit/credited>.
2672 =item total_credited
2674 Old name for total_unapplied_credits. Don't use.
2678 sub total_credited {
2679 #carp "total_credited deprecated, use total_unapplied_credits";
2680 shift->total_unapplied_credits(@_);
2683 sub total_unapplied_credits {
2686 my $custnum = $self->custnum;
2688 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2691 SELECT SUM($unapplied_sql) FROM cust_credit
2692 WHERE custnum = $custnum
2695 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2699 =item total_unapplied_credits_pkgnum PKGNUM
2701 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2702 customer. See L<FS::cust_credit/credited>.
2706 sub total_unapplied_credits_pkgnum {
2707 my( $self, $pkgnum ) = @_;
2708 my $total_credit = 0;
2709 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2710 sprintf( "%.2f", $total_credit );
2714 =item total_unapplied_payments
2716 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2717 See L<FS::cust_pay/unapplied>.
2721 sub total_unapplied_payments {
2724 my $custnum = $self->custnum;
2726 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2729 SELECT SUM($unapplied_sql) FROM cust_pay
2730 WHERE custnum = $custnum
2733 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2737 =item total_unapplied_payments_pkgnum PKGNUM
2739 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2740 specific package when using experimental package balances. See
2741 L<FS::cust_pay/unapplied>.
2745 sub total_unapplied_payments_pkgnum {
2746 my( $self, $pkgnum ) = @_;
2747 my $total_unapplied = 0;
2748 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2749 sprintf( "%.2f", $total_unapplied );
2753 =item total_unapplied_refunds
2755 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2756 customer. See L<FS::cust_refund/unapplied>.
2760 sub total_unapplied_refunds {
2762 my $custnum = $self->custnum;
2764 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2767 SELECT SUM($unapplied_sql) FROM cust_refund
2768 WHERE custnum = $custnum
2771 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2777 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2778 total_unapplied_credits minus total_unapplied_payments).
2784 $self->balance_date_range;
2787 =item balance_date TIME
2789 Returns the balance for this customer, only considering invoices with date
2790 earlier than TIME (total_owed_date minus total_credited minus
2791 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2792 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2799 $self->balance_date_range(shift);
2802 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2804 Returns the balance for this customer, optionally considering invoices with
2805 date earlier than START_TIME, and not later than END_TIME
2806 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2808 Times are specified as SQL fragments or numeric
2809 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2810 L<Date::Parse> for conversion functions. The empty string can be passed
2811 to disable that time constraint completely.
2813 Available options are:
2817 =item unapplied_date
2819 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)
2825 sub balance_date_range {
2827 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2828 ') FROM cust_main WHERE custnum='. $self->custnum;
2829 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2832 =item balance_pkgnum PKGNUM
2834 Returns the balance for this customer's specific package when using
2835 experimental package balances (total_owed plus total_unrefunded, minus
2836 total_unapplied_credits minus total_unapplied_payments)
2840 sub balance_pkgnum {
2841 my( $self, $pkgnum ) = @_;
2844 $self->total_owed_pkgnum($pkgnum)
2845 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2846 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2847 - $self->total_unapplied_credits_pkgnum($pkgnum)
2848 - $self->total_unapplied_payments_pkgnum($pkgnum)
2852 =item in_transit_payments
2854 Returns the total of requests for payments for this customer pending in
2855 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2859 sub in_transit_payments {
2861 my $in_transit_payments = 0;
2862 foreach my $pay_batch ( qsearch('pay_batch', {
2865 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2866 'batchnum' => $pay_batch->batchnum,
2867 'custnum' => $self->custnum,
2869 $in_transit_payments += $cust_pay_batch->amount;
2872 sprintf( "%.2f", $in_transit_payments );
2877 Returns a hash of useful information for making a payment.
2887 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2888 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2889 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2893 For credit card transactions:
2905 For electronic check transactions:
2920 $return{balance} = $self->balance;
2922 $return{payname} = $self->payname
2923 || ( $self->first. ' '. $self->get('last') );
2925 $return{$_} = $self->bill_location->$_
2926 for qw(address1 address2 city state zip);
2928 $return{payby} = $self->payby;
2929 $return{stateid_state} = $self->stateid_state;
2931 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2932 $return{card_type} = cardtype($self->payinfo);
2933 $return{payinfo} = $self->paymask;
2935 @return{'month', 'year'} = $self->paydate_monthyear;
2939 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2940 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2941 $return{payinfo1} = $payinfo1;
2942 $return{payinfo2} = $payinfo2;
2943 $return{paytype} = $self->paytype;
2944 $return{paystate} = $self->paystate;
2948 #doubleclick protection
2950 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2956 =item paydate_monthyear
2958 Returns a two-element list consisting of the month and year of this customer's
2959 paydate (credit card expiration date for CARD customers)
2963 sub paydate_monthyear {
2965 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2967 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2976 Returns the exact time in seconds corresponding to the payment method
2977 expiration date. For CARD/DCRD customers this is the end of the month;
2978 for others (COMP is the only other payby that uses paydate) it's the start.
2979 Returns 0 if the paydate is empty or set to the far future.
2985 my ($month, $year) = $self->paydate_monthyear;
2986 return 0 if !$year or $year >= 2037;
2987 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2989 if ( $month == 13 ) {
2993 return timelocal(0,0,0,1,$month-1,$year) - 1;
2996 return timelocal(0,0,0,1,$month-1,$year);
3000 =item paydate_epoch_sql
3002 Class method. Returns an SQL expression to obtain the payment expiration date
3003 as a number of seconds.
3007 # Special expiration date behavior for non-CARD/DCRD customers has been
3008 # carefully preserved. Do we really use that?
3009 sub paydate_epoch_sql {
3011 my $table = shift || 'cust_main';
3012 my ($case1, $case2);
3013 if ( driver_name eq 'Pg' ) {
3014 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3015 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3017 elsif ( lc(driver_name) eq 'mysql' ) {
3018 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3019 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3022 return "CASE WHEN $table.payby IN('CARD','DCRD')
3028 =item tax_exemption TAXNAME
3033 my( $self, $taxname ) = @_;
3035 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3036 'taxname' => $taxname,
3041 =item cust_main_exemption
3045 sub cust_main_exemption {
3047 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3050 =item invoicing_list [ ARRAYREF ]
3052 If an arguement is given, sets these email addresses as invoice recipients
3053 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3054 (except as warnings), so use check_invoicing_list first.
3056 Returns a list of email addresses (with svcnum entries expanded).
3058 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3059 check it without disturbing anything by passing nothing.
3061 This interface may change in the future.
3065 sub invoicing_list {
3066 my( $self, $arrayref ) = @_;
3069 my @cust_main_invoice;
3070 if ( $self->custnum ) {
3071 @cust_main_invoice =
3072 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3074 @cust_main_invoice = ();
3076 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3077 #warn $cust_main_invoice->destnum;
3078 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3079 #warn $cust_main_invoice->destnum;
3080 my $error = $cust_main_invoice->delete;
3081 warn $error if $error;
3084 if ( $self->custnum ) {
3085 @cust_main_invoice =
3086 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3088 @cust_main_invoice = ();
3090 my %seen = map { $_->address => 1 } @cust_main_invoice;
3091 foreach my $address ( @{$arrayref} ) {
3092 next if exists $seen{$address} && $seen{$address};
3093 $seen{$address} = 1;
3094 my $cust_main_invoice = new FS::cust_main_invoice ( {
3095 'custnum' => $self->custnum,
3098 my $error = $cust_main_invoice->insert;
3099 warn $error if $error;
3103 if ( $self->custnum ) {
3105 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3112 =item check_invoicing_list ARRAYREF
3114 Checks these arguements as valid input for the invoicing_list method. If there
3115 is an error, returns the error, otherwise returns false.
3119 sub check_invoicing_list {
3120 my( $self, $arrayref ) = @_;
3122 foreach my $address ( @$arrayref ) {
3124 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3125 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3128 my $cust_main_invoice = new FS::cust_main_invoice ( {
3129 'custnum' => $self->custnum,
3132 my $error = $self->custnum
3133 ? $cust_main_invoice->check
3134 : $cust_main_invoice->checkdest
3136 return $error if $error;
3140 return "Email address required"
3141 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3142 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3147 =item set_default_invoicing_list
3149 Sets the invoicing list to all accounts associated with this customer,
3150 overwriting any previous invoicing list.
3154 sub set_default_invoicing_list {
3156 $self->invoicing_list($self->all_emails);
3161 Returns the email addresses of all accounts provisioned for this customer.
3168 foreach my $cust_pkg ( $self->all_pkgs ) {
3169 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3171 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3172 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3174 $list{$_}=1 foreach map { $_->email } @svc_acct;
3179 =item invoicing_list_addpost
3181 Adds postal invoicing to this customer. If this customer is already configured
3182 to receive postal invoices, does nothing.
3186 sub invoicing_list_addpost {
3188 return if grep { $_ eq 'POST' } $self->invoicing_list;
3189 my @invoicing_list = $self->invoicing_list;
3190 push @invoicing_list, 'POST';
3191 $self->invoicing_list(\@invoicing_list);
3194 =item invoicing_list_emailonly
3196 Returns the list of email invoice recipients (invoicing_list without non-email
3197 destinations such as POST and FAX).
3201 sub invoicing_list_emailonly {
3203 warn "$me invoicing_list_emailonly called"
3205 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3208 =item invoicing_list_emailonly_scalar
3210 Returns the list of email invoice recipients (invoicing_list without non-email
3211 destinations such as POST and FAX) as a comma-separated scalar.
3215 sub invoicing_list_emailonly_scalar {
3217 warn "$me invoicing_list_emailonly_scalar called"
3219 join(', ', $self->invoicing_list_emailonly);
3222 =item referral_custnum_cust_main
3224 Returns the customer who referred this customer (or the empty string, if
3225 this customer was not referred).
3227 Note the difference with referral_cust_main method: This method,
3228 referral_custnum_cust_main returns the single customer (if any) who referred
3229 this customer, while referral_cust_main returns an array of customers referred
3234 sub referral_custnum_cust_main {
3236 return '' unless $self->referral_custnum;
3237 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3240 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3242 Returns an array of customers referred by this customer (referral_custnum set
3243 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3244 customers referred by customers referred by this customer and so on, inclusive.
3245 The default behavior is DEPTH 1 (no recursion).
3247 Note the difference with referral_custnum_cust_main method: This method,
3248 referral_cust_main, returns an array of customers referred BY this customer,
3249 while referral_custnum_cust_main returns the single customer (if any) who
3250 referred this customer.
3254 sub referral_cust_main {
3256 my $depth = @_ ? shift : 1;
3257 my $exclude = @_ ? shift : {};
3260 map { $exclude->{$_->custnum}++; $_; }
3261 grep { ! $exclude->{ $_->custnum } }
3262 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3266 map { $_->referral_cust_main($depth-1, $exclude) }
3273 =item referral_cust_main_ncancelled
3275 Same as referral_cust_main, except only returns customers with uncancelled
3280 sub referral_cust_main_ncancelled {
3282 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3285 =item referral_cust_pkg [ DEPTH ]
3287 Like referral_cust_main, except returns a flat list of all unsuspended (and
3288 uncancelled) packages for each customer. The number of items in this list may
3289 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3293 sub referral_cust_pkg {
3295 my $depth = @_ ? shift : 1;
3297 map { $_->unsuspended_pkgs }
3298 grep { $_->unsuspended_pkgs }
3299 $self->referral_cust_main($depth);
3302 =item referring_cust_main
3304 Returns the single cust_main record for the customer who referred this customer
3305 (referral_custnum), or false.
3309 sub referring_cust_main {
3311 return '' unless $self->referral_custnum;
3312 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3315 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3317 Applies a credit to this customer. If there is an error, returns the error,
3318 otherwise returns false.
3320 REASON can be a text string, an FS::reason object, or a scalar reference to
3321 a reasonnum. If a text string, it will be automatically inserted as a new
3322 reason, and a 'reason_type' option must be passed to indicate the
3323 FS::reason_type for the new reason.
3325 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3327 Any other options are passed to FS::cust_credit::insert.
3332 my( $self, $amount, $reason, %options ) = @_;
3334 my $cust_credit = new FS::cust_credit {
3335 'custnum' => $self->custnum,
3336 'amount' => $amount,
3339 if ( ref($reason) ) {
3341 if ( ref($reason) eq 'SCALAR' ) {
3342 $cust_credit->reasonnum( $$reason );
3344 $cust_credit->reasonnum( $reason->reasonnum );
3348 $cust_credit->set('reason', $reason)
3351 for (qw( addlinfo eventnum )) {
3352 $cust_credit->$_( delete $options{$_} )
3353 if exists($options{$_});
3356 $cust_credit->insert(%options);
3360 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3362 Creates a one-time charge for this customer. If there is an error, returns
3363 the error, otherwise returns false.
3365 New-style, with a hashref of options:
3367 my $error = $cust_main->charge(
3371 'start_date' => str2time('7/4/2009'),
3372 'pkg' => 'Description',
3373 'comment' => 'Comment',
3374 'additional' => [], #extra invoice detail
3375 'classnum' => 1, #pkg_class
3377 'setuptax' => '', # or 'Y' for tax exempt
3379 'locationnum'=> 1234, # optional
3382 'taxclass' => 'Tax class',
3385 'taxproduct' => 2, #part_pkg_taxproduct
3386 'override' => {}, #XXX describe
3388 #will be filled in with the new object
3389 'cust_pkg_ref' => \$cust_pkg,
3391 #generate an invoice immediately
3393 'invoice_terms' => '', #with these terms
3399 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3405 my ( $amount, $quantity, $start_date, $classnum );
3406 my ( $pkg, $comment, $additional );
3407 my ( $setuptax, $taxclass ); #internal taxes
3408 my ( $taxproduct, $override ); #vendor (CCH) taxes
3410 my $cust_pkg_ref = '';
3411 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3413 if ( ref( $_[0] ) ) {
3414 $amount = $_[0]->{amount};
3415 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3416 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3417 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3418 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3419 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3420 : '$'. sprintf("%.2f",$amount);
3421 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3422 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3423 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3424 $additional = $_[0]->{additional} || [];
3425 $taxproduct = $_[0]->{taxproductnum};
3426 $override = { '' => $_[0]->{tax_override} };
3427 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3428 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3429 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3430 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3435 $pkg = @_ ? shift : 'One-time charge';
3436 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3438 $taxclass = @_ ? shift : '';
3442 local $SIG{HUP} = 'IGNORE';
3443 local $SIG{INT} = 'IGNORE';
3444 local $SIG{QUIT} = 'IGNORE';
3445 local $SIG{TERM} = 'IGNORE';
3446 local $SIG{TSTP} = 'IGNORE';
3447 local $SIG{PIPE} = 'IGNORE';
3449 my $oldAutoCommit = $FS::UID::AutoCommit;
3450 local $FS::UID::AutoCommit = 0;
3453 my $part_pkg = new FS::part_pkg ( {
3455 'comment' => $comment,
3459 'classnum' => ( $classnum ? $classnum : '' ),
3460 'setuptax' => $setuptax,
3461 'taxclass' => $taxclass,
3462 'taxproductnum' => $taxproduct,
3465 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3466 ( 0 .. @$additional - 1 )
3468 'additional_count' => scalar(@$additional),
3469 'setup_fee' => $amount,
3472 my $error = $part_pkg->insert( options => \%options,
3473 tax_overrides => $override,
3476 $dbh->rollback if $oldAutoCommit;
3480 my $pkgpart = $part_pkg->pkgpart;
3481 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3482 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3483 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3484 $error = $type_pkgs->insert;
3486 $dbh->rollback if $oldAutoCommit;
3491 my $cust_pkg = new FS::cust_pkg ( {
3492 'custnum' => $self->custnum,
3493 'pkgpart' => $pkgpart,
3494 'quantity' => $quantity,
3495 'start_date' => $start_date,
3496 'no_auto' => $no_auto,
3497 'locationnum'=> $locationnum,
3500 $error = $cust_pkg->insert;
3502 $dbh->rollback if $oldAutoCommit;
3504 } elsif ( $cust_pkg_ref ) {
3505 ${$cust_pkg_ref} = $cust_pkg;
3509 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3510 'pkg_list' => [ $cust_pkg ],
3513 $dbh->rollback if $oldAutoCommit;
3518 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3523 #=item charge_postal_fee
3525 #Applies a one time charge this customer. If there is an error,
3526 #returns the error, returns the cust_pkg charge object or false
3527 #if there was no charge.
3531 # This should be a customer event. For that to work requires that bill
3532 # also be a customer event.
3534 sub charge_postal_fee {
3537 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3538 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3540 my $cust_pkg = new FS::cust_pkg ( {
3541 'custnum' => $self->custnum,
3542 'pkgpart' => $pkgpart,
3546 my $error = $cust_pkg->insert;
3547 $error ? $error : $cust_pkg;
3550 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3552 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3554 Optionally, a list or hashref of additional arguments to the qsearch call can
3561 my $opt = ref($_[0]) ? shift : { @_ };
3563 #return $self->num_cust_bill unless wantarray || keys %$opt;
3565 $opt->{'table'} = 'cust_bill';
3566 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3567 $opt->{'hashref'}{'custnum'} = $self->custnum;
3568 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3570 map { $_ } #behavior of sort undefined in scalar context
3571 sort { $a->_date <=> $b->_date }
3575 =item open_cust_bill
3577 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3582 sub open_cust_bill {
3586 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3592 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3594 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3598 sub legacy_cust_bill {
3601 #return $self->num_legacy_cust_bill unless wantarray;
3603 map { $_ } #behavior of sort undefined in scalar context
3604 sort { $a->_date <=> $b->_date }
3605 qsearch({ 'table' => 'legacy_cust_bill',
3606 'hashref' => { 'custnum' => $self->custnum, },
3607 'order_by' => 'ORDER BY _date ASC',
3611 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3613 Returns all the statements (see L<FS::cust_statement>) for this customer.
3615 Optionally, a list or hashref of additional arguments to the qsearch call can
3620 =item cust_bill_void
3622 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3626 sub cust_bill_void {
3629 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3630 sort { $a->_date <=> $b->_date }
3631 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3634 sub cust_statement {
3636 my $opt = ref($_[0]) ? shift : { @_ };
3638 #return $self->num_cust_statement unless wantarray || keys %$opt;
3640 $opt->{'table'} = 'cust_statement';
3641 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3642 $opt->{'hashref'}{'custnum'} = $self->custnum;
3643 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3645 map { $_ } #behavior of sort undefined in scalar context
3646 sort { $a->_date <=> $b->_date }
3650 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3652 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3654 Optionally, a list or hashref of additional arguments to the qsearch call can
3655 be passed following the SVCDB.
3662 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3663 warn "$me svc_x requires a svcdb";
3666 my $opt = ref($_[0]) ? shift : { @_ };
3668 $opt->{'table'} = $svcdb;
3669 $opt->{'addl_from'} =
3670 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3671 ($opt->{'addl_from'} || '');
3673 my $custnum = $self->custnum;
3674 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3675 my $where = "cust_pkg.custnum = $custnum";
3677 my $extra_sql = $opt->{'extra_sql'} || '';
3678 if ( keys %{ $opt->{'hashref'} } ) {
3679 $extra_sql = " AND $where $extra_sql";
3682 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3683 $extra_sql = "WHERE $where AND $1";
3686 $extra_sql = "WHERE $where $extra_sql";
3689 $opt->{'extra_sql'} = $extra_sql;
3694 # required for use as an eventtable;
3697 $self->svc_x('svc_acct', @_);
3702 Returns all the credits (see L<FS::cust_credit>) for this customer.
3708 map { $_ } #return $self->num_cust_credit unless wantarray;
3709 sort { $a->_date <=> $b->_date }
3710 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3713 =item cust_credit_pkgnum
3715 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3716 package when using experimental package balances.
3720 sub cust_credit_pkgnum {
3721 my( $self, $pkgnum ) = @_;
3722 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3723 sort { $a->_date <=> $b->_date }
3724 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3725 'pkgnum' => $pkgnum,
3732 Returns all the payments (see L<FS::cust_pay>) for this customer.
3738 return $self->num_cust_pay unless wantarray;
3739 sort { $a->_date <=> $b->_date }
3740 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3745 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3746 called automatically when the cust_pay method is used in a scalar context.
3752 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3753 my $sth = dbh->prepare($sql) or die dbh->errstr;
3754 $sth->execute($self->custnum) or die $sth->errstr;
3755 $sth->fetchrow_arrayref->[0];
3758 =item cust_pay_pkgnum
3760 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3761 package when using experimental package balances.
3765 sub cust_pay_pkgnum {
3766 my( $self, $pkgnum ) = @_;
3767 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3768 sort { $a->_date <=> $b->_date }
3769 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3770 'pkgnum' => $pkgnum,
3777 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3783 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3784 sort { $a->_date <=> $b->_date }
3785 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3788 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3790 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3792 Optionally, a list or hashref of additional arguments to the qsearch call can
3797 sub cust_pay_batch {
3799 my $opt = ref($_[0]) ? shift : { @_ };
3801 #return $self->num_cust_statement unless wantarray || keys %$opt;
3803 $opt->{'table'} = 'cust_pay_batch';
3804 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3805 $opt->{'hashref'}{'custnum'} = $self->custnum;
3806 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3808 map { $_ } #behavior of sort undefined in scalar context
3809 sort { $a->paybatchnum <=> $b->paybatchnum }
3813 =item cust_pay_pending
3815 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3816 (without status "done").
3820 sub cust_pay_pending {
3822 return $self->num_cust_pay_pending unless wantarray;
3823 sort { $a->_date <=> $b->_date }
3824 qsearch( 'cust_pay_pending', {
3825 'custnum' => $self->custnum,
3826 'status' => { op=>'!=', value=>'done' },
3831 =item cust_pay_pending_attempt
3833 Returns all payment attempts / declined payments for this customer, as pending
3834 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3835 a corresponding payment (see L<FS::cust_pay>).
3839 sub cust_pay_pending_attempt {
3841 return $self->num_cust_pay_pending_attempt unless wantarray;
3842 sort { $a->_date <=> $b->_date }
3843 qsearch( 'cust_pay_pending', {
3844 'custnum' => $self->custnum,