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 'DCRD') { # 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 qsearch('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$/ ) {
1636 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1640 $dbh->rollback if $oldAutoCommit;
1641 return "unparsable frequency: ". $part_pkg->freq;
1643 $cust_pkg->setfield('bill',
1644 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1647 warn "\$setup is undefined" unless defined($setup);
1648 warn "\$recur is undefined" unless defined($recur);
1649 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1651 if ( $cust_pkg->modified ) {
1653 warn " package ". $cust_pkg->pkgnum. " modified; updating\n" if $DEBUG;
1655 $error=$cust_pkg->replace($old_cust_pkg);
1656 if ( $error ) { #just in case
1657 $dbh->rollback if $oldAutoCommit;
1658 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1661 $setup = sprintf( "%.2f", $setup );
1662 $recur = sprintf( "%.2f", $recur );
1663 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1664 $dbh->rollback if $oldAutoCommit;
1665 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1667 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1668 $dbh->rollback if $oldAutoCommit;
1669 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1671 if ( $setup != 0 || $recur != 0 ) {
1672 warn " charges (setup=$setup, recur=$recur); queueing line items\n"
1674 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1675 'pkgnum' => $cust_pkg->pkgnum,
1679 'edate' => $cust_pkg->bill,
1680 'details' => \@details,
1682 push @cust_bill_pkg, $cust_bill_pkg;
1683 $total_setup += $setup;
1684 $total_recur += $recur;
1686 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1688 my @taxes = qsearch( 'cust_main_county', {
1689 'state' => $self->state,
1690 'county' => $self->county,
1691 'country' => $self->country,
1692 'taxclass' => $part_pkg->taxclass,
1695 @taxes = qsearch( 'cust_main_county', {
1696 'state' => $self->state,
1697 'county' => $self->county,
1698 'country' => $self->country,
1703 #one more try at a whole-country tax rate
1705 @taxes = qsearch( 'cust_main_county', {
1708 'country' => $self->country,
1713 # maybe eliminate this entirely, along with all the 0% records
1715 $dbh->rollback if $oldAutoCommit;
1717 "fatal: can't find tax rate for state/county/country/taxclass ".
1718 join('/', ( map $self->$_(), qw(state county country) ),
1719 $part_pkg->taxclass ). "\n";
1722 foreach my $tax ( @taxes ) {
1724 my $taxable_charged = 0;
1725 $taxable_charged += $setup
1726 unless $part_pkg->setuptax =~ /^Y$/i
1727 || $tax->setuptax =~ /^Y$/i;
1728 $taxable_charged += $recur
1729 unless $part_pkg->recurtax =~ /^Y$/i
1730 || $tax->recurtax =~ /^Y$/i;
1731 next unless $taxable_charged;
1733 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
1734 my ($mon,$year) = (localtime($sdate) )[4,5];
1736 my $freq = $part_pkg->freq || 1;
1737 if ( $freq !~ /(\d+)$/ ) {
1738 $dbh->rollback if $oldAutoCommit;
1739 return "daily/weekly package definitions not (yet?)".
1740 " compatible with monthly tax exemptions";
1742 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1743 foreach my $which_month ( 1 .. $freq ) {
1745 'custnum' => $self->custnum,
1746 'taxnum' => $tax->taxnum,
1747 'year' => 1900+$year,
1750 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1751 until ( $mon < 13 ) { $mon -= 12; $year++; }
1752 my $cust_tax_exempt =
1753 qsearchs('cust_tax_exempt', \%hash)
1754 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1755 my $remaining_exemption = sprintf("%.2f",
1756 $tax->exempt_amount - $cust_tax_exempt->amount );
1757 if ( $remaining_exemption > 0 ) {
1758 my $addl = $remaining_exemption > $taxable_per_month
1759 ? $taxable_per_month
1760 : $remaining_exemption;
1761 $taxable_charged -= $addl;
1762 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1763 $cust_tax_exempt->hash,
1765 sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1767 $error = $new_cust_tax_exempt->exemptnum
1768 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1769 : $new_cust_tax_exempt->insert;
1771 $dbh->rollback if $oldAutoCommit;
1772 return "fatal: can't update cust_tax_exempt: $error";
1775 } # if $remaining_exemption > 0
1777 } #foreach $which_month
1779 } #if $tax->exempt_amount
1781 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1783 #$tax += $taxable_charged * $cust_main_county->tax / 100
1784 $tax{ $tax->taxname || 'Tax' } +=
1785 $taxable_charged * $tax->tax / 100
1787 } #foreach my $tax ( @taxes )
1789 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
1791 } #if $setup != 0 || $recur != 0
1793 } #if $cust_pkg->modified
1795 } #foreach my $cust_pkg
1797 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1798 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1800 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1801 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1805 # unless ( $self->tax =~ /Y/i
1806 # || $self->payby eq 'COMP'
1807 # || $taxable_charged == 0 ) {
1808 # my $cust_main_county = qsearchs('cust_main_county',{
1809 # 'state' => $self->state,
1810 # 'county' => $self->county,
1811 # 'country' => $self->country,
1812 # } ) or die "fatal: can't find tax rate for state/county/country ".
1813 # $self->state. "/". $self->county. "/". $self->country. "\n";
1814 # my $tax = sprintf( "%.2f",
1815 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1818 if ( dbdef->table('cust_bill_pkg')->column('itemdesc') ) { #1.5 schema
1820 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
1821 my $tax = sprintf("%.2f", $tax{$taxname} );
1822 $charged = sprintf( "%.2f", $charged+$tax );
1824 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1830 'itemdesc' => $taxname,
1832 push @cust_bill_pkg, $cust_bill_pkg;
1835 } else { #1.4 schema
1838 foreach ( values %tax ) { $tax += $_ };
1839 $tax = sprintf("%.2f", $tax);
1841 $charged = sprintf( "%.2f", $charged+$tax );
1843 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1850 push @cust_bill_pkg, $cust_bill_pkg;
1855 my $cust_bill = new FS::cust_bill ( {
1856 'custnum' => $self->custnum,
1858 'charged' => $charged,
1860 $error = $cust_bill->insert;
1862 $dbh->rollback if $oldAutoCommit;
1863 return "can't create invoice for customer #". $self->custnum. ": $error";
1866 my $invnum = $cust_bill->invnum;
1868 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1870 $cust_bill_pkg->invnum($invnum);
1871 $error = $cust_bill_pkg->insert;
1873 $dbh->rollback if $oldAutoCommit;
1874 return "can't create invoice line item for customer #". $self->custnum.
1879 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1883 =item collect OPTIONS
1885 (Attempt to) collect money for this customer's outstanding invoices (see
1886 L<FS::cust_bill>). Usually used after the bill method.
1888 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
1889 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
1890 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
1892 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1893 and the invoice events web interface.
1895 If there is an error, returns the error, otherwise returns false.
1897 Options are passed as name-value pairs.
1899 Currently available options are:
1901 invoice_time - Use this time when deciding when to print invoices and
1902 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>
1903 for conversion functions.
1905 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
1908 retry_card - Deprecated alias for 'retry'
1910 batch_card - This option is deprecated. See the invoice events web interface
1911 to control whether cards are batched or run against a realtime gateway.
1913 report_badcard - This option is deprecated.
1915 force_print - This option is deprecated; see the invoice events web interface.
1917 quiet - set true to surpress email card/ACH decline notices.
1922 my( $self, %options ) = @_;
1923 my $invoice_time = $options{'invoice_time'} || time;
1926 local $SIG{HUP} = 'IGNORE';
1927 local $SIG{INT} = 'IGNORE';
1928 local $SIG{QUIT} = 'IGNORE';
1929 local $SIG{TERM} = 'IGNORE';
1930 local $SIG{TSTP} = 'IGNORE';
1931 local $SIG{PIPE} = 'IGNORE';
1933 my $oldAutoCommit = $FS::UID::AutoCommit;
1934 local $FS::UID::AutoCommit = 0;
1937 $self->select_for_update; #mutex
1939 my $balance = $self->balance;
1940 warn "collect customer ". $self->custnum. ": balance $balance\n" if $DEBUG;
1941 unless ( $balance > 0 ) { #redundant?????
1942 $dbh->rollback if $oldAutoCommit; #hmm
1946 if ( exists($options{'retry_card'}) ) {
1947 carp 'retry_card option passed to collect is deprecated; use retry';
1948 $options{'retry'} ||= $options{'retry_card'};
1950 if ( exists($options{'retry'}) && $options{'retry'} ) {
1951 my $error = $self->retry_realtime;
1953 $dbh->rollback if $oldAutoCommit;
1958 foreach my $cust_bill ( $self->open_cust_bill ) {
1960 # don't try to charge for the same invoice if it's already in a batch
1961 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1963 last if $self->balance <= 0;
1965 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
1968 foreach my $part_bill_event (
1969 sort { $a->seconds <=> $b->seconds
1970 || $a->weight <=> $b->weight
1971 || $a->eventpart <=> $b->eventpart }
1972 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1973 && ! qsearch( 'cust_bill_event', {
1974 'invnum' => $cust_bill->invnum,
1975 'eventpart' => $_->eventpart,
1979 qsearch('part_bill_event', { 'payby' => $self->payby,
1980 'disabled' => '', } )
1983 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
1984 || $self->balance <= 0; # or if balance<=0
1986 warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1988 my $cust_main = $self; #for callback
1992 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
1993 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
1994 $error = eval $part_bill_event->eventcode;
1998 my $statustext = '';
2002 } elsif ( $error ) {
2004 $statustext = $error;
2009 #add cust_bill_event
2010 my $cust_bill_event = new FS::cust_bill_event {
2011 'invnum' => $cust_bill->invnum,
2012 'eventpart' => $part_bill_event->eventpart,
2013 #'_date' => $invoice_time,
2015 'status' => $status,
2016 'statustext' => $statustext,
2018 $error = $cust_bill_event->insert;
2020 #$dbh->rollback if $oldAutoCommit;
2021 #return "error: $error";
2023 # gah, even with transactions.
2024 $dbh->commit if $oldAutoCommit; #well.
2025 my $e = 'WARNING: Event run but database not updated - '.
2026 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
2027 ', eventpart '. $part_bill_event->eventpart.
2038 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2043 =item retry_realtime
2045 Schedules realtime credit card / electronic check / LEC billing events for
2046 for retry. Useful if card information has changed or manual retry is desired.
2047 The 'collect' method must be called to actually retry the transaction.
2049 Implementation details: For each of this customer's open invoices, changes
2050 the status of the first "done" (with statustext error) realtime processing
2055 sub retry_realtime {
2058 local $SIG{HUP} = 'IGNORE';
2059 local $SIG{INT} = 'IGNORE';
2060 local $SIG{QUIT} = 'IGNORE';
2061 local $SIG{TERM} = 'IGNORE';
2062 local $SIG{TSTP} = 'IGNORE';
2063 local $SIG{PIPE} = 'IGNORE';
2065 my $oldAutoCommit = $FS::UID::AutoCommit;
2066 local $FS::UID::AutoCommit = 0;
2069 foreach my $cust_bill (
2070 grep { $_->cust_bill_event }
2071 $self->open_cust_bill
2073 my @cust_bill_event =
2074 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2076 #$_->part_bill_event->plan eq 'realtime-card'
2077 $_->part_bill_event->eventcode =~
2078 /\$cust_bill\->realtime_(card|ach|lec)/
2079 && $_->status eq 'done'
2082 $cust_bill->cust_bill_event;
2083 next unless @cust_bill_event;
2084 my $error = $cust_bill_event[0]->retry;
2086 $dbh->rollback if $oldAutoCommit;
2087 return "error scheduling invoice event for retry: $error";
2092 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2097 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2099 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2100 via a Business::OnlinePayment realtime gateway. See
2101 L<http://420.am/business-onlinepayment> for supported gateways.
2103 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2105 Available options are: I<description>, I<invnum>, I<quiet>
2107 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2108 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2109 if set, will override the value from the customer record.
2111 I<description> is a free-text field passed to the gateway. It defaults to
2112 "Internet services".
2114 If an I<invnum> is specified, this payment (if sucessful) is applied to the
2115 specified invoice. If you don't specify an I<invnum> you might want to
2116 call the B<apply_payments> method.
2118 I<quiet> can be set true to surpress email decline notices.
2120 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2125 my( $self, $method, $amount, %options ) = @_;
2127 warn "$self $method $amount\n";
2128 warn " $_ => $options{$_}\n" foreach keys %options;
2131 $options{'description'} ||= 'Internet services';
2133 eval "use Business::OnlinePayment";
2136 my $payinfo = exists($options{'payinfo'})
2137 ? $options{'payinfo'}
2145 if ( $options{'invnum'} ) {
2146 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2147 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2149 map { $_->part_pkg->taxclass }
2151 map { $_->cust_pkg }
2152 $cust_bill->cust_bill_pkg;
2153 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2154 #different taxclasses
2155 $taxclass = $taxclasses[0];
2159 #look for an agent gateway override first
2161 if ( $method eq 'CC' ) {
2162 $cardtype = cardtype($payinfo);
2163 } elsif ( $method eq 'ECHECK' ) {
2166 $cardtype = $method;
2170 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2171 cardtype => $cardtype,
2172 taxclass => $taxclass, } )
2173 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2175 taxclass => $taxclass, } )
2176 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2177 cardtype => $cardtype,
2179 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2181 taxclass => '', } );
2183 my $payment_gateway = '';
2184 my( $processor, $login, $password, $action, @bop_options );
2185 if ( $override ) { #use a payment gateway override
2187 $payment_gateway = $override->payment_gateway;
2189 $processor = $payment_gateway->gateway_module;
2190 $login = $payment_gateway->gateway_username;
2191 $password = $payment_gateway->gateway_password;
2192 $action = $payment_gateway->gateway_action;
2193 @bop_options = $payment_gateway->options;
2195 } else { #use the standard settings from the config
2197 ( $processor, $login, $password, $action, @bop_options ) =
2198 $self->default_payment_gateway($method);
2206 my $address = exists($options{'address1'})
2207 ? $options{'address1'}
2209 my $address2 = exists($options{'address2'})
2210 ? $options{'address2'}
2212 $address .= ", ". $address2 if length($address2);
2214 my $o_payname = exists($options{'payname'})
2215 ? $options{'payname'}
2217 my($payname, $payfirst, $paylast);
2218 if ( $o_payname && $method ne 'ECHECK' ) {
2219 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2220 or return "Illegal payname $payname";
2221 ($payfirst, $paylast) = ($1, $2);
2223 $payfirst = $self->getfield('first');
2224 $paylast = $self->getfield('last');
2225 $payname = "$payfirst $paylast";
2228 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2229 if ( $conf->exists('emailinvoiceauto')
2230 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2231 push @invoicing_list, $self->all_emails;
2234 my $email = ($conf->exists('business-onlinepayment-email-override'))
2235 ? $conf->config('business-onlinepayment-email-override')
2236 : $invoicing_list[0];
2239 if ( $method eq 'CC' ) {
2241 $content{card_number} = $payinfo;
2242 my $paydate = exists($options{'paydate'})
2243 ? $options{'paydate'}
2245 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2246 $content{expiration} = "$2/$1";
2248 my $paycvv = exists($options{'paycvv'})
2249 ? $options{'paycvv'}
2251 $content{cvv2} = $self->paycvv
2254 my $paystart_month = exists($options{'paystart_month'})
2255 ? $options{'paystart_month'}
2256 : $self->paystart_month;
2258 my $paystart_year = exists($options{'paystart_year'})
2259 ? $options{'paystart_year'}
2260 : $self->paystart_year;
2262 $content{card_start} = "$paystart_month/$paystart_year"
2263 if $paystart_month && $paystart_year;
2265 my $payissue = exists($options{'payissue'})
2266 ? $options{'payissue'}
2268 $content{issue_number} = $payissue if $payissue;
2270 my $payip = exists($options{'payip'})
2273 $content{customer_ip} = $payip
2276 $content{recurring_billing} = 'YES'
2277 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2279 'payinfo' => $payinfo,
2282 } elsif ( $method eq 'ECHECK' ) {
2283 ( $content{account_number}, $content{routing_code} ) =
2284 split('@', $payinfo);
2285 $content{bank_name} = $o_payname;
2286 $content{account_type} = 'CHECKING';
2287 $content{account_name} = $payname;
2288 $content{customer_org} = $self->company ? 'B' : 'I';
2289 $content{customer_ssn} = exists($options{'ss'})
2292 } elsif ( $method eq 'LEC' ) {
2293 $content{phone} = $payinfo;
2297 # run transaction(s)
2300 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2302 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2303 $transaction->content(
2306 'password' => $password,
2307 'action' => $action1,
2308 'description' => $options{'description'},
2309 'amount' => $amount,
2310 'invoice_number' => $options{'invnum'},
2311 'customer_id' => $self->custnum,
2312 'last_name' => $paylast,
2313 'first_name' => $payfirst,
2315 'address' => $address,
2316 'city' => ( exists($options{'city'})
2319 'state' => ( exists($options{'state'})
2322 'zip' => ( exists($options{'zip'})
2325 'country' => ( exists($options{'country'})
2326 ? $options{'country'}
2328 'referer' => 'http://cleanwhisker.420.am/',
2330 'phone' => $self->daytime || $self->night,
2333 $transaction->submit();
2335 if ( $transaction->is_success() && $action2 ) {
2336 my $auth = $transaction->authorization;
2337 my $ordernum = $transaction->can('order_number')
2338 ? $transaction->order_number
2342 new Business::OnlinePayment( $processor, @bop_options );
2349 password => $password,
2350 order_number => $ordernum,
2352 authorization => $auth,
2353 description => $options{'description'},
2356 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2357 transaction_sequence_num local_transaction_date
2358 local_transaction_time AVS_result_code )) {
2359 $capture{$field} = $transaction->$field() if $transaction->can($field);
2362 $capture->content( %capture );
2366 unless ( $capture->is_success ) {
2367 my $e = "Authorization sucessful but capture failed, custnum #".
2368 $self->custnum. ': '. $capture->result_code.
2369 ": ". $capture->error_message;
2377 # remove paycvv after initial transaction
2380 #false laziness w/misc/process/payment.cgi - check both to make sure working
2382 if ( defined $self->dbdef_table->column('paycvv')
2383 && length($self->paycvv)
2384 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2386 my $error = $self->remove_cvv;
2388 warn "error removing cvv: $error\n";
2396 if ( $transaction->is_success() ) {
2398 my %method2payby = (
2405 if ( $payment_gateway ) { # agent override
2406 $paybatch = $payment_gateway->gatewaynum. '-';
2409 $paybatch .= "$processor:". $transaction->authorization;
2411 $paybatch .= ':'. $transaction->order_number
2412 if $transaction->can('order_number')
2413 && length($transaction->order_number);
2415 my $cust_pay = new FS::cust_pay ( {
2416 'custnum' => $self->custnum,
2417 'invnum' => $options{'invnum'},
2420 'payby' => $method2payby{$method},
2421 'payinfo' => $payinfo,
2422 'paybatch' => $paybatch,
2424 my $error = $cust_pay->insert;
2426 $cust_pay->invnum(''); #try again with no specific invnum
2427 my $error2 = $cust_pay->insert;
2429 # gah, even with transactions.
2430 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2431 "error inserting payment ($processor): $error2".
2432 " (previously tried insert with invnum #$options{'invnum'}" .
2438 return ''; #no error
2442 my $perror = "$processor error: ". $transaction->error_message;
2444 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2445 && $conf->exists('emaildecline')
2446 && grep { $_ ne 'POST' } $self->invoicing_list
2447 && ! grep { $transaction->error_message =~ /$_/ }
2448 $conf->config('emaildecline-exclude')
2450 my @templ = $conf->config('declinetemplate');
2451 my $template = new Text::Template (
2453 SOURCE => [ map "$_\n", @templ ],
2454 ) or return "($perror) can't create template: $Text::Template::ERROR";
2455 $template->compile()
2456 or return "($perror) can't compile template: $Text::Template::ERROR";
2458 my $templ_hash = { error => $transaction->error_message };
2460 my $error = send_email(
2461 'from' => $conf->config('invoice_from'),
2462 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2463 'subject' => 'Your payment could not be processed',
2464 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2467 $perror .= " (also received error sending decline notification: $error)"
2477 =item default_payment_gateway
2481 sub default_payment_gateway {
2482 my( $self, $method ) = @_;
2484 die "Real-time processing not enabled\n"
2485 unless $conf->exists('business-onlinepayment');
2488 my $bop_config = 'business-onlinepayment';
2489 $bop_config .= '-ach'
2490 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2491 my ( $processor, $login, $password, $action, @bop_options ) =
2492 $conf->config($bop_config);
2493 $action ||= 'normal authorization';
2494 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2495 die "No real-time processor is enabled - ".
2496 "did you set the business-onlinepayment configuration value?\n"
2499 ( $processor, $login, $password, $action, @bop_options )
2504 Removes the I<paycvv> field from the database directly.
2506 If there is an error, returns the error, otherwise returns false.
2512 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2513 or return dbh->errstr;
2514 $sth->execute($self->custnum)
2515 or return $sth->errstr;
2520 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2522 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2523 via a Business::OnlinePayment realtime gateway. See
2524 L<http://420.am/business-onlinepayment> for supported gateways.
2526 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2528 Available options are: I<amount>, I<reason>, I<paynum>
2530 Most gateways require a reference to an original payment transaction to refund,
2531 so you probably need to specify a I<paynum>.
2533 I<amount> defaults to the original amount of the payment if not specified.
2535 I<reason> specifies a reason for the refund.
2537 Implementation note: If I<amount> is unspecified or equal to the amount of the
2538 orignal payment, first an attempt is made to "void" the transaction via
2539 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2540 the normal attempt is made to "refund" ("credit") the transaction via the
2541 gateway is attempted.
2543 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2544 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2545 #if set, will override the value from the customer record.
2547 #If an I<invnum> is specified, this payment (if sucessful) is applied to the
2548 #specified invoice. If you don't specify an I<invnum> you might want to
2549 #call the B<apply_payments> method.
2553 #some false laziness w/realtime_bop, not enough to make it worth merging
2554 #but some useful small subs should be pulled out
2555 sub realtime_refund_bop {
2556 my( $self, $method, %options ) = @_;
2558 warn "$self $method refund\n";
2559 warn " $_ => $options{$_}\n" foreach keys %options;
2562 eval "use Business::OnlinePayment";
2566 # look up the original payment and optionally a gateway for that payment
2570 my $amount = $options{'amount'};
2572 my( $processor, $login, $password, @bop_options ) ;
2573 my( $auth, $order_number ) = ( '', '', '' );
2575 if ( $options{'paynum'} ) {
2577 warn "FS::cust_main::realtime_bop: paynum: $options{paynum}\n" if $DEBUG;
2578 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2579 or return "Unknown paynum $options{'paynum'}";
2580 $amount ||= $cust_pay->paid;
2582 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2583 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2584 $cust_pay->paybatch;
2585 my $gatewaynum = '';
2586 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2588 if ( $gatewaynum ) { #gateway for the payment to be refunded
2590 my $payment_gateway =
2591 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2592 die "payment gateway $gatewaynum not found"
2593 unless $payment_gateway;
2595 $processor = $payment_gateway->gateway_module;
2596 $login = $payment_gateway->gateway_username;
2597 $password = $payment_gateway->gateway_password;
2598 @bop_options = $payment_gateway->options;
2600 } else { #try the default gateway
2602 my( $conf_processor, $unused_action );
2603 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2604 $self->default_payment_gateway($method);
2606 return "processor of payment $options{'paynum'} $processor does not".
2607 " match default processor $conf_processor"
2608 unless $processor eq $conf_processor;
2613 } else { # didn't specify a paynum, so look for agent gateway overrides
2614 # like a normal transaction
2617 if ( $method eq 'CC' ) {
2618 $cardtype = cardtype($self->payinfo);
2619 } elsif ( $method eq 'ECHECK' ) {
2622 $cardtype = $method;
2625 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2626 cardtype => $cardtype,
2628 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2630 taxclass => '', } );
2632 if ( $override ) { #use a payment gateway override
2634 my $payment_gateway = $override->payment_gateway;
2636 $processor = $payment_gateway->gateway_module;
2637 $login = $payment_gateway->gateway_username;
2638 $password = $payment_gateway->gateway_password;
2639 #$action = $payment_gateway->gateway_action;
2640 @bop_options = $payment_gateway->options;
2642 } else { #use the standard settings from the config
2645 ( $processor, $login, $password, $unused_action, @bop_options ) =
2646 $self->default_payment_gateway($method);
2651 return "neither amount nor paynum specified" unless $amount;
2656 'password' => $password,
2657 'order_number' => $order_number,
2658 'amount' => $amount,
2659 'referer' => 'http://cleanwhisker.420.am/',
2661 $content{authorization} = $auth
2662 if length($auth); #echeck/ACH transactions have an order # but no auth
2663 #(at least with authorize.net)
2665 #first try void if applicable
2666 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2667 warn "FS::cust_main::realtime_bop: attempting void\n" if $DEBUG;
2668 my $void = new Business::OnlinePayment( $processor, @bop_options );
2669 $void->content( 'action' => 'void', %content );
2671 if ( $void->is_success ) {
2672 my $error = $cust_pay->void($options{'reason'});
2674 # gah, even with transactions.
2675 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2676 "error voiding payment: $error";
2680 warn "FS::cust_main::realtime_bop: void successful\n" if $DEBUG;
2685 warn "FS::cust_main::realtime_bop: void unsuccessful, trying refund\n"
2689 my $address = $self->address1;
2690 $address .= ", ". $self->address2 if $self->address2;
2692 my($payname, $payfirst, $paylast);
2693 if ( $self->payname && $method ne 'ECHECK' ) {
2694 $payname = $self->payname;
2695 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2696 or return "Illegal payname $payname";
2697 ($payfirst, $paylast) = ($1, $2);
2699 $payfirst = $self->getfield('first');
2700 $paylast = $self->getfield('last');
2701 $payname = "$payfirst $paylast";
2705 if ( $method eq 'CC' ) {
2708 $content{card_number} = $payinfo = $cust_pay->payinfo;
2709 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2710 #$content{expiration} = "$2/$1";
2712 $content{card_number} = $payinfo = $self->payinfo;
2713 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2714 $content{expiration} = "$2/$1";
2717 } elsif ( $method eq 'ECHECK' ) {
2718 ( $content{account_number}, $content{routing_code} ) =
2719 split('@', $payinfo = $self->payinfo);
2720 $content{bank_name} = $self->payname;
2721 $content{account_type} = 'CHECKING';
2722 $content{account_name} = $payname;
2723 $content{customer_org} = $self->company ? 'B' : 'I';
2724 $content{customer_ssn} = $self->ss;
2725 } elsif ( $method eq 'LEC' ) {
2726 $content{phone} = $payinfo = $self->payinfo;
2730 my $refund = new Business::OnlinePayment( $processor, @bop_options );
2731 my %sub_content = $refund->content(
2732 'action' => 'credit',
2733 'customer_id' => $self->custnum,
2734 'last_name' => $paylast,
2735 'first_name' => $payfirst,
2737 'address' => $address,
2738 'city' => $self->city,
2739 'state' => $self->state,
2740 'zip' => $self->zip,
2741 'country' => $self->country,
2744 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
2748 return "$processor error: ". $refund->error_message
2749 unless $refund->is_success();
2751 my %method2payby = (
2757 my $paybatch = "$processor:". $refund->authorization;
2758 $paybatch .= ':'. $refund->order_number
2759 if $refund->can('order_number') && $refund->order_number;
2761 while ( $cust_pay && $cust_pay->unappled < $amount ) {
2762 my @cust_bill_pay = $cust_pay->cust_bill_pay;
2763 last unless @cust_bill_pay;
2764 my $cust_bill_pay = pop @cust_bill_pay;
2765 my $error = $cust_bill_pay->delete;
2769 my $cust_refund = new FS::cust_refund ( {
2770 'custnum' => $self->custnum,
2771 'paynum' => $options{'paynum'},
2772 'refund' => $amount,
2774 'payby' => $method2payby{$method},
2775 'payinfo' => $payinfo,
2776 'paybatch' => $paybatch,
2777 'reason' => $options{'reason'} || 'card or ACH refund',
2779 my $error = $cust_refund->insert;
2781 $cust_refund->paynum(''); #try again with no specific paynum
2782 my $error2 = $cust_refund->insert;
2784 # gah, even with transactions.
2785 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
2786 "error inserting refund ($processor): $error2".
2787 " (previously tried insert with paynum #$options{'paynum'}" .
2800 Returns the total owed for this customer on all invoices
2801 (see L<FS::cust_bill/owed>).
2807 $self->total_owed_date(2145859200); #12/31/2037
2810 =item total_owed_date TIME
2812 Returns the total owed for this customer on all invoices with date earlier than
2813 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2814 see L<Time::Local> and L<Date::Parse> for conversion functions.
2818 sub total_owed_date {
2822 foreach my $cust_bill (
2823 grep { $_->_date <= $time }
2824 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2826 $total_bill += $cust_bill->owed;
2828 sprintf( "%.2f", $total_bill );
2831 =item apply_credits OPTION => VALUE ...
2833 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2834 to outstanding invoice balances in chronological order (or reverse
2835 chronological order if the I<order> option is set to B<newest>) and returns the
2836 value of any remaining unapplied credits available for refund (see
2837 L<FS::cust_refund>).
2845 return 0 unless $self->total_credited;
2847 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2848 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2850 my @invoices = $self->open_cust_bill;
2851 @invoices = sort { $b->_date <=> $a->_date } @invoices
2852 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2855 foreach my $cust_bill ( @invoices ) {
2858 if ( !defined($credit) || $credit->credited == 0) {
2859 $credit = pop @credits or last;
2862 if ($cust_bill->owed >= $credit->credited) {
2863 $amount=$credit->credited;
2865 $amount=$cust_bill->owed;
2868 my $cust_credit_bill = new FS::cust_credit_bill ( {
2869 'crednum' => $credit->crednum,
2870 'invnum' => $cust_bill->invnum,
2871 'amount' => $amount,
2873 my $error = $cust_credit_bill->insert;
2874 die $error if $error;
2876 redo if ($cust_bill->owed > 0);
2880 return $self->total_credited;
2883 =item apply_payments
2885 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2886 to outstanding invoice balances in chronological order.
2888 #and returns the value of any remaining unapplied payments.
2892 sub apply_payments {
2897 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
2898 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
2900 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
2901 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
2905 foreach my $cust_bill ( @invoices ) {
2908 if ( !defined($payment) || $payment->unapplied == 0 ) {
2909 $payment = pop @payments or last;
2912 if ( $cust_bill->owed >= $payment->unapplied ) {
2913 $amount = $payment->unapplied;
2915 $amount = $cust_bill->owed;
2918 my $cust_bill_pay = new FS::cust_bill_pay ( {
2919 'paynum' => $payment->paynum,
2920 'invnum' => $cust_bill->invnum,
2921 'amount' => $amount,
2923 my $error = $cust_bill_pay->insert;
2924 die $error if $error;
2926 redo if ( $cust_bill->owed > 0);
2930 return $self->total_unapplied_payments;
2933 =item total_credited
2935 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2936 customer. See L<FS::cust_credit/credited>.
2940 sub total_credited {
2942 my $total_credit = 0;
2943 foreach my $cust_credit ( qsearch('cust_credit', {
2944 'custnum' => $self->custnum,
2946 $total_credit += $cust_credit->credited;
2948 sprintf( "%.2f", $total_credit );
2951 =item total_unapplied_payments
2953 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2954 See L<FS::cust_pay/unapplied>.
2958 sub total_unapplied_payments {
2960 my $total_unapplied = 0;
2961 foreach my $cust_pay ( qsearch('cust_pay', {
2962 'custnum' => $self->custnum,
2964 $total_unapplied += $cust_pay->unapplied;
2966 sprintf( "%.2f", $total_unapplied );
2971 Returns the balance for this customer (total_owed minus total_credited
2972 minus total_unapplied_payments).
2979 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
2983 =item balance_date TIME
2985 Returns the balance for this customer, only considering invoices with date
2986 earlier than TIME (total_owed_date minus total_credited minus
2987 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2988 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2997 $self->total_owed_date($time)
2998 - $self->total_credited
2999 - $self->total_unapplied_payments
3003 =item paydate_monthyear
3005 Returns a two-element list consisting of the month and year of this customer's
3006 paydate (credit card expiration date for CARD customers)
3010 sub paydate_monthyear {
3012 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3014 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3021 =item payinfo_masked
3023 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.
3025 Credit Cards - Mask all but the last four characters.
3026 Checks - Mask all but last 2 of account number and bank routing number.
3027 Others - Do nothing, return the unmasked string.
3031 sub payinfo_masked {
3033 return $self->paymask;
3036 =item invoicing_list [ ARRAYREF ]
3038 If an arguement is given, sets these email addresses as invoice recipients
3039 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3040 (except as warnings), so use check_invoicing_list first.
3042 Returns a list of email addresses (with svcnum entries expanded).
3044 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3045 check it without disturbing anything by passing nothing.
3047 This interface may change in the future.
3051 sub invoicing_list {
3052 my( $self, $arrayref ) = @_;
3054 my @cust_main_invoice;
3055 if ( $self->custnum ) {
3056 @cust_main_invoice =
3057 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3059 @cust_main_invoice = ();
3061 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3062 #warn $cust_main_invoice->destnum;
3063 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3064 #warn $cust_main_invoice->destnum;
3065 my $error = $cust_main_invoice->delete;
3066 warn $error if $error;
3069 if ( $self->custnum ) {
3070 @cust_main_invoice =
3071 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3073 @cust_main_invoice = ();
3075 my %seen = map { $_->address => 1 } @cust_main_invoice;
3076 foreach my $address ( @{$arrayref} ) {
3077 next if exists $seen{$address} && $seen{$address};
3078 $seen{$address} = 1;
3079 my $cust_main_invoice = new FS::cust_main_invoice ( {
3080 'custnum' => $self->custnum,
3083 my $error = $cust_main_invoice->insert;
3084 warn $error if $error;
3087 if ( $self->custnum ) {
3089 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3095 =item check_invoicing_list ARRAYREF
3097 Checks these arguements as valid input for the invoicing_list method. If there
3098 is an error, returns the error, otherwise returns false.
3102 sub check_invoicing_list {
3103 my( $self, $arrayref ) = @_;
3104 foreach my $address ( @{$arrayref} ) {
3106 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3107 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3110 my $cust_main_invoice = new FS::cust_main_invoice ( {
3111 'custnum' => $self->custnum,
3114 my $error = $self->custnum
3115 ? $cust_main_invoice->check
3116 : $cust_main_invoice->checkdest
3118 return $error if $error;
3123 =item set_default_invoicing_list
3125 Sets the invoicing list to all accounts associated with this customer,
3126 overwriting any previous invoicing list.
3130 sub set_default_invoicing_list {
3132 $self->invoicing_list($self->all_emails);
3137 Returns the email addresses of all accounts provisioned for this customer.
3144 foreach my $cust_pkg ( $self->all_pkgs ) {
3145 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3147 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3148 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3150 $list{$_}=1 foreach map { $_->email } @svc_acct;
3155 =item invoicing_list_addpost
3157 Adds postal invoicing to this customer. If this customer is already configured
3158 to receive postal invoices, does nothing.
3162 sub invoicing_list_addpost {
3164 return if grep { $_ eq 'POST' } $self->invoicing_list;
3165 my @invoicing_list = $self->invoicing_list;
3166 push @invoicing_list, 'POST';
3167 $self->invoicing_list(\@invoicing_list);
3170 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3172 Returns an array of customers referred by this customer (referral_custnum set
3173 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3174 customers referred by customers referred by this customer and so on, inclusive.
3175 The default behavior is DEPTH 1 (no recursion).
3179 sub referral_cust_main {
3181 my $depth = @_ ? shift : 1;
3182 my $exclude = @_ ? shift : {};
3185 map { $exclude->{$_->custnum}++; $_; }
3186 grep { ! $exclude->{ $_->custnum } }
3187 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3191 map { $_->referral_cust_main($depth-1, $exclude) }
3198 =item referral_cust_main_ncancelled
3200 Same as referral_cust_main, except only returns customers with uncancelled
3205 sub referral_cust_main_ncancelled {
3207 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3210 =item referral_cust_pkg [ DEPTH ]
3212 Like referral_cust_main, except returns a flat list of all unsuspended (and
3213 uncancelled) packages for each customer. The number of items in this list may
3214 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3218 sub referral_cust_pkg {
3220 my $depth = @_ ? shift : 1;
3222 map { $_->unsuspended_pkgs }
3223 grep { $_->unsuspended_pkgs }
3224 $self->referral_cust_main($depth);
3227 =item referring_cust_main
3229 Returns the single cust_main record for the customer who referred this customer
3230 (referral_custnum), or false.
3234 sub referring_cust_main {
3236 return '' unless $self->referral_custnum;
3237 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3240 =item credit AMOUNT, REASON
3242 Applies a credit to this customer. If there is an error, returns the error,
3243 otherwise returns false.
3248 my( $self, $amount, $reason ) = @_;
3249 my $cust_credit = new FS::cust_credit {
3250 'custnum' => $self->custnum,
3251 'amount' => $amount,
3252 'reason' => $reason,
3254 $cust_credit->insert;
3257 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3259 Creates a one-time charge for this customer. If there is an error, returns
3260 the error, otherwise returns false.
3265 my ( $self, $amount ) = ( shift, shift );
3266 my $pkg = @_ ? shift : 'One-time charge';
3267 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3268 my $taxclass = @_ ? shift : '';
3270 local $SIG{HUP} = 'IGNORE';
3271 local $SIG{INT} = 'IGNORE';
3272 local $SIG{QUIT} = 'IGNORE';
3273 local $SIG{TERM} = 'IGNORE';
3274 local $SIG{TSTP} = 'IGNORE';
3275 local $SIG{PIPE} = 'IGNORE';
3277 my $oldAutoCommit = $FS::UID::AutoCommit;
3278 local $FS::UID::AutoCommit = 0;
3281 my $part_pkg = new FS::part_pkg ( {
3283 'comment' => $comment,
3284 #'setup' => $amount,
3287 'plandata' => "setup_fee=$amount",
3290 'taxclass' => $taxclass,
3293 my $error = $part_pkg->insert;
3295 $dbh->rollback if $oldAutoCommit;
3299 my $pkgpart = $part_pkg->pkgpart;
3300 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3301 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3302 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3303 $error = $type_pkgs->insert;
3305 $dbh->rollback if $oldAutoCommit;
3310 my $cust_pkg = new FS::cust_pkg ( {
3311 'custnum' => $self->custnum,
3312 'pkgpart' => $pkgpart,
3315 $error = $cust_pkg->insert;
3317 $dbh->rollback if $oldAutoCommit;
3321 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3328 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3334 sort { $a->_date <=> $b->_date }
3335 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3338 =item open_cust_bill
3340 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3345 sub open_cust_bill {
3347 grep { $_->owed > 0 } $self->cust_bill;
3352 Returns all the credits (see L<FS::cust_credit>) for this customer.
3358 sort { $a->_date <=> $b->_date }
3359 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3364 Returns all the payments (see L<FS::cust_pay>) for this customer.
3370 sort { $a->_date <=> $b->_date }
3371 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3376 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3382 sort { $a->_date <=> $b->_date }
3383 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3389 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3395 sort { $a->_date <=> $b->_date }
3396 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3399 =item select_for_update
3401 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3406 sub select_for_update {
3408 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3413 Returns a name string for this customer, either "Company (Last, First)" or
3420 my $name = $self->contact;
3421 $name = $self->company. " ($name)" if $self->company;
3427 Returns a name string for this (service/shipping) contact, either
3428 "Company (Last, First)" or "Last, First".
3434 if ( $self->get('ship_last') ) {
3435 my $name = $self->ship_contact;
3436 $name = $self->ship_company. " ($name)" if $self->ship_company;
3445 Returns this customer's full (billing) contact name only, "Last, First"
3451 $self->get('last'). ', '. $self->first;
3456 Returns this customer's full (shipping) contact name only, "Last, First"
3462 $self->get('ship_last')
3463 ? $self->get('ship_last'). ', '. $self->ship_first
3469 Returns a status string for this customer, currently:
3473 =item prospect - No packages have ever been ordered
3475 =item active - One or more recurring packages is active
3477 =item suspended - All non-cancelled recurring packages are suspended
3479 =item cancelled - All recurring packages are cancelled
3487 for my $status (qw( prospect active suspended cancelled )) {
3488 my $method = $status.'_sql';
3489 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3490 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3491 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3492 return $status if $sth->fetchrow_arrayref->[0];
3498 Returns a hex triplet color string for this customer's status.
3503 'prospect' => '000000',
3504 'active' => '00CC00',
3505 'suspended' => 'FF9900',
3506 'cancelled' => 'FF0000',
3510 $statuscolor{$self->status};
3515 =head1 CLASS METHODS
3521 Returns an SQL expression identifying prospective cust_main records (customers
3522 with no packages ever ordered)
3526 sub prospect_sql { "
3527 0 = ( SELECT COUNT(*) FROM cust_pkg
3528 WHERE cust_pkg.custnum = cust_main.custnum
3534 Returns an SQL expression identifying active cust_main records.
3539 0 < ( SELECT COUNT(*) FROM cust_pkg
3540 WHERE cust_pkg.custnum = cust_main.custnum
3541 AND ". FS::cust_pkg->active_sql. "
3548 Returns an SQL expression identifying suspended cust_main records.
3552 #my $recurring_sql = FS::cust_pkg->recurring_sql;
3553 my $recurring_sql = "
3554 '0' != ( select freq from part_pkg
3555 where cust_pkg.pkgpart = part_pkg.pkgpart )
3558 sub suspended_sql { susp_sql(@_); }
3560 0 < ( SELECT COUNT(*) FROM cust_pkg
3561 WHERE cust_pkg.custnum = cust_main.custnum
3563 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3565 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3566 WHERE cust_pkg.custnum = cust_main.custnum
3567 AND ". FS::cust_pkg->active_sql. "
3574 Returns an SQL expression identifying cancelled cust_main records.
3578 sub cancelled_sql { cancel_sql(@_); }
3580 0 < ( SELECT COUNT(*) FROM cust_pkg
3581 WHERE cust_pkg.custnum = cust_main.custnum
3583 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3584 WHERE cust_pkg.custnum = cust_main.custnum
3586 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3590 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3592 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3593 records. Currently, only I<last> or I<company> may be specified (the
3594 appropriate ship_ field is also searched if applicable).
3596 Additional options are the same as FS::Record::qsearch
3601 my( $self, $fuzzy, $hash, @opt) = @_;
3606 check_and_rebuild_fuzzyfiles();
3607 foreach my $field ( keys %$fuzzy ) {
3608 my $sub = \&{"all_$field"};
3610 $match{$_}=1 foreach ( amatch($fuzzy->{$field}, ['i'], @{ &$sub() } ) );
3612 foreach ( keys %match ) {
3613 push @cust_main, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3614 push @cust_main, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt)
3615 if defined dbdef->table('cust_main')->column('ship_last');
3620 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
3632 =item smart_search OPTION => VALUE ...
3634 Accepts the following options: I<search>, the string to search for. The string
3635 will be searched for as a customer number, last name or company name, first
3636 searching for an exact match then fuzzy and substring matches.
3638 Any additional options treated as an additional qualifier on the search
3641 Returns a (possibly empty) array of FS::cust_main objects.
3647 my $search = delete $options{'search'};
3650 if ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
3652 push @cust_main, qsearch('cust_main', { 'custnum' => $1, %options } );
3654 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { #value search
3657 my $q_value = dbh->quote($value);
3660 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
3661 $sql .= " ( LOWER(last) = $q_value OR LOWER(company) = $q_value";
3662 $sql .= " OR LOWER(ship_last) = $q_value OR LOWER(ship_company) = $q_value"
3663 if defined dbdef->table('cust_main')->column('ship_last');
3666 push @cust_main, qsearch( 'cust_main', \%options, '', $sql );
3668 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
3670 #still some false laziness w/ search/cust_main.cgi
3673 push @cust_main, qsearch( 'cust_main',
3674 { 'last' => { 'op' => 'ILIKE',
3675 'value' => "%$q_value%" },
3679 push @cust_main, qsearch( 'cust_main',
3680 { 'ship_last' => { 'op' => 'ILIKE',
3681 'value' => "%$q_value%" },
3686 if defined dbdef->table('cust_main')->column('ship_last');
3688 push @cust_main, qsearch( 'cust_main',
3689 { 'company' => { 'op' => 'ILIKE',
3690 'value' => "%$q_value%" },
3694 push @cust_main, qsearch( 'cust_main',
3695 { 'ship_company' => { 'op' => 'ILIKE',
3696 'value' => "%$q_value%" },
3700 if defined dbdef->table('cust_main')->column('ship_last');
3703 push @cust_main, FS::cust_main->fuzzy_search(
3704 { 'last' => $value },
3707 push @cust_main, FS::cust_main->fuzzy_search(
3708 { 'company' => $value },
3720 =item check_and_rebuild_fuzzyfiles
3724 sub check_and_rebuild_fuzzyfiles {
3725 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3726 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
3727 or &rebuild_fuzzyfiles;
3730 =item rebuild_fuzzyfiles
3734 sub rebuild_fuzzyfiles {
3736 use Fcntl qw(:flock);
3738 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3742 open(LASTLOCK,">>$dir/cust_main.last")
3743 or die "can't open $dir/cust_main.last: $!";
3744 flock(LASTLOCK,LOCK_EX)
3745 or die "can't lock $dir/cust_main.last: $!";
3747 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
3749 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
3750 if defined dbdef->table('cust_main')->column('ship_last');
3752 open (LASTCACHE,">$dir/cust_main.last.tmp")
3753 or die "can't open $dir/cust_main.last.tmp: $!";
3754 print LASTCACHE join("\n", @all_last), "\n";
3755 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
3757 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
3762 open(COMPANYLOCK,">>$dir/cust_main.company")
3763 or die "can't open $dir/cust_main.company: $!";
3764 flock(COMPANYLOCK,LOCK_EX)
3765 or die "can't lock $dir/cust_main.company: $!";
3767 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
3769 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
3770 if defined dbdef->table('cust_main')->column('ship_last');
3772 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
3773 or die "can't open $dir/cust_main.company.tmp: $!";
3774 print COMPANYCACHE join("\n", @all_company), "\n";
3775 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
3777 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
3787 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3788 open(LASTCACHE,"<$dir/cust_main.last")
3789 or die "can't open $dir/cust_main.last: $!";
3790 my @array = map { chomp; $_; } <LASTCACHE>;
3800 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3801 open(COMPANYCACHE,"<$dir/cust_main.company")
3802 or die "can't open $dir/cust_main.last: $!";
3803 my @array = map { chomp; $_; } <COMPANYCACHE>;
3808 =item append_fuzzyfiles LASTNAME COMPANY
3812 sub append_fuzzyfiles {
3813 my( $last, $company ) = @_;
3815 &check_and_rebuild_fuzzyfiles;
3817 use Fcntl qw(:flock);
3819 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3823 open(LAST,">>$dir/cust_main.last")
3824 or die "can't open $dir/cust_main.last: $!";
3826 or die "can't lock $dir/cust_main.last: $!";
3828 print LAST "$last\n";
3831 or die "can't unlock $dir/cust_main.last: $!";
3837 open(COMPANY,">>$dir/cust_main.company")
3838 or die "can't open $dir/cust_main.company: $!";
3839 flock(COMPANY,LOCK_EX)
3840 or die "can't lock $dir/cust_main.company: $!";
3842 print COMPANY "$company\n";
3844 flock(COMPANY,LOCK_UN)
3845 or die "can't unlock $dir/cust_main.company: $!";
3859 #warn join('-',keys %$param);
3860 my $fh = $param->{filehandle};
3861 my $agentnum = $param->{agentnum};
3862 my $refnum = $param->{refnum};
3863 my $pkgpart = $param->{pkgpart};
3864 my @fields = @{$param->{fields}};
3866 eval "use Date::Parse;";
3868 eval "use Text::CSV_XS;";
3871 my $csv = new Text::CSV_XS;
3878 local $SIG{HUP} = 'IGNORE';
3879 local $SIG{INT} = 'IGNORE';
3880 local $SIG{QUIT} = 'IGNORE';
3881 local $SIG{TERM} = 'IGNORE';
3882 local $SIG{TSTP} = 'IGNORE';
3883 local $SIG{PIPE} = 'IGNORE';
3885 my $oldAutoCommit = $FS::UID::AutoCommit;
3886 local $FS::UID::AutoCommit = 0;
3889 #while ( $columns = $csv->getline($fh) ) {
3891 while ( defined($line=<$fh>) ) {
3893 $csv->parse($line) or do {
3894 $dbh->rollback if $oldAutoCommit;
3895 return "can't parse: ". $csv->error_input();
3898 my @columns = $csv->fields();
3899 #warn join('-',@columns);
3902 agentnum => $agentnum,
3904 country => $conf->config('countrydefault') || 'US',
3905 payby => 'BILL', #default
3906 paydate => '12/2037', #default
3908 my $billtime = time;
3909 my %cust_pkg = ( pkgpart => $pkgpart );
3910 foreach my $field ( @fields ) {
3911 if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
3912 #$cust_pkg{$1} = str2time( shift @$columns );
3913 if ( $1 eq 'setup' ) {
3914 $billtime = str2time(shift @columns);
3916 $cust_pkg{$1} = str2time( shift @columns );
3919 #$cust_main{$field} = shift @$columns;
3920 $cust_main{$field} = shift @columns;
3924 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
3925 my $cust_main = new FS::cust_main ( \%cust_main );
3927 tie my %hash, 'Tie::RefHash'; #this part is important
3928 $hash{$cust_pkg} = [] if $pkgpart;
3929 my $error = $cust_main->insert( \%hash );
3932 $dbh->rollback if $oldAutoCommit;
3933 return "can't insert customer for $line: $error";
3936 #false laziness w/bill.cgi
3937 $error = $cust_main->bill( 'time' => $billtime );
3939 $dbh->rollback if $oldAutoCommit;
3940 return "can't bill customer for $line: $error";
3943 $cust_main->apply_payments;
3944 $cust_main->apply_credits;
3946 $error = $cust_main->collect();
3948 $dbh->rollback if $oldAutoCommit;
3949 return "can't collect customer for $line: $error";
3955 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3957 return "Empty file!" unless $imported;
3969 #warn join('-',keys %$param);
3970 my $fh = $param->{filehandle};
3971 my @fields = @{$param->{fields}};
3973 eval "use Date::Parse;";
3975 eval "use Text::CSV_XS;";
3978 my $csv = new Text::CSV_XS;
3985 local $SIG{HUP} = 'IGNORE';
3986 local $SIG{INT} = 'IGNORE';
3987 local $SIG{QUIT} = 'IGNORE';
3988 local $SIG{TERM} = 'IGNORE';
3989 local $SIG{TSTP} = 'IGNORE';
3990 local $SIG{PIPE} = 'IGNORE';
3992 my $oldAutoCommit = $FS::UID::AutoCommit;
3993 local $FS::UID::AutoCommit = 0;
3996 #while ( $columns = $csv->getline($fh) ) {
3998 while ( defined($line=<$fh>) ) {
4000 $csv->parse($line) or do {
4001 $dbh->rollback if $oldAutoCommit;
4002 return "can't parse: ". $csv->error_input();
4005 my @columns = $csv->fields();
4006 #warn join('-',@columns);
4009 foreach my $field ( @fields ) {
4010 $row{$field} = shift @columns;
4013 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4014 unless ( $cust_main ) {
4015 $dbh->rollback if $oldAutoCommit;
4016 return "unknown custnum $row{'custnum'}";
4019 if ( $row{'amount'} > 0 ) {
4020 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4022 $dbh->rollback if $oldAutoCommit;
4026 } elsif ( $row{'amount'} < 0 ) {
4027 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4030 $dbh->rollback if $oldAutoCommit;
4040 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4042 return "Empty file!" unless $imported;
4054 The delete method should possibly take an FS::cust_main object reference
4055 instead of a scalar customer number.
4057 Bill and collect options should probably be passed as references instead of a
4060 There should probably be a configuration file with a list of allowed credit
4063 No multiple currency support (probably a larger project than just this module).
4065 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4069 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4070 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4071 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.