Bug 27680: Add support for sorting fields with multiple data points
[koha.git] / Koha / REST / Plugin / Query.pm
1 package Koha::REST::Plugin::Query;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Mojo::Base 'Mojolicious::Plugin';
21 use List::MoreUtils qw(any);
22 use Scalar::Util qw(reftype);
23 use JSON qw(decode_json);
24
25 use Koha::Exceptions;
26
27 =head1 NAME
28
29 Koha::REST::Plugin::Query
30
31 =head1 API
32
33 =head2 Mojolicious::Plugin methods
34
35 =head3 register
36
37 =cut
38
39 sub register {
40     my ( $self, $app ) = @_;
41
42 =head2 Helper methods
43
44 =head3 extract_reserved_params
45
46     my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($params);
47
48 Generates the DBIC query from the query parameters.
49
50 =cut
51
52     $app->helper(
53         'extract_reserved_params' => sub {
54             my ( $c, $params ) = @_;
55
56             my $reserved_params;
57             my $filtered_params;
58             my $path_params;
59
60             my $reserved_words = _reserved_words();
61             my @query_param_names = keys %{$c->req->params->to_hash};
62
63             foreach my $param ( keys %{$params} ) {
64                 if ( grep { $param eq $_ } @{$reserved_words} ) {
65                     $reserved_params->{$param} = $params->{$param};
66                 }
67                 elsif ( grep { $param eq $_ } @query_param_names ) {
68                     $filtered_params->{$param} = $params->{$param};
69                 }
70                 else {
71                     $path_params->{$param} = $params->{$param};
72                 }
73             }
74
75             return ( $filtered_params, $reserved_params, $path_params );
76         }
77     );
78
79 =head3 dbic_merge_sorting
80
81     $attributes = $c->dbic_merge_sorting({ attributes => $attributes, params => $params });
82
83 Generates the DBIC order_by attributes based on I<$params>, and merges into I<$attributes>.
84
85 =cut
86
87     $app->helper(
88         'dbic_merge_sorting' => sub {
89             my ( $c, $args ) = @_;
90             my $attributes = $args->{attributes};
91             my $result_set = $args->{result_set};
92
93             if ( defined $args->{params}->{_order_by} ) {
94                 my $order_by = $args->{params}->{_order_by};
95                 $order_by = [ split(/,/, $order_by) ] if ( index(',',$order_by) == -1);
96                 if ( reftype($order_by) and reftype($order_by) eq 'ARRAY' ) {
97                     my @order_by = map { _build_order_atom({ string => $_, result_set => $result_set }) }
98                                 @{ $order_by };
99                     $attributes->{order_by} = \@order_by;
100                 }
101                 else {
102                     $attributes->{order_by} = _build_order_atom({ string => $order_by, result_set => $result_set });
103                 }
104             }
105
106             return $attributes;
107         }
108     );
109
110 =head3 dbic_merge_prefetch
111
112     $attributes = $c->dbic_merge_prefetch({ attributes => $attributes, result_set => $result_set });
113
114 Generates the DBIC prefetch attribute based on embedded relations, and merges into I<$attributes>.
115
116 =cut
117
118     $app->helper(
119         'dbic_merge_prefetch' => sub {
120             my ( $c, $args ) = @_;
121             my $attributes = $args->{attributes};
122             my $result_set = $args->{result_set};
123             my $embed = $c->stash('koha.embed');
124
125             return unless defined $embed;
126
127             my @prefetches;
128             foreach my $key (sort keys(%{$embed})) {
129                 my $parsed = _parse_prefetch($key, $embed, $result_set);
130                 push @prefetches, $parsed if defined $parsed;
131             }
132
133             if(scalar(@prefetches)) {
134                 $attributes->{prefetch} = \@prefetches;
135             }
136         }
137     );
138
139 =head3 _build_query_params_from_api
140
141     my $params = _build_query_params_from_api( $filtered_params, $reserved_params );
142
143 Builds the params for searching on DBIC based on the selected matching algorithm.
144 Valid options are I<contains>, I<starts_with>, I<ends_with> and I<exact>. Default is
145 I<contains>. If other value is passed, a Koha::Exceptions::WrongParameter exception
146 is raised.
147
148 =cut
149
150     $app->helper(
151         'build_query_params' => sub {
152
153             my ( $c, $filtered_params, $reserved_params ) = @_;
154
155             my $params;
156             my $match = $reserved_params->{_match} // 'contains';
157
158             foreach my $param ( keys %{$filtered_params} ) {
159                 if ( $match eq 'contains' ) {
160                     $params->{$param} =
161                       { like => '%' . $filtered_params->{$param} . '%' };
162                 }
163                 elsif ( $match eq 'starts_with' ) {
164                     $params->{$param} = { like => $filtered_params->{$param} . '%' };
165                 }
166                 elsif ( $match eq 'ends_with' ) {
167                     $params->{$param} = { like => '%' . $filtered_params->{$param} };
168                 }
169                 elsif ( $match eq 'exact' ) {
170                     $params->{$param} = $filtered_params->{$param};
171                 }
172                 else {
173                     # We should never reach here, because the OpenAPI plugin should
174                     # prevent invalid params to be passed
175                     Koha::Exceptions::WrongParameter->throw(
176                         "Invalid value for _match param ($match)");
177                 }
178             }
179
180             return $params;
181         }
182     );
183
184 =head3 merge_q_params
185
186     $c->merge_q_params( $filtered_params, $q_params, $result_set );
187
188 Merges parameters from $q_params into $filtered_params.
189
190 =cut
191
192     $app->helper(
193         'merge_q_params' => sub {
194
195             my ( $c, $filtered_params, $q_params, $result_set ) = @_;
196
197             $q_params = decode_json($q_params) unless reftype $q_params;
198
199             my $params = _parse_dbic_query($q_params, $result_set);
200
201             return $params unless scalar(keys %{$filtered_params});
202             return {'-and' => [$params, $filtered_params ]};
203         }
204     );
205
206 =head3 stash_embed
207
208     $c->stash_embed( $c->match->endpoint->pattern->defaults->{'openapi.op_spec'} );
209
210 =cut
211
212     $app->helper(
213         'stash_embed' => sub {
214
215             my ( $c, $args ) = @_;
216
217             my $spec = $args->{spec} // {};
218
219             my $embed_spec   = $spec->{'x-koha-embed'};
220             my $embed_header = $c->req->headers->header('x-koha-embed');
221
222             Koha::Exceptions::BadParameter->throw("Embedding objects is not allowed on this endpoint.")
223                 if $embed_header and !defined $embed_spec;
224
225             if ( $embed_header ) {
226                 my $THE_embed = {};
227                 foreach my $embed_req ( split /\s*,\s*/, $embed_header ) {
228                     my $matches = grep {lc $_ eq lc $embed_req} @{ $embed_spec };
229
230                     Koha::Exceptions::BadParameter->throw(
231                         error => 'Embeding '.$embed_req. ' is not authorised. Check your x-koha-embed headers or remove it.'
232                     ) unless $matches;
233
234                     _merge_embed( _parse_embed($embed_req), $THE_embed);
235                 }
236
237                 $c->stash( 'koha.embed' => $THE_embed )
238                     if $THE_embed;
239             }
240
241             return $c;
242         }
243     );
244 }
245
246 =head2 Internal methods
247
248 =head3 _reserved_words
249
250     my $reserved_words = _reserved_words();
251
252 =cut
253
254 sub _reserved_words {
255
256     my @reserved_words = qw( _match _order_by _page _per_page q query x-koha-query);
257     return \@reserved_words;
258 }
259
260 =head3 _build_order_atom
261
262     my $order_atom = _build_order_atom( $string );
263
264 Parses I<$string> and outputs data valid for using in SQL::Abstract order_by attribute
265 according to the following rules:
266
267      string -> I<string>
268     +string -> I<{ -asc => string }>
269     -string -> I<{ -desc => string }>
270
271 =cut
272
273 sub _build_order_atom {
274     my ( $args )   = @_;
275     my $string     = $args->{string};
276     my $result_set = $args->{result_set};
277
278     my $param = $string;
279     $param =~ s/^(\+|\-|\s)//;
280     if ( $result_set ) {
281         my $model_param = _from_api_param($param, $result_set);
282         $param = $model_param if defined $model_param;
283     }
284
285     if ( $string =~ m/^\+/ or
286          $string =~ m/^\s/ ) {
287         # asc order operator present
288         return { -asc => $param };
289     }
290     elsif ( $string =~ m/^\-/ ) {
291         # desc order operator present
292         return { -desc => $param };
293     }
294     else {
295         # no order operator present
296         return $param;
297     }
298 }
299
300 =head3 _parse_embed
301
302     my $embed = _parse_embed( $string );
303
304 Parses I<$string> and outputs data valid for passing to the Kohaa::Object(s)->to_api
305 method.
306
307 =cut
308
309 sub _parse_embed {
310     my $string = shift;
311
312     my $result;
313     my ( $curr, $next ) = split /\s*\.\s*/, $string, 2;
314
315     if ( $next ) {
316         $result->{$curr} = { children => _parse_embed( $next ) };
317     }
318     else {
319         if ( $curr =~ m/^(?<relation>.*)\+count/ ) {
320             my $key = $+{relation} . "_count";
321             $result->{$key} = { is_count => 1 };
322         }
323         else {
324             $result->{$curr} = {};
325         }
326     }
327
328     return $result;
329 }
330
331 =head3 _merge_embed
332
333     _merge_embed( $parsed_embed, $global_embed );
334
335 Merges the hash referenced by I<$parsed_embed> into I<$global_embed>.
336
337 =cut
338
339 sub _merge_embed {
340     my ( $structure, $embed ) = @_;
341
342     my ($root) = keys %{ $structure };
343
344     if ( any { $root eq $_ } keys %{ $embed } ) {
345         # Recurse
346         _merge_embed( $structure->{$root}, $embed->{$root} );
347     }
348     else {
349         # Embed
350         $embed->{$root} = $structure->{$root};
351     }
352 }
353
354 sub _parse_prefetch {
355     my ( $key, $embed, $result_set) = @_;
356
357     my $pref_key = $key;
358     $pref_key =~ s/_count$// if $embed->{$key}->{is_count};
359     return unless exists $result_set->prefetch_whitelist->{$pref_key};
360
361     my $ko_class = $result_set->prefetch_whitelist->{$pref_key};
362     return $pref_key unless defined $embed->{$key}->{children} && defined $ko_class;
363
364     my @prefetches;
365     foreach my $child (sort keys(%{$embed->{$key}->{children}})) {
366         my $parsed = _parse_prefetch($child, $embed->{$key}->{children}, $ko_class->new);
367         push @prefetches, $parsed if defined $parsed;
368     }
369
370     return $pref_key unless scalar(@prefetches);
371
372     return {$pref_key => $prefetches[0]} if scalar(@prefetches) eq 1;
373
374     return {$pref_key => \@prefetches};
375 }
376
377 sub _from_api_param {
378     my ($key, $result_set) = @_;
379
380     if($key =~ /\./) {
381
382         my ($curr, $next) = split /\s*\.\s*/, $key, 2;
383
384         return $curr.'.'._from_api_param($next, $result_set) if $curr eq 'me';
385
386         my $ko_class = $result_set->prefetch_whitelist->{$curr};
387
388         Koha::Exceptions::BadParameter->throw("Cannot find Koha::Object class for $curr")
389             unless defined $ko_class;
390
391         $result_set = $ko_class->new;
392
393         if ($next =~ /\./) {
394             return _from_api_param($next, $result_set);
395         } else {
396             return $curr.'.'.($result_set->from_api_mapping && defined $result_set->from_api_mapping->{$next} ? $result_set->from_api_mapping->{$next}:$next);
397         }
398     } else {
399         return defined $result_set->from_api_mapping->{$key} ? $result_set->from_api_mapping->{$key} : $key;
400     }
401 }
402
403 sub _parse_dbic_query {
404     my ($q_params, $result_set) = @_;
405
406     if(reftype($q_params) && reftype($q_params) eq 'HASH') {
407         my $parsed_hash;
408         foreach my $key (keys %{$q_params}) {
409             if($key =~ /-?(not_?)?bool/i ) {
410                 $parsed_hash->{$key} = _from_api_param($q_params->{$key}, $result_set);
411                 next;
412             }
413             my $k = _from_api_param($key, $result_set);
414             $parsed_hash->{$k} = _parse_dbic_query($q_params->{$key}, $result_set);
415         }
416         return $parsed_hash;
417     } elsif (reftype($q_params) && reftype($q_params) eq 'ARRAY') {
418         my @mapped = map{ _parse_dbic_query($_, $result_set) } @$q_params;
419         return \@mapped;
420     } else {
421         return $q_params;
422     }
423
424 }
425
426 1;