5 #FS::cust_main:_Marketgear when they're ready to move to 2.1
6 use base qw( FS::cust_main::Packages FS::cust_main::Status
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 use vars qw( $DEBUG $me $conf
16 $ignore_expired_card $ignore_illegal_zip $ignore_banned_card
17 $skip_fuzzyfiles @fuzzyfields
21 use Scalar::Util qw( blessed );
22 use Time::Local qw(timelocal);
23 use Storable qw(thaw);
27 use Digest::MD5 qw(md5_base64);
30 use File::Temp; #qw( tempfile );
31 use Business::CreditCard 0.28;
33 use FS::UID qw( getotaker dbh driver_name );
34 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_email send_email generate_ps do_print );
36 use FS::Msgcat qw(gettext);
44 use FS::cust_pay_pending;
45 use FS::cust_pay_void;
46 use FS::cust_pay_batch;
49 use FS::part_referral;
50 use FS::cust_main_county;
51 use FS::cust_location;
53 use FS::cust_main_exemption;
54 use FS::cust_tax_adjustment;
55 use FS::cust_tax_location;
57 use FS::cust_main_invoice;
59 use FS::prepay_credit;
65 use FS::payment_gateway;
66 use FS::agent_payment_gateway;
68 use FS::cust_main_note;
69 use FS::cust_attachment;
72 # 1 is mostly method/subroutine entry and options
73 # 2 traces progress of some operations
74 # 3 is even more information including possibly sensitive data
76 $me = '[FS::cust_main]';
79 $ignore_expired_card = 0;
80 $ignore_illegal_zip = 0;
81 $ignore_banned_card = 0;
84 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
86 @encrypted_fields = ('payinfo', 'paycvv');
87 sub nohistory_fields { ('payinfo', 'paycvv'); }
89 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
91 #ask FS::UID to run this stuff for us later
92 #$FS::UID::callback{'FS::cust_main'} = sub {
93 install_callback FS::UID sub {
95 #yes, need it for stuff below (prolly should be cached)
100 my ( $hashref, $cache ) = @_;
101 if ( exists $hashref->{'pkgnum'} ) {
102 #@{ $self->{'_pkgnum'} } = ();
103 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
104 $self->{'_pkgnum'} = $subcache;
105 #push @{ $self->{'_pkgnum'} },
106 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
112 FS::cust_main - Object methods for cust_main records
118 $record = new FS::cust_main \%hash;
119 $record = new FS::cust_main { 'column' => 'value' };
121 $error = $record->insert;
123 $error = $new_record->replace($old_record);
125 $error = $record->delete;
127 $error = $record->check;
129 @cust_pkg = $record->all_pkgs;
131 @cust_pkg = $record->ncancelled_pkgs;
133 @cust_pkg = $record->suspended_pkgs;
135 $error = $record->bill;
136 $error = $record->bill %options;
137 $error = $record->bill 'time' => $time;
139 $error = $record->collect;
140 $error = $record->collect %options;
141 $error = $record->collect 'invoice_time' => $time,
146 An FS::cust_main object represents a customer. FS::cust_main inherits from
147 FS::Record. The following fields are currently supported:
153 Primary key (assigned automatically for new customers)
157 Agent (see L<FS::agent>)
161 Advertising source (see L<FS::part_referral>)
173 Cocial security number (optional)
189 (optional, see L<FS::cust_main_county>)
193 (see L<FS::cust_main_county>)
199 (see L<FS::cust_main_county>)
235 (optional, see L<FS::cust_main_county>)
239 (see L<FS::cust_main_county>)
245 (see L<FS::cust_main_county>)
261 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
265 Payment Information (See L<FS::payinfo_Mixin> for data format)
269 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
273 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
277 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
281 Start date month (maestro/solo cards only)
285 Start date year (maestro/solo cards only)
289 Issue number (maestro/solo cards only)
293 Name on card or billing name
297 IP address from which payment information was received
301 Tax exempt, empty or `Y'
305 Order taker (see L<FS::access_user>)
311 =item referral_custnum
313 Referring customer number
317 Enable individual CDR spooling, empty or `Y'
321 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
325 Discourage individual CDR printing, empty or `Y'
335 Creates a new customer. To add the customer to the database, see L<"insert">.
337 Note that this stores the hash reference, not a distinct copy of the hash it
338 points to. You can ask the object for a copy with the I<hash> method.
342 sub table { 'cust_main'; }
344 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
346 Adds this customer to the database. If there is an error, returns the error,
347 otherwise returns false.
349 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
350 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
351 are inserted atomicly, or the transaction is rolled back. Passing an empty
352 hash reference is equivalent to not supplying this parameter. There should be
353 a better explanation of this, but until then, here's an example:
356 tie %hash, 'Tie::RefHash'; #this part is important
358 $cust_pkg => [ $svc_acct ],
361 $cust_main->insert( \%hash );
363 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
364 be set as the invoicing list (see L<"invoicing_list">). Errors return as
365 expected and rollback the entire transaction; it is not necessary to call
366 check_invoicing_list first. The invoicing_list is set after the records in the
367 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
368 invoicing_list destination to the newly-created svc_acct. Here's an example:
370 $cust_main->insert( {}, [ $email, 'POST' ] );
372 Currently available options are: I<depend_jobnum>, I<noexport>,
373 I<tax_exemption> and I<prospectnum>.
375 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
376 on the supplied jobnum (they will not run until the specific job completes).
377 This can be used to defer provisioning until some action completes (such
378 as running the customer's credit card successfully).
380 The I<noexport> option is deprecated. If I<noexport> is set true, no
381 provisioning jobs (exports) are scheduled. (You can schedule them later with
382 the B<reexport> method.)
384 The I<tax_exemption> option can be set to an arrayref of tax names.
385 FS::cust_main_exemption records will be created and inserted.
387 If I<prospectnum> is set, moves contacts and locations from that prospect.
393 my $cust_pkgs = @_ ? shift : {};
394 my $invoicing_list = @_ ? shift : '';
396 warn "$me insert called with options ".
397 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
400 local $SIG{HUP} = 'IGNORE';
401 local $SIG{INT} = 'IGNORE';
402 local $SIG{QUIT} = 'IGNORE';
403 local $SIG{TERM} = 'IGNORE';
404 local $SIG{TSTP} = 'IGNORE';
405 local $SIG{PIPE} = 'IGNORE';
407 my $oldAutoCommit = $FS::UID::AutoCommit;
408 local $FS::UID::AutoCommit = 0;
411 my $prepay_identifier = '';
412 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
414 if ( $self->payby eq 'PREPAY' ) {
416 $self->payby('BILL');
417 $prepay_identifier = $self->payinfo;
420 warn " looking up prepaid card $prepay_identifier\n"
423 my $error = $self->get_prepay( $prepay_identifier,
424 'amount_ref' => \$amount,
425 'seconds_ref' => \$seconds,
426 'upbytes_ref' => \$upbytes,
427 'downbytes_ref' => \$downbytes,
428 'totalbytes_ref' => \$totalbytes,
431 $dbh->rollback if $oldAutoCommit;
432 #return "error applying prepaid card (transaction rolled back): $error";
436 $payby = 'PREP' if $amount;
438 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
441 $self->payby('BILL');
442 $amount = $self->paid;
446 warn " inserting $self\n"
449 $self->signupdate(time) unless $self->signupdate;
451 $self->auto_agent_custid()
452 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
454 my $error = $self->SUPER::insert;
456 $dbh->rollback if $oldAutoCommit;
457 #return "inserting cust_main record (transaction rolled back): $error";
461 warn " setting invoicing list\n"
464 if ( $invoicing_list ) {
465 $error = $self->check_invoicing_list( $invoicing_list );
467 $dbh->rollback if $oldAutoCommit;
468 #return "checking invoicing_list (transaction rolled back): $error";
471 $self->invoicing_list( $invoicing_list );
474 warn " setting customer tags\n"
477 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
478 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
479 'custnum' => $self->custnum };
480 my $error = $cust_tag->insert;
482 $dbh->rollback if $oldAutoCommit;
487 my $prospectnum = delete $options{'prospectnum'};
488 if ( $prospectnum ) {
490 warn " moving contacts and locations from prospect $prospectnum\n"
494 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
495 unless ( $prospect_main ) {
496 $dbh->rollback if $oldAutoCommit;
497 return "Unknown prospectnum $prospectnum";
499 $prospect_main->custnum($self->custnum);
500 $prospect_main->disabled('Y');
501 my $error = $prospect_main->replace;
503 $dbh->rollback if $oldAutoCommit;
507 my @contact = $prospect_main->contact;
508 my @cust_location = $prospect_main->cust_location;
509 my @qual = $prospect_main->qual;
511 foreach my $r ( @contact, @cust_location, @qual ) {
513 $r->custnum($self->custnum);
514 my $error = $r->replace;
516 $dbh->rollback if $oldAutoCommit;
523 warn " setting cust_main_exemption\n"
526 my $tax_exemption = delete $options{'tax_exemption'};
527 if ( $tax_exemption ) {
528 foreach my $taxname ( @$tax_exemption ) {
529 my $cust_main_exemption = new FS::cust_main_exemption {
530 'custnum' => $self->custnum,
531 'taxname' => $taxname,
533 my $error = $cust_main_exemption->insert;
535 $dbh->rollback if $oldAutoCommit;
536 return "inserting cust_main_exemption (transaction rolled back): $error";
541 if ( $self->can('start_copy_skel') ) {
542 my $error = $self->start_copy_skel;
544 $dbh->rollback if $oldAutoCommit;
549 warn " ordering packages\n"
552 $error = $self->order_pkgs( $cust_pkgs,
554 'seconds_ref' => \$seconds,
555 'upbytes_ref' => \$upbytes,
556 'downbytes_ref' => \$downbytes,
557 'totalbytes_ref' => \$totalbytes,
560 $dbh->rollback if $oldAutoCommit;
565 $dbh->rollback if $oldAutoCommit;
566 return "No svc_acct record to apply pre-paid time";
568 if ( $upbytes || $downbytes || $totalbytes ) {
569 $dbh->rollback if $oldAutoCommit;
570 return "No svc_acct record to apply pre-paid data";
574 warn " inserting initial $payby payment of $amount\n"
576 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
578 $dbh->rollback if $oldAutoCommit;
579 return "inserting payment (transaction rolled back): $error";
583 unless ( $import || $skip_fuzzyfiles ) {
584 warn " queueing fuzzyfiles update\n"
586 $error = $self->queue_fuzzyfiles_update;
588 $dbh->rollback if $oldAutoCommit;
589 return "updating fuzzy search cache: $error";
594 warn " exporting\n" if $DEBUG > 1;
596 my $export_args = $options{'export_args'} || [];
599 map qsearch( 'part_export', {exportnum=>$_} ),
600 $conf->config('cust_main-exports'); #, $agentnum
602 foreach my $part_export ( @part_export ) {
603 my $error = $part_export->export_insert($self, @$export_args);
605 $dbh->rollback if $oldAutoCommit;
606 return "exporting to ". $part_export->exporttype.
607 " (transaction rolled back): $error";
611 #foreach my $depend_jobnum ( @$depend_jobnums ) {
612 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
614 # foreach my $jobnum ( @jobnums ) {
615 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
616 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
618 # my $error = $queue->depend_insert($depend_jobnum);
620 # $dbh->rollback if $oldAutoCommit;
621 # return "error queuing job dependancy: $error";
628 #if ( exists $options{'jobnums'} ) {
629 # push @{ $options{'jobnums'} }, @jobnums;
632 warn " insert complete; committing transaction\n"
635 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
640 use File::CounterFile;
641 sub auto_agent_custid {
644 my $format = $conf->config('cust_main-auto_agent_custid');
646 if ( $format eq '1YMMXXXXXXXX' ) {
648 my $counter = new File::CounterFile 'cust_main.agent_custid';
651 my $ym = 100000000000 + time2str('%y%m00000000', time);
652 if ( $ym > $counter->value ) {
653 $counter->{'value'} = $agent_custid = $ym;
654 $counter->{'updated'} = 1;
656 $agent_custid = $counter->inc;
662 die "Unknown cust_main-auto_agent_custid format: $format";
665 $self->agent_custid($agent_custid);
669 =item PACKAGE METHODS
671 Documentation on customer package methods has been moved to
672 L<FS::cust_main::Packages>.
674 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
676 Recharges this (existing) customer with the specified prepaid card (see
677 L<FS::prepay_credit>), specified either by I<identifier> or as an
678 FS::prepay_credit object. If there is an error, returns the error, otherwise
681 Optionally, five scalar references can be passed as well. They will have their
682 values filled in with the amount, number of seconds, and number of upload,
683 download, and total bytes applied by this prepaid card.
687 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
688 #the only place that uses these args
689 sub recharge_prepay {
690 my( $self, $prepay_credit, $amountref, $secondsref,
691 $upbytesref, $downbytesref, $totalbytesref ) = @_;
693 local $SIG{HUP} = 'IGNORE';
694 local $SIG{INT} = 'IGNORE';
695 local $SIG{QUIT} = 'IGNORE';
696 local $SIG{TERM} = 'IGNORE';
697 local $SIG{TSTP} = 'IGNORE';
698 local $SIG{PIPE} = 'IGNORE';
700 my $oldAutoCommit = $FS::UID::AutoCommit;
701 local $FS::UID::AutoCommit = 0;
704 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
706 my $error = $self->get_prepay( $prepay_credit,
707 'amount_ref' => \$amount,
708 'seconds_ref' => \$seconds,
709 'upbytes_ref' => \$upbytes,
710 'downbytes_ref' => \$downbytes,
711 'totalbytes_ref' => \$totalbytes,
713 || $self->increment_seconds($seconds)
714 || $self->increment_upbytes($upbytes)
715 || $self->increment_downbytes($downbytes)
716 || $self->increment_totalbytes($totalbytes)
717 || $self->insert_cust_pay_prepay( $amount,
719 ? $prepay_credit->identifier
724 $dbh->rollback if $oldAutoCommit;
728 if ( defined($amountref) ) { $$amountref = $amount; }
729 if ( defined($secondsref) ) { $$secondsref = $seconds; }
730 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
731 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
732 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
734 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
739 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
741 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
742 specified either by I<identifier> or as an FS::prepay_credit object.
744 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
745 incremented by the values of the prepaid card.
747 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
748 check or set this customer's I<agentnum>.
750 If there is an error, returns the error, otherwise returns false.
756 my( $self, $prepay_credit, %opt ) = @_;
758 local $SIG{HUP} = 'IGNORE';
759 local $SIG{INT} = 'IGNORE';
760 local $SIG{QUIT} = 'IGNORE';
761 local $SIG{TERM} = 'IGNORE';
762 local $SIG{TSTP} = 'IGNORE';
763 local $SIG{PIPE} = 'IGNORE';
765 my $oldAutoCommit = $FS::UID::AutoCommit;
766 local $FS::UID::AutoCommit = 0;
769 unless ( ref($prepay_credit) ) {
771 my $identifier = $prepay_credit;
773 $prepay_credit = qsearchs(
775 { 'identifier' => $prepay_credit },
780 unless ( $prepay_credit ) {
781 $dbh->rollback if $oldAutoCommit;
782 return "Invalid prepaid card: ". $identifier;
787 if ( $prepay_credit->agentnum ) {
788 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
789 $dbh->rollback if $oldAutoCommit;
790 return "prepaid card not valid for agent ". $self->agentnum;
792 $self->agentnum($prepay_credit->agentnum);
795 my $error = $prepay_credit->delete;
797 $dbh->rollback if $oldAutoCommit;
798 return "removing prepay_credit (transaction rolled back): $error";
801 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
802 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
804 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
809 =item increment_upbytes SECONDS
811 Updates this customer's single or primary account (see L<FS::svc_acct>) by
812 the specified number of upbytes. If there is an error, returns the error,
813 otherwise returns false.
817 sub increment_upbytes {
818 _increment_column( shift, 'upbytes', @_);
821 =item increment_downbytes SECONDS
823 Updates this customer's single or primary account (see L<FS::svc_acct>) by
824 the specified number of downbytes. If there is an error, returns the error,
825 otherwise returns false.
829 sub increment_downbytes {
830 _increment_column( shift, 'downbytes', @_);
833 =item increment_totalbytes SECONDS
835 Updates this customer's single or primary account (see L<FS::svc_acct>) by
836 the specified number of totalbytes. If there is an error, returns the error,
837 otherwise returns false.
841 sub increment_totalbytes {
842 _increment_column( shift, 'totalbytes', @_);
845 =item increment_seconds SECONDS
847 Updates this customer's single or primary account (see L<FS::svc_acct>) by
848 the specified number of seconds. If there is an error, returns the error,
849 otherwise returns false.
853 sub increment_seconds {
854 _increment_column( shift, 'seconds', @_);
857 =item _increment_column AMOUNT
859 Updates this customer's single or primary account (see L<FS::svc_acct>) by
860 the specified number of seconds or bytes. If there is an error, returns
861 the error, otherwise returns false.
865 sub _increment_column {
866 my( $self, $column, $amount ) = @_;
867 warn "$me increment_column called: $column, $amount\n"
870 return '' unless $amount;
872 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
873 $self->ncancelled_pkgs;
876 return 'No packages with primary or single services found'.
877 ' to apply pre-paid time';
878 } elsif ( scalar(@cust_pkg) > 1 ) {
879 #maybe have a way to specify the package/account?
880 return 'Multiple packages found to apply pre-paid time';
883 my $cust_pkg = $cust_pkg[0];
884 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
888 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
891 return 'No account found to apply pre-paid time';
892 } elsif ( scalar(@cust_svc) > 1 ) {
893 return 'Multiple accounts found to apply pre-paid time';
896 my $svc_acct = $cust_svc[0]->svc_x;
897 warn " found service svcnum ". $svc_acct->pkgnum.
898 ' ('. $svc_acct->email. ")\n"
901 $column = "increment_$column";
902 $svc_acct->$column($amount);
906 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
908 Inserts a prepayment in the specified amount for this customer. An optional
909 second argument can specify the prepayment identifier for tracking purposes.
910 If there is an error, returns the error, otherwise returns false.
914 sub insert_cust_pay_prepay {
915 shift->insert_cust_pay('PREP', @_);
918 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
920 Inserts a cash payment in the specified amount for this customer. An optional
921 second argument can specify the payment identifier for tracking purposes.
922 If there is an error, returns the error, otherwise returns false.
926 sub insert_cust_pay_cash {
927 shift->insert_cust_pay('CASH', @_);
930 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
932 Inserts a Western Union payment in the specified amount for this customer. An
933 optional second argument can specify the prepayment identifier for tracking
934 purposes. If there is an error, returns the error, otherwise returns false.
938 sub insert_cust_pay_west {
939 shift->insert_cust_pay('WEST', @_);
942 sub insert_cust_pay {
943 my( $self, $payby, $amount ) = splice(@_, 0, 3);
944 my $payinfo = scalar(@_) ? shift : '';
946 my $cust_pay = new FS::cust_pay {
947 'custnum' => $self->custnum,
948 'paid' => sprintf('%.2f', $amount),
949 #'_date' => #date the prepaid card was purchased???
951 'payinfo' => $payinfo,
959 This method is deprecated. See the I<depend_jobnum> option to the insert and
960 order_pkgs methods for a better way to defer provisioning.
962 Re-schedules all exports by calling the B<reexport> method of all associated
963 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
964 otherwise returns false.
971 carp "WARNING: FS::cust_main::reexport is deprectated; ".
972 "use the depend_jobnum option to insert or order_pkgs to delay export";
974 local $SIG{HUP} = 'IGNORE';
975 local $SIG{INT} = 'IGNORE';
976 local $SIG{QUIT} = 'IGNORE';
977 local $SIG{TERM} = 'IGNORE';
978 local $SIG{TSTP} = 'IGNORE';
979 local $SIG{PIPE} = 'IGNORE';
981 my $oldAutoCommit = $FS::UID::AutoCommit;
982 local $FS::UID::AutoCommit = 0;
985 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
986 my $error = $cust_pkg->reexport;
988 $dbh->rollback if $oldAutoCommit;
993 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
998 =item delete [ OPTION => VALUE ... ]
1000 This deletes the customer. If there is an error, returns the error, otherwise
1003 This will completely remove all traces of the customer record. This is not
1004 what you want when a customer cancels service; for that, cancel all of the
1005 customer's packages (see L</cancel>).
1007 If the customer has any uncancelled packages, you need to pass a new (valid)
1008 customer number for those packages to be transferred to, as the "new_customer"
1009 option. Cancelled packages will be deleted. Did I mention that this is NOT
1010 what you want when a customer cancels service and that you really should be
1011 looking at L<FS::cust_pkg/cancel>?
1013 You can't delete a customer with invoices (see L<FS::cust_bill>),
1014 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1015 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1016 set the "delete_financials" option to a true value.
1021 my( $self, %opt ) = @_;
1023 local $SIG{HUP} = 'IGNORE';
1024 local $SIG{INT} = 'IGNORE';
1025 local $SIG{QUIT} = 'IGNORE';
1026 local $SIG{TERM} = 'IGNORE';
1027 local $SIG{TSTP} = 'IGNORE';
1028 local $SIG{PIPE} = 'IGNORE';
1030 my $oldAutoCommit = $FS::UID::AutoCommit;
1031 local $FS::UID::AutoCommit = 0;
1034 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1035 $dbh->rollback if $oldAutoCommit;
1036 return "Can't delete a master agent customer";
1039 #use FS::access_user
1040 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1041 $dbh->rollback if $oldAutoCommit;
1042 return "Can't delete a master employee customer";
1045 tie my %financial_tables, 'Tie::IxHash',
1046 'cust_bill' => 'invoices',
1047 'cust_statement' => 'statements',
1048 'cust_credit' => 'credits',
1049 'cust_pay' => 'payments',
1050 'cust_refund' => 'refunds',
1053 foreach my $table ( keys %financial_tables ) {
1055 my @records = $self->$table();
1057 if ( @records && ! $opt{'delete_financials'} ) {
1058 $dbh->rollback if $oldAutoCommit;
1059 return "Can't delete a customer with ". $financial_tables{$table};
1062 foreach my $record ( @records ) {
1063 my $error = $record->delete;
1065 $dbh->rollback if $oldAutoCommit;
1066 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1072 my @cust_pkg = $self->ncancelled_pkgs;
1074 my $new_custnum = $opt{'new_custnum'};
1075 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1076 $dbh->rollback if $oldAutoCommit;
1077 return "Invalid new customer number: $new_custnum";
1079 foreach my $cust_pkg ( @cust_pkg ) {
1080 my %hash = $cust_pkg->hash;
1081 $hash{'custnum'} = $new_custnum;
1082 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1083 my $error = $new_cust_pkg->replace($cust_pkg,
1084 options => { $cust_pkg->options },
1087 $dbh->rollback if $oldAutoCommit;
1092 my @cancelled_cust_pkg = $self->all_pkgs;
1093 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1094 my $error = $cust_pkg->delete;
1096 $dbh->rollback if $oldAutoCommit;
1101 #cust_tax_adjustment in financials?
1102 #cust_pay_pending? ouch
1104 foreach my $table (qw(
1105 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1106 cust_location cust_main_note cust_tax_adjustment
1107 cust_pay_void cust_pay_batch queue cust_tax_exempt
1109 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1110 my $error = $record->delete;
1112 $dbh->rollback if $oldAutoCommit;
1118 my $sth = $dbh->prepare(
1119 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1121 my $errstr = $dbh->errstr;
1122 $dbh->rollback if $oldAutoCommit;
1125 $sth->execute($self->custnum) or do {
1126 my $errstr = $sth->errstr;
1127 $dbh->rollback if $oldAutoCommit;
1133 my $ticket_dbh = '';
1134 if ($conf->config('ticket_system') eq 'RT_Internal') {
1136 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1137 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1138 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1139 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1142 if ( $ticket_dbh ) {
1144 my $ticket_sth = $ticket_dbh->prepare(
1145 'DELETE FROM Links WHERE Target = ?'
1147 my $errstr = $ticket_dbh->errstr;
1148 $dbh->rollback if $oldAutoCommit;
1151 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1153 my $errstr = $ticket_sth->errstr;
1154 $dbh->rollback if $oldAutoCommit;
1158 #check and see if the customer is the only link on the ticket, and
1159 #if so, set the ticket to deleted status in RT?
1160 #maybe someday, for now this will at least fix tickets not displaying
1164 #delete the customer record
1166 my $error = $self->SUPER::delete;
1168 $dbh->rollback if $oldAutoCommit;
1172 # cust_main exports!
1174 #my $export_args = $options{'export_args'} || [];
1177 map qsearch( 'part_export', {exportnum=>$_} ),
1178 $conf->config('cust_main-exports'); #, $agentnum
1180 foreach my $part_export ( @part_export ) {
1181 my $error = $part_export->export_delete( $self ); #, @$export_args);
1183 $dbh->rollback if $oldAutoCommit;
1184 return "exporting to ". $part_export->exporttype.
1185 " (transaction rolled back): $error";
1189 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1194 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1196 This merges this customer into the provided new custnum, and then deletes the
1197 customer. If there is an error, returns the error, otherwise returns false.
1199 The source customer's name, company name, phone numbers, agent,
1200 referring customer, customer class, advertising source, order taker, and
1201 billing information (except balance) are discarded.
1203 All packages are moved to the target customer. Packages with package locations
1204 are preserved. Packages without package locations are moved to a new package
1205 location with the source customer's service/shipping address.
1207 All invoices, statements, payments, credits and refunds are moved to the target
1208 customer. The source customer's balance is added to the target customer.
1210 All notes, attachments, tickets and customer tags are moved to the target
1213 Change history is not currently moved.
1218 my( $self, $new_custnum, %opt ) = @_;
1220 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1222 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1223 return "Invalid new customer number: $new_custnum";
1226 local $SIG{HUP} = 'IGNORE';
1227 local $SIG{INT} = 'IGNORE';
1228 local $SIG{QUIT} = 'IGNORE';
1229 local $SIG{TERM} = 'IGNORE';
1230 local $SIG{TSTP} = 'IGNORE';
1231 local $SIG{PIPE} = 'IGNORE';
1233 my $oldAutoCommit = $FS::UID::AutoCommit;
1234 local $FS::UID::AutoCommit = 0;
1237 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1238 $dbh->rollback if $oldAutoCommit;
1239 return "Can't merge a master agent customer";
1242 #use FS::access_user
1243 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1244 $dbh->rollback if $oldAutoCommit;
1245 return "Can't merge a master employee customer";
1248 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1249 'status' => { op=>'!=', value=>'done' },
1253 $dbh->rollback if $oldAutoCommit;
1254 return "Can't merge a customer with pending payments";
1257 tie my %financial_tables, 'Tie::IxHash',
1258 'cust_bill' => 'invoices',
1259 'cust_statement' => 'statements',
1260 'cust_credit' => 'credits',
1261 'cust_pay' => 'payments',
1262 'cust_pay_void' => 'voided payments',
1263 'cust_refund' => 'refunds',
1266 foreach my $table ( keys %financial_tables ) {
1268 my @records = $self->$table();
1270 foreach my $record ( @records ) {
1271 $record->custnum($new_custnum);
1272 my $error = $record->replace;
1274 $dbh->rollback if $oldAutoCommit;
1275 return "Error merging ". $financial_tables{$table}. ": $error\n";
1281 my $name = $self->ship_name;
1283 my $locationnum = '';
1284 foreach my $cust_pkg ( $self->all_pkgs ) {
1285 $cust_pkg->custnum($new_custnum);
1287 unless ( $cust_pkg->locationnum ) {
1288 unless ( $locationnum ) {
1289 my $cust_location = new FS::cust_location {
1290 $self->location_hash,
1291 'custnum' => $new_custnum,
1293 my $error = $cust_location->insert;
1295 $dbh->rollback if $oldAutoCommit;
1298 $locationnum = $cust_location->locationnum;
1300 $cust_pkg->locationnum($locationnum);
1303 my $error = $cust_pkg->replace;
1305 $dbh->rollback if $oldAutoCommit;
1309 # add customer (ship) name to svc_phone.phone_name if blank
1310 my @cust_svc = $cust_pkg->cust_svc;
1311 foreach my $cust_svc (@cust_svc) {
1312 my($label, $value, $svcdb) = $cust_svc->label;
1313 next unless $svcdb eq 'svc_phone';
1314 my $svc_phone = $cust_svc->svc_x;
1315 next if $svc_phone->phone_name;
1316 $svc_phone->phone_name($name);
1317 my $error = $svc_phone->replace;
1319 $dbh->rollback if $oldAutoCommit;
1327 # cust_tax_exempt (texas tax exemptions)
1328 # cust_recon (some sort of not-well understood thing for OnPac)
1330 #these are moved over
1331 foreach my $table (qw(
1332 cust_tag cust_location contact cust_attachment cust_main_note
1333 cust_tax_adjustment cust_pay_batch queue
1335 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1336 $record->custnum($new_custnum);
1337 my $error = $record->replace;
1339 $dbh->rollback if $oldAutoCommit;
1345 #these aren't preserved
1346 foreach my $table (qw(
1347 cust_main_exemption cust_main_invoice
1349 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1350 my $error = $record->delete;
1352 $dbh->rollback if $oldAutoCommit;
1359 my $sth = $dbh->prepare(
1360 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1362 my $errstr = $dbh->errstr;
1363 $dbh->rollback if $oldAutoCommit;
1366 $sth->execute($new_custnum, $self->custnum) or do {
1367 my $errstr = $sth->errstr;
1368 $dbh->rollback if $oldAutoCommit;
1374 my $ticket_dbh = '';
1375 if ($conf->config('ticket_system') eq 'RT_Internal') {
1377 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1378 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1379 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1380 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1383 if ( $ticket_dbh ) {
1385 my $ticket_sth = $ticket_dbh->prepare(
1386 'UPDATE Links SET Target = ? WHERE Target = ?'
1388 my $errstr = $ticket_dbh->errstr;
1389 $dbh->rollback if $oldAutoCommit;
1392 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1393 'freeside://freeside/cust_main/'.$self->custnum)
1395 my $errstr = $ticket_sth->errstr;
1396 $dbh->rollback if $oldAutoCommit;
1402 #delete the customer record
1404 my $error = $self->delete;
1406 $dbh->rollback if $oldAutoCommit;
1410 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1415 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1418 Replaces the OLD_RECORD with this one in the database. If there is an error,
1419 returns the error, otherwise returns false.
1421 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1422 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1423 expected and rollback the entire transaction; it is not necessary to call
1424 check_invoicing_list first. Here's an example:
1426 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1428 Currently available options are: I<tax_exemption>.
1430 The I<tax_exemption> option can be set to an arrayref of tax names.
1431 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1438 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1440 : $self->replace_old;
1444 warn "$me replace called\n"
1447 my $curuser = $FS::CurrentUser::CurrentUser;
1448 if ( $self->payby eq 'COMP'
1449 && $self->payby ne $old->payby
1450 && ! $curuser->access_right('Complimentary customer')
1453 return "You are not permitted to create complimentary accounts.";
1456 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1457 && $conf->exists('enable_taxproducts')
1460 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1462 $self->set('geocode', '')
1463 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1464 && length($self->get($pre.'zip')) >= 10;
1467 local($ignore_expired_card) = 1
1468 if $old->payby =~ /^(CARD|DCRD)$/
1469 && $self->payby =~ /^(CARD|DCRD)$/
1470 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1472 local $SIG{HUP} = 'IGNORE';
1473 local $SIG{INT} = 'IGNORE';
1474 local $SIG{QUIT} = 'IGNORE';
1475 local $SIG{TERM} = 'IGNORE';
1476 local $SIG{TSTP} = 'IGNORE';
1477 local $SIG{PIPE} = 'IGNORE';
1479 my $oldAutoCommit = $FS::UID::AutoCommit;
1480 local $FS::UID::AutoCommit = 0;
1483 my $error = $self->SUPER::replace($old);
1486 $dbh->rollback if $oldAutoCommit;
1490 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1491 my $invoicing_list = shift @param;
1492 $error = $self->check_invoicing_list( $invoicing_list );
1494 $dbh->rollback if $oldAutoCommit;
1497 $self->invoicing_list( $invoicing_list );
1500 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1502 #this could be more efficient than deleting and re-inserting, if it matters
1503 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1504 my $error = $cust_tag->delete;
1506 $dbh->rollback if $oldAutoCommit;
1510 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1511 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1512 'custnum' => $self->custnum };
1513 my $error = $cust_tag->insert;
1515 $dbh->rollback if $oldAutoCommit;
1522 my %options = @param;
1524 my $tax_exemption = delete $options{'tax_exemption'};
1525 if ( $tax_exemption ) {
1527 my %cust_main_exemption =
1528 map { $_->taxname => $_ }
1529 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1531 foreach my $taxname ( @$tax_exemption ) {
1533 next if delete $cust_main_exemption{$taxname};
1535 my $cust_main_exemption = new FS::cust_main_exemption {
1536 'custnum' => $self->custnum,
1537 'taxname' => $taxname,
1539 my $error = $cust_main_exemption->insert;
1541 $dbh->rollback if $oldAutoCommit;
1542 return "inserting cust_main_exemption (transaction rolled back): $error";
1546 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1547 my $error = $cust_main_exemption->delete;
1549 $dbh->rollback if $oldAutoCommit;
1550 return "deleting cust_main_exemption (transaction rolled back): $error";
1556 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1557 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1558 && $self->get('payinfo') !~ /^99\d{14}$/
1560 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1565 # card/check/lec info has changed, want to retry realtime_ invoice events
1566 my $error = $self->retry_realtime;
1568 $dbh->rollback if $oldAutoCommit;
1573 unless ( $import || $skip_fuzzyfiles ) {
1574 $error = $self->queue_fuzzyfiles_update;
1576 $dbh->rollback if $oldAutoCommit;
1577 return "updating fuzzy search cache: $error";
1581 # cust_main exports!
1583 my $export_args = $options{'export_args'} || [];
1586 map qsearch( 'part_export', {exportnum=>$_} ),
1587 $conf->config('cust_main-exports'); #, $agentnum
1589 foreach my $part_export ( @part_export ) {
1590 my $error = $part_export->export_replace( $self, $old, @$export_args);
1592 $dbh->rollback if $oldAutoCommit;
1593 return "exporting to ". $part_export->exporttype.
1594 " (transaction rolled back): $error";
1598 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1603 =item queue_fuzzyfiles_update
1605 Used by insert & replace to update the fuzzy search cache
1609 sub queue_fuzzyfiles_update {
1612 local $SIG{HUP} = 'IGNORE';
1613 local $SIG{INT} = 'IGNORE';
1614 local $SIG{QUIT} = 'IGNORE';
1615 local $SIG{TERM} = 'IGNORE';
1616 local $SIG{TSTP} = 'IGNORE';
1617 local $SIG{PIPE} = 'IGNORE';
1619 my $oldAutoCommit = $FS::UID::AutoCommit;
1620 local $FS::UID::AutoCommit = 0;
1623 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1624 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1626 $dbh->rollback if $oldAutoCommit;
1627 return "queueing job (transaction rolled back): $error";
1630 if ( $self->ship_last ) {
1631 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1632 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1634 $dbh->rollback if $oldAutoCommit;
1635 return "queueing job (transaction rolled back): $error";
1639 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1646 Checks all fields to make sure this is a valid customer record. If there is
1647 an error, returns the error, otherwise returns false. Called by the insert
1648 and replace methods.
1655 warn "$me check BEFORE: \n". $self->_dump
1659 $self->ut_numbern('custnum')
1660 || $self->ut_number('agentnum')
1661 || $self->ut_textn('agent_custid')
1662 || $self->ut_number('refnum')
1663 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1664 || $self->ut_textn('custbatch')
1665 || $self->ut_name('last')
1666 || $self->ut_name('first')
1667 || $self->ut_snumbern('birthdate')
1668 || $self->ut_snumbern('signupdate')
1669 || $self->ut_textn('company')
1670 || $self->ut_text('address1')
1671 || $self->ut_textn('address2')
1672 || $self->ut_text('city')
1673 || $self->ut_textn('county')
1674 || $self->ut_textn('state')
1675 || $self->ut_country('country')
1676 || $self->ut_anything('comments')
1677 || $self->ut_numbern('referral_custnum')
1678 || $self->ut_textn('stateid')
1679 || $self->ut_textn('stateid_state')
1680 || $self->ut_textn('invoice_terms')
1681 || $self->ut_alphan('geocode')
1682 || $self->ut_floatn('cdr_termination_percentage')
1683 || $self->ut_floatn('credit_limit')
1684 || $self->ut_numbern('billday')
1687 #barf. need message catalogs. i18n. etc.
1688 $error .= "Please select an advertising source."
1689 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1690 return $error if $error;
1692 return "Unknown agent"
1693 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1695 return "Unknown refnum"
1696 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1698 return "Unknown referring custnum: ". $self->referral_custnum
1699 unless ! $self->referral_custnum
1700 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1702 if ( $self->censustract ne '' ) {
1703 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1704 or return "Illegal census tract: ". $self->censustract;
1706 $self->censustract("$1.$2");
1709 if ( $self->ss eq '' ) {
1714 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1715 or return "Illegal social security number: ". $self->ss;
1716 $self->ss("$1-$2-$3");
1720 # bad idea to disable, causes billing to fail because of no tax rates later
1721 # except we don't fail any more
1722 unless ( $import ) {
1723 unless ( qsearch('cust_main_county', {
1724 'country' => $self->country,
1727 return "Unknown state/county/country: ".
1728 $self->state. "/". $self->county. "/". $self->country
1729 unless qsearch('cust_main_county',{
1730 'state' => $self->state,
1731 'county' => $self->county,
1732 'country' => $self->country,
1738 $self->ut_phonen('daytime', $self->country)
1739 || $self->ut_phonen('night', $self->country)
1740 || $self->ut_phonen('fax', $self->country)
1742 return $error if $error;
1744 unless ( $ignore_illegal_zip ) {
1745 $error = $self->ut_zip('zip', $self->country);
1746 return $error if $error;
1749 if ( $conf->exists('cust_main-require_phone')
1750 && ! length($self->daytime) && ! length($self->night)
1753 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1755 : FS::Msgcat::_gettext('daytime');
1756 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1758 : FS::Msgcat::_gettext('night');
1760 return "$daytime_label or $night_label is required"
1764 if ( $self->has_ship_address
1765 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1766 $self->addr_fields )
1770 $self->ut_name('ship_last')
1771 || $self->ut_name('ship_first')
1772 || $self->ut_textn('ship_company')
1773 || $self->ut_text('ship_address1')
1774 || $self->ut_textn('ship_address2')
1775 || $self->ut_text('ship_city')
1776 || $self->ut_textn('ship_county')
1777 || $self->ut_textn('ship_state')
1778 || $self->ut_country('ship_country')
1780 return $error if $error;
1782 #false laziness with above
1783 unless ( qsearchs('cust_main_county', {
1784 'country' => $self->ship_country,
1787 return "Unknown ship_state/ship_county/ship_country: ".
1788 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1789 unless qsearch('cust_main_county',{
1790 'state' => $self->ship_state,
1791 'county' => $self->ship_county,
1792 'country' => $self->ship_country,
1798 $self->ut_phonen('ship_daytime', $self->ship_country)
1799 || $self->ut_phonen('ship_night', $self->ship_country)
1800 || $self->ut_phonen('ship_fax', $self->ship_country)
1802 return $error if $error;
1804 unless ( $ignore_illegal_zip ) {
1805 $error = $self->ut_zip('ship_zip', $self->ship_country);
1806 return $error if $error;
1808 return "Unit # is required."
1809 if $self->ship_address2 =~ /^\s*$/
1810 && $conf->exists('cust_main-require_address2');
1812 } else { # ship_ info eq billing info, so don't store dup info in database
1814 $self->setfield("ship_$_", '')
1815 foreach $self->addr_fields;
1817 return "Unit # is required."
1818 if $self->address2 =~ /^\s*$/
1819 && $conf->exists('cust_main-require_address2');
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 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1849 my $payinfo = $self->payinfo;
1850 $payinfo =~ s/\D//g;
1851 $payinfo =~ /^(\d{13,16})$/
1852 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1854 $self->payinfo($payinfo);
1856 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1858 return gettext('unknown_card_type')
1859 if $self->payinfo !~ /^99\d{14}$/ #token
1860 && cardtype($self->payinfo) eq "Unknown";
1862 unless ( $ignore_banned_card ) {
1863 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1865 return 'Banned credit card: banned on '.
1866 time2str('%a %h %o at %r', $ban->_date).
1867 ' by '. $ban->otaker.
1868 ' (ban# '. $ban->bannum. ')';
1872 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1873 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1874 $self->paycvv =~ /^(\d{4})$/
1875 or return "CVV2 (CID) for American Express cards is four digits.";
1878 $self->paycvv =~ /^(\d{3})$/
1879 or return "CVV2 (CVC2/CID) is three digits.";
1886 my $cardtype = cardtype($payinfo);
1887 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1889 return "Start date or issue number is required for $cardtype cards"
1890 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1892 return "Start month must be between 1 and 12"
1893 if $self->paystart_month
1894 and $self->paystart_month < 1 || $self->paystart_month > 12;
1896 return "Start year must be 1990 or later"
1897 if $self->paystart_year
1898 and $self->paystart_year < 1990;
1900 return "Issue number must be beween 1 and 99"
1902 and $self->payissue < 1 || $self->payissue > 99;
1905 $self->paystart_month('');
1906 $self->paystart_year('');
1907 $self->payissue('');
1910 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1912 my $payinfo = $self->payinfo;
1913 $payinfo =~ s/[^\d\@]//g;
1914 if ( $conf->exists('echeck-nonus') ) {
1915 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1916 $payinfo = "$1\@$2";
1918 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1919 $payinfo = "$1\@$2";
1921 $self->payinfo($payinfo);
1924 unless ( $ignore_banned_card ) {
1925 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1927 return 'Banned ACH account: banned on '.
1928 time2str('%a %h %o at %r', $ban->_date).
1929 ' by '. $ban->otaker.
1930 ' (ban# '. $ban->bannum. ')';
1934 } elsif ( $self->payby eq 'LECB' ) {
1936 my $payinfo = $self->payinfo;
1937 $payinfo =~ s/\D//g;
1938 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1940 $self->payinfo($payinfo);
1943 } elsif ( $self->payby eq 'BILL' ) {
1945 $error = $self->ut_textn('payinfo');
1946 return "Illegal P.O. number: ". $self->payinfo if $error;
1949 } elsif ( $self->payby eq 'COMP' ) {
1951 my $curuser = $FS::CurrentUser::CurrentUser;
1952 if ( ! $self->custnum
1953 && ! $curuser->access_right('Complimentary customer')
1956 return "You are not permitted to create complimentary accounts."
1959 $error = $self->ut_textn('payinfo');
1960 return "Illegal comp account issuer: ". $self->payinfo if $error;
1963 } elsif ( $self->payby eq 'PREPAY' ) {
1965 my $payinfo = $self->payinfo;
1966 $payinfo =~ s/\W//g; #anything else would just confuse things
1967 $self->payinfo($payinfo);
1968 $error = $self->ut_alpha('payinfo');
1969 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1970 return "Unknown prepayment identifier"
1971 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1976 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1977 return "Expiration date required"
1978 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1982 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1983 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1984 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1985 ( $m, $y ) = ( $2, "19$1" );
1986 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1987 ( $m, $y ) = ( $3, "20$2" );
1989 return "Illegal expiration date: ". $self->paydate;
1991 $m = sprintf('%02d',$m);
1992 $self->paydate("$y-$m-01");
1993 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1994 return gettext('expired_card')
1996 && !$ignore_expired_card
1997 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2000 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2001 ( ! $conf->exists('require_cardname')
2002 || $self->payby !~ /^(CARD|DCRD)$/ )
2004 $self->payname( $self->first. " ". $self->getfield('last') );
2006 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2007 or return gettext('illegal_name'). " payname: ". $self->payname;
2011 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2012 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2016 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2018 warn "$me check AFTER: \n". $self->_dump
2021 $self->SUPER::check;
2026 Returns a list of fields which have ship_ duplicates.
2031 qw( last first company
2032 address1 address2 city county state zip country
2037 =item has_ship_address
2039 Returns true if this customer record has a separate shipping address.
2043 sub has_ship_address {
2045 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2050 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2051 city, county, state, zip, country, and geocode. The shipping address is used if present.
2057 Returns all locations (see L<FS::cust_location>) for this customer.
2063 qsearch('cust_location', { 'custnum' => $self->custnum } );
2068 Returns all contacts (see L<FS::contact>) for this customer.
2072 #already used :/ sub contact {
2075 qsearch('contact', { 'custnum' => $self->custnum } );
2080 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2081 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2082 on success or a list of errors.
2088 grep { $_->unsuspend } $self->suspended_pkgs;
2093 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2095 Returns a list: an empty list on success or a list of errors.
2101 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2104 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2106 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2107 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2108 of a list of pkgparts; the hashref has the following keys:
2112 =item pkgparts - listref of pkgparts
2114 =item (other options are passed to the suspend method)
2119 Returns a list: an empty list on success or a list of errors.
2123 sub suspend_if_pkgpart {
2125 my (@pkgparts, %opt);
2126 if (ref($_[0]) eq 'HASH'){
2127 @pkgparts = @{$_[0]{pkgparts}};
2132 grep { $_->suspend(%opt) }
2133 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2134 $self->unsuspended_pkgs;
2137 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2139 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2140 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2141 instead of a list of pkgparts; the hashref has the following keys:
2145 =item pkgparts - listref of pkgparts
2147 =item (other options are passed to the suspend method)
2151 Returns a list: an empty list on success or a list of errors.
2155 sub suspend_unless_pkgpart {
2157 my (@pkgparts, %opt);
2158 if (ref($_[0]) eq 'HASH'){
2159 @pkgparts = @{$_[0]{pkgparts}};
2164 grep { $_->suspend(%opt) }
2165 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2166 $self->unsuspended_pkgs;
2169 =item cancel [ OPTION => VALUE ... ]
2171 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2173 Available options are:
2177 =item quiet - can be set true to supress email cancellation notices.
2179 =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.
2181 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2183 =item nobill - can be set true to skip billing if it might otherwise be done.
2187 Always returns a list: an empty list on success or a list of errors.
2191 # nb that dates are not specified as valid options to this method
2194 my( $self, %opt ) = @_;
2196 warn "$me cancel called on customer ". $self->custnum. " with options ".
2197 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2200 return ( 'access denied' )
2201 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2203 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2205 #should try decryption (we might have the private key)
2206 # and if not maybe queue a job for the server that does?
2207 return ( "Can't (yet) ban encrypted credit cards" )
2208 if $self->is_encrypted($self->payinfo);
2210 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2211 my $error = $ban->insert;
2212 return ( $error ) if $error;
2216 my @pkgs = $self->ncancelled_pkgs;
2218 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2220 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2221 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2225 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2226 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2229 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2232 sub _banned_pay_hashref {
2243 'payby' => $payby2ban{$self->payby},
2244 'payinfo' => md5_base64($self->payinfo),
2245 #don't ever *search* on reason! #'reason' =>
2251 Returns all notes (see L<FS::cust_main_note>) for this customer.
2256 my($self,$orderby_classnum) = (shift,shift);
2257 my $orderby = "_DATE DESC";
2258 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2259 qsearch( 'cust_main_note',
2260 { 'custnum' => $self->custnum },
2262 "ORDER BY $orderby",
2268 Returns the agent (see L<FS::agent>) for this customer.
2274 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2279 Returns the agent name (see L<FS::agent>) for this customer.
2285 $self->agent->agent;
2290 Returns any tags associated with this customer, as FS::cust_tag objects,
2291 or an empty list if there are no tags.
2297 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2302 Returns any tags associated with this customer, as FS::part_tag objects,
2303 or an empty list if there are no tags.
2309 map $_->part_tag, $self->cust_tag;
2315 Returns the customer class, as an FS::cust_class object, or the empty string
2316 if there is no customer class.
2322 if ( $self->classnum ) {
2323 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2331 Returns the customer category name, or the empty string if there is no customer
2338 my $cust_class = $self->cust_class;
2340 ? $cust_class->categoryname
2346 Returns the customer class name, or the empty string if there is no customer
2353 my $cust_class = $self->cust_class;
2355 ? $cust_class->classname
2359 =item BILLING METHODS
2361 Documentation on billing methods has been moved to
2362 L<FS::cust_main::Billing>.
2364 =item REALTIME BILLING METHODS
2366 Documentation on realtime billing methods has been moved to
2367 L<FS::cust_main::Billing_Realtime>.
2371 Removes the I<paycvv> field from the database directly.
2373 If there is an error, returns the error, otherwise returns false.
2379 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2380 or return dbh->errstr;
2381 $sth->execute($self->custnum)
2382 or return $sth->errstr;
2387 =item batch_card OPTION => VALUE...
2389 Adds a payment for this invoice to the pending credit card batch (see
2390 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2391 runs the payment using a realtime gateway.
2396 my ($self, %options) = @_;
2399 if (exists($options{amount})) {
2400 $amount = $options{amount};
2402 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2404 return '' unless $amount > 0;
2406 my $invnum = delete $options{invnum};
2407 my $payby = $options{payby} || $self->payby; #still dubious
2409 if ($options{'realtime'}) {
2410 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2416 my $oldAutoCommit = $FS::UID::AutoCommit;
2417 local $FS::UID::AutoCommit = 0;
2420 #this needs to handle mysql as well as Pg, like svc_acct.pm
2421 #(make it into a common function if folks need to do batching with mysql)
2422 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2423 or return "Cannot lock pay_batch: " . $dbh->errstr;
2427 'payby' => FS::payby->payby2payment($payby),
2430 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2432 unless ( $pay_batch ) {
2433 $pay_batch = new FS::pay_batch \%pay_batch;
2434 my $error = $pay_batch->insert;
2436 $dbh->rollback if $oldAutoCommit;
2437 die "error creating new batch: $error\n";
2441 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2442 'batchnum' => $pay_batch->batchnum,
2443 'custnum' => $self->custnum,
2446 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2448 $options{$_} = '' unless exists($options{$_});
2451 my $cust_pay_batch = new FS::cust_pay_batch ( {
2452 'batchnum' => $pay_batch->batchnum,
2453 'invnum' => $invnum || 0, # is there a better value?
2454 # this field should be
2456 # cust_bill_pay_batch now
2457 'custnum' => $self->custnum,
2458 'last' => $self->getfield('last'),
2459 'first' => $self->getfield('first'),
2460 'address1' => $options{address1} || $self->address1,
2461 'address2' => $options{address2} || $self->address2,
2462 'city' => $options{city} || $self->city,
2463 'state' => $options{state} || $self->state,
2464 'zip' => $options{zip} || $self->zip,
2465 'country' => $options{country} || $self->country,
2466 'payby' => $options{payby} || $self->payby,
2467 'payinfo' => $options{payinfo} || $self->payinfo,
2468 'exp' => $options{paydate} || $self->paydate,
2469 'payname' => $options{payname} || $self->payname,
2470 'amount' => $amount, # consolidating
2473 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2474 if $old_cust_pay_batch;
2477 if ($old_cust_pay_batch) {
2478 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2480 $error = $cust_pay_batch->insert;
2484 $dbh->rollback if $oldAutoCommit;
2488 my $unapplied = $self->total_unapplied_credits
2489 + $self->total_unapplied_payments
2490 + $self->in_transit_payments;
2491 foreach my $cust_bill ($self->open_cust_bill) {
2492 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2493 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2494 'invnum' => $cust_bill->invnum,
2495 'paybatchnum' => $cust_pay_batch->paybatchnum,
2496 'amount' => $cust_bill->owed,
2499 if ($unapplied >= $cust_bill_pay_batch->amount){
2500 $unapplied -= $cust_bill_pay_batch->amount;
2503 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2504 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2506 $error = $cust_bill_pay_batch->insert;
2508 $dbh->rollback if $oldAutoCommit;
2513 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2519 Returns the total owed for this customer on all invoices
2520 (see L<FS::cust_bill/owed>).
2526 $self->total_owed_date(2145859200); #12/31/2037
2529 =item total_owed_date TIME
2531 Returns the total owed for this customer on all invoices with date earlier than
2532 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2533 see L<Time::Local> and L<Date::Parse> for conversion functions.
2537 sub total_owed_date {
2541 my $custnum = $self->custnum;
2543 my $owed_sql = FS::cust_bill->owed_sql;
2546 SELECT SUM($owed_sql) FROM cust_bill
2547 WHERE custnum = $custnum
2551 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2555 =item total_owed_pkgnum PKGNUM
2557 Returns the total owed on all invoices for this customer's specific package
2558 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2562 sub total_owed_pkgnum {
2563 my( $self, $pkgnum ) = @_;
2564 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2567 =item total_owed_date_pkgnum TIME PKGNUM
2569 Returns the total owed for this customer's specific package when using
2570 experimental package balances on all invoices with date earlier than
2571 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2572 see L<Time::Local> and L<Date::Parse> for conversion functions.
2576 sub total_owed_date_pkgnum {
2577 my( $self, $time, $pkgnum ) = @_;
2580 foreach my $cust_bill (
2581 grep { $_->_date <= $time }
2582 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2584 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2586 sprintf( "%.2f", $total_bill );
2592 Returns the total amount of all payments.
2599 $total += $_->paid foreach $self->cust_pay;
2600 sprintf( "%.2f", $total );
2603 =item total_unapplied_credits
2605 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2606 customer. See L<FS::cust_credit/credited>.
2608 =item total_credited
2610 Old name for total_unapplied_credits. Don't use.
2614 sub total_credited {
2615 #carp "total_credited deprecated, use total_unapplied_credits";
2616 shift->total_unapplied_credits(@_);
2619 sub total_unapplied_credits {
2622 my $custnum = $self->custnum;
2624 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2627 SELECT SUM($unapplied_sql) FROM cust_credit
2628 WHERE custnum = $custnum
2631 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2635 =item total_unapplied_credits_pkgnum PKGNUM
2637 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2638 customer. See L<FS::cust_credit/credited>.
2642 sub total_unapplied_credits_pkgnum {
2643 my( $self, $pkgnum ) = @_;
2644 my $total_credit = 0;
2645 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2646 sprintf( "%.2f", $total_credit );
2650 =item total_unapplied_payments
2652 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2653 See L<FS::cust_pay/unapplied>.
2657 sub total_unapplied_payments {
2660 my $custnum = $self->custnum;
2662 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2665 SELECT SUM($unapplied_sql) FROM cust_pay
2666 WHERE custnum = $custnum
2669 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2673 =item total_unapplied_payments_pkgnum PKGNUM
2675 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2676 specific package when using experimental package balances. See
2677 L<FS::cust_pay/unapplied>.
2681 sub total_unapplied_payments_pkgnum {
2682 my( $self, $pkgnum ) = @_;
2683 my $total_unapplied = 0;
2684 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2685 sprintf( "%.2f", $total_unapplied );
2689 =item total_unapplied_refunds
2691 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2692 customer. See L<FS::cust_refund/unapplied>.
2696 sub total_unapplied_refunds {
2698 my $custnum = $self->custnum;
2700 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2703 SELECT SUM($unapplied_sql) FROM cust_refund
2704 WHERE custnum = $custnum
2707 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2713 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2714 total_unapplied_credits minus total_unapplied_payments).
2720 $self->balance_date_range;
2723 =item balance_date TIME
2725 Returns the balance for this customer, only considering invoices with date
2726 earlier than TIME (total_owed_date minus total_credited minus
2727 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2728 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2735 $self->balance_date_range(shift);
2738 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2740 Returns the balance for this customer, optionally considering invoices with
2741 date earlier than START_TIME, and not later than END_TIME
2742 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2744 Times are specified as SQL fragments or numeric
2745 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2746 L<Date::Parse> for conversion functions. The empty string can be passed
2747 to disable that time constraint completely.
2749 Available options are:
2753 =item unapplied_date
2755 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)
2761 sub balance_date_range {
2763 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2764 ') FROM cust_main WHERE custnum='. $self->custnum;
2765 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2768 =item balance_pkgnum PKGNUM
2770 Returns the balance for this customer's specific package when using
2771 experimental package balances (total_owed plus total_unrefunded, minus
2772 total_unapplied_credits minus total_unapplied_payments)
2776 sub balance_pkgnum {
2777 my( $self, $pkgnum ) = @_;
2780 $self->total_owed_pkgnum($pkgnum)
2781 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2782 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2783 - $self->total_unapplied_credits_pkgnum($pkgnum)
2784 - $self->total_unapplied_payments_pkgnum($pkgnum)
2788 =item in_transit_payments
2790 Returns the total of requests for payments for this customer pending in
2791 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2795 sub in_transit_payments {
2797 my $in_transit_payments = 0;
2798 foreach my $pay_batch ( qsearch('pay_batch', {
2801 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2802 'batchnum' => $pay_batch->batchnum,
2803 'custnum' => $self->custnum,
2805 $in_transit_payments += $cust_pay_batch->amount;
2808 sprintf( "%.2f", $in_transit_payments );
2813 Returns a hash of useful information for making a payment.
2823 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2824 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2825 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2829 For credit card transactions:
2841 For electronic check transactions:
2856 $return{balance} = $self->balance;
2858 $return{payname} = $self->payname
2859 || ( $self->first. ' '. $self->get('last') );
2861 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2863 $return{payby} = $self->payby;
2864 $return{stateid_state} = $self->stateid_state;
2866 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2867 $return{card_type} = cardtype($self->payinfo);
2868 $return{payinfo} = $self->paymask;
2870 @return{'month', 'year'} = $self->paydate_monthyear;
2874 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2875 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2876 $return{payinfo1} = $payinfo1;
2877 $return{payinfo2} = $payinfo2;
2878 $return{paytype} = $self->paytype;
2879 $return{paystate} = $self->paystate;
2883 #doubleclick protection
2885 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2891 =item paydate_monthyear
2893 Returns a two-element list consisting of the month and year of this customer's
2894 paydate (credit card expiration date for CARD customers)
2898 sub paydate_monthyear {
2900 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2902 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2909 =item tax_exemption TAXNAME
2914 my( $self, $taxname ) = @_;
2916 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2917 'taxname' => $taxname,
2922 =item cust_main_exemption
2926 sub cust_main_exemption {
2928 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
2931 =item invoicing_list [ ARRAYREF ]
2933 If an arguement is given, sets these email addresses as invoice recipients
2934 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2935 (except as warnings), so use check_invoicing_list first.
2937 Returns a list of email addresses (with svcnum entries expanded).
2939 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2940 check it without disturbing anything by passing nothing.
2942 This interface may change in the future.
2946 sub invoicing_list {
2947 my( $self, $arrayref ) = @_;
2950 my @cust_main_invoice;
2951 if ( $self->custnum ) {
2952 @cust_main_invoice =
2953 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2955 @cust_main_invoice = ();
2957 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2958 #warn $cust_main_invoice->destnum;
2959 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2960 #warn $cust_main_invoice->destnum;
2961 my $error = $cust_main_invoice->delete;
2962 warn $error if $error;
2965 if ( $self->custnum ) {
2966 @cust_main_invoice =
2967 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2969 @cust_main_invoice = ();
2971 my %seen = map { $_->address => 1 } @cust_main_invoice;
2972 foreach my $address ( @{$arrayref} ) {
2973 next if exists $seen{$address} && $seen{$address};
2974 $seen{$address} = 1;
2975 my $cust_main_invoice = new FS::cust_main_invoice ( {
2976 'custnum' => $self->custnum,
2979 my $error = $cust_main_invoice->insert;
2980 warn $error if $error;
2984 if ( $self->custnum ) {
2986 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2993 =item check_invoicing_list ARRAYREF
2995 Checks these arguements as valid input for the invoicing_list method. If there
2996 is an error, returns the error, otherwise returns false.
3000 sub check_invoicing_list {
3001 my( $self, $arrayref ) = @_;
3003 foreach my $address ( @$arrayref ) {
3005 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3006 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3009 my $cust_main_invoice = new FS::cust_main_invoice ( {
3010 'custnum' => $self->custnum,
3013 my $error = $self->custnum
3014 ? $cust_main_invoice->check
3015 : $cust_main_invoice->checkdest
3017 return $error if $error;
3021 return "Email address required"
3022 if $conf->exists('cust_main-require_invoicing_list_email')
3023 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3028 =item set_default_invoicing_list
3030 Sets the invoicing list to all accounts associated with this customer,
3031 overwriting any previous invoicing list.
3035 sub set_default_invoicing_list {
3037 $self->invoicing_list($self->all_emails);
3042 Returns the email addresses of all accounts provisioned for this customer.
3049 foreach my $cust_pkg ( $self->all_pkgs ) {
3050 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3052 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3053 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3055 $list{$_}=1 foreach map { $_->email } @svc_acct;
3060 =item invoicing_list_addpost
3062 Adds postal invoicing to this customer. If this customer is already configured
3063 to receive postal invoices, does nothing.
3067 sub invoicing_list_addpost {
3069 return if grep { $_ eq 'POST' } $self->invoicing_list;
3070 my @invoicing_list = $self->invoicing_list;
3071 push @invoicing_list, 'POST';
3072 $self->invoicing_list(\@invoicing_list);
3075 =item invoicing_list_emailonly
3077 Returns the list of email invoice recipients (invoicing_list without non-email
3078 destinations such as POST and FAX).
3082 sub invoicing_list_emailonly {
3084 warn "$me invoicing_list_emailonly called"
3086 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3089 =item invoicing_list_emailonly_scalar
3091 Returns the list of email invoice recipients (invoicing_list without non-email
3092 destinations such as POST and FAX) as a comma-separated scalar.
3096 sub invoicing_list_emailonly_scalar {
3098 warn "$me invoicing_list_emailonly_scalar called"
3100 join(', ', $self->invoicing_list_emailonly);
3103 =item referral_custnum_cust_main
3105 Returns the customer who referred this customer (or the empty string, if
3106 this customer was not referred).
3108 Note the difference with referral_cust_main method: This method,
3109 referral_custnum_cust_main returns the single customer (if any) who referred
3110 this customer, while referral_cust_main returns an array of customers referred
3115 sub referral_custnum_cust_main {
3117 return '' unless $self->referral_custnum;
3118 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3121 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3123 Returns an array of customers referred by this customer (referral_custnum set
3124 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3125 customers referred by customers referred by this customer and so on, inclusive.
3126 The default behavior is DEPTH 1 (no recursion).
3128 Note the difference with referral_custnum_cust_main method: This method,
3129 referral_cust_main, returns an array of customers referred BY this customer,
3130 while referral_custnum_cust_main returns the single customer (if any) who
3131 referred this customer.
3135 sub referral_cust_main {
3137 my $depth = @_ ? shift : 1;
3138 my $exclude = @_ ? shift : {};
3141 map { $exclude->{$_->custnum}++; $_; }
3142 grep { ! $exclude->{ $_->custnum } }
3143 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3147 map { $_->referral_cust_main($depth-1, $exclude) }
3154 =item referral_cust_main_ncancelled
3156 Same as referral_cust_main, except only returns customers with uncancelled
3161 sub referral_cust_main_ncancelled {
3163 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3166 =item referral_cust_pkg [ DEPTH ]
3168 Like referral_cust_main, except returns a flat list of all unsuspended (and
3169 uncancelled) packages for each customer. The number of items in this list may
3170 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3174 sub referral_cust_pkg {
3176 my $depth = @_ ? shift : 1;
3178 map { $_->unsuspended_pkgs }
3179 grep { $_->unsuspended_pkgs }
3180 $self->referral_cust_main($depth);
3183 =item referring_cust_main
3185 Returns the single cust_main record for the customer who referred this customer
3186 (referral_custnum), or false.
3190 sub referring_cust_main {
3192 return '' unless $self->referral_custnum;
3193 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3196 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3198 Applies a credit to this customer. If there is an error, returns the error,
3199 otherwise returns false.
3201 REASON can be a text string, an FS::reason object, or a scalar reference to
3202 a reasonnum. If a text string, it will be automatically inserted as a new
3203 reason, and a 'reason_type' option must be passed to indicate the
3204 FS::reason_type for the new reason.
3206 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3208 Any other options are passed to FS::cust_credit::insert.
3213 my( $self, $amount, $reason, %options ) = @_;
3215 my $cust_credit = new FS::cust_credit {
3216 'custnum' => $self->custnum,
3217 'amount' => $amount,
3220 if ( ref($reason) ) {
3222 if ( ref($reason) eq 'SCALAR' ) {
3223 $cust_credit->reasonnum( $$reason );
3225 $cust_credit->reasonnum( $reason->reasonnum );
3229 $cust_credit->set('reason', $reason)
3232 for (qw( addlinfo eventnum )) {
3233 $cust_credit->$_( delete $options{$_} )
3234 if exists($options{$_});
3237 $cust_credit->insert(%options);
3241 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3243 Creates a one-time charge for this customer. If there is an error, returns
3244 the error, otherwise returns false.
3246 New-style, with a hashref of options:
3248 my $error = $cust_main->charge(
3252 'start_date' => str2time('7/4/2009'),
3253 'pkg' => 'Description',
3254 'comment' => 'Comment',
3255 'additional' => [], #extra invoice detail
3256 'classnum' => 1, #pkg_class
3258 'setuptax' => '', # or 'Y' for tax exempt
3261 'taxclass' => 'Tax class',
3264 'taxproduct' => 2, #part_pkg_taxproduct
3265 'override' => {}, #XXX describe
3267 #will be filled in with the new object
3268 'cust_pkg_ref' => \$cust_pkg,
3270 #generate an invoice immediately
3272 'invoice_terms' => '', #with these terms
3278 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3284 my ( $amount, $quantity, $start_date, $classnum );
3285 my ( $pkg, $comment, $additional );
3286 my ( $setuptax, $taxclass ); #internal taxes
3287 my ( $taxproduct, $override ); #vendor (CCH) taxes
3289 my $cust_pkg_ref = '';
3290 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3291 if ( ref( $_[0] ) ) {
3292 $amount = $_[0]->{amount};
3293 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3294 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3295 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3296 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3297 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3298 : '$'. sprintf("%.2f",$amount);
3299 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3300 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3301 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3302 $additional = $_[0]->{additional} || [];
3303 $taxproduct = $_[0]->{taxproductnum};
3304 $override = { '' => $_[0]->{tax_override} };
3305 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3306 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3307 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3312 $pkg = @_ ? shift : 'One-time charge';
3313 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3315 $taxclass = @_ ? shift : '';
3319 local $SIG{HUP} = 'IGNORE';
3320 local $SIG{INT} = 'IGNORE';
3321 local $SIG{QUIT} = 'IGNORE';
3322 local $SIG{TERM} = 'IGNORE';
3323 local $SIG{TSTP} = 'IGNORE';
3324 local $SIG{PIPE} = 'IGNORE';
3326 my $oldAutoCommit = $FS::UID::AutoCommit;
3327 local $FS::UID::AutoCommit = 0;
3330 my $part_pkg = new FS::part_pkg ( {
3332 'comment' => $comment,
3336 'classnum' => ( $classnum ? $classnum : '' ),
3337 'setuptax' => $setuptax,
3338 'taxclass' => $taxclass,
3339 'taxproductnum' => $taxproduct,
3342 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3343 ( 0 .. @$additional - 1 )
3345 'additional_count' => scalar(@$additional),
3346 'setup_fee' => $amount,
3349 my $error = $part_pkg->insert( options => \%options,
3350 tax_overrides => $override,
3353 $dbh->rollback if $oldAutoCommit;
3357 my $pkgpart = $part_pkg->pkgpart;
3358 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3359 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3360 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3361 $error = $type_pkgs->insert;
3363 $dbh->rollback if $oldAutoCommit;
3368 my $cust_pkg = new FS::cust_pkg ( {
3369 'custnum' => $self->custnum,
3370 'pkgpart' => $pkgpart,
3371 'quantity' => $quantity,
3372 'start_date' => $start_date,
3373 'no_auto' => $no_auto,
3376 $error = $cust_pkg->insert;
3378 $dbh->rollback if $oldAutoCommit;
3380 } elsif ( $cust_pkg_ref ) {
3381 ${$cust_pkg_ref} = $cust_pkg;
3385 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3386 'pkg_list' => [ $cust_pkg ],
3389 $dbh->rollback if $oldAutoCommit;
3394 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3399 #=item charge_postal_fee
3401 #Applies a one time charge this customer. If there is an error,
3402 #returns the error, returns the cust_pkg charge object or false
3403 #if there was no charge.
3407 # This should be a customer event. For that to work requires that bill
3408 # also be a customer event.
3410 sub charge_postal_fee {
3413 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3414 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3416 my $cust_pkg = new FS::cust_pkg ( {
3417 'custnum' => $self->custnum,
3418 'pkgpart' => $pkgpart,
3422 my $error = $cust_pkg->insert;
3423 $error ? $error : $cust_pkg;
3426 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3428 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3430 Optionally, a list or hashref of additional arguments to the qsearch call can
3437 my $opt = ref($_[0]) ? shift : { @_ };
3439 #return $self->num_cust_bill unless wantarray || keys %$opt;
3441 $opt->{'table'} = 'cust_bill';
3442 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3443 $opt->{'hashref'}{'custnum'} = $self->custnum;
3444 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3446 map { $_ } #behavior of sort undefined in scalar context
3447 sort { $a->_date <=> $b->_date }
3451 =item open_cust_bill
3453 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3458 sub open_cust_bill {
3462 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3468 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3470 Returns all the statements (see L<FS::cust_statement>) for this customer.
3472 Optionally, a list or hashref of additional arguments to the qsearch call can
3477 sub cust_statement {
3479 my $opt = ref($_[0]) ? shift : { @_ };
3481 #return $self->num_cust_statement unless wantarray || keys %$opt;
3483 $opt->{'table'} = 'cust_statement';
3484 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3485 $opt->{'hashref'}{'custnum'} = $self->custnum;
3486 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3488 map { $_ } #behavior of sort undefined in scalar context
3489 sort { $a->_date <=> $b->_date }
3495 Returns all the credits (see L<FS::cust_credit>) for this customer.
3501 map { $_ } #return $self->num_cust_credit unless wantarray;
3502 sort { $a->_date <=> $b->_date }
3503 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3506 =item cust_credit_pkgnum
3508 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3509 package when using experimental package balances.
3513 sub cust_credit_pkgnum {
3514 my( $self, $pkgnum ) = @_;
3515 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3516 sort { $a->_date <=> $b->_date }
3517 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3518 'pkgnum' => $pkgnum,
3525 Returns all the payments (see L<FS::cust_pay>) for this customer.
3531 return $self->num_cust_pay unless wantarray;
3532 sort { $a->_date <=> $b->_date }
3533 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3538 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3539 called automatically when the cust_pay method is used in a scalar context.
3545 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3546 my $sth = dbh->prepare($sql) or die dbh->errstr;
3547 $sth->execute($self->custnum) or die $sth->errstr;
3548 $sth->fetchrow_arrayref->[0];
3551 =item cust_pay_pkgnum
3553 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3554 package when using experimental package balances.
3558 sub cust_pay_pkgnum {
3559 my( $self, $pkgnum ) = @_;
3560 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3561 sort { $a->_date <=> $b->_date }
3562 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3563 'pkgnum' => $pkgnum,
3570 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3576 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3577 sort { $a->_date <=> $b->_date }
3578 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3581 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3583 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3585 Optionally, a list or hashref of additional arguments to the qsearch call can
3590 sub cust_pay_batch {
3592 my $opt = ref($_[0]) ? shift : { @_ };
3594 #return $self->num_cust_statement unless wantarray || keys %$opt;
3596 $opt->{'table'} = 'cust_pay_batch';
3597 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3598 $opt->{'hashref'}{'custnum'} = $self->custnum;
3599 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3601 map { $_ } #behavior of sort undefined in scalar context
3602 sort { $a->paybatchnum <=> $b->paybatchnum }
3606 =item cust_pay_pending
3608 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3609 (without status "done").
3613 sub cust_pay_pending {
3615 return $self->num_cust_pay_pending unless wantarray;
3616 sort { $a->_date <=> $b->_date }
3617 qsearch( 'cust_pay_pending', {
3618 'custnum' => $self->custnum,
3619 'status' => { op=>'!=', value=>'done' },
3624 =item cust_pay_pending_attempt
3626 Returns all payment attempts / declined payments for this customer, as pending
3627 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3628 a corresponding payment (see L<FS::cust_pay>).
3632 sub cust_pay_pending_attempt {
3634 return $self->num_cust_pay_pending_attempt unless wantarray;
3635 sort { $a->_date <=> $b->_date }
3636 qsearch( 'cust_pay_pending', {
3637 'custnum' => $self->custnum,
3644 =item num_cust_pay_pending
3646 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3647 customer (without status "done"). Also called automatically when the
3648 cust_pay_pending method is used in a scalar context.
3652 sub num_cust_pay_pending {
3655 " SELECT COUNT(*) FROM cust_pay_pending ".
3656 " WHERE custnum = ? AND status != 'done' ",
3661 =item num_cust_pay_pending_attempt
3663 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3664 customer, with status "done" but without a corresp. Also called automatically when the
3665 cust_pay_pending method is used in a scalar context.
3669 sub num_cust_pay_pending_attempt {
3672 " SELECT COUNT(*) FROM cust_pay_pending ".
3673 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3680 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3686 map { $_ } #return $self->num_cust_refund unless wantarray;
3687 sort { $a->_date <=> $b->_date }
3688 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3691 =item display_custnum
3693 Returns the displayed customer number for this customer: agent_custid if
3694 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3698 sub display_custnum {
3700 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3701 return $self->agent_custid;
3703 return $self->custnum;
3709 Returns a name string for this customer, either "Company (Last, First)" or
3716 my $name = $self->contact;
3717 $name = $self->company. " ($name)" if $self->company;
3723 Returns a name string for this (service/shipping) contact, either
3724 "Company (Last, First)" or "Last, First".
3730 if ( $self->get('ship_last') ) {
3731 my $name = $self->ship_contact;
3732 $name = $self->ship_company. " ($name)" if $self->ship_company;
3741 Returns a name string for this customer, either "Company" or "First Last".
3747 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3750 =item ship_name_short
3752 Returns a name string for this (service/shipping) contact, either "Company"
3757 sub ship_name_short {
3759 if ( $self->get('ship_last') ) {
3760 $self->ship_company !~ /^\s*$/
3761 ? $self->ship_company
3762 : $self->ship_contact_firstlast;
3764 $self->name_company_or_firstlast;
3770 Returns this customer's full (billing) contact name only, "Last, First"
3776 $self->get('last'). ', '. $self->first;
3781 Returns this customer's full (shipping) contact name only, "Last, First"
3787 $self->get('ship_last')
3788 ? $self->get('ship_last'). ', '. $self->ship_first
3792 =item contact_firstlast
3794 Returns this customers full (billing) contact name only, "First Last".
3798 sub contact_firstlast {
3800 $self->first. ' '. $self->get('last');
3803 =item ship_contact_firstlast
3805 Returns this customer's full (shipping) contact name only, "First Last".
3809 sub ship_contact_firstlast {
3811 $self->get('ship_last')
3812 ? $self->first. ' '. $self->get('ship_last')
3813 : $self->contact_firstlast;
3818 Returns this customer's full country name
3824 code2country($self->country);
3827 =item geocode DATA_VENDOR
3829 Returns a value for the customer location as encoded by DATA_VENDOR.
3830 Currently this only makes sense for "CCH" as DATA_VENDOR.
3838 Returns a status string for this customer, currently:
3842 =item prospect - No packages have ever been ordered
3844 =item ordered - Recurring packages all are new (not yet billed).
3846 =item active - One or more recurring packages is active
3848 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3850 =item suspended - All non-cancelled recurring packages are suspended
3852 =item cancelled - All recurring packages are cancelled
3856 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3857 cust_main-status_module configuration option.
3861 sub status { shift->cust_status(@_); }
3865 for my $status ( FS::cust_main->statuses() ) {
3866 my $method = $status.'_sql';
3867 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3868 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3869 $sth->execute( ($self->custnum) x $numnum )
3870 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3871 return $status if $sth->fetchrow_arrayref->[0];
3875 =item ucfirst_cust_status
3877 =item ucfirst_status
3879 Returns the status with the first character capitalized.
3883 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
3885 sub ucfirst_cust_status {
3887 ucfirst($self->cust_status);
3892 Returns a hex triplet color string for this customer's status.
3896 sub statuscolor { shift->cust_statuscolor(@_); }
3898 sub cust_statuscolor {
3900 __PACKAGE__->statuscolors->{$self->cust_status};
3905 Returns an array of hashes representing the customer's RT tickets.
3912 my $num = $conf->config('cust_main-max_tickets') || 10;
3915 if ( $conf->config('ticket_system') ) {
3916 unless ( $conf->config('ticket_system-custom_priority_field') ) {
3918 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
3922 foreach my $priority (
3923 $conf->config('ticket_system-custom_priority_field-values'), ''
3925 last if scalar(@tickets) >= $num;
3927 @{ FS::TicketSystem->customer_tickets( $self->custnum,
3928 $num - scalar(@tickets),
3938 # Return services representing svc_accts in customer support packages
3939 sub support_services {
3941 my %packages = map { $_ => 1 } $conf->config('support_packages');
3943 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
3944 grep { $_->part_svc->svcdb eq 'svc_acct' }
3945 map { $_->cust_svc }
3946 grep { exists $packages{ $_->pkgpart } }
3947 $self->ncancelled_pkgs;
3951 # Return a list of latitude/longitude for one of the services (if any)
3952 sub service_coordinates {
3956 grep { $_->latitude && $_->longitude }
3958 map { $_->cust_svc }
3959 $self->ncancelled_pkgs;
3961 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
3966 Returns a masked version of the named field
3971 my ($self,$field) = @_;
3975 'x'x(length($self->getfield($field))-4).
3976 substr($self->getfield($field), (length($self->getfield($field))-4));
3982 =head1 CLASS METHODS
3988 Class method that returns the list of possible status strings for customers
3989 (see L<the status method|/status>). For example:
3991 @statuses = FS::cust_main->statuses();
3997 keys %{ $self->statuscolors };
4000 =item cust_status_sql
4002 Returns an SQL fragment to determine the status of a cust_main record, as a
4007 sub cust_status_sql {
4009 for my $status ( FS::cust_main->statuses() ) {
4010 my $method = $status.'_sql';
4011 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4020 Returns an SQL expression identifying prospective cust_main records (customers
4021 with no packages ever ordered)
4025 use vars qw($select_count_pkgs);
4026 $select_count_pkgs =
4027 "SELECT COUNT(*) FROM cust_pkg
4028 WHERE cust_pkg.custnum = cust_main.custnum";
4030 sub select_count_pkgs_sql {
4035 " 0 = ( $select_count_pkgs ) ";
4040 Returns an SQL expression identifying ordered cust_main records (customers with
4041 no active packages, but recurring packages not yet setup or one time charges
4047 FS::cust_main->none_active_sql.
4048 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4053 Returns an SQL expression identifying active cust_main records (customers with
4054 active recurring packages).
4059 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4062 =item none_active_sql
4064 Returns an SQL expression identifying cust_main records with no active
4065 recurring packages. This includes customers of status prospect, ordered,
4066 inactive, and suspended.
4070 sub none_active_sql {
4071 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4076 Returns an SQL expression identifying inactive cust_main records (customers with
4077 no active recurring packages, but otherwise unsuspended/uncancelled).
4082 FS::cust_main->none_active_sql.
4083 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4089 Returns an SQL expression identifying suspended cust_main records.
4094 sub suspended_sql { susp_sql(@_); }
4096 FS::cust_main->none_active_sql.
4097 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4103 Returns an SQL expression identifying cancelled cust_main records.
4107 sub cancel_sql { shift->cancelled_sql(@_); }
4110 =item uncancelled_sql
4112 Returns an SQL expression identifying un-cancelled cust_main records.
4116 sub uncancelled_sql { uncancel_sql(@_); }
4117 sub uncancel_sql { "
4118 ( 0 < ( $select_count_pkgs
4119 AND ( cust_pkg.cancel IS NULL
4120 OR cust_pkg.cancel = 0
4123 OR 0 = ( $select_count_pkgs )
4129 Returns an SQL fragment to retreive the balance.
4134 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4135 WHERE cust_bill.custnum = cust_main.custnum )
4136 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4137 WHERE cust_pay.custnum = cust_main.custnum )
4138 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4139 WHERE cust_credit.custnum = cust_main.custnum )
4140 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4141 WHERE cust_refund.custnum = cust_main.custnum )
4144 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4146 Returns an SQL fragment to retreive the balance for this customer, optionally
4147 considering invoices with date earlier than START_TIME, and not
4148 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4149 total_unapplied_payments).
4151 Times are specified as SQL fragments or numeric
4152 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4153 L<Date::Parse> for conversion functions. The empty string can be passed
4154 to disable that time constraint completely.
4156 Available options are:
4160 =item unapplied_date
4162 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)
4167 set to true to remove all customer comparison clauses, for totals
4172 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4177 JOIN clause (typically used with the total option)
4181 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4182 time will be ignored. Note that START_TIME and END_TIME only limit the date
4183 range for invoices and I<unapplied> payments, credits, and refunds.
4189 sub balance_date_sql {
4190 my( $class, $start, $end, %opt ) = @_;
4192 my $cutoff = $opt{'cutoff'};
4194 my $owed = FS::cust_bill->owed_sql($cutoff);
4195 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4196 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4197 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4199 my $j = $opt{'join'} || '';
4201 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4202 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4203 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4204 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4206 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4207 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4208 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4209 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4214 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4216 Returns an SQL fragment to retreive the total unapplied payments for this
4217 customer, only considering invoices with date earlier than START_TIME, and
4218 optionally not later than END_TIME.
4220 Times are specified as SQL fragments or numeric
4221 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4222 L<Date::Parse> for conversion functions. The empty string can be passed
4223 to disable that time constraint completely.
4225 Available options are:
4229 sub unapplied_payments_date_sql {
4230 my( $class, $start, $end, %opt ) = @_;
4232 my $cutoff = $opt{'cutoff'};
4234 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4236 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4237 'unapplied_date'=>1 );
4239 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4242 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4244 Helper method for balance_date_sql; name (and usage) subject to change
4245 (suggestions welcome).
4247 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4248 cust_refund, cust_credit or cust_pay).
4250 If TABLE is "cust_bill" or the unapplied_date option is true, only
4251 considers records with date earlier than START_TIME, and optionally not
4252 later than END_TIME .
4256 sub _money_table_where {
4257 my( $class, $table, $start, $end, %opt ) = @_;
4260 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4261 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4262 push @where, "$table._date <= $start" if defined($start) && length($start);
4263 push @where, "$table._date > $end" if defined($end) && length($end);
4265 push @where, @{$opt{'where'}} if $opt{'where'};
4266 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4272 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4273 use FS::cust_main::Search;
4276 FS::cust_main::Search->search(@_);
4285 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4289 use FS::cust_main::Search;
4290 sub append_fuzzyfiles {
4291 #my( $first, $last, $company ) = @_;
4293 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4295 use Fcntl qw(:flock);
4297 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4299 foreach my $field (@fuzzyfields) {
4304 open(CACHE,">>$dir/cust_main.$field")
4305 or die "can't open $dir/cust_main.$field: $!";
4306 flock(CACHE,LOCK_EX)
4307 or die "can't lock $dir/cust_main.$field: $!";
4309 print CACHE "$value\n";
4311 flock(CACHE,LOCK_UN)
4312 or die "can't unlock $dir/cust_main.$field: $!";
4327 #warn join('-',keys %$param);
4328 my $fh = $param->{filehandle};
4329 my $agentnum = $param->{agentnum};
4330 my $format = $param->{format};
4332 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4335 if ( $format eq 'simple' ) {
4336 @fields = qw( custnum agent_custid amount pkg );
4338 die "unknown format $format";
4341 eval "use Text::CSV_XS;";
4344 my $csv = new Text::CSV_XS;
4351 local $SIG{HUP} = 'IGNORE';
4352 local $SIG{INT} = 'IGNORE';
4353 local $SIG{QUIT} = 'IGNORE';
4354 local $SIG{TERM} = 'IGNORE';
4355 local $SIG{TSTP} = 'IGNORE';
4356 local $SIG{PIPE} = 'IGNORE';
4358 my $oldAutoCommit = $FS::UID::AutoCommit;
4359 local $FS::UID::AutoCommit = 0;
4362 #while ( $columns = $csv->getline($fh) ) {
4364 while ( defined($line=<$fh>) ) {
4366 $csv->parse($line) or do {
4367 $dbh->rollback if $oldAutoCommit;
4368 return "can't parse: ". $csv->error_input();
4371 my @columns = $csv->fields();
4372 #warn join('-',@columns);
4375 foreach my $field ( @fields ) {
4376 $row{$field} = shift @columns;
4379 if ( $row{custnum} && $row{agent_custid} ) {
4380 dbh->rollback if $oldAutoCommit;
4381 return "can't specify custnum with agent_custid $row{agent_custid}";
4385 if ( $row{agent_custid} && $agentnum ) {
4386 %hash = ( 'agent_custid' => $row{agent_custid},
4387 'agentnum' => $agentnum,
4391 if ( $row{custnum} ) {
4392 %hash = ( 'custnum' => $row{custnum} );
4395 unless ( scalar(keys %hash) ) {
4396 $dbh->rollback if $oldAutoCommit;
4397 return "can't find customer without custnum or agent_custid and agentnum";
4400 my $cust_main = qsearchs('cust_main', { %hash } );
4401 unless ( $cust_main ) {
4402 $dbh->rollback if $oldAutoCommit;
4403 my $custnum = $row{custnum} || $row{agent_custid};
4404 return "unknown custnum $custnum";
4407 if ( $row{'amount'} > 0 ) {
4408 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4410 $dbh->rollback if $oldAutoCommit;
4414 } elsif ( $row{'amount'} < 0 ) {
4415 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4418 $dbh->rollback if $oldAutoCommit;
4428 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4430 return "Empty file!" unless $imported;
4436 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4438 Deprecated. Use event notification and message templates
4439 (L<FS::msg_template>) instead.
4441 Sends a templated email notification to the customer (see L<Text::Template>).
4443 OPTIONS is a hash and may include
4445 I<from> - the email sender (default is invoice_from)
4447 I<to> - comma-separated scalar or arrayref of recipients
4448 (default is invoicing_list)
4450 I<subject> - The subject line of the sent email notification
4451 (default is "Notice from company_name")
4453 I<extra_fields> - a hashref of name/value pairs which will be substituted
4456 The following variables are vavailable in the template.
4458 I<$first> - the customer first name
4459 I<$last> - the customer last name
4460 I<$company> - the customer company
4461 I<$payby> - a description of the method of payment for the customer
4462 # would be nice to use FS::payby::shortname
4463 I<$payinfo> - the account information used to collect for this customer
4464 I<$expdate> - the expiration of the customer payment in seconds from epoch
4469 my ($self, $template, %options) = @_;
4471 return unless $conf->exists($template);
4473 my $from = $conf->config('invoice_from', $self->agentnum)
4474 if $conf->exists('invoice_from', $self->agentnum);
4475 $from = $options{from} if exists($options{from});
4477 my $to = join(',', $self->invoicing_list_emailonly);
4478 $to = $options{to} if exists($options{to});
4480 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4481 if $conf->exists('company_name', $self->agentnum);
4482 $subject = $options{subject} if exists($options{subject});
4484 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4485 SOURCE => [ map "$_\n",
4486 $conf->config($template)]
4488 or die "can't create new Text::Template object: Text::Template::ERROR";
4489 $notify_template->compile()
4490 or die "can't compile template: Text::Template::ERROR";
4492 $FS::notify_template::_template::company_name =
4493 $conf->config('company_name', $self->agentnum);
4494 $FS::notify_template::_template::company_address =
4495 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4497 my $paydate = $self->paydate || '2037-12-31';
4498 $FS::notify_template::_template::first = $self->first;
4499 $FS::notify_template::_template::last = $self->last;
4500 $FS::notify_template::_template::company = $self->company;
4501 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4502 my $payby = $self->payby;
4503 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4504 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4506 #credit cards expire at the end of the month/year of their exp date
4507 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4508 $FS::notify_template::_template::payby = 'credit card';
4509 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4510 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4512 }elsif ($payby eq 'COMP') {
4513 $FS::notify_template::_template::payby = 'complimentary account';
4515 $FS::notify_template::_template::payby = 'current method';
4517 $FS::notify_template::_template::expdate = $expire_time;
4519 for (keys %{$options{extra_fields}}){
4521 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4524 send_email(from => $from,
4526 subject => $subject,
4527 body => $notify_template->fill_in( PACKAGE =>
4528 'FS::notify_template::_template' ),
4533 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4535 Generates a templated notification to the customer (see L<Text::Template>).
4537 OPTIONS is a hash and may include
4539 I<extra_fields> - a hashref of name/value pairs which will be substituted
4540 into the template. These values may override values mentioned below
4541 and those from the customer record.
4543 The following variables are available in the template instead of or in addition
4544 to the fields of the customer record.
4546 I<$payby> - a description of the method of payment for the customer
4547 # would be nice to use FS::payby::shortname
4548 I<$payinfo> - the masked account information used to collect for this customer
4549 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4550 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4554 # a lot like cust_bill::print_latex
4555 sub generate_letter {
4556 my ($self, $template, %options) = @_;
4558 return unless $conf->exists($template);
4560 my $letter_template = new Text::Template
4562 SOURCE => [ map "$_\n", $conf->config($template)],
4563 DELIMITERS => [ '[@--', '--@]' ],
4565 or die "can't create new Text::Template object: Text::Template::ERROR";
4567 $letter_template->compile()
4568 or die "can't compile template: Text::Template::ERROR";
4570 my %letter_data = map { $_ => $self->$_ } $self->fields;
4571 $letter_data{payinfo} = $self->mask_payinfo;
4573 #my $paydate = $self->paydate || '2037-12-31';
4574 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4576 my $payby = $self->payby;
4577 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4578 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4580 #credit cards expire at the end of the month/year of their exp date
4581 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4582 $letter_data{payby} = 'credit card';
4583 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4584 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4586 }elsif ($payby eq 'COMP') {
4587 $letter_data{payby} = 'complimentary account';
4589 $letter_data{payby} = 'current method';
4591 $letter_data{expdate} = $expire_time;
4593 for (keys %{$options{extra_fields}}){
4594 $letter_data{$_} = $options{extra_fields}->{$_};
4597 unless(exists($letter_data{returnaddress})){
4598 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4599 $self->agent_template)
4601 if ( length($retadd) ) {
4602 $letter_data{returnaddress} = $retadd;
4603 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4604 $letter_data{returnaddress} =
4605 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4609 ( $conf->config('company_name', $self->agentnum),
4610 $conf->config('company_address', $self->agentnum),
4614 $letter_data{returnaddress} = '~';
4618 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4620 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4622 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4624 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4628 ) or die "can't open temp file: $!\n";
4629 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4630 or die "can't write temp file: $!\n";
4632 $letter_data{'logo_file'} = $lh->filename;
4634 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4638 ) or die "can't open temp file: $!\n";
4640 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4642 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4643 return ($1, $letter_data{'logo_file'});
4647 =item print_ps TEMPLATE
4649 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4655 my($file, $lfile) = $self->generate_letter(@_);
4656 my $ps = FS::Misc::generate_ps($file);
4657 unlink($file.'.tex');
4663 =item print TEMPLATE
4665 Prints the filled in template.
4667 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4671 sub queueable_print {
4674 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4675 or die "invalid customer number: " . $opt{custvnum};
4677 my $error = $self->print( $opt{template} );
4678 die $error if $error;
4682 my ($self, $template) = (shift, shift);
4683 do_print [ $self->print_ps($template) ];
4686 #these three subs should just go away once agent stuff is all config overrides
4688 sub agent_template {
4690 $self->_agent_plandata('agent_templatename');
4693 sub agent_invoice_from {
4695 $self->_agent_plandata('agent_invoice_from');
4698 sub _agent_plandata {
4699 my( $self, $option ) = @_;
4701 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4702 #agent-specific Conf
4704 use FS::part_event::Condition;
4706 my $agentnum = $self->agentnum;
4708 my $regexp = regexp_sql();
4710 my $part_event_option =
4712 'select' => 'part_event_option.*',
4713 'table' => 'part_event_option',
4715 LEFT JOIN part_event USING ( eventpart )
4716 LEFT JOIN part_event_option AS peo_agentnum
4717 ON ( part_event.eventpart = peo_agentnum.eventpart
4718 AND peo_agentnum.optionname = 'agentnum'
4719 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4721 LEFT JOIN part_event_condition
4722 ON ( part_event.eventpart = part_event_condition.eventpart
4723 AND part_event_condition.conditionname = 'cust_bill_age'
4725 LEFT JOIN part_event_condition_option
4726 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4727 AND part_event_condition_option.optionname = 'age'
4730 #'hashref' => { 'optionname' => $option },
4731 #'hashref' => { 'part_event_option.optionname' => $option },
4733 " WHERE part_event_option.optionname = ". dbh->quote($option).
4734 " AND action = 'cust_bill_send_agent' ".
4735 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4736 " AND peo_agentnum.optionname = 'agentnum' ".
4737 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4739 CASE WHEN part_event_condition_option.optionname IS NULL
4741 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4743 , part_event.weight".
4747 unless ( $part_event_option ) {
4748 return $self->agent->invoice_template || ''
4749 if $option eq 'agent_templatename';
4753 $part_event_option->optionvalue;
4757 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4759 Subroutine (not a method), designed to be called from the queue.
4761 Takes a list of options and values.
4763 Pulls up the customer record via the custnum option and calls bill_and_collect.
4768 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4770 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4771 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4773 $cust_main->bill_and_collect( %args );
4776 sub process_bill_and_collect {
4778 my $param = thaw(decode_base64(shift));
4779 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4780 or die "custnum '$param->{custnum}' not found!\n";
4781 $param->{'job'} = $job;
4782 $param->{'fatal'} = 1; # runs from job queue, will be caught
4783 $param->{'retry'} = 1;
4785 $cust_main->bill_and_collect( %$param );
4788 sub _upgrade_data { #class method
4789 my ($class, %opts) = @_;
4792 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4793 'UPDATE cust_main SET signupdate = (SELECT signupdate FROM h_cust_main WHERE signupdate IS NOT NULL AND h_cust_main.custnum = cust_main.custnum ORDER BY historynum DESC LIMIT 1) WHERE signupdate IS NULL',
4795 # fix yyyy-m-dd formatted paydates
4796 if ( driver_name =~ /^mysql$/i ) {
4798 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4800 else { # the SQL standard
4802 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4805 foreach my $sql ( @statements ) {
4806 my $sth = dbh->prepare($sql) or die dbh->errstr;
4807 $sth->execute or die $sth->errstr;
4810 local($ignore_expired_card) = 1;
4811 local($ignore_illegal_zip) = 1;
4812 local($ignore_banned_card) = 1;
4813 local($skip_fuzzyfiles) = 1;
4814 $class->_upgrade_otaker(%opts);
4824 The delete method should possibly take an FS::cust_main object reference
4825 instead of a scalar customer number.
4827 Bill and collect options should probably be passed as references instead of a
4830 There should probably be a configuration file with a list of allowed credit
4833 No multiple currency support (probably a larger project than just this module).
4835 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4837 Birthdates rely on negative epoch values.
4839 The payby for card/check batches is broken. With mixed batching, bad
4842 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4846 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4847 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4848 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.