5 #FS::cust_main:_Marketgear when they're ready to move to 2.1
6 use base qw( FS::cust_main::Packages
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;
71 # 1 is mostly method/subroutine entry and options
72 # 2 traces progress of some operations
73 # 3 is even more information including possibly sensitive data
75 $me = '[FS::cust_main]';
78 $ignore_expired_card = 0;
79 $ignore_illegal_zip = 0;
80 $ignore_banned_card = 0;
83 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
85 @encrypted_fields = ('payinfo', 'paycvv');
86 sub nohistory_fields { ('payinfo', 'paycvv'); }
88 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
90 #ask FS::UID to run this stuff for us later
91 #$FS::UID::callback{'FS::cust_main'} = sub {
92 install_callback FS::UID sub {
94 #yes, need it for stuff below (prolly should be cached)
99 my ( $hashref, $cache ) = @_;
100 if ( exists $hashref->{'pkgnum'} ) {
101 #@{ $self->{'_pkgnum'} } = ();
102 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
103 $self->{'_pkgnum'} = $subcache;
104 #push @{ $self->{'_pkgnum'} },
105 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
111 FS::cust_main - Object methods for cust_main records
117 $record = new FS::cust_main \%hash;
118 $record = new FS::cust_main { 'column' => 'value' };
120 $error = $record->insert;
122 $error = $new_record->replace($old_record);
124 $error = $record->delete;
126 $error = $record->check;
128 @cust_pkg = $record->all_pkgs;
130 @cust_pkg = $record->ncancelled_pkgs;
132 @cust_pkg = $record->suspended_pkgs;
134 $error = $record->bill;
135 $error = $record->bill %options;
136 $error = $record->bill 'time' => $time;
138 $error = $record->collect;
139 $error = $record->collect %options;
140 $error = $record->collect 'invoice_time' => $time,
145 An FS::cust_main object represents a customer. FS::cust_main inherits from
146 FS::Record. The following fields are currently supported:
152 Primary key (assigned automatically for new customers)
156 Agent (see L<FS::agent>)
160 Advertising source (see L<FS::part_referral>)
172 Cocial security number (optional)
188 (optional, see L<FS::cust_main_county>)
192 (see L<FS::cust_main_county>)
198 (see L<FS::cust_main_county>)
234 (optional, see L<FS::cust_main_county>)
238 (see L<FS::cust_main_county>)
244 (see L<FS::cust_main_county>)
260 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
264 Payment Information (See L<FS::payinfo_Mixin> for data format)
268 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
272 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
276 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
280 Start date month (maestro/solo cards only)
284 Start date year (maestro/solo cards only)
288 Issue number (maestro/solo cards only)
292 Name on card or billing name
296 IP address from which payment information was received
300 Tax exempt, empty or `Y'
304 Order taker (see L<FS::access_user>)
310 =item referral_custnum
312 Referring customer number
316 Enable individual CDR spooling, empty or `Y'
320 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
324 Discourage individual CDR printing, empty or `Y'
334 Creates a new customer. To add the customer to the database, see L<"insert">.
336 Note that this stores the hash reference, not a distinct copy of the hash it
337 points to. You can ask the object for a copy with the I<hash> method.
341 sub table { 'cust_main'; }
343 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
345 Adds this customer to the database. If there is an error, returns the error,
346 otherwise returns false.
348 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
349 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
350 are inserted atomicly, or the transaction is rolled back. Passing an empty
351 hash reference is equivalent to not supplying this parameter. There should be
352 a better explanation of this, but until then, here's an example:
355 tie %hash, 'Tie::RefHash'; #this part is important
357 $cust_pkg => [ $svc_acct ],
360 $cust_main->insert( \%hash );
362 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
363 be set as the invoicing list (see L<"invoicing_list">). Errors return as
364 expected and rollback the entire transaction; it is not necessary to call
365 check_invoicing_list first. The invoicing_list is set after the records in the
366 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
367 invoicing_list destination to the newly-created svc_acct. Here's an example:
369 $cust_main->insert( {}, [ $email, 'POST' ] );
371 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
373 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
374 on the supplied jobnum (they will not run until the specific job completes).
375 This can be used to defer provisioning until some action completes (such
376 as running the customer's credit card successfully).
378 The I<noexport> option is deprecated. If I<noexport> is set true, no
379 provisioning jobs (exports) are scheduled. (You can schedule them later with
380 the B<reexport> method.)
382 The I<tax_exemption> option can be set to an arrayref of tax names.
383 FS::cust_main_exemption records will be created and inserted.
389 my $cust_pkgs = @_ ? shift : {};
390 my $invoicing_list = @_ ? shift : '';
392 warn "$me insert called with options ".
393 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
396 local $SIG{HUP} = 'IGNORE';
397 local $SIG{INT} = 'IGNORE';
398 local $SIG{QUIT} = 'IGNORE';
399 local $SIG{TERM} = 'IGNORE';
400 local $SIG{TSTP} = 'IGNORE';
401 local $SIG{PIPE} = 'IGNORE';
403 my $oldAutoCommit = $FS::UID::AutoCommit;
404 local $FS::UID::AutoCommit = 0;
407 my $prepay_identifier = '';
408 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
410 if ( $self->payby eq 'PREPAY' ) {
412 $self->payby('BILL');
413 $prepay_identifier = $self->payinfo;
416 warn " looking up prepaid card $prepay_identifier\n"
419 my $error = $self->get_prepay( $prepay_identifier,
420 'amount_ref' => \$amount,
421 'seconds_ref' => \$seconds,
422 'upbytes_ref' => \$upbytes,
423 'downbytes_ref' => \$downbytes,
424 'totalbytes_ref' => \$totalbytes,
427 $dbh->rollback if $oldAutoCommit;
428 #return "error applying prepaid card (transaction rolled back): $error";
432 $payby = 'PREP' if $amount;
434 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
437 $self->payby('BILL');
438 $amount = $self->paid;
442 warn " inserting $self\n"
445 $self->signupdate(time) unless $self->signupdate;
447 $self->auto_agent_custid()
448 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
450 my $error = $self->SUPER::insert;
452 $dbh->rollback if $oldAutoCommit;
453 #return "inserting cust_main record (transaction rolled back): $error";
457 warn " setting invoicing list\n"
460 if ( $invoicing_list ) {
461 $error = $self->check_invoicing_list( $invoicing_list );
463 $dbh->rollback if $oldAutoCommit;
464 #return "checking invoicing_list (transaction rolled back): $error";
467 $self->invoicing_list( $invoicing_list );
470 warn " setting customer tags\n"
473 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
474 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
475 'custnum' => $self->custnum };
476 my $error = $cust_tag->insert;
478 $dbh->rollback if $oldAutoCommit;
483 if ( $invoicing_list ) {
484 $error = $self->check_invoicing_list( $invoicing_list );
486 $dbh->rollback if $oldAutoCommit;
487 #return "checking invoicing_list (transaction rolled back): $error";
490 $self->invoicing_list( $invoicing_list );
494 warn " setting cust_main_exemption\n"
497 my $tax_exemption = delete $options{'tax_exemption'};
498 if ( $tax_exemption ) {
499 foreach my $taxname ( @$tax_exemption ) {
500 my $cust_main_exemption = new FS::cust_main_exemption {
501 'custnum' => $self->custnum,
502 'taxname' => $taxname,
504 my $error = $cust_main_exemption->insert;
506 $dbh->rollback if $oldAutoCommit;
507 return "inserting cust_main_exemption (transaction rolled back): $error";
512 if ( $self->can('start_copy_skel') ) {
513 my $error = $self->start_copy_skel;
515 $dbh->rollback if $oldAutoCommit;
520 warn " ordering packages\n"
523 $error = $self->order_pkgs( $cust_pkgs,
525 'seconds_ref' => \$seconds,
526 'upbytes_ref' => \$upbytes,
527 'downbytes_ref' => \$downbytes,
528 'totalbytes_ref' => \$totalbytes,
531 $dbh->rollback if $oldAutoCommit;
536 $dbh->rollback if $oldAutoCommit;
537 return "No svc_acct record to apply pre-paid time";
539 if ( $upbytes || $downbytes || $totalbytes ) {
540 $dbh->rollback if $oldAutoCommit;
541 return "No svc_acct record to apply pre-paid data";
545 warn " inserting initial $payby payment of $amount\n"
547 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
549 $dbh->rollback if $oldAutoCommit;
550 return "inserting payment (transaction rolled back): $error";
554 unless ( $import || $skip_fuzzyfiles ) {
555 warn " queueing fuzzyfiles update\n"
557 $error = $self->queue_fuzzyfiles_update;
559 $dbh->rollback if $oldAutoCommit;
560 return "updating fuzzy search cache: $error";
565 warn " exporting\n" if $DEBUG > 1;
567 my $export_args = $options{'export_args'} || [];
570 map qsearch( 'part_export', {exportnum=>$_} ),
571 $conf->config('cust_main-exports'); #, $agentnum
573 foreach my $part_export ( @part_export ) {
574 my $error = $part_export->export_insert($self, @$export_args);
576 $dbh->rollback if $oldAutoCommit;
577 return "exporting to ". $part_export->exporttype.
578 " (transaction rolled back): $error";
582 #foreach my $depend_jobnum ( @$depend_jobnums ) {
583 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
585 # foreach my $jobnum ( @jobnums ) {
586 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
587 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
589 # my $error = $queue->depend_insert($depend_jobnum);
591 # $dbh->rollback if $oldAutoCommit;
592 # return "error queuing job dependancy: $error";
599 #if ( exists $options{'jobnums'} ) {
600 # push @{ $options{'jobnums'} }, @jobnums;
603 warn " insert complete; committing transaction\n"
606 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
611 use File::CounterFile;
612 sub auto_agent_custid {
615 my $format = $conf->config('cust_main-auto_agent_custid');
617 if ( $format eq '1YMMXXXXXXXX' ) {
619 my $counter = new File::CounterFile 'cust_main.agent_custid';
622 my $ym = 100000000000 + time2str('%y%m00000000', time);
623 if ( $ym > $counter->value ) {
624 $counter->{'value'} = $agent_custid = $ym;
625 $counter->{'updated'} = 1;
627 $agent_custid = $counter->inc;
633 die "Unknown cust_main-auto_agent_custid format: $format";
636 $self->agent_custid($agent_custid);
640 =item PACKAGE METHODS
642 Documentation on customer package methods has been moved to
643 L<FS::cust_main::Packages>.
645 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
647 Recharges this (existing) customer with the specified prepaid card (see
648 L<FS::prepay_credit>), specified either by I<identifier> or as an
649 FS::prepay_credit object. If there is an error, returns the error, otherwise
652 Optionally, five scalar references can be passed as well. They will have their
653 values filled in with the amount, number of seconds, and number of upload,
654 download, and total bytes applied by this prepaid card.
658 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
659 #the only place that uses these args
660 sub recharge_prepay {
661 my( $self, $prepay_credit, $amountref, $secondsref,
662 $upbytesref, $downbytesref, $totalbytesref ) = @_;
664 local $SIG{HUP} = 'IGNORE';
665 local $SIG{INT} = 'IGNORE';
666 local $SIG{QUIT} = 'IGNORE';
667 local $SIG{TERM} = 'IGNORE';
668 local $SIG{TSTP} = 'IGNORE';
669 local $SIG{PIPE} = 'IGNORE';
671 my $oldAutoCommit = $FS::UID::AutoCommit;
672 local $FS::UID::AutoCommit = 0;
675 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
677 my $error = $self->get_prepay( $prepay_credit,
678 'amount_ref' => \$amount,
679 'seconds_ref' => \$seconds,
680 'upbytes_ref' => \$upbytes,
681 'downbytes_ref' => \$downbytes,
682 'totalbytes_ref' => \$totalbytes,
684 || $self->increment_seconds($seconds)
685 || $self->increment_upbytes($upbytes)
686 || $self->increment_downbytes($downbytes)
687 || $self->increment_totalbytes($totalbytes)
688 || $self->insert_cust_pay_prepay( $amount,
690 ? $prepay_credit->identifier
695 $dbh->rollback if $oldAutoCommit;
699 if ( defined($amountref) ) { $$amountref = $amount; }
700 if ( defined($secondsref) ) { $$secondsref = $seconds; }
701 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
702 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
703 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
705 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
710 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
712 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
713 specified either by I<identifier> or as an FS::prepay_credit object.
715 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
716 incremented by the values of the prepaid card.
718 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
719 check or set this customer's I<agentnum>.
721 If there is an error, returns the error, otherwise returns false.
727 my( $self, $prepay_credit, %opt ) = @_;
729 local $SIG{HUP} = 'IGNORE';
730 local $SIG{INT} = 'IGNORE';
731 local $SIG{QUIT} = 'IGNORE';
732 local $SIG{TERM} = 'IGNORE';
733 local $SIG{TSTP} = 'IGNORE';
734 local $SIG{PIPE} = 'IGNORE';
736 my $oldAutoCommit = $FS::UID::AutoCommit;
737 local $FS::UID::AutoCommit = 0;
740 unless ( ref($prepay_credit) ) {
742 my $identifier = $prepay_credit;
744 $prepay_credit = qsearchs(
746 { 'identifier' => $prepay_credit },
751 unless ( $prepay_credit ) {
752 $dbh->rollback if $oldAutoCommit;
753 return "Invalid prepaid card: ". $identifier;
758 if ( $prepay_credit->agentnum ) {
759 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
760 $dbh->rollback if $oldAutoCommit;
761 return "prepaid card not valid for agent ". $self->agentnum;
763 $self->agentnum($prepay_credit->agentnum);
766 my $error = $prepay_credit->delete;
768 $dbh->rollback if $oldAutoCommit;
769 return "removing prepay_credit (transaction rolled back): $error";
772 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
773 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
775 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
780 =item increment_upbytes SECONDS
782 Updates this customer's single or primary account (see L<FS::svc_acct>) by
783 the specified number of upbytes. If there is an error, returns the error,
784 otherwise returns false.
788 sub increment_upbytes {
789 _increment_column( shift, 'upbytes', @_);
792 =item increment_downbytes SECONDS
794 Updates this customer's single or primary account (see L<FS::svc_acct>) by
795 the specified number of downbytes. If there is an error, returns the error,
796 otherwise returns false.
800 sub increment_downbytes {
801 _increment_column( shift, 'downbytes', @_);
804 =item increment_totalbytes SECONDS
806 Updates this customer's single or primary account (see L<FS::svc_acct>) by
807 the specified number of totalbytes. If there is an error, returns the error,
808 otherwise returns false.
812 sub increment_totalbytes {
813 _increment_column( shift, 'totalbytes', @_);
816 =item increment_seconds SECONDS
818 Updates this customer's single or primary account (see L<FS::svc_acct>) by
819 the specified number of seconds. If there is an error, returns the error,
820 otherwise returns false.
824 sub increment_seconds {
825 _increment_column( shift, 'seconds', @_);
828 =item _increment_column AMOUNT
830 Updates this customer's single or primary account (see L<FS::svc_acct>) by
831 the specified number of seconds or bytes. If there is an error, returns
832 the error, otherwise returns false.
836 sub _increment_column {
837 my( $self, $column, $amount ) = @_;
838 warn "$me increment_column called: $column, $amount\n"
841 return '' unless $amount;
843 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
844 $self->ncancelled_pkgs;
847 return 'No packages with primary or single services found'.
848 ' to apply pre-paid time';
849 } elsif ( scalar(@cust_pkg) > 1 ) {
850 #maybe have a way to specify the package/account?
851 return 'Multiple packages found to apply pre-paid time';
854 my $cust_pkg = $cust_pkg[0];
855 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
859 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
862 return 'No account found to apply pre-paid time';
863 } elsif ( scalar(@cust_svc) > 1 ) {
864 return 'Multiple accounts found to apply pre-paid time';
867 my $svc_acct = $cust_svc[0]->svc_x;
868 warn " found service svcnum ". $svc_acct->pkgnum.
869 ' ('. $svc_acct->email. ")\n"
872 $column = "increment_$column";
873 $svc_acct->$column($amount);
877 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
879 Inserts a prepayment in the specified amount for this customer. An optional
880 second argument can specify the prepayment identifier for tracking purposes.
881 If there is an error, returns the error, otherwise returns false.
885 sub insert_cust_pay_prepay {
886 shift->insert_cust_pay('PREP', @_);
889 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
891 Inserts a cash payment in the specified amount for this customer. An optional
892 second argument can specify the payment identifier for tracking purposes.
893 If there is an error, returns the error, otherwise returns false.
897 sub insert_cust_pay_cash {
898 shift->insert_cust_pay('CASH', @_);
901 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
903 Inserts a Western Union payment in the specified amount for this customer. An
904 optional second argument can specify the prepayment identifier for tracking
905 purposes. If there is an error, returns the error, otherwise returns false.
909 sub insert_cust_pay_west {
910 shift->insert_cust_pay('WEST', @_);
913 sub insert_cust_pay {
914 my( $self, $payby, $amount ) = splice(@_, 0, 3);
915 my $payinfo = scalar(@_) ? shift : '';
917 my $cust_pay = new FS::cust_pay {
918 'custnum' => $self->custnum,
919 'paid' => sprintf('%.2f', $amount),
920 #'_date' => #date the prepaid card was purchased???
922 'payinfo' => $payinfo,
930 This method is deprecated. See the I<depend_jobnum> option to the insert and
931 order_pkgs methods for a better way to defer provisioning.
933 Re-schedules all exports by calling the B<reexport> method of all associated
934 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
935 otherwise returns false.
942 carp "WARNING: FS::cust_main::reexport is deprectated; ".
943 "use the depend_jobnum option to insert or order_pkgs to delay export";
945 local $SIG{HUP} = 'IGNORE';
946 local $SIG{INT} = 'IGNORE';
947 local $SIG{QUIT} = 'IGNORE';
948 local $SIG{TERM} = 'IGNORE';
949 local $SIG{TSTP} = 'IGNORE';
950 local $SIG{PIPE} = 'IGNORE';
952 my $oldAutoCommit = $FS::UID::AutoCommit;
953 local $FS::UID::AutoCommit = 0;
956 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
957 my $error = $cust_pkg->reexport;
959 $dbh->rollback if $oldAutoCommit;
964 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
969 =item delete [ OPTION => VALUE ... ]
971 This deletes the customer. If there is an error, returns the error, otherwise
974 This will completely remove all traces of the customer record. This is not
975 what you want when a customer cancels service; for that, cancel all of the
976 customer's packages (see L</cancel>).
978 If the customer has any uncancelled packages, you need to pass a new (valid)
979 customer number for those packages to be transferred to, as the "new_customer"
980 option. Cancelled packages will be deleted. Did I mention that this is NOT
981 what you want when a customer cancels service and that you really should be
982 looking at L<FS::cust_pkg/cancel>?
984 You can't delete a customer with invoices (see L<FS::cust_bill>),
985 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
986 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
987 set the "delete_financials" option to a true value.
992 my( $self, %opt ) = @_;
994 local $SIG{HUP} = 'IGNORE';
995 local $SIG{INT} = 'IGNORE';
996 local $SIG{QUIT} = 'IGNORE';
997 local $SIG{TERM} = 'IGNORE';
998 local $SIG{TSTP} = 'IGNORE';
999 local $SIG{PIPE} = 'IGNORE';
1001 my $oldAutoCommit = $FS::UID::AutoCommit;
1002 local $FS::UID::AutoCommit = 0;
1005 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1006 $dbh->rollback if $oldAutoCommit;
1007 return "Can't delete a master agent customer";
1010 #use FS::access_user
1011 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1012 $dbh->rollback if $oldAutoCommit;
1013 return "Can't delete a master employee customer";
1016 tie my %financial_tables, 'Tie::IxHash',
1017 'cust_bill' => 'invoices',
1018 'cust_statement' => 'statements',
1019 'cust_credit' => 'credits',
1020 'cust_pay' => 'payments',
1021 'cust_refund' => 'refunds',
1024 foreach my $table ( keys %financial_tables ) {
1026 my @records = $self->$table();
1028 if ( @records && ! $opt{'delete_financials'} ) {
1029 $dbh->rollback if $oldAutoCommit;
1030 return "Can't delete a customer with ". $financial_tables{$table};
1033 foreach my $record ( @records ) {
1034 my $error = $record->delete;
1036 $dbh->rollback if $oldAutoCommit;
1037 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1043 my @cust_pkg = $self->ncancelled_pkgs;
1045 my $new_custnum = $opt{'new_custnum'};
1046 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1047 $dbh->rollback if $oldAutoCommit;
1048 return "Invalid new customer number: $new_custnum";
1050 foreach my $cust_pkg ( @cust_pkg ) {
1051 my %hash = $cust_pkg->hash;
1052 $hash{'custnum'} = $new_custnum;
1053 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1054 my $error = $new_cust_pkg->replace($cust_pkg,
1055 options => { $cust_pkg->options },
1058 $dbh->rollback if $oldAutoCommit;
1063 my @cancelled_cust_pkg = $self->all_pkgs;
1064 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1065 my $error = $cust_pkg->delete;
1067 $dbh->rollback if $oldAutoCommit;
1072 #cust_tax_adjustment in financials?
1073 #cust_pay_pending? ouch
1075 foreach my $table (qw(
1076 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1077 cust_location cust_main_note cust_tax_adjustment
1078 cust_pay_void cust_pay_batch queue cust_tax_exempt
1080 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1081 my $error = $record->delete;
1083 $dbh->rollback if $oldAutoCommit;
1089 my $sth = $dbh->prepare(
1090 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1092 my $errstr = $dbh->errstr;
1093 $dbh->rollback if $oldAutoCommit;
1096 $sth->execute($self->custnum) or do {
1097 my $errstr = $sth->errstr;
1098 $dbh->rollback if $oldAutoCommit;
1104 my $ticket_dbh = '';
1105 if ($conf->config('ticket_system') eq 'RT_Internal') {
1107 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1108 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1109 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1110 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1113 if ( $ticket_dbh ) {
1115 my $ticket_sth = $ticket_dbh->prepare(
1116 'DELETE FROM Links WHERE Target = ?'
1118 my $errstr = $ticket_dbh->errstr;
1119 $dbh->rollback if $oldAutoCommit;
1122 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1124 my $errstr = $ticket_sth->errstr;
1125 $dbh->rollback if $oldAutoCommit;
1129 #check and see if the customer is the only link on the ticket, and
1130 #if so, set the ticket to deleted status in RT?
1131 #maybe someday, for now this will at least fix tickets not displaying
1135 #delete the customer record
1137 my $error = $self->SUPER::delete;
1139 $dbh->rollback if $oldAutoCommit;
1143 # cust_main exports!
1145 #my $export_args = $options{'export_args'} || [];
1148 map qsearch( 'part_export', {exportnum=>$_} ),
1149 $conf->config('cust_main-exports'); #, $agentnum
1151 foreach my $part_export ( @part_export ) {
1152 my $error = $part_export->export_delete( $self ); #, @$export_args);
1154 $dbh->rollback if $oldAutoCommit;
1155 return "exporting to ". $part_export->exporttype.
1156 " (transaction rolled back): $error";
1160 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1165 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1167 This merges this customer into the provided new custnum, and then deletes the
1168 customer. If there is an error, returns the error, otherwise returns false.
1170 The source customer's name, company name, phone numbers, agent,
1171 referring customer, customer class, advertising source, order taker, and
1172 billing information (except balance) are discarded.
1174 All packages are moved to the target customer. Packages with package locations
1175 are preserved. Packages without package locations are moved to a new package
1176 location with the source customer's service/shipping address.
1178 All invoices, statements, payments, credits and refunds are moved to the target
1179 customer. The source customer's balance is added to the target customer.
1181 All notes, attachments, tickets and customer tags are moved to the target
1184 Change history is not currently moved.
1189 my( $self, $new_custnum, %opt ) = @_;
1191 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1193 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1194 return "Invalid new customer number: $new_custnum";
1197 local $SIG{HUP} = 'IGNORE';
1198 local $SIG{INT} = 'IGNORE';
1199 local $SIG{QUIT} = 'IGNORE';
1200 local $SIG{TERM} = 'IGNORE';
1201 local $SIG{TSTP} = 'IGNORE';
1202 local $SIG{PIPE} = 'IGNORE';
1204 my $oldAutoCommit = $FS::UID::AutoCommit;
1205 local $FS::UID::AutoCommit = 0;
1208 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1209 $dbh->rollback if $oldAutoCommit;
1210 return "Can't merge a master agent customer";
1213 #use FS::access_user
1214 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1215 $dbh->rollback if $oldAutoCommit;
1216 return "Can't merge a master employee customer";
1219 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1220 'status' => { op=>'!=', value=>'done' },
1224 $dbh->rollback if $oldAutoCommit;
1225 return "Can't merge a customer with pending payments";
1228 tie my %financial_tables, 'Tie::IxHash',
1229 'cust_bill' => 'invoices',
1230 'cust_statement' => 'statements',
1231 'cust_credit' => 'credits',
1232 'cust_pay' => 'payments',
1233 'cust_pay_void' => 'voided payments',
1234 'cust_refund' => 'refunds',
1237 foreach my $table ( keys %financial_tables ) {
1239 my @records = $self->$table();
1241 foreach my $record ( @records ) {
1242 $record->custnum($new_custnum);
1243 my $error = $record->replace;
1245 $dbh->rollback if $oldAutoCommit;
1246 return "Error merging ". $financial_tables{$table}. ": $error\n";
1252 my $name = $self->ship_name;
1254 my $locationnum = '';
1255 foreach my $cust_pkg ( $self->all_pkgs ) {
1256 $cust_pkg->custnum($new_custnum);
1258 unless ( $cust_pkg->locationnum ) {
1259 unless ( $locationnum ) {
1260 my $cust_location = new FS::cust_location {
1261 $self->location_hash,
1262 'custnum' => $new_custnum,
1264 my $error = $cust_location->insert;
1266 $dbh->rollback if $oldAutoCommit;
1269 $locationnum = $cust_location->locationnum;
1271 $cust_pkg->locationnum($locationnum);
1274 my $error = $cust_pkg->replace;
1276 $dbh->rollback if $oldAutoCommit;
1280 # add customer (ship) name to svc_phone.phone_name if blank
1281 my @cust_svc = $cust_pkg->cust_svc;
1282 foreach my $cust_svc (@cust_svc) {
1283 my($label, $value, $svcdb) = $cust_svc->label;
1284 next unless $svcdb eq 'svc_phone';
1285 my $svc_phone = $cust_svc->svc_x;
1286 next if $svc_phone->phone_name;
1287 $svc_phone->phone_name($name);
1288 my $error = $svc_phone->replace;
1290 $dbh->rollback if $oldAutoCommit;
1298 # cust_tax_exempt (texas tax exemptions)
1299 # cust_recon (some sort of not-well understood thing for OnPac)
1301 #these are moved over
1302 foreach my $table (qw(
1303 cust_tag cust_location contact cust_attachment cust_main_note
1304 cust_tax_adjustment cust_pay_batch queue
1306 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1307 $record->custnum($new_custnum);
1308 my $error = $record->replace;
1310 $dbh->rollback if $oldAutoCommit;
1316 #these aren't preserved
1317 foreach my $table (qw(
1318 cust_main_exemption cust_main_invoice
1320 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1321 my $error = $record->delete;
1323 $dbh->rollback if $oldAutoCommit;
1330 my $sth = $dbh->prepare(
1331 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1333 my $errstr = $dbh->errstr;
1334 $dbh->rollback if $oldAutoCommit;
1337 $sth->execute($new_custnum, $self->custnum) or do {
1338 my $errstr = $sth->errstr;
1339 $dbh->rollback if $oldAutoCommit;
1345 my $ticket_dbh = '';
1346 if ($conf->config('ticket_system') eq 'RT_Internal') {
1348 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1349 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1350 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1351 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1354 if ( $ticket_dbh ) {
1356 my $ticket_sth = $ticket_dbh->prepare(
1357 'UPDATE Links SET Target = ? WHERE Target = ?'
1359 my $errstr = $ticket_dbh->errstr;
1360 $dbh->rollback if $oldAutoCommit;
1363 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1364 'freeside://freeside/cust_main/'.$self->custnum)
1366 my $errstr = $ticket_sth->errstr;
1367 $dbh->rollback if $oldAutoCommit;
1373 #delete the customer record
1375 my $error = $self->delete;
1377 $dbh->rollback if $oldAutoCommit;
1381 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1386 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1389 Replaces the OLD_RECORD with this one in the database. If there is an error,
1390 returns the error, otherwise returns false.
1392 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1393 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1394 expected and rollback the entire transaction; it is not necessary to call
1395 check_invoicing_list first. Here's an example:
1397 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1399 Currently available options are: I<tax_exemption>.
1401 The I<tax_exemption> option can be set to an arrayref of tax names.
1402 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1409 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1411 : $self->replace_old;
1415 warn "$me replace called\n"
1418 my $curuser = $FS::CurrentUser::CurrentUser;
1419 if ( $self->payby eq 'COMP'
1420 && $self->payby ne $old->payby
1421 && ! $curuser->access_right('Complimentary customer')
1424 return "You are not permitted to create complimentary accounts.";
1427 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1428 && $conf->exists('enable_taxproducts')
1431 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1433 $self->set('geocode', '')
1434 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1435 && length($self->get($pre.'zip')) >= 10;
1438 local($ignore_expired_card) = 1
1439 if $old->payby =~ /^(CARD|DCRD)$/
1440 && $self->payby =~ /^(CARD|DCRD)$/
1441 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1443 local $SIG{HUP} = 'IGNORE';
1444 local $SIG{INT} = 'IGNORE';
1445 local $SIG{QUIT} = 'IGNORE';
1446 local $SIG{TERM} = 'IGNORE';
1447 local $SIG{TSTP} = 'IGNORE';
1448 local $SIG{PIPE} = 'IGNORE';
1450 my $oldAutoCommit = $FS::UID::AutoCommit;
1451 local $FS::UID::AutoCommit = 0;
1454 my $error = $self->SUPER::replace($old);
1457 $dbh->rollback if $oldAutoCommit;
1461 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1462 my $invoicing_list = shift @param;
1463 $error = $self->check_invoicing_list( $invoicing_list );
1465 $dbh->rollback if $oldAutoCommit;
1468 $self->invoicing_list( $invoicing_list );
1471 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1473 #this could be more efficient than deleting and re-inserting, if it matters
1474 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1475 my $error = $cust_tag->delete;
1477 $dbh->rollback if $oldAutoCommit;
1481 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1482 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1483 'custnum' => $self->custnum };
1484 my $error = $cust_tag->insert;
1486 $dbh->rollback if $oldAutoCommit;
1493 my %options = @param;
1495 my $tax_exemption = delete $options{'tax_exemption'};
1496 if ( $tax_exemption ) {
1498 my %cust_main_exemption =
1499 map { $_->taxname => $_ }
1500 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1502 foreach my $taxname ( @$tax_exemption ) {
1504 next if delete $cust_main_exemption{$taxname};
1506 my $cust_main_exemption = new FS::cust_main_exemption {
1507 'custnum' => $self->custnum,
1508 'taxname' => $taxname,
1510 my $error = $cust_main_exemption->insert;
1512 $dbh->rollback if $oldAutoCommit;
1513 return "inserting cust_main_exemption (transaction rolled back): $error";
1517 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1518 my $error = $cust_main_exemption->delete;
1520 $dbh->rollback if $oldAutoCommit;
1521 return "deleting cust_main_exemption (transaction rolled back): $error";
1527 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1528 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1529 && $self->get('payinfo') !~ /^99\d{14}$/
1531 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1536 # card/check/lec info has changed, want to retry realtime_ invoice events
1537 my $error = $self->retry_realtime;
1539 $dbh->rollback if $oldAutoCommit;
1544 unless ( $import || $skip_fuzzyfiles ) {
1545 $error = $self->queue_fuzzyfiles_update;
1547 $dbh->rollback if $oldAutoCommit;
1548 return "updating fuzzy search cache: $error";
1552 # cust_main exports!
1554 my $export_args = $options{'export_args'} || [];
1557 map qsearch( 'part_export', {exportnum=>$_} ),
1558 $conf->config('cust_main-exports'); #, $agentnum
1560 foreach my $part_export ( @part_export ) {
1561 my $error = $part_export->export_replace( $self, $old, @$export_args);
1563 $dbh->rollback if $oldAutoCommit;
1564 return "exporting to ". $part_export->exporttype.
1565 " (transaction rolled back): $error";
1569 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1574 =item queue_fuzzyfiles_update
1576 Used by insert & replace to update the fuzzy search cache
1580 sub queue_fuzzyfiles_update {
1583 local $SIG{HUP} = 'IGNORE';
1584 local $SIG{INT} = 'IGNORE';
1585 local $SIG{QUIT} = 'IGNORE';
1586 local $SIG{TERM} = 'IGNORE';
1587 local $SIG{TSTP} = 'IGNORE';
1588 local $SIG{PIPE} = 'IGNORE';
1590 my $oldAutoCommit = $FS::UID::AutoCommit;
1591 local $FS::UID::AutoCommit = 0;
1594 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1595 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1597 $dbh->rollback if $oldAutoCommit;
1598 return "queueing job (transaction rolled back): $error";
1601 if ( $self->ship_last ) {
1602 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1603 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1605 $dbh->rollback if $oldAutoCommit;
1606 return "queueing job (transaction rolled back): $error";
1610 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1617 Checks all fields to make sure this is a valid customer record. If there is
1618 an error, returns the error, otherwise returns false. Called by the insert
1619 and replace methods.
1626 warn "$me check BEFORE: \n". $self->_dump
1630 $self->ut_numbern('custnum')
1631 || $self->ut_number('agentnum')
1632 || $self->ut_textn('agent_custid')
1633 || $self->ut_number('refnum')
1634 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1635 || $self->ut_textn('custbatch')
1636 || $self->ut_name('last')
1637 || $self->ut_name('first')
1638 || $self->ut_snumbern('birthdate')
1639 || $self->ut_snumbern('signupdate')
1640 || $self->ut_textn('company')
1641 || $self->ut_text('address1')
1642 || $self->ut_textn('address2')
1643 || $self->ut_text('city')
1644 || $self->ut_textn('county')
1645 || $self->ut_textn('state')
1646 || $self->ut_country('country')
1647 || $self->ut_anything('comments')
1648 || $self->ut_numbern('referral_custnum')
1649 || $self->ut_textn('stateid')
1650 || $self->ut_textn('stateid_state')
1651 || $self->ut_textn('invoice_terms')
1652 || $self->ut_alphan('geocode')
1653 || $self->ut_floatn('cdr_termination_percentage')
1654 || $self->ut_floatn('credit_limit')
1657 #barf. need message catalogs. i18n. etc.
1658 $error .= "Please select an advertising source."
1659 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1660 return $error if $error;
1662 return "Unknown agent"
1663 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1665 return "Unknown refnum"
1666 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1668 return "Unknown referring custnum: ". $self->referral_custnum
1669 unless ! $self->referral_custnum
1670 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1672 if ( $self->censustract ne '' ) {
1673 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1674 or return "Illegal census tract: ". $self->censustract;
1676 $self->censustract("$1.$2");
1679 if ( $self->ss eq '' ) {
1684 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1685 or return "Illegal social security number: ". $self->ss;
1686 $self->ss("$1-$2-$3");
1690 # bad idea to disable, causes billing to fail because of no tax rates later
1691 # except we don't fail any more
1692 unless ( $import ) {
1693 unless ( qsearch('cust_main_county', {
1694 'country' => $self->country,
1697 return "Unknown state/county/country: ".
1698 $self->state. "/". $self->county. "/". $self->country
1699 unless qsearch('cust_main_county',{
1700 'state' => $self->state,
1701 'county' => $self->county,
1702 'country' => $self->country,
1708 $self->ut_phonen('daytime', $self->country)
1709 || $self->ut_phonen('night', $self->country)
1710 || $self->ut_phonen('fax', $self->country)
1712 return $error if $error;
1714 unless ( $ignore_illegal_zip ) {
1715 $error = $self->ut_zip('zip', $self->country);
1716 return $error if $error;
1719 if ( $conf->exists('cust_main-require_phone')
1720 && ! length($self->daytime) && ! length($self->night)
1723 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1725 : FS::Msgcat::_gettext('daytime');
1726 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1728 : FS::Msgcat::_gettext('night');
1730 return "$daytime_label or $night_label is required"
1734 if ( $self->has_ship_address
1735 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1736 $self->addr_fields )
1740 $self->ut_name('ship_last')
1741 || $self->ut_name('ship_first')
1742 || $self->ut_textn('ship_company')
1743 || $self->ut_text('ship_address1')
1744 || $self->ut_textn('ship_address2')
1745 || $self->ut_text('ship_city')
1746 || $self->ut_textn('ship_county')
1747 || $self->ut_textn('ship_state')
1748 || $self->ut_country('ship_country')
1750 return $error if $error;
1752 #false laziness with above
1753 unless ( qsearchs('cust_main_county', {
1754 'country' => $self->ship_country,
1757 return "Unknown ship_state/ship_county/ship_country: ".
1758 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1759 unless qsearch('cust_main_county',{
1760 'state' => $self->ship_state,
1761 'county' => $self->ship_county,
1762 'country' => $self->ship_country,
1768 $self->ut_phonen('ship_daytime', $self->ship_country)
1769 || $self->ut_phonen('ship_night', $self->ship_country)
1770 || $self->ut_phonen('ship_fax', $self->ship_country)
1772 return $error if $error;
1774 unless ( $ignore_illegal_zip ) {
1775 $error = $self->ut_zip('ship_zip', $self->ship_country);
1776 return $error if $error;
1778 return "Unit # is required."
1779 if $self->ship_address2 =~ /^\s*$/
1780 && $conf->exists('cust_main-require_address2');
1782 } else { # ship_ info eq billing info, so don't store dup info in database
1784 $self->setfield("ship_$_", '')
1785 foreach $self->addr_fields;
1787 return "Unit # is required."
1788 if $self->address2 =~ /^\s*$/
1789 && $conf->exists('cust_main-require_address2');
1793 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1794 # or return "Illegal payby: ". $self->payby;
1796 FS::payby->can_payby($self->table, $self->payby)
1797 or return "Illegal payby: ". $self->payby;
1799 $error = $self->ut_numbern('paystart_month')
1800 || $self->ut_numbern('paystart_year')
1801 || $self->ut_numbern('payissue')
1802 || $self->ut_textn('paytype')
1804 return $error if $error;
1806 if ( $self->payip eq '' ) {
1809 $error = $self->ut_ip('payip');
1810 return $error if $error;
1813 # If it is encrypted and the private key is not availaible then we can't
1814 # check the credit card.
1815 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1817 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1819 my $payinfo = $self->payinfo;
1820 $payinfo =~ s/\D//g;
1821 $payinfo =~ /^(\d{13,16})$/
1822 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1824 $self->payinfo($payinfo);
1826 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1828 return gettext('unknown_card_type')
1829 if $self->payinfo !~ /^99\d{14}$/ #token
1830 && cardtype($self->payinfo) eq "Unknown";
1832 unless ( $ignore_banned_card ) {
1833 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1835 return 'Banned credit card: banned on '.
1836 time2str('%a %h %o at %r', $ban->_date).
1837 ' by '. $ban->otaker.
1838 ' (ban# '. $ban->bannum. ')';
1842 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1843 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1844 $self->paycvv =~ /^(\d{4})$/
1845 or return "CVV2 (CID) for American Express cards is four digits.";
1848 $self->paycvv =~ /^(\d{3})$/
1849 or return "CVV2 (CVC2/CID) is three digits.";
1856 my $cardtype = cardtype($payinfo);
1857 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1859 return "Start date or issue number is required for $cardtype cards"
1860 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1862 return "Start month must be between 1 and 12"
1863 if $self->paystart_month
1864 and $self->paystart_month < 1 || $self->paystart_month > 12;
1866 return "Start year must be 1990 or later"
1867 if $self->paystart_year
1868 and $self->paystart_year < 1990;
1870 return "Issue number must be beween 1 and 99"
1872 and $self->payissue < 1 || $self->payissue > 99;
1875 $self->paystart_month('');
1876 $self->paystart_year('');
1877 $self->payissue('');
1880 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1882 my $payinfo = $self->payinfo;
1883 $payinfo =~ s/[^\d\@]//g;
1884 if ( $conf->exists('echeck-nonus') ) {
1885 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1886 $payinfo = "$1\@$2";
1888 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1889 $payinfo = "$1\@$2";
1891 $self->payinfo($payinfo);
1894 unless ( $ignore_banned_card ) {
1895 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1897 return 'Banned ACH account: banned on '.
1898 time2str('%a %h %o at %r', $ban->_date).
1899 ' by '. $ban->otaker.
1900 ' (ban# '. $ban->bannum. ')';
1904 } elsif ( $self->payby eq 'LECB' ) {
1906 my $payinfo = $self->payinfo;
1907 $payinfo =~ s/\D//g;
1908 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1910 $self->payinfo($payinfo);
1913 } elsif ( $self->payby eq 'BILL' ) {
1915 $error = $self->ut_textn('payinfo');
1916 return "Illegal P.O. number: ". $self->payinfo if $error;
1919 } elsif ( $self->payby eq 'COMP' ) {
1921 my $curuser = $FS::CurrentUser::CurrentUser;
1922 if ( ! $self->custnum
1923 && ! $curuser->access_right('Complimentary customer')
1926 return "You are not permitted to create complimentary accounts."
1929 $error = $self->ut_textn('payinfo');
1930 return "Illegal comp account issuer: ". $self->payinfo if $error;
1933 } elsif ( $self->payby eq 'PREPAY' ) {
1935 my $payinfo = $self->payinfo;
1936 $payinfo =~ s/\W//g; #anything else would just confuse things
1937 $self->payinfo($payinfo);
1938 $error = $self->ut_alpha('payinfo');
1939 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1940 return "Unknown prepayment identifier"
1941 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1946 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1947 return "Expiration date required"
1948 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1952 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1953 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1954 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1955 ( $m, $y ) = ( $2, "19$1" );
1956 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1957 ( $m, $y ) = ( $3, "20$2" );
1959 return "Illegal expiration date: ". $self->paydate;
1961 $m = sprintf('%02d',$m);
1962 $self->paydate("$y-$m-01");
1963 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1964 return gettext('expired_card')
1966 && !$ignore_expired_card
1967 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1970 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1971 ( ! $conf->exists('require_cardname')
1972 || $self->payby !~ /^(CARD|DCRD)$/ )
1974 $self->payname( $self->first. " ". $self->getfield('last') );
1976 $self->payname =~ /^([µ_0123456789aAáÁàÀâÂåÅäÄãêæÆbBcCçÇdDðÐeEéÉèÈêÊëËfFgGhHiIíÍìÌîÎïÏjJkKlLmMnNñÑoOóÓòÒôÔöÖõÕøغpPqQrRsSßtTuUúÚùÙûÛüÜvVwWxXyYýÝÿzZþÞ \,\.\-\'\&]+)$/
1977 or return gettext('illegal_name'). " payname: ". $self->payname;
1981 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1982 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1986 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1988 warn "$me check AFTER: \n". $self->_dump
1991 $self->SUPER::check;
1996 Returns a list of fields which have ship_ duplicates.
2001 qw( last first company
2002 address1 address2 city county state zip country
2007 =item has_ship_address
2009 Returns true if this customer record has a separate shipping address.
2013 sub has_ship_address {
2015 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2020 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2021 city, county, state, zip, country, and geocode. The shipping address is used if present.
2027 Returns all locations (see L<FS::cust_location>) for this customer.
2033 qsearch('cust_location', { 'custnum' => $self->custnum } );
2038 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2039 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2040 on success or a list of errors.
2046 grep { $_->unsuspend } $self->suspended_pkgs;
2051 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2053 Returns a list: an empty list on success or a list of errors.
2059 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2062 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2064 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2065 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2066 of a list of pkgparts; the hashref has the following keys:
2070 =item pkgparts - listref of pkgparts
2072 =item (other options are passed to the suspend method)
2077 Returns a list: an empty list on success or a list of errors.
2081 sub suspend_if_pkgpart {
2083 my (@pkgparts, %opt);
2084 if (ref($_[0]) eq 'HASH'){
2085 @pkgparts = @{$_[0]{pkgparts}};
2090 grep { $_->suspend(%opt) }
2091 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2092 $self->unsuspended_pkgs;
2095 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2097 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2098 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2099 instead of a list of pkgparts; the hashref has the following keys:
2103 =item pkgparts - listref of pkgparts
2105 =item (other options are passed to the suspend method)
2109 Returns a list: an empty list on success or a list of errors.
2113 sub suspend_unless_pkgpart {
2115 my (@pkgparts, %opt);
2116 if (ref($_[0]) eq 'HASH'){
2117 @pkgparts = @{$_[0]{pkgparts}};
2122 grep { $_->suspend(%opt) }
2123 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2124 $self->unsuspended_pkgs;
2127 =item cancel [ OPTION => VALUE ... ]
2129 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2131 Available options are:
2135 =item quiet - can be set true to supress email cancellation notices.
2137 =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.
2139 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2141 =item nobill - can be set true to skip billing if it might otherwise be done.
2145 Always returns a list: an empty list on success or a list of errors.
2149 # nb that dates are not specified as valid options to this method
2152 my( $self, %opt ) = @_;
2154 warn "$me cancel called on customer ". $self->custnum. " with options ".
2155 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2158 return ( 'access denied' )
2159 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2161 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2163 #should try decryption (we might have the private key)
2164 # and if not maybe queue a job for the server that does?
2165 return ( "Can't (yet) ban encrypted credit cards" )
2166 if $self->is_encrypted($self->payinfo);
2168 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2169 my $error = $ban->insert;
2170 return ( $error ) if $error;
2174 my @pkgs = $self->ncancelled_pkgs;
2176 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2178 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2179 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2183 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2184 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2187 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2190 sub _banned_pay_hashref {
2201 'payby' => $payby2ban{$self->payby},
2202 'payinfo' => md5_base64($self->payinfo),
2203 #don't ever *search* on reason! #'reason' =>
2209 Returns all notes (see L<FS::cust_main_note>) for this customer.
2214 my($self,$orderby_classnum) = (shift,shift);
2215 my $orderby = "_DATE DESC";
2216 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2217 qsearch( 'cust_main_note',
2218 { 'custnum' => $self->custnum },
2220 "ORDER BY $orderby",
2226 Returns the agent (see L<FS::agent>) for this customer.
2232 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2237 Returns the agent name (see L<FS::agent>) for this customer.
2243 $self->agent->agent;
2248 Returns any tags associated with this customer, as FS::cust_tag objects,
2249 or an empty list if there are no tags.
2255 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2260 Returns any tags associated with this customer, as FS::part_tag objects,
2261 or an empty list if there are no tags.
2267 map $_->part_tag, $self->cust_tag;
2273 Returns the customer class, as an FS::cust_class object, or the empty string
2274 if there is no customer class.
2280 if ( $self->classnum ) {
2281 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2289 Returns the customer category name, or the empty string if there is no customer
2296 my $cust_class = $self->cust_class;
2298 ? $cust_class->categoryname
2304 Returns the customer class name, or the empty string if there is no customer
2311 my $cust_class = $self->cust_class;
2313 ? $cust_class->classname
2317 =item BILLING METHODS
2319 Documentation on billing methods has been moved to
2320 L<FS::cust_main::Billing>.
2322 =item REALTIME BILLING METHODS
2324 Documentation on realtime billing methods has been moved to
2325 L<FS::cust_main::Billing_Realtime>.
2329 Removes the I<paycvv> field from the database directly.
2331 If there is an error, returns the error, otherwise returns false.
2337 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2338 or return dbh->errstr;
2339 $sth->execute($self->custnum)
2340 or return $sth->errstr;
2345 =item batch_card OPTION => VALUE...
2347 Adds a payment for this invoice to the pending credit card batch (see
2348 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2349 runs the payment using a realtime gateway.
2354 my ($self, %options) = @_;
2357 if (exists($options{amount})) {
2358 $amount = $options{amount};
2360 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2362 return '' unless $amount > 0;
2364 my $invnum = delete $options{invnum};
2365 my $payby = $options{payby} || $self->payby; #still dubious
2367 if ($options{'realtime'}) {
2368 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2374 my $oldAutoCommit = $FS::UID::AutoCommit;
2375 local $FS::UID::AutoCommit = 0;
2378 #this needs to handle mysql as well as Pg, like svc_acct.pm
2379 #(make it into a common function if folks need to do batching with mysql)
2380 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2381 or return "Cannot lock pay_batch: " . $dbh->errstr;
2385 'payby' => FS::payby->payby2payment($payby),
2388 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2390 unless ( $pay_batch ) {
2391 $pay_batch = new FS::pay_batch \%pay_batch;
2392 my $error = $pay_batch->insert;
2394 $dbh->rollback if $oldAutoCommit;
2395 die "error creating new batch: $error\n";
2399 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2400 'batchnum' => $pay_batch->batchnum,
2401 'custnum' => $self->custnum,
2404 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2406 $options{$_} = '' unless exists($options{$_});
2409 my $cust_pay_batch = new FS::cust_pay_batch ( {
2410 'batchnum' => $pay_batch->batchnum,
2411 'invnum' => $invnum || 0, # is there a better value?
2412 # this field should be
2414 # cust_bill_pay_batch now
2415 'custnum' => $self->custnum,
2416 'last' => $self->getfield('last'),
2417 'first' => $self->getfield('first'),
2418 'address1' => $options{address1} || $self->address1,
2419 'address2' => $options{address2} || $self->address2,
2420 'city' => $options{city} || $self->city,
2421 'state' => $options{state} || $self->state,
2422 'zip' => $options{zip} || $self->zip,
2423 'country' => $options{country} || $self->country,
2424 'payby' => $options{payby} || $self->payby,
2425 'payinfo' => $options{payinfo} || $self->payinfo,
2426 'exp' => $options{paydate} || $self->paydate,
2427 'payname' => $options{payname} || $self->payname,
2428 'amount' => $amount, # consolidating
2431 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2432 if $old_cust_pay_batch;
2435 if ($old_cust_pay_batch) {
2436 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2438 $error = $cust_pay_batch->insert;
2442 $dbh->rollback if $oldAutoCommit;
2446 my $unapplied = $self->total_unapplied_credits
2447 + $self->total_unapplied_payments
2448 + $self->in_transit_payments;
2449 foreach my $cust_bill ($self->open_cust_bill) {
2450 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2451 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2452 'invnum' => $cust_bill->invnum,
2453 'paybatchnum' => $cust_pay_batch->paybatchnum,
2454 'amount' => $cust_bill->owed,
2457 if ($unapplied >= $cust_bill_pay_batch->amount){
2458 $unapplied -= $cust_bill_pay_batch->amount;
2461 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2462 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2464 $error = $cust_bill_pay_batch->insert;
2466 $dbh->rollback if $oldAutoCommit;
2471 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2477 Returns the total owed for this customer on all invoices
2478 (see L<FS::cust_bill/owed>).
2484 $self->total_owed_date(2145859200); #12/31/2037
2487 =item total_owed_date TIME
2489 Returns the total owed for this customer on all invoices with date earlier than
2490 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2491 see L<Time::Local> and L<Date::Parse> for conversion functions.
2495 sub total_owed_date {
2499 my $custnum = $self->custnum;
2501 my $owed_sql = FS::cust_bill->owed_sql;
2504 SELECT SUM($owed_sql) FROM cust_bill
2505 WHERE custnum = $custnum
2509 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2513 =item total_owed_pkgnum PKGNUM
2515 Returns the total owed on all invoices for this customer's specific package
2516 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2520 sub total_owed_pkgnum {
2521 my( $self, $pkgnum ) = @_;
2522 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2525 =item total_owed_date_pkgnum TIME PKGNUM
2527 Returns the total owed for this customer's specific package when using
2528 experimental package balances on all invoices with date earlier than
2529 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2530 see L<Time::Local> and L<Date::Parse> for conversion functions.
2534 sub total_owed_date_pkgnum {
2535 my( $self, $time, $pkgnum ) = @_;
2538 foreach my $cust_bill (
2539 grep { $_->_date <= $time }
2540 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2542 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2544 sprintf( "%.2f", $total_bill );
2550 Returns the total amount of all payments.
2557 $total += $_->paid foreach $self->cust_pay;
2558 sprintf( "%.2f", $total );
2561 =item total_unapplied_credits
2563 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2564 customer. See L<FS::cust_credit/credited>.
2566 =item total_credited
2568 Old name for total_unapplied_credits. Don't use.
2572 sub total_credited {
2573 #carp "total_credited deprecated, use total_unapplied_credits";
2574 shift->total_unapplied_credits(@_);
2577 sub total_unapplied_credits {
2580 my $custnum = $self->custnum;
2582 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2585 SELECT SUM($unapplied_sql) FROM cust_credit
2586 WHERE custnum = $custnum
2589 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2593 =item total_unapplied_credits_pkgnum PKGNUM
2595 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2596 customer. See L<FS::cust_credit/credited>.
2600 sub total_unapplied_credits_pkgnum {
2601 my( $self, $pkgnum ) = @_;
2602 my $total_credit = 0;
2603 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2604 sprintf( "%.2f", $total_credit );
2608 =item total_unapplied_payments
2610 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2611 See L<FS::cust_pay/unapplied>.
2615 sub total_unapplied_payments {
2618 my $custnum = $self->custnum;
2620 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2623 SELECT SUM($unapplied_sql) FROM cust_pay
2624 WHERE custnum = $custnum
2627 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2631 =item total_unapplied_payments_pkgnum PKGNUM
2633 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2634 specific package when using experimental package balances. See
2635 L<FS::cust_pay/unapplied>.
2639 sub total_unapplied_payments_pkgnum {
2640 my( $self, $pkgnum ) = @_;
2641 my $total_unapplied = 0;
2642 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2643 sprintf( "%.2f", $total_unapplied );
2647 =item total_unapplied_refunds
2649 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2650 customer. See L<FS::cust_refund/unapplied>.
2654 sub total_unapplied_refunds {
2656 my $custnum = $self->custnum;
2658 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2661 SELECT SUM($unapplied_sql) FROM cust_refund
2662 WHERE custnum = $custnum
2665 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2671 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2672 total_unapplied_credits minus total_unapplied_payments).
2678 $self->balance_date_range;
2681 =item balance_date TIME
2683 Returns the balance for this customer, only considering invoices with date
2684 earlier than TIME (total_owed_date minus total_credited minus
2685 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2686 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2693 $self->balance_date_range(shift);
2696 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2698 Returns the balance for this customer, optionally considering invoices with
2699 date earlier than START_TIME, and not later than END_TIME
2700 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2702 Times are specified as SQL fragments or numeric
2703 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2704 L<Date::Parse> for conversion functions. The empty string can be passed
2705 to disable that time constraint completely.
2707 Available options are:
2711 =item unapplied_date
2713 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)
2719 sub balance_date_range {
2721 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2722 ') FROM cust_main WHERE custnum='. $self->custnum;
2723 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2726 =item balance_pkgnum PKGNUM
2728 Returns the balance for this customer's specific package when using
2729 experimental package balances (total_owed plus total_unrefunded, minus
2730 total_unapplied_credits minus total_unapplied_payments)
2734 sub balance_pkgnum {
2735 my( $self, $pkgnum ) = @_;
2738 $self->total_owed_pkgnum($pkgnum)
2739 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2740 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2741 - $self->total_unapplied_credits_pkgnum($pkgnum)
2742 - $self->total_unapplied_payments_pkgnum($pkgnum)
2746 =item in_transit_payments
2748 Returns the total of requests for payments for this customer pending in
2749 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2753 sub in_transit_payments {
2755 my $in_transit_payments = 0;
2756 foreach my $pay_batch ( qsearch('pay_batch', {
2759 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2760 'batchnum' => $pay_batch->batchnum,
2761 'custnum' => $self->custnum,
2763 $in_transit_payments += $cust_pay_batch->amount;
2766 sprintf( "%.2f", $in_transit_payments );
2771 Returns a hash of useful information for making a payment.
2781 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2782 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2783 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2787 For credit card transactions:
2799 For electronic check transactions:
2814 $return{balance} = $self->balance;
2816 $return{payname} = $self->payname
2817 || ( $self->first. ' '. $self->get('last') );
2819 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2821 $return{payby} = $self->payby;
2822 $return{stateid_state} = $self->stateid_state;
2824 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2825 $return{card_type} = cardtype($self->payinfo);
2826 $return{payinfo} = $self->paymask;
2828 @return{'month', 'year'} = $self->paydate_monthyear;
2832 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2833 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2834 $return{payinfo1} = $payinfo1;
2835 $return{payinfo2} = $payinfo2;
2836 $return{paytype} = $self->paytype;
2837 $return{paystate} = $self->paystate;
2841 #doubleclick protection
2843 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2849 =item paydate_monthyear
2851 Returns a two-element list consisting of the month and year of this customer's
2852 paydate (credit card expiration date for CARD customers)
2856 sub paydate_monthyear {
2858 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2860 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2867 =item tax_exemption TAXNAME
2872 my( $self, $taxname ) = @_;
2874 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2875 'taxname' => $taxname,
2880 =item cust_main_exemption
2884 sub cust_main_exemption {
2886 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
2889 =item invoicing_list [ ARRAYREF ]
2891 If an arguement is given, sets these email addresses as invoice recipients
2892 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2893 (except as warnings), so use check_invoicing_list first.
2895 Returns a list of email addresses (with svcnum entries expanded).
2897 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2898 check it without disturbing anything by passing nothing.
2900 This interface may change in the future.
2904 sub invoicing_list {
2905 my( $self, $arrayref ) = @_;
2908 my @cust_main_invoice;
2909 if ( $self->custnum ) {
2910 @cust_main_invoice =
2911 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2913 @cust_main_invoice = ();
2915 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2916 #warn $cust_main_invoice->destnum;
2917 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2918 #warn $cust_main_invoice->destnum;
2919 my $error = $cust_main_invoice->delete;
2920 warn $error if $error;
2923 if ( $self->custnum ) {
2924 @cust_main_invoice =
2925 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2927 @cust_main_invoice = ();
2929 my %seen = map { $_->address => 1 } @cust_main_invoice;
2930 foreach my $address ( @{$arrayref} ) {
2931 next if exists $seen{$address} && $seen{$address};
2932 $seen{$address} = 1;
2933 my $cust_main_invoice = new FS::cust_main_invoice ( {
2934 'custnum' => $self->custnum,
2937 my $error = $cust_main_invoice->insert;
2938 warn $error if $error;
2942 if ( $self->custnum ) {
2944 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2951 =item check_invoicing_list ARRAYREF
2953 Checks these arguements as valid input for the invoicing_list method. If there
2954 is an error, returns the error, otherwise returns false.
2958 sub check_invoicing_list {
2959 my( $self, $arrayref ) = @_;
2961 foreach my $address ( @$arrayref ) {
2963 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2964 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2967 my $cust_main_invoice = new FS::cust_main_invoice ( {
2968 'custnum' => $self->custnum,
2971 my $error = $self->custnum
2972 ? $cust_main_invoice->check
2973 : $cust_main_invoice->checkdest
2975 return $error if $error;
2979 return "Email address required"
2980 if $conf->exists('cust_main-require_invoicing_list_email')
2981 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2986 =item set_default_invoicing_list
2988 Sets the invoicing list to all accounts associated with this customer,
2989 overwriting any previous invoicing list.
2993 sub set_default_invoicing_list {
2995 $self->invoicing_list($self->all_emails);
3000 Returns the email addresses of all accounts provisioned for this customer.
3007 foreach my $cust_pkg ( $self->all_pkgs ) {
3008 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3010 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3011 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3013 $list{$_}=1 foreach map { $_->email } @svc_acct;
3018 =item invoicing_list_addpost
3020 Adds postal invoicing to this customer. If this customer is already configured
3021 to receive postal invoices, does nothing.
3025 sub invoicing_list_addpost {
3027 return if grep { $_ eq 'POST' } $self->invoicing_list;
3028 my @invoicing_list = $self->invoicing_list;
3029 push @invoicing_list, 'POST';
3030 $self->invoicing_list(\@invoicing_list);
3033 =item invoicing_list_emailonly
3035 Returns the list of email invoice recipients (invoicing_list without non-email
3036 destinations such as POST and FAX).
3040 sub invoicing_list_emailonly {
3042 warn "$me invoicing_list_emailonly called"
3044 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3047 =item invoicing_list_emailonly_scalar
3049 Returns the list of email invoice recipients (invoicing_list without non-email
3050 destinations such as POST and FAX) as a comma-separated scalar.
3054 sub invoicing_list_emailonly_scalar {
3056 warn "$me invoicing_list_emailonly_scalar called"
3058 join(', ', $self->invoicing_list_emailonly);
3061 =item referral_custnum_cust_main
3063 Returns the customer who referred this customer (or the empty string, if
3064 this customer was not referred).
3066 Note the difference with referral_cust_main method: This method,
3067 referral_custnum_cust_main returns the single customer (if any) who referred
3068 this customer, while referral_cust_main returns an array of customers referred
3073 sub referral_custnum_cust_main {
3075 return '' unless $self->referral_custnum;
3076 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3079 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3081 Returns an array of customers referred by this customer (referral_custnum set
3082 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3083 customers referred by customers referred by this customer and so on, inclusive.
3084 The default behavior is DEPTH 1 (no recursion).
3086 Note the difference with referral_custnum_cust_main method: This method,
3087 referral_cust_main, returns an array of customers referred BY this customer,
3088 while referral_custnum_cust_main returns the single customer (if any) who
3089 referred this customer.
3093 sub referral_cust_main {
3095 my $depth = @_ ? shift : 1;
3096 my $exclude = @_ ? shift : {};
3099 map { $exclude->{$_->custnum}++; $_; }
3100 grep { ! $exclude->{ $_->custnum } }
3101 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3105 map { $_->referral_cust_main($depth-1, $exclude) }
3112 =item referral_cust_main_ncancelled
3114 Same as referral_cust_main, except only returns customers with uncancelled
3119 sub referral_cust_main_ncancelled {
3121 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3124 =item referral_cust_pkg [ DEPTH ]
3126 Like referral_cust_main, except returns a flat list of all unsuspended (and
3127 uncancelled) packages for each customer. The number of items in this list may
3128 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3132 sub referral_cust_pkg {
3134 my $depth = @_ ? shift : 1;
3136 map { $_->unsuspended_pkgs }
3137 grep { $_->unsuspended_pkgs }
3138 $self->referral_cust_main($depth);
3141 =item referring_cust_main
3143 Returns the single cust_main record for the customer who referred this customer
3144 (referral_custnum), or false.
3148 sub referring_cust_main {
3150 return '' unless $self->referral_custnum;
3151 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3154 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3156 Applies a credit to this customer. If there is an error, returns the error,
3157 otherwise returns false.
3159 REASON can be a text string, an FS::reason object, or a scalar reference to
3160 a reasonnum. If a text string, it will be automatically inserted as a new
3161 reason, and a 'reason_type' option must be passed to indicate the
3162 FS::reason_type for the new reason.
3164 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3166 Any other options are passed to FS::cust_credit::insert.
3171 my( $self, $amount, $reason, %options ) = @_;
3173 my $cust_credit = new FS::cust_credit {
3174 'custnum' => $self->custnum,
3175 'amount' => $amount,
3178 if ( ref($reason) ) {
3180 if ( ref($reason) eq 'SCALAR' ) {
3181 $cust_credit->reasonnum( $$reason );
3183 $cust_credit->reasonnum( $reason->reasonnum );
3187 $cust_credit->set('reason', $reason)
3190 for (qw( addlinfo eventnum )) {
3191 $cust_credit->$_( delete $options{$_} )
3192 if exists($options{$_});
3195 $cust_credit->insert(%options);
3199 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3201 Creates a one-time charge for this customer. If there is an error, returns
3202 the error, otherwise returns false.
3204 New-style, with a hashref of options:
3206 my $error = $cust_main->charge(
3210 'start_date' => str2time('7/4/2009'),
3211 'pkg' => 'Description',
3212 'comment' => 'Comment',
3213 'additional' => [], #extra invoice detail
3214 'classnum' => 1, #pkg_class
3216 'setuptax' => '', # or 'Y' for tax exempt
3219 'taxclass' => 'Tax class',
3222 'taxproduct' => 2, #part_pkg_taxproduct
3223 'override' => {}, #XXX describe
3225 #will be filled in with the new object
3226 'cust_pkg_ref' => \$cust_pkg,
3228 #generate an invoice immediately
3230 'invoice_terms' => '', #with these terms
3236 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3242 my ( $amount, $quantity, $start_date, $classnum );
3243 my ( $pkg, $comment, $additional );
3244 my ( $setuptax, $taxclass ); #internal taxes
3245 my ( $taxproduct, $override ); #vendor (CCH) taxes
3247 my $cust_pkg_ref = '';
3248 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3249 if ( ref( $_[0] ) ) {
3250 $amount = $_[0]->{amount};
3251 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3252 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3253 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3254 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3255 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3256 : '$'. sprintf("%.2f",$amount);
3257 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3258 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3259 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3260 $additional = $_[0]->{additional} || [];
3261 $taxproduct = $_[0]->{taxproductnum};
3262 $override = { '' => $_[0]->{tax_override} };
3263 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3264 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3265 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3270 $pkg = @_ ? shift : 'One-time charge';
3271 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3273 $taxclass = @_ ? shift : '';
3277 local $SIG{HUP} = 'IGNORE';
3278 local $SIG{INT} = 'IGNORE';
3279 local $SIG{QUIT} = 'IGNORE';
3280 local $SIG{TERM} = 'IGNORE';
3281 local $SIG{TSTP} = 'IGNORE';
3282 local $SIG{PIPE} = 'IGNORE';
3284 my $oldAutoCommit = $FS::UID::AutoCommit;
3285 local $FS::UID::AutoCommit = 0;
3288 my $part_pkg = new FS::part_pkg ( {
3290 'comment' => $comment,
3294 'classnum' => ( $classnum ? $classnum : '' ),
3295 'setuptax' => $setuptax,
3296 'taxclass' => $taxclass,
3297 'taxproductnum' => $taxproduct,
3300 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3301 ( 0 .. @$additional - 1 )
3303 'additional_count' => scalar(@$additional),
3304 'setup_fee' => $amount,
3307 my $error = $part_pkg->insert( options => \%options,
3308 tax_overrides => $override,
3311 $dbh->rollback if $oldAutoCommit;
3315 my $pkgpart = $part_pkg->pkgpart;
3316 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3317 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3318 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3319 $error = $type_pkgs->insert;
3321 $dbh->rollback if $oldAutoCommit;
3326 my $cust_pkg = new FS::cust_pkg ( {
3327 'custnum' => $self->custnum,
3328 'pkgpart' => $pkgpart,
3329 'quantity' => $quantity,
3330 'start_date' => $start_date,
3331 'no_auto' => $no_auto,
3334 $error = $cust_pkg->insert;
3336 $dbh->rollback if $oldAutoCommit;
3338 } elsif ( $cust_pkg_ref ) {
3339 ${$cust_pkg_ref} = $cust_pkg;
3343 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3344 'pkg_list' => [ $cust_pkg ],
3347 $dbh->rollback if $oldAutoCommit;
3352 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3357 #=item charge_postal_fee
3359 #Applies a one time charge this customer. If there is an error,
3360 #returns the error, returns the cust_pkg charge object or false
3361 #if there was no charge.
3365 # This should be a customer event. For that to work requires that bill
3366 # also be a customer event.
3368 sub charge_postal_fee {
3371 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
3372 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3374 my $cust_pkg = new FS::cust_pkg ( {
3375 'custnum' => $self->custnum,
3376 'pkgpart' => $pkgpart,
3380 my $error = $cust_pkg->insert;
3381 $error ? $error : $cust_pkg;
3384 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3386 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3388 Optionally, a list or hashref of additional arguments to the qsearch call can
3395 my $opt = ref($_[0]) ? shift : { @_ };
3397 #return $self->num_cust_bill unless wantarray || keys %$opt;
3399 $opt->{'table'} = 'cust_bill';
3400 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3401 $opt->{'hashref'}{'custnum'} = $self->custnum;
3402 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3404 map { $_ } #behavior of sort undefined in scalar context
3405 sort { $a->_date <=> $b->_date }
3409 =item open_cust_bill
3411 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3416 sub open_cust_bill {
3420 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3426 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3428 Returns all the statements (see L<FS::cust_statement>) for this customer.
3430 Optionally, a list or hashref of additional arguments to the qsearch call can
3435 sub cust_statement {
3437 my $opt = ref($_[0]) ? shift : { @_ };
3439 #return $self->num_cust_statement unless wantarray || keys %$opt;
3441 $opt->{'table'} = 'cust_statement';
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 }
3453 Returns all the credits (see L<FS::cust_credit>) for this customer.
3459 map { $_ } #return $self->num_cust_credit unless wantarray;
3460 sort { $a->_date <=> $b->_date }
3461 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3464 =item cust_credit_pkgnum
3466 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3467 package when using experimental package balances.
3471 sub cust_credit_pkgnum {
3472 my( $self, $pkgnum ) = @_;
3473 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3474 sort { $a->_date <=> $b->_date }
3475 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3476 'pkgnum' => $pkgnum,
3483 Returns all the payments (see L<FS::cust_pay>) for this customer.
3489 return $self->num_cust_pay unless wantarray;
3490 sort { $a->_date <=> $b->_date }
3491 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3496 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3497 called automatically when the cust_pay method is used in a scalar context.
3503 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3504 my $sth = dbh->prepare($sql) or die dbh->errstr;
3505 $sth->execute($self->custnum) or die $sth->errstr;
3506 $sth->fetchrow_arrayref->[0];
3509 =item cust_pay_pkgnum
3511 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3512 package when using experimental package balances.
3516 sub cust_pay_pkgnum {
3517 my( $self, $pkgnum ) = @_;
3518 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3519 sort { $a->_date <=> $b->_date }
3520 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3521 'pkgnum' => $pkgnum,
3528 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3534 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3535 sort { $a->_date <=> $b->_date }
3536 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3539 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3541 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3543 Optionally, a list or hashref of additional arguments to the qsearch call can
3548 sub cust_pay_batch {
3550 my $opt = ref($_[0]) ? shift : { @_ };
3552 #return $self->num_cust_statement unless wantarray || keys %$opt;
3554 $opt->{'table'} = 'cust_pay_batch';
3555 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3556 $opt->{'hashref'}{'custnum'} = $self->custnum;
3557 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3559 map { $_ } #behavior of sort undefined in scalar context
3560 sort { $a->paybatchnum <=> $b->paybatchnum }
3564 =item cust_pay_pending
3566 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3567 (without status "done").
3571 sub cust_pay_pending {
3573 return $self->num_cust_pay_pending unless wantarray;
3574 sort { $a->_date <=> $b->_date }
3575 qsearch( 'cust_pay_pending', {
3576 'custnum' => $self->custnum,
3577 'status' => { op=>'!=', value=>'done' },
3582 =item cust_pay_pending_attempt
3584 Returns all payment attempts / declined payments for this customer, as pending
3585 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3586 a corresponding payment (see L<FS::cust_pay>).
3590 sub cust_pay_pending_attempt {
3592 return $self->num_cust_pay_pending_attempt unless wantarray;
3593 sort { $a->_date <=> $b->_date }
3594 qsearch( 'cust_pay_pending', {
3595 'custnum' => $self->custnum,
3602 =item num_cust_pay_pending
3604 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3605 customer (without status "done"). Also called automatically when the
3606 cust_pay_pending method is used in a scalar context.
3610 sub num_cust_pay_pending {
3613 " SELECT COUNT(*) FROM cust_pay_pending ".
3614 " WHERE custnum = ? AND status != 'done' ",
3619 =item num_cust_pay_pending_attempt
3621 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3622 customer, with status "done" but without a corresp. Also called automatically when the
3623 cust_pay_pending method is used in a scalar context.
3627 sub num_cust_pay_pending_attempt {
3630 " SELECT COUNT(*) FROM cust_pay_pending ".
3631 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3638 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3644 map { $_ } #return $self->num_cust_refund unless wantarray;
3645 sort { $a->_date <=> $b->_date }
3646 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3649 =item display_custnum
3651 Returns the displayed customer number for this customer: agent_custid if
3652 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3656 sub display_custnum {
3658 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3659 return $self->agent_custid;
3661 return $self->custnum;
3667 Returns a name string for this customer, either "Company (Last, First)" or
3674 my $name = $self->contact;
3675 $name = $self->company. " ($name)" if $self->company;
3681 Returns a name string for this (service/shipping) contact, either
3682 "Company (Last, First)" or "Last, First".
3688 if ( $self->get('ship_last') ) {
3689 my $name = $self->ship_contact;
3690 $name = $self->ship_company. " ($name)" if $self->ship_company;
3699 Returns a name string for this customer, either "Company" or "First Last".
3705 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3708 =item ship_name_short
3710 Returns a name string for this (service/shipping) contact, either "Company"
3715 sub ship_name_short {
3717 if ( $self->get('ship_last') ) {
3718 $self->ship_company !~ /^\s*$/
3719 ? $self->ship_company
3720 : $self->ship_contact_firstlast;
3722 $self->name_company_or_firstlast;
3728 Returns this customer's full (billing) contact name only, "Last, First"
3734 $self->get('last'). ', '. $self->first;
3739 Returns this customer's full (shipping) contact name only, "Last, First"
3745 $self->get('ship_last')
3746 ? $self->get('ship_last'). ', '. $self->ship_first
3750 =item contact_firstlast
3752 Returns this customers full (billing) contact name only, "First Last".
3756 sub contact_firstlast {
3758 $self->first. ' '. $self->get('last');
3761 =item ship_contact_firstlast
3763 Returns this customer's full (shipping) contact name only, "First Last".
3767 sub ship_contact_firstlast {
3769 $self->get('ship_last')
3770 ? $self->first. ' '. $self->get('ship_last')
3771 : $self->contact_firstlast;
3776 Returns this customer's full country name
3782 code2country($self->country);
3785 =item geocode DATA_VENDOR
3787 Returns a value for the customer location as encoded by DATA_VENDOR.
3788 Currently this only makes sense for "CCH" as DATA_VENDOR.
3796 Returns a status string for this customer, currently:
3800 =item prospect - No packages have ever been ordered
3802 =item ordered - Recurring packages all are new (not yet billed).
3804 =item active - One or more recurring packages is active
3806 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3808 =item suspended - All non-cancelled recurring packages are suspended
3810 =item cancelled - All recurring packages are cancelled
3816 sub status { shift->cust_status(@_); }
3820 for my $status ( FS::cust_main->statuses() ) {
3821 my $method = $status.'_sql';
3822 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3823 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3824 $sth->execute( ($self->custnum) x $numnum )
3825 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3826 return $status if $sth->fetchrow_arrayref->[0];
3830 =item ucfirst_cust_status
3832 =item ucfirst_status
3834 Returns the status with the first character capitalized.
3838 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
3840 sub ucfirst_cust_status {
3842 ucfirst($self->cust_status);
3847 Returns a hex triplet color string for this customer's status.
3851 use vars qw(%statuscolor);
3852 tie %statuscolor, 'Tie::IxHash',
3853 'prospect' => '7e0079', #'000000', #black? naw, purple
3854 'active' => '00CC00', #green
3855 'ordered' => '009999', #teal? cyan?
3856 'suspended' => 'FF9900', #yellow
3857 'cancelled' => 'FF0000', #red
3858 'inactive' => '0000CC', #blue
3861 sub statuscolor { shift->cust_statuscolor(@_); }
3863 sub cust_statuscolor {
3865 $statuscolor{$self->cust_status};
3870 Returns an array of hashes representing the customer's RT tickets.
3877 my $num = $conf->config('cust_main-max_tickets') || 10;
3880 if ( $conf->config('ticket_system') ) {
3881 unless ( $conf->config('ticket_system-custom_priority_field') ) {
3883 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
3887 foreach my $priority (
3888 $conf->config('ticket_system-custom_priority_field-values'), ''
3890 last if scalar(@tickets) >= $num;
3892 @{ FS::TicketSystem->customer_tickets( $self->custnum,
3893 $num - scalar(@tickets),
3903 # Return services representing svc_accts in customer support packages
3904 sub support_services {
3906 my %packages = map { $_ => 1 } $conf->config('support_packages');
3908 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
3909 grep { $_->part_svc->svcdb eq 'svc_acct' }
3910 map { $_->cust_svc }
3911 grep { exists $packages{ $_->pkgpart } }
3912 $self->ncancelled_pkgs;
3916 # Return a list of latitude/longitude for one of the services (if any)
3917 sub service_coordinates {
3921 grep { $_->latitude && $_->longitude }
3923 map { $_->cust_svc }
3924 $self->ncancelled_pkgs;
3926 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
3931 Returns a masked version of the named field
3936 my ($self,$field) = @_;
3940 'x'x(length($self->getfield($field))-4).
3941 substr($self->getfield($field), (length($self->getfield($field))-4));
3947 =head1 CLASS METHODS
3953 Class method that returns the list of possible status strings for customers
3954 (see L<the status method|/status>). For example:
3956 @statuses = FS::cust_main->statuses();
3961 #my $self = shift; #could be class...
3965 =item cust_status_sql
3967 Returns an SQL fragment to determine the status of a cust_main record, as a
3972 sub cust_status_sql {
3974 for my $status ( FS::cust_main->statuses() ) {
3975 my $method = $status.'_sql';
3976 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
3985 Returns an SQL expression identifying prospective cust_main records (customers
3986 with no packages ever ordered)
3990 use vars qw($select_count_pkgs);
3991 $select_count_pkgs =
3992 "SELECT COUNT(*) FROM cust_pkg
3993 WHERE cust_pkg.custnum = cust_main.custnum";
3995 sub select_count_pkgs_sql {
4000 " 0 = ( $select_count_pkgs ) ";
4005 Returns an SQL expression identifying ordered cust_main records (customers with
4006 recurring packages not yet setup).
4011 FS::cust_main->none_active_sql.
4012 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
4017 Returns an SQL expression identifying active cust_main records (customers with
4018 active recurring packages).
4023 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4026 =item none_active_sql
4028 Returns an SQL expression identifying cust_main records with no active
4029 recurring packages. This includes customers of status prospect, ordered,
4030 inactive, and suspended.
4034 sub none_active_sql {
4035 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4040 Returns an SQL expression identifying inactive cust_main records (customers with
4041 no active recurring packages, but otherwise unsuspended/uncancelled).
4046 FS::cust_main->none_active_sql.
4047 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4053 Returns an SQL expression identifying suspended cust_main records.
4058 sub suspended_sql { susp_sql(@_); }
4060 FS::cust_main->none_active_sql.
4061 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4067 Returns an SQL expression identifying cancelled cust_main records.
4071 sub cancelled_sql { cancel_sql(@_); }
4074 my $recurring_sql = FS::cust_pkg->recurring_sql;
4075 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4078 0 < ( $select_count_pkgs )
4079 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
4080 AND 0 = ( $select_count_pkgs AND $recurring_sql
4081 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4084 # AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4089 =item uncancelled_sql
4091 Returns an SQL expression identifying un-cancelled cust_main records.
4095 sub uncancelled_sql { uncancel_sql(@_); }
4096 sub uncancel_sql { "
4097 ( 0 < ( $select_count_pkgs
4098 AND ( cust_pkg.cancel IS NULL
4099 OR cust_pkg.cancel = 0
4102 OR 0 = ( $select_count_pkgs )
4108 Returns an SQL fragment to retreive the balance.
4113 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4114 WHERE cust_bill.custnum = cust_main.custnum )
4115 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4116 WHERE cust_pay.custnum = cust_main.custnum )
4117 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4118 WHERE cust_credit.custnum = cust_main.custnum )
4119 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4120 WHERE cust_refund.custnum = cust_main.custnum )
4123 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4125 Returns an SQL fragment to retreive the balance for this customer, optionally
4126 considering invoices with date earlier than START_TIME, and not
4127 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4128 total_unapplied_payments).
4130 Times are specified as SQL fragments or numeric
4131 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4132 L<Date::Parse> for conversion functions. The empty string can be passed
4133 to disable that time constraint completely.
4135 Available options are:
4139 =item unapplied_date
4141 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)
4146 set to true to remove all customer comparison clauses, for totals
4151 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4156 JOIN clause (typically used with the total option)
4160 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4161 time will be ignored. Note that START_TIME and END_TIME only limit the date
4162 range for invoices and I<unapplied> payments, credits, and refunds.
4168 sub balance_date_sql {
4169 my( $class, $start, $end, %opt ) = @_;
4171 my $cutoff = $opt{'cutoff'};
4173 my $owed = FS::cust_bill->owed_sql($cutoff);
4174 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4175 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4176 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4178 my $j = $opt{'join'} || '';
4180 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4181 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4182 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4183 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4185 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4186 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4187 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4188 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4193 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4195 Returns an SQL fragment to retreive the total unapplied payments for this
4196 customer, only considering invoices with date earlier than START_TIME, and
4197 optionally not later than END_TIME.
4199 Times are specified as SQL fragments or numeric
4200 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4201 L<Date::Parse> for conversion functions. The empty string can be passed
4202 to disable that time constraint completely.
4204 Available options are:
4208 sub unapplied_payments_date_sql {
4209 my( $class, $start, $end, %opt ) = @_;
4211 my $cutoff = $opt{'cutoff'};
4213 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4215 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4216 'unapplied_date'=>1 );
4218 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4221 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4223 Helper method for balance_date_sql; name (and usage) subject to change
4224 (suggestions welcome).
4226 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4227 cust_refund, cust_credit or cust_pay).
4229 If TABLE is "cust_bill" or the unapplied_date option is true, only
4230 considers records with date earlier than START_TIME, and optionally not
4231 later than END_TIME .
4235 sub _money_table_where {
4236 my( $class, $table, $start, $end, %opt ) = @_;
4239 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4240 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4241 push @where, "$table._date <= $start" if defined($start) && length($start);
4242 push @where, "$table._date > $end" if defined($end) && length($end);
4244 push @where, @{$opt{'where'}} if $opt{'where'};
4245 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4251 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4252 use FS::cust_main::Search;
4255 FS::cust_main::Search->search(@_);
4264 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4268 use FS::cust_main::Search;
4269 sub append_fuzzyfiles {
4270 #my( $first, $last, $company ) = @_;
4272 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4274 use Fcntl qw(:flock);
4276 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4278 foreach my $field (@fuzzyfields) {
4283 open(CACHE,">>$dir/cust_main.$field")
4284 or die "can't open $dir/cust_main.$field: $!";
4285 flock(CACHE,LOCK_EX)
4286 or die "can't lock $dir/cust_main.$field: $!";
4288 print CACHE "$value\n";
4290 flock(CACHE,LOCK_UN)
4291 or die "can't unlock $dir/cust_main.$field: $!";
4306 #warn join('-',keys %$param);
4307 my $fh = $param->{filehandle};
4308 my $agentnum = $param->{agentnum};
4309 my $format = $param->{format};
4311 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4314 if ( $format eq 'simple' ) {
4315 @fields = qw( custnum agent_custid amount pkg );
4317 die "unknown format $format";
4320 eval "use Text::CSV_XS;";
4323 my $csv = new Text::CSV_XS;
4330 local $SIG{HUP} = 'IGNORE';
4331 local $SIG{INT} = 'IGNORE';
4332 local $SIG{QUIT} = 'IGNORE';
4333 local $SIG{TERM} = 'IGNORE';
4334 local $SIG{TSTP} = 'IGNORE';
4335 local $SIG{PIPE} = 'IGNORE';
4337 my $oldAutoCommit = $FS::UID::AutoCommit;
4338 local $FS::UID::AutoCommit = 0;
4341 #while ( $columns = $csv->getline($fh) ) {
4343 while ( defined($line=<$fh>) ) {
4345 $csv->parse($line) or do {
4346 $dbh->rollback if $oldAutoCommit;
4347 return "can't parse: ". $csv->error_input();
4350 my @columns = $csv->fields();
4351 #warn join('-',@columns);
4354 foreach my $field ( @fields ) {
4355 $row{$field} = shift @columns;
4358 if ( $row{custnum} && $row{agent_custid} ) {
4359 dbh->rollback if $oldAutoCommit;
4360 return "can't specify custnum with agent_custid $row{agent_custid}";
4364 if ( $row{agent_custid} && $agentnum ) {
4365 %hash = ( 'agent_custid' => $row{agent_custid},
4366 'agentnum' => $agentnum,
4370 if ( $row{custnum} ) {
4371 %hash = ( 'custnum' => $row{custnum} );
4374 unless ( scalar(keys %hash) ) {
4375 $dbh->rollback if $oldAutoCommit;
4376 return "can't find customer without custnum or agent_custid and agentnum";
4379 my $cust_main = qsearchs('cust_main', { %hash } );
4380 unless ( $cust_main ) {
4381 $dbh->rollback if $oldAutoCommit;
4382 my $custnum = $row{custnum} || $row{agent_custid};
4383 return "unknown custnum $custnum";
4386 if ( $row{'amount'} > 0 ) {
4387 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4389 $dbh->rollback if $oldAutoCommit;
4393 } elsif ( $row{'amount'} < 0 ) {
4394 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4397 $dbh->rollback if $oldAutoCommit;
4407 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4409 return "Empty file!" unless $imported;
4415 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4417 Deprecated. Use event notification and message templates
4418 (L<FS::msg_template>) instead.
4420 Sends a templated email notification to the customer (see L<Text::Template>).
4422 OPTIONS is a hash and may include
4424 I<from> - the email sender (default is invoice_from)
4426 I<to> - comma-separated scalar or arrayref of recipients
4427 (default is invoicing_list)
4429 I<subject> - The subject line of the sent email notification
4430 (default is "Notice from company_name")
4432 I<extra_fields> - a hashref of name/value pairs which will be substituted
4435 The following variables are vavailable in the template.
4437 I<$first> - the customer first name
4438 I<$last> - the customer last name
4439 I<$company> - the customer company
4440 I<$payby> - a description of the method of payment for the customer
4441 # would be nice to use FS::payby::shortname
4442 I<$payinfo> - the account information used to collect for this customer
4443 I<$expdate> - the expiration of the customer payment in seconds from epoch
4448 my ($self, $template, %options) = @_;
4450 return unless $conf->exists($template);
4452 my $from = $conf->config('invoice_from', $self->agentnum)
4453 if $conf->exists('invoice_from', $self->agentnum);
4454 $from = $options{from} if exists($options{from});
4456 my $to = join(',', $self->invoicing_list_emailonly);
4457 $to = $options{to} if exists($options{to});
4459 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4460 if $conf->exists('company_name', $self->agentnum);
4461 $subject = $options{subject} if exists($options{subject});
4463 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4464 SOURCE => [ map "$_\n",
4465 $conf->config($template)]
4467 or die "can't create new Text::Template object: Text::Template::ERROR";
4468 $notify_template->compile()
4469 or die "can't compile template: Text::Template::ERROR";
4471 $FS::notify_template::_template::company_name =
4472 $conf->config('company_name', $self->agentnum);
4473 $FS::notify_template::_template::company_address =
4474 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4476 my $paydate = $self->paydate || '2037-12-31';
4477 $FS::notify_template::_template::first = $self->first;
4478 $FS::notify_template::_template::last = $self->last;
4479 $FS::notify_template::_template::company = $self->company;
4480 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4481 my $payby = $self->payby;
4482 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4483 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4485 #credit cards expire at the end of the month/year of their exp date
4486 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4487 $FS::notify_template::_template::payby = 'credit card';
4488 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4489 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4491 }elsif ($payby eq 'COMP') {
4492 $FS::notify_template::_template::payby = 'complimentary account';
4494 $FS::notify_template::_template::payby = 'current method';
4496 $FS::notify_template::_template::expdate = $expire_time;
4498 for (keys %{$options{extra_fields}}){
4500 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4503 send_email(from => $from,
4505 subject => $subject,
4506 body => $notify_template->fill_in( PACKAGE =>
4507 'FS::notify_template::_template' ),
4512 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4514 Generates a templated notification to the customer (see L<Text::Template>).
4516 OPTIONS is a hash and may include
4518 I<extra_fields> - a hashref of name/value pairs which will be substituted
4519 into the template. These values may override values mentioned below
4520 and those from the customer record.
4522 The following variables are available in the template instead of or in addition
4523 to the fields of the customer record.
4525 I<$payby> - a description of the method of payment for the customer
4526 # would be nice to use FS::payby::shortname
4527 I<$payinfo> - the masked account information used to collect for this customer
4528 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4529 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4533 # a lot like cust_bill::print_latex
4534 sub generate_letter {
4535 my ($self, $template, %options) = @_;
4537 return unless $conf->exists($template);
4539 my $letter_template = new Text::Template
4541 SOURCE => [ map "$_\n", $conf->config($template)],
4542 DELIMITERS => [ '[@--', '--@]' ],
4544 or die "can't create new Text::Template object: Text::Template::ERROR";
4546 $letter_template->compile()
4547 or die "can't compile template: Text::Template::ERROR";
4549 my %letter_data = map { $_ => $self->$_ } $self->fields;
4550 $letter_data{payinfo} = $self->mask_payinfo;
4552 #my $paydate = $self->paydate || '2037-12-31';
4553 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4555 my $payby = $self->payby;
4556 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4557 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4559 #credit cards expire at the end of the month/year of their exp date
4560 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4561 $letter_data{payby} = 'credit card';
4562 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4563 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4565 }elsif ($payby eq 'COMP') {
4566 $letter_data{payby} = 'complimentary account';
4568 $letter_data{payby} = 'current method';
4570 $letter_data{expdate} = $expire_time;
4572 for (keys %{$options{extra_fields}}){
4573 $letter_data{$_} = $options{extra_fields}->{$_};
4576 unless(exists($letter_data{returnaddress})){
4577 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4578 $self->agent_template)
4580 if ( length($retadd) ) {
4581 $letter_data{returnaddress} = $retadd;
4582 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4583 $letter_data{returnaddress} =
4584 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4588 ( $conf->config('company_name', $self->agentnum),
4589 $conf->config('company_address', $self->agentnum),
4593 $letter_data{returnaddress} = '~';
4597 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4599 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4601 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4603 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4607 ) or die "can't open temp file: $!\n";
4608 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4609 or die "can't write temp file: $!\n";
4611 $letter_data{'logo_file'} = $lh->filename;
4613 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4617 ) or die "can't open temp file: $!\n";
4619 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4621 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4622 return ($1, $letter_data{'logo_file'});
4626 =item print_ps TEMPLATE
4628 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4634 my($file, $lfile) = $self->generate_letter(@_);
4635 my $ps = FS::Misc::generate_ps($file);
4636 unlink($file.'.tex');
4642 =item print TEMPLATE
4644 Prints the filled in template.
4646 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4650 sub queueable_print {
4653 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4654 or die "invalid customer number: " . $opt{custvnum};
4656 my $error = $self->print( $opt{template} );
4657 die $error if $error;
4661 my ($self, $template) = (shift, shift);
4662 do_print [ $self->print_ps($template) ];
4665 #these three subs should just go away once agent stuff is all config overrides
4667 sub agent_template {
4669 $self->_agent_plandata('agent_templatename');
4672 sub agent_invoice_from {
4674 $self->_agent_plandata('agent_invoice_from');
4677 sub _agent_plandata {
4678 my( $self, $option ) = @_;
4680 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4681 #agent-specific Conf
4683 use FS::part_event::Condition;
4685 my $agentnum = $self->agentnum;
4687 my $regexp = regexp_sql();
4689 my $part_event_option =
4691 'select' => 'part_event_option.*',
4692 'table' => 'part_event_option',
4694 LEFT JOIN part_event USING ( eventpart )
4695 LEFT JOIN part_event_option AS peo_agentnum
4696 ON ( part_event.eventpart = peo_agentnum.eventpart
4697 AND peo_agentnum.optionname = 'agentnum'
4698 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4700 LEFT JOIN part_event_condition
4701 ON ( part_event.eventpart = part_event_condition.eventpart
4702 AND part_event_condition.conditionname = 'cust_bill_age'
4704 LEFT JOIN part_event_condition_option
4705 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4706 AND part_event_condition_option.optionname = 'age'
4709 #'hashref' => { 'optionname' => $option },
4710 #'hashref' => { 'part_event_option.optionname' => $option },
4712 " WHERE part_event_option.optionname = ". dbh->quote($option).
4713 " AND action = 'cust_bill_send_agent' ".
4714 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4715 " AND peo_agentnum.optionname = 'agentnum' ".
4716 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4718 CASE WHEN part_event_condition_option.optionname IS NULL
4720 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4722 , part_event.weight".
4726 unless ( $part_event_option ) {
4727 return $self->agent->invoice_template || ''
4728 if $option eq 'agent_templatename';
4732 $part_event_option->optionvalue;
4736 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4738 Subroutine (not a method), designed to be called from the queue.
4740 Takes a list of options and values.
4742 Pulls up the customer record via the custnum option and calls bill_and_collect.
4747 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4749 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4750 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4752 $cust_main->bill_and_collect( %args );
4755 sub process_bill_and_collect {
4757 my $param = thaw(decode_base64(shift));
4758 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4759 or die "custnum '$param->{custnum}' not found!\n";
4760 $param->{'job'} = $job;
4761 $param->{'fatal'} = 1; # runs from job queue, will be caught
4762 $param->{'retry'} = 1;
4764 $cust_main->bill_and_collect( %$param );
4767 sub _upgrade_data { #class method
4768 my ($class, %opts) = @_;
4771 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4772 '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',
4774 # fix yyyy-m-dd formatted paydates
4775 if ( driver_name =~ /^mysql$/i ) {
4777 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4779 else { # the SQL standard
4781 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4784 foreach my $sql ( @statements ) {
4785 my $sth = dbh->prepare($sql) or die dbh->errstr;
4786 $sth->execute or die $sth->errstr;
4789 local($ignore_expired_card) = 1;
4790 local($ignore_illegal_zip) = 1;
4791 local($ignore_banned_card) = 1;
4792 local($skip_fuzzyfiles) = 1;
4793 $class->_upgrade_otaker(%opts);
4803 The delete method should possibly take an FS::cust_main object reference
4804 instead of a scalar customer number.
4806 Bill and collect options should probably be passed as references instead of a
4809 There should probably be a configuration file with a list of allowed credit
4812 No multiple currency support (probably a larger project than just this module).
4814 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4816 Birthdates rely on negative epoch values.
4818 The payby for card/check batches is broken. With mixed batching, bad
4821 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4825 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4826 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4827 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.