Bug 23970: Make search with "Publication date" field work at any position
[koha.git] / catalogue / itemsearch.pl
1 #!/usr/bin/perl
2 # Copyright 2013 BibLibre
3 #
4 # This file is part of Koha
5 #
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 3 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19 use Modern::Perl;
20 use CGI;
21
22 use JSON;
23
24 use C4::Auth;
25 use C4::Output;
26 use C4::Items;
27 use C4::Biblio;
28 use C4::Koha;
29
30 use Koha::AuthorisedValues;
31 use Koha::Biblios;
32 use Koha::Item::Search::Field qw(GetItemSearchFields);
33 use Koha::ItemTypes;
34 use Koha::Libraries;
35
36 my $cgi = new CGI;
37 my %params = $cgi->Vars;
38
39 my $format = $cgi->param('format');
40 my $template_name = 'catalogue/itemsearch.tt';
41
42 if (defined $format and $format eq 'json') {
43     $template_name = 'catalogue/itemsearch_json.tt';
44
45     # Map DataTables parameters with 'regular' parameters
46     $cgi->param('rows', scalar $cgi->param('iDisplayLength'));
47     $cgi->param('page', (scalar $cgi->param('iDisplayStart') / scalar $cgi->param('iDisplayLength')) + 1);
48     my @columns = split /,/, scalar $cgi->param('sColumns');
49     $cgi->param('sortby', $columns[ scalar $cgi->param('iSortCol_0') ]);
50     $cgi->param('sortorder', scalar $cgi->param('sSortDir_0'));
51
52     my @f = $cgi->multi_param('f');
53     my @q = $cgi->multi_param('q');
54     push @q, '' if @q == 0;
55     my @op = $cgi->multi_param('op');
56     my @c = $cgi->multi_param('c');
57     my $iColumns = $cgi->param('iColumns');
58     foreach my $i (0 .. ($iColumns - 1)) {
59         my $sSearch = $cgi->param("sSearch_$i");
60         if (defined $sSearch and $sSearch ne '') {
61             my @words = split /\s+/, $sSearch;
62             foreach my $word (@words) {
63                 push @f, $columns[$i];
64                 push @c, 'and';
65
66                 if ( grep /^$columns[$i]$/, qw( ccode homebranch holdingbranch location itype notforloan itemlost ) ) {
67                     push @q, "$word";
68                     push @op, '=';
69                 } else {
70                     push @q, "%$word%";
71                     push @op, 'like';
72                 }
73             }
74         }
75     }
76     $cgi->param('f', @f);
77     $cgi->param('q', @q);
78     $cgi->param('op', @op);
79     $cgi->param('c', @c);
80 } elsif (defined $format and $format eq 'csv') {
81     $template_name = 'catalogue/itemsearch_csv.tt';
82
83     # Retrieve all results
84     $cgi->param('rows', 0);
85 } elsif (defined $format and $format eq 'barcodes') {
86     # Retrieve all results
87     $cgi->param('rows', 0);
88 } elsif (defined $format) {
89     die "Unsupported format $format";
90 }
91
92 my ($template, $borrowernumber, $cookie) = get_template_and_user({
93     template_name => $template_name,
94     query => $cgi,
95     type => 'intranet',
96     authnotrequired => 0,
97     flagsrequired   => { catalogue => 1 },
98 });
99
100 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.notforloan', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
101 my $notforloan_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : [];
102
103 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
104 my $location_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : [];
105
106 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
107 my $itemlost_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : [];
108
109 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.withdrawn', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
110 my $withdrawn_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : [];
111
112 if (scalar keys %params > 0) {
113     # Parameters given, it's a search
114
115     my $filter = {
116         conjunction => 'AND',
117         filters => [],
118     };
119
120     foreach my $p (qw(homebranch holdingbranch location itype ccode issues datelastborrowed notforloan itemlost withdrawn)) {
121         if (my @q = $cgi->multi_param($p)) {
122             if ($q[0] ne '') {
123                 my $f = {
124                     field => $p,
125                     query => \@q,
126                 };
127                 if (my $op = scalar $cgi->param($p . '_op')) {
128                     $f->{operator} = $op;
129                 }
130                 push @{ $filter->{filters} }, $f;
131             }
132         }
133     }
134
135     my @c = $cgi->multi_param('c');
136     my @fields = $cgi->multi_param('f');
137     my @q = $cgi->multi_param('q');
138     my @op = $cgi->multi_param('op');
139
140     my $f;
141     for (my $i = 0; $i < @fields; $i++) {
142         my $field = $fields[$i];
143         my $q = shift @q;
144         my $op = shift @op;
145         if (defined $q and $q ne '') {
146             if (C4::Context->preference("marcflavour") ne "UNIMARC" && $field eq 'publicationyear') {
147                 $field = 'copyrightdate';
148             }
149
150             if ($i == 0) {
151                 $f = {
152                     field => $field,
153                     query => $q,
154                     operator => $op,
155                 };
156             } else {
157                 my $c = shift @c;
158                 $f = {
159                     conjunction => $c,
160                     filters => [
161                         $f, {
162                             field => $field,
163                             query => $q,
164                             operator => $op,
165                         }
166                     ],
167                 };
168             }
169         }
170     }
171     push @{ $filter->{filters} }, $f;
172
173     # Yes/No parameters
174     foreach my $p (qw( damaged )) {
175         my $v = $cgi->param($p) // '';
176         my $f = {
177             field => $p,
178             query => 0,
179         };
180         if ($v eq 'yes') {
181             $f->{operator} = '!=';
182             push @{ $filter->{filters} }, $f;
183         } elsif ($v eq 'no') {
184             $f->{operator} = '=';
185             push @{ $filter->{filters} }, $f;
186         }
187     }
188
189     if (my $itemcallnumber_from = scalar $cgi->param('itemcallnumber_from')) {
190         push @{ $filter->{filters} }, {
191             field => 'itemcallnumber',
192             query => $itemcallnumber_from,
193             operator => '>=',
194         };
195     }
196     if (my $itemcallnumber_to = scalar $cgi->param('itemcallnumber_to')) {
197         push @{ $filter->{filters} }, {
198             field => 'itemcallnumber',
199             query => $itemcallnumber_to,
200             operator => '<=',
201         };
202     }
203
204     my $sortby = $cgi->param('sortby') || 'itemnumber';
205     if (C4::Context->preference("marcflavour") ne "UNIMARC" && $sortby eq 'publicationyear') {
206         $sortby = 'copyrightdate';
207     }
208     my $search_params = {
209         rows => scalar $cgi->param('rows') // 20,
210         page => scalar $cgi->param('page') || 1,
211         sortby => $sortby,
212         sortorder => scalar $cgi->param('sortorder') || 'asc',
213     };
214
215     my ($results, $total_rows) = SearchItems($filter, $search_params);
216
217     if ($format eq 'barcodes') {
218         print $cgi->header({
219             type => 'text/plain',
220             attachment => 'barcodes.txt',
221         });
222
223         foreach my $item (@$results) {
224             print $item->{barcode} . "\n";
225         }
226         exit;
227     }
228
229     if ($results) {
230         # Get notforloan labels
231         my $notforloan_map = {};
232         foreach my $nfl_value (@$notforloan_values) {
233             $notforloan_map->{$nfl_value->{authorised_value}} = $nfl_value->{lib};
234         }
235
236         # Get location labels
237         my $location_map = {};
238         foreach my $loc_value (@$location_values) {
239             $location_map->{$loc_value->{authorised_value}} = $loc_value->{lib};
240         }
241
242         # Get itemlost labels
243         my $itemlost_map = {};
244         foreach my $il_value (@$itemlost_values) {
245             $itemlost_map->{$il_value->{authorised_value}} = $il_value->{lib};
246         }
247
248         # Get withdrawn labels
249         my $withdrawn_map = {};
250         foreach my $wd_value (@$withdrawn_values) {
251             $withdrawn_map->{$wd_value->{authorised_value}} = $wd_value->{lib};
252         }
253
254         foreach my $item (@$results) {
255             my $biblio = Koha::Biblios->find( $item->{biblionumber} );
256             $item->{biblio} = $biblio;
257             $item->{biblioitem} = $biblio->biblioitem->unblessed;
258             $item->{status} = $notforloan_map->{$item->{notforloan}};
259             if (defined $item->{location}) {
260                 $item->{location} = $location_map->{$item->{location}};
261             }
262         }
263     }
264
265     $template->param(
266         filter => $filter,
267         search_params => $search_params,
268         results => $results,
269         total_rows => $total_rows,
270     );
271
272     if ($format eq 'csv') {
273         print $cgi->header({
274             type => 'text/csv',
275             attachment => 'items.csv',
276         });
277
278         for my $line ( split '\n', $template->output ) {
279             print "$line\n" unless $line =~ m|^\s*$|;
280         }
281     } elsif ($format eq 'json') {
282         $template->param(sEcho => scalar $cgi->param('sEcho'));
283         output_with_http_headers $cgi, $cookie, $template->output, 'json';
284     }
285
286     exit;
287 }
288
289 # Display the search form
290
291 my @branches = map { value => $_->branchcode, label => $_->branchname }, Koha::Libraries->search( {}, { order_by => 'branchname' } );
292 my @locations;
293 foreach my $location (@$location_values) {
294     push @locations, {
295         value => $location->{authorised_value},
296         label => $location->{lib} // $location->{authorised_value},
297     };
298 }
299 my @itemtypes;
300 foreach my $itemtype ( Koha::ItemTypes->search ) {
301     push @itemtypes, {
302         value => $itemtype->itemtype,
303         label => $itemtype->translated_description,
304     };
305 }
306
307 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.ccode', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
308 my $ccode_avcode = $mss->count ? $mss->next->authorised_value : 'CCODE';
309 my $ccodes = GetAuthorisedValues($ccode_avcode);
310 my @ccodes;
311 foreach my $ccode (@$ccodes) {
312     push @ccodes, {
313         value => $ccode->{authorised_value},
314         label => $ccode->{lib},
315     };
316 }
317
318 my @notforloans;
319 foreach my $value (@$notforloan_values) {
320     push @notforloans, {
321         value => $value->{authorised_value},
322         label => $value->{lib},
323     };
324 }
325
326 my @itemlosts;
327 foreach my $value (@$itemlost_values) {
328     push @itemlosts, {
329         value => $value->{authorised_value},
330         label => $value->{lib},
331     };
332 }
333
334 my @withdrawns;
335 foreach my $value (@$withdrawn_values) {
336     push @withdrawns, {
337         value => $value->{authorised_value},
338         label => $value->{lib},
339     };
340 }
341
342 my @items_search_fields = GetItemSearchFields();
343
344 my $authorised_values = {};
345 foreach my $field (@items_search_fields) {
346     if (my $category = ($field->{authorised_values_category})) {
347         $authorised_values->{$category} = GetAuthorisedValues($category);
348     }
349 }
350
351 $template->param(
352     branches => \@branches,
353     locations => \@locations,
354     itemtypes => \@itemtypes,
355     ccodes => \@ccodes,
356     notforloans => \@notforloans,
357     itemlosts => \@itemlosts,
358     withdrawns => \@withdrawns,
359     items_search_fields => \@items_search_fields,
360     authorised_values_json => to_json($authorised_values),
361 );
362
363 output_html_with_http_headers $cgi, $cookie, $template->output;