4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles $ignore_expired_card );
6 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 eval "use Time::Local;";
12 die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
13 if $] < 5.006 && !defined($Time::Local::VERSION);
14 #eval "use Time::Local qw(timelocal timelocal_nocheck);";
15 eval "use Time::Local qw(timelocal_nocheck);";
17 use Digest::MD5 qw(md5_base64);
20 use String::Approx qw(amatch);
21 use Business::CreditCard 0.28;
22 use FS::UID qw( getotaker dbh );
23 use FS::Record qw( qsearchs qsearch dbdef );
24 use FS::Misc qw( send_email );
25 use FS::Msgcat qw(gettext);
29 use FS::cust_bill_pkg;
31 use FS::cust_pay_void;
34 use FS::part_referral;
35 use FS::cust_main_county;
37 use FS::cust_main_invoice;
38 use FS::cust_credit_bill;
39 use FS::cust_bill_pay;
40 use FS::prepay_credit;
43 use FS::part_bill_event;
44 use FS::cust_bill_event;
45 use FS::cust_tax_exempt;
47 use FS::payment_gateway;
48 use FS::agent_payment_gateway;
51 @ISA = qw( FS::Record );
53 @EXPORT_OK = qw( smart_search );
55 $realtime_bop_decline_quiet = 0;
57 # 1 is mostly method/subroutine entry and options
58 # 2 traces progress of some operations
59 # 3 is even more information including possibly sensitive data
61 $me = '[FS::cust_main]';
65 $ignore_expired_card = 0;
67 @encrypted_fields = ('payinfo', 'paycvv');
69 #ask FS::UID to run this stuff for us later
70 #$FS::UID::callback{'FS::cust_main'} = sub {
71 install_callback FS::UID sub {
73 #yes, need it for stuff below (prolly should be cached)
78 my ( $hashref, $cache ) = @_;
79 if ( exists $hashref->{'pkgnum'} ) {
80 # #@{ $self->{'_pkgnum'} } = ();
81 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
82 $self->{'_pkgnum'} = $subcache;
83 #push @{ $self->{'_pkgnum'} },
84 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
90 FS::cust_main - Object methods for cust_main records
96 $record = new FS::cust_main \%hash;
97 $record = new FS::cust_main { 'column' => 'value' };
99 $error = $record->insert;
101 $error = $new_record->replace($old_record);
103 $error = $record->delete;
105 $error = $record->check;
107 @cust_pkg = $record->all_pkgs;
109 @cust_pkg = $record->ncancelled_pkgs;
111 @cust_pkg = $record->suspended_pkgs;
113 $error = $record->bill;
114 $error = $record->bill %options;
115 $error = $record->bill 'time' => $time;
117 $error = $record->collect;
118 $error = $record->collect %options;
119 $error = $record->collect 'invoice_time' => $time,
120 'batch_card' => 'yes',
121 'report_badcard' => 'yes',
126 An FS::cust_main object represents a customer. FS::cust_main inherits from
127 FS::Record. The following fields are currently supported:
131 =item custnum - primary key (assigned automatically for new customers)
133 =item agentnum - agent (see L<FS::agent>)
135 =item refnum - Advertising source (see L<FS::part_referral>)
141 =item ss - social security number (optional)
143 =item company - (optional)
147 =item address2 - (optional)
151 =item county - (optional, see L<FS::cust_main_county>)
153 =item state - (see L<FS::cust_main_county>)
157 =item country - (see L<FS::cust_main_county>)
159 =item daytime - phone (optional)
161 =item night - phone (optional)
163 =item fax - phone (optional)
165 =item ship_first - name
167 =item ship_last - name
169 =item ship_company - (optional)
173 =item ship_address2 - (optional)
177 =item ship_county - (optional, see L<FS::cust_main_county>)
179 =item ship_state - (see L<FS::cust_main_county>)
183 =item ship_country - (see L<FS::cust_main_county>)
185 =item ship_daytime - phone (optional)
187 =item ship_night - phone (optional)
189 =item ship_fax - phone (optional)
193 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>)
197 Card Number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
202 my($self,$payinfo) = @_;
203 if ( defined($payinfo) ) {
204 $self->paymask($payinfo);
205 $self->setfield('payinfo', $payinfo); # This is okay since we are the 'setter'
207 $payinfo = $self->getfield('payinfo'); # This is okay since we are the 'getter'
215 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
219 =item paymask - Masked payment type
225 Mask all but the last four characters.
229 Mask all but last 2 of account number and bank routing number.
233 Do nothing, return the unmasked string.
242 # If it doesn't exist then generate it
243 my $paymask=$self->getfield('paymask');
244 if (!defined($value) && (!defined($paymask) || $paymask eq '')) {
245 $value = $self->payinfo;
248 if ( defined($value) && !$self->is_encrypted($value)) {
249 my $payinfo = $value;
250 my $payby = $self->payby;
251 if ($payby eq 'CARD' || $payby eq 'DCRD') { # Credit Cards (Show last four)
252 $paymask = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
253 } elsif ($payby eq 'CHEK' ||
254 $payby eq 'DCHK' ) { # Checks (Show last 2 @ bank)
255 my( $account, $aba ) = split('@', $payinfo );
256 $paymask = 'x'x(length($account)-2). substr($account,(length($account)-2))."@".$aba;
257 } else { # Tie up loose ends
260 $self->setfield('paymask', $paymask); # This is okay since we are the 'setter'
261 } elsif (defined($value) && $self->is_encrypted($value)) {
267 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
269 =item paystart_month - start date month (maestro/solo cards only)
271 =item paystart_year - start date year (maestro/solo cards only)
273 =item payissue - issue number (maestro/solo cards only)
275 =item payname - name on card or billing name
277 =item payip - IP address from which payment information was received
279 =item tax - tax exempt, empty or `Y'
281 =item otaker - order taker (assigned automatically, see L<FS::UID>)
283 =item comments - comments (optional)
285 =item referral_custnum - referring customer number
295 Creates a new customer. To add the customer to the database, see L<"insert">.
297 Note that this stores the hash reference, not a distinct copy of the hash it
298 points to. You can ask the object for a copy with the I<hash> method.
302 sub table { 'cust_main'; }
304 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
306 Adds this customer to the database. If there is an error, returns the error,
307 otherwise returns false.
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back. Passing an empty
312 hash reference is equivalent to not supplying this parameter. There should be
313 a better explanation of this, but until then, here's an example:
316 tie %hash, 'Tie::RefHash'; #this part is important
318 $cust_pkg => [ $svc_acct ],
321 $cust_main->insert( \%hash );
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">). Errors return as
325 expected and rollback the entire transaction; it is not necessary to call
326 check_invoicing_list first. The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct. Here's an example:
330 $cust_main->insert( {}, [ $email, 'POST' ] );
332 Currently available options are: I<depend_jobnum> and I<noexport>.
334 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
335 on the supplied jobnum (they will not run until the specific job completes).
336 This can be used to defer provisioning until some action completes (such
337 as running the customer's credit card sucessfully).
339 The I<noexport> option is deprecated. If I<noexport> is set true, no
340 provisioning jobs (exports) are scheduled. (You can schedule them later with
341 the B<reexport> method.)
347 my $cust_pkgs = @_ ? shift : {};
348 my $invoicing_list = @_ ? shift : '';
350 warn "$me insert called with options ".
351 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
354 local $SIG{HUP} = 'IGNORE';
355 local $SIG{INT} = 'IGNORE';
356 local $SIG{QUIT} = 'IGNORE';
357 local $SIG{TERM} = 'IGNORE';
358 local $SIG{TSTP} = 'IGNORE';
359 local $SIG{PIPE} = 'IGNORE';
361 my $oldAutoCommit = $FS::UID::AutoCommit;
362 local $FS::UID::AutoCommit = 0;
365 my $prepay_identifier = '';
366 my( $amount, $seconds ) = ( 0, 0 );
368 if ( $self->payby eq 'PREPAY' ) {
370 $self->payby('BILL');
371 $prepay_identifier = $self->payinfo;
374 warn " looking up prepaid card $prepay_identifier\n"
377 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
379 $dbh->rollback if $oldAutoCommit;
380 #return "error applying prepaid card (transaction rolled back): $error";
384 $payby = 'PREP' if $amount;
386 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
389 $self->payby('BILL');
390 $amount = $self->paid;
394 warn " inserting $self\n"
397 my $error = $self->SUPER::insert;
399 $dbh->rollback if $oldAutoCommit;
400 #return "inserting cust_main record (transaction rolled back): $error";
404 warn " setting invoicing list\n"
407 if ( $invoicing_list ) {
408 $error = $self->check_invoicing_list( $invoicing_list );
410 $dbh->rollback if $oldAutoCommit;
411 return "checking invoicing_list (transaction rolled back): $error";
413 $self->invoicing_list( $invoicing_list );
416 warn " ordering packages\n"
419 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
421 $dbh->rollback if $oldAutoCommit;
426 $dbh->rollback if $oldAutoCommit;
427 return "No svc_acct record to apply pre-paid time";
431 warn " inserting initial $payby payment of $amount\n"
433 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
435 $dbh->rollback if $oldAutoCommit;
436 return "inserting payment (transaction rolled back): $error";
440 unless ( $import || $skip_fuzzyfiles ) {
441 warn " queueing fuzzyfiles update\n"
443 $error = $self->queue_fuzzyfiles_update;
445 $dbh->rollback if $oldAutoCommit;
446 return "updating fuzzy search cache: $error";
450 warn " insert complete; committing transaction\n"
453 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
458 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
460 Like the insert method on an existing record, this method orders a package
461 and included services atomicaly. Pass a Tie::RefHash data structure to this
462 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
463 be a better explanation of this, but until then, here's an example:
466 tie %hash, 'Tie::RefHash'; #this part is important
468 $cust_pkg => [ $svc_acct ],
471 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
473 Services can be new, in which case they are inserted, or existing unaudited
474 services, in which case they are linked to the newly-created package.
476 Currently available options are: I<depend_jobnum> and I<noexport>.
478 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
479 on the supplied jobnum (they will not run until the specific job completes).
480 This can be used to defer provisioning until some action completes (such
481 as running the customer's credit card sucessfully).
483 The I<noexport> option is deprecated. If I<noexport> is set true, no
484 provisioning jobs (exports) are scheduled. (You can schedule them later with
485 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
486 on the cust_main object is not recommended, as existing services will also be
493 my $cust_pkgs = shift;
496 my %svc_options = ();
497 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
498 if exists $options{'depend_jobnum'};
499 warn "$me order_pkgs called with options ".
500 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
503 local $SIG{HUP} = 'IGNORE';
504 local $SIG{INT} = 'IGNORE';
505 local $SIG{QUIT} = 'IGNORE';
506 local $SIG{TERM} = 'IGNORE';
507 local $SIG{TSTP} = 'IGNORE';
508 local $SIG{PIPE} = 'IGNORE';
510 my $oldAutoCommit = $FS::UID::AutoCommit;
511 local $FS::UID::AutoCommit = 0;
514 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
516 foreach my $cust_pkg ( keys %$cust_pkgs ) {
517 $cust_pkg->custnum( $self->custnum );
518 my $error = $cust_pkg->insert;
520 $dbh->rollback if $oldAutoCommit;
521 return "inserting cust_pkg (transaction rolled back): $error";
523 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
524 if ( $svc_something->svcnum ) {
525 my $old_cust_svc = $svc_something->cust_svc;
526 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
527 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
528 $error = $new_cust_svc->replace($old_cust_svc);
530 $svc_something->pkgnum( $cust_pkg->pkgnum );
531 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
532 $svc_something->seconds( $svc_something->seconds + $$seconds );
535 $error = $svc_something->insert(%svc_options);
538 $dbh->rollback if $oldAutoCommit;
539 #return "inserting svc_ (transaction rolled back): $error";
545 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
549 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF ]
551 Recharges this (existing) customer with the specified prepaid card (see
552 L<FS::prepay_credit>), specified either by I<identifier> or as an
553 FS::prepay_credit object. If there is an error, returns the error, otherwise
556 Optionally, two scalar references can be passed as well. They will have their
557 values filled in with the amount and number of seconds applied by this prepaid
562 sub recharge_prepay {
563 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
565 local $SIG{HUP} = 'IGNORE';
566 local $SIG{INT} = 'IGNORE';
567 local $SIG{QUIT} = 'IGNORE';
568 local $SIG{TERM} = 'IGNORE';
569 local $SIG{TSTP} = 'IGNORE';
570 local $SIG{PIPE} = 'IGNORE';
572 my $oldAutoCommit = $FS::UID::AutoCommit;
573 local $FS::UID::AutoCommit = 0;
576 my( $amount, $seconds ) = ( 0, 0 );
578 my $error = $self->get_prepay($prepay_credit, \$amount, \$seconds)
579 || $self->increment_seconds($seconds)
580 || $self->insert_cust_pay_prepay( $amount,
582 ? $prepay_credit->identifier
587 $dbh->rollback if $oldAutoCommit;
591 if ( defined($amountref) ) { $$amountref = $amount; }
592 if ( defined($secondsref) ) { $$secondsref = $seconds; }
594 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
599 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
601 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
602 specified either by I<identifier> or as an FS::prepay_credit object.
604 References to I<amount> and I<seconds> scalars should be passed as arguments
605 and will be incremented by the values of the prepaid card.
607 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
608 check or set this customer's I<agentnum>.
610 If there is an error, returns the error, otherwise returns false.
616 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
618 local $SIG{HUP} = 'IGNORE';
619 local $SIG{INT} = 'IGNORE';
620 local $SIG{QUIT} = 'IGNORE';
621 local $SIG{TERM} = 'IGNORE';
622 local $SIG{TSTP} = 'IGNORE';
623 local $SIG{PIPE} = 'IGNORE';
625 my $oldAutoCommit = $FS::UID::AutoCommit;
626 local $FS::UID::AutoCommit = 0;
629 unless ( ref($prepay_credit) ) {
631 my $identifier = $prepay_credit;
633 $prepay_credit = qsearchs(
635 { 'identifier' => $prepay_credit },
640 unless ( $prepay_credit ) {
641 $dbh->rollback if $oldAutoCommit;
642 return "Invalid prepaid card: ". $identifier;
647 if ( $prepay_credit->agentnum ) {
648 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
649 $dbh->rollback if $oldAutoCommit;
650 return "prepaid card not valid for agent ". $self->agentnum;
652 $self->agentnum($prepay_credit->agentnum);
655 my $error = $prepay_credit->delete;
657 $dbh->rollback if $oldAutoCommit;
658 return "removing prepay_credit (transaction rolled back): $error";
661 $$amountref += $prepay_credit->amount;
662 $$secondsref += $prepay_credit->seconds;
664 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
669 =item increment_seconds SECONDS
671 Updates this customer's single or primary account (see L<FS::svc_acct>) by
672 the specified number of seconds. If there is an error, returns the error,
673 otherwise returns false.
677 sub increment_seconds {
678 my( $self, $seconds ) = @_;
679 warn "$me increment_seconds called: $seconds seconds\n"
682 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
683 $self->ncancelled_pkgs;
686 return 'No packages with primary or single services found'.
687 ' to apply pre-paid time';
688 } elsif ( scalar(@cust_pkg) > 1 ) {
689 #maybe have a way to specify the package/account?
690 return 'Multiple packages found to apply pre-paid time';
693 my $cust_pkg = $cust_pkg[0];
694 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
698 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
701 return 'No account found to apply pre-paid time';
702 } elsif ( scalar(@cust_svc) > 1 ) {
703 return 'Multiple accounts found to apply pre-paid time';
706 my $svc_acct = $cust_svc[0]->svc_x;
707 warn " found service svcnum ". $svc_acct->pkgnum.
708 ' ('. $svc_acct->email. ")\n"
711 $svc_acct->increment_seconds($seconds);
715 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
717 Inserts a prepayment in the specified amount for this customer. An optional
718 second argument can specify the prepayment identifier for tracking purposes.
719 If there is an error, returns the error, otherwise returns false.
723 sub insert_cust_pay_prepay {
724 shift->insert_cust_pay('PREP', @_);
727 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
729 Inserts a cash payment in the specified amount for this customer. An optional
730 second argument can specify the payment identifier for tracking purposes.
731 If there is an error, returns the error, otherwise returns false.
735 sub insert_cust_pay_cash {
736 shift->insert_cust_pay('CASH', @_);
739 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
741 Inserts a Western Union payment in the specified amount for this customer. An
742 optional second argument can specify the prepayment identifier for tracking
743 purposes. If there is an error, returns the error, otherwise returns false.
747 sub insert_cust_pay_west {
748 shift->insert_cust_pay('WEST', @_);
751 sub insert_cust_pay {
752 my( $self, $payby, $amount ) = splice(@_, 0, 3);
753 my $payinfo = scalar(@_) ? shift : '';
755 my $cust_pay = new FS::cust_pay {
756 'custnum' => $self->custnum,
757 'paid' => sprintf('%.2f', $amount),
758 #'_date' => #date the prepaid card was purchased???
760 'payinfo' => $payinfo,
768 This method is deprecated. See the I<depend_jobnum> option to the insert and
769 order_pkgs methods for a better way to defer provisioning.
771 Re-schedules all exports by calling the B<reexport> method of all associated
772 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
773 otherwise returns false.
780 carp "WARNING: FS::cust_main::reexport is deprectated; ".
781 "use the depend_jobnum option to insert or order_pkgs to delay export";
783 local $SIG{HUP} = 'IGNORE';
784 local $SIG{INT} = 'IGNORE';
785 local $SIG{QUIT} = 'IGNORE';
786 local $SIG{TERM} = 'IGNORE';
787 local $SIG{TSTP} = 'IGNORE';
788 local $SIG{PIPE} = 'IGNORE';
790 my $oldAutoCommit = $FS::UID::AutoCommit;
791 local $FS::UID::AutoCommit = 0;
794 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
795 my $error = $cust_pkg->reexport;
797 $dbh->rollback if $oldAutoCommit;
802 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
807 =item delete NEW_CUSTNUM
809 This deletes the customer. If there is an error, returns the error, otherwise
812 This will completely remove all traces of the customer record. This is not
813 what you want when a customer cancels service; for that, cancel all of the
814 customer's packages (see L</cancel>).
816 If the customer has any uncancelled packages, you need to pass a new (valid)
817 customer number for those packages to be transferred to. Cancelled packages
818 will be deleted. Did I mention that this is NOT what you want when a customer
819 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
821 You can't delete a customer with invoices (see L<FS::cust_bill>),
822 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
823 refunds (see L<FS::cust_refund>).
830 local $SIG{HUP} = 'IGNORE';
831 local $SIG{INT} = 'IGNORE';
832 local $SIG{QUIT} = 'IGNORE';
833 local $SIG{TERM} = 'IGNORE';
834 local $SIG{TSTP} = 'IGNORE';
835 local $SIG{PIPE} = 'IGNORE';
837 my $oldAutoCommit = $FS::UID::AutoCommit;
838 local $FS::UID::AutoCommit = 0;
841 if ( $self->cust_bill ) {
842 $dbh->rollback if $oldAutoCommit;
843 return "Can't delete a customer with invoices";
845 if ( $self->cust_credit ) {
846 $dbh->rollback if $oldAutoCommit;
847 return "Can't delete a customer with credits";
849 if ( $self->cust_pay ) {
850 $dbh->rollback if $oldAutoCommit;
851 return "Can't delete a customer with payments";
853 if ( $self->cust_refund ) {
854 $dbh->rollback if $oldAutoCommit;
855 return "Can't delete a customer with refunds";
858 my @cust_pkg = $self->ncancelled_pkgs;
860 my $new_custnum = shift;
861 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
862 $dbh->rollback if $oldAutoCommit;
863 return "Invalid new customer number: $new_custnum";
865 foreach my $cust_pkg ( @cust_pkg ) {
866 my %hash = $cust_pkg->hash;
867 $hash{'custnum'} = $new_custnum;
868 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
869 my $error = $new_cust_pkg->replace($cust_pkg);
871 $dbh->rollback if $oldAutoCommit;
876 my @cancelled_cust_pkg = $self->all_pkgs;
877 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
878 my $error = $cust_pkg->delete;
880 $dbh->rollback if $oldAutoCommit;
885 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
886 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
888 my $error = $cust_main_invoice->delete;
890 $dbh->rollback if $oldAutoCommit;
895 my $error = $self->SUPER::delete;
897 $dbh->rollback if $oldAutoCommit;
901 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
906 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
908 Replaces the OLD_RECORD with this one in the database. If there is an error,
909 returns the error, otherwise returns false.
911 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
912 be set as the invoicing list (see L<"invoicing_list">). Errors return as
913 expected and rollback the entire transaction; it is not necessary to call
914 check_invoicing_list first. Here's an example:
916 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
925 local $SIG{HUP} = 'IGNORE';
926 local $SIG{INT} = 'IGNORE';
927 local $SIG{QUIT} = 'IGNORE';
928 local $SIG{TERM} = 'IGNORE';
929 local $SIG{TSTP} = 'IGNORE';
930 local $SIG{PIPE} = 'IGNORE';
932 # If the mask is blank then try to set it - if we can...
933 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
934 $self->paymask($self->payinfo);
937 # We absolutely have to have an old vs. new record to make this work.
938 if (!defined($old)) {
939 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
942 if ( $self->payby eq 'COMP' && $self->payby ne $old->payby
943 && $conf->config('users-allow_comp') ) {
944 return "You are not permitted to create complimentary accounts."
945 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
948 local($ignore_expired_card) = 1
949 if $old->payby =~ /^(CARD|DCRD)$/
950 && $self->payby =~ /^(CARD|DCRD)$/
951 && $old->payinfo eq $self->payinfo;
953 my $oldAutoCommit = $FS::UID::AutoCommit;
954 local $FS::UID::AutoCommit = 0;
957 my $error = $self->SUPER::replace($old);
960 $dbh->rollback if $oldAutoCommit;
964 if ( @param ) { # INVOICING_LIST_ARYREF
965 my $invoicing_list = shift @param;
966 $error = $self->check_invoicing_list( $invoicing_list );
968 $dbh->rollback if $oldAutoCommit;
971 $self->invoicing_list( $invoicing_list );
974 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
975 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
976 # card/check/lec info has changed, want to retry realtime_ invoice events
977 my $error = $self->retry_realtime;
979 $dbh->rollback if $oldAutoCommit;
984 unless ( $import || $skip_fuzzyfiles ) {
985 $error = $self->queue_fuzzyfiles_update;
987 $dbh->rollback if $oldAutoCommit;
988 return "updating fuzzy search cache: $error";
992 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
997 =item queue_fuzzyfiles_update
999 Used by insert & replace to update the fuzzy search cache
1003 sub queue_fuzzyfiles_update {
1006 local $SIG{HUP} = 'IGNORE';
1007 local $SIG{INT} = 'IGNORE';
1008 local $SIG{QUIT} = 'IGNORE';
1009 local $SIG{TERM} = 'IGNORE';
1010 local $SIG{TSTP} = 'IGNORE';
1011 local $SIG{PIPE} = 'IGNORE';
1013 my $oldAutoCommit = $FS::UID::AutoCommit;
1014 local $FS::UID::AutoCommit = 0;
1017 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1018 my $error = $queue->insert($self->getfield('last'), $self->company);
1020 $dbh->rollback if $oldAutoCommit;
1021 return "queueing job (transaction rolled back): $error";
1024 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
1025 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1026 $error = $queue->insert($self->getfield('ship_last'), $self->ship_company);
1028 $dbh->rollback if $oldAutoCommit;
1029 return "queueing job (transaction rolled back): $error";
1033 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1040 Checks all fields to make sure this is a valid customer record. If there is
1041 an error, returns the error, otherwise returns false. Called by the insert
1042 and replace methods.
1049 warn "$me check BEFORE: \n". $self->_dump
1053 $self->ut_numbern('custnum')
1054 || $self->ut_number('agentnum')
1055 || $self->ut_number('refnum')
1056 || $self->ut_name('last')
1057 || $self->ut_name('first')
1058 || $self->ut_textn('company')
1059 || $self->ut_text('address1')
1060 || $self->ut_textn('address2')
1061 || $self->ut_text('city')
1062 || $self->ut_textn('county')
1063 || $self->ut_textn('state')
1064 || $self->ut_country('country')
1065 || $self->ut_anything('comments')
1066 || $self->ut_numbern('referral_custnum')
1068 #barf. need message catalogs. i18n. etc.
1069 $error .= "Please select an advertising source."
1070 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1071 return $error if $error;
1073 return "Unknown agent"
1074 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1076 return "Unknown refnum"
1077 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1079 return "Unknown referring custnum: ". $self->referral_custnum
1080 unless ! $self->referral_custnum
1081 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1083 if ( $self->ss eq '' ) {
1088 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1089 or return "Illegal social security number: ". $self->ss;
1090 $self->ss("$1-$2-$3");
1094 # bad idea to disable, causes billing to fail because of no tax rates later
1095 # unless ( $import ) {
1096 unless ( qsearch('cust_main_county', {
1097 'country' => $self->country,
1100 return "Unknown state/county/country: ".
1101 $self->state. "/". $self->county. "/". $self->country
1102 unless qsearch('cust_main_county',{
1103 'state' => $self->state,
1104 'county' => $self->county,
1105 'country' => $self->country,
1111 $self->ut_phonen('daytime', $self->country)
1112 || $self->ut_phonen('night', $self->country)
1113 || $self->ut_phonen('fax', $self->country)
1114 || $self->ut_zip('zip', $self->country)
1116 return $error if $error;
1119 last first company address1 address2 city county state zip
1120 country daytime night fax
1123 if ( defined $self->dbdef_table->column('ship_last') ) {
1124 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1126 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1130 $self->ut_name('ship_last')
1131 || $self->ut_name('ship_first')
1132 || $self->ut_textn('ship_company')
1133 || $self->ut_text('ship_address1')
1134 || $self->ut_textn('ship_address2')
1135 || $self->ut_text('ship_city')
1136 || $self->ut_textn('ship_county')
1137 || $self->ut_textn('ship_state')
1138 || $self->ut_country('ship_country')
1140 return $error if $error;
1142 #false laziness with above
1143 unless ( qsearchs('cust_main_county', {
1144 'country' => $self->ship_country,
1147 return "Unknown ship_state/ship_county/ship_country: ".
1148 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1149 unless qsearch('cust_main_county',{
1150 'state' => $self->ship_state,
1151 'county' => $self->ship_county,
1152 'country' => $self->ship_country,
1158 $self->ut_phonen('ship_daytime', $self->ship_country)
1159 || $self->ut_phonen('ship_night', $self->ship_country)
1160 || $self->ut_phonen('ship_fax', $self->ship_country)
1161 || $self->ut_zip('ship_zip', $self->ship_country)
1163 return $error if $error;
1165 } else { # ship_ info eq billing info, so don't store dup info in database
1166 $self->setfield("ship_$_", '')
1167 foreach qw( last first company address1 address2 city county state zip
1168 country daytime night fax );
1172 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1173 or return "Illegal payby: ". $self->payby;
1175 $error = $self->ut_numbern('paystart_month')
1176 || $self->ut_numbern('paystart_year')
1177 || $self->ut_numbern('payissue')
1179 return $error if $error;
1181 if ( $self->payip eq '' ) {
1184 $error = $self->ut_ip('payip');
1185 return $error if $error;
1188 # If it is encrypted and the private key is not availaible then we can't
1189 # check the credit card.
1191 my $check_payinfo = 1;
1193 if ($self->is_encrypted($self->payinfo)) {
1199 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1201 my $payinfo = $self->payinfo;
1202 $payinfo =~ s/\D//g;
1203 $payinfo =~ /^(\d{13,16})$/
1204 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1206 $self->payinfo($payinfo);
1208 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1210 return gettext('unknown_card_type')
1211 if cardtype($self->payinfo) eq "Unknown";
1213 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1214 return "Banned credit card" if $ban;
1216 if ( defined $self->dbdef_table->column('paycvv') ) {
1217 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1218 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1219 $self->paycvv =~ /^(\d{4})$/
1220 or return "CVV2 (CID) for American Express cards is four digits.";
1223 $self->paycvv =~ /^(\d{3})$/
1224 or return "CVV2 (CVC2/CID) is three digits.";
1232 my $cardtype = cardtype($payinfo);
1233 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1235 return "Start date or issue number is required for $cardtype cards"
1236 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1238 return "Start month must be between 1 and 12"
1239 if $self->paystart_month
1240 and $self->paystart_month < 1 || $self->paystart_month > 12;
1242 return "Start year must be 1990 or later"
1243 if $self->paystart_year
1244 and $self->paystart_year < 1990;
1246 return "Issue number must be beween 1 and 99"
1248 and $self->payissue < 1 || $self->payissue > 99;
1251 $self->paystart_month('');
1252 $self->paystart_year('');
1253 $self->payissue('');
1256 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1258 my $payinfo = $self->payinfo;
1259 $payinfo =~ s/[^\d\@]//g;
1260 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1261 $payinfo = "$1\@$2";
1262 $self->payinfo($payinfo);
1263 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1265 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1266 return "Banned ACH account" if $ban;
1268 } elsif ( $self->payby eq 'LECB' ) {
1270 my $payinfo = $self->payinfo;
1271 $payinfo =~ s/\D//g;
1272 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1274 $self->payinfo($payinfo);
1275 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1277 } elsif ( $self->payby eq 'BILL' ) {
1279 $error = $self->ut_textn('payinfo');
1280 return "Illegal P.O. number: ". $self->payinfo if $error;
1281 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1283 } elsif ( $self->payby eq 'COMP' ) {
1285 if ( !$self->custnum && $conf->config('users-allow_comp') ) {
1286 return "You are not permitted to create complimentary accounts."
1287 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
1290 $error = $self->ut_textn('payinfo');
1291 return "Illegal comp account issuer: ". $self->payinfo if $error;
1292 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1294 } elsif ( $self->payby eq 'PREPAY' ) {
1296 my $payinfo = $self->payinfo;
1297 $payinfo =~ s/\W//g; #anything else would just confuse things
1298 $self->payinfo($payinfo);
1299 $error = $self->ut_alpha('payinfo');
1300 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1301 return "Unknown prepayment identifier"
1302 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1303 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1307 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1308 return "Expriation date required"
1309 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1313 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1314 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1315 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1316 ( $m, $y ) = ( $3, "20$2" );
1318 return "Illegal expiration date: ". $self->paydate;
1320 $self->paydate("$y-$m-01");
1321 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1322 return gettext('expired_card')
1324 && !$ignore_expired_card
1325 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1328 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1329 ( ! $conf->exists('require_cardname')
1330 || $self->payby !~ /^(CARD|DCRD)$/ )
1332 $self->payname( $self->first. " ". $self->getfield('last') );
1334 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1335 or return gettext('illegal_name'). " payname: ". $self->payname;
1339 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
1342 $self->otaker(getotaker) unless $self->otaker;
1344 warn "$me check AFTER: \n". $self->_dump
1347 $self->SUPER::check;
1352 Returns all packages (see L<FS::cust_pkg>) for this customer.
1358 if ( $self->{'_pkgnum'} ) {
1359 values %{ $self->{'_pkgnum'}->cache };
1361 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1365 =item ncancelled_pkgs
1367 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1371 sub ncancelled_pkgs {
1373 if ( $self->{'_pkgnum'} ) {
1374 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1376 @{ [ # force list context
1377 qsearch( 'cust_pkg', {
1378 'custnum' => $self->custnum,
1381 qsearch( 'cust_pkg', {
1382 'custnum' => $self->custnum,
1389 =item suspended_pkgs
1391 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1395 sub suspended_pkgs {
1397 grep { $_->susp } $self->ncancelled_pkgs;
1400 =item unflagged_suspended_pkgs
1402 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1403 customer (thouse packages without the `manual_flag' set).
1407 sub unflagged_suspended_pkgs {
1409 return $self->suspended_pkgs
1410 unless dbdef->table('cust_pkg')->column('manual_flag');
1411 grep { ! $_->manual_flag } $self->suspended_pkgs;
1414 =item unsuspended_pkgs
1416 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1421 sub unsuspended_pkgs {
1423 grep { ! $_->susp } $self->ncancelled_pkgs;
1426 =item num_cancelled_pkgs
1428 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1433 sub num_cancelled_pkgs {
1435 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1439 my( $self, $sql ) = @_;
1440 my $sth = dbh->prepare(
1441 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1442 ) or die dbh->errstr;
1443 $sth->execute($self->custnum) or die $sth->errstr;
1444 $sth->fetchrow_arrayref->[0];
1449 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1450 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1451 on success or a list of errors.
1457 grep { $_->unsuspend } $self->suspended_pkgs;
1462 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1464 Returns a list: an empty list on success or a list of errors.
1470 grep { $_->suspend } $self->unsuspended_pkgs;
1473 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1475 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1476 PKGPARTs (see L<FS::part_pkg>).
1478 Returns a list: an empty list on success or a list of errors.
1482 sub suspend_if_pkgpart {
1485 grep { $_->suspend }
1486 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1487 $self->unsuspended_pkgs;
1490 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1492 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1493 listed PKGPARTs (see L<FS::part_pkg>).
1495 Returns a list: an empty list on success or a list of errors.
1499 sub suspend_unless_pkgpart {
1502 grep { $_->suspend }
1503 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1504 $self->unsuspended_pkgs;
1507 =item cancel [ OPTION => VALUE ... ]
1509 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1511 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1513 I<quiet> can be set true to supress email cancellation notices.
1515 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1517 I<ban> can be set true to ban this customer's credit card or ACH information,
1520 Always returns a list: an empty list on success or a list of errors.
1528 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1530 #should try decryption (we might have the private key)
1531 # and if not maybe queue a job for the server that does?
1532 return ( "Can't (yet) ban encrypted credit cards" )
1533 if $self->is_encrypted($self->payinfo);
1535 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1536 my $error = $ban->insert;
1537 return ( $error ) if $error;
1541 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1544 sub _banned_pay_hashref {
1555 'payby' => $payby2ban{$self->payby},
1556 'payinfo' => md5_base64($self->payinfo),
1563 Returns the agent (see L<FS::agent>) for this customer.
1569 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1574 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1575 conjunction with the collect method.
1577 Options are passed as name-value pairs.
1579 Currently available options are:
1581 resetup - if set true, re-charges setup fees.
1583 time - bills the customer as if it were that time. Specified as a UNIX
1584 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1585 L<Date::Parse> for conversion functions. For example:
1589 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1592 If there is an error, returns the error, otherwise returns false.
1597 my( $self, %options ) = @_;
1598 return '' if $self->payby eq 'COMP';
1599 warn "$me bill customer ". $self->custnum. "\n"
1602 my $time = $options{'time'} || time;
1607 local $SIG{HUP} = 'IGNORE';
1608 local $SIG{INT} = 'IGNORE';
1609 local $SIG{QUIT} = 'IGNORE';
1610 local $SIG{TERM} = 'IGNORE';
1611 local $SIG{TSTP} = 'IGNORE';
1612 local $SIG{PIPE} = 'IGNORE';
1614 my $oldAutoCommit = $FS::UID::AutoCommit;
1615 local $FS::UID::AutoCommit = 0;
1618 $self->select_for_update; #mutex
1620 # find the packages which are due for billing, find out how much they are
1621 # & generate invoice database.
1623 my( $total_setup, $total_recur ) = ( 0, 0 );
1624 #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
1625 my @cust_bill_pkg = ();
1627 #my $taxable_charged = 0;##
1632 foreach my $cust_pkg (
1633 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1636 #NO!! next if $cust_pkg->cancel;
1637 next if $cust_pkg->getfield('cancel');
1639 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1641 #? to avoid use of uninitialized value errors... ?
1642 $cust_pkg->setfield('bill', '')
1643 unless defined($cust_pkg->bill);
1645 my $part_pkg = $cust_pkg->part_pkg;
1647 my %hash = $cust_pkg->hash;
1648 my $old_cust_pkg = new FS::cust_pkg \%hash;
1654 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1656 warn " bill setup\n" if $DEBUG > 1;
1658 $setup = eval { $cust_pkg->calc_setup( $time ) };
1660 $dbh->rollback if $oldAutoCommit;
1664 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1670 if ( $part_pkg->getfield('freq') ne '0' &&
1671 ! $cust_pkg->getfield('susp') &&
1672 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1675 warn " bill recur\n" if $DEBUG > 1;
1677 # XXX shared with $recur_prog
1678 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1680 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details ) };
1682 $dbh->rollback if $oldAutoCommit;
1686 #change this bit to use Date::Manip? CAREFUL with timezones (see
1687 # mailing list archive)
1688 my ($sec,$min,$hour,$mday,$mon,$year) =
1689 (localtime($sdate) )[0,1,2,3,4,5];
1691 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1692 # only for figuring next bill date, nothing else, so, reset $sdate again
1694 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1695 $cust_pkg->last_bill($sdate)
1696 if $cust_pkg->dbdef_table->column('last_bill');
1698 if ( $part_pkg->freq =~ /^\d+$/ ) {
1699 $mon += $part_pkg->freq;
1700 until ( $mon < 12 ) { $mon -= 12; $year++; }
1701 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1703 $mday += $weeks * 7;
1704 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1707 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1711 $dbh->rollback if $oldAutoCommit;
1712 return "unparsable frequency: ". $part_pkg->freq;
1714 $cust_pkg->setfield('bill',
1715 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1718 warn "\$setup is undefined" unless defined($setup);
1719 warn "\$recur is undefined" unless defined($recur);
1720 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1722 if ( $cust_pkg->modified ) {
1724 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1727 $error=$cust_pkg->replace($old_cust_pkg);
1728 if ( $error ) { #just in case
1729 $dbh->rollback if $oldAutoCommit;
1730 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1733 $setup = sprintf( "%.2f", $setup );
1734 $recur = sprintf( "%.2f", $recur );
1735 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1736 $dbh->rollback if $oldAutoCommit;
1737 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1739 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1740 $dbh->rollback if $oldAutoCommit;
1741 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1743 if ( $setup != 0 || $recur != 0 ) {
1744 warn " charges (setup=$setup, recur=$recur); queueing line items\n"
1746 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1747 'pkgnum' => $cust_pkg->pkgnum,
1751 'edate' => $cust_pkg->bill,
1752 'details' => \@details,
1754 push @cust_bill_pkg, $cust_bill_pkg;
1755 $total_setup += $setup;
1756 $total_recur += $recur;
1758 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1760 my @taxes = qsearch( 'cust_main_county', {
1761 'state' => $self->state,
1762 'county' => $self->county,
1763 'country' => $self->country,
1764 'taxclass' => $part_pkg->taxclass,
1767 @taxes = qsearch( 'cust_main_county', {
1768 'state' => $self->state,
1769 'county' => $self->county,
1770 'country' => $self->country,
1775 #one more try at a whole-country tax rate
1777 @taxes = qsearch( 'cust_main_county', {
1780 'country' => $self->country,
1785 # maybe eliminate this entirely, along with all the 0% records
1787 $dbh->rollback if $oldAutoCommit;
1789 "fatal: can't find tax rate for state/county/country/taxclass ".
1790 join('/', ( map $self->$_(), qw(state county country) ),
1791 $part_pkg->taxclass ). "\n";
1794 foreach my $tax ( @taxes ) {
1796 my $taxable_charged = 0;
1797 $taxable_charged += $setup
1798 unless $part_pkg->setuptax =~ /^Y$/i
1799 || $tax->setuptax =~ /^Y$/i;
1800 $taxable_charged += $recur
1801 unless $part_pkg->recurtax =~ /^Y$/i
1802 || $tax->recurtax =~ /^Y$/i;
1803 next unless $taxable_charged;
1805 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
1806 my ($mon,$year) = (localtime($sdate) )[4,5];
1808 my $freq = $part_pkg->freq || 1;
1809 if ( $freq !~ /(\d+)$/ ) {
1810 $dbh->rollback if $oldAutoCommit;
1811 return "daily/weekly package definitions not (yet?)".
1812 " compatible with monthly tax exemptions";
1814 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1815 foreach my $which_month ( 1 .. $freq ) {
1817 'custnum' => $self->custnum,
1818 'taxnum' => $tax->taxnum,
1819 'year' => 1900+$year,
1822 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1823 until ( $mon < 13 ) { $mon -= 12; $year++; }
1824 my $cust_tax_exempt =
1825 qsearchs('cust_tax_exempt', \%hash)
1826 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1827 my $remaining_exemption = sprintf("%.2f",
1828 $tax->exempt_amount - $cust_tax_exempt->amount );
1829 if ( $remaining_exemption > 0 ) {
1830 my $addl = $remaining_exemption > $taxable_per_month
1831 ? $taxable_per_month
1832 : $remaining_exemption;
1833 $taxable_charged -= $addl;
1834 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1835 $cust_tax_exempt->hash,
1837 sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1839 $error = $new_cust_tax_exempt->exemptnum
1840 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1841 : $new_cust_tax_exempt->insert;
1843 $dbh->rollback if $oldAutoCommit;
1844 return "fatal: can't update cust_tax_exempt: $error";
1847 } # if $remaining_exemption > 0
1849 } #foreach $which_month
1851 } #if $tax->exempt_amount
1853 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1855 #$tax += $taxable_charged * $cust_main_county->tax / 100
1856 $tax{ $tax->taxname || 'Tax' } +=
1857 $taxable_charged * $tax->tax / 100
1859 } #foreach my $tax ( @taxes )
1861 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
1863 } #if $setup != 0 || $recur != 0
1865 } #if $cust_pkg->modified
1867 } #foreach my $cust_pkg
1869 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1870 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1872 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1873 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1877 # unless ( $self->tax =~ /Y/i
1878 # || $self->payby eq 'COMP'
1879 # || $taxable_charged == 0 ) {
1880 # my $cust_main_county = qsearchs('cust_main_county',{
1881 # 'state' => $self->state,
1882 # 'county' => $self->county,
1883 # 'country' => $self->country,
1884 # } ) or die "fatal: can't find tax rate for state/county/country ".
1885 # $self->state. "/". $self->county. "/". $self->country. "\n";
1886 # my $tax = sprintf( "%.2f",
1887 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1890 if ( dbdef->table('cust_bill_pkg')->column('itemdesc') ) { #1.5 schema
1892 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
1893 my $tax = sprintf("%.2f", $tax{$taxname} );
1894 $charged = sprintf( "%.2f", $charged+$tax );
1896 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1902 'itemdesc' => $taxname,
1904 push @cust_bill_pkg, $cust_bill_pkg;
1907 } else { #1.4 schema
1910 foreach ( values %tax ) { $tax += $_ };
1911 $tax = sprintf("%.2f", $tax);
1913 $charged = sprintf( "%.2f", $charged+$tax );
1915 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1922 push @cust_bill_pkg, $cust_bill_pkg;
1927 my $cust_bill = new FS::cust_bill ( {
1928 'custnum' => $self->custnum,
1930 'charged' => $charged,
1932 $error = $cust_bill->insert;
1934 $dbh->rollback if $oldAutoCommit;
1935 return "can't create invoice for customer #". $self->custnum. ": $error";
1938 my $invnum = $cust_bill->invnum;
1940 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1942 $cust_bill_pkg->invnum($invnum);
1943 $error = $cust_bill_pkg->insert;
1945 $dbh->rollback if $oldAutoCommit;
1946 return "can't create invoice line item for customer #". $self->custnum.
1951 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1955 =item collect OPTIONS
1957 (Attempt to) collect money for this customer's outstanding invoices (see
1958 L<FS::cust_bill>). Usually used after the bill method.
1960 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
1961 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
1962 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
1964 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1965 and the invoice events web interface.
1967 If there is an error, returns the error, otherwise returns false.
1969 Options are passed as name-value pairs.
1971 Currently available options are:
1973 invoice_time - Use this time when deciding when to print invoices and
1974 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>
1975 for conversion functions.
1977 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
1980 retry_card - Deprecated alias for 'retry'
1982 batch_card - This option is deprecated. See the invoice events web interface
1983 to control whether cards are batched or run against a realtime gateway.
1985 report_badcard - This option is deprecated.
1987 force_print - This option is deprecated; see the invoice events web interface.
1989 quiet - set true to surpress email card/ACH decline notices.
1994 my( $self, %options ) = @_;
1995 my $invoice_time = $options{'invoice_time'} || time;
1998 local $SIG{HUP} = 'IGNORE';
1999 local $SIG{INT} = 'IGNORE';
2000 local $SIG{QUIT} = 'IGNORE';
2001 local $SIG{TERM} = 'IGNORE';
2002 local $SIG{TSTP} = 'IGNORE';
2003 local $SIG{PIPE} = 'IGNORE';
2005 my $oldAutoCommit = $FS::UID::AutoCommit;
2006 local $FS::UID::AutoCommit = 0;
2009 $self->select_for_update; #mutex
2011 my $balance = $self->balance;
2012 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2014 unless ( $balance > 0 ) { #redundant?????
2015 $dbh->rollback if $oldAutoCommit; #hmm
2019 if ( exists($options{'retry_card'}) ) {
2020 carp 'retry_card option passed to collect is deprecated; use retry';
2021 $options{'retry'} ||= $options{'retry_card'};
2023 if ( exists($options{'retry'}) && $options{'retry'} ) {
2024 my $error = $self->retry_realtime;
2026 $dbh->rollback if $oldAutoCommit;
2031 foreach my $cust_bill ( $self->open_cust_bill ) {
2033 # don't try to charge for the same invoice if it's already in a batch
2034 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2036 last if $self->balance <= 0;
2038 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2041 foreach my $part_bill_event (
2042 sort { $a->seconds <=> $b->seconds
2043 || $a->weight <=> $b->weight
2044 || $a->eventpart <=> $b->eventpart }
2045 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
2046 && ! qsearch( 'cust_bill_event', {
2047 'invnum' => $cust_bill->invnum,
2048 'eventpart' => $_->eventpart,
2052 qsearch('part_bill_event', { 'payby' => $self->payby,
2053 'disabled' => '', } )
2056 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2057 || $self->balance <= 0; # or if balance<=0
2059 warn " calling invoice event (". $part_bill_event->eventcode. ")\n"
2061 my $cust_main = $self; #for callback
2065 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2066 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
2067 $error = eval $part_bill_event->eventcode;
2071 my $statustext = '';
2075 } elsif ( $error ) {
2077 $statustext = $error;
2082 #add cust_bill_event
2083 my $cust_bill_event = new FS::cust_bill_event {
2084 'invnum' => $cust_bill->invnum,
2085 'eventpart' => $part_bill_event->eventpart,
2086 #'_date' => $invoice_time,
2088 'status' => $status,
2089 'statustext' => $statustext,
2091 $error = $cust_bill_event->insert;
2093 #$dbh->rollback if $oldAutoCommit;
2094 #return "error: $error";
2096 # gah, even with transactions.
2097 $dbh->commit if $oldAutoCommit; #well.
2098 my $e = 'WARNING: Event run but database not updated - '.
2099 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
2100 ', eventpart '. $part_bill_event->eventpart.
2111 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2116 =item retry_realtime
2118 Schedules realtime credit card / electronic check / LEC billing events for
2119 for retry. Useful if card information has changed or manual retry is desired.
2120 The 'collect' method must be called to actually retry the transaction.
2122 Implementation details: For each of this customer's open invoices, changes
2123 the status of the first "done" (with statustext error) realtime processing
2128 sub retry_realtime {
2131 local $SIG{HUP} = 'IGNORE';
2132 local $SIG{INT} = 'IGNORE';
2133 local $SIG{QUIT} = 'IGNORE';
2134 local $SIG{TERM} = 'IGNORE';
2135 local $SIG{TSTP} = 'IGNORE';
2136 local $SIG{PIPE} = 'IGNORE';
2138 my $oldAutoCommit = $FS::UID::AutoCommit;
2139 local $FS::UID::AutoCommit = 0;
2142 foreach my $cust_bill (
2143 grep { $_->cust_bill_event }
2144 $self->open_cust_bill
2146 my @cust_bill_event =
2147 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2149 #$_->part_bill_event->plan eq 'realtime-card'
2150 $_->part_bill_event->eventcode =~
2151 /\$cust_bill\->realtime_(card|ach|lec)/
2152 && $_->status eq 'done'
2155 $cust_bill->cust_bill_event;
2156 next unless @cust_bill_event;
2157 my $error = $cust_bill_event[0]->retry;
2159 $dbh->rollback if $oldAutoCommit;
2160 return "error scheduling invoice event for retry: $error";
2165 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2170 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2172 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2173 via a Business::OnlinePayment realtime gateway. See
2174 L<http://420.am/business-onlinepayment> for supported gateways.
2176 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2178 Available options are: I<description>, I<invnum>, I<quiet>
2180 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2181 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2182 if set, will override the value from the customer record.
2184 I<description> is a free-text field passed to the gateway. It defaults to
2185 "Internet services".
2187 If an I<invnum> is specified, this payment (if sucessful) is applied to the
2188 specified invoice. If you don't specify an I<invnum> you might want to
2189 call the B<apply_payments> method.
2191 I<quiet> can be set true to surpress email decline notices.
2193 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2198 my( $self, $method, $amount, %options ) = @_;
2200 warn "$me realtime_bop: $method $amount\n";
2201 warn " $_ => $options{$_}\n" foreach keys %options;
2204 $options{'description'} ||= 'Internet services';
2206 eval "use Business::OnlinePayment";
2209 my $payinfo = exists($options{'payinfo'})
2210 ? $options{'payinfo'}
2218 if ( $options{'invnum'} ) {
2219 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2220 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2222 map { $_->part_pkg->taxclass }
2224 map { $_->cust_pkg }
2225 $cust_bill->cust_bill_pkg;
2226 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2227 #different taxclasses
2228 $taxclass = $taxclasses[0];
2232 #look for an agent gateway override first
2234 if ( $method eq 'CC' ) {
2235 $cardtype = cardtype($payinfo);
2236 } elsif ( $method eq 'ECHECK' ) {
2239 $cardtype = $method;
2243 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2244 cardtype => $cardtype,
2245 taxclass => $taxclass, } )
2246 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2248 taxclass => $taxclass, } )
2249 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2250 cardtype => $cardtype,
2252 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2254 taxclass => '', } );
2256 my $payment_gateway = '';
2257 my( $processor, $login, $password, $action, @bop_options );
2258 if ( $override ) { #use a payment gateway override
2260 $payment_gateway = $override->payment_gateway;
2262 $processor = $payment_gateway->gateway_module;
2263 $login = $payment_gateway->gateway_username;
2264 $password = $payment_gateway->gateway_password;
2265 $action = $payment_gateway->gateway_action;
2266 @bop_options = $payment_gateway->options;
2268 } else { #use the standard settings from the config
2270 ( $processor, $login, $password, $action, @bop_options ) =
2271 $self->default_payment_gateway($method);
2279 my $address = exists($options{'address1'})
2280 ? $options{'address1'}
2282 my $address2 = exists($options{'address2'})
2283 ? $options{'address2'}
2285 $address .= ", ". $address2 if length($address2);
2287 my $o_payname = exists($options{'payname'})
2288 ? $options{'payname'}
2290 my($payname, $payfirst, $paylast);
2291 if ( $o_payname && $method ne 'ECHECK' ) {
2292 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2293 or return "Illegal payname $payname";
2294 ($payfirst, $paylast) = ($1, $2);
2296 $payfirst = $self->getfield('first');
2297 $paylast = $self->getfield('last');
2298 $payname = "$payfirst $paylast";
2301 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2302 if ( $conf->exists('emailinvoiceauto')
2303 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2304 push @invoicing_list, $self->all_emails;
2307 my $email = ($conf->exists('business-onlinepayment-email-override'))
2308 ? $conf->config('business-onlinepayment-email-override')
2309 : $invoicing_list[0];
2313 my $payip = exists($options{'payip'})
2316 $content{customer_ip} = $payip
2319 if ( $method eq 'CC' ) {
2321 $content{card_number} = $payinfo;
2322 my $paydate = exists($options{'paydate'})
2323 ? $options{'paydate'}
2325 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2326 $content{expiration} = "$2/$1";
2328 my $paycvv = exists($options{'paycvv'})
2329 ? $options{'paycvv'}
2331 $content{cvv2} = $self->paycvv
2334 my $paystart_month = exists($options{'paystart_month'})
2335 ? $options{'paystart_month'}
2336 : $self->paystart_month;
2338 my $paystart_year = exists($options{'paystart_year'})
2339 ? $options{'paystart_year'}
2340 : $self->paystart_year;
2342 $content{card_start} = "$paystart_month/$paystart_year"
2343 if $paystart_month && $paystart_year;
2345 my $payissue = exists($options{'payissue'})
2346 ? $options{'payissue'}
2348 $content{issue_number} = $payissue if $payissue;
2350 $content{recurring_billing} = 'YES'
2351 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2353 'payinfo' => $payinfo,
2356 } elsif ( $method eq 'ECHECK' ) {
2357 ( $content{account_number}, $content{routing_code} ) =
2358 split('@', $payinfo);
2359 $content{bank_name} = $o_payname;
2360 $content{account_type} = 'CHECKING';
2361 $content{account_name} = $payname;
2362 $content{customer_org} = $self->company ? 'B' : 'I';
2363 $content{customer_ssn} = exists($options{'ss'})
2366 } elsif ( $method eq 'LEC' ) {
2367 $content{phone} = $payinfo;
2371 # run transaction(s)
2374 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2376 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2377 $transaction->content(
2380 'password' => $password,
2381 'action' => $action1,
2382 'description' => $options{'description'},
2383 'amount' => $amount,
2384 'invoice_number' => $options{'invnum'},
2385 'customer_id' => $self->custnum,
2386 'last_name' => $paylast,
2387 'first_name' => $payfirst,
2389 'address' => $address,
2390 'city' => ( exists($options{'city'})
2393 'state' => ( exists($options{'state'})
2396 'zip' => ( exists($options{'zip'})
2399 'country' => ( exists($options{'country'})
2400 ? $options{'country'}
2402 'referer' => 'http://cleanwhisker.420.am/',
2404 'phone' => $self->daytime || $self->night,
2407 $transaction->submit();
2409 if ( $transaction->is_success() && $action2 ) {
2410 my $auth = $transaction->authorization;
2411 my $ordernum = $transaction->can('order_number')
2412 ? $transaction->order_number
2416 new Business::OnlinePayment( $processor, @bop_options );
2423 password => $password,
2424 order_number => $ordernum,
2426 authorization => $auth,
2427 description => $options{'description'},
2430 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2431 transaction_sequence_num local_transaction_date
2432 local_transaction_time AVS_result_code )) {
2433 $capture{$field} = $transaction->$field() if $transaction->can($field);
2436 $capture->content( %capture );
2440 unless ( $capture->is_success ) {
2441 my $e = "Authorization sucessful but capture failed, custnum #".
2442 $self->custnum. ': '. $capture->result_code.
2443 ": ". $capture->error_message;
2451 # remove paycvv after initial transaction
2454 #false laziness w/misc/process/payment.cgi - check both to make sure working
2456 if ( defined $self->dbdef_table->column('paycvv')
2457 && length($self->paycvv)
2458 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2460 my $error = $self->remove_cvv;
2462 warn "WARNING: error removing cvv: $error\n";
2470 if ( $transaction->is_success() ) {
2472 my %method2payby = (
2479 if ( $payment_gateway ) { # agent override
2480 $paybatch = $payment_gateway->gatewaynum. '-';
2483 $paybatch .= "$processor:". $transaction->authorization;
2485 $paybatch .= ':'. $transaction->order_number
2486 if $transaction->can('order_number')
2487 && length($transaction->order_number);
2489 my $cust_pay = new FS::cust_pay ( {
2490 'custnum' => $self->custnum,
2491 'invnum' => $options{'invnum'},
2494 'payby' => $method2payby{$method},
2495 'payinfo' => $payinfo,
2496 'paybatch' => $paybatch,
2498 my $error = $cust_pay->insert;
2500 $cust_pay->invnum(''); #try again with no specific invnum
2501 my $error2 = $cust_pay->insert;
2503 # gah, even with transactions.
2504 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2505 "error inserting payment ($processor): $error2".
2506 " (previously tried insert with invnum #$options{'invnum'}" .
2512 return ''; #no error
2516 my $perror = "$processor error: ". $transaction->error_message;
2518 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2519 && $conf->exists('emaildecline')
2520 && grep { $_ ne 'POST' } $self->invoicing_list
2521 && ! grep { $transaction->error_message =~ /$_/ }
2522 $conf->config('emaildecline-exclude')
2524 my @templ = $conf->config('declinetemplate');
2525 my $template = new Text::Template (
2527 SOURCE => [ map "$_\n", @templ ],
2528 ) or return "($perror) can't create template: $Text::Template::ERROR";
2529 $template->compile()
2530 or return "($perror) can't compile template: $Text::Template::ERROR";
2532 my $templ_hash = { error => $transaction->error_message };
2534 my $error = send_email(
2535 'from' => $conf->config('invoice_from'),
2536 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2537 'subject' => 'Your payment could not be processed',
2538 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2541 $perror .= " (also received error sending decline notification: $error)"
2551 =item default_payment_gateway
2555 sub default_payment_gateway {
2556 my( $self, $method ) = @_;
2558 die "Real-time processing not enabled\n"
2559 unless $conf->exists('business-onlinepayment');
2562 my $bop_config = 'business-onlinepayment';
2563 $bop_config .= '-ach'
2564 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2565 my ( $processor, $login, $password, $action, @bop_options ) =
2566 $conf->config($bop_config);
2567 $action ||= 'normal authorization';
2568 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2569 die "No real-time processor is enabled - ".
2570 "did you set the business-onlinepayment configuration value?\n"
2573 ( $processor, $login, $password, $action, @bop_options )
2578 Removes the I<paycvv> field from the database directly.
2580 If there is an error, returns the error, otherwise returns false.
2586 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2587 or return dbh->errstr;
2588 $sth->execute($self->custnum)
2589 or return $sth->errstr;
2594 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2596 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2597 via a Business::OnlinePayment realtime gateway. See
2598 L<http://420.am/business-onlinepayment> for supported gateways.
2600 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2602 Available options are: I<amount>, I<reason>, I<paynum>
2604 Most gateways require a reference to an original payment transaction to refund,
2605 so you probably need to specify a I<paynum>.
2607 I<amount> defaults to the original amount of the payment if not specified.
2609 I<reason> specifies a reason for the refund.
2611 Implementation note: If I<amount> is unspecified or equal to the amount of the
2612 orignal payment, first an attempt is made to "void" the transaction via
2613 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2614 the normal attempt is made to "refund" ("credit") the transaction via the
2615 gateway is attempted.
2617 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2618 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2619 #if set, will override the value from the customer record.
2621 #If an I<invnum> is specified, this payment (if sucessful) is applied to the
2622 #specified invoice. If you don't specify an I<invnum> you might want to
2623 #call the B<apply_payments> method.
2627 #some false laziness w/realtime_bop, not enough to make it worth merging
2628 #but some useful small subs should be pulled out
2629 sub realtime_refund_bop {
2630 my( $self, $method, %options ) = @_;
2632 warn "$me realtime_refund_bop: $method refund\n";
2633 warn " $_ => $options{$_}\n" foreach keys %options;
2636 eval "use Business::OnlinePayment";
2640 # look up the original payment and optionally a gateway for that payment
2644 my $amount = $options{'amount'};
2646 my( $processor, $login, $password, @bop_options ) ;
2647 my( $auth, $order_number ) = ( '', '', '' );
2649 if ( $options{'paynum'} ) {
2651 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2652 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2653 or return "Unknown paynum $options{'paynum'}";
2654 $amount ||= $cust_pay->paid;
2656 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2657 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2658 $cust_pay->paybatch;
2659 my $gatewaynum = '';
2660 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2662 if ( $gatewaynum ) { #gateway for the payment to be refunded
2664 my $payment_gateway =
2665 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2666 die "payment gateway $gatewaynum not found"
2667 unless $payment_gateway;
2669 $processor = $payment_gateway->gateway_module;
2670 $login = $payment_gateway->gateway_username;
2671 $password = $payment_gateway->gateway_password;
2672 @bop_options = $payment_gateway->options;
2674 } else { #try the default gateway
2676 my( $conf_processor, $unused_action );
2677 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2678 $self->default_payment_gateway($method);
2680 return "processor of payment $options{'paynum'} $processor does not".
2681 " match default processor $conf_processor"
2682 unless $processor eq $conf_processor;
2687 } else { # didn't specify a paynum, so look for agent gateway overrides
2688 # like a normal transaction
2691 if ( $method eq 'CC' ) {
2692 $cardtype = cardtype($self->payinfo);
2693 } elsif ( $method eq 'ECHECK' ) {
2696 $cardtype = $method;
2699 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2700 cardtype => $cardtype,
2702 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2704 taxclass => '', } );
2706 if ( $override ) { #use a payment gateway override
2708 my $payment_gateway = $override->payment_gateway;
2710 $processor = $payment_gateway->gateway_module;
2711 $login = $payment_gateway->gateway_username;
2712 $password = $payment_gateway->gateway_password;
2713 #$action = $payment_gateway->gateway_action;
2714 @bop_options = $payment_gateway->options;
2716 } else { #use the standard settings from the config
2719 ( $processor, $login, $password, $unused_action, @bop_options ) =
2720 $self->default_payment_gateway($method);
2725 return "neither amount nor paynum specified" unless $amount;
2730 'password' => $password,
2731 'order_number' => $order_number,
2732 'amount' => $amount,
2733 'referer' => 'http://cleanwhisker.420.am/',
2735 $content{authorization} = $auth
2736 if length($auth); #echeck/ACH transactions have an order # but no auth
2737 #(at least with authorize.net)
2739 #first try void if applicable
2740 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2741 warn " attempting void\n" if $DEBUG > 1;
2742 my $void = new Business::OnlinePayment( $processor, @bop_options );
2743 $void->content( 'action' => 'void', %content );
2745 if ( $void->is_success ) {
2746 my $error = $cust_pay->void($options{'reason'});
2748 # gah, even with transactions.
2749 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2750 "error voiding payment: $error";
2754 warn " void successful\n" if $DEBUG > 1;
2759 warn " void unsuccessful, trying refund\n"
2763 my $address = $self->address1;
2764 $address .= ", ". $self->address2 if $self->address2;
2766 my($payname, $payfirst, $paylast);
2767 if ( $self->payname && $method ne 'ECHECK' ) {
2768 $payname = $self->payname;
2769 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2770 or return "Illegal payname $payname";
2771 ($payfirst, $paylast) = ($1, $2);
2773 $payfirst = $self->getfield('first');
2774 $paylast = $self->getfield('last');
2775 $payname = "$payfirst $paylast";
2779 if ( $method eq 'CC' ) {
2782 $content{card_number} = $payinfo = $cust_pay->payinfo;
2783 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2784 #$content{expiration} = "$2/$1";
2786 $content{card_number} = $payinfo = $self->payinfo;
2787 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2788 $content{expiration} = "$2/$1";
2791 } elsif ( $method eq 'ECHECK' ) {
2792 ( $content{account_number}, $content{routing_code} ) =
2793 split('@', $payinfo = $self->payinfo);
2794 $content{bank_name} = $self->payname;
2795 $content{account_type} = 'CHECKING';
2796 $content{account_name} = $payname;
2797 $content{customer_org} = $self->company ? 'B' : 'I';
2798 $content{customer_ssn} = $self->ss;
2799 } elsif ( $method eq 'LEC' ) {
2800 $content{phone} = $payinfo = $self->payinfo;
2804 my $refund = new Business::OnlinePayment( $processor, @bop_options );
2805 my %sub_content = $refund->content(
2806 'action' => 'credit',
2807 'customer_id' => $self->custnum,
2808 'last_name' => $paylast,
2809 'first_name' => $payfirst,
2811 'address' => $address,
2812 'city' => $self->city,
2813 'state' => $self->state,
2814 'zip' => $self->zip,
2815 'country' => $self->country,
2818 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
2822 return "$processor error: ". $refund->error_message
2823 unless $refund->is_success();
2825 my %method2payby = (
2831 my $paybatch = "$processor:". $refund->authorization;
2832 $paybatch .= ':'. $refund->order_number
2833 if $refund->can('order_number') && $refund->order_number;
2835 while ( $cust_pay && $cust_pay->unappled < $amount ) {
2836 my @cust_bill_pay = $cust_pay->cust_bill_pay;
2837 last unless @cust_bill_pay;
2838 my $cust_bill_pay = pop @cust_bill_pay;
2839 my $error = $cust_bill_pay->delete;
2843 my $cust_refund = new FS::cust_refund ( {
2844 'custnum' => $self->custnum,
2845 'paynum' => $options{'paynum'},
2846 'refund' => $amount,
2848 'payby' => $method2payby{$method},
2849 'payinfo' => $payinfo,
2850 'paybatch' => $paybatch,
2851 'reason' => $options{'reason'} || 'card or ACH refund',
2853 my $error = $cust_refund->insert;
2855 $cust_refund->paynum(''); #try again with no specific paynum
2856 my $error2 = $cust_refund->insert;
2858 # gah, even with transactions.
2859 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
2860 "error inserting refund ($processor): $error2".
2861 " (previously tried insert with paynum #$options{'paynum'}" .
2874 Returns the total owed for this customer on all invoices
2875 (see L<FS::cust_bill/owed>).
2881 $self->total_owed_date(2145859200); #12/31/2037
2884 =item total_owed_date TIME
2886 Returns the total owed for this customer on all invoices with date earlier than
2887 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2888 see L<Time::Local> and L<Date::Parse> for conversion functions.
2892 sub total_owed_date {
2896 foreach my $cust_bill (
2897 grep { $_->_date <= $time }
2898 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2900 $total_bill += $cust_bill->owed;
2902 sprintf( "%.2f", $total_bill );
2905 =item apply_credits OPTION => VALUE ...
2907 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2908 to outstanding invoice balances in chronological order (or reverse
2909 chronological order if the I<order> option is set to B<newest>) and returns the
2910 value of any remaining unapplied credits available for refund (see
2911 L<FS::cust_refund>).
2919 return 0 unless $self->total_credited;
2921 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2922 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2924 my @invoices = $self->open_cust_bill;
2925 @invoices = sort { $b->_date <=> $a->_date } @invoices
2926 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2929 foreach my $cust_bill ( @invoices ) {
2932 if ( !defined($credit) || $credit->credited == 0) {
2933 $credit = pop @credits or last;
2936 if ($cust_bill->owed >= $credit->credited) {
2937 $amount=$credit->credited;
2939 $amount=$cust_bill->owed;
2942 my $cust_credit_bill = new FS::cust_credit_bill ( {
2943 'crednum' => $credit->crednum,
2944 'invnum' => $cust_bill->invnum,
2945 'amount' => $amount,
2947 my $error = $cust_credit_bill->insert;
2948 die $error if $error;
2950 redo if ($cust_bill->owed > 0);
2954 return $self->total_credited;
2957 =item apply_payments
2959 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2960 to outstanding invoice balances in chronological order.
2962 #and returns the value of any remaining unapplied payments.
2966 sub apply_payments {
2971 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
2972 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
2974 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
2975 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
2979 foreach my $cust_bill ( @invoices ) {
2982 if ( !defined($payment) || $payment->unapplied == 0 ) {
2983 $payment = pop @payments or last;
2986 if ( $cust_bill->owed >= $payment->unapplied ) {
2987 $amount = $payment->unapplied;
2989 $amount = $cust_bill->owed;
2992 my $cust_bill_pay = new FS::cust_bill_pay ( {
2993 'paynum' => $payment->paynum,
2994 'invnum' => $cust_bill->invnum,
2995 'amount' => $amount,
2997 my $error = $cust_bill_pay->insert;
2998 die $error if $error;
3000 redo if ( $cust_bill->owed > 0);
3004 return $self->total_unapplied_payments;
3007 =item total_credited
3009 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3010 customer. See L<FS::cust_credit/credited>.
3014 sub total_credited {
3016 my $total_credit = 0;
3017 foreach my $cust_credit ( qsearch('cust_credit', {
3018 'custnum' => $self->custnum,
3020 $total_credit += $cust_credit->credited;
3022 sprintf( "%.2f", $total_credit );
3025 =item total_unapplied_payments
3027 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3028 See L<FS::cust_pay/unapplied>.
3032 sub total_unapplied_payments {
3034 my $total_unapplied = 0;
3035 foreach my $cust_pay ( qsearch('cust_pay', {
3036 'custnum' => $self->custnum,
3038 $total_unapplied += $cust_pay->unapplied;
3040 sprintf( "%.2f", $total_unapplied );
3045 Returns the balance for this customer (total_owed minus total_credited
3046 minus total_unapplied_payments).
3053 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3057 =item balance_date TIME
3059 Returns the balance for this customer, only considering invoices with date
3060 earlier than TIME (total_owed_date minus total_credited minus
3061 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3062 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3071 $self->total_owed_date($time)
3072 - $self->total_credited
3073 - $self->total_unapplied_payments
3077 =item paydate_monthyear
3079 Returns a two-element list consisting of the month and year of this customer's
3080 paydate (credit card expiration date for CARD customers)
3084 sub paydate_monthyear {
3086 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3088 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3095 =item payinfo_masked
3097 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.
3099 Credit Cards - Mask all but the last four characters.
3100 Checks - Mask all but last 2 of account number and bank routing number.
3101 Others - Do nothing, return the unmasked string.
3105 sub payinfo_masked {
3107 return $self->paymask;
3110 =item invoicing_list [ ARRAYREF ]
3112 If an arguement is given, sets these email addresses as invoice recipients
3113 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3114 (except as warnings), so use check_invoicing_list first.
3116 Returns a list of email addresses (with svcnum entries expanded).
3118 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3119 check it without disturbing anything by passing nothing.
3121 This interface may change in the future.
3125 sub invoicing_list {
3126 my( $self, $arrayref ) = @_;
3128 my @cust_main_invoice;
3129 if ( $self->custnum ) {
3130 @cust_main_invoice =
3131 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3133 @cust_main_invoice = ();
3135 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3136 #warn $cust_main_invoice->destnum;
3137 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3138 #warn $cust_main_invoice->destnum;
3139 my $error = $cust_main_invoice->delete;
3140 warn $error if $error;
3143 if ( $self->custnum ) {
3144 @cust_main_invoice =
3145 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3147 @cust_main_invoice = ();
3149 my %seen = map { $_->address => 1 } @cust_main_invoice;
3150 foreach my $address ( @{$arrayref} ) {
3151 next if exists $seen{$address} && $seen{$address};
3152 $seen{$address} = 1;
3153 my $cust_main_invoice = new FS::cust_main_invoice ( {
3154 'custnum' => $self->custnum,
3157 my $error = $cust_main_invoice->insert;
3158 warn $error if $error;
3161 if ( $self->custnum ) {
3163 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3169 =item check_invoicing_list ARRAYREF
3171 Checks these arguements as valid input for the invoicing_list method. If there
3172 is an error, returns the error, otherwise returns false.
3176 sub check_invoicing_list {
3177 my( $self, $arrayref ) = @_;
3178 foreach my $address ( @{$arrayref} ) {
3180 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3181 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3184 my $cust_main_invoice = new FS::cust_main_invoice ( {
3185 'custnum' => $self->custnum,
3188 my $error = $self->custnum
3189 ? $cust_main_invoice->check
3190 : $cust_main_invoice->checkdest
3192 return $error if $error;
3197 =item set_default_invoicing_list
3199 Sets the invoicing list to all accounts associated with this customer,
3200 overwriting any previous invoicing list.
3204 sub set_default_invoicing_list {
3206 $self->invoicing_list($self->all_emails);
3211 Returns the email addresses of all accounts provisioned for this customer.
3218 foreach my $cust_pkg ( $self->all_pkgs ) {
3219 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3221 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3222 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3224 $list{$_}=1 foreach map { $_->email } @svc_acct;
3229 =item invoicing_list_addpost
3231 Adds postal invoicing to this customer. If this customer is already configured
3232 to receive postal invoices, does nothing.
3236 sub invoicing_list_addpost {
3238 return if grep { $_ eq 'POST' } $self->invoicing_list;
3239 my @invoicing_list = $self->invoicing_list;
3240 push @invoicing_list, 'POST';
3241 $self->invoicing_list(\@invoicing_list);
3244 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3246 Returns an array of customers referred by this customer (referral_custnum set
3247 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3248 customers referred by customers referred by this customer and so on, inclusive.
3249 The default behavior is DEPTH 1 (no recursion).
3253 sub referral_cust_main {
3255 my $depth = @_ ? shift : 1;
3256 my $exclude = @_ ? shift : {};
3259 map { $exclude->{$_->custnum}++; $_; }
3260 grep { ! $exclude->{ $_->custnum } }
3261 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3265 map { $_->referral_cust_main($depth-1, $exclude) }
3272 =item referral_cust_main_ncancelled
3274 Same as referral_cust_main, except only returns customers with uncancelled
3279 sub referral_cust_main_ncancelled {
3281 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3284 =item referral_cust_pkg [ DEPTH ]
3286 Like referral_cust_main, except returns a flat list of all unsuspended (and
3287 uncancelled) packages for each customer. The number of items in this list may
3288 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3292 sub referral_cust_pkg {
3294 my $depth = @_ ? shift : 1;
3296 map { $_->unsuspended_pkgs }
3297 grep { $_->unsuspended_pkgs }
3298 $self->referral_cust_main($depth);
3301 =item referring_cust_main
3303 Returns the single cust_main record for the customer who referred this customer
3304 (referral_custnum), or false.
3308 sub referring_cust_main {
3310 return '' unless $self->referral_custnum;
3311 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3314 =item credit AMOUNT, REASON
3316 Applies a credit to this customer. If there is an error, returns the error,
3317 otherwise returns false.
3322 my( $self, $amount, $reason ) = @_;
3323 my $cust_credit = new FS::cust_credit {
3324 'custnum' => $self->custnum,
3325 'amount' => $amount,
3326 'reason' => $reason,
3328 $cust_credit->insert;
3331 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3333 Creates a one-time charge for this customer. If there is an error, returns
3334 the error, otherwise returns false.
3339 my ( $self, $amount ) = ( shift, shift );
3340 my $pkg = @_ ? shift : 'One-time charge';
3341 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3342 my $taxclass = @_ ? shift : '';
3344 local $SIG{HUP} = 'IGNORE';
3345 local $SIG{INT} = 'IGNORE';
3346 local $SIG{QUIT} = 'IGNORE';
3347 local $SIG{TERM} = 'IGNORE';
3348 local $SIG{TSTP} = 'IGNORE';
3349 local $SIG{PIPE} = 'IGNORE';
3351 my $oldAutoCommit = $FS::UID::AutoCommit;
3352 local $FS::UID::AutoCommit = 0;
3355 my $part_pkg = new FS::part_pkg ( {
3357 'comment' => $comment,
3358 #'setup' => $amount,
3361 'plandata' => "setup_fee=$amount",
3364 'taxclass' => $taxclass,
3367 my $error = $part_pkg->insert;
3369 $dbh->rollback if $oldAutoCommit;
3373 my $pkgpart = $part_pkg->pkgpart;
3374 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3375 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3376 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3377 $error = $type_pkgs->insert;
3379 $dbh->rollback if $oldAutoCommit;
3384 my $cust_pkg = new FS::cust_pkg ( {
3385 'custnum' => $self->custnum,
3386 'pkgpart' => $pkgpart,
3389 $error = $cust_pkg->insert;
3391 $dbh->rollback if $oldAutoCommit;
3395 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3402 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3408 sort { $a->_date <=> $b->_date }
3409 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3412 =item open_cust_bill
3414 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3419 sub open_cust_bill {
3421 grep { $_->owed > 0 } $self->cust_bill;
3426 Returns all the credits (see L<FS::cust_credit>) for this customer.
3432 sort { $a->_date <=> $b->_date }
3433 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3438 Returns all the payments (see L<FS::cust_pay>) for this customer.
3444 sort { $a->_date <=> $b->_date }
3445 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3450 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3456 sort { $a->_date <=> $b->_date }
3457 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3463 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3469 sort { $a->_date <=> $b->_date }
3470 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3473 =item select_for_update
3475 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3480 sub select_for_update {
3482 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3487 Returns a name string for this customer, either "Company (Last, First)" or
3494 my $name = $self->contact;
3495 $name = $self->company. " ($name)" if $self->company;
3501 Returns a name string for this (service/shipping) contact, either
3502 "Company (Last, First)" or "Last, First".
3508 if ( $self->get('ship_last') ) {
3509 my $name = $self->ship_contact;
3510 $name = $self->ship_company. " ($name)" if $self->ship_company;
3519 Returns this customer's full (billing) contact name only, "Last, First"
3525 $self->get('last'). ', '. $self->first;
3530 Returns this customer's full (shipping) contact name only, "Last, First"
3536 $self->get('ship_last')
3537 ? $self->get('ship_last'). ', '. $self->ship_first
3543 Returns a status string for this customer, currently:
3547 =item prospect - No packages have ever been ordered
3549 =item active - One or more recurring packages is active
3551 =item suspended - All non-cancelled recurring packages are suspended
3553 =item cancelled - All recurring packages are cancelled
3561 for my $status (qw( prospect active suspended cancelled )) {
3562 my $method = $status.'_sql';
3563 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3564 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3565 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3566 return $status if $sth->fetchrow_arrayref->[0];
3572 Returns a hex triplet color string for this customer's status.
3577 'prospect' => '000000',
3578 'active' => '00CC00',
3579 'suspended' => 'FF9900',
3580 'cancelled' => 'FF0000',
3584 $statuscolor{$self->status};
3589 =head1 CLASS METHODS
3595 Returns an SQL expression identifying prospective cust_main records (customers
3596 with no packages ever ordered)
3600 sub prospect_sql { "
3601 0 = ( SELECT COUNT(*) FROM cust_pkg
3602 WHERE cust_pkg.custnum = cust_main.custnum
3608 Returns an SQL expression identifying active cust_main records.
3613 0 < ( SELECT COUNT(*) FROM cust_pkg
3614 WHERE cust_pkg.custnum = cust_main.custnum
3615 AND ". FS::cust_pkg->active_sql. "
3622 Returns an SQL expression identifying suspended cust_main records.
3626 #my $recurring_sql = FS::cust_pkg->recurring_sql;
3627 my $recurring_sql = "
3628 '0' != ( select freq from part_pkg
3629 where cust_pkg.pkgpart = part_pkg.pkgpart )
3632 sub suspended_sql { susp_sql(@_); }
3634 0 < ( SELECT COUNT(*) FROM cust_pkg
3635 WHERE cust_pkg.custnum = cust_main.custnum
3637 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3639 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3640 WHERE cust_pkg.custnum = cust_main.custnum
3641 AND ". FS::cust_pkg->active_sql. "
3648 Returns an SQL expression identifying cancelled cust_main records.
3652 sub cancelled_sql { cancel_sql(@_); }
3654 0 < ( SELECT COUNT(*) FROM cust_pkg
3655 WHERE cust_pkg.custnum = cust_main.custnum
3657 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3658 WHERE cust_pkg.custnum = cust_main.custnum
3660 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3664 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3666 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3667 records. Currently, only I<last> or I<company> may be specified (the
3668 appropriate ship_ field is also searched if applicable).
3670 Additional options are the same as FS::Record::qsearch
3675 my( $self, $fuzzy, $hash, @opt) = @_;
3680 check_and_rebuild_fuzzyfiles();
3681 foreach my $field ( keys %$fuzzy ) {
3682 my $sub = \&{"all_$field"};
3684 $match{$_}=1 foreach ( amatch($fuzzy->{$field}, ['i'], @{ &$sub() } ) );
3686 foreach ( keys %match ) {
3687 push @cust_main, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3688 push @cust_main, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt)
3689 if defined dbdef->table('cust_main')->column('ship_last');
3694 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
3706 =item smart_search OPTION => VALUE ...
3708 Accepts the following options: I<search>, the string to search for. The string
3709 will be searched for as a customer number, last name or company name, first
3710 searching for an exact match then fuzzy and substring matches.
3712 Any additional options treated as an additional qualifier on the search
3715 Returns a (possibly empty) array of FS::cust_main objects.
3721 my $search = delete $options{'search'};
3724 if ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
3726 push @cust_main, qsearch('cust_main', { 'custnum' => $1, %options } );
3728 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { #value search
3731 my $q_value = dbh->quote($value);
3734 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
3735 $sql .= " ( LOWER(last) = $q_value OR LOWER(company) = $q_value";
3736 $sql .= " OR LOWER(ship_last) = $q_value OR LOWER(ship_company) = $q_value"
3737 if defined dbdef->table('cust_main')->column('ship_last');
3740 push @cust_main, qsearch( 'cust_main', \%options, '', $sql );
3742 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
3744 #still some false laziness w/ search/cust_main.cgi
3747 push @cust_main, qsearch( 'cust_main',
3748 { 'last' => { 'op' => 'ILIKE',
3749 'value' => "%$q_value%" },
3753 push @cust_main, qsearch( 'cust_main',
3754 { 'ship_last' => { 'op' => 'ILIKE',
3755 'value' => "%$q_value%" },
3760 if defined dbdef->table('cust_main')->column('ship_last');
3762 push @cust_main, qsearch( 'cust_main',
3763 { 'company' => { 'op' => 'ILIKE',
3764 'value' => "%$q_value%" },
3768 push @cust_main, qsearch( 'cust_main',
3769 { 'ship_company' => { 'op' => 'ILIKE',
3770 'value' => "%$q_value%" },
3774 if defined dbdef->table('cust_main')->column('ship_last');
3777 push @cust_main, FS::cust_main->fuzzy_search(
3778 { 'last' => $value },
3781 push @cust_main, FS::cust_main->fuzzy_search(
3782 { 'company' => $value },
3794 =item check_and_rebuild_fuzzyfiles
3798 sub check_and_rebuild_fuzzyfiles {
3799 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3800 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
3801 or &rebuild_fuzzyfiles;
3804 =item rebuild_fuzzyfiles
3808 sub rebuild_fuzzyfiles {
3810 use Fcntl qw(:flock);
3812 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3816 open(LASTLOCK,">>$dir/cust_main.last")
3817 or die "can't open $dir/cust_main.last: $!";
3818 flock(LASTLOCK,LOCK_EX)
3819 or die "can't lock $dir/cust_main.last: $!";
3821 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
3823 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
3824 if defined dbdef->table('cust_main')->column('ship_last');
3826 open (LASTCACHE,">$dir/cust_main.last.tmp")
3827 or die "can't open $dir/cust_main.last.tmp: $!";
3828 print LASTCACHE join("\n", @all_last), "\n";
3829 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
3831 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
3836 open(COMPANYLOCK,">>$dir/cust_main.company")
3837 or die "can't open $dir/cust_main.company: $!";
3838 flock(COMPANYLOCK,LOCK_EX)
3839 or die "can't lock $dir/cust_main.company: $!";
3841 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
3843 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
3844 if defined dbdef->table('cust_main')->column('ship_last');
3846 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
3847 or die "can't open $dir/cust_main.company.tmp: $!";
3848 print COMPANYCACHE join("\n", @all_company), "\n";
3849 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
3851 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
3861 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3862 open(LASTCACHE,"<$dir/cust_main.last")
3863 or die "can't open $dir/cust_main.last: $!";
3864 my @array = map { chomp; $_; } <LASTCACHE>;
3874 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3875 open(COMPANYCACHE,"<$dir/cust_main.company")
3876 or die "can't open $dir/cust_main.last: $!";
3877 my @array = map { chomp; $_; } <COMPANYCACHE>;
3882 =item append_fuzzyfiles LASTNAME COMPANY
3886 sub append_fuzzyfiles {
3887 my( $last, $company ) = @_;
3889 &check_and_rebuild_fuzzyfiles;
3891 use Fcntl qw(:flock);
3893 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3897 open(LAST,">>$dir/cust_main.last")
3898 or die "can't open $dir/cust_main.last: $!";
3900 or die "can't lock $dir/cust_main.last: $!";
3902 print LAST "$last\n";
3905 or die "can't unlock $dir/cust_main.last: $!";
3911 open(COMPANY,">>$dir/cust_main.company")
3912 or die "can't open $dir/cust_main.company: $!";
3913 flock(COMPANY,LOCK_EX)
3914 or die "can't lock $dir/cust_main.company: $!";
3916 print COMPANY "$company\n";
3918 flock(COMPANY,LOCK_UN)
3919 or die "can't unlock $dir/cust_main.company: $!";
3933 #warn join('-',keys %$param);
3934 my $fh = $param->{filehandle};
3935 my $agentnum = $param->{agentnum};
3936 my $refnum = $param->{refnum};
3937 my $pkgpart = $param->{pkgpart};
3938 my @fields = @{$param->{fields}};
3940 eval "use Date::Parse;";
3942 eval "use Text::CSV_XS;";
3945 my $csv = new Text::CSV_XS;
3952 local $SIG{HUP} = 'IGNORE';
3953 local $SIG{INT} = 'IGNORE';
3954 local $SIG{QUIT} = 'IGNORE';
3955 local $SIG{TERM} = 'IGNORE';
3956 local $SIG{TSTP} = 'IGNORE';
3957 local $SIG{PIPE} = 'IGNORE';
3959 my $oldAutoCommit = $FS::UID::AutoCommit;
3960 local $FS::UID::AutoCommit = 0;
3963 #while ( $columns = $csv->getline($fh) ) {
3965 while ( defined($line=<$fh>) ) {
3967 $csv->parse($line) or do {
3968 $dbh->rollback if $oldAutoCommit;
3969 return "can't parse: ". $csv->error_input();
3972 my @columns = $csv->fields();
3973 #warn join('-',@columns);
3976 agentnum => $agentnum,
3978 country => $conf->config('countrydefault') || 'US',
3979 payby => 'BILL', #default
3980 paydate => '12/2037', #default
3982 my $billtime = time;
3983 my %cust_pkg = ( pkgpart => $pkgpart );
3984 foreach my $field ( @fields ) {
3985 if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
3986 #$cust_pkg{$1} = str2time( shift @$columns );
3987 if ( $1 eq 'setup' ) {
3988 $billtime = str2time(shift @columns);
3990 $cust_pkg{$1} = str2time( shift @columns );
3993 #$cust_main{$field} = shift @$columns;
3994 $cust_main{$field} = shift @columns;
3998 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
3999 my $cust_main = new FS::cust_main ( \%cust_main );
4001 tie my %hash, 'Tie::RefHash'; #this part is important
4002 $hash{$cust_pkg} = [] if $pkgpart;
4003 my $error = $cust_main->insert( \%hash );
4006 $dbh->rollback if $oldAutoCommit;
4007 return "can't insert customer for $line: $error";
4010 #false laziness w/bill.cgi
4011 $error = $cust_main->bill( 'time' => $billtime );
4013 $dbh->rollback if $oldAutoCommit;
4014 return "can't bill customer for $line: $error";
4017 $cust_main->apply_payments;
4018 $cust_main->apply_credits;
4020 $error = $cust_main->collect();
4022 $dbh->rollback if $oldAutoCommit;
4023 return "can't collect customer for $line: $error";
4029 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4031 return "Empty file!" unless $imported;
4043 #warn join('-',keys %$param);
4044 my $fh = $param->{filehandle};
4045 my @fields = @{$param->{fields}};
4047 eval "use Date::Parse;";
4049 eval "use Text::CSV_XS;";
4052 my $csv = new Text::CSV_XS;
4059 local $SIG{HUP} = 'IGNORE';
4060 local $SIG{INT} = 'IGNORE';
4061 local $SIG{QUIT} = 'IGNORE';
4062 local $SIG{TERM} = 'IGNORE';
4063 local $SIG{TSTP} = 'IGNORE';
4064 local $SIG{PIPE} = 'IGNORE';
4066 my $oldAutoCommit = $FS::UID::AutoCommit;
4067 local $FS::UID::AutoCommit = 0;
4070 #while ( $columns = $csv->getline($fh) ) {
4072 while ( defined($line=<$fh>) ) {
4074 $csv->parse($line) or do {
4075 $dbh->rollback if $oldAutoCommit;
4076 return "can't parse: ". $csv->error_input();
4079 my @columns = $csv->fields();
4080 #warn join('-',@columns);
4083 foreach my $field ( @fields ) {
4084 $row{$field} = shift @columns;
4087 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4088 unless ( $cust_main ) {
4089 $dbh->rollback if $oldAutoCommit;
4090 return "unknown custnum $row{'custnum'}";
4093 if ( $row{'amount'} > 0 ) {
4094 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4096 $dbh->rollback if $oldAutoCommit;
4100 } elsif ( $row{'amount'} < 0 ) {
4101 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4104 $dbh->rollback if $oldAutoCommit;
4114 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4116 return "Empty file!" unless $imported;
4128 The delete method should possibly take an FS::cust_main object reference
4129 instead of a scalar customer number.
4131 Bill and collect options should probably be passed as references instead of a
4134 There should probably be a configuration file with a list of allowed credit
4137 No multiple currency support (probably a larger project than just this module).
4139 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4143 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4144 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4145 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.