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