626fc9fe92be2a04641f1a020a8432c08aa4e158
[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 paycardtype
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     } else {
254       $error = $self->tokenize;
255     }
256     return $error if $error;
257
258   }
259
260   local $SIG{HUP} = 'IGNORE';
261   local $SIG{INT} = 'IGNORE';
262   local $SIG{QUIT} = 'IGNORE';
263   local $SIG{TERM} = 'IGNORE';
264   local $SIG{TSTP} = 'IGNORE';
265   local $SIG{PIPE} = 'IGNORE';
266
267   my $oldAutoCommit = $FS::UID::AutoCommit;
268   local $FS::UID::AutoCommit = 0;
269   my $dbh = dbh;
270
271   my $error = $self->SUPER::replace($old);
272   if ( $error ) {
273     $dbh->rollback if $oldAutoCommit;
274     return $error;
275   }
276
277   if ( $self->payby =~ /^(CARD|CHEK)$/
278        && ( ( $self->get('payinfo') ne $old->get('payinfo')
279               && $self->get('payinfo') !~ /^99\d{14}$/ 
280             )
281             || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
282           )
283      )
284   {
285
286     # card/check/lec info has changed, want to retry realtime_ invoice events
287     my $error = $self->cust_main->retry_realtime;
288     if ( $error ) {
289       $dbh->rollback if $oldAutoCommit;
290       return $error;
291     }
292   }
293
294   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
295   '';
296
297 }
298
299 =item check
300
301 Checks all fields to make sure this is a valid record.  If there is
302 an error, returns the error, otherwise returns false.  Called by the insert
303 and replace methods.
304
305 =cut
306
307 sub check {
308   my $self = shift;
309
310   my $error = 
311     $self->ut_numbern('custpaybynum')
312     || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
313     || $self->ut_numbern('weight')
314     #encrypted #|| $self->ut_textn('payinfo')
315     #encrypted #|| $self->ut_textn('paycvv')
316 #    || $self->ut_textn('paymask') #XXX something
317     #later #|| $self->ut_textn('paydate')
318     || $self->ut_numbern('paystart_month')
319     || $self->ut_numbern('paystart_year')
320     || $self->ut_numbern('payissue')
321 #    || $self->ut_textn('payname') #XXX something
322     || $self->ut_alphan('paystate')
323     || $self->ut_textn('paytype')
324     || $self->ut_ipn('payip')
325   ;
326   return $error if $error;
327
328   ### from cust_main
329
330   FS::payby->can_payby($self->table, $self->payby)
331     or return "Illegal payby: ". $self->payby;
332
333   # If it is encrypted and the private key is not availaible then we can't
334   # check the credit card.
335   my $check_payinfo = ! $self->is_encrypted($self->payinfo);
336
337   # Need some kind of global flag to accept invalid cards, for testing
338   # on scrubbed data.
339   #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
340
341   # In this block: detect card type; reject credit card / account numbers that
342   # are impossible or banned; reject other payment features (date, CVV length)
343   # that are inappropriate for the card type.
344   # However, if the payinfo is encrypted then just detect card type and assume
345   # the other checks were already done.
346
347   if ( !$ignore_invalid_card && 
348     $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
349
350     my $payinfo = $self->payinfo;
351     $payinfo =~ s/\D//g;
352     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
353       or return gettext('invalid_card'); #. ": ". $self->payinfo;
354     $payinfo = $1;
355     $self->payinfo($payinfo);
356     validate($payinfo)
357       or return gettext('invalid_card'); # . ": ". $self->payinfo;
358
359     my $cardtype = cardtype($payinfo);
360     $cardtype = 'Tokenized' if $self->payinfo =~ /^99\d{14}$/; #token
361     
362     return gettext('unknown_card_type') if $cardtype eq "Unknown";
363     
364     $self->set('paycardtype', $cardtype);
365
366     unless ( $ignore_banned_card ) {
367       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
368       if ( $ban ) {
369         if ( $ban->bantype eq 'warn' ) {
370           #or others depending on value of $ban->reason ?
371           return '_duplicate_card'.
372                  ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
373                  ' until '.         time2str('%a %h %o at %r', $ban->_end_date).
374                  ' (ban# '. $ban->bannum. ')'
375             unless $self->override_ban_warn;
376         } else {
377           return 'Banned credit card: banned on '.
378                  time2str('%a %h %o at %r', $ban->_date).
379                  ' by '. $ban->otaker.
380                  ' (ban# '. $ban->bannum. ')';
381         }
382       }
383     }
384
385     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
386       if ( $cardtype eq 'American Express card' ) {
387         $self->paycvv =~ /^(\d{4})$/
388           or return "CVV2 (CID) for American Express cards is four digits.";
389         $self->paycvv($1);
390       } else {
391         $self->paycvv =~ /^(\d{3})$/
392           or return "CVV2 (CVC2/CID) is three digits.";
393         $self->paycvv($1);
394       }
395     } else {
396       $self->paycvv('');
397     }
398
399     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
400
401       return "Start date or issue number is required for $cardtype cards"
402         unless $self->paystart_month && $self->paystart_year or $self->payissue;
403
404       return "Start month must be between 1 and 12"
405         if $self->paystart_month
406            and $self->paystart_month < 1 || $self->paystart_month > 12;
407
408       return "Start year must be 1990 or later"
409         if $self->paystart_year
410            and $self->paystart_year < 1990;
411
412       return "Issue number must be beween 1 and 99"
413         if $self->payissue
414           and $self->payissue < 1 || $self->payissue > 99;
415
416     } else {
417       $self->paystart_month('');
418       $self->paystart_year('');
419       $self->payissue('');
420     }
421
422   } elsif ( !$ignore_invalid_card && 
423     $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
424
425     my $payinfo = $self->payinfo;
426     $payinfo =~ s/[^\d\@\.]//g;
427     if ( $conf->config('echeck-country') eq 'CA' ) {
428       $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
429         or return 'invalid echeck account@branch.bank';
430       $payinfo = "$1\@$2.$3";
431     } elsif ( $conf->config('echeck-country') eq 'US' ) {
432       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
433       $payinfo = "$1\@$2";
434     } else {
435       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
436       $payinfo = "$1\@$2";
437     }
438     $self->payinfo($payinfo);
439     $self->paycvv('');
440
441     unless ( $ignore_banned_card ) {
442       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
443       if ( $ban ) {
444         if ( $ban->bantype eq 'warn' ) {
445           #or others depending on value of $ban->reason ?
446           return '_duplicate_ach' unless $self->override_ban_warn;
447         } else {
448           return 'Banned ACH account: banned on '.
449                  time2str('%a %h %o at %r', $ban->_date).
450                  ' by '. $ban->otaker.
451                  ' (ban# '. $ban->bannum. ')';
452         }
453       }
454     }
455
456   } elsif ( $self->payby =~ /^CARD|DCRD$/ and $self->paymask ) {
457     # either ignoring invalid cards, or we can't decrypt the payinfo, but
458     # try to detect the card type anyway. this never returns failure, so
459     # the contract of $ignore_invalid_cards is maintained.
460     $self->set('paycardtype', cardtype($self->paymask));
461   } else {
462     $self->set('paycardtype', '');
463   }
464
465 #  } elsif ( $self->payby eq 'PREPAY' ) {
466 #
467 #    my $payinfo = $self->payinfo;
468 #    $payinfo =~ s/\W//g; #anything else would just confuse things
469 #    $self->payinfo($payinfo);
470 #    $error = $self->ut_alpha('payinfo');
471 #    return "Illegal prepayment identifier: ". $self->payinfo if $error;
472 #    return "Unknown prepayment identifier"
473 #      unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
474 #    $self->paycvv('');
475
476   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
477
478     $self->paydate('');
479
480   } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
481
482     # shouldn't payinfo_check do this?
483     # (except we don't ever call payinfo_check from here)
484     return "Expiration date required"
485       if $self->paydate eq '' || $self->paydate eq '-';
486
487     my( $m, $y );
488     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
489       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
490     } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
491       ( $m, $y ) = ( $2, "19$1" );
492     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
493       ( $m, $y ) = ( $3, "20$2" );
494     } else {
495       return "Illegal expiration date: ". $self->paydate;
496     }
497     $m = sprintf('%02d',$m);
498     $self->paydate("$y-$m-01");
499     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
500     return gettext('expired_card')
501       if #XXX !$import
502       #&&
503          !$ignore_expired_card 
504       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
505
506   }
507
508   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
509        ( ! $conf->exists('require_cardname')
510          || $self->payby !~ /^(CARD|DCRD)$/  ) 
511   ) {
512     $self->payname( $self->first. " ". $self->getfield('last') );
513   } else {
514
515     if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
516       $self->payname =~ /^([\w \,\.\-\']*)$/
517         or return gettext('illegal_name'). " payname: ". $self->payname;
518       $self->payname($1);
519     } else {
520       $self->payname =~ /^([\w \,\.\-\'\&]*)$/
521         or return gettext('illegal_name'). " payname: ". $self->payname;
522       $self->payname($1);
523     }
524
525   }
526
527   if ( ! $self->custpaybynum ) {
528     if ($conf->exists('business-onlinepayment-verification')) {
529       $error = $self->verify;
530     } else {
531       $error = $self->tokenize;
532     }
533     return $error if $error;
534   }
535
536   $self->SUPER::check;
537 }
538
539 sub check_payinfo_cardtype {
540   my $self = shift;
541
542   return '' if $ignore_cardtype;
543
544   return '' unless $self->payby =~ /^(CARD|CHEK)$/;
545
546   my $payinfo = $self->payinfo;
547   $payinfo =~ s/\D//g;
548
549   if ( $payinfo =~ /^99\d{14}$/ ) {
550     $self->set('paycardtype', 'Tokenized');
551     return '';
552   }
553
554   my %bop_card_types = map { $_=>1 } values %{ card_types() };
555   my $cardtype = cardtype($payinfo);
556   $self->set('paycardtype', $cardtype);
557
558   return "$cardtype not accepted" unless $bop_card_types{$cardtype};
559
560   '';
561
562 }
563
564 sub _banned_pay_hashref {
565   my $self = shift;
566
567   my %payby2ban = (
568     'CARD' => 'CARD',
569     'DCRD' => 'CARD',
570     'CHEK' => 'CHEK',
571     'DCHK' => 'CHEK'
572   );
573
574   {
575     'payby'   => $payby2ban{$self->payby},
576     'payinfo' => $self->payinfo,
577     #don't ever *search* on reason! #'reason'  =>
578   };
579 }
580
581 sub _new_banned_pay_hashref {
582   my $self = shift;
583   my $hr = $self->_banned_pay_hashref;
584   $hr->{payinfo_hash} = 'SHA512';
585   $hr->{payinfo} = sha512_base64($hr->{payinfo});
586   $hr;
587 }
588
589 =item paydate_mon_year
590
591 Returns a two element list consisting of the paydate month and year.
592
593 =cut
594
595 sub paydate_mon_year {
596   my $self = shift;
597
598   my $date = $self->paydate; # || '12-2037';
599
600   #false laziness w/elements/select-month_year.html
601   if ( $date  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
602     ( $2, $1 );
603   } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
604     ( $1, $3 );
605   } else {
606     warn "unrecognized expiration date format: $date";
607     ( '', '' );
608   }
609
610 }
611
612 =item label
613
614 Returns a one line text label for this payment type.
615
616 =cut
617
618 my %weight = (
619   1 => 'Primary',
620   2 => 'Secondary',
621   3 => 'Tertiary',
622   4 => 'Fourth',
623   5 => 'Fifth',
624   6 => 'Sixth',
625   7 => 'Seventh',
626 );
627
628 sub label {
629   my $self = shift;
630
631   my $name = $self->payby =~ /^(CARD|DCRD)$/
632               && $self->paycardtype || FS::payby->shortname($self->payby);
633
634   ( $self->payby =~ /^(CARD|CHEK)$/  ? $weight{$self->weight}. ' automatic '
635                                      : 'Manual '
636   ).
637   "$name: ". $self->paymask.
638   ( $self->payby =~ /^(CARD|DCRD)$/
639       ? ' Exp '. join('/', $self->paydate_mon_year)
640       : ''
641   );
642
643 }
644
645 =item realtime_bop
646
647 Runs a L<realtime_bop|FS::cust_main::Billing_Realtime::realtime_bop> transaction on this card
648
649 =cut
650
651 sub realtime_bop {
652   my( $self, %opt ) = @_;
653
654   $self->cust_main->realtime_bop({
655     %opt,
656     'cust_payby' => $self,
657   });
658
659 }
660
661 =item tokenize
662
663 Runs a L<realtime_tokenize|FS::cust_main::Billing_Realtime::realtime_tokenize> transaction on this card
664
665 =cut
666
667 sub tokenize {
668   my $self = shift;
669   return '' unless $self->payby =~ /^(CARD|DCRD)$/;
670
671   $self->cust_main->realtime_tokenize({
672     'cust_payby' => $self,
673   });
674
675 }
676
677 =item verify 
678
679 Runs a L<realtime_verify_bop|FS::cust_main::Billing_Realtime/realtime_verify_bop> transaction on this card
680
681 =cut
682
683 sub verify {
684   my $self = shift;
685   return '' unless $self->payby =~ /^(CARD|DCRD)$/;
686
687   $self->cust_main->realtime_verify_bop({
688     'cust_payby' => $self,
689   });
690
691 }
692
693 =item paytypes
694
695 Returns a list of valid values for the paytype field (bank account type for
696 electronic check payment).
697
698 =cut
699
700 sub paytypes {
701   #my $class = shift;
702
703   ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
704 }
705
706 =item cgi_cust_payby_fields
707
708 Returns the field names used in the web interface (including some pseudo-fields).
709
710 =cut
711
712 sub cgi_cust_payby_fields {
713   #my $class = shift;
714   [qw( payby payinfo paydate_month paydate_year paycvv payname weight
715        payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
716 }
717
718 =item cgi_hash_callback HASHREF OLD
719
720 Subroutine (not a class or object method).  Processes a hash reference
721 of web interface contet (transfers the data from pseudo-fields to real fields).
722
723 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
724 payissue and payip.  If the new field is blank but the old is not, the old field 
725 will be preserved.
726
727 =cut
728
729 sub cgi_hash_callback {
730   my $hashref = shift;
731   my $old = shift;
732
733   my %noauto = (
734     'CARD' => 'DCRD',
735     'CHEK' => 'DCHK',
736   );
737   # the payby selector gives the choice of CARD or CHEK (or others, but
738   # those are the ones with auto and on-demand versions). if the user didn't
739   # choose a weight, then they mean DCRD/DCHK.
740   $hashref->{payby} = $noauto{$hashref->{payby}}
741     if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
742
743   if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
744
745     unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
746       %$hashref = ();
747       return;
748     }
749
750     $hashref->{payinfo} = $hashref->{payinfo1}. '@';
751     $hashref->{payinfo} .= $hashref->{payinfo3}.'.' 
752       if $conf->config('echeck-country') eq 'CA';
753     $hashref->{payinfo} .= $hashref->{'payinfo2'};
754
755     $hashref->{payname} = $hashref->{'payname_CHEK'};
756
757   } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
758
759     unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
760       %$hashref = ();
761       return;
762     }
763
764   }
765
766   $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
767
768   if ($old) {
769     foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
770       next if $hashref->{$field};
771       next unless $old->get($field);
772       $hashref->{$field} = $old->get($field);
773     }
774   }
775
776 }
777
778 =item search_sql
779
780 Class method.
781
782 Returns a qsearch hash expression to search for parameters specified in HASHREF.
783 Valid paramters are:
784
785 =over 4
786
787 =item payby
788
789 listref
790
791 =item paydate_year
792
793 =item paydate_month
794
795
796 =back
797
798 =cut
799
800 sub search_sql {
801   my ($class, $params) = @_;
802
803   my @where = ();
804   my $orderby;
805
806   # initialize these to prevent warnings
807   $params = {
808     'paydate_year'  => '',
809     %$params
810   };
811
812   ###
813   # payby
814   ###
815
816   if ( $params->{'payby'} ) {
817
818     my @payby = ref( $params->{'payby'} )
819                   ? @{ $params->{'payby'} }
820                   :  ( $params->{'payby'} );
821
822     @payby = grep /^([A-Z]{4})$/, @payby;
823     my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
824     push @where, "cust_payby.payby $in_payby"
825       if @payby;
826   }
827
828   ###
829   # paydate_year / paydate_month
830   ###
831
832   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
833     my $year = $1;
834     $params->{'paydate_month'} =~ /^(\d\d?)$/
835       or die "paydate_year without paydate_month?";
836     my $month = $1;
837
838     push @where,
839       'cust_payby.paydate IS NOT NULL',
840       "cust_payby.paydate != ''",
841       "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
842 ;
843   }
844   ##
845   # setup queries, subs, etc. for the search
846   ##
847
848   $orderby ||= 'ORDER BY custnum';
849
850   # here is the agent virtualization
851   push @where,
852     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
853
854   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
855
856   my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
857   # always make address fields available in results
858   for my $pre ('bill_', 'ship_') {
859     $addl_from .= 
860       ' LEFT JOIN cust_location AS '.$pre.'location '.
861       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
862   }
863   # always make referral available in results
864   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
865   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
866
867   my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
868
869   my @select = ( 'cust_payby.*',
870                  #'cust_main.custnum',
871                  # there's a good chance that we'll need these
872                  'cust_main.bill_locationnum',
873                  'cust_main.ship_locationnum',
874                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
875                );
876
877   my $select = join(', ', @select);
878
879   my $sql_query = {
880     'table'         => 'cust_payby',
881     'select'        => $select,
882     'addl_from'     => $addl_from,
883     'hashref'       => {},
884     'extra_sql'     => $extra_sql,
885     'order_by'      => $orderby,
886     'count_query'   => $count_query,
887   };
888   $sql_query;
889
890 }
891
892 =back
893
894 =cut
895
896 sub _upgrade_data {
897
898   my $class = shift;
899   local $ignore_banned_card = 1;
900   local $ignore_expired_card = 1;
901   local $ignore_invalid_card = 1;
902   $class->upgrade_set_cardtype;
903
904 }
905
906 =head1 BUGS
907
908 =head1 SEE ALSO
909
910 L<FS::Record>, schema.html from the base documentation.
911
912 =cut
913
914 1;
915