Bug 17375: Search by dateofbirth - handle invalid dates
[koha.git] / C4 / Utils / DataTables / Members.pm
1 package C4::Utils::DataTables::Members;
2
3 use Modern::Perl;
4 use C4::Context;
5 use C4::Members qw/GetMemberIssuesAndFines/;
6 use C4::Utils::DataTables;
7 use Koha::DateUtils;
8
9 sub search {
10     my ( $params ) = @_;
11     my $searchmember = $params->{searchmember};
12     my $firstletter = $params->{firstletter};
13     my $categorycode = $params->{categorycode};
14     my $branchcode = $params->{branchcode};
15     my $searchtype = $params->{searchtype} || 'contain';
16     my $searchfieldstype = $params->{searchfieldstype} || 'standard';
17     my $dt_params = $params->{dt_params};
18
19     unless ( $searchmember ) {
20         $searchmember = $dt_params->{sSearch} // '';
21     }
22
23     my ($sth, $query, $iTotalRecords, $iTotalDisplayRecords);
24     my $dbh = C4::Context->dbh;
25     # Get the iTotalRecords DataTable variable
26     $query = "SELECT COUNT(borrowers.borrowernumber) FROM borrowers";
27     $sth = $dbh->prepare($query);
28     $sth->execute;
29     ($iTotalRecords) = $sth->fetchrow_array;
30
31     if ( $searchfieldstype eq 'dateofbirth' ) {
32         # Return an empty list if the date of birth is not correctly formatted
33         $searchmember = eval { output_pref( { str => $searchmember, dateformat => 'iso', dateonly => 1 } ); };
34         if ( $@ or not $searchmember ) {
35             return {
36                 iTotalRecords        => 0,
37                 iTotalDisplayRecords => 0,
38                 patrons              => [],
39             };
40         }
41     }
42
43     # If branches are independent and user is not superlibrarian
44     # The search has to be only on the user branch
45     if ( C4::Context::only_my_library ) {
46         my $userenv = C4::Context->userenv;
47         $branchcode = $userenv->{'branch'};
48
49     }
50
51     my $select = "SELECT
52         borrowers.borrowernumber, borrowers.surname, borrowers.firstname,
53         borrowers.streetnumber, borrowers.streettype, borrowers.address,
54         borrowers.address2, borrowers.city, borrowers.state, borrowers.zipcode,
55         borrowers.country, cardnumber, borrowers.dateexpiry,
56         borrowers.borrowernotes, borrowers.branchcode, borrowers.email,
57         borrowers.userid, borrowers.dateofbirth, borrowers.categorycode,
58         categories.description AS category_description, categories.category_type,
59         branches.branchname";
60     my $from = "FROM borrowers
61         LEFT JOIN branches ON borrowers.branchcode = branches.branchcode
62         LEFT JOIN categories ON borrowers.categorycode = categories.categorycode";
63     my @where_args;
64     my @where_strs;
65     if(defined $firstletter and $firstletter ne '') {
66         push @where_strs, "borrowers.surname LIKE ?";
67         push @where_args, "$firstletter%";
68     }
69     if(defined $categorycode and $categorycode ne '') {
70         push @where_strs, "borrowers.categorycode = ?";
71         push @where_args, $categorycode;
72     }
73     if(defined $branchcode and $branchcode ne '') {
74         push @where_strs, "borrowers.branchcode = ?";
75         push @where_args, $branchcode;
76     }
77
78     my $searchfields = {
79         standard => 'surname,firstname,othernames,cardnumber,userid',
80         surname => 'surname',
81         email => 'email,emailpro,B_email',
82         borrowernumber => 'borrowernumber',
83         userid => 'userid',
84         phone => 'phone,phonepro,B_phone,altcontactphone,mobile',
85         address => 'streettype,address,address2,city,state,zipcode,country',
86         dateofbirth => 'dateofbirth',
87         sort1 => 'sort1',
88         sort2 => 'sort2',
89     };
90
91     # * is replaced with % for sql
92     $searchmember =~ s/\*/%/g;
93
94     # split into search terms
95     my @terms;
96     # consider coma as space
97     $searchmember =~ s/,/ /g;
98     if ( $searchtype eq 'contain' ) {
99        @terms = split / /, $searchmember;
100     } else {
101        @terms = ($searchmember);
102     }
103
104     foreach my $term (@terms) {
105         next unless $term;
106
107         $term .= '%' # end with anything
108             if $term !~ /%$/;
109         $term = "%$term" # begin with anythin unless start_with
110             if $searchtype eq 'contain' && $term !~ /^%/;
111
112         my @where_strs_or;
113         for my $searchfield ( split /,/, $searchfields->{$searchfieldstype} ) {
114             push @where_strs_or, "borrowers." . $dbh->quote_identifier($searchfield) . " LIKE ?";
115             push @where_args, $term;
116         }
117
118         if ( C4::Context->preference('ExtendedPatronAttributes') and $searchmember ) {
119             my $matching_borrowernumbers = C4::Members::Attributes::SearchIdMatchingAttribute($searchmember);
120
121             for my $borrowernumber ( @$matching_borrowernumbers ) {
122                 push @where_strs_or, "borrowers.borrowernumber = ?";
123                 push @where_args, $borrowernumber;
124             }
125         }
126
127         push @where_strs, '('. join (' OR ', @where_strs_or) . ')'
128             if @where_strs_or;
129     }
130
131     my $where;
132     $where = " WHERE " . join (" AND ", @where_strs) if @where_strs;
133     my $orderby = dt_build_orderby($dt_params);
134
135     my $limit;
136     # If iDisplayLength == -1, we want to display all patrons
137     if ( !$dt_params->{iDisplayLength} || $dt_params->{iDisplayLength} > -1 ) {
138         # In order to avoid sql injection
139         $dt_params->{iDisplayStart} =~ s/\D//g if defined($dt_params->{iDisplayStart});
140         $dt_params->{iDisplayLength} =~ s/\D//g if defined($dt_params->{iDisplayLength});
141         $dt_params->{iDisplayStart} //= 0;
142         $dt_params->{iDisplayLength} //= 20;
143         $limit = "LIMIT $dt_params->{iDisplayStart},$dt_params->{iDisplayLength}";
144     }
145
146     $query = join(
147         " ",
148         ($select ? $select : ""),
149         ($from ? $from : ""),
150         ($where ? $where : ""),
151         ($orderby ? $orderby : ""),
152         ($limit ? $limit : "")
153     );
154     $sth = $dbh->prepare($query);
155     $sth->execute(@where_args);
156     my $patrons = $sth->fetchall_arrayref({});
157
158     # Get the iTotalDisplayRecords DataTable variable
159     $query = "SELECT COUNT(borrowers.borrowernumber) " . $from . ($where ? $where : "");
160     $sth = $dbh->prepare($query);
161     $sth->execute(@where_args);
162     ($iTotalDisplayRecords) = $sth->fetchrow_array;
163
164     # Get some information on patrons
165     foreach my $patron (@$patrons) {
166         ($patron->{overdues}, $patron->{issues}, $patron->{fines}) =
167             GetMemberIssuesAndFines($patron->{borrowernumber});
168         if($patron->{dateexpiry} and $patron->{dateexpiry} ne '0000-00-00') {
169             $patron->{dateexpiry} = output_pref( { dt => dt_from_string( $patron->{dateexpiry}, 'iso'), dateonly => 1} );
170         } else {
171             $patron->{dateexpiry} = '';
172         }
173         $patron->{fines} = sprintf("%.2f", $patron->{fines} || 0);
174     }
175
176     return {
177         iTotalRecords => $iTotalRecords,
178         iTotalDisplayRecords => $iTotalDisplayRecords,
179         patrons => $patrons
180     }
181 }
182
183 1;
184 __END__
185
186 =head1 NAME
187
188 C4::Utils::DataTables::Members - module for using DataTables with patrons
189
190 =head1 SYNOPSIS
191
192 This module provides (one for the moment) routines used by the patrons search
193
194 =head2 FUNCTIONS
195
196 =head3 search
197
198     my $dt_infos = C4::Utils::DataTables::Members->search($params);
199
200 $params is a hashref with some keys:
201
202 =over 4
203
204 =item searchmember
205
206   String to search in the borrowers sql table
207
208 =item firstletter
209
210   Introduced to contain 1 letter but can contain more.
211   The search will done on the borrowers.surname field
212
213 =item categorycode
214
215   Search patrons with this categorycode
216
217 =item branchcode
218
219   Search patrons with this branchcode
220
221 =item searchtype
222
223   Can be 'start_with' or 'contain' (default value). Used for the searchmember parameter.
224
225 =item searchfieldstype
226
227   Can be 'standard' (default value), 'email', 'borrowernumber', 'phone', 'address' or 'dateofbirth', 'sort1', 'sort2'
228
229 =item dt_params
230
231   Is the reference of C4::Utils::DataTables::dt_get_params($input);
232
233 =cut
234
235 =back
236
237 =head1 LICENSE
238
239 This file is part of Koha.
240
241 Copyright 2013 BibLibre
242
243 Koha is free software; you can redistribute it and/or modify it
244 under the terms of the GNU General Public License as published by
245 the Free Software Foundation; either version 3 of the License, or
246 (at your option) any later version.
247
248 Koha is distributed in the hope that it will be useful, but
249 WITHOUT ANY WARRANTY; without even the implied warranty of
250 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
251 GNU General Public License for more details.
252
253 You should have received a copy of the GNU General Public License
254 along with Koha; if not, see <http://www.gnu.org/licenses>.