4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles );
6 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 eval "use Time::Local;";
12 die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
13 if $] < 5.006 && !defined($Time::Local::VERSION);
14 #eval "use Time::Local qw(timelocal timelocal_nocheck);";
15 eval "use Time::Local qw(timelocal_nocheck);";
17 use Digest::MD5 qw(md5_base64);
20 use String::Approx qw(amatch);
21 use Business::CreditCard 0.28;
22 use FS::UID qw( getotaker dbh );
23 use FS::Record qw( qsearchs qsearch dbdef );
24 use FS::Misc qw( send_email );
25 use FS::Msgcat qw(gettext);
29 use FS::cust_bill_pkg;
31 use FS::cust_pay_void;
34 use FS::part_referral;
35 use FS::cust_main_county;
37 use FS::cust_main_invoice;
38 use FS::cust_credit_bill;
39 use FS::cust_bill_pay;
40 use FS::prepay_credit;
43 use FS::part_bill_event;
44 use FS::cust_bill_event;
45 use FS::cust_tax_exempt;
47 use FS::payment_gateway;
48 use FS::agent_payment_gateway;
51 @ISA = qw( FS::Record );
53 @EXPORT_OK = qw( smart_search );
55 $realtime_bop_decline_quiet = 0;
58 $me = '[FS::cust_main]';
63 @encrypted_fields = ('payinfo', 'paycvv');
65 #ask FS::UID to run this stuff for us later
66 #$FS::UID::callback{'FS::cust_main'} = sub {
67 install_callback FS::UID sub {
69 #yes, need it for stuff below (prolly should be cached)
74 my ( $hashref, $cache ) = @_;
75 if ( exists $hashref->{'pkgnum'} ) {
76 # #@{ $self->{'_pkgnum'} } = ();
77 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
78 $self->{'_pkgnum'} = $subcache;
79 #push @{ $self->{'_pkgnum'} },
80 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
86 FS::cust_main - Object methods for cust_main records
92 $record = new FS::cust_main \%hash;
93 $record = new FS::cust_main { 'column' => 'value' };
95 $error = $record->insert;
97 $error = $new_record->replace($old_record);
99 $error = $record->delete;
101 $error = $record->check;
103 @cust_pkg = $record->all_pkgs;
105 @cust_pkg = $record->ncancelled_pkgs;
107 @cust_pkg = $record->suspended_pkgs;
109 $error = $record->bill;
110 $error = $record->bill %options;
111 $error = $record->bill 'time' => $time;
113 $error = $record->collect;
114 $error = $record->collect %options;
115 $error = $record->collect 'invoice_time' => $time,
116 'batch_card' => 'yes',
117 'report_badcard' => 'yes',
122 An FS::cust_main object represents a customer. FS::cust_main inherits from
123 FS::Record. The following fields are currently supported:
127 =item custnum - primary key (assigned automatically for new customers)
129 =item agentnum - agent (see L<FS::agent>)
131 =item refnum - Advertising source (see L<FS::part_referral>)
137 =item ss - social security number (optional)
139 =item company - (optional)
143 =item address2 - (optional)
147 =item county - (optional, see L<FS::cust_main_county>)
149 =item state - (see L<FS::cust_main_county>)
153 =item country - (see L<FS::cust_main_county>)
155 =item daytime - phone (optional)
157 =item night - phone (optional)
159 =item fax - phone (optional)
161 =item ship_first - name
163 =item ship_last - name
165 =item ship_company - (optional)
169 =item ship_address2 - (optional)
173 =item ship_county - (optional, see L<FS::cust_main_county>)
175 =item ship_state - (see L<FS::cust_main_county>)
179 =item ship_country - (see L<FS::cust_main_county>)
181 =item ship_daytime - phone (optional)
183 =item ship_night - phone (optional)
185 =item ship_fax - phone (optional)
189 I<CARD> (credit card - automatic), I<DCRD> (credit card - on-demand), I<CHEK> (electronic check - automatic), I<DCHK> (electronic check - on-demand), I<LECB> (Phone bill billing), I<BILL> (billing), I<COMP> (free), or I<PREPAY> (special billing type: applies a credit - see L<FS::prepay_credit> and sets billing type to I<BILL>)
193 Card Number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
198 my($self,$payinfo) = @_;
199 if ( defined($payinfo) ) {
200 $self->paymask($payinfo);
201 $self->setfield('payinfo', $payinfo); # This is okay since we are the 'setter'
203 $payinfo = $self->getfield('payinfo'); # This is okay since we are the 'getter'
211 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
215 =item paymask - Masked payment type
221 Mask all but the last four characters.
225 Mask all but last 2 of account number and bank routing number.
229 Do nothing, return the unmasked string.
238 # If it doesn't exist then generate it
239 my $paymask=$self->getfield('paymask');
240 if (!defined($value) && (!defined($paymask) || $paymask eq '')) {
241 $value = $self->payinfo;
244 if ( defined($value) && !$self->is_encrypted($value)) {
245 my $payinfo = $value;
246 my $payby = $self->payby;
247 if ($payby eq 'CARD' || $payby eq 'DCARD') { # Credit Cards (Show last four)
248 $paymask = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
249 } elsif ($payby eq 'CHEK' ||
250 $payby eq 'DCHK' ) { # Checks (Show last 2 @ bank)
251 my( $account, $aba ) = split('@', $payinfo );
252 $paymask = 'x'x(length($account)-2). substr($account,(length($account)-2))."@".$aba;
253 } else { # Tie up loose ends
256 $self->setfield('paymask', $paymask); # This is okay since we are the 'setter'
257 } elsif (defined($value) && $self->is_encrypted($value)) {
263 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
265 =item paystart_month - start date month (maestro/solo cards only)
267 =item paystart_year - start date year (maestro/solo cards only)
269 =item payissue - issue number (maestro/solo cards only)
271 =item payname - name on card or billing name
273 =item payip - IP address from which payment information was received
275 =item tax - tax exempt, empty or `Y'
277 =item otaker - order taker (assigned automatically, see L<FS::UID>)
279 =item comments - comments (optional)
281 =item referral_custnum - referring customer number
291 Creates a new customer. To add the customer to the database, see L<"insert">.
293 Note that this stores the hash reference, not a distinct copy of the hash it
294 points to. You can ask the object for a copy with the I<hash> method.
298 sub table { 'cust_main'; }
300 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
302 Adds this customer to the database. If there is an error, returns the error,
303 otherwise returns false.
305 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
306 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
307 are inserted atomicly, or the transaction is rolled back. Passing an empty
308 hash reference is equivalent to not supplying this parameter. There should be
309 a better explanation of this, but until then, here's an example:
312 tie %hash, 'Tie::RefHash'; #this part is important
314 $cust_pkg => [ $svc_acct ],
317 $cust_main->insert( \%hash );
319 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
320 be set as the invoicing list (see L<"invoicing_list">). Errors return as
321 expected and rollback the entire transaction; it is not necessary to call
322 check_invoicing_list first. The invoicing_list is set after the records in the
323 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
324 invoicing_list destination to the newly-created svc_acct. Here's an example:
326 $cust_main->insert( {}, [ $email, 'POST' ] );
328 Currently available options are: I<depend_jobnum> and I<noexport>.
330 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
331 on the supplied jobnum (they will not run until the specific job completes).
332 This can be used to defer provisioning until some action completes (such
333 as running the customer's credit card sucessfully).
335 The I<noexport> option is deprecated. If I<noexport> is set true, no
336 provisioning jobs (exports) are scheduled. (You can schedule them later with
337 the B<reexport> method.)
343 my $cust_pkgs = @_ ? shift : {};
344 my $invoicing_list = @_ ? shift : '';
346 warn "FS::cust_main::insert called with options ".
347 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
350 local $SIG{HUP} = 'IGNORE';
351 local $SIG{INT} = 'IGNORE';
352 local $SIG{QUIT} = 'IGNORE';
353 local $SIG{TERM} = 'IGNORE';
354 local $SIG{TSTP} = 'IGNORE';
355 local $SIG{PIPE} = 'IGNORE';
357 my $oldAutoCommit = $FS::UID::AutoCommit;
358 local $FS::UID::AutoCommit = 0;
361 my $prepay_identifier = '';
362 my( $amount, $seconds ) = ( 0, 0 );
363 if ( $self->payby eq 'PREPAY' ) {
365 $self->payby('BILL');
366 $prepay_identifier = $self->payinfo;
369 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
371 $dbh->rollback if $oldAutoCommit;
372 #return "error applying prepaid card (transaction rolled back): $error";
378 my $error = $self->SUPER::insert;
380 $dbh->rollback if $oldAutoCommit;
381 #return "inserting cust_main record (transaction rolled back): $error";
386 if ( $invoicing_list ) {
387 $error = $self->check_invoicing_list( $invoicing_list );
389 $dbh->rollback if $oldAutoCommit;
390 return "checking invoicing_list (transaction rolled back): $error";
392 $self->invoicing_list( $invoicing_list );
396 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
398 $dbh->rollback if $oldAutoCommit;
403 $dbh->rollback if $oldAutoCommit;
404 return "No svc_acct record to apply pre-paid time";
408 $error = $self->insert_cust_pay_prepay($amount, $prepay_identifier);
410 $dbh->rollback if $oldAutoCommit;
411 return "inserting prepayment (transaction rolled back): $error";
415 unless ( $import || $skip_fuzzyfiles ) {
416 $error = $self->queue_fuzzyfiles_update;
418 $dbh->rollback if $oldAutoCommit;
419 return "updating fuzzy search cache: $error";
423 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
428 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
430 Like the insert method on an existing record, this method orders a package
431 and included services atomicaly. Pass a Tie::RefHash data structure to this
432 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
433 be a better explanation of this, but until then, here's an example:
436 tie %hash, 'Tie::RefHash'; #this part is important
438 $cust_pkg => [ $svc_acct ],
441 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
443 Services can be new, in which case they are inserted, or existing unaudited
444 services, in which case they are linked to the newly-created package.
446 Currently available options are: I<depend_jobnum> and I<noexport>.
448 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
449 on the supplied jobnum (they will not run until the specific job completes).
450 This can be used to defer provisioning until some action completes (such
451 as running the customer's credit card sucessfully).
453 The I<noexport> option is deprecated. If I<noexport> is set true, no
454 provisioning jobs (exports) are scheduled. (You can schedule them later with
455 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
456 on the cust_main object is not recommended, as existing services will also be
463 my $cust_pkgs = shift;
466 my %svc_options = ();
467 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
468 if exists $options{'depend_jobnum'};
469 warn "FS::cust_main::order_pkgs called with options ".
470 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
473 local $SIG{HUP} = 'IGNORE';
474 local $SIG{INT} = 'IGNORE';
475 local $SIG{QUIT} = 'IGNORE';
476 local $SIG{TERM} = 'IGNORE';
477 local $SIG{TSTP} = 'IGNORE';
478 local $SIG{PIPE} = 'IGNORE';
480 my $oldAutoCommit = $FS::UID::AutoCommit;
481 local $FS::UID::AutoCommit = 0;
484 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
486 foreach my $cust_pkg ( keys %$cust_pkgs ) {
487 $cust_pkg->custnum( $self->custnum );
488 my $error = $cust_pkg->insert;
490 $dbh->rollback if $oldAutoCommit;
491 return "inserting cust_pkg (transaction rolled back): $error";
493 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
494 if ( $svc_something->svcnum ) {
495 my $old_cust_svc = $svc_something->cust_svc;
496 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
497 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
498 $error = $new_cust_svc->replace($old_cust_svc);
500 $svc_something->pkgnum( $cust_pkg->pkgnum );
501 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
502 $svc_something->seconds( $svc_something->seconds + $$seconds );
505 $error = $svc_something->insert(%svc_options);
508 $dbh->rollback if $oldAutoCommit;
509 #return "inserting svc_ (transaction rolled back): $error";
515 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
519 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF ]
521 Recharges this (existing) customer with the specified prepaid card (see
522 L<FS::prepay_credit>), specified either by I<identifier> or as an
523 FS::prepay_credit object. If there is an error, returns the error, otherwise
526 Optionally, two scalar references can be passed as well. They will have their
527 values filled in with the amount and number of seconds applied by this prepaid
532 sub recharge_prepay {
533 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
535 local $SIG{HUP} = 'IGNORE';
536 local $SIG{INT} = 'IGNORE';
537 local $SIG{QUIT} = 'IGNORE';
538 local $SIG{TERM} = 'IGNORE';
539 local $SIG{TSTP} = 'IGNORE';
540 local $SIG{PIPE} = 'IGNORE';
542 my $oldAutoCommit = $FS::UID::AutoCommit;
543 local $FS::UID::AutoCommit = 0;
546 my( $amount, $seconds ) = ( 0, 0 );
548 my $error = $self->get_prepay($prepay_credit, \$amount, \$seconds)
549 || $self->increment_seconds($seconds)
550 || $self->insert_cust_pay_prepay( $amount,
552 ? $prepay_credit->identifier
557 $dbh->rollback if $oldAutoCommit;
561 if ( defined($amountref) ) { $$amountref = $amount; }
562 if ( defined($secondsref) ) { $$secondsref = $seconds; }
564 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
569 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
571 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
572 specified either by I<identifier> or as an FS::prepay_credit object.
574 References to I<amount> and I<seconds> scalars should be passed as arguments
575 and will be incremented by the values of the prepaid card.
577 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
578 check or set this customer's I<agentnum>.
580 If there is an error, returns the error, otherwise returns false.
586 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
588 local $SIG{HUP} = 'IGNORE';
589 local $SIG{INT} = 'IGNORE';
590 local $SIG{QUIT} = 'IGNORE';
591 local $SIG{TERM} = 'IGNORE';
592 local $SIG{TSTP} = 'IGNORE';
593 local $SIG{PIPE} = 'IGNORE';
595 my $oldAutoCommit = $FS::UID::AutoCommit;
596 local $FS::UID::AutoCommit = 0;
599 unless ( ref($prepay_credit) ) {
601 my $identifier = $prepay_credit;
603 $prepay_credit = qsearchs(
605 { 'identifier' => $prepay_credit },
610 unless ( $prepay_credit ) {
611 $dbh->rollback if $oldAutoCommit;
612 return "Invalid prepaid card: ". $identifier;
617 if ( $prepay_credit->agentnum ) {
618 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
619 $dbh->rollback if $oldAutoCommit;
620 return "prepaid card not valid for agent ". $self->agentnum;
622 $self->agentnum($prepay_credit->agentnum);
625 my $error = $prepay_credit->delete;
627 $dbh->rollback if $oldAutoCommit;
628 return "removing prepay_credit (transaction rolled back): $error";
631 $$amountref += $prepay_credit->amount;
632 $$secondsref += $prepay_credit->seconds;
634 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
639 =item increment_seconds SECONDS
641 Updates this customer's single or primary account (see L<FS::svc_acct>) by
642 the specified number of seconds. If there is an error, returns the error,
643 otherwise returns false.
647 sub increment_seconds {
648 my( $self, $seconds ) = @_;
649 warn "$me increment_seconds called: $seconds seconds\n"
652 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
653 $self->ncancelled_pkgs;
656 return 'No packages with primary or single services found'.
657 ' to apply pre-paid time';
658 } elsif ( scalar(@cust_pkg) > 1 ) {
659 #maybe have a way to specify the package/account?
660 return 'Multiple packages found to apply pre-paid time';
663 my $cust_pkg = $cust_pkg[0];
664 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
668 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
671 return 'No account found to apply pre-paid time';
672 } elsif ( scalar(@cust_svc) > 1 ) {
673 return 'Multiple accounts found to apply pre-paid time';
676 my $svc_acct = $cust_svc[0]->svc_x;
677 warn " found service svcnum ". $svc_acct->pkgnum.
678 ' ('. $svc_acct->email. ")\n"
681 $svc_acct->increment_seconds($seconds);
685 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
687 Inserts a prepayment in the specified amount for this customer. An optional
688 second argument can specify the prepayment identifier for tracking purposes.
689 If there is an error, returns the error, otherwise returns false.
693 sub insert_cust_pay_prepay {
694 my( $self, $amount ) = splice(@_, 0, 2);
695 my $payinfo = scalar(@_) ? shift : '';
697 my $cust_pay = new FS::cust_pay {
698 'custnum' => $self->custnum,
699 'paid' => sprintf('%.2f', $amount),
700 #'_date' => #date the prepaid card was purchased???
702 'payinfo' => $payinfo,
710 This method is deprecated. See the I<depend_jobnum> option to the insert and
711 order_pkgs methods for a better way to defer provisioning.
713 Re-schedules all exports by calling the B<reexport> method of all associated
714 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
715 otherwise returns false.
722 carp "warning: FS::cust_main::reexport is deprectated; ".
723 "use the depend_jobnum option to insert or order_pkgs to delay export";
725 local $SIG{HUP} = 'IGNORE';
726 local $SIG{INT} = 'IGNORE';
727 local $SIG{QUIT} = 'IGNORE';
728 local $SIG{TERM} = 'IGNORE';
729 local $SIG{TSTP} = 'IGNORE';
730 local $SIG{PIPE} = 'IGNORE';
732 my $oldAutoCommit = $FS::UID::AutoCommit;
733 local $FS::UID::AutoCommit = 0;
736 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
737 my $error = $cust_pkg->reexport;
739 $dbh->rollback if $oldAutoCommit;
744 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
749 =item delete NEW_CUSTNUM
751 This deletes the customer. If there is an error, returns the error, otherwise
754 This will completely remove all traces of the customer record. This is not
755 what you want when a customer cancels service; for that, cancel all of the
756 customer's packages (see L</cancel>).
758 If the customer has any uncancelled packages, you need to pass a new (valid)
759 customer number for those packages to be transferred to. Cancelled packages
760 will be deleted. Did I mention that this is NOT what you want when a customer
761 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
763 You can't delete a customer with invoices (see L<FS::cust_bill>),
764 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
765 refunds (see L<FS::cust_refund>).
772 local $SIG{HUP} = 'IGNORE';
773 local $SIG{INT} = 'IGNORE';
774 local $SIG{QUIT} = 'IGNORE';
775 local $SIG{TERM} = 'IGNORE';
776 local $SIG{TSTP} = 'IGNORE';
777 local $SIG{PIPE} = 'IGNORE';
779 my $oldAutoCommit = $FS::UID::AutoCommit;
780 local $FS::UID::AutoCommit = 0;
783 if ( $self->cust_bill ) {
784 $dbh->rollback if $oldAutoCommit;
785 return "Can't delete a customer with invoices";
787 if ( $self->cust_credit ) {
788 $dbh->rollback if $oldAutoCommit;
789 return "Can't delete a customer with credits";
791 if ( $self->cust_pay ) {
792 $dbh->rollback if $oldAutoCommit;
793 return "Can't delete a customer with payments";
795 if ( $self->cust_refund ) {
796 $dbh->rollback if $oldAutoCommit;
797 return "Can't delete a customer with refunds";
800 my @cust_pkg = $self->ncancelled_pkgs;
802 my $new_custnum = shift;
803 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
804 $dbh->rollback if $oldAutoCommit;
805 return "Invalid new customer number: $new_custnum";
807 foreach my $cust_pkg ( @cust_pkg ) {
808 my %hash = $cust_pkg->hash;
809 $hash{'custnum'} = $new_custnum;
810 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
811 my $error = $new_cust_pkg->replace($cust_pkg);
813 $dbh->rollback if $oldAutoCommit;
818 my @cancelled_cust_pkg = $self->all_pkgs;
819 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
820 my $error = $cust_pkg->delete;
822 $dbh->rollback if $oldAutoCommit;
827 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
828 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
830 my $error = $cust_main_invoice->delete;
832 $dbh->rollback if $oldAutoCommit;
837 my $error = $self->SUPER::delete;
839 $dbh->rollback if $oldAutoCommit;
843 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
848 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
850 Replaces the OLD_RECORD with this one in the database. If there is an error,
851 returns the error, otherwise returns false.
853 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
854 be set as the invoicing list (see L<"invoicing_list">). Errors return as
855 expected and rollback the entire transaction; it is not necessary to call
856 check_invoicing_list first. Here's an example:
858 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
867 local $SIG{HUP} = 'IGNORE';
868 local $SIG{INT} = 'IGNORE';
869 local $SIG{QUIT} = 'IGNORE';
870 local $SIG{TERM} = 'IGNORE';
871 local $SIG{TSTP} = 'IGNORE';
872 local $SIG{PIPE} = 'IGNORE';
874 # If the mask is blank then try to set it - if we can...
875 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
876 $self->paymask($self->payinfo);
879 # We absolutely have to have an old vs. new record to make this work.
880 if (!defined($old)) {
881 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
884 if ( $self->payby eq 'COMP' && $self->payby ne $old->payby
885 && $conf->config('users-allow_comp') ) {
886 return "You are not permitted to create complimentary accounts."
887 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
890 my $oldAutoCommit = $FS::UID::AutoCommit;
891 local $FS::UID::AutoCommit = 0;
894 my $error = $self->SUPER::replace($old);
897 $dbh->rollback if $oldAutoCommit;
901 if ( @param ) { # INVOICING_LIST_ARYREF
902 my $invoicing_list = shift @param;
903 $error = $self->check_invoicing_list( $invoicing_list );
905 $dbh->rollback if $oldAutoCommit;
908 $self->invoicing_list( $invoicing_list );
911 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
912 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
913 # card/check/lec info has changed, want to retry realtime_ invoice events
914 my $error = $self->retry_realtime;
916 $dbh->rollback if $oldAutoCommit;
921 unless ( $import || $skip_fuzzyfiles ) {
922 $error = $self->queue_fuzzyfiles_update;
924 $dbh->rollback if $oldAutoCommit;
925 return "updating fuzzy search cache: $error";
929 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
934 =item queue_fuzzyfiles_update
936 Used by insert & replace to update the fuzzy search cache
940 sub queue_fuzzyfiles_update {
943 local $SIG{HUP} = 'IGNORE';
944 local $SIG{INT} = 'IGNORE';
945 local $SIG{QUIT} = 'IGNORE';
946 local $SIG{TERM} = 'IGNORE';
947 local $SIG{TSTP} = 'IGNORE';
948 local $SIG{PIPE} = 'IGNORE';
950 my $oldAutoCommit = $FS::UID::AutoCommit;
951 local $FS::UID::AutoCommit = 0;
954 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
955 my $error = $queue->insert($self->getfield('last'), $self->company);
957 $dbh->rollback if $oldAutoCommit;
958 return "queueing job (transaction rolled back): $error";
961 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
962 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
963 $error = $queue->insert($self->getfield('ship_last'), $self->ship_company);
965 $dbh->rollback if $oldAutoCommit;
966 return "queueing job (transaction rolled back): $error";
970 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
977 Checks all fields to make sure this is a valid customer record. If there is
978 an error, returns the error, otherwise returns false. Called by the insert
986 #warn "BEFORE: \n". $self->_dump;
989 $self->ut_numbern('custnum')
990 || $self->ut_number('agentnum')
991 || $self->ut_number('refnum')
992 || $self->ut_name('last')
993 || $self->ut_name('first')
994 || $self->ut_textn('company')
995 || $self->ut_text('address1')
996 || $self->ut_textn('address2')
997 || $self->ut_text('city')
998 || $self->ut_textn('county')
999 || $self->ut_textn('state')
1000 || $self->ut_country('country')
1001 || $self->ut_anything('comments')
1002 || $self->ut_numbern('referral_custnum')
1004 #barf. need message catalogs. i18n. etc.
1005 $error .= "Please select an advertising source."
1006 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1007 return $error if $error;
1009 return "Unknown agent"
1010 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1012 return "Unknown refnum"
1013 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1015 return "Unknown referring custnum: ". $self->referral_custnum
1016 unless ! $self->referral_custnum
1017 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1019 if ( $self->ss eq '' ) {
1024 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1025 or return "Illegal social security number: ". $self->ss;
1026 $self->ss("$1-$2-$3");
1030 # bad idea to disable, causes billing to fail because of no tax rates later
1031 # unless ( $import ) {
1032 unless ( qsearch('cust_main_county', {
1033 'country' => $self->country,
1036 return "Unknown state/county/country: ".
1037 $self->state. "/". $self->county. "/". $self->country
1038 unless qsearc('cust_main_county',{
1039 'state' => $self->state,
1040 'county' => $self->county,
1041 'country' => $self->country,
1047 $self->ut_phonen('daytime', $self->country)
1048 || $self->ut_phonen('night', $self->country)
1049 || $self->ut_phonen('fax', $self->country)
1050 || $self->ut_zip('zip', $self->country)
1052 return $error if $error;
1055 last first company address1 address2 city county state zip
1056 country daytime night fax
1059 if ( defined $self->dbdef_table->column('ship_last') ) {
1060 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1062 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1066 $self->ut_name('ship_last')
1067 || $self->ut_name('ship_first')
1068 || $self->ut_textn('ship_company')
1069 || $self->ut_text('ship_address1')
1070 || $self->ut_textn('ship_address2')
1071 || $self->ut_text('ship_city')
1072 || $self->ut_textn('ship_county')
1073 || $self->ut_textn('ship_state')
1074 || $self->ut_country('ship_country')
1076 return $error if $error;
1078 #false laziness with above
1079 unless ( qsearchs('cust_main_county', {
1080 'country' => $self->ship_country,
1083 return "Unknown ship_state/ship_county/ship_country: ".
1084 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1085 unless qsearch('cust_main_county',{
1086 'state' => $self->ship_state,
1087 'county' => $self->ship_county,
1088 'country' => $self->ship_country,
1094 $self->ut_phonen('ship_daytime', $self->ship_country)
1095 || $self->ut_phonen('ship_night', $self->ship_country)
1096 || $self->ut_phonen('ship_fax', $self->ship_country)
1097 || $self->ut_zip('ship_zip', $self->ship_country)
1099 return $error if $error;
1101 } else { # ship_ info eq billing info, so don't store dup info in database
1102 $self->setfield("ship_$_", '')
1103 foreach qw( last first company address1 address2 city county state zip
1104 country daytime night fax );
1108 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY)$/
1109 or return "Illegal payby: ". $self->payby;
1111 $error = $self->ut_numbern('paystart_month')
1112 || $self->ut_numbern('paystart_year')
1113 || $self->ut_numbern('payissue')
1115 return $error if $error;
1117 if ( $self->payip eq '' ) {
1120 $error = $self->ut_ip('payip');
1121 return $error if $error;
1124 # If it is encrypted and the private key is not availaible then we can't
1125 # check the credit card.
1127 my $check_payinfo = 1;
1129 if ($self->is_encrypted($self->payinfo)) {
1135 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1137 my $payinfo = $self->payinfo;
1138 $payinfo =~ s/\D//g;
1139 $payinfo =~ /^(\d{13,16})$/
1140 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1142 $self->payinfo($payinfo);
1144 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1146 return gettext('unknown_card_type')
1147 if cardtype($self->payinfo) eq "Unknown";
1149 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1150 return "Banned credit card" if $ban;
1152 if ( defined $self->dbdef_table->column('paycvv') ) {
1153 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1154 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1155 $self->paycvv =~ /^(\d{4})$/
1156 or return "CVV2 (CID) for American Express cards is four digits.";
1159 $self->paycvv =~ /^(\d{3})$/
1160 or return "CVV2 (CVC2/CID) is three digits.";
1168 my $cardtype = cardtype($payinfo);
1169 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1171 return "Start date or issue number is required for $cardtype cards"
1172 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1174 return "Start month must be between 1 and 12"
1175 if $self->paystart_month
1176 and $self->paystart_month < 1 || $self->paystart_month > 12;
1178 return "Start year must be 1990 or later"
1179 if $self->paystart_year
1180 and $self->paystart_year < 1990;
1182 return "Issue number must be beween 1 and 99"
1184 and $self->payissue < 1 || $self->payissue > 99;
1187 $self->paystart_month('');
1188 $self->paystart_year('');
1189 $self->payissue('');
1192 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1194 my $payinfo = $self->payinfo;
1195 $payinfo =~ s/[^\d\@]//g;
1196 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1197 $payinfo = "$1\@$2";
1198 $self->payinfo($payinfo);
1199 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1201 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1202 return "Banned ACH account" if $ban;
1204 } elsif ( $self->payby eq 'LECB' ) {
1206 my $payinfo = $self->payinfo;
1207 $payinfo =~ s/\D//g;
1208 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1210 $self->payinfo($payinfo);
1211 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1213 } elsif ( $self->payby eq 'BILL' ) {
1215 $error = $self->ut_textn('payinfo');
1216 return "Illegal P.O. number: ". $self->payinfo if $error;
1217 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1219 } elsif ( $self->payby eq 'COMP' ) {
1221 if ( !$self->custnum && $conf->config('users-allow_comp') ) {
1222 return "You are not permitted to create complimentary accounts."
1223 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
1226 $error = $self->ut_textn('payinfo');
1227 return "Illegal comp account issuer: ". $self->payinfo if $error;
1228 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1230 } elsif ( $self->payby eq 'PREPAY' ) {
1232 my $payinfo = $self->payinfo;
1233 $payinfo =~ s/\W//g; #anything else would just confuse things
1234 $self->payinfo($payinfo);
1235 $error = $self->ut_alpha('payinfo');
1236 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1237 return "Unknown prepayment identifier"
1238 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1239 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1243 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1244 return "Expriation date required"
1245 unless $self->payby =~ /^(BILL|PREPAY|CHEK|LECB)$/;
1249 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1250 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1251 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1252 ( $m, $y ) = ( $3, "20$2" );
1254 return "Illegal expiration date: ". $self->paydate;
1256 $self->paydate("$y-$m-01");
1257 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1258 return gettext('expired_card')
1259 if !$import && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1262 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1263 ( ! $conf->exists('require_cardname')
1264 || $self->payby !~ /^(CARD|DCRD)$/ )
1266 $self->payname( $self->first. " ". $self->getfield('last') );
1268 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1269 or return gettext('illegal_name'). " payname: ". $self->payname;
1273 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
1276 $self->otaker(getotaker) unless $self->otaker;
1278 #warn "AFTER: \n". $self->_dump;
1280 $self->SUPER::check;
1285 Returns all packages (see L<FS::cust_pkg>) for this customer.
1291 if ( $self->{'_pkgnum'} ) {
1292 values %{ $self->{'_pkgnum'}->cache };
1294 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1298 =item ncancelled_pkgs
1300 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1304 sub ncancelled_pkgs {
1306 if ( $self->{'_pkgnum'} ) {
1307 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1309 @{ [ # force list context
1310 qsearch( 'cust_pkg', {
1311 'custnum' => $self->custnum,
1314 qsearch( 'cust_pkg', {
1315 'custnum' => $self->custnum,
1322 =item suspended_pkgs
1324 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1328 sub suspended_pkgs {
1330 grep { $_->susp } $self->ncancelled_pkgs;
1333 =item unflagged_suspended_pkgs
1335 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1336 customer (thouse packages without the `manual_flag' set).
1340 sub unflagged_suspended_pkgs {
1342 return $self->suspended_pkgs
1343 unless dbdef->table('cust_pkg')->column('manual_flag');
1344 grep { ! $_->manual_flag } $self->suspended_pkgs;
1347 =item unsuspended_pkgs
1349 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1354 sub unsuspended_pkgs {
1356 grep { ! $_->susp } $self->ncancelled_pkgs;
1359 =item num_cancelled_pkgs
1361 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1366 sub num_cancelled_pkgs {
1368 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1372 my( $self, $sql ) = @_;
1373 my $sth = dbh->prepare(
1374 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1375 ) or die dbh->errstr;
1376 $sth->execute($self->custnum) or die $sth->errstr;
1377 $sth->fetchrow_arrayref->[0];
1382 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1383 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1384 on success or a list of errors.
1390 grep { $_->unsuspend } $self->suspended_pkgs;
1395 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1396 Always returns a list: an empty list on success or a list of errors.
1402 grep { $_->suspend } $self->unsuspended_pkgs;
1405 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1407 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1408 PKGPARTs (see L<FS::part_pkg>). Always returns a list: an empty list on
1409 success or a list of errors.
1413 sub suspend_if_pkgpart {
1416 grep { $_->suspend }
1417 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1418 $self->unsuspended_pkgs;
1421 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1423 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1424 listed PKGPARTs (see L<FS::part_pkg>). Always returns a list: an empty list
1425 on success or a list of errors.
1429 sub suspend_unless_pkgpart {
1432 grep { $_->suspend }
1433 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1434 $self->unsuspended_pkgs;
1437 =item cancel [ OPTION => VALUE ... ]
1439 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1441 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1443 I<quiet> can be set true to supress email cancellation notices.
1445 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1447 I<ban> can be set true to ban this customer's credit card or ACH information,
1450 Always returns a list: an empty list on success or a list of errors.
1458 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1460 #should try decryption (we might have the private key)
1461 # and if not maybe queue a job for the server that does?
1462 return ( "Can't (yet) ban encrypted credit cards" )
1463 if $self->is_encrypted($self->payinfo);
1465 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1466 my $error = $ban->insert;
1467 return ( $error ) if $error;
1471 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1474 sub _banned_pay_hashref {
1485 'payby' => $payby2ban{$self->payby},
1486 'payinfo' => md5_base64($self->payinfo),
1493 Returns the agent (see L<FS::agent>) for this customer.
1499 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1504 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1505 conjunction with the collect method.
1507 Options are passed as name-value pairs.
1509 Currently available options are:
1511 resetup - if set true, re-charges setup fees.
1513 time - bills the customer as if it were that time. Specified as a UNIX
1514 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1515 L<Date::Parse> for conversion functions. For example:
1519 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1522 If there is an error, returns the error, otherwise returns false.
1527 my( $self, %options ) = @_;
1528 return '' if $self->payby eq 'COMP';
1529 warn "bill customer ". $self->custnum. "\n" if $DEBUG;
1531 my $time = $options{'time'} || time;
1536 local $SIG{HUP} = 'IGNORE';
1537 local $SIG{INT} = 'IGNORE';
1538 local $SIG{QUIT} = 'IGNORE';
1539 local $SIG{TERM} = 'IGNORE';
1540 local $SIG{TSTP} = 'IGNORE';
1541 local $SIG{PIPE} = 'IGNORE';
1543 my $oldAutoCommit = $FS::UID::AutoCommit;
1544 local $FS::UID::AutoCommit = 0;
1547 $self->select_for_update; #mutex
1549 # find the packages which are due for billing, find out how much they are
1550 # & generate invoice database.
1552 my( $total_setup, $total_recur ) = ( 0, 0 );
1553 #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
1554 my @cust_bill_pkg = ();
1556 #my $taxable_charged = 0;##
1561 foreach my $cust_pkg (
1562 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1565 #NO!! next if $cust_pkg->cancel;
1566 next if $cust_pkg->getfield('cancel');
1568 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG;
1570 #? to avoid use of uninitialized value errors... ?
1571 $cust_pkg->setfield('bill', '')
1572 unless defined($cust_pkg->bill);
1574 my $part_pkg = $cust_pkg->part_pkg;
1576 my %hash = $cust_pkg->hash;
1577 my $old_cust_pkg = new FS::cust_pkg \%hash;
1583 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1585 warn " bill setup\n" if $DEBUG;
1587 $setup = eval { $cust_pkg->calc_setup( $time ) };
1589 $dbh->rollback if $oldAutoCommit;
1593 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1599 if ( $part_pkg->getfield('freq') ne '0' &&
1600 ! $cust_pkg->getfield('susp') &&
1601 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1604 warn " bill recur\n" if $DEBUG;
1606 # XXX shared with $recur_prog
1607 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1609 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details ) };
1611 $dbh->rollback if $oldAutoCommit;
1615 #change this bit to use Date::Manip? CAREFUL with timezones (see
1616 # mailing list archive)
1617 my ($sec,$min,$hour,$mday,$mon,$year) =
1618 (localtime($sdate) )[0,1,2,3,4,5];
1620 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1621 # only for figuring next bill date, nothing else, so, reset $sdate again
1623 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1624 $cust_pkg->last_bill($sdate)
1625 if $cust_pkg->dbdef_table->column('last_bill');
1627 if ( $part_pkg->freq =~ /^\d+$/ ) {
1628 $mon += $part_pkg->freq;
1629 until ( $mon < 12 ) { $mon -= 12; $year++; }
1630 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1632 $mday += $weeks * 7;
1633 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1637 $dbh->rollback if $oldAutoCommit;
1638 return "unparsable frequency: ". $part_pkg->freq;
1640 $cust_pkg->setfield('bill',
1641 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1644 warn "\$setup is undefined" unless defined($setup);
1645 warn "\$recur is undefined" unless defined($recur);
1646 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1648 if ( $cust_pkg->modified ) {
1650 warn " package ". $cust_pkg->pkgnum. " modified; updating\n" if $DEBUG;
1652 $error=$cust_pkg->replace($old_cust_pkg);
1653 if ( $error ) { #just in case
1654 $dbh->rollback if $oldAutoCommit;
1655 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1658 $setup = sprintf( "%.2f", $setup );
1659 $recur = sprintf( "%.2f", $recur );
1660 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1661 $dbh->rollback if $oldAutoCommit;
1662 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1664 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1665 $dbh->rollback if $oldAutoCommit;
1666 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1668 if ( $setup != 0 || $recur != 0 ) {
1669 warn " charges (setup=$setup, recur=$recur); queueing line items\n"
1671 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1672 'pkgnum' => $cust_pkg->pkgnum,
1676 'edate' => $cust_pkg->bill,
1677 'details' => \@details,
1679 push @cust_bill_pkg, $cust_bill_pkg;
1680 $total_setup += $setup;
1681 $total_recur += $recur;
1683 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1685 my @taxes = qsearch( 'cust_main_county', {
1686 'state' => $self->state,
1687 'county' => $self->county,
1688 'country' => $self->country,
1689 'taxclass' => $part_pkg->taxclass,
1692 @taxes = qsearch( 'cust_main_county', {
1693 'state' => $self->state,
1694 'county' => $self->county,
1695 'country' => $self->country,
1700 #one more try at a whole-country tax rate
1702 @taxes = qsearch( 'cust_main_county', {
1705 'country' => $self->country,
1710 # maybe eliminate this entirely, along with all the 0% records
1712 $dbh->rollback if $oldAutoCommit;
1714 "fatal: can't find tax rate for state/county/country/taxclass ".
1715 join('/', ( map $self->$_(), qw(state county country) ),
1716 $part_pkg->taxclass ). "\n";
1719 foreach my $tax ( @taxes ) {
1721 my $taxable_charged = 0;
1722 $taxable_charged += $setup
1723 unless $part_pkg->setuptax =~ /^Y$/i
1724 || $tax->setuptax =~ /^Y$/i;
1725 $taxable_charged += $recur
1726 unless $part_pkg->recurtax =~ /^Y$/i
1727 || $tax->recurtax =~ /^Y$/i;
1728 next unless $taxable_charged;
1730 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
1731 my ($mon,$year) = (localtime($sdate) )[4,5];
1733 my $freq = $part_pkg->freq || 1;
1734 if ( $freq !~ /(\d+)$/ ) {
1735 $dbh->rollback if $oldAutoCommit;
1736 return "daily/weekly package definitions not (yet?)".
1737 " compatible with monthly tax exemptions";
1739 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1740 foreach my $which_month ( 1 .. $freq ) {
1742 'custnum' => $self->custnum,
1743 'taxnum' => $tax->taxnum,
1744 'year' => 1900+$year,
1747 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1748 until ( $mon < 13 ) { $mon -= 12; $year++; }
1749 my $cust_tax_exempt =
1750 qsearchs('cust_tax_exempt', \%hash)
1751 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1752 my $remaining_exemption = sprintf("%.2f",
1753 $tax->exempt_amount - $cust_tax_exempt->amount );
1754 if ( $remaining_exemption > 0 ) {
1755 my $addl = $remaining_exemption > $taxable_per_month
1756 ? $taxable_per_month
1757 : $remaining_exemption;
1758 $taxable_charged -= $addl;
1759 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1760 $cust_tax_exempt->hash,
1762 sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1764 $error = $new_cust_tax_exempt->exemptnum
1765 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1766 : $new_cust_tax_exempt->insert;
1768 $dbh->rollback if $oldAutoCommit;
1769 return "fatal: can't update cust_tax_exempt: $error";
1772 } # if $remaining_exemption > 0
1774 } #foreach $which_month
1776 } #if $tax->exempt_amount
1778 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1780 #$tax += $taxable_charged * $cust_main_county->tax / 100
1781 $tax{ $tax->taxname || 'Tax' } +=
1782 $taxable_charged * $tax->tax / 100
1784 } #foreach my $tax ( @taxes )
1786 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
1788 } #if $setup != 0 || $recur != 0
1790 } #if $cust_pkg->modified
1792 } #foreach my $cust_pkg
1794 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1795 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1797 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1798 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1802 # unless ( $self->tax =~ /Y/i
1803 # || $self->payby eq 'COMP'
1804 # || $taxable_charged == 0 ) {
1805 # my $cust_main_county = qsearchs('cust_main_county',{
1806 # 'state' => $self->state,
1807 # 'county' => $self->county,
1808 # 'country' => $self->country,
1809 # } ) or die "fatal: can't find tax rate for state/county/country ".
1810 # $self->state. "/". $self->county. "/". $self->country. "\n";
1811 # my $tax = sprintf( "%.2f",
1812 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1815 if ( dbdef->table('cust_bill_pkg')->column('itemdesc') ) { #1.5 schema
1817 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
1818 my $tax = sprintf("%.2f", $tax{$taxname} );
1819 $charged = sprintf( "%.2f", $charged+$tax );
1821 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1827 'itemdesc' => $taxname,
1829 push @cust_bill_pkg, $cust_bill_pkg;
1832 } else { #1.4 schema
1835 foreach ( values %tax ) { $tax += $_ };
1836 $tax = sprintf("%.2f", $tax);
1838 $charged = sprintf( "%.2f", $charged+$tax );
1840 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1847 push @cust_bill_pkg, $cust_bill_pkg;
1852 my $cust_bill = new FS::cust_bill ( {
1853 'custnum' => $self->custnum,
1855 'charged' => $charged,
1857 $error = $cust_bill->insert;
1859 $dbh->rollback if $oldAutoCommit;
1860 return "can't create invoice for customer #". $self->custnum. ": $error";
1863 my $invnum = $cust_bill->invnum;
1865 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1867 $cust_bill_pkg->invnum($invnum);
1868 $error = $cust_bill_pkg->insert;
1870 $dbh->rollback if $oldAutoCommit;
1871 return "can't create invoice line item for customer #". $self->custnum.
1876 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1880 =item collect OPTIONS
1882 (Attempt to) collect money for this customer's outstanding invoices (see
1883 L<FS::cust_bill>). Usually used after the bill method.
1885 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
1886 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
1887 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
1889 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1890 and the invoice events web interface.
1892 If there is an error, returns the error, otherwise returns false.
1894 Options are passed as name-value pairs.
1896 Currently available options are:
1898 invoice_time - Use this time when deciding when to print invoices and
1899 late notices on those invoices. The default is now. It is specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse>
1900 for conversion functions.
1902 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
1905 retry_card - Deprecated alias for 'retry'
1907 batch_card - This option is deprecated. See the invoice events web interface
1908 to control whether cards are batched or run against a realtime gateway.
1910 report_badcard - This option is deprecated.
1912 force_print - This option is deprecated; see the invoice events web interface.
1914 quiet - set true to surpress email card/ACH decline notices.
1919 my( $self, %options ) = @_;
1920 my $invoice_time = $options{'invoice_time'} || time;
1923 local $SIG{HUP} = 'IGNORE';
1924 local $SIG{INT} = 'IGNORE';
1925 local $SIG{QUIT} = 'IGNORE';
1926 local $SIG{TERM} = 'IGNORE';
1927 local $SIG{TSTP} = 'IGNORE';
1928 local $SIG{PIPE} = 'IGNORE';
1930 my $oldAutoCommit = $FS::UID::AutoCommit;
1931 local $FS::UID::AutoCommit = 0;
1934 $self->select_for_update; #mutex
1936 my $balance = $self->balance;
1937 warn "collect customer ". $self->custnum. ": balance $balance\n" if $DEBUG;
1938 unless ( $balance > 0 ) { #redundant?????
1939 $dbh->rollback if $oldAutoCommit; #hmm
1943 if ( exists($options{'retry_card'}) ) {
1944 carp 'retry_card option passed to collect is deprecated; use retry';
1945 $options{'retry'} ||= $options{'retry_card'};
1947 if ( exists($options{'retry'}) && $options{'retry'} ) {
1948 my $error = $self->retry_realtime;
1950 $dbh->rollback if $oldAutoCommit;
1955 foreach my $cust_bill ( $self->open_cust_bill ) {
1957 # don't try to charge for the same invoice if it's already in a batch
1958 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1960 last if $self->balance <= 0;
1962 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
1965 foreach my $part_bill_event (
1966 sort { $a->seconds <=> $b->seconds
1967 || $a->weight <=> $b->weight
1968 || $a->eventpart <=> $b->eventpart }
1969 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1970 && ! qsearch( 'cust_bill_event', {
1971 'invnum' => $cust_bill->invnum,
1972 'eventpart' => $_->eventpart,
1976 qsearch('part_bill_event', { 'payby' => $self->payby,
1977 'disabled' => '', } )
1980 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
1981 || $self->balance <= 0; # or if balance<=0
1983 warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1985 my $cust_main = $self; #for callback
1989 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
1990 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
1991 $error = eval $part_bill_event->eventcode;
1995 my $statustext = '';
1999 } elsif ( $error ) {
2001 $statustext = $error;
2006 #add cust_bill_event
2007 my $cust_bill_event = new FS::cust_bill_event {
2008 'invnum' => $cust_bill->invnum,
2009 'eventpart' => $part_bill_event->eventpart,
2010 #'_date' => $invoice_time,
2012 'status' => $status,
2013 'statustext' => $statustext,
2015 $error = $cust_bill_event->insert;
2017 #$dbh->rollback if $oldAutoCommit;
2018 #return "error: $error";
2020 # gah, even with transactions.
2021 $dbh->commit if $oldAutoCommit; #well.
2022 my $e = 'WARNING: Event run but database not updated - '.
2023 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
2024 ', eventpart '. $part_bill_event->eventpart.
2035 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2040 =item retry_realtime
2042 Schedules realtime credit card / electronic check / LEC billing events for
2043 for retry. Useful if card information has changed or manual retry is desired.
2044 The 'collect' method must be called to actually retry the transaction.
2046 Implementation details: For each of this customer's open invoices, changes
2047 the status of the first "done" (with statustext error) realtime processing
2052 sub retry_realtime {
2055 local $SIG{HUP} = 'IGNORE';
2056 local $SIG{INT} = 'IGNORE';
2057 local $SIG{QUIT} = 'IGNORE';
2058 local $SIG{TERM} = 'IGNORE';
2059 local $SIG{TSTP} = 'IGNORE';
2060 local $SIG{PIPE} = 'IGNORE';
2062 my $oldAutoCommit = $FS::UID::AutoCommit;
2063 local $FS::UID::AutoCommit = 0;
2066 foreach my $cust_bill (
2067 grep { $_->cust_bill_event }
2068 $self->open_cust_bill
2070 my @cust_bill_event =
2071 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2073 #$_->part_bill_event->plan eq 'realtime-card'
2074 $_->part_bill_event->eventcode =~
2075 /\$cust_bill\->realtime_(card|ach|lec)/
2076 && $_->status eq 'done'
2079 $cust_bill->cust_bill_event;
2080 next unless @cust_bill_event;
2081 my $error = $cust_bill_event[0]->retry;
2083 $dbh->rollback if $oldAutoCommit;
2084 return "error scheduling invoice event for retry: $error";
2089 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2094 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2096 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2097 via a Business::OnlinePayment realtime gateway. See
2098 L<http://420.am/business-onlinepayment> for supported gateways.
2100 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2102 Available options are: I<description>, I<invnum>, I<quiet>
2104 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2105 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2106 if set, will override the value from the customer record.
2108 I<description> is a free-text field passed to the gateway. It defaults to
2109 "Internet services".
2111 If an I<invnum> is specified, this payment (if sucessful) is applied to the
2112 specified invoice. If you don't specify an I<invnum> you might want to
2113 call the B<apply_payments> method.
2115 I<quiet> can be set true to surpress email decline notices.
2117 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2122 my( $self, $method, $amount, %options ) = @_;
2124 warn "$self $method $amount\n";
2125 warn " $_ => $options{$_}\n" foreach keys %options;
2128 $options{'description'} ||= 'Internet services';
2130 eval "use Business::OnlinePayment";
2133 my $payinfo = exists($options{'payinfo'})
2134 ? $options{'payinfo'}
2142 if ( $options{'invnum'} ) {
2143 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2144 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2146 map { $_->part_pkg->taxclass }
2148 map { $_->cust_pkg }
2149 $cust_bill->cust_bill_pkg;
2150 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2151 #different taxclasses
2152 $taxclass = $taxclasses[0];
2156 #look for an agent gateway override first
2158 if ( $method eq 'CC' ) {
2159 $cardtype = cardtype($payinfo);
2160 } elsif ( $method eq 'ECHECK' ) {
2163 $cardtype = $method;
2167 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2168 cardtype => $cardtype,
2169 taxclass => $taxclass, } )
2170 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2172 taxclass => $taxclass, } )
2173 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2174 cardtype => $cardtype,
2176 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2178 taxclass => '', } );
2180 my $payment_gateway = '';
2181 my( $processor, $login, $password, $action, @bop_options );
2182 if ( $override ) { #use a payment gateway override
2184 $payment_gateway = $override->payment_gateway;
2186 $processor = $payment_gateway->gateway_module;
2187 $login = $payment_gateway->gateway_username;
2188 $password = $payment_gateway->gateway_password;
2189 $action = $payment_gateway->gateway_action;
2190 @bop_options = $payment_gateway->options;
2192 } else { #use the standard settings from the config
2194 ( $processor, $login, $password, $action, @bop_options ) =
2195 $self->default_payment_gateway($method);
2203 my $address = exists($options{'address1'})
2204 ? $options{'address1'}
2206 my $address2 = exists($options{'address2'})
2207 ? $options{'address2'}
2209 $address .= ", ". $address2 if length($address2);
2211 my $o_payname = exists($options{'payname'})
2212 ? $options{'payname'}
2214 my($payname, $payfirst, $paylast);
2215 if ( $o_payname && $method ne 'ECHECK' ) {
2216 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2217 or return "Illegal payname $payname";
2218 ($payfirst, $paylast) = ($1, $2);
2220 $payfirst = $self->getfield('first');
2221 $paylast = $self->getfield('last');
2222 $payname = "$payfirst $paylast";
2225 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2226 if ( $conf->exists('emailinvoiceauto')
2227 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2228 push @invoicing_list, $self->all_emails;
2231 my $email = ($conf->exists('business-onlinepayment-email-override'))
2232 ? $conf->config('business-onlinepayment-email-override')
2233 : $invoicing_list[0];
2236 if ( $method eq 'CC' ) {
2238 $content{card_number} = $payinfo;
2239 my $paydate = exists($options{'paydate'})
2240 ? $options{'paydate'}
2242 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2243 $content{expiration} = "$2/$1";
2245 my $paycvv = exists($options{'paycvv'})
2246 ? $options{'paycvv'}
2248 $content{cvv2} = $self->paycvv
2251 my $paystart_month = exists($options{'paystart_month'})
2252 ? $options{'paystart_month'}
2253 : $self->paystart_month;
2255 my $paystart_year = exists($options{'paystart_year'})
2256 ? $options{'paystart_year'}
2257 : $self->paystart_year;
2259 $content{card_start} = "$paystart_month/$paystart_year"
2260 if $paystart_month && $paystart_year;
2262 my $payissue = exists($options{'payissue'})
2263 ? $options{'payissue'}
2265 $content{issue_number} = $payissue if $payissue;
2267 my $payip = exists($options{'payip'})
2270 $content{customer_ip} = $payip
2273 $content{recurring_billing} = 'YES'
2274 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2276 'payinfo' => $payinfo,
2279 } elsif ( $method eq 'ECHECK' ) {
2280 ( $content{account_number}, $content{routing_code} ) =
2281 split('@', $payinfo);
2282 $content{bank_name} = $o_payname;
2283 $content{account_type} = 'CHECKING';
2284 $content{account_name} = $payname;
2285 $content{customer_org} = $self->company ? 'B' : 'I';
2286 $content{customer_ssn} = exists($options{'ss'})
2289 } elsif ( $method eq 'LEC' ) {
2290 $content{phone} = $payinfo;
2294 # run transaction(s)
2297 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2299 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2300 $transaction->content(
2303 'password' => $password,
2304 'action' => $action1,
2305 'description' => $options{'description'},
2306 'amount' => $amount,
2307 'invoice_number' => $options{'invnum'},
2308 'customer_id' => $self->custnum,
2309 'last_name' => $paylast,
2310 'first_name' => $payfirst,
2312 'address' => $address,
2313 'city' => ( exists($options{'city'})
2316 'state' => ( exists($options{'state'})
2319 'zip' => ( exists($options{'zip'})
2322 'country' => ( exists($options{'country'})
2323 ? $options{'country'}
2325 'referer' => 'http://cleanwhisker.420.am/',
2327 'phone' => $self->daytime || $self->night,
2330 $transaction->submit();
2332 if ( $transaction->is_success() && $action2 ) {
2333 my $auth = $transaction->authorization;
2334 my $ordernum = $transaction->can('order_number')
2335 ? $transaction->order_number
2339 new Business::OnlinePayment( $processor, @bop_options );
2346 password => $password,
2347 order_number => $ordernum,
2349 authorization => $auth,
2350 description => $options{'description'},
2353 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2354 transaction_sequence_num local_transaction_date
2355 local_transaction_time AVS_result_code )) {
2356 $capture{$field} = $transaction->$field() if $transaction->can($field);
2359 $capture->content( %capture );
2363 unless ( $capture->is_success ) {
2364 my $e = "Authorization sucessful but capture failed, custnum #".
2365 $self->custnum. ': '. $capture->result_code.
2366 ": ". $capture->error_message;
2374 # remove paycvv after initial transaction
2377 #false laziness w/misc/process/payment.cgi - check both to make sure working
2379 if ( defined $self->dbdef_table->column('paycvv')
2380 && length($self->paycvv)
2381 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2383 my $error = $self->remove_cvv;
2385 warn "error removing cvv: $error\n";
2393 if ( $transaction->is_success() ) {
2395 my %method2payby = (
2402 if ( $payment_gateway ) { # agent override
2403 $paybatch = $payment_gateway->gatewaynum. '-';
2406 $paybatch .= "$processor:". $transaction->authorization;
2408 $paybatch .= ':'. $transaction->order_number
2409 if $transaction->can('order_number')
2410 && length($transaction->order_number);
2412 my $cust_pay = new FS::cust_pay ( {
2413 'custnum' => $self->custnum,
2414 'invnum' => $options{'invnum'},
2417 'payby' => $method2payby{$method},
2418 'payinfo' => $payinfo,
2419 'paybatch' => $paybatch,
2421 my $error = $cust_pay->insert;
2423 $cust_pay->invnum(''); #try again with no specific invnum
2424 my $error2 = $cust_pay->insert;
2426 # gah, even with transactions.
2427 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2428 "error inserting payment ($processor): $error2".
2429 " (previously tried insert with invnum #$options{'invnum'}" .
2435 return ''; #no error
2439 my $perror = "$processor error: ". $transaction->error_message;
2441 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2442 && $conf->exists('emaildecline')
2443 && grep { $_ ne 'POST' } $self->invoicing_list
2444 && ! grep { $transaction->error_message =~ /$_/ }
2445 $conf->config('emaildecline-exclude')
2447 my @templ = $conf->config('declinetemplate');
2448 my $template = new Text::Template (
2450 SOURCE => [ map "$_\n", @templ ],
2451 ) or return "($perror) can't create template: $Text::Template::ERROR";
2452 $template->compile()
2453 or return "($perror) can't compile template: $Text::Template::ERROR";
2455 my $templ_hash = { error => $transaction->error_message };
2457 my $error = send_email(
2458 'from' => $conf->config('invoice_from'),
2459 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2460 'subject' => 'Your payment could not be processed',
2461 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2464 $perror .= " (also received error sending decline notification: $error)"
2474 =item default_payment_gateway
2478 sub default_payment_gateway {
2479 my( $self, $method ) = @_;
2481 die "Real-time processing not enabled\n"
2482 unless $conf->exists('business-onlinepayment');
2485 my $bop_config = 'business-onlinepayment';
2486 $bop_config .= '-ach'
2487 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2488 my ( $processor, $login, $password, $action, @bop_options ) =
2489 $conf->config($bop_config);
2490 $action ||= 'normal authorization';
2491 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2492 die "No real-time processor is enabled - ".
2493 "did you set the business-onlinepayment configuration value?\n"
2496 ( $processor, $login, $password, $action, @bop_options )
2501 Removes the I<paycvv> field from the database directly.
2503 If there is an error, returns the error, otherwise returns false.
2509 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2510 or return dbh->errstr;
2511 $sth->execute($self->custnum)
2512 or return $sth->errstr;
2517 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2519 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2520 via a Business::OnlinePayment realtime gateway. See
2521 L<http://420.am/business-onlinepayment> for supported gateways.
2523 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2525 Available options are: I<amount>, I<reason>, I<paynum>
2527 Most gateways require a reference to an original payment transaction to refund,
2528 so you probably need to specify a I<paynum>.
2530 I<amount> defaults to the original amount of the payment if not specified.
2532 I<reason> specifies a reason for the refund.
2534 Implementation note: If I<amount> is unspecified or equal to the amount of the
2535 orignal payment, first an attempt is made to "void" the transaction via
2536 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2537 the normal attempt is made to "refund" ("credit") the transaction via the
2538 gateway is attempted.
2540 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2541 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2542 #if set, will override the value from the customer record.
2544 #If an I<invnum> is specified, this payment (if sucessful) is applied to the
2545 #specified invoice. If you don't specify an I<invnum> you might want to
2546 #call the B<apply_payments> method.
2550 #some false laziness w/realtime_bop, not enough to make it worth merging
2551 #but some useful small subs should be pulled out
2552 sub realtime_refund_bop {
2553 my( $self, $method, %options ) = @_;
2555 warn "$self $method refund\n";
2556 warn " $_ => $options{$_}\n" foreach keys %options;
2559 eval "use Business::OnlinePayment";
2563 # look up the original payment and optionally a gateway for that payment
2567 my $amount = $options{'amount'};
2569 my( $processor, $login, $password, @bop_options ) ;
2570 my( $auth, $order_number ) = ( '', '', '' );
2572 if ( $options{'paynum'} ) {
2574 warn "FS::cust_main::realtime_bop: paynum: $options{paynum}\n" if $DEBUG;
2575 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2576 or return "Unknown paynum $options{'paynum'}";
2577 $amount ||= $cust_pay->paid;
2579 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):([\w-]*)(:(\w+))?$/
2580 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2581 $cust_pay->paybatch;
2582 my $gatewaynum = '';
2583 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2585 if ( $gatewaynum ) { #gateway for the payment to be refunded
2587 my $payment_gateway =
2588 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2589 die "payment gateway $gatewaynum not found"
2590 unless $payment_gateway;
2592 $processor = $payment_gateway->gateway_module;
2593 $login = $payment_gateway->gateway_username;
2594 $password = $payment_gateway->gateway_password;
2595 @bop_options = $payment_gateway->options;
2597 } else { #try the default gateway
2599 my( $conf_processor, $unused_action );
2600 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2601 $self->default_payment_gateway($method);
2603 return "processor of payment $options{'paynum'} $processor does not".
2604 " match default processor $conf_processor"
2605 unless $processor eq $conf_processor;
2610 } else { # didn't specify a paynum, so look for agent gateway overrides
2611 # like a normal transaction
2614 if ( $method eq 'CC' ) {
2615 $cardtype = cardtype($self->payinfo);
2616 } elsif ( $method eq 'ECHECK' ) {
2619 $cardtype = $method;
2622 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2623 cardtype => $cardtype,
2625 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2627 taxclass => '', } );
2629 if ( $override ) { #use a payment gateway override
2631 my $payment_gateway = $override->payment_gateway;
2633 $processor = $payment_gateway->gateway_module;
2634 $login = $payment_gateway->gateway_username;
2635 $password = $payment_gateway->gateway_password;
2636 #$action = $payment_gateway->gateway_action;
2637 @bop_options = $payment_gateway->options;
2639 } else { #use the standard settings from the config
2642 ( $processor, $login, $password, $unused_action, @bop_options ) =
2643 $self->default_payment_gateway($method);
2648 return "neither amount nor paynum specified" unless $amount;
2653 'password' => $password,
2654 'order_number' => $order_number,
2655 'amount' => $amount,
2656 'referer' => 'http://cleanwhisker.420.am/',
2658 $content{authorization} = $auth
2659 if length($auth); #echeck/ACH transactions have an order # but no auth
2660 #(at least with authorize.net)
2662 #first try void if applicable
2663 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2664 warn "FS::cust_main::realtime_bop: attempting void\n" if $DEBUG;
2665 my $void = new Business::OnlinePayment( $processor, @bop_options );
2666 $void->content( 'action' => 'void', %content );
2668 if ( $void->is_success ) {
2669 my $error = $cust_pay->void($options{'reason'});
2671 # gah, even with transactions.
2672 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2673 "error voiding payment: $error";
2677 warn "FS::cust_main::realtime_bop: void successful\n" if $DEBUG;
2682 warn "FS::cust_main::realtime_bop: void unsuccessful, trying refund\n"
2686 my $address = $self->address1;
2687 $address .= ", ". $self->address2 if $self->address2;
2689 my($payname, $payfirst, $paylast);
2690 if ( $self->payname && $method ne 'ECHECK' ) {
2691 $payname = $self->payname;
2692 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2693 or return "Illegal payname $payname";
2694 ($payfirst, $paylast) = ($1, $2);
2696 $payfirst = $self->getfield('first');
2697 $paylast = $self->getfield('last');
2698 $payname = "$payfirst $paylast";
2702 if ( $method eq 'CC' ) {
2705 $content{card_number} = $payinfo = $cust_pay->payinfo;
2706 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2707 #$content{expiration} = "$2/$1";
2709 $content{card_number} = $payinfo = $self->payinfo;
2710 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2711 $content{expiration} = "$2/$1";
2714 } elsif ( $method eq 'ECHECK' ) {
2715 ( $content{account_number}, $content{routing_code} ) =
2716 split('@', $payinfo = $self->payinfo);
2717 $content{bank_name} = $self->payname;
2718 $content{account_type} = 'CHECKING';
2719 $content{account_name} = $payname;
2720 $content{customer_org} = $self->company ? 'B' : 'I';
2721 $content{customer_ssn} = $self->ss;
2722 } elsif ( $method eq 'LEC' ) {
2723 $content{phone} = $payinfo = $self->payinfo;
2727 my $refund = new Business::OnlinePayment( $processor, @bop_options );
2728 my %sub_content = $refund->content(
2729 'action' => 'credit',
2730 'customer_id' => $self->custnum,
2731 'last_name' => $paylast,
2732 'first_name' => $payfirst,
2734 'address' => $address,
2735 'city' => $self->city,
2736 'state' => $self->state,
2737 'zip' => $self->zip,
2738 'country' => $self->country,
2741 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
2745 return "$processor error: ". $refund->error_message
2746 unless $refund->is_success();
2748 my %method2payby = (
2754 my $paybatch = "$processor:". $refund->authorization;
2755 $paybatch .= ':'. $refund->order_number
2756 if $refund->can('order_number') && $refund->order_number;
2758 while ( $cust_pay && $cust_pay->unappled < $amount ) {
2759 my @cust_bill_pay = $cust_pay->cust_bill_pay;
2760 last unless @cust_bill_pay;
2761 my $cust_bill_pay = pop @cust_bill_pay;
2762 my $error = $cust_bill_pay->delete;
2766 my $cust_refund = new FS::cust_refund ( {
2767 'custnum' => $self->custnum,
2768 'paynum' => $options{'paynum'},
2769 'refund' => $amount,
2771 'payby' => $method2payby{$method},
2772 'payinfo' => $payinfo,
2773 'paybatch' => $paybatch,
2774 'reason' => $options{'reason'} || 'card or ACH refund',
2776 my $error = $cust_refund->insert;
2778 $cust_refund->paynum(''); #try again with no specific paynum
2779 my $error2 = $cust_refund->insert;
2781 # gah, even with transactions.
2782 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
2783 "error inserting refund ($processor): $error2".
2784 " (previously tried insert with paynum #$options{'paynum'}" .
2797 Returns the total owed for this customer on all invoices
2798 (see L<FS::cust_bill/owed>).
2804 $self->total_owed_date(2145859200); #12/31/2037
2807 =item total_owed_date TIME
2809 Returns the total owed for this customer on all invoices with date earlier than
2810 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2811 see L<Time::Local> and L<Date::Parse> for conversion functions.
2815 sub total_owed_date {
2819 foreach my $cust_bill (
2820 grep { $_->_date <= $time }
2821 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2823 $total_bill += $cust_bill->owed;
2825 sprintf( "%.2f", $total_bill );
2828 =item apply_credits OPTION => VALUE ...
2830 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2831 to outstanding invoice balances in chronological order (or reverse
2832 chronological order if the I<order> option is set to B<newest>) and returns the
2833 value of any remaining unapplied credits available for refund (see
2834 L<FS::cust_refund>).
2842 return 0 unless $self->total_credited;
2844 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2845 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2847 my @invoices = $self->open_cust_bill;
2848 @invoices = sort { $b->_date <=> $a->_date } @invoices
2849 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2852 foreach my $cust_bill ( @invoices ) {
2855 if ( !defined($credit) || $credit->credited == 0) {
2856 $credit = pop @credits or last;
2859 if ($cust_bill->owed >= $credit->credited) {
2860 $amount=$credit->credited;
2862 $amount=$cust_bill->owed;
2865 my $cust_credit_bill = new FS::cust_credit_bill ( {
2866 'crednum' => $credit->crednum,
2867 'invnum' => $cust_bill->invnum,
2868 'amount' => $amount,
2870 my $error = $cust_credit_bill->insert;
2871 die $error if $error;
2873 redo if ($cust_bill->owed > 0);
2877 return $self->total_credited;
2880 =item apply_payments
2882 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2883 to outstanding invoice balances in chronological order.
2885 #and returns the value of any remaining unapplied payments.
2889 sub apply_payments {
2894 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
2895 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
2897 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
2898 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
2902 foreach my $cust_bill ( @invoices ) {
2905 if ( !defined($payment) || $payment->unapplied == 0 ) {
2906 $payment = pop @payments or last;
2909 if ( $cust_bill->owed >= $payment->unapplied ) {
2910 $amount = $payment->unapplied;
2912 $amount = $cust_bill->owed;
2915 my $cust_bill_pay = new FS::cust_bill_pay ( {
2916 'paynum' => $payment->paynum,
2917 'invnum' => $cust_bill->invnum,
2918 'amount' => $amount,
2920 my $error = $cust_bill_pay->insert;
2921 die $error if $error;
2923 redo if ( $cust_bill->owed > 0);
2927 return $self->total_unapplied_payments;
2930 =item total_credited
2932 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2933 customer. See L<FS::cust_credit/credited>.
2937 sub total_credited {
2939 my $total_credit = 0;
2940 foreach my $cust_credit ( qsearch('cust_credit', {
2941 'custnum' => $self->custnum,
2943 $total_credit += $cust_credit->credited;
2945 sprintf( "%.2f", $total_credit );
2948 =item total_unapplied_payments
2950 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2951 See L<FS::cust_pay/unapplied>.
2955 sub total_unapplied_payments {
2957 my $total_unapplied = 0;
2958 foreach my $cust_pay ( qsearch('cust_pay', {
2959 'custnum' => $self->custnum,
2961 $total_unapplied += $cust_pay->unapplied;
2963 sprintf( "%.2f", $total_unapplied );
2968 Returns the balance for this customer (total_owed minus total_credited
2969 minus total_unapplied_payments).
2976 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
2980 =item balance_date TIME
2982 Returns the balance for this customer, only considering invoices with date
2983 earlier than TIME (total_owed_date minus total_credited minus
2984 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2985 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2994 $self->total_owed_date($time)
2995 - $self->total_credited
2996 - $self->total_unapplied_payments
3000 =item paydate_monthyear
3002 Returns a two-element list consisting of the month and year of this customer's
3003 paydate (credit card expiration date for CARD customers)
3007 sub paydate_monthyear {
3009 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3011 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3018 =item payinfo_masked
3020 Returns a "masked" payinfo field appropriate to the payment type. Masked characters are replaced by 'x'es. Use this to display publicly accessable account Information.
3022 Credit Cards - Mask all but the last four characters.
3023 Checks - Mask all but last 2 of account number and bank routing number.
3024 Others - Do nothing, return the unmasked string.
3028 sub payinfo_masked {
3030 return $self->paymask;
3033 =item invoicing_list [ ARRAYREF ]
3035 If an arguement is given, sets these email addresses as invoice recipients
3036 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3037 (except as warnings), so use check_invoicing_list first.
3039 Returns a list of email addresses (with svcnum entries expanded).
3041 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3042 check it without disturbing anything by passing nothing.
3044 This interface may change in the future.
3048 sub invoicing_list {
3049 my( $self, $arrayref ) = @_;
3051 my @cust_main_invoice;
3052 if ( $self->custnum ) {
3053 @cust_main_invoice =
3054 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3056 @cust_main_invoice = ();
3058 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3059 #warn $cust_main_invoice->destnum;
3060 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3061 #warn $cust_main_invoice->destnum;
3062 my $error = $cust_main_invoice->delete;
3063 warn $error if $error;
3066 if ( $self->custnum ) {
3067 @cust_main_invoice =
3068 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3070 @cust_main_invoice = ();
3072 my %seen = map { $_->address => 1 } @cust_main_invoice;
3073 foreach my $address ( @{$arrayref} ) {
3074 next if exists $seen{$address} && $seen{$address};
3075 $seen{$address} = 1;
3076 my $cust_main_invoice = new FS::cust_main_invoice ( {
3077 'custnum' => $self->custnum,
3080 my $error = $cust_main_invoice->insert;
3081 warn $error if $error;
3084 if ( $self->custnum ) {
3086 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3092 =item check_invoicing_list ARRAYREF
3094 Checks these arguements as valid input for the invoicing_list method. If there
3095 is an error, returns the error, otherwise returns false.
3099 sub check_invoicing_list {
3100 my( $self, $arrayref ) = @_;
3101 foreach my $address ( @{$arrayref} ) {
3103 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3104 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3107 my $cust_main_invoice = new FS::cust_main_invoice ( {
3108 'custnum' => $self->custnum,
3111 my $error = $self->custnum
3112 ? $cust_main_invoice->check
3113 : $cust_main_invoice->checkdest
3115 return $error if $error;
3120 =item set_default_invoicing_list
3122 Sets the invoicing list to all accounts associated with this customer,
3123 overwriting any previous invoicing list.
3127 sub set_default_invoicing_list {
3129 $self->invoicing_list($self->all_emails);
3134 Returns the email addresses of all accounts provisioned for this customer.
3141 foreach my $cust_pkg ( $self->all_pkgs ) {
3142 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3144 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3145 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3147 $list{$_}=1 foreach map { $_->email } @svc_acct;
3152 =item invoicing_list_addpost
3154 Adds postal invoicing to this customer. If this customer is already configured
3155 to receive postal invoices, does nothing.
3159 sub invoicing_list_addpost {
3161 return if grep { $_ eq 'POST' } $self->invoicing_list;
3162 my @invoicing_list = $self->invoicing_list;
3163 push @invoicing_list, 'POST';
3164 $self->invoicing_list(\@invoicing_list);
3167 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3169 Returns an array of customers referred by this customer (referral_custnum set
3170 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3171 customers referred by customers referred by this customer and so on, inclusive.
3172 The default behavior is DEPTH 1 (no recursion).
3176 sub referral_cust_main {
3178 my $depth = @_ ? shift : 1;
3179 my $exclude = @_ ? shift : {};
3182 map { $exclude->{$_->custnum}++; $_; }
3183 grep { ! $exclude->{ $_->custnum } }
3184 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3188 map { $_->referral_cust_main($depth-1, $exclude) }
3195 =item referral_cust_main_ncancelled
3197 Same as referral_cust_main, except only returns customers with uncancelled
3202 sub referral_cust_main_ncancelled {
3204 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3207 =item referral_cust_pkg [ DEPTH ]
3209 Like referral_cust_main, except returns a flat list of all unsuspended (and
3210 uncancelled) packages for each customer. The number of items in this list may
3211 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3215 sub referral_cust_pkg {
3217 my $depth = @_ ? shift : 1;
3219 map { $_->unsuspended_pkgs }
3220 grep { $_->unsuspended_pkgs }
3221 $self->referral_cust_main($depth);
3224 =item referring_cust_main
3226 Returns the single cust_main record for the customer who referred this customer
3227 (referral_custnum), or false.
3231 sub referring_cust_main {
3233 return '' unless $self->referral_custnum;
3234 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3237 =item credit AMOUNT, REASON
3239 Applies a credit to this customer. If there is an error, returns the error,
3240 otherwise returns false.
3245 my( $self, $amount, $reason ) = @_;
3246 my $cust_credit = new FS::cust_credit {
3247 'custnum' => $self->custnum,
3248 'amount' => $amount,
3249 'reason' => $reason,
3251 $cust_credit->insert;
3254 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3256 Creates a one-time charge for this customer. If there is an error, returns
3257 the error, otherwise returns false.
3262 my ( $self, $amount ) = ( shift, shift );
3263 my $pkg = @_ ? shift : 'One-time charge';
3264 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3265 my $taxclass = @_ ? shift : '';
3267 local $SIG{HUP} = 'IGNORE';
3268 local $SIG{INT} = 'IGNORE';
3269 local $SIG{QUIT} = 'IGNORE';
3270 local $SIG{TERM} = 'IGNORE';
3271 local $SIG{TSTP} = 'IGNORE';
3272 local $SIG{PIPE} = 'IGNORE';
3274 my $oldAutoCommit = $FS::UID::AutoCommit;
3275 local $FS::UID::AutoCommit = 0;
3278 my $part_pkg = new FS::part_pkg ( {
3280 'comment' => $comment,
3281 #'setup' => $amount,
3284 'plandata' => "setup_fee=$amount",
3287 'taxclass' => $taxclass,
3290 my $error = $part_pkg->insert;
3292 $dbh->rollback if $oldAutoCommit;
3296 my $pkgpart = $part_pkg->pkgpart;
3297 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3298 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3299 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3300 $error = $type_pkgs->insert;
3302 $dbh->rollback if $oldAutoCommit;
3307 my $cust_pkg = new FS::cust_pkg ( {
3308 'custnum' => $self->custnum,
3309 'pkgpart' => $pkgpart,
3312 $error = $cust_pkg->insert;
3314 $dbh->rollback if $oldAutoCommit;
3318 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3325 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3331 sort { $a->_date <=> $b->_date }
3332 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3335 =item open_cust_bill
3337 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3342 sub open_cust_bill {
3344 grep { $_->owed > 0 } $self->cust_bill;
3349 Returns all the credits (see L<FS::cust_credit>) for this customer.
3355 sort { $a->_date <=> $b->_date }
3356 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3361 Returns all the payments (see L<FS::cust_pay>) for this customer.
3367 sort { $a->_date <=> $b->_date }
3368 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3373 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3379 sort { $a->_date <=> $b->_date }
3380 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3386 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3392 sort { $a->_date <=> $b->_date }
3393 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3396 =item select_for_update
3398 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3403 sub select_for_update {
3405 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3410 Returns a name string for this customer, either "Company (Last, First)" or
3417 my $name = $self->contact;
3418 $name = $self->company. " ($name)" if $self->company;
3424 Returns a name string for this (service/shipping) contact, either
3425 "Company (Last, First)" or "Last, First".
3431 if ( $self->get('ship_last') ) {
3432 my $name = $self->ship_contact;
3433 $name = $self->ship_company. " ($name)" if $self->ship_company;
3442 Returns this customer's full (billing) contact name only, "Last, First"
3448 $self->get('last'). ', '. $self->first;
3453 Returns this customer's full (shipping) contact name only, "Last, First"
3459 $self->get('ship_last')
3460 ? $self->get('ship_last'). ', '. $self->ship_first
3466 Returns a status string for this customer, currently:
3470 =item prospect - No packages have ever been ordered
3472 =item active - One or more recurring packages is active
3474 =item suspended - All non-cancelled recurring packages are suspended
3476 =item cancelled - All recurring packages are cancelled
3484 for my $status (qw( prospect active suspended cancelled )) {
3485 my $method = $status.'_sql';
3486 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3487 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3488 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3489 return $status if $sth->fetchrow_arrayref->[0];
3495 Returns a hex triplet color string for this customer's status.
3500 'prospect' => '000000',
3501 'active' => '00CC00',
3502 'suspended' => 'FF9900',
3503 'cancelled' => 'FF0000',
3507 $statuscolor{$self->status};
3512 =head1 CLASS METHODS
3518 Returns an SQL expression identifying prospective cust_main records (customers
3519 with no packages ever ordered)
3523 sub prospect_sql { "
3524 0 = ( SELECT COUNT(*) FROM cust_pkg
3525 WHERE cust_pkg.custnum = cust_main.custnum
3531 Returns an SQL expression identifying active cust_main records.
3536 0 < ( SELECT COUNT(*) FROM cust_pkg
3537 WHERE cust_pkg.custnum = cust_main.custnum
3538 AND ". FS::cust_pkg->active_sql. "
3545 Returns an SQL expression identifying suspended cust_main records.
3549 #my $recurring_sql = FS::cust_pkg->recurring_sql;
3550 my $recurring_sql = "
3551 '0' != ( select freq from part_pkg
3552 where cust_pkg.pkgpart = part_pkg.pkgpart )
3555 sub suspended_sql { susp_sql(@_); }
3557 0 < ( SELECT COUNT(*) FROM cust_pkg
3558 WHERE cust_pkg.custnum = cust_main.custnum
3560 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3562 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3563 WHERE cust_pkg.custnum = cust_main.custnum
3564 AND ". FS::cust_pkg->active_sql. "
3571 Returns an SQL expression identifying cancelled cust_main records.
3575 sub cancelled_sql { cancel_sql(@_); }
3577 0 < ( SELECT COUNT(*) FROM cust_pkg
3578 WHERE cust_pkg.custnum = cust_main.custnum
3580 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3581 WHERE cust_pkg.custnum = cust_main.custnum
3583 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3587 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3589 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3590 records. Currently, only I<last> or I<company> may be specified (the
3591 appropriate ship_ field is also searched if applicable).
3593 Additional options are the same as FS::Record::qsearch
3598 my( $self, $fuzzy, $hash, @opt) = @_;
3603 check_and_rebuild_fuzzyfiles();
3604 foreach my $field ( keys %$fuzzy ) {
3605 my $sub = \&{"all_$field"};
3607 $match{$_}=1 foreach ( amatch($fuzzy->{$field}, ['i'], @{ &$sub() } ) );
3609 foreach ( keys %match ) {
3610 push @cust_main, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3611 push @cust_main, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt)
3612 if defined dbdef->table('cust_main')->column('ship_last');
3617 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
3629 =item smart_search OPTION => VALUE ...
3631 Accepts the following options: I<search>, the string to search for. The string
3632 will be searched for as a customer number, last name or company name, first
3633 searching for an exact match then fuzzy and substring matches.
3635 Any additional options treated as an additional qualifier on the search
3638 Returns a (possibly empty) array of FS::cust_main objects.
3644 my $search = delete $options{'search'};
3647 if ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
3649 push @cust_main, qsearch('cust_main', { 'custnum' => $1, %options } );
3651 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { #value search
3654 my $q_value = dbh->quote($value);
3657 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
3658 $sql .= " ( LOWER(last) = $q_value OR LOWER(company) = $q_value";
3659 $sql .= " OR LOWER(ship_last) = $q_value OR LOWER(ship_company) = $q_value"
3660 if defined dbdef->table('cust_main')->column('ship_last');
3663 push @cust_main, qsearch( 'cust_main', \%options, '', $sql );
3665 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
3667 #still some false laziness w/ search/cust_main.cgi
3670 push @cust_main, qsearch( 'cust_main',
3671 { 'last' => { 'op' => 'ILIKE',
3672 'value' => "%$q_value%" },
3676 push @cust_main, qsearch( 'cust_main',
3677 { 'ship_last' => { 'op' => 'ILIKE',
3678 'value' => "%$q_value%" },
3683 if defined dbdef->table('cust_main')->column('ship_last');
3685 push @cust_main, qsearch( 'cust_main',
3686 { 'company' => { 'op' => 'ILIKE',
3687 'value' => "%$q_value%" },
3691 push @cust_main, qsearch( 'cust_main',
3692 { 'ship_company' => { 'op' => 'ILIKE',
3693 'value' => "%$q_value%" },
3697 if defined dbdef->table('cust_main')->column('ship_last');
3700 push @cust_main, FS::cust_main->fuzzy_search(
3701 { 'last' => $value },
3704 push @cust_main, FS::cust_main->fuzzy_search(
3705 { 'company' => $value },
3717 =item check_and_rebuild_fuzzyfiles
3721 sub check_and_rebuild_fuzzyfiles {
3722 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3723 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
3724 or &rebuild_fuzzyfiles;
3727 =item rebuild_fuzzyfiles
3731 sub rebuild_fuzzyfiles {
3733 use Fcntl qw(:flock);
3735 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3739 open(LASTLOCK,">>$dir/cust_main.last")
3740 or die "can't open $dir/cust_main.last: $!";
3741 flock(LASTLOCK,LOCK_EX)
3742 or die "can't lock $dir/cust_main.last: $!";
3744 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
3746 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
3747 if defined dbdef->table('cust_main')->column('ship_last');
3749 open (LASTCACHE,">$dir/cust_main.last.tmp")
3750 or die "can't open $dir/cust_main.last.tmp: $!";
3751 print LASTCACHE join("\n", @all_last), "\n";
3752 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
3754 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
3759 open(COMPANYLOCK,">>$dir/cust_main.company")
3760 or die "can't open $dir/cust_main.company: $!";
3761 flock(COMPANYLOCK,LOCK_EX)
3762 or die "can't lock $dir/cust_main.company: $!";
3764 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
3766 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
3767 if defined dbdef->table('cust_main')->column('ship_last');
3769 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
3770 or die "can't open $dir/cust_main.company.tmp: $!";
3771 print COMPANYCACHE join("\n", @all_company), "\n";
3772 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
3774 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
3784 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3785 open(LASTCACHE,"<$dir/cust_main.last")
3786 or die "can't open $dir/cust_main.last: $!";
3787 my @array = map { chomp; $_; } <LASTCACHE>;
3797 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3798 open(COMPANYCACHE,"<$dir/cust_main.company")
3799 or die "can't open $dir/cust_main.last: $!";
3800 my @array = map { chomp; $_; } <COMPANYCACHE>;
3805 =item append_fuzzyfiles LASTNAME COMPANY
3809 sub append_fuzzyfiles {
3810 my( $last, $company ) = @_;
3812 &check_and_rebuild_fuzzyfiles;
3814 use Fcntl qw(:flock);
3816 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3820 open(LAST,">>$dir/cust_main.last")
3821 or die "can't open $dir/cust_main.last: $!";
3823 or die "can't lock $dir/cust_main.last: $!";
3825 print LAST "$last\n";
3828 or die "can't unlock $dir/cust_main.last: $!";
3834 open(COMPANY,">>$dir/cust_main.company")
3835 or die "can't open $dir/cust_main.company: $!";
3836 flock(COMPANY,LOCK_EX)
3837 or die "can't lock $dir/cust_main.company: $!";
3839 print COMPANY "$company\n";
3841 flock(COMPANY,LOCK_UN)
3842 or die "can't unlock $dir/cust_main.company: $!";
3856 #warn join('-',keys %$param);
3857 my $fh = $param->{filehandle};
3858 my $agentnum = $param->{agentnum};
3859 my $refnum = $param->{refnum};
3860 my $pkgpart = $param->{pkgpart};
3861 my @fields = @{$param->{fields}};
3863 eval "use Date::Parse;";
3865 eval "use Text::CSV_XS;";
3868 my $csv = new Text::CSV_XS;
3875 local $SIG{HUP} = 'IGNORE';
3876 local $SIG{INT} = 'IGNORE';
3877 local $SIG{QUIT} = 'IGNORE';
3878 local $SIG{TERM} = 'IGNORE';
3879 local $SIG{TSTP} = 'IGNORE';
3880 local $SIG{PIPE} = 'IGNORE';
3882 my $oldAutoCommit = $FS::UID::AutoCommit;
3883 local $FS::UID::AutoCommit = 0;
3886 #while ( $columns = $csv->getline($fh) ) {
3888 while ( defined($line=<$fh>) ) {
3890 $csv->parse($line) or do {
3891 $dbh->rollback if $oldAutoCommit;
3892 return "can't parse: ". $csv->error_input();
3895 my @columns = $csv->fields();
3896 #warn join('-',@columns);
3899 agentnum => $agentnum,
3901 country => $conf->config('countrydefault') || 'US',
3902 payby => 'BILL', #default
3903 paydate => '12/2037', #default
3905 my $billtime = time;
3906 my %cust_pkg = ( pkgpart => $pkgpart );
3907 foreach my $field ( @fields ) {
3908 if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
3909 #$cust_pkg{$1} = str2time( shift @$columns );
3910 if ( $1 eq 'setup' ) {
3911 $billtime = str2time(shift @columns);
3913 $cust_pkg{$1} = str2time( shift @columns );
3916 #$cust_main{$field} = shift @$columns;
3917 $cust_main{$field} = shift @columns;
3921 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
3922 my $cust_main = new FS::cust_main ( \%cust_main );
3924 tie my %hash, 'Tie::RefHash'; #this part is important
3925 $hash{$cust_pkg} = [] if $pkgpart;
3926 my $error = $cust_main->insert( \%hash );
3929 $dbh->rollback if $oldAutoCommit;
3930 return "can't insert customer for $line: $error";
3933 #false laziness w/bill.cgi
3934 $error = $cust_main->bill( 'time' => $billtime );
3936 $dbh->rollback if $oldAutoCommit;
3937 return "can't bill customer for $line: $error";
3940 $cust_main->apply_payments;
3941 $cust_main->apply_credits;
3943 $error = $cust_main->collect();
3945 $dbh->rollback if $oldAutoCommit;
3946 return "can't collect customer for $line: $error";
3952 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3954 return "Empty file!" unless $imported;
3966 #warn join('-',keys %$param);
3967 my $fh = $param->{filehandle};
3968 my @fields = @{$param->{fields}};
3970 eval "use Date::Parse;";
3972 eval "use Text::CSV_XS;";
3975 my $csv = new Text::CSV_XS;
3982 local $SIG{HUP} = 'IGNORE';
3983 local $SIG{INT} = 'IGNORE';
3984 local $SIG{QUIT} = 'IGNORE';
3985 local $SIG{TERM} = 'IGNORE';
3986 local $SIG{TSTP} = 'IGNORE';
3987 local $SIG{PIPE} = 'IGNORE';
3989 my $oldAutoCommit = $FS::UID::AutoCommit;
3990 local $FS::UID::AutoCommit = 0;
3993 #while ( $columns = $csv->getline($fh) ) {
3995 while ( defined($line=<$fh>) ) {
3997 $csv->parse($line) or do {
3998 $dbh->rollback if $oldAutoCommit;
3999 return "can't parse: ". $csv->error_input();
4002 my @columns = $csv->fields();
4003 #warn join('-',@columns);
4006 foreach my $field ( @fields ) {
4007 $row{$field} = shift @columns;
4010 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4011 unless ( $cust_main ) {
4012 $dbh->rollback if $oldAutoCommit;
4013 return "unknown custnum $row{'custnum'}";
4016 if ( $row{'amount'} > 0 ) {
4017 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4019 $dbh->rollback if $oldAutoCommit;
4023 } elsif ( $row{'amount'} < 0 ) {
4024 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4027 $dbh->rollback if $oldAutoCommit;
4037 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4039 return "Empty file!" unless $imported;
4051 The delete method should possibly take an FS::cust_main object reference
4052 instead of a scalar customer number.
4054 Bill and collect options should probably be passed as references instead of a
4057 There should probably be a configuration file with a list of allowed credit
4060 No multiple currency support (probably a larger project than just this module).
4062 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4066 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4067 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4068 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.