store credit card type in cust_payby and transaction records, #71291, schema support
[freeside.git] / FS / FS / cust_payby.pm
1 package FS::cust_payby;
2 use base qw( FS::payinfo_Mixin FS::cust_main_Mixin FS::Record );
3
4 use strict;
5 use Scalar::Util qw( blessed );
6 use Digest::SHA qw( sha512_base64 );
7 use Business::CreditCard qw( validate cardtype );
8 use FS::UID qw( dbh );
9 use FS::Msgcat qw( gettext );
10 use FS::Misc qw( card_types );
11 use FS::Record; #qw( qsearch qsearchs );
12 use FS::payby;
13 use FS::cust_main;
14 use FS::banned_pay;
15
16 our @encrypted_fields = ('payinfo', 'paycvv');
17 sub nohistory_fields { ('payinfo', 'paycvv'); }
18
19 our $ignore_expired_card = 0;
20 our $ignore_banned_card = 0;
21 our $ignore_invalid_card = 0;
22 our $ignore_cardtype = 0;
23
24 our $conf;
25 install_callback FS::UID sub { 
26   $conf = new FS::Conf;
27   #yes, need it for stuff below (prolly should be cached)
28   $ignore_invalid_card = $conf->exists('allow_invalid_cards');
29 };
30
31 =head1 NAME
32
33 FS::cust_payby - Object methods for cust_payby records
34
35 =head1 SYNOPSIS
36
37   use FS::cust_payby;
38
39   $record = new FS::cust_payby \%hash;
40   $record = new FS::cust_payby { 'column' => 'value' };
41
42   $error = $record->insert;
43
44   $error = $new_record->replace($old_record);
45
46   $error = $record->delete;
47
48   $error = $record->check;
49
50 =head1 DESCRIPTION
51
52 An FS::cust_payby object represents customer stored payment information.
53 FS::cust_payby inherits from FS::Record.  The following fields are currently
54 supported:
55
56 =over 4
57
58 =item custpaybynum
59
60 primary key
61
62 =item custnum
63
64 custnum
65
66 =item weight
67
68 weight
69
70 =item payby
71
72 payby
73
74 =item payinfo
75
76 payinfo
77
78 =item paycvv
79
80 paycvv
81
82 =item paymask
83
84 paymask
85
86 =item paydate
87
88 paydate
89
90 =item paystart_month
91
92 paystart_month
93
94 =item paystart_year
95
96 paystart_year
97
98 =item payissue
99
100 payissue
101
102 =item payname
103
104 payname
105
106 =item paystate
107
108 paystate
109
110 =item paytype
111
112 paytype
113
114 =item payip
115
116 payip
117
118 =item cardtype
119
120 The credit card type (deduced from the card number).
121
122 =back
123
124 =head1 METHODS
125
126 =over 4
127
128 =item new HASHREF
129
130 Creates a new record.  To add the record to the database, see L<"insert">.
131
132 Note that this stores the hash reference, not a distinct copy of the hash it
133 points to.  You can ask the object for a copy with the I<hash> method.
134
135 =cut
136
137 # the new method can be inherited from FS::Record, if a table method is defined
138
139 sub table { 'cust_payby'; }
140
141 =item insert
142
143 Adds this record to the database.  If there is an error, returns the error,
144 otherwise returns false.
145
146 =cut
147
148 sub insert {
149   my $self = shift;
150
151   local $SIG{HUP} = 'IGNORE';
152   local $SIG{INT} = 'IGNORE';
153   local $SIG{QUIT} = 'IGNORE';
154   local $SIG{TERM} = 'IGNORE';
155   local $SIG{TSTP} = 'IGNORE';
156   local $SIG{PIPE} = 'IGNORE';
157
158   my $oldAutoCommit = $FS::UID::AutoCommit;
159   local $FS::UID::AutoCommit = 0;
160   my $dbh = dbh;
161
162   my $error =  $self->check_payinfo_cardtype
163             || $self->SUPER::insert;
164   if ( $error ) {
165     $dbh->rollback if $oldAutoCommit;
166     return $error;
167   }
168
169   if ( $self->payby =~ /^(CARD|CHEK)$/ ) {
170     # new auto card/check info, want to retry realtime_ invoice events
171     #  (new customer?  that's okay, they won't have any)
172     my $error = $self->cust_main->retry_realtime;
173     if ( $error ) {
174       $dbh->rollback if $oldAutoCommit;
175       return $error;
176     }
177   }
178
179   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
180   '';
181
182 }
183
184 =item delete
185
186 Delete this record from the database.
187
188 =item replace OLD_RECORD
189
190 Replaces the OLD_RECORD with this one in the database.  If there is an error,
191 returns the error, otherwise returns false.
192
193 =cut
194
195 sub replace {
196   my $self = shift;
197
198   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
199               ? shift
200               : $self->replace_old;
201
202   if ( $self->payby =~ /^(CARD|DCRD)$/
203        && (    $self->payinfo =~ /xx/
204             || $self->payinfo =~ /^\s*N\/A\s+\(tokenized\)\s*$/
205           )
206      )
207   {
208
209     $self->payinfo($old->payinfo);
210
211   } elsif ( $self->payby =~ /^(CHEK|DCHK)$/ && $self->payinfo =~ /xx/ ) {
212     #fix for #3085 "edit of customer's routing code only surprisingly causes
213     #nothing to happen...
214     # this probably won't do the right thing when we don't have the
215     # public key (can't actually get the real $old->payinfo)
216     my($new_account, $new_aba) = split('@', $self->payinfo);
217     my($old_account, $old_aba) = split('@', $old->payinfo);
218     $new_account = $old_account if $new_account =~ /xx/;
219     $new_aba     = $old_aba     if $new_aba     =~ /xx/;
220     $self->payinfo($new_account.'@'.$new_aba);
221   }
222
223   # only unmask paycvv if payinfo stayed the same
224   if ( $self->payby =~ /^(CARD|DCRD)$/ and $self->paycvv =~ /^\s*[\*x]+\s*$/ ) {
225     if ( $old->payinfo eq $self->payinfo
226          && $old->paymask eq $self->paymask
227     ) {
228       $self->paycvv($old->paycvv);
229     } else {
230       $self->paycvv('');
231     }
232   }
233
234   local($ignore_expired_card) = 1
235     if $old->payby  =~ /^(CARD|DCRD)$/
236     && $self->payby =~ /^(CARD|DCRD)$/
237     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
238
239   local($ignore_banned_card) = 1
240     if (    $old->payby  =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
241          || $old->payby  =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
242     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
243
244   if (    $self->payby =~ /^(CARD|DCRD)$/
245        && $old->payinfo ne $self->payinfo
246        && $old->paymask ne $self->paymask )
247   {
248     my $error = $self->check_payinfo_cardtype;
249     return $error if $error;
250
251     if ( $conf->exists('business-onlinepayment-verification') ) {
252       $error = $self->verify;
253       return $error if $error;
254     }
255   }
256
257   local $SIG{HUP} = 'IGNORE';
258   local $SIG{INT} = 'IGNORE';
259   local $SIG{QUIT} = 'IGNORE';
260   local $SIG{TERM} = 'IGNORE';
261   local $SIG{TSTP} = 'IGNORE';
262   local $SIG{PIPE} = 'IGNORE';
263
264   my $oldAutoCommit = $FS::UID::AutoCommit;
265   local $FS::UID::AutoCommit = 0;
266   my $dbh = dbh;
267
268   my $error = $self->SUPER::replace($old);
269   if ( $error ) {
270     $dbh->rollback if $oldAutoCommit;
271     return $error;
272   }
273
274   if ( $self->payby =~ /^(CARD|CHEK)$/
275        && ( ( $self->get('payinfo') ne $old->get('payinfo')
276               && $self->get('payinfo') !~ /^99\d{14}$/ 
277             )
278             || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
279           )
280      )
281   {
282
283     # card/check/lec info has changed, want to retry realtime_ invoice events
284     my $error = $self->cust_main->retry_realtime;
285     if ( $error ) {
286       $dbh->rollback if $oldAutoCommit;
287       return $error;
288     }
289   }
290
291   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
292   '';
293
294 }
295
296 =item check
297
298 Checks all fields to make sure this is a valid record.  If there is
299 an error, returns the error, otherwise returns false.  Called by the insert
300 and replace methods.
301
302 =cut
303
304 sub check {
305   my $self = shift;
306
307   my $error = 
308     $self->ut_numbern('custpaybynum')
309     || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
310     || $self->ut_numbern('weight')
311     #encrypted #|| $self->ut_textn('payinfo')
312     #encrypted #|| $self->ut_textn('paycvv')
313 #    || $self->ut_textn('paymask') #XXX something
314     #later #|| $self->ut_textn('paydate')
315     || $self->ut_numbern('paystart_month')
316     || $self->ut_numbern('paystart_year')
317     || $self->ut_numbern('payissue')
318 #    || $self->ut_textn('payname') #XXX something
319     || $self->ut_alphan('paystate')
320     || $self->ut_textn('paytype')
321     || $self->ut_ipn('payip')
322   ;
323   return $error if $error;
324
325   ### from cust_main
326
327   FS::payby->can_payby($self->table, $self->payby)
328     or return "Illegal payby: ". $self->payby;
329
330   # If it is encrypted and the private key is not availaible then we can't
331   # check the credit card.
332   my $check_payinfo = ! $self->is_encrypted($self->payinfo);
333
334   # Need some kind of global flag to accept invalid cards, for testing
335   # on scrubbed data.
336   #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
337
338   # In this block: detect card type; reject credit card / account numbers that
339   # are impossible or banned; reject other payment features (date, CVV length)
340   # that are inappropriate for the card type.
341   # However, if the payinfo is encrypted then just detect card type and assume
342   # the other checks were already done.
343
344   if ( !$ignore_invalid_card && 
345     $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
346
347     my $payinfo = $self->payinfo;
348     $payinfo =~ s/\D//g;
349     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
350       or return gettext('invalid_card'); #. ": ". $self->payinfo;
351     $payinfo = $1;
352     $self->payinfo($payinfo);
353     validate($payinfo)
354       or return gettext('invalid_card'); # . ": ". $self->payinfo;
355
356     my $cardtype = cardtype($payinfo);
357     $self->set('cardtype', $cardtype);
358     return gettext('unknown_card_type')
359       if $self->payinfo !~ /^99\d{14}$/ #token
360       && $cardtype eq "Unknown";
361
362     unless ( $ignore_banned_card ) {
363       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
364       if ( $ban ) {
365         if ( $ban->bantype eq 'warn' ) {
366           #or others depending on value of $ban->reason ?
367           return '_duplicate_card'.
368                  ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
369                  ' until '.         time2str('%a %h %o at %r', $ban->_end_date).
370                  ' (ban# '. $ban->bannum. ')'
371             unless $self->override_ban_warn;
372         } else {
373           return 'Banned credit card: banned on '.
374                  time2str('%a %h %o at %r', $ban->_date).
375                  ' by '. $ban->otaker.
376                  ' (ban# '. $ban->bannum. ')';
377         }
378       }
379     }
380
381     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
382       if ( $cardtype eq 'American Express card' ) {
383         $self->paycvv =~ /^(\d{4})$/
384           or return "CVV2 (CID) for American Express cards is four digits.";
385         $self->paycvv($1);
386       } else {
387         $self->paycvv =~ /^(\d{3})$/
388           or return "CVV2 (CVC2/CID) is three digits.";
389         $self->paycvv($1);
390       }
391     } else {
392       $self->paycvv('');
393     }
394
395     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
396
397       return "Start date or issue number is required for $cardtype cards"
398         unless $self->paystart_month && $self->paystart_year or $self->payissue;
399
400       return "Start month must be between 1 and 12"
401         if $self->paystart_month
402            and $self->paystart_month < 1 || $self->paystart_month > 12;
403
404       return "Start year must be 1990 or later"
405         if $self->paystart_year
406            and $self->paystart_year < 1990;
407
408       return "Issue number must be beween 1 and 99"
409         if $self->payissue
410           and $self->payissue < 1 || $self->payissue > 99;
411
412     } else {
413       $self->paystart_month('');
414       $self->paystart_year('');
415       $self->payissue('');
416     }
417
418   } elsif ( !$ignore_invalid_card && 
419     $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
420
421     my $payinfo = $self->payinfo;
422     $payinfo =~ s/[^\d\@\.]//g;
423     if ( $conf->config('echeck-country') eq 'CA' ) {
424       $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
425         or return 'invalid echeck account@branch.bank';
426       $payinfo = "$1\@$2.$3";
427     } elsif ( $conf->config('echeck-country') eq 'US' ) {
428       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
429       $payinfo = "$1\@$2";
430     } else {
431       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
432       $payinfo = "$1\@$2";
433     }
434     $self->payinfo($payinfo);
435     $self->paycvv('');
436
437     unless ( $ignore_banned_card ) {
438       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
439       if ( $ban ) {
440         if ( $ban->bantype eq 'warn' ) {
441           #or others depending on value of $ban->reason ?
442           return '_duplicate_ach' unless $self->override_ban_warn;
443         } else {
444           return 'Banned ACH account: banned on '.
445                  time2str('%a %h %o at %r', $ban->_date).
446                  ' by '. $ban->otaker.
447                  ' (ban# '. $ban->bannum. ')';
448         }
449       }
450     }
451
452   } elsif ( $self->payby =~ /^CARD|DCRD$/ and $self->paymask ) {
453     # either ignoring invalid cards, or we can't decrypt the payinfo, but
454     # try to detect the card type anyway. this never returns failure, so
455     # the contract of $ignore_invalid_cards is maintained.
456     $self->set('cardtype', cardtype($self->paymask));
457   } else {
458     $self->set('cardtype', '');
459   }
460
461 #  } elsif ( $self->payby eq 'PREPAY' ) {
462 #
463 #    my $payinfo = $self->payinfo;
464 #    $payinfo =~ s/\W//g; #anything else would just confuse things
465 #    $self->payinfo($payinfo);
466 #    $error = $self->ut_alpha('payinfo');
467 #    return "Illegal prepayment identifier: ". $self->payinfo if $error;
468 #    return "Unknown prepayment identifier"
469 #      unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
470 #    $self->paycvv('');
471
472   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
473
474     $self->paydate('');
475
476   } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
477
478     # shouldn't payinfo_check do this?
479     # (except we don't ever call payinfo_check from here)
480     return "Expiration date required"
481       if $self->paydate eq '' || $self->paydate eq '-';
482
483     my( $m, $y );
484     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
485       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
486     } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
487       ( $m, $y ) = ( $2, "19$1" );
488     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
489       ( $m, $y ) = ( $3, "20$2" );
490     } else {
491       return "Illegal expiration date: ". $self->paydate;
492     }
493     $m = sprintf('%02d',$m);
494     $self->paydate("$y-$m-01");
495     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
496     return gettext('expired_card')
497       if #XXX !$import
498       #&&
499          !$ignore_expired_card 
500       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
501
502   }
503
504   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
505        ( ! $conf->exists('require_cardname')
506          || $self->payby !~ /^(CARD|DCRD)$/  ) 
507   ) {
508     $self->payname( $self->first. " ". $self->getfield('last') );
509   } else {
510
511     if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
512       $self->payname =~ /^([\w \,\.\-\']*)$/
513         or return gettext('illegal_name'). " payname: ". $self->payname;
514       $self->payname($1);
515     } else {
516       $self->payname =~ /^([\w \,\.\-\'\&]*)$/
517         or return gettext('illegal_name'). " payname: ". $self->payname;
518       $self->payname($1);
519     }
520
521   }
522
523   if ( ! $self->custpaybynum
524        && $conf->exists('business-onlinepayment-verification') ) {
525     $error = $self->verify;
526     return $error if $error;
527   }
528
529   $self->SUPER::check;
530 }
531
532 sub check_payinfo_cardtype {
533   my $self = shift;
534
535   return '' if $ignore_cardtype;
536
537   return '' unless $self->payby =~ /^(CARD|CHEK)$/;
538
539   my $payinfo = $self->payinfo;
540   $payinfo =~ s/\D//g;
541
542   return '' if $payinfo =~ /^99\d{14}$/; #token
543
544   my %bop_card_types = map { $_=>1 } values %{ card_types() };
545   my $cardtype = cardtype($payinfo);
546   $self->set('cardtype', $cardtype);
547
548   return "$cardtype not accepted" unless $bop_card_types{$cardtype};
549
550   '';
551
552 }
553
554 sub _banned_pay_hashref {
555   my $self = shift;
556
557   my %payby2ban = (
558     'CARD' => 'CARD',
559     'DCRD' => 'CARD',
560     'CHEK' => 'CHEK',
561     'DCHK' => 'CHEK'
562   );
563
564   {
565     'payby'   => $payby2ban{$self->payby},
566     'payinfo' => $self->payinfo,
567     #don't ever *search* on reason! #'reason'  =>
568   };
569 }
570
571 sub _new_banned_pay_hashref {
572   my $self = shift;
573   my $hr = $self->_banned_pay_hashref;
574   $hr->{payinfo_hash} = 'SHA512';
575   $hr->{payinfo} = sha512_base64($hr->{payinfo});
576   $hr;
577 }
578
579 =item paydate_mon_year
580
581 Returns a two element list consisting of the paydate month and year.
582
583 =cut
584
585 sub paydate_mon_year {
586   my $self = shift;
587
588   my $date = $self->paydate; # || '12-2037';
589
590   #false laziness w/elements/select-month_year.html
591   if ( $date  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
592     ( $2, $1 );
593   } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
594     ( $1, $3 );
595   } else {
596     warn "unrecognized expiration date format: $date";
597     ( '', '' );
598   }
599
600 }
601
602 =item label
603
604 Returns a one line text label for this payment type.
605
606 =cut
607
608 my %weight = (
609   1 => 'Primary',
610   2 => 'Secondary',
611   3 => 'Tertiary',
612   4 => 'Fourth',
613   5 => 'Fifth',
614   6 => 'Sixth',
615   7 => 'Seventh',
616 );
617
618 sub label {
619   my $self = shift;
620
621   my $name = $self->payby =~ /^(CARD|DCRD)$/
622               && $self->cardtype || FS::payby->shortname($self->payby);
623
624   ( $self->payby =~ /^(CARD|CHEK)$/  ? $weight{$self->weight}. ' automatic '
625                                      : 'Manual '
626   ).
627   "$name: ". $self->paymask.
628   ( $self->payby =~ /^(CARD|DCRD)$/
629       ? ' Exp '. join('/', $self->paydate_mon_year)
630       : ''
631   );
632
633 }
634
635 =item realtime_bop
636
637 =cut
638
639 sub realtime_bop {
640   my( $self, %opt ) = @_;
641
642   $opt{$_} = $self->$_() for qw( payinfo payname paydate );
643
644   if ( $self->locationnum ) {
645     my $cust_location = $self->cust_location;
646     $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
647   }
648
649   $self->cust_main->realtime_bop({
650     'method' => FS::payby->payby2bop( $self->payby ),
651     %opt,
652   });
653
654 }
655
656 =item verify 
657
658 =cut
659
660 sub verify {
661   my $self = shift;
662   return '' unless $self->payby =~ /^(CARD|DCRD)$/;
663
664   my %opt = ();
665
666   # false laziness with check
667   my( $m, $y );
668   if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
669     ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
670   } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
671     ( $m, $y ) = ( $2, "19$1" );
672   } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
673     ( $m, $y ) = ( $3, "20$2" );
674   } else {
675     return "Illegal expiration date: ". $self->paydate;
676   }
677   $m = sprintf('%02d',$m);
678   $opt{paydate} = "$y-$m-01";
679
680   $opt{$_} = $self->$_() for qw( payinfo payname paycvv );
681
682   if ( $self->locationnum ) {
683     my $cust_location = $self->cust_location;
684     $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
685   }
686
687   $self->cust_main->realtime_verify_bop({
688     'method' => FS::payby->payby2bop( $self->payby ),
689     %opt,
690   });
691
692 }
693
694 =item paytypes
695
696 Returns a list of valid values for the paytype field (bank account type for
697 electronic check payment).
698
699 =cut
700
701 sub paytypes {
702   #my $class = shift;
703
704   ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
705 }
706
707 =item cgi_cust_payby_fields
708
709 Returns the field names used in the web interface (including some pseudo-fields).
710
711 =cut
712
713 sub cgi_cust_payby_fields {
714   #my $class = shift;
715   [qw( payby payinfo paydate_month paydate_year paycvv payname weight
716        payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
717 }
718
719 =item cgi_hash_callback HASHREF OLD
720
721 Subroutine (not a class or object method).  Processes a hash reference
722 of web interface contet (transfers the data from pseudo-fields to real fields).
723
724 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
725 payissue and payip.  If the new field is blank but the old is not, the old field 
726 will be preserved.
727
728 =cut
729
730 sub cgi_hash_callback {
731   my $hashref = shift;
732   my $old = shift;
733
734   my %noauto = (
735     'CARD' => 'DCRD',
736     'CHEK' => 'DCHK',
737   );
738   # the payby selector gives the choice of CARD or CHEK (or others, but
739   # those are the ones with auto and on-demand versions). if the user didn't
740   # choose a weight, then they mean DCRD/DCHK.
741   $hashref->{payby} = $noauto{$hashref->{payby}}
742     if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
743
744   if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
745
746     unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
747       %$hashref = ();
748       return;
749     }
750
751     $hashref->{payinfo} = $hashref->{payinfo1}. '@';
752     $hashref->{payinfo} .= $hashref->{payinfo3}.'.' 
753       if $conf->config('echeck-country') eq 'CA';
754     $hashref->{payinfo} .= $hashref->{'payinfo2'};
755
756     $hashref->{payname} = $hashref->{'payname_CHEK'};
757
758   } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
759
760     unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
761       %$hashref = ();
762       return;
763     }
764
765   }
766
767   $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
768
769   if ($old) {
770     foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
771       next if $hashref->{$field};
772       next unless $old->get($field);
773       $hashref->{$field} = $old->get($field);
774     }
775   }
776
777 }
778
779 =item search_sql
780
781 Class method.
782
783 Returns a qsearch hash expression to search for parameters specified in HASHREF.
784 Valid paramters are:
785
786 =over 4
787
788 =item payby
789
790 listref
791
792 =item paydate_year
793
794 =item paydate_month
795
796
797 =back
798
799 =cut
800
801 sub search_sql {
802   my ($class, $params) = @_;
803
804   my @where = ();
805   my $orderby;
806
807   # initialize these to prevent warnings
808   $params = {
809     'paydate_year'  => '',
810     %$params
811   };
812
813   ###
814   # payby
815   ###
816
817   if ( $params->{'payby'} ) {
818
819     my @payby = ref( $params->{'payby'} )
820                   ? @{ $params->{'payby'} }
821                   :  ( $params->{'payby'} );
822
823     @payby = grep /^([A-Z]{4})$/, @payby;
824     my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
825     push @where, "cust_payby.payby $in_payby"
826       if @payby;
827   }
828
829   ###
830   # paydate_year / paydate_month
831   ###
832
833   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
834     my $year = $1;
835     $params->{'paydate_month'} =~ /^(\d\d?)$/
836       or die "paydate_year without paydate_month?";
837     my $month = $1;
838
839     push @where,
840       'cust_payby.paydate IS NOT NULL',
841       "cust_payby.paydate != ''",
842       "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
843 ;
844   }
845   ##
846   # setup queries, subs, etc. for the search
847   ##
848
849   $orderby ||= 'ORDER BY custnum';
850
851   # here is the agent virtualization
852   push @where,
853     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
854
855   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
856
857   my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
858   # always make address fields available in results
859   for my $pre ('bill_', 'ship_') {
860     $addl_from .= 
861       ' LEFT JOIN cust_location AS '.$pre.'location '.
862       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
863   }
864   # always make referral available in results
865   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
866   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
867
868   my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
869
870   my @select = ( 'cust_payby.*',
871                  #'cust_main.custnum',
872                  # there's a good chance that we'll need these
873                  'cust_main.bill_locationnum',
874                  'cust_main.ship_locationnum',
875                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
876                );
877
878   my $select = join(', ', @select);
879
880   my $sql_query = {
881     'table'         => 'cust_payby',
882     'select'        => $select,
883     'addl_from'     => $addl_from,
884     'hashref'       => {},
885     'extra_sql'     => $extra_sql,
886     'order_by'      => $orderby,
887     'count_query'   => $count_query,
888   };
889   $sql_query;
890
891 }
892
893 =back
894
895 =cut
896
897 sub _upgrade_data {
898
899   my $class = shift;
900   local $ignore_banned_card = 1;
901   local $ignore_expired_card = 1;
902   local $ignore_invalid_card = 1;
903   $class->upgrade_set_cardtype;
904
905 }
906
907 =head1 BUGS
908
909 =head1 SEE ALSO
910
911 L<FS::Record>, schema.html from the base documentation.
912
913 =cut
914
915 1;
916