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