Bug 20212: Use the DT column filtering provided by the wrapper
[koha.git] / Koha / REST / V1 / Acquisitions / Orders.pm
1 package Koha::REST::V1::Acquisitions::Orders;
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::Controller';
21
22 use Koha::Acquisition::Orders;
23 use Koha::DateUtils;
24
25 use Clone 'clone';
26 use JSON qw(decode_json);
27 use Scalar::Util qw( blessed );
28 use Try::Tiny;
29
30 =head1 NAME
31
32 Koha::REST::V1::Acquisitions::Orders
33
34 =head1 API
35
36 =head2 Methods
37
38 =head3 list
39
40 Controller function that handles listing Koha::Acquisition::Order objects
41
42 =cut
43
44 sub list {
45
46     my $c = shift->openapi->valid_input or return;
47
48     return try {
49
50         my $only_active = delete $c->validation->output->{only_active};
51         my $order_id    = delete $c->validation->output->{order_id};
52
53         my $orders_rs;
54
55         if ( $only_active ) {
56             $orders_rs = Koha::Acquisition::Orders->filter_by_active;
57         }
58         else {
59             $orders_rs = Koha::Acquisition::Orders->new;
60         }
61
62         $orders_rs = $orders_rs->filter_by_id_including_transfers({ ordernumber => $order_id })
63             if $order_id;
64
65         my $args = $c->validation->output;
66         my $attributes = {};
67
68         # Extract reserved params
69         my ( $filtered_params, $reserved_params, $path_params ) = $c->extract_reserved_params($args);
70         # Look for embeds
71         my $embed = $c->stash('koha.embed');
72         my $fixed_embed = clone($embed);
73         if ( exists $fixed_embed->{biblio} ) {
74             # Add biblioitems to prefetch
75             # FIXME remove if we merge biblio + biblioitems
76             $fixed_embed->{biblio}->{children}->{biblioitem} = {};
77             $c->stash('koha.embed', $fixed_embed);
78         }
79
80         # If no pagination parameters are passed, default
81         $reserved_params->{_per_page} //= C4::Context->preference('RESTdefaultPageSize');
82         $reserved_params->{_page}     //= 1;
83
84         unless ( $reserved_params->{_per_page} == -1 ) {
85             # Merge pagination into query attributes
86             $c->dbic_merge_pagination(
87                 {
88                     filter => $attributes,
89                     params => $reserved_params
90                 }
91             );
92         }
93
94         # Generate prefetches for embedded stuff
95         $c->dbic_merge_prefetch(
96             {
97                 attributes => $attributes,
98                 result_set => $orders_rs
99             }
100         );
101
102         # Call the to_model function by reference, if defined
103         if ( defined $filtered_params ) {
104
105             # Apply the mapping function to the passed params
106             $filtered_params = $orders_rs->attributes_from_api($filtered_params);
107             $filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
108         }
109
110         if ( defined $path_params ) {
111
112             # Apply the mapping function to the passed params
113             $filtered_params //= {};
114             $path_params = $orders_rs->attributes_from_api($path_params);
115             foreach my $param (keys %{$path_params}) {
116                 $filtered_params->{$param} = $path_params->{$param};
117             }
118         }
119
120         if ( defined $reserved_params->{q} || defined $reserved_params->{query} || defined $reserved_params->{'x-koha-query'}) {
121             $filtered_params //={};
122             my @query_params_array;
123             my $query_params;
124             if ( exists $reserved_params->{query} and defined $reserved_params->{query} ) {
125                 push @query_params_array, fix_query({ query => $reserved_params->{query} });
126             }
127             if ( exists $reserved_params->{q} and defined $reserved_params->{q}) {
128                 push @query_params_array, fix_query({ query => decode_json($reserved_params->{q}) });
129             }
130             if ( exists $reserved_params->{'x-koha-query'} and defined $reserved_params->{'x-koha-query'} ) {
131                 push @query_params_array, fix_query({ query => decode_json($reserved_params->{'x-koha-query'}) });;
132             }
133
134             if(scalar(@query_params_array) > 1) {
135                 $query_params = {'-and' => \@query_params_array};
136             }
137             else {
138                 $query_params = $query_params_array[0];
139             }
140
141             $filtered_params = $c->merge_q_params( $filtered_params, $query_params, $orders_rs );
142         }
143
144         # Perform search
145         my $orders = $orders_rs->search( $filtered_params, $attributes );
146         my $total  = $orders_rs->search->count;
147
148         $c->add_pagination_headers(
149             {
150                 total      => ($orders->is_paged ? $orders->pager->total_entries : $orders->count),
151                 base_total => $total,
152                 params     => $args,
153             }
154         );
155
156         return $c->render(
157             status  => 200,
158             openapi => $orders->to_api({ embed => $embed })
159         );
160     }
161     catch {
162         $c->unhandled_exception($_);
163     };
164 }
165
166 =head3 get
167
168 Controller function that handles retrieving a single Koha::Acquisition::Order object
169
170 =cut
171
172 sub get {
173     my $c = shift->openapi->valid_input or return;
174
175     my $order = Koha::Acquisition::Orders->find( $c->validation->param('order_id') );
176
177     unless ($order) {
178         return $c->render(
179             status  => 404,
180             openapi => { error => "Order not found" }
181         );
182     }
183
184     return try {
185         my $embed = $c->stash('koha.embed');
186
187         return $c->render(
188             status  => 200,
189             openapi => $order->to_api({ embed => $embed })
190         );
191     }
192     catch {
193         $c->unhandled_exception($_);
194     };
195 }
196
197 =head3 add
198
199 Controller function that handles adding a new Koha::Acquisition::Order object
200
201 =cut
202
203 sub add {
204     my $c = shift->openapi->valid_input or return;
205
206     return try {
207         my $order = Koha::Acquisition::Order->new_from_api( $c->validation->param('body') );
208         $order->store->discard_changes;
209
210         $c->res->headers->location(
211             $c->req->url->to_string . '/' . $order->ordernumber
212         );
213
214         return $c->render(
215             status  => 201,
216             openapi => $order->to_api
217         );
218     }
219     catch {
220         if ( blessed $_ and $_->isa('Koha::Exceptions::Object::DuplicateID') ) {
221             return $c->render(
222                 status  => 409,
223                 openapi => { error => $_->error, conflict => $_->duplicate_id }
224             );
225         }
226
227         $c->unhandled_exception($_);
228     };
229 }
230
231 =head3 update
232
233 Controller function that handles updating a Koha::Acquisition::Order object
234
235 =cut
236
237 sub update {
238     my $c = shift->openapi->valid_input or return;
239
240     my $order = Koha::Acquisition::Orders->find( $c->validation->param('order_id') );
241
242     unless ($order) {
243         return $c->render(
244             status  => 404,
245             openapi => { error => "Order not found" }
246         );
247     }
248
249     return try {
250         $order->set_from_api( $c->validation->param('body') );
251         $order->store()->discard_changes;
252
253         return $c->render(
254             status  => 200,
255             openapi => $order->to_api
256         );
257     }
258     catch {
259         $c->unhandled_exception($_);
260     };
261 }
262
263 =head3 delete
264
265 Controller function that handles deleting a Koha::Patron object
266
267 =cut
268
269 sub delete {
270     my $c = shift->openapi->valid_input or return;
271
272     my $order = Koha::Acquisition::Orders->find( $c->validation->param('order_id') );
273
274     unless ($order) {
275         return $c->render(
276             status  => 404,
277             openapi => { error => 'Order not found' }
278         );
279     }
280
281     return try {
282
283         $order->delete;
284
285         return $c->render(
286             status  => 204,
287             openapi => q{}
288         );
289     }
290     catch {
291         $c->unhandled_exception($_);
292     };
293 }
294
295 =head2 Internal methods
296
297 =head3 fix_query
298
299     my $query = fix_query($query);
300
301 This method takes care of recursively fixing queries that should be done
302 against biblioitems (instead if biblio as exposed on the API)
303
304 =cut
305
306 sub fix_query {
307     my ($args) = @_;
308
309     my $query = $args->{query};
310     my $biblioitem_fields = {
311         'biblio.age_restriction'     => 'biblio.biblioitem.age_restriction',
312         'biblio.cn_class'            => 'biblio.biblioitem.cn_class',
313         'biblio.cn_item'             => 'biblio.biblioitem.cn_item',
314         'biblio.cn_sort'             => 'biblio.biblioitem.cn_sort',
315         'biblio.cn_source'           => 'biblio.biblioitem.cn_source',
316         'biblio.cn_suffix'           => 'biblio.biblioitem.cn_suffix',
317         'biblio.collection_issn'     => 'biblio.biblioitem.collection_issn',
318         'biblio.collection_title'    => 'biblio.biblioitem.collection_title',
319         'biblio.collection_volume'   => 'biblio.biblioitem.collection_volume',
320         'biblio.ean'                 => 'biblio.biblioitem.ean',
321         'biblio.edition_statement'   => 'biblio.biblioitem.edition_statement',
322         'biblio.illustrations'       => 'biblio.biblioitem.illustrations',
323         'biblio.isbn'                => 'biblio.biblioitem.isbn',
324         'biblio.issn'                => 'biblio.biblioitem.issn',
325         'biblio.item_type'           => 'biblio.biblioitem.item_type',
326         'biblio.lc_control_number'   => 'biblio.biblioitem.lc_control_number',
327         'biblio.material_size'       => 'biblio.biblioitem.material_size',
328         'biblio.notes'               => 'biblio.biblioitem.notes',
329         'biblio.number'              => 'biblio.biblioitem.number',
330         'biblio.pages'               => 'biblio.biblioitem.pages',
331         'biblio.publication_place'   => 'biblio.biblioitem.publication_place',
332         'biblio.publication_year'    => 'biblio.biblioitem.publication_year',
333         'biblio.publisher'           => 'biblio.biblioitem.publisher',
334         'biblio.serial_total_issues' => 'biblio.biblioitem.serial_total_issues',
335         'biblio.url'                 => 'biblio.biblioitem.url',
336         'biblio.volume'              => 'biblio.biblioitem.volume',
337         'biblio.volume_date'         => 'biblio.biblioitem.volume_date',
338         'biblio.volume_description'  => 'biblio.biblioitem.volume_description',
339     };
340
341     if ( ref($query) eq 'HASH' ) {
342         foreach my $key (keys %{$query}) {
343             if ( exists $biblioitem_fields->{$key}) {
344                 my $subq = delete $query->{$key};
345                 $query->{$biblioitem_fields->{$key}} = (ref($subq) eq 'HASH')
346                         ? fix_query({ query => $subq })
347                         : $subq;
348             }
349             else {
350                 $query->{$key} = fix_query({ query => $query->{$key} });
351             }
352         }
353     }
354     elsif ( ref($query) eq 'ARRAY' ) {
355         my @accum;
356         foreach my $item (@{$query}) {
357             push @accum, fix_query({ query => $item });
358         }
359         $query = \@accum;
360     }
361     else { # scalar
362         $query = $biblioitem_fields->{$query}
363             if exists $biblioitem_fields->{$query};
364     }
365
366     return $query;
367 }
368
369 1;