temporarily disabling torrus source build
[freeside.git] / FS / FS / cust_main / Billing_Realtime.pm
1 package FS::cust_main::Billing_Realtime;
2
3 use strict;
4 use vars qw( $conf $DEBUG $me );
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
6 use Carp;
7 use Data::Dumper;
8 use Business::CreditCard 0.35;
9 use FS::UID qw( dbh myconnect );
10 use FS::Record qw( qsearch qsearchs );
11 use FS::payby;
12 use FS::cust_pay;
13 use FS::cust_pay_pending;
14 use FS::cust_bill_pay;
15 use FS::cust_refund;
16 use FS::banned_pay;
17 use FS::payment_gateway;
18
19 $realtime_bop_decline_quiet = 0;
20
21 # 1 is mostly method/subroutine entry and options
22 # 2 traces progress of some operations
23 # 3 is even more information including possibly sensitive data
24 $DEBUG = 0;
25 $me = '[FS::cust_main::Billing_Realtime]';
26
27 our $BOP_TESTING = 0;
28 our $BOP_TESTING_SUCCESS = 1;
29
30 install_callback FS::UID sub { 
31   $conf = new FS::Conf;
32   #yes, need it for stuff below (prolly should be cached)
33 };
34
35 =head1 NAME
36
37 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
38
39 =head1 SYNOPSIS
40
41 =head1 DESCRIPTION
42
43 These methods are available on FS::cust_main objects.
44
45 =head1 METHODS
46
47 =over 4
48
49 =item realtime_cust_payby
50
51 =cut
52
53 sub realtime_cust_payby {
54   my( $self, %options ) = @_;
55
56   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
57
58   $options{amount} = $self->balance unless exists( $options{amount} );
59
60   my @cust_payby = $self->cust_payby('CARD','CHEK');
61                                                    
62   my $error;
63   foreach my $cust_payby (@cust_payby) {
64     $error = $cust_payby->realtime_bop( %options, );
65     last unless $error;
66   }
67
68   #XXX what about the earlier errors?
69
70   $error;
71
72 }
73
74 =item realtime_collect [ OPTION => VALUE ... ]
75
76 Attempt to collect the customer's current balance with a realtime credit 
77 card or electronic check transaction (see realtime_bop() below).
78
79 Returns the result of realtime_bop(): nothing, an error message, or a 
80 hashref of state information for a third-party transaction.
81
82 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
83
84 I<method> is one of: I<CC> or I<ECHECK>.  If none is specified
85 then it is deduced from the customer record.
86
87 If no I<amount> is specified, then the customer balance is used.
88
89 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
90 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
91 if set, will override the value from the customer record.
92
93 I<description> is a free-text field passed to the gateway.  It defaults to
94 the value defined by the business-onlinepayment-description configuration
95 option, or "Internet services" if that is unset.
96
97 If an I<invnum> is specified, this payment (if successful) is applied to the
98 specified invoice.
99
100 I<apply> will automatically apply a resulting payment.
101
102 I<quiet> can be set true to suppress email decline notices.
103
104 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
105 resulting paynum, if any.
106
107 I<payunique> is a unique identifier for this payment.
108
109 I<session_id> is a session identifier associated with this payment.
110
111 I<depend_jobnum> allows payment capture to unlock export jobs
112
113 =cut
114
115 # Currently only used by ClientAPI
116 sub realtime_collect {
117   my( $self, %options ) = @_;
118
119   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
120
121   if ( $DEBUG ) {
122     warn "$me realtime_collect:\n";
123     warn "  $_ => $options{$_}\n" foreach keys %options;
124   }
125
126   $options{amount} = $self->balance unless exists( $options{amount} );
127   return '' unless $options{amount} > 0;
128
129   #huh, in v4, realtime_bop no longer will just process a card without passing
130   # payinfo or cust_payby...
131   if ( ! $options{'payinfo'} && ! $options{'cust_payby'} && $self->has_cust_payby_auto ) {
132     my @cust_payby = $self->cust_payby;
133     $options{'cust_payby'} = $cust_payby[0];
134   }
135
136   return $self->realtime_bop({%options});
137
138 }
139
140 =item realtime_bop { [ ARG => VALUE ... ] }
141
142 Runs a realtime credit card or ACH (electronic check) transaction
143 via a Business::OnlinePayment realtime gateway.  See
144 L<http://420.am/business-onlinepayment> for supported gateways.
145
146 Required arguments in the hashref are I<amount> and either
147 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
148 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
149
150 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
151
152 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
153
154 I<description> is a free-text field passed to the gateway.  It defaults to
155 the value defined by the business-onlinepayment-description configuration
156 option, or "Internet services" if that is unset.
157
158 If an I<invnum> is specified, this payment (if successful) is applied to the
159 specified invoice.  If the customer has exactly one open invoice, that 
160 invoice number will be assumed.  If you don't specify an I<invnum> you might 
161 want to call the B<apply_payments> method or set the I<apply> option.
162
163 I<no_invnum> can be set to true to prevent that default invnum from being set.
164
165 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
166
167 I<no_auto_apply> can be set to true to set that flag on the resulting payment
168 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
169 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
170
171 I<quiet> can be set true to surpress email decline notices.
172
173 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
174 resulting paynum, if any.
175
176 I<payunique> is a unique identifier for this payment.
177
178 I<session_id> is a session identifier associated with this payment.
179
180 I<depend_jobnum> allows payment capture to unlock export jobs
181
182 I<discount_term> attempts to take a discount by prepaying for discount_term.
183 The payment will fail if I<amount> is incorrect for this discount term.
184
185 A direct (Business::OnlinePayment) transaction will return nothing on success,
186 or an error message on failure.
187
188 A third-party transaction will return a hashref containing:
189
190 - popup_url: the URL to which a browser should be redirected to complete 
191   the transaction.
192 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
193 - reference: a reference ID for the transaction, to show the customer.
194
195 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
196
197 =cut
198
199 # some helper routines
200 #
201 # _bop_recurring_billing: Checks whether this payment should have the 
202 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
203 # vSecure, etc.). This works in two different modes:
204 # - actual_oncard (default): treat the payment as recurring if the customer
205 #   has made a payment using this card before.
206 # - transaction_is_recur: treat the payment as recurring if the invoice
207 #   being paid has any recurring package charges.
208
209 sub _bop_recurring_billing {
210   my( $self, %opt ) = @_;
211
212   my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
213
214   if ( defined($method) && $method eq 'transaction_is_recur' ) {
215
216     return 1 if $opt{'trans_is_recur'};
217
218   } else {
219
220     # return 1 if the payinfo has been used for another payment
221     return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
222
223   }
224
225   return 0;
226
227 }
228
229 #can run safely as class method if opt payment_gateway already exists
230 sub _payment_gateway {
231   my ($self, $options) = @_;
232
233   if ( $options->{'fake_gatewaynum'} ) {
234         $options->{payment_gateway} =
235             qsearchs('payment_gateway',
236                       { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
237                     );
238   }
239
240   $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
241     unless exists($options->{payment_gateway});
242
243   $options->{payment_gateway};
244 }
245
246 # not a method!!!
247 sub _bop_auth {
248   my ($options) = @_;
249
250   (
251     'login'    => $options->{payment_gateway}->gateway_username,
252     'password' => $options->{payment_gateway}->gateway_password,
253   );
254 }
255
256 ### not a method!
257 sub _bop_options {
258   my ($options) = @_;
259
260   $options->{payment_gateway}->gatewaynum
261     ? $options->{payment_gateway}->options
262     : @{ $options->{payment_gateway}->get('options') };
263
264 }
265
266 sub _bop_defaults {
267   my ($self, $options) = @_;
268
269   unless ( $options->{'description'} ) {
270     if ( $conf->exists('business-onlinepayment-description') ) {
271       my $dtempl = $conf->config('business-onlinepayment-description');
272
273       my $agent = $self->agent->agent;
274       #$pkgs... not here
275       $options->{'description'} = eval qq("$dtempl");
276     } else {
277       $options->{'description'} = 'Internet services';
278     }
279   }
280
281   # Default invoice number if the customer has exactly one open invoice.
282   unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
283     $options->{'invnum'} = '';
284     my @open = $self->open_cust_bill;
285     $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
286   }
287
288 }
289
290 # not a method!
291 sub _bop_cust_payby_options {
292   my ($options) = @_;
293   my $cust_payby = $options->{'cust_payby'};
294   if ($cust_payby) {
295
296     $options->{'method'} = FS::payby->payby2bop( $cust_payby->payby );
297
298     if ($cust_payby->payby =~ /^(CARD|DCRD)$/) {
299       # false laziness with cust_payby->check
300       #   which might not have been run yet
301       my( $m, $y );
302       if ( $cust_payby->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
303         ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
304       } elsif ( $cust_payby->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
305         ( $m, $y ) = ( $2, "19$1" );
306       } elsif ( $cust_payby->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
307         ( $m, $y ) = ( $3, "20$2" );
308       } else {
309         return "Illegal expiration date: ". $cust_payby->paydate;
310       }
311       $m = sprintf('%02d',$m);
312       $options->{paydate} = "$y-$m-01";
313     } else {
314       $options->{paydate} = '';
315     }
316
317     $options->{$_} = $cust_payby->$_() 
318       for qw( payinfo paycvv paymask paystart_month paystart_year 
319               payissue payname paystate paytype payip );
320
321     if ( $cust_payby->locationnum ) {
322       my $cust_location = $cust_payby->cust_location;
323       $options->{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
324     }
325   }
326 }
327
328 # can be called as class method,
329 # but can't load default name/phone fields as class method
330 sub _bop_content {
331   my ($self, $options) = @_;
332   my %content = ();
333
334   my $payip = $options->{'payip'};
335   $content{customer_ip} = $payip if length($payip);
336
337   $content{invoice_number} = $options->{'invnum'}
338     if exists($options->{'invnum'}) && length($options->{'invnum'});
339
340   $content{email_customer} = 
341     (    $conf->exists('business-onlinepayment-email_customer')
342       || $conf->exists('business-onlinepayment-email-override') );
343       
344   my ($payname, $payfirst, $paylast);
345   if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
346     ($payname = $options->{payname}) =~
347       /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
348       or return "Illegal payname $payname";
349     ($payfirst, $paylast) = ($1, $2);
350   } elsif (ref($self)) { # can't set payname if called as class method
351     $payfirst = $self->getfield('first');
352     $paylast = $self->getfield('last');
353     $payname = "$payfirst $paylast";
354   }
355
356   $content{last_name} = $paylast if $paylast;
357   $content{first_name} = $payfirst if $payfirst;
358
359   $content{name} = $payname if $payname;
360
361   $content{address} = $options->{'address1'};
362   my $address2 = $options->{'address2'};
363   $content{address} .= ", ". $address2 if length($address2);
364
365   $content{city} = $options->{'city'};
366   $content{state} = $options->{'state'};
367   $content{zip} = $options->{'zip'};
368   $content{country} = $options->{'country'};
369
370   # can't set phone if called as class method
371   $content{phone} = $self->daytime || $self->night
372     if ref($self);
373
374   my $currency =    $conf->exists('business-onlinepayment-currency')
375                  && $conf->config('business-onlinepayment-currency');
376   $content{currency} = $currency if $currency;
377
378   \%content;
379 }
380
381 # updates payinfo and cust_payby options with token from transaction
382 # can be called as a class method
383 sub _tokenize_card {
384   my ($self,$transaction,$options) = @_;
385   if ( $transaction->can('card_token') 
386        and $transaction->card_token 
387        and !$self->tokenized($options->{'payinfo'})
388   ) {
389     $options->{'payinfo'} = $transaction->card_token;
390     $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
391     return $transaction->card_token;
392   }
393   return '';
394 }
395
396 my %bop_method2payby = (
397   'CC'     => 'CARD',
398   'ECHECK' => 'CHEK',
399   'PAYPAL' => 'PPAL',
400 );
401
402 sub realtime_bop {
403   my $self = shift;
404
405   confess "Can't call realtime_bop within another transaction ".
406           '($FS::UID::AutoCommit is false)'
407     unless $FS::UID::AutoCommit;
408
409   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
410
411   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
412  
413   my %options = ();
414   if (ref($_[0]) eq 'HASH') {
415     %options = %{$_[0]};
416   } else {
417     my ( $method, $amount ) = ( shift, shift );
418     %options = @_;
419     $options{method} = $method;
420     $options{amount} = $amount;
421   }
422
423   # set fields from passed cust_payby
424   _bop_cust_payby_options(\%options);
425
426   # check for banned credit card/ACH
427   my $ban = FS::banned_pay->ban_search(
428     'payby'   => $bop_method2payby{$options{method}},
429     'payinfo' => $options{payinfo},
430   );
431   return "Banned credit card" if $ban && $ban->bantype ne 'warn';
432
433   # possibly run a separate transaction to tokenize card number,
434   #   so that we never store tokenized card info in cust_pay_pending
435   if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
436     my $token_error = $self->realtime_tokenize(\%options);
437     return $token_error if $token_error;
438     # in theory, all cust_payby will be tokenized during original save,
439     # so we shouldn't get here with opt cust_payby...but just in case...
440     if ($options{'cust_payby'} && $self->tokenized($options{'payinfo'})) {
441       $token_error = $options{'cust_payby'}->replace;
442       return $token_error if $token_error;
443     }
444   }
445
446   ### 
447   # optional credit card surcharge
448   ###
449
450   my $cc_surcharge = 0;
451   my $cc_surcharge_pct = 0;
452   $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum) 
453     if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
454     && $options{method} eq 'CC';
455
456   # always add cc surcharge if called from event 
457   if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
458       $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
459       $options{'amount'} += $cc_surcharge;
460       $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
461   }
462   elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a 
463                                  # payment screen), so consider the given 
464                                  # amount as post-surcharge
465     $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
466   }
467   
468   $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
469   $options{'cc_surcharge'} = $cc_surcharge;
470
471
472   if ( $DEBUG ) {
473     warn "$me realtime_bop (new): $options{method} $options{amount}\n";
474     warn " cc_surcharge = $cc_surcharge\n";
475   }
476   if ( $DEBUG > 2 ) {
477     warn "  $_ => $options{$_}\n" foreach keys %options;
478   }
479
480   return $self->fake_bop(\%options) if $options{'fake'};
481
482   $self->_bop_defaults(\%options);
483
484   return "Missing payinfo"
485     unless $options{'payinfo'};
486
487   ###
488   # set trans_is_recur based on invnum if there is one
489   ###
490
491   my $trans_is_recur = 0;
492   if ( $options{'invnum'} ) {
493
494     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
495     die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
496
497     my @part_pkg =
498       map  { $_->part_pkg }
499       grep { $_ }
500       map  { $_->cust_pkg }
501       $cust_bill->cust_bill_pkg;
502
503     $trans_is_recur = 1
504       if grep { $_->freq ne '0' } @part_pkg;
505
506   }
507
508   ###
509   # select a gateway
510   ###
511
512   my $payment_gateway =  $self->_payment_gateway( \%options );
513   my $namespace = $payment_gateway->gateway_namespace;
514
515   eval "use $namespace";  
516   die $@ if $@;
517
518   ###
519   # check for term discount validity
520   ###
521
522   my $discount_term = $options{discount_term};
523   if ( $discount_term ) {
524     my $bill = ($self->cust_bill)[-1]
525       or return "Can't apply a term discount to an unbilled customer";
526     my $plan = FS::discount_plan->new(
527       cust_bill => $bill,
528       months    => $discount_term
529     ) or return "No discount available for term '$discount_term'";
530     
531     if ( $plan->discounted_total != $options{amount} ) {
532       return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
533     }
534   }
535
536   ###
537   # massage data
538   ###
539
540   my $bop_content = $self->_bop_content(\%options);
541   return $bop_content unless ref($bop_content);
542
543   my @invoicing_list = $self->invoicing_list_emailonly;
544   if ( $conf->exists('emailinvoiceautoalways')
545        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
546        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
547     push @invoicing_list, $self->all_emails;
548   }
549
550   my $email = ($conf->exists('business-onlinepayment-email-override'))
551               ? $conf->config('business-onlinepayment-email-override')
552               : $invoicing_list[0];
553
554   my $paydate = '';
555   my %content = ();
556
557   if ( $namespace eq 'Business::OnlinePayment' ) {
558
559     if ( $options{method} eq 'CC' ) {
560
561       $content{card_number} = $options{payinfo};
562       $paydate = $options{'paydate'};
563       $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
564       $content{expiration} = "$2/$1";
565
566       $content{cvv2} = $options{'paycvv'}
567         if length($options{'paycvv'});
568
569       my $paystart_month = $options{'paystart_month'};
570       my $paystart_year  = $options{'paystart_year'};
571       $content{card_start} = "$paystart_month/$paystart_year"
572         if $paystart_month && $paystart_year;
573
574       my $payissue       = $options{'payissue'};
575       $content{issue_number} = $payissue if $payissue;
576
577       if ( $self->_bop_recurring_billing(
578              'payinfo'        => $options{'payinfo'},
579              'trans_is_recur' => $trans_is_recur,
580            )
581          )
582       {
583         $content{recurring_billing} = 'YES';
584         $content{acct_code} = 'rebill'
585           if $conf->exists('credit_card-recurring_billing_acct_code');
586       }
587
588     } elsif ( $options{method} eq 'ECHECK' ){
589
590       ( $content{account_number}, $content{routing_code} ) =
591         split('@', $options{payinfo});
592       $content{bank_name} = $options{payname};
593       $content{bank_state} = $options{'paystate'};
594       $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
595
596       $content{company} = $self->company if $self->company;
597
598       if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
599         $content{account_name} = $self->company;
600       } else {
601         $content{account_name} = $self->getfield('first'). ' '.
602                                  $self->getfield('last');
603       }
604
605       $content{customer_org} = $self->company ? 'B' : 'I';
606       $content{state_id}       = exists($options{'stateid'})
607                                    ? $options{'stateid'}
608                                    : $self->getfield('stateid');
609       $content{state_id_state} = exists($options{'stateid_state'})
610                                    ? $options{'stateid_state'}
611                                    : $self->getfield('stateid_state');
612       $content{customer_ssn} = exists($options{'ss'})
613                                  ? $options{'ss'}
614                                  : $self->ss;
615
616     } else {
617       die "unknown method ". $options{method};
618     }
619
620   } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
621     #move along
622   } else {
623     die "unknown namespace $namespace";
624   }
625
626   ###
627   # run transaction(s)
628   ###
629
630   my $balance = exists( $options{'balance'} )
631                   ? $options{'balance'}
632                   : $self->balance;
633
634   warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
635   $self->select_for_update; #mutex ... just until we get our pending record in
636   warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
637
638   #the checks here are intended to catch concurrent payments
639   #double-form-submission prevention is taken care of in cust_pay_pending::check
640
641   #check the balance
642   return "The customer's balance has changed; $options{method} transaction aborted."
643     if $self->balance < $balance;
644
645   #also check and make sure there aren't *other* pending payments for this cust
646
647   my @pending = qsearch('cust_pay_pending', {
648     'custnum' => $self->custnum,
649     'status'  => { op=>'!=', value=>'done' } 
650   });
651
652   #for third-party payments only, remove pending payments if they're in the 
653   #'thirdparty' (waiting for customer action) state.
654   if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
655     foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
656       my $error = $_->delete;
657       warn "error deleting unfinished third-party payment ".
658           $_->paypendingnum . ": $error\n"
659         if $error;
660     }
661     @pending = grep { $_->status ne 'thirdparty' } @pending;
662   }
663
664   return "A payment is already being processed for this customer (".
665          join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
666          "); $options{method} transaction aborted."
667     if scalar(@pending);
668
669   #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
670
671   my $cust_pay_pending = new FS::cust_pay_pending {
672     'custnum'           => $self->custnum,
673     'paid'              => $options{amount},
674     '_date'             => '',
675     'payby'             => $bop_method2payby{$options{method}},
676     'payinfo'           => $options{payinfo},
677     'paymask'           => $options{paymask},
678     'paydate'           => $paydate,
679     'recurring_billing' => $content{recurring_billing},
680     'pkgnum'            => $options{'pkgnum'},
681     'status'            => 'new',
682     'gatewaynum'        => $payment_gateway->gatewaynum || '',
683     'session_id'        => $options{session_id} || '',
684     'jobnum'            => $options{depend_jobnum} || '',
685   };
686   $cust_pay_pending->payunique( $options{payunique} )
687     if defined($options{payunique}) && length($options{payunique});
688
689   warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
690     if $DEBUG > 1;
691   my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
692   return $cpp_new_err if $cpp_new_err;
693
694   warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
695     if $DEBUG > 1;
696   warn Dumper($cust_pay_pending) if $DEBUG > 2;
697
698   my( $action1, $action2 ) =
699     split( /\s*\,\s*/, $payment_gateway->gateway_action );
700
701   my $transaction = new $namespace( $payment_gateway->gateway_module,
702                                     _bop_options(\%options),
703                                   );
704
705   $transaction->content(
706     'type'           => $options{method},
707     _bop_auth(\%options),          
708     'action'         => $action1,
709     'description'    => $options{'description'},
710     'amount'         => $options{amount},
711     #'invoice_number' => $options{'invnum'},
712     'customer_id'    => $self->custnum,
713     %$bop_content,
714     'reference'      => $cust_pay_pending->paypendingnum, #for now
715     'callback_url'   => $payment_gateway->gateway_callback_url,
716     'cancel_url'     => $payment_gateway->gateway_cancel_url,
717     'email'          => $email,
718     %content, #after
719   );
720
721   $cust_pay_pending->status('pending');
722   my $cpp_pending_err = $cust_pay_pending->replace;
723   return $cpp_pending_err if $cpp_pending_err;
724
725   warn Dumper($transaction) if $DEBUG > 2;
726
727   unless ( $BOP_TESTING ) {
728     $transaction->test_transaction(1)
729       if $conf->exists('business-onlinepayment-test_transaction');
730     $transaction->submit();
731   } else {
732     if ( $BOP_TESTING_SUCCESS ) {
733       $transaction->is_success(1);
734       $transaction->authorization('fake auth');
735     } else {
736       $transaction->is_success(0);
737       $transaction->error_message('fake failure');
738     }
739   }
740
741   if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
742
743     $cust_pay_pending->status('thirdparty');
744     my $cpp_err = $cust_pay_pending->replace;
745     return { error => $cpp_err } if $cpp_err;
746     return { reference => $cust_pay_pending->paypendingnum,
747              map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
748
749   } elsif ( $transaction->is_success() && $action2 ) {
750
751     $cust_pay_pending->status('authorized');
752     my $cpp_authorized_err = $cust_pay_pending->replace;
753     return $cpp_authorized_err if $cpp_authorized_err;
754
755     my $auth = $transaction->authorization;
756     my $ordernum = $transaction->can('order_number')
757                    ? $transaction->order_number
758                    : '';
759
760     my $capture =
761       new Business::OnlinePayment( $payment_gateway->gateway_module,
762                                    _bop_options(\%options),
763                                  );
764
765     my %capture = (
766       %content,
767       type           => $options{method},
768       action         => $action2,
769       _bop_auth(\%options),          
770       order_number   => $ordernum,
771       amount         => $options{amount},
772       authorization  => $auth,
773       description    => $options{'description'},
774     );
775
776     foreach my $field (qw( authorization_source_code returned_ACI
777                            transaction_identifier validation_code           
778                            transaction_sequence_num local_transaction_date    
779                            local_transaction_time AVS_result_code          )) {
780       $capture{$field} = $transaction->$field() if $transaction->can($field);
781     }
782
783     $capture->content( %capture );
784
785     $capture->test_transaction(1)
786       if $conf->exists('business-onlinepayment-test_transaction');
787     $capture->submit();
788
789     unless ( $capture->is_success ) {
790       my $e = "Authorization successful but capture failed, custnum #".
791               $self->custnum. ': '.  $capture->result_code.
792               ": ". $capture->error_message;
793       warn $e;
794       return $e;
795     }
796
797   }
798
799   ###
800   # remove paycvv after initial transaction
801   ###
802
803   # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
804   if ( length($options{'paycvv'})
805        && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
806   ) {
807     my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
808     if ( $error ) {
809       $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
810       #not returning error, should at least attempt to handle results of an otherwise valid transaction
811       warn "WARNING: error removing cvv: $error\n";
812     }
813   }
814
815   ###
816   # Tokenize
817   ###
818
819   # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
820   #   if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
821   if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
822     # cpp will be replaced in _realtime_bop_result
823     $cust_pay_pending->payinfo($card_token);
824     if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
825       $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
826       #not returning error, should at least attempt to handle results of an otherwise valid transaction
827       #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
828     }
829   }
830
831   ###
832   # result handling
833   ###
834
835   $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
836
837 }
838
839 =item fake_bop
840
841 =cut
842
843 sub fake_bop {
844   my $self = shift;
845
846   my %options = ();
847   if (ref($_[0]) eq 'HASH') {
848     %options = %{$_[0]};
849   } else {
850     my ( $method, $amount ) = ( shift, shift );
851     %options = @_;
852     $options{method} = $method;
853     $options{amount} = $amount;
854   }
855   
856   if ( $options{'fake_failure'} ) {
857      return "Error: No error; test failure requested with fake_failure";
858   }
859
860   my $cust_pay = new FS::cust_pay ( {
861      'custnum'  => $self->custnum,
862      'invnum'   => $options{'invnum'},
863      'paid'     => $options{amount},
864      '_date'    => '',
865      'payby'    => $bop_method2payby{$options{method}},
866      'payinfo'  => '4111111111111111',
867      'paydate'  => '2012-05-01',
868      'processor'      => 'FakeProcessor',
869      'auth'           => '54',
870      'order_number'   => '32',
871   } );
872   $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
873
874   if ( $DEBUG ) {
875       warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
876       warn "  $_ => $options{$_}\n" foreach keys %options;
877   }
878
879   my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
880
881   if ( $error ) {
882     $cust_pay->invnum(''); #try again with no specific invnum
883     my $error2 = $cust_pay->insert( $options{'manual'} ?
884                                     ( 'manual' => 1 ) : ()
885                                   );
886     if ( $error2 ) {
887       # gah, even with transactions.
888       my $e = 'WARNING: Card/ACH debited but database not updated - '.
889               "error inserting (fake!) payment: $error2".
890               " (previously tried insert with invnum #$options{'invnum'}" .
891               ": $error )";
892       warn $e;
893       return $e;
894     }
895   }
896
897   if ( $options{'paynum_ref'} ) {
898     ${ $options{'paynum_ref'} } = $cust_pay->paynum;
899   }
900
901   return ''; #no error
902
903 }
904
905
906 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
907
908 # Wraps up processing of a realtime credit card or ACH (electronic check)
909 # transaction.
910
911 sub _realtime_bop_result {
912   my( $self, $cust_pay_pending, $transaction, %options ) = @_;
913
914   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
915
916   if ( $DEBUG ) {
917     warn "$me _realtime_bop_result: pending transaction ".
918       $cust_pay_pending->paypendingnum. "\n";
919     warn "  $_ => $options{$_}\n" foreach keys %options;
920   }
921
922   my $payment_gateway = $options{payment_gateway}
923     or return "no payment gateway in arguments to _realtime_bop_result";
924
925   $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
926   my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
927   return $cpp_captured_err if $cpp_captured_err;
928
929   if ( $transaction->is_success() ) {
930
931     my $order_number = $transaction->order_number
932       if $transaction->can('order_number');
933
934     my $cust_pay = new FS::cust_pay ( {
935        'custnum'  => $self->custnum,
936        'invnum'   => $options{'invnum'},
937        'paid'     => $cust_pay_pending->paid,
938        '_date'    => '',
939        'payby'    => $cust_pay_pending->payby,
940        'payinfo'  => $options{'payinfo'},
941        'paymask'  => $options{'paymask'} || $cust_pay_pending->paymask,
942        'paydate'  => $cust_pay_pending->paydate,
943        'pkgnum'   => $cust_pay_pending->pkgnum,
944        'discount_term'  => $options{'discount_term'},
945        'gatewaynum'     => ($payment_gateway->gatewaynum || ''),
946        'processor'      => $payment_gateway->gateway_module,
947        'auth'           => $transaction->authorization,
948        'order_number'   => $order_number || '',
949        'no_auto_apply'  => $options{'no_auto_apply'} ? 'Y' : '',
950     } );
951     #doesn't hurt to know, even though the dup check is in cust_pay_pending now
952     $cust_pay->payunique( $options{payunique} )
953       if defined($options{payunique}) && length($options{payunique});
954
955     my $oldAutoCommit = $FS::UID::AutoCommit;
956     local $FS::UID::AutoCommit = 0;
957     my $dbh = dbh;
958
959     #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
960
961     my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
962
963     if ( $error ) {
964       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
965       $cust_pay->invnum(''); #try again with no specific invnum
966       $cust_pay->paynum('');
967       my $error2 = $cust_pay->insert( $options{'manual'} ?
968                                       ( 'manual' => 1 ) : ()
969                                     );
970       if ( $error2 ) {
971         # gah.  but at least we have a record of the state we had to abort in
972         # from cust_pay_pending now.
973         $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
974         my $e = "WARNING: $options{method} captured but payment not recorded -".
975                 " error inserting payment (". $payment_gateway->gateway_module.
976                 "): $error2".
977                 " (previously tried insert with invnum #$options{'invnum'}" .
978                 ": $error ) - pending payment saved as paypendingnum ".
979                 $cust_pay_pending->paypendingnum. "\n";
980         warn $e;
981         return $e;
982       }
983     }
984
985     my $jobnum = $cust_pay_pending->jobnum;
986     if ( $jobnum ) {
987        my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
988       
989        unless ( $placeholder ) {
990          $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
991          my $e = "WARNING: $options{method} captured but job $jobnum not ".
992              "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
993          warn $e;
994          return $e;
995        }
996
997        $error = $placeholder->delete;
998
999        if ( $error ) {
1000          $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1001          my $e = "WARNING: $options{method} captured but could not delete ".
1002               "job $jobnum for paypendingnum ".
1003               $cust_pay_pending->paypendingnum. ": $error\n";
1004          warn $e;
1005          return $e;
1006        }
1007
1008        $cust_pay_pending->set('jobnum','');
1009
1010     }
1011     
1012     if ( $options{'paynum_ref'} ) {
1013       ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1014     }
1015
1016     $cust_pay_pending->status('done');
1017     $cust_pay_pending->statustext('captured');
1018     $cust_pay_pending->paynum($cust_pay->paynum);
1019     my $cpp_done_err = $cust_pay_pending->replace;
1020
1021     if ( $cpp_done_err ) {
1022
1023       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1024       my $e = "WARNING: $options{method} captured but payment not recorded - ".
1025               "error updating status for paypendingnum ".
1026               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1027       warn $e;
1028       return $e;
1029
1030     } else {
1031
1032       $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1033
1034       if ( $options{'apply'} ) {
1035         my $apply_error = $self->apply_payments_and_credits;
1036         if ( $apply_error ) {
1037           warn "WARNING: error applying payment: $apply_error\n";
1038           #but we still should return no error cause the payment otherwise went
1039           #through...
1040         }
1041       }
1042
1043       # have a CC surcharge portion --> one-time charge
1044       if ( $options{'cc_surcharge'} > 0 ) { 
1045             # XXX: this whole block needs to be in a transaction?
1046
1047           my $invnum;
1048           $invnum = $options{'invnum'} if $options{'invnum'};
1049           unless ( $invnum ) { # probably from a payment screen
1050              # do we have any open invoices? pick earliest
1051              # uses the fact that cust_main->cust_bill sorts by date ascending
1052              my @open = $self->open_cust_bill;
1053              $invnum = $open[0]->invnum if scalar(@open);
1054           }
1055             
1056           unless ( $invnum ) {  # still nothing? pick last closed invoice
1057              # again uses fact that cust_main->cust_bill sorts by date ascending
1058              my @closed = $self->cust_bill;
1059              $invnum = $closed[$#closed]->invnum if scalar(@closed);
1060           }
1061
1062           unless ( $invnum ) {
1063             # XXX: unlikely case - pre-paying before any invoices generated
1064             # what it should do is create a new invoice and pick it
1065                 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1066                 return '';
1067           }
1068
1069           my $cust_pkg;
1070           my $charge_error = $self->charge({
1071                                     'amount'    => $options{'cc_surcharge'},
1072                                     'pkg'       => 'Credit Card Surcharge',
1073                                     'setuptax'  => 'Y',
1074                                     'cust_pkg_ref' => \$cust_pkg,
1075                                 });
1076           if($charge_error) {
1077                 warn 'Unable to add CC surcharge cust_pkg';
1078                 return '';
1079           }
1080
1081           $cust_pkg->setup(time);
1082           my $cp_error = $cust_pkg->replace;
1083           if($cp_error) {
1084               warn 'Unable to set setup time on cust_pkg for cc surcharge';
1085             # but keep going...
1086           }
1087                                     
1088           my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1089           unless ( $cust_bill ) {
1090               warn "race condition + invoice deletion just happened";
1091               return '';
1092           }
1093
1094           my $grand_error = 
1095             $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1096
1097           warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1098             if $grand_error;
1099       }
1100
1101       return ''; #no error
1102
1103     }
1104
1105   } else {
1106
1107     my $perror = $transaction->error_message;
1108     #$payment_gateway->gateway_module. " error: ".
1109     # removed for conciseness
1110
1111     my $jobnum = $cust_pay_pending->jobnum;
1112     if ( $jobnum ) {
1113        my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1114       
1115        if ( $placeholder ) {
1116          my $error = $placeholder->depended_delete;
1117          $error ||= $placeholder->delete;
1118          $cust_pay_pending->set('jobnum','');
1119          warn "error removing provisioning jobs after declined paypendingnum ".
1120            $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1121        } else {
1122          my $e = "error finding job $jobnum for declined paypendingnum ".
1123               $cust_pay_pending->paypendingnum. "\n";
1124          warn $e;
1125        }
1126
1127     }
1128     
1129     unless ( $transaction->error_message ) {
1130
1131       my $t_response;
1132       if ( $transaction->can('response_page') ) {
1133         $t_response = {
1134                         'page'    => ( $transaction->can('response_page')
1135                                          ? $transaction->response_page
1136                                          : ''
1137                                      ),
1138                         'code'    => ( $transaction->can('response_code')
1139                                          ? $transaction->response_code
1140                                          : ''
1141                                      ),
1142                         'headers' => ( $transaction->can('response_headers')
1143                                          ? $transaction->response_headers
1144                                          : ''
1145                                      ),
1146                       };
1147       } else {
1148         $t_response .=
1149           "No additional debugging information available for ".
1150             $payment_gateway->gateway_module;
1151       }
1152
1153       $perror .= "No error_message returned from ".
1154                    $payment_gateway->gateway_module. " -- ".
1155                  ( ref($t_response) ? Dumper($t_response) : $t_response );
1156
1157     }
1158
1159     if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1160          && $conf->exists('emaildecline', $self->agentnum)
1161          && grep { $_ ne 'POST' } $self->invoicing_list
1162          && ! grep { $transaction->error_message =~ /$_/ }
1163                    $conf->config('emaildecline-exclude', $self->agentnum)
1164     ) {
1165
1166       # Send a decline alert to the customer.
1167       my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1168       my $error = '';
1169       if ( $msgnum ) {
1170         # include the raw error message in the transaction state
1171         $cust_pay_pending->setfield('error', $transaction->error_message);
1172         my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1173         $error = $msg_template->send( 'cust_main' => $self,
1174                                       'object'    => $cust_pay_pending );
1175       }
1176
1177
1178       $perror .= " (also received error sending decline notification: $error)"
1179         if $error;
1180
1181     }
1182
1183     $cust_pay_pending->status('done');
1184     $cust_pay_pending->statustext($perror);
1185     #'declined:': no, that's failure_status
1186     if ( $transaction->can('failure_status') ) {
1187       $cust_pay_pending->failure_status( $transaction->failure_status );
1188     }
1189     my $cpp_done_err = $cust_pay_pending->replace;
1190     if ( $cpp_done_err ) {
1191       my $e = "WARNING: $options{method} declined but pending payment not ".
1192               "resolved - error updating status for paypendingnum ".
1193               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1194       warn $e;
1195       $perror = "$e ($perror)";
1196     }
1197
1198     return $perror;
1199   }
1200
1201 }
1202
1203 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1204
1205 Verifies successful third party processing of a realtime credit card or
1206 ACH (electronic check) transaction via a
1207 Business::OnlineThirdPartyPayment realtime gateway.  See
1208 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1209
1210 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1211
1212 The additional options I<payname>, I<city>, I<state>,
1213 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
1214 if set, will override the value from the customer record.
1215
1216 I<description> is a free-text field passed to the gateway.  It defaults to
1217 "Internet services".
1218
1219 If an I<invnum> is specified, this payment (if successful) is applied to the
1220 specified invoice.  If you don't specify an I<invnum> you might want to
1221 call the B<apply_payments> method.
1222
1223 I<quiet> can be set true to surpress email decline notices.
1224
1225 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
1226 resulting paynum, if any.
1227
1228 I<payunique> is a unique identifier for this payment.
1229
1230 Returns a hashref containing elements bill_error (which will be undefined
1231 upon success) and session_id of any associated session.
1232
1233 =cut
1234
1235 sub realtime_botpp_capture {
1236   my( $self, $cust_pay_pending, %options ) = @_;
1237
1238   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1239
1240   if ( $DEBUG ) {
1241     warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1242     warn "  $_ => $options{$_}\n" foreach keys %options;
1243   }
1244
1245   eval "use Business::OnlineThirdPartyPayment";  
1246   die $@ if $@;
1247
1248   ###
1249   # select the gateway
1250   ###
1251
1252   my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1253
1254   my $payment_gateway;
1255   my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1256   $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1257                 { gatewaynum => $gatewaynum }
1258               )
1259     : $self->agent->payment_gateway( 'method' => $method,
1260                                      # 'invnum'  => $cust_pay_pending->invnum,
1261                                      # 'payinfo' => $cust_pay_pending->payinfo,
1262                                    );
1263
1264   $options{payment_gateway} = $payment_gateway; # for the helper subs
1265
1266   ###
1267   # massage data
1268   ###
1269
1270   my @invoicing_list = $self->invoicing_list_emailonly;
1271   if ( $conf->exists('emailinvoiceautoalways')
1272        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1273        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1274     push @invoicing_list, $self->all_emails;
1275   }
1276
1277   my $email = ($conf->exists('business-onlinepayment-email-override'))
1278               ? $conf->config('business-onlinepayment-email-override')
1279               : $invoicing_list[0];
1280
1281   my %content = ();
1282
1283   $content{email_customer} = 
1284     (    $conf->exists('business-onlinepayment-email_customer')
1285       || $conf->exists('business-onlinepayment-email-override') );
1286       
1287   ###
1288   # run transaction(s)
1289   ###
1290
1291   my $transaction =
1292     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1293                                            _bop_options(\%options),
1294                                          );
1295
1296   $transaction->reference({ %options }); 
1297
1298   $transaction->content(
1299     'type'           => $method,
1300     _bop_auth(\%options),
1301     'action'         => 'Post Authorization',
1302     'description'    => $options{'description'},
1303     'amount'         => $cust_pay_pending->paid,
1304     #'invoice_number' => $options{'invnum'},
1305     'customer_id'    => $self->custnum,
1306     'reference'      => $cust_pay_pending->paypendingnum,
1307     'email'          => $email,
1308     'phone'          => $self->daytime || $self->night,
1309     %content, #after
1310     # plus whatever is required for bogus capture avoidance
1311   );
1312
1313   $transaction->submit();
1314
1315   my $error =
1316     $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1317
1318   if ( $options{'apply'} ) {
1319     my $apply_error = $self->apply_payments_and_credits;
1320     if ( $apply_error ) {
1321       warn "WARNING: error applying payment: $apply_error\n";
1322     }
1323   }
1324
1325   return {
1326     bill_error => $error,
1327     session_id => $cust_pay_pending->session_id,
1328   }
1329
1330 }
1331
1332 =item default_payment_gateway
1333
1334 DEPRECATED -- use agent->payment_gateway
1335
1336 =cut
1337
1338 sub default_payment_gateway {
1339   my( $self, $method ) = @_;
1340
1341   die "Real-time processing not enabled\n"
1342     unless $conf->exists('business-onlinepayment');
1343
1344   #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1345
1346   #load up config
1347   my $bop_config = 'business-onlinepayment';
1348   $bop_config .= '-ach'
1349     if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1350   my ( $processor, $login, $password, $action, @bop_options ) =
1351     $conf->config($bop_config);
1352   $action ||= 'normal authorization';
1353   pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1354   die "No real-time processor is enabled - ".
1355       "did you set the business-onlinepayment configuration value?\n"
1356     unless $processor;
1357
1358   ( $processor, $login, $password, $action, @bop_options )
1359 }
1360
1361 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1362
1363 Refunds a realtime credit card or ACH (electronic check) transaction
1364 via a Business::OnlinePayment realtime gateway.  See
1365 L<http://420.am/business-onlinepayment> for supported gateways.
1366
1367 Available methods are: I<CC> or I<ECHECK>
1368
1369 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1370
1371 Most gateways require a reference to an original payment transaction to refund,
1372 so you probably need to specify a I<paynum>.
1373
1374 I<amount> defaults to the original amount of the payment if not specified.
1375
1376 I<reasonnum> specified an existing refund reason for the refund
1377
1378 I<paydate> specifies the expiration date for a credit card overriding the
1379 value from the customer record or the payment record. Specified as yyyy-mm-dd
1380
1381 Implementation note: If I<amount> is unspecified or equal to the amount of the
1382 orignal payment, first an attempt is made to "void" the transaction via
1383 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1384 the normal attempt is made to "refund" ("credit") the transaction via the
1385 gateway is attempted. No attempt to "void" the transaction is made if the 
1386 gateway has introspection data and doesn't support void.
1387
1388 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1389 #I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
1390 #if set, will override the value from the customer record.
1391
1392 #If an I<invnum> is specified, this payment (if successful) is applied to the
1393 #specified invoice.  If you don't specify an I<invnum> you might want to
1394 #call the B<apply_payments> method.
1395
1396 =cut
1397
1398 #some false laziness w/realtime_bop, not enough to make it worth merging
1399 #but some useful small subs should be pulled out
1400 sub realtime_refund_bop {
1401   my $self = shift;
1402
1403   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1404
1405   my %options = ();
1406   if (ref($_[0]) eq 'HASH') {
1407     %options = %{$_[0]};
1408   } else {
1409     my $method = shift;
1410     %options = @_;
1411     $options{method} = $method;
1412   }
1413
1414   if ( $DEBUG ) {
1415     warn "$me realtime_refund_bop (new): $options{method} refund\n";
1416     warn "  $_ => $options{$_}\n" foreach keys %options;
1417   }
1418
1419   return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1420
1421   my %content = ();
1422
1423   ###
1424   # look up the original payment and optionally a gateway for that payment
1425   ###
1426
1427   my $cust_pay = '';
1428   my $amount = $options{'amount'};
1429
1430   my( $processor, $login, $password, @bop_options, $namespace ) ;
1431   my( $auth, $order_number ) = ( '', '', '' );
1432   my $gatewaynum = '';
1433
1434   if ( $options{'paynum'} ) {
1435
1436     warn "  paynum: $options{paynum}\n" if $DEBUG > 1;
1437     $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1438       or return "Unknown paynum $options{'paynum'}";
1439     $amount ||= $cust_pay->paid;
1440
1441     my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1442     $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1443
1444     if ( $cust_pay->get('processor') ) {
1445       ($gatewaynum, $processor, $auth, $order_number) =
1446       (
1447         $cust_pay->gatewaynum,
1448         $cust_pay->processor,
1449         $cust_pay->auth,
1450         $cust_pay->order_number,
1451       );
1452     } else {
1453       # this payment wasn't upgraded, which probably means this won't work,
1454       # but try it anyway
1455       $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1456         or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1457                   $cust_pay->paybatch;
1458       ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1459     }
1460
1461     my $payment_gateway;
1462     if ( $gatewaynum ) { #gateway for the payment to be refunded
1463
1464       $payment_gateway =
1465         qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1466       die "payment gateway $gatewaynum not found"
1467         unless $payment_gateway;
1468
1469       $processor   = $payment_gateway->gateway_module;
1470       $login       = $payment_gateway->gateway_username;
1471       $password    = $payment_gateway->gateway_password;
1472       $namespace   = $payment_gateway->gateway_namespace;
1473       @bop_options = $payment_gateway->options;
1474
1475     } else { #try the default gateway
1476
1477       my $conf_processor;
1478       $payment_gateway =
1479         $self->agent->payment_gateway('method' => $options{method});
1480
1481       ( $conf_processor, $login, $password, $namespace ) =
1482         map { my $method = "gateway_$_"; $payment_gateway->$method }
1483           qw( module username password namespace );
1484
1485       @bop_options = $payment_gateway->gatewaynum
1486                        ? $payment_gateway->options
1487                        : @{ $payment_gateway->get('options') };
1488       my %bop_options = @bop_options;
1489
1490       return "processor of payment $options{'paynum'} $processor does not".
1491              " match default processor $conf_processor"
1492         unless ($processor eq $conf_processor)
1493             || (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}));
1494
1495       $processor = $conf_processor;
1496
1497     }
1498
1499     # if gateway has switched to CardFortress but token_check hasn't run yet,
1500     # tokenize just this record now, so that token gets passed/set appropriately
1501     if ($cust_pay->payby eq 'CARD' && !$cust_pay->tokenized) {
1502       my %tokenopts = (
1503         'payment_gateway' => $payment_gateway,
1504         'method'          => 'CC',
1505         'payinfo'         => $cust_pay->payinfo,
1506         'paydate'         => $cust_pay->paydate,
1507       );
1508       my $error = $self->realtime_tokenize(\%tokenopts); # no-op unless gateway can tokenize
1509       if ($self->tokenized($tokenopts{'payinfo'})) { # implies no error
1510         warn "  tokenizing cust_pay\n" if $DEBUG > 1;
1511         $cust_pay->payinfo($tokenopts{'payinfo'});
1512         $error = $cust_pay->replace;
1513       }
1514       return $error if $error;
1515     }
1516
1517   } else { # didn't specify a paynum, so look for agent gateway overrides
1518            # like a normal transaction 
1519  
1520     my $payment_gateway =
1521       $self->agent->payment_gateway( 'method'  => $options{method} );
1522     my( $processor, $login, $password, $namespace ) =
1523       map { my $method = "gateway_$_"; $payment_gateway->$method }
1524         qw( module username password namespace );
1525
1526     my @bop_options = $payment_gateway->gatewaynum
1527                         ? $payment_gateway->options
1528                         : @{ $payment_gateway->get('options') };
1529
1530   }
1531   return "neither amount nor paynum specified" unless $amount;
1532
1533   eval "use $namespace";  
1534   die $@ if $@;
1535
1536   %content = (
1537     %content,
1538     'type'           => $options{method},
1539     'login'          => $login,
1540     'password'       => $password,
1541     'order_number'   => $order_number,
1542     'amount'         => $amount,
1543   );
1544   $content{authorization} = $auth
1545     if length($auth); #echeck/ACH transactions have an order # but no auth
1546                       #(at least with authorize.net)
1547
1548   my $currency =    $conf->exists('business-onlinepayment-currency')
1549                  && $conf->config('business-onlinepayment-currency');
1550   $content{currency} = $currency if $currency;
1551
1552   my $disable_void_after;
1553   if ($conf->exists('disable_void_after')
1554       && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1555     $disable_void_after = $1;
1556   }
1557
1558   #first try void if applicable
1559   my $void = new Business::OnlinePayment( $processor, @bop_options );
1560
1561   my $tryvoid = 1;
1562   if ($void->can('info')) {
1563       my $paytype = '';
1564       $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1565       $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1566       my %supported_actions = $void->info('supported_actions');
1567       $tryvoid = 0 
1568         if ( %supported_actions && $paytype 
1569                 && defined($supported_actions{$paytype}) 
1570                 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1571   }
1572
1573   if ( $cust_pay && $cust_pay->paid == $amount
1574     && (
1575       ( not defined($disable_void_after) )
1576       || ( time < ($cust_pay->_date + $disable_void_after ) )
1577     )
1578     && $tryvoid
1579   ) {
1580     warn "  attempting void\n" if $DEBUG > 1;
1581     if ( $void->can('info') ) {
1582       if ( $cust_pay->payby eq 'CARD'
1583            && $void->info('CC_void_requires_card') )
1584       {
1585         $content{'card_number'} = $cust_pay->payinfo;
1586       } elsif ( $cust_pay->payby eq 'CHEK'
1587                 && $void->info('ECHECK_void_requires_account') )
1588       {
1589         ( $content{'account_number'}, $content{'routing_code'} ) =
1590           split('@', $cust_pay->payinfo);
1591         $content{'name'} = $self->get('first'). ' '. $self->get('last');
1592       }
1593     }
1594     $void->content( 'action' => 'void', %content );
1595     $void->test_transaction(1)
1596       if $conf->exists('business-onlinepayment-test_transaction');
1597     $void->submit();
1598     if ( $void->is_success ) {
1599       # specified as a refund reason, but now we want a payment void reason
1600       # extract just the reason text, let cust_pay::void handle new_or_existing
1601       my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1602       my $error;
1603       $error = 'Reason could not be loaded' unless $reason;      
1604       $error = $cust_pay->void($reason->reason) unless $error;
1605       if ( $error ) {
1606         # gah, even with transactions.
1607         my $e = 'WARNING: Card/ACH voided but database not updated - '.
1608                 "error voiding payment: $error";
1609         warn $e;
1610         return $e;
1611       }
1612       warn "  void successful\n" if $DEBUG > 1;
1613       return '';
1614     }
1615   }
1616
1617   warn "  void unsuccessful, trying refund\n"
1618     if $DEBUG > 1;
1619
1620   #massage data
1621   my $address = $self->address1;
1622   $address .= ", ". $self->address2 if $self->address2;
1623
1624   my($payname, $payfirst, $paylast);
1625   if ( $self->payname && $options{method} ne 'ECHECK' ) {
1626     $payname = $self->payname;
1627     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1628       or return "Illegal payname $payname";
1629     ($payfirst, $paylast) = ($1, $2);
1630   } else {
1631     $payfirst = $self->getfield('first');
1632     $paylast = $self->getfield('last');
1633     $payname =  "$payfirst $paylast";
1634   }
1635
1636   my @invoicing_list = $self->invoicing_list_emailonly;
1637   if ( $conf->exists('emailinvoiceautoalways')
1638        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1639        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1640     push @invoicing_list, $self->all_emails;
1641   }
1642
1643   my $email = ($conf->exists('business-onlinepayment-email-override'))
1644               ? $conf->config('business-onlinepayment-email-override')
1645               : $invoicing_list[0];
1646
1647   my $payip = exists($options{'payip'})
1648                 ? $options{'payip'}
1649                 : $self->payip;
1650   $content{customer_ip} = $payip
1651     if length($payip);
1652
1653   my $payinfo = '';
1654   my $paymask = ''; # for refund record
1655   if ( $options{method} eq 'CC' ) {
1656
1657     if ( $cust_pay ) {
1658       $content{card_number} = $payinfo = $cust_pay->payinfo;
1659       $paymask = $cust_pay->paymask;
1660       (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1661         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1662         ($content{expiration} = "$2/$1");  # where available
1663     } else {
1664       # this really needs a better cleanup
1665       die "Refund without paynum not supported";
1666 #      $content{card_number} = $payinfo = $self->payinfo;
1667 #      (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1668 #        =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1669 #      $content{expiration} = "$2/$1";
1670     }
1671
1672   } elsif ( $options{method} eq 'ECHECK' ) {
1673
1674     if ( $cust_pay ) {
1675       $payinfo = $cust_pay->payinfo;
1676     } else {
1677       $payinfo = $self->payinfo;
1678     } 
1679     ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1680     $content{bank_name} = $self->payname;
1681     $content{account_type} = 'CHECKING';
1682     $content{account_name} = $payname;
1683     $content{customer_org} = $self->company ? 'B' : 'I';
1684     $content{customer_ssn} = $self->ss;
1685
1686   }
1687
1688   #then try refund
1689   my $refund = new Business::OnlinePayment( $processor, @bop_options );
1690   my %sub_content = $refund->content(
1691     'action'         => 'credit',
1692     'customer_id'    => $self->custnum,
1693     'last_name'      => $paylast,
1694     'first_name'     => $payfirst,
1695     'name'           => $payname,
1696     'address'        => $address,
1697     'city'           => $self->city,
1698     'state'          => $self->state,
1699     'zip'            => $self->zip,
1700     'country'        => $self->country,
1701     'email'          => $email,
1702     'phone'          => $self->daytime || $self->night,
1703     %content, #after
1704   );
1705   warn join('', map { "  $_ => $sub_content{$_}\n" } keys %sub_content )
1706     if $DEBUG > 1;
1707   $refund->test_transaction(1)
1708     if $conf->exists('business-onlinepayment-test_transaction');
1709   $refund->submit();
1710
1711   return "$processor error: ". $refund->error_message
1712     unless $refund->is_success();
1713
1714   $order_number = $refund->order_number if $refund->can('order_number');
1715
1716   # change this to just use $cust_pay->delete_cust_bill_pay?
1717   while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1718     my @cust_bill_pay = $cust_pay->cust_bill_pay;
1719     last unless @cust_bill_pay;
1720     my $cust_bill_pay = pop @cust_bill_pay;
1721     my $error = $cust_bill_pay->delete;
1722     last if $error;
1723   }
1724
1725   my $cust_refund = new FS::cust_refund ( {
1726     'custnum'  => $self->custnum,
1727     'paynum'   => $options{'paynum'},
1728     'source_paynum' => $options{'paynum'},
1729     'refund'   => $amount,
1730     '_date'    => '',
1731     'payby'    => $bop_method2payby{$options{method}},
1732     'payinfo'  => $payinfo,
1733     'paymask'  => $paymask,
1734     'reasonnum'     => $options{'reasonnum'},
1735     'gatewaynum'    => $gatewaynum, # may be null
1736     'processor'     => $processor,
1737     'auth'          => $refund->authorization,
1738     'order_number'  => $order_number,
1739   } );
1740   my $error = $cust_refund->insert;
1741   if ( $error ) {
1742     $cust_refund->paynum(''); #try again with no specific paynum
1743     $cust_refund->source_paynum('');
1744     my $error2 = $cust_refund->insert;
1745     if ( $error2 ) {
1746       # gah, even with transactions.
1747       my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1748               "error inserting refund ($processor): $error2".
1749               " (previously tried insert with paynum #$options{'paynum'}" .
1750               ": $error )";
1751       warn $e;
1752       return $e;
1753     }
1754   }
1755
1756   ''; #no error
1757
1758 }
1759
1760 =item realtime_verify_bop [ OPTION => VALUE ... ]
1761
1762 Runs an authorization-only transaction for $1 against this credit card (if
1763 successful, immediatly reverses the authorization).
1764
1765 Returns the empty string if the authorization was sucessful, or an error
1766 message otherwise.
1767
1768 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1769 Object will be tokenized if possible, but that change will not be
1770 updated in database (must be inserted/replaced afterwards.)
1771
1772 Currently only succeeds for Business::OnlinePayment CC transactions.
1773
1774 =cut
1775
1776 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1777 #it worth merging but some useful small subs should be pulled out
1778 sub realtime_verify_bop {
1779   my $self = shift;
1780
1781   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1782   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1783
1784   my %options = ();
1785   if (ref($_[0]) eq 'HASH') {
1786     %options = %{$_[0]};
1787   } else {
1788     %options = @_;
1789   }
1790
1791   if ( $DEBUG ) {
1792     warn "$me realtime_verify_bop\n";
1793     warn "  $_ => $options{$_}\n" foreach keys %options;
1794   }
1795
1796   # set fields from passed cust_payby
1797   return "No cust_payby" unless $options{'cust_payby'};
1798   _bop_cust_payby_options(\%options);
1799
1800   # check for banned credit card/ACH
1801   my $ban = FS::banned_pay->ban_search(
1802     'payby'   => $bop_method2payby{'CC'},
1803     'payinfo' => $options{payinfo},
1804   );
1805   return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1806
1807   # possibly run a separate transaction to tokenize card number,
1808   #   so that we never store tokenized card info in cust_pay_pending
1809   if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1810     my $token_error = $self->realtime_tokenize(\%options);
1811     return $token_error if $token_error;
1812     #important that we not replace cust_payby here,
1813     #because cust_payby->replace uses realtime_verify_bop!
1814   }
1815
1816   ###
1817   # select a gateway
1818   ###
1819
1820   my $payment_gateway =  $self->_payment_gateway( \%options );
1821   my $namespace = $payment_gateway->gateway_namespace;
1822
1823   eval "use $namespace";  
1824   die $@ if $@;
1825
1826   ###
1827   # massage data
1828   ###
1829
1830   my $bop_content = $self->_bop_content(\%options);
1831   return $bop_content unless ref($bop_content);
1832
1833   my @invoicing_list = $self->invoicing_list_emailonly;
1834   if ( $conf->exists('emailinvoiceautoalways')
1835        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1836        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1837     push @invoicing_list, $self->all_emails;
1838   }
1839
1840   my $email = ($conf->exists('business-onlinepayment-email-override'))
1841               ? $conf->config('business-onlinepayment-email-override')
1842               : $invoicing_list[0];
1843
1844   my $paydate = '';
1845   my %content = ();
1846
1847   if ( $namespace eq 'Business::OnlinePayment' ) {
1848
1849     if ( $options{method} eq 'CC' ) {
1850
1851       $content{card_number} = $options{payinfo};
1852       $paydate = $options{'paydate'};
1853       $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1854       $content{expiration} = "$2/$1";
1855
1856       $content{cvv2} = $options{'paycvv'}
1857         if length($options{'paycvv'});
1858
1859       my $paystart_month = $options{'paystart_month'};
1860       my $paystart_year  = $options{'paystart_year'};
1861
1862       $content{card_start} = "$paystart_month/$paystart_year"
1863         if $paystart_month && $paystart_year;
1864
1865       my $payissue       = $options{'payissue'};
1866       $content{issue_number} = $payissue if $payissue;
1867
1868     } elsif ( $options{method} eq 'ECHECK' ){
1869       #cannot verify, move along (though it shouldn't be called...)
1870       return '';
1871     } else {
1872       return "unknown method ". $options{method};
1873     }
1874   } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1875     #cannot verify, move along
1876     return '';
1877   } else {
1878     return "unknown namespace $namespace";
1879   }
1880
1881   ###
1882   # run transaction(s)
1883   ###
1884
1885   my $error;
1886   my $transaction; #need this back so we can do _tokenize_card
1887
1888   # don't mutex the customer here, because they might be uncommitted. and
1889   # this is only verification. it doesn't matter if they have other
1890   # unfinished verifications.
1891
1892   my $cust_pay_pending = new FS::cust_pay_pending {
1893     'custnum_pending'   => 1,
1894     'paid'              => '1.00',
1895     '_date'             => '',
1896     'payby'             => $bop_method2payby{'CC'},
1897     'payinfo'           => $options{payinfo},
1898     'paymask'           => $options{paymask},
1899     'paydate'           => $paydate,
1900     'pkgnum'            => $options{'pkgnum'},
1901     'status'            => 'new',
1902     'gatewaynum'        => $payment_gateway->gatewaynum || '',
1903     'session_id'        => $options{session_id} || '',
1904   };
1905   $cust_pay_pending->payunique( $options{payunique} )
1906     if defined($options{payunique}) && length($options{payunique});
1907
1908   IMMEDIATE: {
1909     # open a separate handle for creating/updating the cust_pay_pending
1910     # record
1911     local $FS::UID::dbh = myconnect();
1912     local $FS::UID::AutoCommit = 1;
1913
1914     # if this is an existing customer (and we can tell now because
1915     # this is a fresh transaction), it's safe to assign their custnum
1916     # to the cust_pay_pending record, and then the verification attempt
1917     # will remain linked to them even if it fails.
1918     if ( FS::cust_main->by_key($self->custnum) ) {
1919       $cust_pay_pending->set('custnum', $self->custnum);
1920     }
1921
1922     warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1923       if $DEBUG > 1;
1924
1925     # if this fails, just return; everything else will still allow the
1926     # cust_pay_pending to have its custnum set later
1927     my $cpp_new_err = $cust_pay_pending->insert;
1928     return $cpp_new_err if $cpp_new_err;
1929
1930     warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1931       if $DEBUG > 1;
1932     warn Dumper($cust_pay_pending) if $DEBUG > 2;
1933
1934     $transaction = new $namespace( $payment_gateway->gateway_module,
1935                                    _bop_options(\%options),
1936                                     );
1937
1938     $transaction->content(
1939       'type'           => 'CC',
1940       _bop_auth(\%options),          
1941       'action'         => 'Authorization Only',
1942       'description'    => $options{'description'},
1943       'amount'         => '1.00',
1944       'customer_id'    => $self->custnum,
1945       %$bop_content,
1946       'reference'      => $cust_pay_pending->paypendingnum, #for now
1947       'email'          => $email,
1948       %content, #after
1949     );
1950
1951     $cust_pay_pending->status('pending');
1952     my $cpp_pending_err = $cust_pay_pending->replace;
1953     return $cpp_pending_err if $cpp_pending_err;
1954
1955     warn Dumper($transaction) if $DEBUG > 2;
1956
1957     unless ( $BOP_TESTING ) {
1958       $transaction->test_transaction(1)
1959         if $conf->exists('business-onlinepayment-test_transaction');
1960       $transaction->submit();
1961     } else {
1962       if ( $BOP_TESTING_SUCCESS ) {
1963         $transaction->is_success(1);
1964         $transaction->authorization('fake auth');
1965       } else {
1966         $transaction->is_success(0);
1967         $transaction->error_message('fake failure');
1968       }
1969     }
1970
1971     if ( $transaction->is_success() ) {
1972
1973       $cust_pay_pending->status('authorized');
1974       my $cpp_authorized_err = $cust_pay_pending->replace;
1975       return $cpp_authorized_err if $cpp_authorized_err;
1976
1977       my $auth = $transaction->authorization;
1978       my $ordernum = $transaction->can('order_number')
1979                      ? $transaction->order_number
1980                      : '';
1981
1982       my $reverse = new $namespace( $payment_gateway->gateway_module,
1983                                     _bop_options(\%options),
1984                                   );
1985
1986       $reverse->content( 'action'        => 'Reverse Authorization',
1987                          _bop_auth(\%options),          
1988
1989                          # B:OP
1990                          'amount'        => '1.00',
1991                          'authorization' => $transaction->authorization,
1992                          'order_number'  => $ordernum,
1993
1994                          # vsecure
1995                          'result_code'   => $transaction->result_code,
1996                          'txn_date'      => $transaction->txn_date,
1997
1998                          %content,
1999                        );
2000       $reverse->test_transaction(1)
2001         if $conf->exists('business-onlinepayment-test_transaction');
2002       $reverse->submit();
2003
2004       if ( $reverse->is_success ) {
2005
2006         $cust_pay_pending->status('done');
2007         $cust_pay_pending->statustext('reversed');
2008         my $cpp_reversed_err = $cust_pay_pending->replace;
2009         return $cpp_reversed_err if $cpp_reversed_err;
2010
2011       } else {
2012
2013         my $e = "Authorization successful but reversal failed, custnum #".
2014                 $self->custnum. ': '.  $reverse->result_code.
2015                 ": ". $reverse->error_message;
2016         $log->warning($e);
2017         warn $e;
2018         return $e;
2019
2020       }
2021
2022       ### Address Verification ###
2023       #
2024       # Single-letter codes vary by cardtype.
2025       #
2026       # Erring on the side of accepting cards if avs is not available,
2027       # only rejecting if avs occurred and there's been an explicit mismatch
2028       #
2029       # Charts below taken from vSecure documentation,
2030       #    shows codes for Amex/Dscv/MC/Visa
2031       #
2032       # ACCEPTABLE AVS RESPONSES:
2033       # Both Address and 5-digit postal code match Y A Y Y
2034       # Both address and 9-digit postal code match Y A X Y
2035       # United Kingdom â€“ Address and postal code match _ _ _ F
2036       # International transaction â€“ Address and postal code match _ _ _ D/M
2037       #
2038       # ACCEPTABLE, BUT ISSUE A WARNING:
2039       # Ineligible transaction; or message contains a content error _ _ _ E
2040       # System unavailable; retry R U R R
2041       # Information unavailable U W U U
2042       # Issuer does not support AVS S U S S
2043       # AVS is not applicable _ _ _ S
2044       # Incompatible formats â€“ Not verified _ _ _ C
2045       # Incompatible formats â€“ Address not verified; postal code matches _ _ _ P
2046       # International transaction â€“ address not verified _ G _ G/I
2047       #
2048       # UNACCEPTABLE AVS RESPONSES:
2049       # Only Address matches A Y A A
2050       # Only 5-digit postal code matches Z Z Z Z
2051       # Only 9-digit postal code matches Z Z W W
2052       # Neither address nor postal code matches N N N N
2053
2054       if (my $avscode = uc($transaction->avs_code)) {
2055
2056         # map codes to accept/warn/reject
2057         my $avs = {
2058           'American Express card' => {
2059             'A' => 'r',
2060             'N' => 'r',
2061             'R' => 'w',
2062             'S' => 'w',
2063             'U' => 'w',
2064             'Y' => 'a',
2065             'Z' => 'r',
2066           },
2067           'Discover card' => {
2068             'A' => 'a',
2069             'G' => 'w',
2070             'N' => 'r',
2071             'U' => 'w',
2072             'W' => 'w',
2073             'Y' => 'r',
2074             'Z' => 'r',
2075           },
2076           'MasterCard' => {
2077             'A' => 'r',
2078             'N' => 'r',
2079             'R' => 'w',
2080             'S' => 'w',
2081             'U' => 'w',
2082             'W' => 'r',
2083             'X' => 'a',
2084             'Y' => 'a',
2085             'Z' => 'r',
2086           },
2087           'VISA card' => {
2088             'A' => 'r',
2089             'C' => 'w',
2090             'D' => 'a',
2091             'E' => 'w',
2092             'F' => 'a',
2093             'G' => 'w',
2094             'I' => 'w',
2095             'M' => 'a',
2096             'N' => 'r',
2097             'P' => 'w',
2098             'R' => 'w',
2099             'S' => 'w',
2100             'U' => 'w',
2101             'W' => 'r',
2102             'Y' => 'a',
2103             'Z' => 'r',
2104           },
2105         };
2106         my $cardtype = cardtype($content{card_number});
2107         if ($avs->{$cardtype}) {
2108           my $avsact = $avs->{$cardtype}->{$avscode};
2109           my $warning = '';
2110           if ($avsact eq 'r') {
2111             return "AVS code verification failed, cardtype $cardtype, code $avscode";
2112           } elsif ($avsact eq 'w') {
2113             $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2114           } elsif (!$avsact) {
2115             $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2116           } # else $avsact eq 'a'
2117           if ($warning) {
2118             $log->warning($warning);
2119             warn $warning;
2120           }
2121         } # else $cardtype avs handling not implemented
2122       } # else !$transaction->avs_code
2123
2124     } else { # is not success
2125
2126       # status is 'done' not 'declined', as in _realtime_bop_result
2127       $cust_pay_pending->status('done');
2128       $error = $transaction->error_message || 'Unknown error';
2129       $cust_pay_pending->statustext($error);
2130       # could also record failure_status here,
2131       #   but it's not supported by B::OP::vSecureProcessing...
2132       #   need a B::OP module with (reverse) auth only to test it with
2133       my $cpp_declined_err = $cust_pay_pending->replace;
2134       return $cpp_declined_err if $cpp_declined_err;
2135
2136     }
2137
2138   } # end of IMMEDIATE; we now have our $error and $transaction
2139
2140   ###
2141   # Save the custnum (as part of the main transaction, so it can reference
2142   # the cust_main)
2143   ###
2144
2145   if (!$cust_pay_pending->custnum) {
2146     $cust_pay_pending->set('custnum', $self->custnum);
2147     my $set_custnum_err = $cust_pay_pending->replace;
2148     if ($set_custnum_err) {
2149       $log->error($set_custnum_err);
2150       $error ||= $set_custnum_err;
2151       # but if there was a real verification error also, return that one
2152     }
2153   }
2154
2155   ###
2156   # remove paycvv here?  need to find out if a reversed auth
2157   #   counts as an initial transaction for paycvv retention requirements
2158   ###
2159
2160   ###
2161   # Tokenize
2162   ###
2163
2164   # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2165   #   if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2166   if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2167     $cust_pay_pending->payinfo($card_token);
2168     my $cpp_token_err = $cust_pay_pending->replace;
2169     #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2170     return $cpp_token_err if $cpp_token_err;
2171     #important that we not replace cust_payby here,
2172     #because cust_payby->replace uses realtime_verify_bop!
2173   }
2174
2175   ###
2176   # result handling
2177   ###
2178
2179   # $error contains the transaction error_message, if is_success was false.
2180  
2181   return $error;
2182
2183 }
2184
2185 =item realtime_tokenize [ OPTION => VALUE ... ]
2186
2187 If possible and necessary, runs a tokenize transaction.
2188 In order to be possible, a credit card cust_payby record
2189 must be passed and a Business::OnlinePayment gateway capable
2190 of Tokenize transactions must be configured for this user.
2191 Is only necessary if payinfo is not yet tokenized.
2192
2193 Returns the empty string if the authorization was sucessful
2194 or was not possible/necessary (thus allowing this to be safely called with
2195 non-tokenizable records/gateways, without having to perform separate tests),
2196 or an error message otherwise.
2197
2198 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2199 Object will be tokenized if possible, but that change will not be
2200 updated in database (must be inserted/replaced afterwards.)
2201
2202 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2203 may be passed.  If options are passed as a hashref, I<payinfo>
2204 will be updated as appropriate in the passed hashref.
2205
2206 Can be run as a class method if option I<payment_gateway> is passed,
2207 but default customer id/name/phone can't be set in that case.  This
2208 is really only intended for tokenizing old records on upgrade.
2209
2210 =cut
2211
2212 # careful--might be run as a class method
2213 sub realtime_tokenize {
2214   my $self = shift;
2215
2216   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2217   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2218
2219   my %options = ();
2220   my $outoptions; #for returning cust_payby/payinfo
2221   if (ref($_[0]) eq 'HASH') {
2222     %options = %{$_[0]};
2223     $outoptions = $_[0];
2224   } else {
2225     %options = @_;
2226     $outoptions = \%options;
2227   }
2228
2229   # set fields from passed cust_payby
2230   _bop_cust_payby_options(\%options);
2231   return '' unless $options{method} eq 'CC';
2232   return '' if $self->tokenized($options{payinfo}); #already tokenized
2233
2234   # check for banned credit card/ACH
2235   my $ban = FS::banned_pay->ban_search(
2236     'payby'   => $bop_method2payby{'CC'},
2237     'payinfo' => $options{payinfo},
2238   );
2239   return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2240
2241   ###
2242   # select a gateway
2243   ###
2244
2245   $options{'nofatal'} = 1;
2246   my $payment_gateway =  $self->_payment_gateway( \%options );
2247   return '' unless $payment_gateway;
2248   my $namespace = $payment_gateway->gateway_namespace;
2249   return '' unless $namespace eq 'Business::OnlinePayment';
2250
2251   eval "use $namespace";  
2252   return $@ if $@;
2253
2254   ###
2255   # check for tokenize ability
2256   ###
2257
2258   my $transaction = new $namespace( $payment_gateway->gateway_module,
2259                                     _bop_options(\%options),
2260                                   );
2261
2262   return '' unless $transaction->can('info');
2263
2264   my %supported_actions = $transaction->info('supported_actions');
2265   return '' unless $supported_actions{'CC'}
2266                 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2267
2268   ###
2269   # massage data
2270   ###
2271
2272   ### Currently, cardfortress only keys in on card number and exp date.
2273   ### We pass everything we'd pass to a normal transaction,
2274   ### for ease of current and future development,
2275   ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2276
2277   my $bop_content = $self->_bop_content(\%options);
2278   return $bop_content unless ref($bop_content);
2279
2280   my $paydate = '';
2281   my %content = ();
2282
2283   $content{card_number} = $options{payinfo};
2284   $paydate = $options{'paydate'};
2285   $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2286   $content{expiration} = "$2/$1";
2287
2288   $content{cvv2} = $options{'paycvv'}
2289     if length($options{'paycvv'});
2290
2291   my $paystart_month = $options{'paystart_month'};
2292   my $paystart_year  = $options{'paystart_year'};
2293
2294   $content{card_start} = "$paystart_month/$paystart_year"
2295     if $paystart_month && $paystart_year;
2296
2297   my $payissue       = $options{'payissue'};
2298   $content{issue_number} = $payissue if $payissue;
2299
2300   $content{customer_id} = $self->custnum
2301     if ref($self);
2302
2303   ###
2304   # run transaction
2305   ###
2306
2307   my $error;
2308
2309   # no cust_pay_pending---this is not a financial transaction
2310
2311   $transaction->content(
2312     'type'           => 'CC',
2313     _bop_auth(\%options),          
2314     'action'         => 'Tokenize',
2315     'description'    => $options{'description'},
2316     %$bop_content,
2317     %content, #after
2318   );
2319
2320   # no $BOP_TESTING handling for this
2321   $transaction->test_transaction(1)
2322     if $conf->exists('business-onlinepayment-test_transaction');
2323   $transaction->submit();
2324
2325   if ( $transaction->card_token() ) { # no is_success flag
2326
2327     # realtime_tokenize should not clear paycvv at this time.  it might be
2328     # needed for the first transaction, and a tokenize isn't actually a
2329     # transaction that hits the gateway.  at some point in the future, card
2330     # fortress should take on the "store paycvv until first transaction"
2331     # functionality and we should fix this in freeside, but i that's a bigger
2332     # project for another time.
2333
2334     #important that we not replace cust_payby here, 
2335     #because cust_payby->replace uses realtime_tokenize!
2336     $self->_tokenize_card($transaction,$outoptions);
2337
2338   } else {
2339
2340     $error = $transaction->error_message || 'Unknown error when tokenizing card';
2341
2342   }
2343
2344   return $error;
2345
2346 }
2347
2348
2349 =item tokenized PAYINFO
2350
2351 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2352
2353 PAYINFO is required.
2354
2355 Can be run as class or object method, never loads from object.
2356
2357 =cut
2358
2359 sub tokenized {
2360   my $this = shift;
2361   my $payinfo = shift;
2362   FS::cust_pay->tokenized($payinfo);
2363 }
2364
2365 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2366
2367 NOT A METHOD.  Acts on all customers.  Placed here because it makes
2368 use of module-internal methods, and to keep everything that uses
2369 Billing::OnlinePayment all in one place.
2370
2371 Tokenizes all tokenizable card numbers from payinfo in cust_payby and 
2372 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2373
2374 If the I<queue> flag is set, newly tokenized records will be immediately
2375 committed, regardless of AutoCommit, so as to release the mutex on the record.
2376
2377 If all configured gateways have the ability to tokenize, detection of an 
2378 untokenizable record will cause a fatal error.  However, if the I<queue> flag 
2379 is set, this will instead cause a critical error to be recorded in the log, 
2380 and any other tokenizable records will still be committed.
2381
2382 If the I<daily> flag is also set, detection of existing untokenized records will 
2383 record an info message in the system log (because they should have never appeared 
2384 in the first place.)  Tokenization will still be attempted.
2385
2386 If any configured gateways do NOT have the ability to tokenize, or if a
2387 default gateway is not configured, then untokenized records are not considered 
2388 a threat, and no critical errors will be generated in the log.
2389
2390 =cut
2391
2392 sub token_check {
2393   #acts on all customers
2394   my %opt = @_;
2395   my $debug = !$opt{'quiet'} || $DEBUG;
2396   my $hascritical = 0;
2397
2398   warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2399
2400   # force some explicitness when invoking this method
2401   die "token_check must run with queue flag if run with daily flag"
2402     if $opt{'daily'} && !$opt{'queue'};
2403
2404   my $conf = FS::Conf->new;
2405
2406   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2407
2408   my $cache = {}; #cache for module info
2409
2410   # look for a gateway that can and can't tokenize
2411   my $require_tokenized = 1;
2412   my $someone_tokenizing = 0;
2413   foreach my $gateway (
2414     FS::payment_gateway->all_gateways(
2415       'method'  => 'CC',
2416       'conf'    => $conf,
2417       'nofatal' => 1,
2418     )
2419   ) {
2420     if (!$gateway) {
2421       # no default gateway, no promise to tokenize
2422       # can just load other gateways as-needeed below
2423       $require_tokenized = 0;
2424       last if $someone_tokenizing;
2425       next;
2426     }
2427     my $info = _token_check_gateway_info($cache,$gateway);
2428     die $info unless ref($info); # means it's an error message
2429     if ($info->{'can_tokenize'}) {
2430       $someone_tokenizing = 1;
2431     } else {
2432       # a configured gateway can't tokenize, that's all we need to know right now
2433       # can just load other gateways as-needeed below
2434       $require_tokenized = 0;
2435       last if $someone_tokenizing;
2436     }
2437   }
2438
2439   unless ($someone_tokenizing) { #no need to check, if no one can tokenize
2440     warn "no gateways tokenize\n" if $debug;
2441     return;
2442   }
2443
2444   warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2445
2446   # upgrade does not call this with autocommit turned on,
2447   # and autocommit will be ignored if opt queue is set,
2448   # but might as well be thorough...
2449   my $oldAutoCommit = $FS::UID::AutoCommit;
2450   local $FS::UID::AutoCommit = 0;
2451   my $dbh = dbh;
2452
2453   # for retrieving data in chunks
2454   my $step = 500;
2455   my $offset = 0;
2456
2457   ### Tokenize cust_payby
2458
2459   my @recnums;
2460
2461 CUSTLOOP:
2462   while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2463     my $cust_main = FS::cust_main->by_key($custnum);
2464     my $payment_gateway;
2465     foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
2466
2467       # see if it's already tokenized
2468       if ($cust_payby->tokenized) {
2469         warn "cust_payby ".$cust_payby->get($cust_payby->primary_key)." already tokenized" if $debug;
2470         next;
2471       }
2472
2473       if ($require_tokenized && $opt{'daily'}) {
2474         $log->info("Untokenized card number detected in cust_payby ".$cust_payby->custpaybynum. '; tokenizing');
2475         $dbh->commit or die $dbh->errstr; # commit log message
2476       }
2477
2478       # only load gateway if we need to, and only need to load it once
2479       $payment_gateway ||= $cust_main->_payment_gateway({
2480         'method'  => 'CC',
2481         'conf'    => $conf,
2482         'nofatal' => 1, # handle lack of gateway smoothly below
2483       });
2484       unless ($payment_gateway) {
2485         # no reason to have untokenized card numbers saved if no gateway,
2486         #   but only a problem if we expected everyone to tokenize card numbers
2487         unless ($require_tokenized) {
2488           warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2489           next CUSTLOOP; # can skip rest of customer
2490         }
2491         my $error = "No gateway found for custnum ".$cust_main->custnum;
2492         if ($opt{'queue'}) {
2493           $hascritical = 1;
2494           $log->critical($error);
2495           $dbh->commit or die $dbh->errstr; # commit error message
2496           next; # not next CUSTLOOP, want to record error for every cust_payby
2497         }
2498         $dbh->rollback if $oldAutoCommit;
2499         die $error;
2500       }
2501
2502       my $info = _token_check_gateway_info($cache,$payment_gateway);
2503       unless (ref($info)) {
2504         # only throws error if Business::OnlinePayment won't load,
2505         #   which is just cause to abort this whole process, even if queue
2506         $dbh->rollback if $oldAutoCommit;
2507         die $info; # error message
2508       }
2509       # no fail here--a configured gateway can't tokenize, so be it
2510       unless ($info->{'can_tokenize'}) {
2511         warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2512         next;
2513       }
2514
2515       # time to tokenize
2516       $cust_payby = $cust_payby->select_for_update;
2517       my %tokenopts = (
2518         'payment_gateway' => $payment_gateway,
2519         'cust_payby'      => $cust_payby,
2520       );
2521       my $error = $cust_main->realtime_tokenize(\%tokenopts);
2522       if ($cust_payby->tokenized) { # implies no error
2523         $error = $cust_payby->replace;
2524       } else {
2525         $error ||= 'Unknown error';
2526       }
2527       if ($error) {
2528         $error = "Error tokenizing cust_payby ".$cust_payby->custpaybynum.": ".$error;
2529         if ($opt{'queue'}) {
2530           $hascritical = 1;
2531           $log->critical($error);
2532           $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2533           next; # not next CUSTLOOP, want to record error for every cust_payby
2534         }
2535         $dbh->rollback if $oldAutoCommit;
2536         die $error;
2537       }
2538       $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2539       warn "TOKENIZED cust_payby ".$cust_payby->get($cust_payby->primary_key) if $debug;
2540     }
2541     warn "cust_payby upgraded for custnum ".$cust_main->custnum if $debug;
2542
2543   }
2544
2545   ### Tokenize/mask transaction tables
2546
2547   # allow tokenization of closed cust_pay/cust_refund records
2548   local $FS::payinfo_Mixin::allow_closed_replace = 1;
2549
2550   # grep assistance:
2551   #   $cust_pay_pending->replace, $cust_pay->replace, $cust_pay_void->replace, $cust_refund->replace all run here
2552   foreach my $table ( qw(cust_pay_pending cust_pay cust_pay_void cust_refund) ) {
2553     warn "Checking $table" if $debug;
2554
2555     # FS::Cursor does not seem to work over multiple commits (gives cursor not found errors)
2556     # loading only record ids, then loading individual records one at a time
2557     my $tclass = 'FS::'.$table;
2558     $offset = 0;
2559     @recnums = ();
2560
2561     while (my $recnum = _token_check_next_recnum($dbh,$table,$step,\$offset,\@recnums)) {
2562       my $record = $tclass->by_key($recnum);
2563       unless ($record->payby eq 'CARD') {
2564         warn "Skipping non-card record for $table ".$record->get($record->primary_key) if $debug;
2565         next;
2566       }
2567       if (FS::cust_main::Billing_Realtime->tokenized($record->payinfo)) {
2568         warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2569         next;
2570       }
2571       if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2572         warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2573         next;
2574       }
2575       if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2576         warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2577         next;
2578       }
2579
2580       if ($require_tokenized && $opt{'daily'}) {
2581         $log->info("Untokenized card number detected in $table ".$record->get($record->primary_key). ';tokenizing');
2582         $dbh->commit or die $dbh->errstr; # commit log message
2583       }
2584
2585       my $cust_main = $record->cust_main;
2586       if (!$cust_main) {
2587         # might happen for cust_pay_pending from failed verify records,
2588         #   in which case we attempt tokenization without cust_main
2589         # everything else should absolutely have a cust_main
2590         if ($table eq 'cust_pay_pending' and !$record->custnum ) {
2591           # override the usual safety check and allow the record to be
2592           # updated even without a custnum.
2593           $record->set('custnum_pending', 1);
2594         } else {
2595           my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2596           if ($opt{'queue'}) {
2597             $hascritical = 1;
2598             $log->critical($error);
2599             $dbh->commit or die $dbh->errstr; # commit log message
2600             next;
2601           }
2602           $dbh->rollback if $oldAutoCommit;
2603           die $error;
2604         }
2605       }
2606
2607       my $gateway;
2608
2609       # use the gatewaynum specified by the record if possible
2610       $gateway = FS::payment_gateway->by_key_with_namespace(
2611         'gatewaynum' => $record->gatewaynum,
2612       ) if $record->gateway;
2613
2614       # otherwise use the cust agent gateway if possible (which realtime_refund_bop would do)
2615       # otherwise just use default gateway
2616       unless ($gateway) {
2617
2618         $gateway = $cust_main 
2619                  ? $cust_main->agent->payment_gateway
2620                  : FS::payment_gateway->default_gateway;
2621
2622         # check for processor mismatch
2623         unless ($table eq 'cust_pay_pending') { # has no processor table
2624           if (my $processor = $record->processor) {
2625
2626             my $conf_processor = $gateway->gateway_module;
2627             my %bop_options = $gateway->gatewaynum
2628                             ? $gateway->options
2629                             : @{ $gateway->get('options') };
2630
2631             # this is the same standard used by realtime_refund_bop
2632             unless (
2633               ($processor eq $conf_processor) ||
2634               (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}))
2635             ) {
2636
2637               # processors don't match, so refund already cannot be run on this object,
2638               # regardless of what we do now...
2639               # but unless we gotta tokenize everything, just leave well enough alone
2640               unless ($require_tokenized) {
2641                 warn "Skipping mismatched processor for $table ".$record->get($record->primary_key) if $debug;
2642                 next;
2643               }
2644               ### no error--we'll tokenize using the new gateway, just to remove stored payinfo,
2645               ### because refunds are already impossible for this record, anyway
2646
2647             } # end processor mismatch
2648
2649           } # end record has processor
2650         } # end not cust_pay_pending
2651
2652       }
2653
2654       # means no default gateway, no promise to tokenize, can skip
2655       unless ($gateway) {
2656         warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2657         next;
2658       }
2659
2660       my $info = _token_check_gateway_info($cache,$gateway);
2661       unless (ref($info)) {
2662         # only throws error if Business::OnlinePayment won't load,
2663         #   which is just cause to abort this whole process, even if queue
2664         $dbh->rollback if $oldAutoCommit;
2665         die $info; # error message
2666       }
2667
2668       # a configured gateway can't tokenize, move along
2669       unless ($info->{'can_tokenize'}) {
2670         warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
2671         next;
2672       }
2673
2674       warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug && !$cust_main;
2675
2676       # if we got this far, time to mutex
2677       $record->select_for_update;
2678
2679       # no clear record of name/address/etc used for transaction,
2680       # but will load name/phone/id from customer if run as an object method,
2681       # so we try that if we can
2682       my %tokenopts = (
2683         'payment_gateway' => $gateway,
2684         'method'          => 'CC',
2685         'payinfo'         => $record->payinfo,
2686         'paydate'         => $record->paydate,
2687       );
2688       my $error = $cust_main
2689                 ? $cust_main->realtime_tokenize(\%tokenopts)
2690                 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2691       if (FS::cust_main::Billing_Realtime->tokenized($tokenopts{'payinfo'})) { # implies no error
2692         $record->payinfo($tokenopts{'payinfo'});
2693         $error = $record->replace;
2694       } else {
2695         $error ||= 'Unknown error';
2696       }
2697       if ($error) {
2698         $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2699         if ($opt{'queue'}) {
2700           $hascritical = 1;
2701           $log->critical($error);
2702           $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2703           next;
2704         }
2705         $dbh->rollback if $oldAutoCommit;
2706         die $error;
2707       }
2708       $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2709       warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2710
2711     } # end record loop
2712   } # end table loop
2713
2714   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2715
2716   return $hascritical ? 'Critical errors occurred on some records, see system log' : '';
2717 }
2718
2719 # not a method!
2720 sub _token_check_next_recnum {
2721   my ($dbh,$table,$step,$offset,$recnums) = @_;
2722   my $recnum = shift @$recnums;
2723   return $recnum if $recnum;
2724   my $tclass = 'FS::'.$table;
2725   my $sth = $dbh->prepare(
2726     'SELECT '.$tclass->primary_key.
2727     ' FROM '.$table.
2728     " WHERE ( is_tokenized IS NULL OR is_tokenized = '' ) ".
2729     ' ORDER BY '.$tclass->primary_key.
2730     ' LIMIT '.$step.
2731     ' OFFSET '.$$offset
2732   ) or die $dbh->errstr;
2733   $sth->execute() or die $sth->errstr;
2734   my @recnums;
2735   while (my $rec = $sth->fetchrow_hashref) {
2736     push @$recnums, $rec->{$tclass->primary_key};
2737   }
2738   $sth->finish();
2739   $$offset += $step;
2740   return shift @$recnums;
2741 }
2742
2743 # not a method!
2744 sub _token_check_gateway_info {
2745   my ($cache,$payment_gateway) = @_;
2746
2747   return $cache->{$payment_gateway->gateway_module}
2748     if $cache->{$payment_gateway->gateway_module};
2749
2750   my $info = {};
2751   $cache->{$payment_gateway->gateway_module} = $info;
2752
2753   my $namespace = $payment_gateway->gateway_namespace;
2754   return $info unless $namespace eq 'Business::OnlinePayment';
2755   $info->{'is_bop'} = 1;
2756
2757   # only need to load this once,
2758   # don't want to load if nothing is_bop
2759   unless ($cache->{'Business::OnlinePayment'}) {
2760     eval "use $namespace";  
2761     return "Error initializing Business:OnlinePayment: ".$@ if $@;
2762     $cache->{'Business::OnlinePayment'} = 1;
2763   }
2764
2765   my $transaction = new $namespace( $payment_gateway->gateway_module,
2766                                     _bop_options({ 'payment_gateway' => $payment_gateway }),
2767                                   );
2768
2769   return $info unless $transaction->can('info');
2770   $info->{'can_info'} = 1;
2771
2772   my %supported_actions = $transaction->info('supported_actions');
2773   $info->{'can_tokenize'} = 1
2774     if $supported_actions{'CC'}
2775       && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2776
2777   # not using this any more, but for future reference...
2778   $info->{'void_requires_card'} = 1
2779     if $transaction->info('CC_void_requires_card');
2780
2781   return $info;
2782 }
2783
2784 =back
2785
2786 =head1 BUGS
2787
2788 =head1 SEE ALSO
2789
2790 L<FS::cust_main>, L<FS::cust_main::Billing>
2791
2792 =cut
2793
2794 1;