Bug 16951: Fix Item search sorting
[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::Item::Search::Field qw(GetItemSearchFields);
32 use Koha::ItemTypes;
33 use Koha::Libraries;
34
35 my $cgi = new CGI;
36 my %params = $cgi->Vars;
37
38 my $format = $cgi->param('format');
39 my ($template_name, $content_type);
40 if (defined $format and $format eq 'json') {
41     $template_name = 'catalogue/itemsearch_json.tt';
42     $content_type = 'json';
43
44     # Map DataTables parameters with 'regular' parameters
45     $cgi->param('rows', $cgi->param('iDisplayLength'));
46     $cgi->param('page', ($cgi->param('iDisplayStart') / $cgi->param('iDisplayLength')) + 1);
47     my @columns = split /,/, scalar $cgi->param('sColumns');
48     $cgi->param('sortby', $columns[ $cgi->param('iSortCol_0') ]);
49     $cgi->param('sortorder', $cgi->param('sSortDir_0'));
50
51     my @f = $cgi->multi_param('f');
52     my @q = $cgi->multi_param('q');
53     push @q, '' if @q == 0;
54     my @op = $cgi->multi_param('op');
55     my @c = $cgi->multi_param('c');
56     foreach my $i (0 .. ($cgi->param('iColumns') - 1)) {
57         my $sSearch = $cgi->param("sSearch_$i");
58         if (defined $sSearch and $sSearch ne '') {
59             my @words = split /\s+/, $sSearch;
60             foreach my $word (@words) {
61                 push @f, $columns[$i];
62                 push @q, "%$word%";
63                 push @op, 'like';
64                 push @c, 'and';
65             }
66         }
67     }
68     $cgi->param('f', @f);
69     $cgi->param('q', @q);
70     $cgi->param('op', @op);
71     $cgi->param('c', @c);
72 } elsif (defined $format and $format eq 'csv') {
73     $template_name = 'catalogue/itemsearch_csv.tt';
74
75     # Retrieve all results
76     $cgi->param('rows', 0);
77 } else {
78     $format = 'html';
79     $template_name = 'catalogue/itemsearch.tt';
80     $content_type = 'html';
81 }
82
83 my ($template, $borrowernumber, $cookie) = get_template_and_user({
84     template_name => $template_name,
85     query => $cgi,
86     type => 'intranet',
87     authnotrequired => 0,
88     flagsrequired   => { catalogue => 1 },
89 });
90
91 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.notforloan', authorised_value => { not => undef } });
92 my $notforloan_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : [];
93
94 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.location', authorised_value => { not => undef } });
95 my $location_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : [];
96
97 if (scalar keys %params > 0) {
98     # Parameters given, it's a search
99
100     my $filter = {
101         conjunction => 'AND',
102         filters => [],
103     };
104
105     foreach my $p (qw(homebranch holdingbranch location itype ccode issues datelastborrowed notforloan)) {
106         if (my @q = $cgi->multi_param($p)) {
107             if ($q[0] ne '') {
108                 my $f = {
109                     field => $p,
110                     query => \@q,
111                 };
112                 if (my $op = $cgi->param($p . '_op')) {
113                     $f->{operator} = $op;
114                 }
115                 push @{ $filter->{filters} }, $f;
116             }
117         }
118     }
119
120     my @c = $cgi->multi_param('c');
121     my @fields = $cgi->multi_param('f');
122     my @q = $cgi->multi_param('q');
123     my @op = $cgi->multi_param('op');
124
125     my $f;
126     for (my $i = 0; $i < @fields; $i++) {
127         my $field = $fields[$i];
128         my $q = shift @q;
129         my $op = shift @op;
130         if (defined $q and $q ne '') {
131             if ($i == 0) {
132                 if (C4::Context->preference("marcflavour") ne "UNIMARC" && $field eq 'publicationyear') {
133                     $field = 'copyrightdate';
134                 }
135                 $f = {
136                     field => $field,
137                     query => $q,
138                     operator => $op,
139                 };
140             } else {
141                 my $c = shift @c;
142                 $f = {
143                     conjunction => $c,
144                     filters => [
145                         $f, {
146                             field => $field,
147                             query => $q,
148                             operator => $op,
149                         }
150                     ],
151                 };
152             }
153         }
154     }
155     push @{ $filter->{filters} }, $f;
156
157     # Yes/No parameters
158     foreach my $p (qw(damaged itemlost)) {
159         my $v = $cgi->param($p) // '';
160         my $f = {
161             field => $p,
162             query => 0,
163         };
164         if ($v eq 'yes') {
165             $f->{operator} = '!=';
166             push @{ $filter->{filters} }, $f;
167         } elsif ($v eq 'no') {
168             $f->{operator} = '=';
169             push @{ $filter->{filters} }, $f;
170         }
171     }
172
173     if (my $itemcallnumber_from = $cgi->param('itemcallnumber_from')) {
174         push @{ $filter->{filters} }, {
175             field => 'itemcallnumber',
176             query => $itemcallnumber_from,
177             operator => '>=',
178         };
179     }
180     if (my $itemcallnumber_to = $cgi->param('itemcallnumber_to')) {
181         push @{ $filter->{filters} }, {
182             field => 'itemcallnumber',
183             query => $itemcallnumber_to,
184             operator => '<=',
185         };
186     }
187
188     my $sortby = $cgi->param('sortby') || 'itemnumber';
189     if (C4::Context->preference("marcflavour") ne "UNIMARC" && $sortby eq 'publicationyear') {
190         $sortby = 'copyrightdate';
191     }
192     my $search_params = {
193         rows => scalar $cgi->param('rows') // 20,
194         page => scalar $cgi->param('page') || 1,
195         sortby => $sortby,
196         sortorder => scalar $cgi->param('sortorder') || 'asc',
197     };
198
199     my ($results, $total_rows) = SearchItems($filter, $search_params);
200     if ($results) {
201         # Get notforloan labels
202         my $notforloan_map = {};
203         foreach my $nfl_value (@$notforloan_values) {
204             $notforloan_map->{$nfl_value->{authorised_value}} = $nfl_value->{lib};
205         }
206
207         # Get location labels
208         my $location_map = {};
209         foreach my $loc_value (@$location_values) {
210             $location_map->{$loc_value->{authorised_value}} = $loc_value->{lib};
211         }
212
213         foreach my $item (@$results) {
214             $item->{biblio} = GetBiblio($item->{biblionumber});
215             ($item->{biblioitem}) = GetBiblioItemByBiblioNumber($item->{biblionumber});
216             $item->{status} = $notforloan_map->{$item->{notforloan}};
217             if (defined $item->{location}) {
218                 $item->{location} = $location_map->{$item->{location}};
219             }
220         }
221     }
222
223     $template->param(
224         filter => $filter,
225         search_params => $search_params,
226         results => $results,
227         total_rows => $total_rows,
228         search_done => 1,
229     );
230
231     if ($format eq 'html') {
232         # Build pagination bar
233         my $url = '/cgi-bin/koha/catalogue/itemsearch.pl';
234         my @params;
235         foreach my $p (keys %params) {
236             my @v = $cgi->multi_param($p);
237             push @params, map { "$p=" . $_ } @v;
238         }
239         $url .= '?' . join ('&', @params);
240         my $nb_pages = 1 + int($total_rows / $search_params->{rows});
241         my $current_page = $search_params->{page};
242         my $pagination_bar = pagination_bar($url, $nb_pages, $current_page, 'page');
243
244         $template->param(pagination_bar => $pagination_bar);
245     }
246 }
247
248 if ($format eq 'html') {
249     # Retrieve data required for the form.
250
251     my @branches = map { value => $_->branchcode, label => $_->branchname }, Koha::Libraries->search( {}, { order_by => 'branchname' } );
252     my @locations;
253     foreach my $location (@$location_values) {
254         push @locations, {
255             value => $location->{authorised_value},
256             label => $location->{lib} // $location->{authorised_value},
257         };
258     }
259     my @itemtypes;
260     foreach my $itemtype ( Koha::ItemTypes->search ) {
261         push @itemtypes, {
262             value => $itemtype->itemtype,
263             label => $itemtype->translated_description,
264         };
265     }
266
267     my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.ccode', authorised_value => { not => undef } });
268     my $ccode_avcode = $mss->count ? $mss->next->authorised_value : 'CCODE';
269     my $ccodes = GetAuthorisedValues($ccode_avcode);
270     my @ccodes;
271     foreach my $ccode (@$ccodes) {
272         push @ccodes, {
273             value => $ccode->{authorised_value},
274             label => $ccode->{lib},
275         };
276     }
277
278     my @notforloans;
279     foreach my $value (@$notforloan_values) {
280         push @notforloans, {
281             value => $value->{authorised_value},
282             label => $value->{lib},
283         };
284     }
285
286     my @items_search_fields = GetItemSearchFields();
287
288     my $authorised_values = {};
289     foreach my $field (@items_search_fields) {
290         if (my $category = ($field->{authorised_values_category})) {
291             $authorised_values->{$category} = GetAuthorisedValues($category);
292         }
293     }
294
295     $template->param(
296         branches => \@branches,
297         locations => \@locations,
298         itemtypes => \@itemtypes,
299         ccodes => \@ccodes,
300         notforloans => \@notforloans,
301         items_search_fields => \@items_search_fields,
302         authorised_values_json => to_json($authorised_values),
303     );
304 }
305
306 if ($format eq 'csv') {
307     print $cgi->header({
308         type => 'text/csv',
309         attachment => 'items.csv',
310     });
311
312     for my $line ( split '\n', $template->output ) {
313         print "$line\n" unless $line =~ m|^\s*$|;
314     }
315 } else {
316     output_with_http_headers $cgi, $cookie, $template->output, $content_type;
317 }