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);";
19 use String::Approx qw(amatch);
20 use Business::CreditCard;
21 use FS::UID qw( getotaker dbh );
22 use FS::Record qw( qsearchs qsearch dbdef );
23 use FS::Misc qw( send_email );
27 use FS::cust_bill_pkg;
29 use FS::cust_pay_void;
32 use FS::part_referral;
33 use FS::cust_main_county;
35 use FS::cust_main_invoice;
36 use FS::cust_credit_bill;
37 use FS::cust_bill_pay;
38 use FS::prepay_credit;
41 use FS::part_bill_event;
42 use FS::cust_bill_event;
43 use FS::cust_tax_exempt;
45 use FS::payment_gateway;
46 use FS::agent_payment_gateway;
47 use FS::Msgcat qw(gettext);
49 @ISA = qw( FS::Record );
51 @EXPORT_OK = qw( smart_search );
53 $realtime_bop_decline_quiet = 0;
56 $me = '[FS::cust_main]';
61 @encrypted_fields = ('payinfo', 'paycvv');
63 #ask FS::UID to run this stuff for us later
64 #$FS::UID::callback{'FS::cust_main'} = sub {
65 install_callback FS::UID sub {
67 #yes, need it for stuff below (prolly should be cached)
72 my ( $hashref, $cache ) = @_;
73 if ( exists $hashref->{'pkgnum'} ) {
74 # #@{ $self->{'_pkgnum'} } = ();
75 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
76 $self->{'_pkgnum'} = $subcache;
77 #push @{ $self->{'_pkgnum'} },
78 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
84 FS::cust_main - Object methods for cust_main records
90 $record = new FS::cust_main \%hash;
91 $record = new FS::cust_main { 'column' => 'value' };
93 $error = $record->insert;
95 $error = $new_record->replace($old_record);
97 $error = $record->delete;
99 $error = $record->check;
101 @cust_pkg = $record->all_pkgs;
103 @cust_pkg = $record->ncancelled_pkgs;
105 @cust_pkg = $record->suspended_pkgs;
107 $error = $record->bill;
108 $error = $record->bill %options;
109 $error = $record->bill 'time' => $time;
111 $error = $record->collect;
112 $error = $record->collect %options;
113 $error = $record->collect 'invoice_time' => $time,
114 'batch_card' => 'yes',
115 'report_badcard' => 'yes',
120 An FS::cust_main object represents a customer. FS::cust_main inherits from
121 FS::Record. The following fields are currently supported:
125 =item custnum - primary key (assigned automatically for new customers)
127 =item agentnum - agent (see L<FS::agent>)
129 =item refnum - Advertising source (see L<FS::part_referral>)
135 =item ss - social security number (optional)
137 =item company - (optional)
141 =item address2 - (optional)
145 =item county - (optional, see L<FS::cust_main_county>)
147 =item state - (see L<FS::cust_main_county>)
151 =item country - (see L<FS::cust_main_county>)
153 =item daytime - phone (optional)
155 =item night - phone (optional)
157 =item fax - phone (optional)
159 =item ship_first - name
161 =item ship_last - name
163 =item ship_company - (optional)
167 =item ship_address2 - (optional)
171 =item ship_county - (optional, see L<FS::cust_main_county>)
173 =item ship_state - (see L<FS::cust_main_county>)
177 =item ship_country - (see L<FS::cust_main_county>)
179 =item ship_daytime - phone (optional)
181 =item ship_night - phone (optional)
183 =item ship_fax - phone (optional)
187 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>)
191 Card Number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
196 my($self,$payinfo) = @_;
197 if ( defined($payinfo) ) {
198 $self->paymask($payinfo);
199 $self->setfield('payinfo', $payinfo); # This is okay since we are the 'setter'
201 $payinfo = $self->getfield('payinfo'); # This is okay since we are the 'getter'
209 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
213 =item paymask - Masked payment type
219 Mask all but the last four characters.
223 Mask all but last 2 of account number and bank routing number.
227 Do nothing, return the unmasked string.
236 # If it doesn't exist then generate it
237 my $paymask=$self->getfield('paymask');
238 if (!defined($value) && (!defined($paymask) || $paymask eq '')) {
239 $value = $self->payinfo;
242 if ( defined($value) && !$self->is_encrypted($value)) {
243 my $payinfo = $value;
244 my $payby = $self->payby;
245 if ($payby eq 'CARD' || $payby eq 'DCARD') { # Credit Cards (Show last four)
246 $paymask = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
247 } elsif ($payby eq 'CHEK' ||
248 $payby eq 'DCHK' ) { # Checks (Show last 2 @ bank)
249 my( $account, $aba ) = split('@', $payinfo );
250 $paymask = 'x'x(length($account)-2). substr($account,(length($account)-2))."@".$aba;
251 } else { # Tie up loose ends
254 $self->setfield('paymask', $paymask); # This is okay since we are the 'setter'
255 } elsif (defined($value) && $self->is_encrypted($value)) {
261 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
263 =item paystart_month - start date month (maestro/solo cards only)
265 =item paystart_year - start date year (maestro/solo cards only)
267 =item payissue - issue number (maestro/solo cards only)
269 =item payname - name on card or billing name
271 =item payip - IP address from which payment information was received
273 =item tax - tax exempt, empty or `Y'
275 =item otaker - order taker (assigned automatically, see L<FS::UID>)
277 =item comments - comments (optional)
279 =item referral_custnum - referring customer number
289 Creates a new customer. To add the customer to the database, see L<"insert">.
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to. You can ask the object for a copy with the I<hash> method.
296 sub table { 'cust_main'; }
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
300 Adds this customer to the database. If there is an error, returns the error,
301 otherwise returns false.
303 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
304 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
305 are inserted atomicly, or the transaction is rolled back. Passing an empty
306 hash reference is equivalent to not supplying this parameter. There should be
307 a better explanation of this, but until then, here's an example:
310 tie %hash, 'Tie::RefHash'; #this part is important
312 $cust_pkg => [ $svc_acct ],
315 $cust_main->insert( \%hash );
317 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
318 be set as the invoicing list (see L<"invoicing_list">). Errors return as
319 expected and rollback the entire transaction; it is not necessary to call
320 check_invoicing_list first. The invoicing_list is set after the records in the
321 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
322 invoicing_list destination to the newly-created svc_acct. Here's an example:
324 $cust_main->insert( {}, [ $email, 'POST' ] );
326 Currently available options are: I<depend_jobnum> and I<noexport>.
328 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
329 on the supplied jobnum (they will not run until the specific job completes).
330 This can be used to defer provisioning until some action completes (such
331 as running the customer's credit card sucessfully).
333 The I<noexport> option is deprecated. If I<noexport> is set true, no
334 provisioning jobs (exports) are scheduled. (You can schedule them later with
335 the B<reexport> method.)
341 my $cust_pkgs = @_ ? shift : {};
342 my $invoicing_list = @_ ? shift : '';
344 warn "FS::cust_main::insert called with options ".
345 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
348 local $SIG{HUP} = 'IGNORE';
349 local $SIG{INT} = 'IGNORE';
350 local $SIG{QUIT} = 'IGNORE';
351 local $SIG{TERM} = 'IGNORE';
352 local $SIG{TSTP} = 'IGNORE';
353 local $SIG{PIPE} = 'IGNORE';
355 my $oldAutoCommit = $FS::UID::AutoCommit;
356 local $FS::UID::AutoCommit = 0;
359 my $prepay_identifier = '';
360 my( $amount, $seconds ) = ( 0, 0 );
361 if ( $self->payby eq 'PREPAY' ) {
363 $self->payby('BILL');
364 $prepay_identifier = $self->payinfo;
367 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
369 $dbh->rollback if $oldAutoCommit;
370 #return "error applying prepaid card (transaction rolled back): $error";
376 my $error = $self->SUPER::insert;
378 $dbh->rollback if $oldAutoCommit;
379 #return "inserting cust_main record (transaction rolled back): $error";
384 if ( $invoicing_list ) {
385 $error = $self->check_invoicing_list( $invoicing_list );
387 $dbh->rollback if $oldAutoCommit;
388 return "checking invoicing_list (transaction rolled back): $error";
390 $self->invoicing_list( $invoicing_list );
394 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
396 $dbh->rollback if $oldAutoCommit;
401 $dbh->rollback if $oldAutoCommit;
402 return "No svc_acct record to apply pre-paid time";
406 $error = $self->insert_cust_pay_prepay($amount, $prepay_identifier);
408 $dbh->rollback if $oldAutoCommit;
409 return "inserting prepayment (transaction rolled back): $error";
413 unless ( $import || $skip_fuzzyfiles ) {
414 $error = $self->queue_fuzzyfiles_update;
416 $dbh->rollback if $oldAutoCommit;
417 return "updating fuzzy search cache: $error";
421 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
426 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
428 Like the insert method on an existing record, this method orders a package
429 and included services atomicaly. Pass a Tie::RefHash data structure to this
430 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
431 be a better explanation of this, but until then, here's an example:
434 tie %hash, 'Tie::RefHash'; #this part is important
436 $cust_pkg => [ $svc_acct ],
439 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
441 Services can be new, in which case they are inserted, or existing unaudited
442 services, in which case they are linked to the newly-created package.
444 Currently available options are: I<depend_jobnum> and I<noexport>.
446 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
447 on the supplied jobnum (they will not run until the specific job completes).
448 This can be used to defer provisioning until some action completes (such
449 as running the customer's credit card sucessfully).
451 The I<noexport> option is deprecated. If I<noexport> is set true, no
452 provisioning jobs (exports) are scheduled. (You can schedule them later with
453 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
454 on the cust_main object is not recommended, as existing services will also be
461 my $cust_pkgs = shift;
464 my %svc_options = ();
465 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
466 if exists $options{'depend_jobnum'};
467 warn "FS::cust_main::order_pkgs called with options ".
468 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
471 local $SIG{HUP} = 'IGNORE';
472 local $SIG{INT} = 'IGNORE';
473 local $SIG{QUIT} = 'IGNORE';
474 local $SIG{TERM} = 'IGNORE';
475 local $SIG{TSTP} = 'IGNORE';
476 local $SIG{PIPE} = 'IGNORE';
478 my $oldAutoCommit = $FS::UID::AutoCommit;
479 local $FS::UID::AutoCommit = 0;
482 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
484 foreach my $cust_pkg ( keys %$cust_pkgs ) {
485 $cust_pkg->custnum( $self->custnum );
486 my $error = $cust_pkg->insert;
488 $dbh->rollback if $oldAutoCommit;
489 return "inserting cust_pkg (transaction rolled back): $error";
491 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
492 if ( $svc_something->svcnum ) {
493 my $old_cust_svc = $svc_something->cust_svc;
494 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
495 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
496 $error = $new_cust_svc->replace($old_cust_svc);
498 $svc_something->pkgnum( $cust_pkg->pkgnum );
499 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
500 $svc_something->seconds( $svc_something->seconds + $$seconds );
503 $error = $svc_something->insert(%svc_options);
506 $dbh->rollback if $oldAutoCommit;
507 #return "inserting svc_ (transaction rolled back): $error";
513 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
517 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF ]
519 Recharges this (existing) customer with the specified prepaid card (see
520 L<FS::prepay_credit>), specified either by I<identifier> or as an
521 FS::prepay_credit object. If there is an error, returns the error, otherwise
524 Optionally, two scalar references can be passed as well. They will have their
525 values filled in with the amount and number of seconds applied by this prepaid
530 sub recharge_prepay {
531 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
533 local $SIG{HUP} = 'IGNORE';
534 local $SIG{INT} = 'IGNORE';
535 local $SIG{QUIT} = 'IGNORE';
536 local $SIG{TERM} = 'IGNORE';
537 local $SIG{TSTP} = 'IGNORE';
538 local $SIG{PIPE} = 'IGNORE';
540 my $oldAutoCommit = $FS::UID::AutoCommit;
541 local $FS::UID::AutoCommit = 0;
544 my( $amount, $seconds ) = ( 0, 0 );
546 my $error = $self->get_prepay($prepay_credit, \$amount, \$seconds)
547 || $self->increment_seconds($seconds)
548 || $self->insert_cust_pay_prepay( $amount,
550 ? $prepay_credit->identifier
555 $dbh->rollback if $oldAutoCommit;
559 if ( defined($amountref) ) { $$amountref = $amount; }
560 if ( defined($secondsref) ) { $$secondsref = $seconds; }
562 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
567 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
569 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
570 specified either by I<identifier> or as an FS::prepay_credit object.
572 References to I<amount> and I<seconds> scalars should be passed as arguments
573 and will be incremented by the values of the prepaid card.
575 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
576 check or set this customer's I<agentnum>.
578 If there is an error, returns the error, otherwise returns false.
584 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
586 local $SIG{HUP} = 'IGNORE';
587 local $SIG{INT} = 'IGNORE';
588 local $SIG{QUIT} = 'IGNORE';
589 local $SIG{TERM} = 'IGNORE';
590 local $SIG{TSTP} = 'IGNORE';
591 local $SIG{PIPE} = 'IGNORE';
593 my $oldAutoCommit = $FS::UID::AutoCommit;
594 local $FS::UID::AutoCommit = 0;
597 unless ( ref($prepay_credit) ) {
599 my $identifier = $prepay_credit;
601 $prepay_credit = qsearchs(
603 { 'identifier' => $prepay_credit },
608 unless ( $prepay_credit ) {
609 $dbh->rollback if $oldAutoCommit;
610 return "Invalid prepaid card: ". $identifier;
615 if ( $prepay_credit->agentnum ) {
616 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
617 $dbh->rollback if $oldAutoCommit;
618 return "prepaid card not valid for agent ". $self->agentnum;
620 $self->agentnum($prepay_credit->agentnum);
623 my $error = $prepay_credit->delete;
625 $dbh->rollback if $oldAutoCommit;
626 return "removing prepay_credit (transaction rolled back): $error";
629 $$amountref += $prepay_credit->amount;
630 $$secondsref += $prepay_credit->seconds;
632 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
637 =item increment_seconds SECONDS
639 Updates this customer's single or primary account (see L<FS::svc_acct>) by
640 the specified number of seconds. If there is an error, returns the error,
641 otherwise returns false.
645 sub increment_seconds {
646 my( $self, $seconds ) = @_;
647 warn "$me increment_seconds called: $seconds seconds\n"
650 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
651 $self->ncancelled_pkgs;
654 return 'No packages with primary or single services found'.
655 ' to apply pre-paid time';
656 } elsif ( scalar(@cust_pkg) > 1 ) {
657 #maybe have a way to specify the package/account?
658 return 'Multiple packages found to apply pre-paid time';
661 my $cust_pkg = $cust_pkg[0];
662 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
666 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
669 return 'No account found to apply pre-paid time';
670 } elsif ( scalar(@cust_svc) > 1 ) {
671 return 'Multiple accounts found to apply pre-paid time';
674 my $svc_acct = $cust_svc[0]->svc_x;
675 warn " found service svcnum ". $svc_acct->pkgnum.
676 ' ('. $svc_acct->email. ")\n"
679 $svc_acct->increment_seconds($seconds);
683 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
685 Inserts a prepayment in the specified amount for this customer. An optional
686 second argument can specify the prepayment identifier for tracking purposes.
687 If there is an error, returns the error, otherwise returns false.
691 sub insert_cust_pay_prepay {
692 my( $self, $amount ) = splice(@_, 0, 2);
693 my $payinfo = scalar(@_) ? shift : '';
695 my $cust_pay = new FS::cust_pay {
696 'custnum' => $self->custnum,
697 'paid' => sprintf('%.2f', $amount),
698 #'_date' => #date the prepaid card was purchased???
700 'payinfo' => $payinfo,
708 This method is deprecated. See the I<depend_jobnum> option to the insert and
709 order_pkgs methods for a better way to defer provisioning.
711 Re-schedules all exports by calling the B<reexport> method of all associated
712 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
713 otherwise returns false.
720 carp "warning: FS::cust_main::reexport is deprectated; ".
721 "use the depend_jobnum option to insert or order_pkgs to delay export";
723 local $SIG{HUP} = 'IGNORE';
724 local $SIG{INT} = 'IGNORE';
725 local $SIG{QUIT} = 'IGNORE';
726 local $SIG{TERM} = 'IGNORE';
727 local $SIG{TSTP} = 'IGNORE';
728 local $SIG{PIPE} = 'IGNORE';
730 my $oldAutoCommit = $FS::UID::AutoCommit;
731 local $FS::UID::AutoCommit = 0;
734 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
735 my $error = $cust_pkg->reexport;
737 $dbh->rollback if $oldAutoCommit;
742 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
747 =item delete NEW_CUSTNUM
749 This deletes the customer. If there is an error, returns the error, otherwise
752 This will completely remove all traces of the customer record. This is not
753 what you want when a customer cancels service; for that, cancel all of the
754 customer's packages (see L</cancel>).
756 If the customer has any uncancelled packages, you need to pass a new (valid)
757 customer number for those packages to be transferred to. Cancelled packages
758 will be deleted. Did I mention that this is NOT what you want when a customer
759 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
761 You can't delete a customer with invoices (see L<FS::cust_bill>),
762 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
763 refunds (see L<FS::cust_refund>).
770 local $SIG{HUP} = 'IGNORE';
771 local $SIG{INT} = 'IGNORE';
772 local $SIG{QUIT} = 'IGNORE';
773 local $SIG{TERM} = 'IGNORE';
774 local $SIG{TSTP} = 'IGNORE';
775 local $SIG{PIPE} = 'IGNORE';
777 my $oldAutoCommit = $FS::UID::AutoCommit;
778 local $FS::UID::AutoCommit = 0;
781 if ( $self->cust_bill ) {
782 $dbh->rollback if $oldAutoCommit;
783 return "Can't delete a customer with invoices";
785 if ( $self->cust_credit ) {
786 $dbh->rollback if $oldAutoCommit;
787 return "Can't delete a customer with credits";
789 if ( $self->cust_pay ) {
790 $dbh->rollback if $oldAutoCommit;
791 return "Can't delete a customer with payments";
793 if ( $self->cust_refund ) {
794 $dbh->rollback if $oldAutoCommit;
795 return "Can't delete a customer with refunds";
798 my @cust_pkg = $self->ncancelled_pkgs;
800 my $new_custnum = shift;
801 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
802 $dbh->rollback if $oldAutoCommit;
803 return "Invalid new customer number: $new_custnum";
805 foreach my $cust_pkg ( @cust_pkg ) {
806 my %hash = $cust_pkg->hash;
807 $hash{'custnum'} = $new_custnum;
808 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
809 my $error = $new_cust_pkg->replace($cust_pkg);
811 $dbh->rollback if $oldAutoCommit;
816 my @cancelled_cust_pkg = $self->all_pkgs;
817 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
818 my $error = $cust_pkg->delete;
820 $dbh->rollback if $oldAutoCommit;
825 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
826 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
828 my $error = $cust_main_invoice->delete;
830 $dbh->rollback if $oldAutoCommit;
835 my $error = $self->SUPER::delete;
837 $dbh->rollback if $oldAutoCommit;
841 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
846 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
848 Replaces the OLD_RECORD with this one in the database. If there is an error,
849 returns the error, otherwise returns false.
851 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
852 be set as the invoicing list (see L<"invoicing_list">). Errors return as
853 expected and rollback the entire transaction; it is not necessary to call
854 check_invoicing_list first. Here's an example:
856 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
865 local $SIG{HUP} = 'IGNORE';
866 local $SIG{INT} = 'IGNORE';
867 local $SIG{QUIT} = 'IGNORE';
868 local $SIG{TERM} = 'IGNORE';
869 local $SIG{TSTP} = 'IGNORE';
870 local $SIG{PIPE} = 'IGNORE';
872 # If the mask is blank then try to set it - if we can...
873 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
874 $self->paymask($self->payinfo);
877 # We absolutely have to have an old vs. new record to make this work.
878 if (!defined($old)) {
879 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
882 if ( $self->payby eq 'COMP' && $self->payby ne $old->payby
883 && $conf->config('users-allow_comp') ) {
884 return "You are not permitted to create complimentary accounts."
885 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
888 my $oldAutoCommit = $FS::UID::AutoCommit;
889 local $FS::UID::AutoCommit = 0;
892 my $error = $self->SUPER::replace($old);
895 $dbh->rollback if $oldAutoCommit;
899 if ( @param ) { # INVOICING_LIST_ARYREF
900 my $invoicing_list = shift @param;
901 $error = $self->check_invoicing_list( $invoicing_list );
903 $dbh->rollback if $oldAutoCommit;
906 $self->invoicing_list( $invoicing_list );
909 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
910 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
911 # card/check/lec info has changed, want to retry realtime_ invoice events
912 my $error = $self->retry_realtime;
914 $dbh->rollback if $oldAutoCommit;
919 unless ( $import || $skip_fuzzyfiles ) {
920 $error = $self->queue_fuzzyfiles_update;
922 $dbh->rollback if $oldAutoCommit;
923 return "updating fuzzy search cache: $error";
927 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
932 =item queue_fuzzyfiles_update
934 Used by insert & replace to update the fuzzy search cache
938 sub queue_fuzzyfiles_update {
941 local $SIG{HUP} = 'IGNORE';
942 local $SIG{INT} = 'IGNORE';
943 local $SIG{QUIT} = 'IGNORE';
944 local $SIG{TERM} = 'IGNORE';
945 local $SIG{TSTP} = 'IGNORE';
946 local $SIG{PIPE} = 'IGNORE';
948 my $oldAutoCommit = $FS::UID::AutoCommit;
949 local $FS::UID::AutoCommit = 0;
952 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
953 my $error = $queue->insert($self->getfield('last'), $self->company);
955 $dbh->rollback if $oldAutoCommit;
956 return "queueing job (transaction rolled back): $error";
959 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
960 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
961 $error = $queue->insert($self->getfield('ship_last'), $self->ship_company);
963 $dbh->rollback if $oldAutoCommit;
964 return "queueing job (transaction rolled back): $error";
968 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
975 Checks all fields to make sure this is a valid customer record. If there is
976 an error, returns the error, otherwise returns false. Called by the insert
984 #warn "BEFORE: \n". $self->_dump;
987 $self->ut_numbern('custnum')
988 || $self->ut_number('agentnum')
989 || $self->ut_number('refnum')
990 || $self->ut_name('last')
991 || $self->ut_name('first')
992 || $self->ut_textn('company')
993 || $self->ut_text('address1')
994 || $self->ut_textn('address2')
995 || $self->ut_text('city')
996 || $self->ut_textn('county')
997 || $self->ut_textn('state')
998 || $self->ut_country('country')
999 || $self->ut_anything('comments')
1000 || $self->ut_numbern('referral_custnum')
1002 #barf. need message catalogs. i18n. etc.
1003 $error .= "Please select an advertising source."
1004 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1005 return $error if $error;
1007 return "Unknown agent"
1008 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1010 return "Unknown refnum"
1011 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1013 return "Unknown referring custnum: ". $self->referral_custnum
1014 unless ! $self->referral_custnum
1015 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1017 if ( $self->ss eq '' ) {
1022 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1023 or return "Illegal social security number: ". $self->ss;
1024 $self->ss("$1-$2-$3");
1028 # bad idea to disable, causes billing to fail because of no tax rates later
1029 # unless ( $import ) {
1030 unless ( qsearch('cust_main_county', {
1031 'country' => $self->country,
1034 return "Unknown state/county/country: ".
1035 $self->state. "/". $self->county. "/". $self->country
1036 unless qsearch('cust_main_county',{
1037 'state' => $self->state,
1038 'county' => $self->county,
1039 'country' => $self->country,
1045 $self->ut_phonen('daytime', $self->country)
1046 || $self->ut_phonen('night', $self->country)
1047 || $self->ut_phonen('fax', $self->country)
1048 || $self->ut_zip('zip', $self->country)
1050 return $error if $error;
1053 last first company address1 address2 city county state zip
1054 country daytime night fax
1057 if ( defined $self->dbdef_table->column('ship_last') ) {
1058 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1060 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1064 $self->ut_name('ship_last')
1065 || $self->ut_name('ship_first')
1066 || $self->ut_textn('ship_company')
1067 || $self->ut_text('ship_address1')
1068 || $self->ut_textn('ship_address2')
1069 || $self->ut_text('ship_city')
1070 || $self->ut_textn('ship_county')
1071 || $self->ut_textn('ship_state')
1072 || $self->ut_country('ship_country')
1074 return $error if $error;
1076 #false laziness with above
1077 unless ( qsearchs('cust_main_county', {
1078 'country' => $self->ship_country,
1081 return "Unknown ship_state/ship_county/ship_country: ".
1082 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1083 unless qsearchs('cust_main_county',{
1084 'state' => $self->ship_state,
1085 'county' => $self->ship_county,
1086 'country' => $self->ship_country,
1092 $self->ut_phonen('ship_daytime', $self->ship_country)
1093 || $self->ut_phonen('ship_night', $self->ship_country)
1094 || $self->ut_phonen('ship_fax', $self->ship_country)
1095 || $self->ut_zip('ship_zip', $self->ship_country)
1097 return $error if $error;
1099 } else { # ship_ info eq billing info, so don't store dup info in database
1100 $self->setfield("ship_$_", '')
1101 foreach qw( last first company address1 address2 city county state zip
1102 country daytime night fax );
1106 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY)$/
1107 or return "Illegal payby: ". $self->payby;
1109 $error = $self->ut_numbern('paystart_month')
1110 || $self->ut_numbern('paystart_year')
1111 || $self->ut_numbern('payissue')
1113 return $error if $error;
1115 if ( $self->payip eq '' ) {
1118 $error = $self->ut_ip('payip');
1119 return $error if $error;
1122 # If it is encrypted and the private key is not availaible then we can't
1123 # check the credit card.
1125 my $check_payinfo = 1;
1127 if ($self->is_encrypted($self->payinfo)) {
1133 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1135 my $payinfo = $self->payinfo;
1136 $payinfo =~ s/\D//g;
1137 $payinfo =~ /^(\d{13,16})$/
1138 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1140 $self->payinfo($payinfo);
1142 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1143 return gettext('unknown_card_type')
1144 if cardtype($self->payinfo) eq "Unknown";
1145 if ( defined $self->dbdef_table->column('paycvv') ) {
1146 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1147 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1148 $self->paycvv =~ /^(\d{4})$/
1149 or return "CVV2 (CID) for American Express cards is four digits.";
1152 $self->paycvv =~ /^(\d{3})$/
1153 or return "CVV2 (CVC2/CID) is three digits.";
1161 my $cardtype = cardtype($payinfo);
1162 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1164 return "Start date or issue number is required for $cardtype cards"
1165 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1167 return "Start month must be between 1 and 12"
1168 if $self->paystart_month
1169 and $self->paystart_month < 1 || $self->paystart_month > 12;
1171 return "Start year must be 1990 or later"
1172 if $self->paystart_year
1173 and $self->paystart_year < 1990;
1175 return "Issue number must be beween 1 and 99"
1177 and $self->payissue < 1 || $self->payissue > 99;
1180 $self->paystart_month('');
1181 $self->paystart_year('');
1182 $self->payissue('');
1185 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1187 my $payinfo = $self->payinfo;
1188 $payinfo =~ s/[^\d\@]//g;
1189 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1190 $payinfo = "$1\@$2";
1191 $self->payinfo($payinfo);
1192 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1194 } elsif ( $self->payby eq 'LECB' ) {
1196 my $payinfo = $self->payinfo;
1197 $payinfo =~ s/\D//g;
1198 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1200 $self->payinfo($payinfo);
1201 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1203 } elsif ( $self->payby eq 'BILL' ) {
1205 $error = $self->ut_textn('payinfo');
1206 return "Illegal P.O. number: ". $self->payinfo if $error;
1207 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1209 } elsif ( $self->payby eq 'COMP' ) {
1211 if ( !$self->custnum && $conf->config('users-allow_comp') ) {
1212 return "You are not permitted to create complimentary accounts."
1213 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
1216 $error = $self->ut_textn('payinfo');
1217 return "Illegal comp account issuer: ". $self->payinfo if $error;
1218 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1220 } elsif ( $self->payby eq 'PREPAY' ) {
1222 my $payinfo = $self->payinfo;
1223 $payinfo =~ s/\W//g; #anything else would just confuse things
1224 $self->payinfo($payinfo);
1225 $error = $self->ut_alpha('payinfo');
1226 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1227 return "Unknown prepayment identifier"
1228 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1229 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1233 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1234 return "Expriation date required"
1235 unless $self->payby =~ /^(BILL|PREPAY|CHEK|LECB)$/;
1239 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1240 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1241 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1242 ( $m, $y ) = ( $3, "20$2" );
1244 return "Illegal expiration date: ". $self->paydate;
1246 $self->paydate("$y-$m-01");
1247 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1248 return gettext('expired_card')
1249 if !$import && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1252 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1253 ( ! $conf->exists('require_cardname')
1254 || $self->payby !~ /^(CARD|DCRD)$/ )
1256 $self->payname( $self->first. " ". $self->getfield('last') );
1258 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1259 or return gettext('illegal_name'). " payname: ". $self->payname;
1263 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
1266 $self->otaker(getotaker) unless $self->otaker;
1268 #warn "AFTER: \n". $self->_dump;
1270 $self->SUPER::check;
1275 Returns all packages (see L<FS::cust_pkg>) for this customer.
1281 if ( $self->{'_pkgnum'} ) {
1282 values %{ $self->{'_pkgnum'}->cache };
1284 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1288 =item ncancelled_pkgs
1290 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1294 sub ncancelled_pkgs {
1296 if ( $self->{'_pkgnum'} ) {
1297 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1299 @{ [ # force list context
1300 qsearch( 'cust_pkg', {
1301 'custnum' => $self->custnum,
1304 qsearch( 'cust_pkg', {
1305 'custnum' => $self->custnum,
1312 =item suspended_pkgs
1314 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1318 sub suspended_pkgs {
1320 grep { $_->susp } $self->ncancelled_pkgs;
1323 =item unflagged_suspended_pkgs
1325 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1326 customer (thouse packages without the `manual_flag' set).
1330 sub unflagged_suspended_pkgs {
1332 return $self->suspended_pkgs
1333 unless dbdef->table('cust_pkg')->column('manual_flag');
1334 grep { ! $_->manual_flag } $self->suspended_pkgs;
1337 =item unsuspended_pkgs
1339 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1344 sub unsuspended_pkgs {
1346 grep { ! $_->susp } $self->ncancelled_pkgs;
1349 =item num_cancelled_pkgs
1351 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1356 sub num_cancelled_pkgs {
1358 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1362 my( $self, $sql ) = @_;
1363 my $sth = dbh->prepare(
1364 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1365 ) or die dbh->errstr;
1366 $sth->execute($self->custnum) or die $sth->errstr;
1367 $sth->fetchrow_arrayref->[0];
1372 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1373 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1374 on success or a list of errors.
1380 grep { $_->unsuspend } $self->suspended_pkgs;
1385 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1386 Always returns a list: an empty list on success or a list of errors.
1392 grep { $_->suspend } $self->unsuspended_pkgs;
1395 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1397 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1398 PKGPARTs (see L<FS::part_pkg>). Always returns a list: an empty list on
1399 success or a list of errors.
1403 sub suspend_if_pkgpart {
1406 grep { $_->suspend }
1407 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1408 $self->unsuspended_pkgs;
1411 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1413 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1414 listed PKGPARTs (see L<FS::part_pkg>). Always returns a list: an empty list
1415 on success or a list of errors.
1419 sub suspend_unless_pkgpart {
1422 grep { $_->suspend }
1423 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1424 $self->unsuspended_pkgs;
1427 =item cancel [ OPTION => VALUE ... ]
1429 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1431 Available options are: I<quiet>
1433 I<quiet> can be set true to supress email cancellation notices.
1435 Always returns a list: an empty list on success or a list of errors.
1441 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1446 Returns the agent (see L<FS::agent>) for this customer.
1452 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1457 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1458 conjunction with the collect method.
1460 Options are passed as name-value pairs.
1462 Currently available options are:
1464 resetup - if set true, re-charges setup fees.
1466 time - bills the customer as if it were that time. Specified as a UNIX
1467 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1468 L<Date::Parse> for conversion functions. For example:
1472 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1475 If there is an error, returns the error, otherwise returns false.
1480 my( $self, %options ) = @_;
1481 return '' if $self->payby eq 'COMP';
1482 warn "bill customer ". $self->custnum. "\n" if $DEBUG;
1484 my $time = $options{'time'} || time;
1489 local $SIG{HUP} = 'IGNORE';
1490 local $SIG{INT} = 'IGNORE';
1491 local $SIG{QUIT} = 'IGNORE';
1492 local $SIG{TERM} = 'IGNORE';
1493 local $SIG{TSTP} = 'IGNORE';
1494 local $SIG{PIPE} = 'IGNORE';
1496 my $oldAutoCommit = $FS::UID::AutoCommit;
1497 local $FS::UID::AutoCommit = 0;
1500 $self->select_for_update; #mutex
1502 # find the packages which are due for billing, find out how much they are
1503 # & generate invoice database.
1505 my( $total_setup, $total_recur ) = ( 0, 0 );
1506 #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
1507 my @cust_bill_pkg = ();
1509 #my $taxable_charged = 0;##
1514 foreach my $cust_pkg (
1515 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1518 #NO!! next if $cust_pkg->cancel;
1519 next if $cust_pkg->getfield('cancel');
1521 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG;
1523 #? to avoid use of uninitialized value errors... ?
1524 $cust_pkg->setfield('bill', '')
1525 unless defined($cust_pkg->bill);
1527 my $part_pkg = $cust_pkg->part_pkg;
1529 my %hash = $cust_pkg->hash;
1530 my $old_cust_pkg = new FS::cust_pkg \%hash;
1536 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1538 warn " bill setup\n" if $DEBUG;
1540 $setup = eval { $cust_pkg->calc_setup( $time ) };
1542 $dbh->rollback if $oldAutoCommit;
1546 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1552 if ( $part_pkg->getfield('freq') ne '0' &&
1553 ! $cust_pkg->getfield('susp') &&
1554 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1557 warn " bill recur\n" if $DEBUG;
1559 # XXX shared with $recur_prog
1560 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1562 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details ) };
1564 $dbh->rollback if $oldAutoCommit;
1568 #change this bit to use Date::Manip? CAREFUL with timezones (see
1569 # mailing list archive)
1570 my ($sec,$min,$hour,$mday,$mon,$year) =
1571 (localtime($sdate) )[0,1,2,3,4,5];
1573 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1574 # only for figuring next bill date, nothing else, so, reset $sdate again
1576 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1577 $cust_pkg->last_bill($sdate)
1578 if $cust_pkg->dbdef_table->column('last_bill');
1580 if ( $part_pkg->freq =~ /^\d+$/ ) {
1581 $mon += $part_pkg->freq;
1582 until ( $mon < 12 ) { $mon -= 12; $year++; }
1583 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1585 $mday += $weeks * 7;
1586 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1590 $dbh->rollback if $oldAutoCommit;
1591 return "unparsable frequency: ". $part_pkg->freq;
1593 $cust_pkg->setfield('bill',
1594 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1597 warn "\$setup is undefined" unless defined($setup);
1598 warn "\$recur is undefined" unless defined($recur);
1599 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1601 if ( $cust_pkg->modified ) {
1603 warn " package ". $cust_pkg->pkgnum. " modified; updating\n" if $DEBUG;
1605 $error=$cust_pkg->replace($old_cust_pkg);
1606 if ( $error ) { #just in case
1607 $dbh->rollback if $oldAutoCommit;
1608 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1611 $setup = sprintf( "%.2f", $setup );
1612 $recur = sprintf( "%.2f", $recur );
1613 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1614 $dbh->rollback if $oldAutoCommit;
1615 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1617 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1618 $dbh->rollback if $oldAutoCommit;
1619 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1621 if ( $setup != 0 || $recur != 0 ) {
1622 warn " charges (setup=$setup, recur=$recur); queueing line items\n"
1624 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1625 'pkgnum' => $cust_pkg->pkgnum,
1629 'edate' => $cust_pkg->bill,
1630 'details' => \@details,
1632 push @cust_bill_pkg, $cust_bill_pkg;
1633 $total_setup += $setup;
1634 $total_recur += $recur;
1636 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1638 my @taxes = qsearch( 'cust_main_county', {
1639 'state' => $self->state,
1640 'county' => $self->county,
1641 'country' => $self->country,
1642 'taxclass' => $part_pkg->taxclass,
1645 @taxes = qsearch( 'cust_main_county', {
1646 'state' => $self->state,
1647 'county' => $self->county,
1648 'country' => $self->country,
1653 #one more try at a whole-country tax rate
1655 @taxes = qsearch( 'cust_main_county', {
1658 'country' => $self->country,
1663 # maybe eliminate this entirely, along with all the 0% records
1665 $dbh->rollback if $oldAutoCommit;
1667 "fatal: can't find tax rate for state/county/country/taxclass ".
1668 join('/', ( map $self->$_(), qw(state county country) ),
1669 $part_pkg->taxclass ). "\n";
1672 foreach my $tax ( @taxes ) {
1674 my $taxable_charged = 0;
1675 $taxable_charged += $setup
1676 unless $part_pkg->setuptax =~ /^Y$/i
1677 || $tax->setuptax =~ /^Y$/i;
1678 $taxable_charged += $recur
1679 unless $part_pkg->recurtax =~ /^Y$/i
1680 || $tax->recurtax =~ /^Y$/i;
1681 next unless $taxable_charged;
1683 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
1684 my ($mon,$year) = (localtime($sdate) )[4,5];
1686 my $freq = $part_pkg->freq || 1;
1687 if ( $freq !~ /(\d+)$/ ) {
1688 $dbh->rollback if $oldAutoCommit;
1689 return "daily/weekly package definitions not (yet?)".
1690 " compatible with monthly tax exemptions";
1692 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1693 foreach my $which_month ( 1 .. $freq ) {
1695 'custnum' => $self->custnum,
1696 'taxnum' => $tax->taxnum,
1697 'year' => 1900+$year,
1700 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1701 until ( $mon < 13 ) { $mon -= 12; $year++; }
1702 my $cust_tax_exempt =
1703 qsearchs('cust_tax_exempt', \%hash)
1704 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1705 my $remaining_exemption = sprintf("%.2f",
1706 $tax->exempt_amount - $cust_tax_exempt->amount );
1707 if ( $remaining_exemption > 0 ) {
1708 my $addl = $remaining_exemption > $taxable_per_month
1709 ? $taxable_per_month
1710 : $remaining_exemption;
1711 $taxable_charged -= $addl;
1712 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1713 $cust_tax_exempt->hash,
1715 sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1717 $error = $new_cust_tax_exempt->exemptnum
1718 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1719 : $new_cust_tax_exempt->insert;
1721 $dbh->rollback if $oldAutoCommit;
1722 return "fatal: can't update cust_tax_exempt: $error";
1725 } # if $remaining_exemption > 0
1727 } #foreach $which_month
1729 } #if $tax->exempt_amount
1731 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1733 #$tax += $taxable_charged * $cust_main_county->tax / 100
1734 $tax{ $tax->taxname || 'Tax' } +=
1735 $taxable_charged * $tax->tax / 100
1737 } #foreach my $tax ( @taxes )
1739 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
1741 } #if $setup != 0 || $recur != 0
1743 } #if $cust_pkg->modified
1745 } #foreach my $cust_pkg
1747 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1748 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1750 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1751 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1755 # unless ( $self->tax =~ /Y/i
1756 # || $self->payby eq 'COMP'
1757 # || $taxable_charged == 0 ) {
1758 # my $cust_main_county = qsearchs('cust_main_county',{
1759 # 'state' => $self->state,
1760 # 'county' => $self->county,
1761 # 'country' => $self->country,
1762 # } ) or die "fatal: can't find tax rate for state/county/country ".
1763 # $self->state. "/". $self->county. "/". $self->country. "\n";
1764 # my $tax = sprintf( "%.2f",
1765 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1768 if ( dbdef->table('cust_bill_pkg')->column('itemdesc') ) { #1.5 schema
1770 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
1771 my $tax = sprintf("%.2f", $tax{$taxname} );
1772 $charged = sprintf( "%.2f", $charged+$tax );
1774 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1780 'itemdesc' => $taxname,
1782 push @cust_bill_pkg, $cust_bill_pkg;
1785 } else { #1.4 schema
1788 foreach ( values %tax ) { $tax += $_ };
1789 $tax = sprintf("%.2f", $tax);
1791 $charged = sprintf( "%.2f", $charged+$tax );
1793 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1800 push @cust_bill_pkg, $cust_bill_pkg;
1805 my $cust_bill = new FS::cust_bill ( {
1806 'custnum' => $self->custnum,
1808 'charged' => $charged,
1810 $error = $cust_bill->insert;
1812 $dbh->rollback if $oldAutoCommit;
1813 return "can't create invoice for customer #". $self->custnum. ": $error";
1816 my $invnum = $cust_bill->invnum;
1818 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1820 $cust_bill_pkg->invnum($invnum);
1821 $error = $cust_bill_pkg->insert;
1823 $dbh->rollback if $oldAutoCommit;
1824 return "can't create invoice line item for customer #". $self->custnum.
1829 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1833 =item collect OPTIONS
1835 (Attempt to) collect money for this customer's outstanding invoices (see
1836 L<FS::cust_bill>). Usually used after the bill method.
1838 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
1839 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
1840 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
1842 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1843 and the invoice events web interface.
1845 If there is an error, returns the error, otherwise returns false.
1847 Options are passed as name-value pairs.
1849 Currently available options are:
1851 invoice_time - Use this time when deciding when to print invoices and
1852 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>
1853 for conversion functions.
1855 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
1858 retry_card - Deprecated alias for 'retry'
1860 batch_card - This option is deprecated. See the invoice events web interface
1861 to control whether cards are batched or run against a realtime gateway.
1863 report_badcard - This option is deprecated.
1865 force_print - This option is deprecated; see the invoice events web interface.
1867 quiet - set true to surpress email card/ACH decline notices.
1872 my( $self, %options ) = @_;
1873 my $invoice_time = $options{'invoice_time'} || time;
1876 local $SIG{HUP} = 'IGNORE';
1877 local $SIG{INT} = 'IGNORE';
1878 local $SIG{QUIT} = 'IGNORE';
1879 local $SIG{TERM} = 'IGNORE';
1880 local $SIG{TSTP} = 'IGNORE';
1881 local $SIG{PIPE} = 'IGNORE';
1883 my $oldAutoCommit = $FS::UID::AutoCommit;
1884 local $FS::UID::AutoCommit = 0;
1887 $self->select_for_update; #mutex
1889 my $balance = $self->balance;
1890 warn "collect customer ". $self->custnum. ": balance $balance\n" if $DEBUG;
1891 unless ( $balance > 0 ) { #redundant?????
1892 $dbh->rollback if $oldAutoCommit; #hmm
1896 if ( exists($options{'retry_card'}) ) {
1897 carp 'retry_card option passed to collect is deprecated; use retry';
1898 $options{'retry'} ||= $options{'retry_card'};
1900 if ( exists($options{'retry'}) && $options{'retry'} ) {
1901 my $error = $self->retry_realtime;
1903 $dbh->rollback if $oldAutoCommit;
1908 foreach my $cust_bill ( $self->open_cust_bill ) {
1910 # don't try to charge for the same invoice if it's already in a batch
1911 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1913 last if $self->balance <= 0;
1915 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
1918 foreach my $part_bill_event (
1919 sort { $a->seconds <=> $b->seconds
1920 || $a->weight <=> $b->weight
1921 || $a->eventpart <=> $b->eventpart }
1922 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1923 && ! qsearch( 'cust_bill_event', {
1924 'invnum' => $cust_bill->invnum,
1925 'eventpart' => $_->eventpart,
1929 qsearch('part_bill_event', { 'payby' => $self->payby,
1930 'disabled' => '', } )
1933 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
1934 || $self->balance <= 0; # or if balance<=0
1936 warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1938 my $cust_main = $self; #for callback
1942 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
1943 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
1944 $error = eval $part_bill_event->eventcode;
1948 my $statustext = '';
1952 } elsif ( $error ) {
1954 $statustext = $error;
1959 #add cust_bill_event
1960 my $cust_bill_event = new FS::cust_bill_event {
1961 'invnum' => $cust_bill->invnum,
1962 'eventpart' => $part_bill_event->eventpart,
1963 #'_date' => $invoice_time,
1965 'status' => $status,
1966 'statustext' => $statustext,
1968 $error = $cust_bill_event->insert;
1970 #$dbh->rollback if $oldAutoCommit;
1971 #return "error: $error";
1973 # gah, even with transactions.
1974 $dbh->commit if $oldAutoCommit; #well.
1975 my $e = 'WARNING: Event run but database not updated - '.
1976 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
1977 ', eventpart '. $part_bill_event->eventpart.
1988 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1993 =item retry_realtime
1995 Schedules realtime credit card / electronic check / LEC billing events for
1996 for retry. Useful if card information has changed or manual retry is desired.
1997 The 'collect' method must be called to actually retry the transaction.
1999 Implementation details: For each of this customer's open invoices, changes
2000 the status of the first "done" (with statustext error) realtime processing
2005 sub retry_realtime {
2008 local $SIG{HUP} = 'IGNORE';
2009 local $SIG{INT} = 'IGNORE';
2010 local $SIG{QUIT} = 'IGNORE';
2011 local $SIG{TERM} = 'IGNORE';
2012 local $SIG{TSTP} = 'IGNORE';
2013 local $SIG{PIPE} = 'IGNORE';
2015 my $oldAutoCommit = $FS::UID::AutoCommit;
2016 local $FS::UID::AutoCommit = 0;
2019 foreach my $cust_bill (
2020 grep { $_->cust_bill_event }
2021 $self->open_cust_bill
2023 my @cust_bill_event =
2024 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2026 #$_->part_bill_event->plan eq 'realtime-card'
2027 $_->part_bill_event->eventcode =~
2028 /\$cust_bill\->realtime_(card|ach|lec)/
2029 && $_->status eq 'done'
2032 $cust_bill->cust_bill_event;
2033 next unless @cust_bill_event;
2034 my $error = $cust_bill_event[0]->retry;
2036 $dbh->rollback if $oldAutoCommit;
2037 return "error scheduling invoice event for retry: $error";
2042 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2047 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2049 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2050 via a Business::OnlinePayment realtime gateway. See
2051 L<http://420.am/business-onlinepayment> for supported gateways.
2053 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2055 Available options are: I<description>, I<invnum>, I<quiet>
2057 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2058 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2059 if set, will override the value from the customer record.
2061 I<description> is a free-text field passed to the gateway. It defaults to
2062 "Internet services".
2064 If an I<invnum> is specified, this payment (if sucessful) is applied to the
2065 specified invoice. If you don't specify an I<invnum> you might want to
2066 call the B<apply_payments> method.
2068 I<quiet> can be set true to surpress email decline notices.
2070 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2075 my( $self, $method, $amount, %options ) = @_;
2077 warn "$self $method $amount\n";
2078 warn " $_ => $options{$_}\n" foreach keys %options;
2081 $options{'description'} ||= 'Internet services';
2083 eval "use Business::OnlinePayment";
2086 my $payinfo = exists($options{'payinfo'})
2087 ? $options{'payinfo'}
2095 if ( $options{'invnum'} ) {
2096 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2097 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2099 map { $_->part_pkg->taxclass }
2101 map { $_->cust_pkg }
2102 $cust_bill->cust_bill_pkg;
2103 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2104 #different taxclasses
2105 $taxclass = $taxclasses[0];
2109 #look for an agent gateway override first
2111 if ( $method eq 'CC' ) {
2112 $cardtype = cardtype($payinfo);
2113 } elsif ( $method eq 'ECHECK' ) {
2116 $cardtype = $method;
2120 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2121 cardtype => $cardtype,
2122 taxclass => $taxclass, } )
2123 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2125 taxclass => $taxclass, } )
2126 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2127 cardtype => $cardtype,
2129 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2131 taxclass => '', } );
2133 my $payment_gateway = '';
2134 my( $processor, $login, $password, $action, @bop_options );
2135 if ( $override ) { #use a payment gateway override
2137 $payment_gateway = $override->payment_gateway;
2139 $processor = $payment_gateway->gateway_module;
2140 $login = $payment_gateway->gateway_username;
2141 $password = $payment_gateway->gateway_password;
2142 $action = $payment_gateway->gateway_action;
2143 @bop_options = $payment_gateway->options;
2145 } else { #use the standard settings from the config
2147 ( $processor, $login, $password, $action, @bop_options ) =
2148 $self->default_payment_gateway($method);
2156 my $address = exists($options{'address1'})
2157 ? $options{'address1'}
2159 my $address2 = exists($options{'address2'})
2160 ? $options{'address2'}
2162 $address .= ", ". $address2 if length($address2);
2164 my $o_payname = exists($options{'payname'})
2165 ? $options{'payname'}
2167 my($payname, $payfirst, $paylast);
2168 if ( $o_payname && $method ne 'ECHECK' ) {
2169 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2170 or return "Illegal payname $payname";
2171 ($payfirst, $paylast) = ($1, $2);
2173 $payfirst = $self->getfield('first');
2174 $paylast = $self->getfield('last');
2175 $payname = "$payfirst $paylast";
2178 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2179 if ( $conf->exists('emailinvoiceauto')
2180 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2181 push @invoicing_list, $self->all_emails;
2184 my $email = ($conf->exists('business-onlinepayment-email-override'))
2185 ? $conf->config('business-onlinepayment-email-override')
2186 : $invoicing_list[0];
2189 if ( $method eq 'CC' ) {
2191 $content{card_number} = $payinfo;
2192 my $paydate = exists($options{'paydate'})
2193 ? $options{'paydate'}
2195 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2196 $content{expiration} = "$2/$1";
2198 if ( defined $self->dbdef_table->column('paycvv') ) {
2199 my $paycvv = exists($options{'paycvv'})
2200 ? $options{'paycvv'}
2202 $content{cvv2} = $self->paycvv
2206 $content{recurring_billing} = 'YES'
2207 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2209 'payinfo' => $payinfo,
2212 } elsif ( $method eq 'ECHECK' ) {
2213 ( $content{account_number}, $content{routing_code} ) =
2214 split('@', $payinfo);
2215 $content{bank_name} = $o_payname;
2216 $content{account_type} = 'CHECKING';
2217 $content{account_name} = $payname;
2218 $content{customer_org} = $self->company ? 'B' : 'I';
2219 $content{customer_ssn} = exists($options{'ss'})
2222 } elsif ( $method eq 'LEC' ) {
2223 $content{phone} = $payinfo;
2227 # run transaction(s)
2230 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2232 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2233 $transaction->content(
2236 'password' => $password,
2237 'action' => $action1,
2238 'description' => $options{'description'},
2239 'amount' => $amount,
2240 'invoice_number' => $options{'invnum'},
2241 'customer_id' => $self->custnum,
2242 'last_name' => $paylast,
2243 'first_name' => $payfirst,
2245 'address' => $address,
2246 'city' => ( exists($options{'city'})
2249 'state' => ( exists($options{'state'})
2252 'zip' => ( exists($options{'zip'})
2255 'country' => ( exists($options{'country'})
2256 ? $options{'country'}
2258 'referer' => 'http://cleanwhisker.420.am/',
2260 'phone' => $self->daytime || $self->night,
2263 $transaction->submit();
2265 if ( $transaction->is_success() && $action2 ) {
2266 my $auth = $transaction->authorization;
2267 my $ordernum = $transaction->can('order_number')
2268 ? $transaction->order_number
2272 new Business::OnlinePayment( $processor, @bop_options );
2279 password => $password,
2280 order_number => $ordernum,
2282 authorization => $auth,
2283 description => $options{'description'},
2286 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2287 transaction_sequence_num local_transaction_date
2288 local_transaction_time AVS_result_code )) {
2289 $capture{$field} = $transaction->$field() if $transaction->can($field);
2292 $capture->content( %capture );
2296 unless ( $capture->is_success ) {
2297 my $e = "Authorization sucessful but capture failed, custnum #".
2298 $self->custnum. ': '. $capture->result_code.
2299 ": ". $capture->error_message;
2307 # remove paycvv after initial transaction
2310 #false laziness w/misc/process/payment.cgi - check both to make sure working
2312 if ( defined $self->dbdef_table->column('paycvv')
2313 && length($self->paycvv)
2314 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2316 my $error = $self->remove_cvv;
2318 warn "error removing cvv: $error\n";
2326 if ( $transaction->is_success() ) {
2328 my %method2payby = (
2335 if ( $payment_gateway ) { # agent override
2336 $paybatch = $payment_gateway->gatewaynum. '-';
2339 $paybatch .= "$processor:". $transaction->authorization;
2341 $paybatch .= ':'. $transaction->order_number
2342 if $transaction->can('order_number')
2343 && length($transaction->order_number);
2345 my $cust_pay = new FS::cust_pay ( {
2346 'custnum' => $self->custnum,
2347 'invnum' => $options{'invnum'},
2350 'payby' => $method2payby{$method},
2351 'payinfo' => $payinfo,
2352 'paybatch' => $paybatch,
2354 my $error = $cust_pay->insert;
2356 $cust_pay->invnum(''); #try again with no specific invnum
2357 my $error2 = $cust_pay->insert;
2359 # gah, even with transactions.
2360 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2361 "error inserting payment ($processor): $error2".
2362 " (previously tried insert with invnum #$options{'invnum'}" .
2368 return ''; #no error
2372 my $perror = "$processor error: ". $transaction->error_message;
2374 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2375 && $conf->exists('emaildecline')
2376 && grep { $_ ne 'POST' } $self->invoicing_list
2377 && ! grep { $transaction->error_message =~ /$_/ }
2378 $conf->config('emaildecline-exclude')
2380 my @templ = $conf->config('declinetemplate');
2381 my $template = new Text::Template (
2383 SOURCE => [ map "$_\n", @templ ],
2384 ) or return "($perror) can't create template: $Text::Template::ERROR";
2385 $template->compile()
2386 or return "($perror) can't compile template: $Text::Template::ERROR";
2388 my $templ_hash = { error => $transaction->error_message };
2390 my $error = send_email(
2391 'from' => $conf->config('invoice_from'),
2392 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2393 'subject' => 'Your payment could not be processed',
2394 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2397 $perror .= " (also received error sending decline notification: $error)"
2407 =item default_payment_gateway
2411 sub default_payment_gateway {
2412 my( $self, $method ) = @_;
2414 die "Real-time processing not enabled\n"
2415 unless $conf->exists('business-onlinepayment');
2418 my $bop_config = 'business-onlinepayment';
2419 $bop_config .= '-ach'
2420 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2421 my ( $processor, $login, $password, $action, @bop_options ) =
2422 $conf->config($bop_config);
2423 $action ||= 'normal authorization';
2424 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2425 die "No real-time processor is enabled - ".
2426 "did you set the business-onlinepayment configuration value?\n"
2429 ( $processor, $login, $password, $action, @bop_options )
2434 Removes the I<paycvv> field from the database directly.
2436 If there is an error, returns the error, otherwise returns false.
2442 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2443 or return dbh->errstr;
2444 $sth->execute($self->custnum)
2445 or return $sth->errstr;
2450 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2452 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2453 via a Business::OnlinePayment realtime gateway. See
2454 L<http://420.am/business-onlinepayment> for supported gateways.
2456 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2458 Available options are: I<amount>, I<reason>, I<paynum>
2460 Most gateways require a reference to an original payment transaction to refund,
2461 so you probably need to specify a I<paynum>.
2463 I<amount> defaults to the original amount of the payment if not specified.
2465 I<reason> specifies a reason for the refund.
2467 Implementation note: If I<amount> is unspecified or equal to the amount of the
2468 orignal payment, first an attempt is made to "void" the transaction via
2469 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2470 the normal attempt is made to "refund" ("credit") the transaction via the
2471 gateway is attempted.
2473 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2474 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2475 #if set, will override the value from the customer record.
2477 #If an I<invnum> is specified, this payment (if sucessful) is applied to the
2478 #specified invoice. If you don't specify an I<invnum> you might want to
2479 #call the B<apply_payments> method.
2483 #some false laziness w/realtime_bop, not enough to make it worth merging
2484 #but some useful small subs should be pulled out
2485 sub realtime_refund_bop {
2486 my( $self, $method, %options ) = @_;
2488 warn "$self $method refund\n";
2489 warn " $_ => $options{$_}\n" foreach keys %options;
2492 eval "use Business::OnlinePayment";
2496 # look up the original payment and optionally a gateway for that payment
2500 my $amount = $options{'amount'};
2502 my( $processor, $login, $password, @bop_options ) ;
2503 my( $auth, $order_number ) = ( '', '', '' );
2505 if ( $options{'paynum'} ) {
2507 warn "FS::cust_main::realtime_bop: paynum: $options{paynum}\n" if $DEBUG;
2508 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2509 or return "Unknown paynum $options{'paynum'}";
2510 $amount ||= $cust_pay->paid;
2512 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):([\w-]*)(:(\w+))?$/
2513 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2514 $cust_pay->paybatch;
2515 my $gatewaynum = '';
2516 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2518 if ( $gatewaynum ) { #gateway for the payment to be refunded
2520 my $payment_gateway =
2521 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2522 die "payment gateway $gatewaynum not found"
2523 unless $payment_gateway;
2525 $processor = $payment_gateway->gateway_module;
2526 $login = $payment_gateway->gateway_username;
2527 $password = $payment_gateway->gateway_password;
2528 @bop_options = $payment_gateway->options;
2530 } else { #try the default gateway
2532 my( $conf_processor, $unused_action );
2533 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2534 $self->default_payment_gateway($method);
2536 return "processor of payment $options{'paynum'} $processor does not".
2537 " match default processor $conf_processor"
2538 unless $processor eq $conf_processor;
2543 } else { # didn't specify a paynum, so look for agent gateway overrides
2544 # like a normal transaction
2547 if ( $method eq 'CC' ) {
2548 $cardtype = cardtype($self->payinfo);
2549 } elsif ( $method eq 'ECHECK' ) {
2552 $cardtype = $method;
2555 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2556 cardtype => $cardtype,
2558 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2560 taxclass => '', } );
2562 if ( $override ) { #use a payment gateway override
2564 my $payment_gateway = $override->payment_gateway;
2566 $processor = $payment_gateway->gateway_module;
2567 $login = $payment_gateway->gateway_username;
2568 $password = $payment_gateway->gateway_password;
2569 #$action = $payment_gateway->gateway_action;
2570 @bop_options = $payment_gateway->options;
2572 } else { #use the standard settings from the config
2575 ( $processor, $login, $password, $unused_action, @bop_options ) =
2576 $self->default_payment_gateway($method);
2581 return "neither amount nor paynum specified" unless $amount;
2586 'password' => $password,
2587 'order_number' => $order_number,
2588 'amount' => $amount,
2589 'referer' => 'http://cleanwhisker.420.am/',
2591 $content{authorization} = $auth
2592 if length($auth); #echeck/ACH transactions have an order # but no auth
2593 #(at least with authorize.net)
2595 #first try void if applicable
2596 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2597 warn "FS::cust_main::realtime_bop: attempting void\n" if $DEBUG;
2598 my $void = new Business::OnlinePayment( $processor, @bop_options );
2599 $void->content( 'action' => 'void', %content );
2601 if ( $void->is_success ) {
2602 my $error = $cust_pay->void($options{'reason'});
2604 # gah, even with transactions.
2605 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2606 "error voiding payment: $error";
2610 warn "FS::cust_main::realtime_bop: void successful\n" if $DEBUG;
2615 warn "FS::cust_main::realtime_bop: void unsuccessful, trying refund\n"
2619 my $address = $self->address1;
2620 $address .= ", ". $self->address2 if $self->address2;
2622 my($payname, $payfirst, $paylast);
2623 if ( $self->payname && $method ne 'ECHECK' ) {
2624 $payname = $self->payname;
2625 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2626 or return "Illegal payname $payname";
2627 ($payfirst, $paylast) = ($1, $2);
2629 $payfirst = $self->getfield('first');
2630 $paylast = $self->getfield('last');
2631 $payname = "$payfirst $paylast";
2635 if ( $method eq 'CC' ) {
2638 $content{card_number} = $payinfo = $cust_pay->payinfo;
2639 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2640 #$content{expiration} = "$2/$1";
2642 $content{card_number} = $payinfo = $self->payinfo;
2643 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2644 $content{expiration} = "$2/$1";
2647 } elsif ( $method eq 'ECHECK' ) {
2648 ( $content{account_number}, $content{routing_code} ) =
2649 split('@', $payinfo = $self->payinfo);
2650 $content{bank_name} = $self->payname;
2651 $content{account_type} = 'CHECKING';
2652 $content{account_name} = $payname;
2653 $content{customer_org} = $self->company ? 'B' : 'I';
2654 $content{customer_ssn} = $self->ss;
2655 } elsif ( $method eq 'LEC' ) {
2656 $content{phone} = $payinfo = $self->payinfo;
2660 my $refund = new Business::OnlinePayment( $processor, @bop_options );
2661 my %sub_content = $refund->content(
2662 'action' => 'credit',
2663 'customer_id' => $self->custnum,
2664 'last_name' => $paylast,
2665 'first_name' => $payfirst,
2667 'address' => $address,
2668 'city' => $self->city,
2669 'state' => $self->state,
2670 'zip' => $self->zip,
2671 'country' => $self->country,
2674 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
2678 return "$processor error: ". $refund->error_message
2679 unless $refund->is_success();
2681 my %method2payby = (
2687 my $paybatch = "$processor:". $refund->authorization;
2688 $paybatch .= ':'. $refund->order_number
2689 if $refund->can('order_number') && $refund->order_number;
2691 while ( $cust_pay && $cust_pay->unappled < $amount ) {
2692 my @cust_bill_pay = $cust_pay->cust_bill_pay;
2693 last unless @cust_bill_pay;
2694 my $cust_bill_pay = pop @cust_bill_pay;
2695 my $error = $cust_bill_pay->delete;
2699 my $cust_refund = new FS::cust_refund ( {
2700 'custnum' => $self->custnum,
2701 'paynum' => $options{'paynum'},
2702 'refund' => $amount,
2704 'payby' => $method2payby{$method},
2705 'payinfo' => $payinfo,
2706 'paybatch' => $paybatch,
2707 'reason' => $options{'reason'} || 'card or ACH refund',
2709 my $error = $cust_refund->insert;
2711 $cust_refund->paynum(''); #try again with no specific paynum
2712 my $error2 = $cust_refund->insert;
2714 # gah, even with transactions.
2715 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
2716 "error inserting refund ($processor): $error2".
2717 " (previously tried insert with paynum #$options{'paynum'}" .
2730 Returns the total owed for this customer on all invoices
2731 (see L<FS::cust_bill/owed>).
2737 $self->total_owed_date(2145859200); #12/31/2037
2740 =item total_owed_date TIME
2742 Returns the total owed for this customer on all invoices with date earlier than
2743 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2744 see L<Time::Local> and L<Date::Parse> for conversion functions.
2748 sub total_owed_date {
2752 foreach my $cust_bill (
2753 grep { $_->_date <= $time }
2754 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2756 $total_bill += $cust_bill->owed;
2758 sprintf( "%.2f", $total_bill );
2761 =item apply_credits OPTION => VALUE ...
2763 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2764 to outstanding invoice balances in chronological order (or reverse
2765 chronological order if the I<order> option is set to B<newest>) and returns the
2766 value of any remaining unapplied credits available for refund (see
2767 L<FS::cust_refund>).
2775 return 0 unless $self->total_credited;
2777 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2778 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2780 my @invoices = $self->open_cust_bill;
2781 @invoices = sort { $b->_date <=> $a->_date } @invoices
2782 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2785 foreach my $cust_bill ( @invoices ) {
2788 if ( !defined($credit) || $credit->credited == 0) {
2789 $credit = pop @credits or last;
2792 if ($cust_bill->owed >= $credit->credited) {
2793 $amount=$credit->credited;
2795 $amount=$cust_bill->owed;
2798 my $cust_credit_bill = new FS::cust_credit_bill ( {
2799 'crednum' => $credit->crednum,
2800 'invnum' => $cust_bill->invnum,
2801 'amount' => $amount,
2803 my $error = $cust_credit_bill->insert;
2804 die $error if $error;
2806 redo if ($cust_bill->owed > 0);
2810 return $self->total_credited;
2813 =item apply_payments
2815 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2816 to outstanding invoice balances in chronological order.
2818 #and returns the value of any remaining unapplied payments.
2822 sub apply_payments {
2827 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
2828 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
2830 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
2831 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
2835 foreach my $cust_bill ( @invoices ) {
2838 if ( !defined($payment) || $payment->unapplied == 0 ) {
2839 $payment = pop @payments or last;
2842 if ( $cust_bill->owed >= $payment->unapplied ) {
2843 $amount = $payment->unapplied;
2845 $amount = $cust_bill->owed;
2848 my $cust_bill_pay = new FS::cust_bill_pay ( {
2849 'paynum' => $payment->paynum,
2850 'invnum' => $cust_bill->invnum,
2851 'amount' => $amount,
2853 my $error = $cust_bill_pay->insert;
2854 die $error if $error;
2856 redo if ( $cust_bill->owed > 0);
2860 return $self->total_unapplied_payments;
2863 =item total_credited
2865 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2866 customer. See L<FS::cust_credit/credited>.
2870 sub total_credited {
2872 my $total_credit = 0;
2873 foreach my $cust_credit ( qsearch('cust_credit', {
2874 'custnum' => $self->custnum,
2876 $total_credit += $cust_credit->credited;
2878 sprintf( "%.2f", $total_credit );
2881 =item total_unapplied_payments
2883 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2884 See L<FS::cust_pay/unapplied>.
2888 sub total_unapplied_payments {
2890 my $total_unapplied = 0;
2891 foreach my $cust_pay ( qsearch('cust_pay', {
2892 'custnum' => $self->custnum,
2894 $total_unapplied += $cust_pay->unapplied;
2896 sprintf( "%.2f", $total_unapplied );
2901 Returns the balance for this customer (total_owed minus total_credited
2902 minus total_unapplied_payments).
2909 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
2913 =item balance_date TIME
2915 Returns the balance for this customer, only considering invoices with date
2916 earlier than TIME (total_owed_date minus total_credited minus
2917 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2918 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2927 $self->total_owed_date($time)
2928 - $self->total_credited
2929 - $self->total_unapplied_payments
2933 =item paydate_monthyear
2935 Returns a two-element list consisting of the month and year of this customer's
2936 paydate (credit card expiration date for CARD customers)
2940 sub paydate_monthyear {
2942 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2944 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2951 =item payinfo_masked
2953 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.
2955 Credit Cards - Mask all but the last four characters.
2956 Checks - Mask all but last 2 of account number and bank routing number.
2957 Others - Do nothing, return the unmasked string.
2961 sub payinfo_masked {
2963 return $self->paymask;
2966 =item invoicing_list [ ARRAYREF ]
2968 If an arguement is given, sets these email addresses as invoice recipients
2969 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2970 (except as warnings), so use check_invoicing_list first.
2972 Returns a list of email addresses (with svcnum entries expanded).
2974 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2975 check it without disturbing anything by passing nothing.
2977 This interface may change in the future.
2981 sub invoicing_list {
2982 my( $self, $arrayref ) = @_;
2984 my @cust_main_invoice;
2985 if ( $self->custnum ) {
2986 @cust_main_invoice =
2987 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2989 @cust_main_invoice = ();
2991 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2992 #warn $cust_main_invoice->destnum;
2993 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2994 #warn $cust_main_invoice->destnum;
2995 my $error = $cust_main_invoice->delete;
2996 warn $error if $error;
2999 if ( $self->custnum ) {
3000 @cust_main_invoice =
3001 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3003 @cust_main_invoice = ();
3005 my %seen = map { $_->address => 1 } @cust_main_invoice;
3006 foreach my $address ( @{$arrayref} ) {
3007 next if exists $seen{$address} && $seen{$address};
3008 $seen{$address} = 1;
3009 my $cust_main_invoice = new FS::cust_main_invoice ( {
3010 'custnum' => $self->custnum,
3013 my $error = $cust_main_invoice->insert;
3014 warn $error if $error;
3017 if ( $self->custnum ) {
3019 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3025 =item check_invoicing_list ARRAYREF
3027 Checks these arguements as valid input for the invoicing_list method. If there
3028 is an error, returns the error, otherwise returns false.
3032 sub check_invoicing_list {
3033 my( $self, $arrayref ) = @_;
3034 foreach my $address ( @{$arrayref} ) {
3036 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3037 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3040 my $cust_main_invoice = new FS::cust_main_invoice ( {
3041 'custnum' => $self->custnum,
3044 my $error = $self->custnum
3045 ? $cust_main_invoice->check
3046 : $cust_main_invoice->checkdest
3048 return $error if $error;
3053 =item set_default_invoicing_list
3055 Sets the invoicing list to all accounts associated with this customer,
3056 overwriting any previous invoicing list.
3060 sub set_default_invoicing_list {
3062 $self->invoicing_list($self->all_emails);
3067 Returns the email addresses of all accounts provisioned for this customer.
3074 foreach my $cust_pkg ( $self->all_pkgs ) {
3075 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3077 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3078 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3080 $list{$_}=1 foreach map { $_->email } @svc_acct;
3085 =item invoicing_list_addpost
3087 Adds postal invoicing to this customer. If this customer is already configured
3088 to receive postal invoices, does nothing.
3092 sub invoicing_list_addpost {
3094 return if grep { $_ eq 'POST' } $self->invoicing_list;
3095 my @invoicing_list = $self->invoicing_list;
3096 push @invoicing_list, 'POST';
3097 $self->invoicing_list(\@invoicing_list);
3100 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3102 Returns an array of customers referred by this customer (referral_custnum set
3103 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3104 customers referred by customers referred by this customer and so on, inclusive.
3105 The default behavior is DEPTH 1 (no recursion).
3109 sub referral_cust_main {
3111 my $depth = @_ ? shift : 1;
3112 my $exclude = @_ ? shift : {};
3115 map { $exclude->{$_->custnum}++; $_; }
3116 grep { ! $exclude->{ $_->custnum } }
3117 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3121 map { $_->referral_cust_main($depth-1, $exclude) }
3128 =item referral_cust_main_ncancelled
3130 Same as referral_cust_main, except only returns customers with uncancelled
3135 sub referral_cust_main_ncancelled {
3137 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3140 =item referral_cust_pkg [ DEPTH ]
3142 Like referral_cust_main, except returns a flat list of all unsuspended (and
3143 uncancelled) packages for each customer. The number of items in this list may
3144 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3148 sub referral_cust_pkg {
3150 my $depth = @_ ? shift : 1;
3152 map { $_->unsuspended_pkgs }
3153 grep { $_->unsuspended_pkgs }
3154 $self->referral_cust_main($depth);
3157 =item referring_cust_main
3159 Returns the single cust_main record for the customer who referred this customer
3160 (referral_custnum), or false.
3164 sub referring_cust_main {
3166 return '' unless $self->referral_custnum;
3167 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3170 =item credit AMOUNT, REASON
3172 Applies a credit to this customer. If there is an error, returns the error,
3173 otherwise returns false.
3178 my( $self, $amount, $reason ) = @_;
3179 my $cust_credit = new FS::cust_credit {
3180 'custnum' => $self->custnum,
3181 'amount' => $amount,
3182 'reason' => $reason,
3184 $cust_credit->insert;
3187 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3189 Creates a one-time charge for this customer. If there is an error, returns
3190 the error, otherwise returns false.
3195 my ( $self, $amount ) = ( shift, shift );
3196 my $pkg = @_ ? shift : 'One-time charge';
3197 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3198 my $taxclass = @_ ? shift : '';
3200 local $SIG{HUP} = 'IGNORE';
3201 local $SIG{INT} = 'IGNORE';
3202 local $SIG{QUIT} = 'IGNORE';
3203 local $SIG{TERM} = 'IGNORE';
3204 local $SIG{TSTP} = 'IGNORE';
3205 local $SIG{PIPE} = 'IGNORE';
3207 my $oldAutoCommit = $FS::UID::AutoCommit;
3208 local $FS::UID::AutoCommit = 0;
3211 my $part_pkg = new FS::part_pkg ( {
3213 'comment' => $comment,
3214 #'setup' => $amount,
3217 'plandata' => "setup_fee=$amount",
3220 'taxclass' => $taxclass,
3223 my $error = $part_pkg->insert;
3225 $dbh->rollback if $oldAutoCommit;
3229 my $pkgpart = $part_pkg->pkgpart;
3230 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3231 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3232 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3233 $error = $type_pkgs->insert;
3235 $dbh->rollback if $oldAutoCommit;
3240 my $cust_pkg = new FS::cust_pkg ( {
3241 'custnum' => $self->custnum,
3242 'pkgpart' => $pkgpart,
3245 $error = $cust_pkg->insert;
3247 $dbh->rollback if $oldAutoCommit;
3251 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3258 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3264 sort { $a->_date <=> $b->_date }
3265 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3268 =item open_cust_bill
3270 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3275 sub open_cust_bill {
3277 grep { $_->owed > 0 } $self->cust_bill;
3282 Returns all the credits (see L<FS::cust_credit>) for this customer.
3288 sort { $a->_date <=> $b->_date }
3289 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3294 Returns all the payments (see L<FS::cust_pay>) for this customer.
3300 sort { $a->_date <=> $b->_date }
3301 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3306 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3312 sort { $a->_date <=> $b->_date }
3313 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3319 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3325 sort { $a->_date <=> $b->_date }
3326 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3329 =item select_for_update
3331 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3336 sub select_for_update {
3338 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3343 Returns a name string for this customer, either "Company (Last, First)" or
3350 my $name = $self->contact;
3351 $name = $self->company. " ($name)" if $self->company;
3357 Returns a name string for this (service/shipping) contact, either
3358 "Company (Last, First)" or "Last, First".
3364 if ( $self->get('ship_last') ) {
3365 my $name = $self->ship_contact;
3366 $name = $self->ship_company. " ($name)" if $self->ship_company;
3375 Returns this customer's full (billing) contact name only, "Last, First"
3381 $self->get('last'). ', '. $self->first;
3386 Returns this customer's full (shipping) contact name only, "Last, First"
3392 $self->get('ship_last')
3393 ? $self->get('ship_last'). ', '. $self->ship_first
3399 Returns a status string for this customer, currently:
3403 =item prospect - No packages have ever been ordered
3405 =item active - One or more recurring packages is active
3407 =item suspended - All non-cancelled recurring packages are suspended
3409 =item cancelled - All recurring packages are cancelled
3417 for my $status (qw( prospect active suspended cancelled )) {
3418 my $method = $status.'_sql';
3419 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3420 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3421 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3422 return $status if $sth->fetchrow_arrayref->[0];
3428 Returns a hex triplet color string for this customer's status.
3433 'prospect' => '000000',
3434 'active' => '00CC00',
3435 'suspended' => 'FF9900',
3436 'cancelled' => 'FF0000',
3440 $statuscolor{$self->status};
3445 =head1 CLASS METHODS
3451 Returns an SQL expression identifying prospective cust_main records (customers
3452 with no packages ever ordered)
3456 sub prospect_sql { "
3457 0 = ( SELECT COUNT(*) FROM cust_pkg
3458 WHERE cust_pkg.custnum = cust_main.custnum
3464 Returns an SQL expression identifying active cust_main records.
3469 0 < ( SELECT COUNT(*) FROM cust_pkg
3470 WHERE cust_pkg.custnum = cust_main.custnum
3471 AND ". FS::cust_pkg->active_sql. "
3478 Returns an SQL expression identifying suspended cust_main records.
3482 #my $recurring_sql = FS::cust_pkg->recurring_sql;
3483 my $recurring_sql = "
3484 '0' != ( select freq from part_pkg
3485 where cust_pkg.pkgpart = part_pkg.pkgpart )
3488 sub suspended_sql { susp_sql(@_); }
3490 0 < ( SELECT COUNT(*) FROM cust_pkg
3491 WHERE cust_pkg.custnum = cust_main.custnum
3493 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3495 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3496 WHERE cust_pkg.custnum = cust_main.custnum
3497 AND ". FS::cust_pkg->active_sql. "
3504 Returns an SQL expression identifying cancelled cust_main records.
3508 sub cancelled_sql { cancel_sql(@_); }
3510 0 < ( SELECT COUNT(*) FROM cust_pkg
3511 WHERE cust_pkg.custnum = cust_main.custnum
3513 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3514 WHERE cust_pkg.custnum = cust_main.custnum
3516 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3520 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3522 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3523 records. Currently, only I<last> or I<company> may be specified (the
3524 appropriate ship_ field is also searched if applicable).
3526 Additional options are the same as FS::Record::qsearch
3531 my( $self, $fuzzy, $hash, @opt) = @_;
3536 check_and_rebuild_fuzzyfiles();
3537 foreach my $field ( keys %$fuzzy ) {
3538 my $sub = \&{"all_$field"};
3540 $match{$_}=1 foreach ( amatch($fuzzy->{$field}, ['i'], @{ &$sub() } ) );
3542 foreach ( keys %match ) {
3543 push @cust_main, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3544 push @cust_main, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt)
3545 if defined dbdef->table('cust_main')->column('ship_last');
3550 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
3562 =item smart_search OPTION => VALUE ...
3564 Accepts the following options: I<search>, the string to search for. The string
3565 will be searched for as a customer number, last name or company name, first
3566 searching for an exact match then fuzzy and substring matches.
3568 Any additional options treated as an additional qualifier on the search
3571 Returns a (possibly empty) array of FS::cust_main objects.
3577 my $search = delete $options{'search'};
3580 if ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
3582 push @cust_main, qsearch('cust_main', { 'custnum' => $1, %options } );
3584 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { #value search
3587 my $q_value = dbh->quote($value);
3590 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
3591 $sql .= " ( LOWER(last) = $q_value OR LOWER(company) = $q_value";
3592 $sql .= " OR LOWER(ship_last) = $q_value OR LOWER(ship_company) = $q_value"
3593 if defined dbdef->table('cust_main')->column('ship_last');
3596 push @cust_main, qsearch( 'cust_main', \%options, '', $sql );
3598 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
3600 #still some false laziness w/ search/cust_main.cgi
3603 push @cust_main, qsearch( 'cust_main',
3604 { 'last' => { 'op' => 'ILIKE',
3605 'value' => "%$q_value%" },
3609 push @cust_main, qsearch( 'cust_main',
3610 { 'ship_last' => { 'op' => 'ILIKE',
3611 'value' => "%$q_value%" },
3616 if defined dbdef->table('cust_main')->column('ship_last');
3618 push @cust_main, qsearch( 'cust_main',
3619 { 'company' => { 'op' => 'ILIKE',
3620 'value' => "%$q_value%" },
3624 push @cust_main, qsearch( 'cust_main',
3625 { 'ship_company' => { 'op' => 'ILIKE',
3626 'value' => "%$q_value%" },
3630 if defined dbdef->table('cust_main')->column('ship_last');
3633 push @cust_main, FS::cust_main->fuzzy_search(
3634 { 'last' => $value },
3637 push @cust_main, FS::cust_main->fuzzy_search(
3638 { 'company' => $value },
3650 =item check_and_rebuild_fuzzyfiles
3654 sub check_and_rebuild_fuzzyfiles {
3655 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3656 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
3657 or &rebuild_fuzzyfiles;
3660 =item rebuild_fuzzyfiles
3664 sub rebuild_fuzzyfiles {
3666 use Fcntl qw(:flock);
3668 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3672 open(LASTLOCK,">>$dir/cust_main.last")
3673 or die "can't open $dir/cust_main.last: $!";
3674 flock(LASTLOCK,LOCK_EX)
3675 or die "can't lock $dir/cust_main.last: $!";
3677 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
3679 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
3680 if defined dbdef->table('cust_main')->column('ship_last');
3682 open (LASTCACHE,">$dir/cust_main.last.tmp")
3683 or die "can't open $dir/cust_main.last.tmp: $!";
3684 print LASTCACHE join("\n", @all_last), "\n";
3685 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
3687 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
3692 open(COMPANYLOCK,">>$dir/cust_main.company")
3693 or die "can't open $dir/cust_main.company: $!";
3694 flock(COMPANYLOCK,LOCK_EX)
3695 or die "can't lock $dir/cust_main.company: $!";
3697 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
3699 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
3700 if defined dbdef->table('cust_main')->column('ship_last');
3702 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
3703 or die "can't open $dir/cust_main.company.tmp: $!";
3704 print COMPANYCACHE join("\n", @all_company), "\n";
3705 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
3707 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
3717 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3718 open(LASTCACHE,"<$dir/cust_main.last")
3719 or die "can't open $dir/cust_main.last: $!";
3720 my @array = map { chomp; $_; } <LASTCACHE>;
3730 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3731 open(COMPANYCACHE,"<$dir/cust_main.company")
3732 or die "can't open $dir/cust_main.last: $!";
3733 my @array = map { chomp; $_; } <COMPANYCACHE>;
3738 =item append_fuzzyfiles LASTNAME COMPANY
3742 sub append_fuzzyfiles {
3743 my( $last, $company ) = @_;
3745 &check_and_rebuild_fuzzyfiles;
3747 use Fcntl qw(:flock);
3749 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3753 open(LAST,">>$dir/cust_main.last")
3754 or die "can't open $dir/cust_main.last: $!";
3756 or die "can't lock $dir/cust_main.last: $!";
3758 print LAST "$last\n";
3761 or die "can't unlock $dir/cust_main.last: $!";
3767 open(COMPANY,">>$dir/cust_main.company")
3768 or die "can't open $dir/cust_main.company: $!";
3769 flock(COMPANY,LOCK_EX)
3770 or die "can't lock $dir/cust_main.company: $!";
3772 print COMPANY "$company\n";
3774 flock(COMPANY,LOCK_UN)
3775 or die "can't unlock $dir/cust_main.company: $!";
3789 #warn join('-',keys %$param);
3790 my $fh = $param->{filehandle};
3791 my $agentnum = $param->{agentnum};
3792 my $refnum = $param->{refnum};
3793 my $pkgpart = $param->{pkgpart};
3794 my @fields = @{$param->{fields}};
3796 eval "use Date::Parse;";
3798 eval "use Text::CSV_XS;";
3801 my $csv = new Text::CSV_XS;
3808 local $SIG{HUP} = 'IGNORE';
3809 local $SIG{INT} = 'IGNORE';
3810 local $SIG{QUIT} = 'IGNORE';
3811 local $SIG{TERM} = 'IGNORE';
3812 local $SIG{TSTP} = 'IGNORE';
3813 local $SIG{PIPE} = 'IGNORE';
3815 my $oldAutoCommit = $FS::UID::AutoCommit;
3816 local $FS::UID::AutoCommit = 0;
3819 #while ( $columns = $csv->getline($fh) ) {
3821 while ( defined($line=<$fh>) ) {
3823 $csv->parse($line) or do {
3824 $dbh->rollback if $oldAutoCommit;
3825 return "can't parse: ". $csv->error_input();
3828 my @columns = $csv->fields();
3829 #warn join('-',@columns);
3832 agentnum => $agentnum,
3834 country => $conf->config('countrydefault') || 'US',
3835 payby => 'BILL', #default
3836 paydate => '12/2037', #default
3838 my $billtime = time;
3839 my %cust_pkg = ( pkgpart => $pkgpart );
3840 foreach my $field ( @fields ) {
3841 if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
3842 #$cust_pkg{$1} = str2time( shift @$columns );
3843 if ( $1 eq 'setup' ) {
3844 $billtime = str2time(shift @columns);
3846 $cust_pkg{$1} = str2time( shift @columns );
3849 #$cust_main{$field} = shift @$columns;
3850 $cust_main{$field} = shift @columns;
3854 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
3855 my $cust_main = new FS::cust_main ( \%cust_main );
3857 tie my %hash, 'Tie::RefHash'; #this part is important
3858 $hash{$cust_pkg} = [] if $pkgpart;
3859 my $error = $cust_main->insert( \%hash );
3862 $dbh->rollback if $oldAutoCommit;
3863 return "can't insert customer for $line: $error";
3866 #false laziness w/bill.cgi
3867 $error = $cust_main->bill( 'time' => $billtime );
3869 $dbh->rollback if $oldAutoCommit;
3870 return "can't bill customer for $line: $error";
3873 $cust_main->apply_payments;
3874 $cust_main->apply_credits;
3876 $error = $cust_main->collect();
3878 $dbh->rollback if $oldAutoCommit;
3879 return "can't collect customer for $line: $error";
3885 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3887 return "Empty file!" unless $imported;
3899 #warn join('-',keys %$param);
3900 my $fh = $param->{filehandle};
3901 my @fields = @{$param->{fields}};
3903 eval "use Date::Parse;";
3905 eval "use Text::CSV_XS;";
3908 my $csv = new Text::CSV_XS;
3915 local $SIG{HUP} = 'IGNORE';
3916 local $SIG{INT} = 'IGNORE';
3917 local $SIG{QUIT} = 'IGNORE';
3918 local $SIG{TERM} = 'IGNORE';
3919 local $SIG{TSTP} = 'IGNORE';
3920 local $SIG{PIPE} = 'IGNORE';
3922 my $oldAutoCommit = $FS::UID::AutoCommit;
3923 local $FS::UID::AutoCommit = 0;
3926 #while ( $columns = $csv->getline($fh) ) {
3928 while ( defined($line=<$fh>) ) {
3930 $csv->parse($line) or do {
3931 $dbh->rollback if $oldAutoCommit;
3932 return "can't parse: ". $csv->error_input();
3935 my @columns = $csv->fields();
3936 #warn join('-',@columns);
3939 foreach my $field ( @fields ) {
3940 $row{$field} = shift @columns;
3943 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
3944 unless ( $cust_main ) {
3945 $dbh->rollback if $oldAutoCommit;
3946 return "unknown custnum $row{'custnum'}";
3949 if ( $row{'amount'} > 0 ) {
3950 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
3952 $dbh->rollback if $oldAutoCommit;
3956 } elsif ( $row{'amount'} < 0 ) {
3957 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
3960 $dbh->rollback if $oldAutoCommit;
3970 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3972 return "Empty file!" unless $imported;
3984 The delete method should possibly take an FS::cust_main object reference
3985 instead of a scalar customer number.
3987 Bill and collect options should probably be passed as references instead of a
3990 There should probably be a configuration file with a list of allowed credit
3993 No multiple currency support (probably a larger project than just this module).
3995 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
3999 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4000 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4001 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.