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