RT#41394: Add advertising source to customer fields selection [safer part_referral...
[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   # false laziness with check
640   my( $m, $y );
641   if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
642     ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
643   } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
644     ( $m, $y ) = ( $2, "19$1" );
645   } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
646     ( $m, $y ) = ( $3, "20$2" );
647   } else {
648     return "Illegal expiration date: ". $self->paydate;
649   }
650   $m = sprintf('%02d',$m);
651   $opt{paydate} = "$y-$m-01";
652
653   $opt{$_} = $self->$_() for qw( payinfo payname paycvv );
654
655   if ( $self->locationnum ) {
656     my $cust_location = $self->cust_location;
657     $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
658   }
659
660   $self->cust_main->realtime_verify_bop({
661     'method' => FS::payby->payby2bop( $self->payby ),
662     %opt,
663   });
664
665 }
666
667 =item paytypes
668
669 Returns a list of valid values for the paytype field (bank account type for
670 electronic check payment).
671
672 =cut
673
674 sub paytypes {
675   #my $class = shift;
676
677   ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
678 }
679
680 =item cgi_cust_payby_fields
681
682 Returns the field names used in the web interface (including some pseudo-fields).
683
684 =cut
685
686 sub cgi_cust_payby_fields {
687   #my $class = shift;
688   [qw( payby payinfo paydate_month paydate_year paycvv payname weight
689        payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
690 }
691
692 =item cgi_hash_callback HASHREF OLD
693
694 Subroutine (not a class or object method).  Processes a hash reference
695 of web interface contet (transfers the data from pseudo-fields to real fields).
696
697 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
698 payissue and payip.  If the new field is blank but the old is not, the old field 
699 will be preserved.
700
701 =cut
702
703 sub cgi_hash_callback {
704   my $hashref = shift;
705   my $old = shift;
706
707   my %noauto = (
708     'CARD' => 'DCRD',
709     'CHEK' => 'DCHK',
710   );
711   $hashref->{payby} = $noauto{$hashref->{payby}}
712     if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
713
714   if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
715
716     unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
717       %$hashref = ();
718       return;
719     }
720
721     $hashref->{payinfo} = $hashref->{payinfo1}. '@';
722     $hashref->{payinfo} .= $hashref->{payinfo3}.'.' 
723       if $conf->config('echeck-country') eq 'CA';
724     $hashref->{payinfo} .= $hashref->{'payinfo2'};
725
726     $hashref->{payname} = $hashref->{'payname_CHEK'};
727
728   } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
729
730     unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
731       %$hashref = ();
732       return;
733     }
734
735   }
736
737   $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
738
739   if ($old) {
740     foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
741       next if $hashref->{$field};
742       next unless $old->get($field);
743       $hashref->{$field} = $old->get($field);
744     }
745   }
746
747 }
748
749 =item search_sql
750
751 Class method.
752
753 Returns a qsearch hash expression to search for parameters specified in HASHREF.
754 Valid paramters are:
755
756 =over 4
757
758 =item payby
759
760 listref
761
762 =item paydate_year
763
764 =item paydate_month
765
766
767 =back
768
769 =cut
770
771 sub search_sql {
772   my ($class, $params) = @_;
773
774   my @where = ();
775   my $orderby;
776
777   # initialize these to prevent warnings
778   $params = {
779     'paydate_year'  => '',
780     %$params
781   };
782
783   ###
784   # payby
785   ###
786
787   if ( $params->{'payby'} ) {
788
789     my @payby = ref( $params->{'payby'} )
790                   ? @{ $params->{'payby'} }
791                   :  ( $params->{'payby'} );
792
793     @payby = grep /^([A-Z]{4})$/, @payby;
794     my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
795     push @where, "cust_payby.payby $in_payby"
796       if @payby;
797   }
798
799   ###
800   # paydate_year / paydate_month
801   ###
802
803   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
804     my $year = $1;
805     $params->{'paydate_month'} =~ /^(\d\d?)$/
806       or die "paydate_year without paydate_month?";
807     my $month = $1;
808
809     push @where,
810       'cust_payby.paydate IS NOT NULL',
811       "cust_payby.paydate != ''",
812       "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
813 ;
814   }
815   ##
816   # setup queries, subs, etc. for the search
817   ##
818
819   $orderby ||= 'ORDER BY custnum';
820
821   # here is the agent virtualization
822   push @where,
823     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
824
825   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
826
827   my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
828   # always make address fields available in results
829   for my $pre ('bill_', 'ship_') {
830     $addl_from .= 
831       ' LEFT JOIN cust_location AS '.$pre.'location '.
832       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
833   }
834   # always make referral available in results
835   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
836   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
837
838   my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
839
840   my @select = ( 'cust_payby.*',
841                  #'cust_main.custnum',
842                  # there's a good chance that we'll need these
843                  'cust_main.bill_locationnum',
844                  'cust_main.ship_locationnum',
845                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
846                );
847
848   my $select = join(', ', @select);
849
850   my $sql_query = {
851     'table'         => 'cust_payby',
852     'select'        => $select,
853     'addl_from'     => $addl_from,
854     'hashref'       => {},
855     'extra_sql'     => $extra_sql,
856     'order_by'      => $orderby,
857     'count_query'   => $count_query,
858   };
859   $sql_query;
860
861 }
862
863 =back
864
865 =head1 BUGS
866
867 =head1 SEE ALSO
868
869 L<FS::Record>, schema.html from the base documentation.
870
871 =cut
872
873 1;
874