Bug 27797: Make POST /holds use the stashed koha.overrides
[koha.git] / Koha / REST / V1 / Holds.pm
1 package Koha::REST::V1::Holds;
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 Mojo::JSON qw(decode_json);
23
24 use C4::Biblio;
25 use C4::Reserves;
26
27 use Koha::Items;
28 use Koha::Patrons;
29 use Koha::Holds;
30 use Koha::DateUtils;
31
32 use List::MoreUtils qw(any);
33 use Try::Tiny;
34
35 =head1 API
36
37 =head2 Methods
38
39 =head3 list
40
41 Method that handles listing Koha::Hold objects
42
43 =cut
44
45 sub list {
46     my $c = shift->openapi->valid_input or return;
47
48     return try {
49         my $holds_set = Koha::Holds->new;
50         my $holds     = $c->objects->search( $holds_set );
51         return $c->render( status => 200, openapi => $holds );
52     }
53     catch {
54         $c->unhandled_exception($_);
55     };
56 }
57
58 =head3 add
59
60 Method that handles adding a new Koha::Hold object
61
62 =cut
63
64 sub add {
65     my $c = shift->openapi->valid_input or return;
66
67     return try {
68         my $body = $c->validation->param('body');
69
70         my $biblio;
71         my $item;
72
73         my $biblio_id         = $body->{biblio_id};
74         my $pickup_library_id = $body->{pickup_library_id};
75         my $item_id           = $body->{item_id};
76         my $patron_id         = $body->{patron_id};
77         my $item_type         = $body->{item_type};
78         my $expiration_date   = $body->{expiration_date};
79         my $notes             = $body->{notes};
80         my $hold_date         = $body->{hold_date};
81         my $non_priority      = $body->{non_priority};
82
83         if(!C4::Context->preference( 'AllowHoldDateInFuture' ) && $hold_date) {
84             return $c->render(
85                 status  => 400,
86                 openapi => { error => "Hold date in future not allowed" }
87             );
88         }
89
90         if ( $item_id and $biblio_id ) {
91
92             # check they are consistent
93             unless ( Koha::Items->search( { itemnumber => $item_id, biblionumber => $biblio_id } )
94                 ->count > 0 )
95             {
96                 return $c->render(
97                     status  => 400,
98                     openapi => { error => "Item $item_id doesn't belong to biblio $biblio_id" }
99                 );
100             }
101             else {
102                 $biblio = Koha::Biblios->find($biblio_id);
103             }
104         }
105         elsif ($item_id) {
106             $item = Koha::Items->find($item_id);
107
108             unless ($item) {
109                 return $c->render(
110                     status  => 404,
111                     openapi => { error => "item_id not found." }
112                 );
113             }
114             else {
115                 $biblio = $item->biblio;
116             }
117         }
118         elsif ($biblio_id) {
119             $biblio = Koha::Biblios->find($biblio_id);
120         }
121         else {
122             return $c->render(
123                 status  => 400,
124                 openapi => { error => "At least one of biblio_id, item_id should be given" }
125             );
126         }
127
128         unless ($biblio) {
129             return $c->render(
130                 status  => 400,
131                 openapi => "Biblio not found."
132             );
133         }
134
135         my $patron = Koha::Patrons->find( $patron_id );
136         unless ($patron) {
137             return $c->render(
138                 status  => 400,
139                 openapi => { error => 'patron_id not found' }
140             );
141         }
142
143         # Validate pickup location
144         my $valid_pickup_location;
145         if ($item) {    # item-level hold
146             $valid_pickup_location =
147               any { $_->branchcode eq $pickup_library_id }
148             $item->pickup_locations(
149                 { patron => $patron } );
150         }
151         else {
152             $valid_pickup_location =
153               any { $_->branchcode eq $pickup_library_id }
154             $biblio->pickup_locations(
155                 { patron => $patron } );
156         }
157
158         return $c->render(
159             status  => 400,
160             openapi => {
161                 error => 'The supplied pickup location is not valid'
162             }
163         ) unless $valid_pickup_location;
164
165         my $can_place_hold
166             = $item_id
167             ? C4::Reserves::CanItemBeReserved( $patron_id, $item_id )
168             : C4::Reserves::CanBookBeReserved( $patron_id, $biblio_id );
169
170         if ( $patron->holds->count + 1 > C4::Context->preference('maxreserves') ) {
171             $can_place_hold->{status} = 'tooManyReserves';
172         }
173
174         my $overrides = $c->stash('koha.overrides');
175         my $can_override = $overrides->{any} and C4::Context->preference('AllowHoldPolicyOverride');
176
177         unless ( $can_override || $can_place_hold->{status} eq 'OK' ) {
178             return $c->render(
179                 status => 403,
180                 openapi =>
181                     { error => "Hold cannot be placed. Reason: " . $can_place_hold->{status} }
182             );
183         }
184
185         my $priority = C4::Reserves::CalculatePriority($biblio_id);
186
187         # AddReserve expects date to be in syspref format
188         if ($expiration_date) {
189             $expiration_date = output_pref( dt_from_string( $expiration_date, 'rfc3339' ) );
190         }
191
192         my $hold_id = C4::Reserves::AddReserve(
193             {
194                 branchcode       => $pickup_library_id,
195                 borrowernumber   => $patron_id,
196                 biblionumber     => $biblio_id,
197                 priority         => $priority,
198                 reservation_date => $hold_date,
199                 expiration_date  => $expiration_date,
200                 notes            => $notes,
201                 title            => $biblio->title,
202                 itemnumber       => $item_id,
203                 found            => undef,                # TODO: Why not?
204                 itemtype         => $item_type,
205                 non_priority     => $non_priority,
206             }
207         );
208
209         unless ($hold_id) {
210             return $c->render(
211                 status  => 500,
212                 openapi => 'Error placing the hold. See Koha logs for details.'
213             );
214         }
215
216         my $hold = Koha::Holds->find($hold_id);
217
218         return $c->render(
219             status  => 201,
220             openapi => $hold->to_api
221         );
222     }
223     catch {
224         if ( blessed $_ and $_->isa('Koha::Exceptions') ) {
225             if ( $_->isa('Koha::Exceptions::Object::FKConstraint') ) {
226                 my $broken_fk = $_->broken_fk;
227
228                 if ( grep { $_ eq $broken_fk } keys %{Koha::Holds->new->to_api_mapping} ) {
229                     $c->render(
230                         status  => 404,
231                         openapi => Koha::Holds->new->to_api_mapping->{$broken_fk} . ' not found.'
232                     );
233                 }
234             }
235         }
236
237         $c->unhandled_exception($_);
238     };
239 }
240
241 =head3 edit
242
243 Method that handles modifying a Koha::Hold object
244
245 =cut
246
247 sub edit {
248     my $c = shift->openapi->valid_input or return;
249
250     return try {
251         my $hold_id = $c->validation->param('hold_id');
252         my $hold = Koha::Holds->find( $hold_id );
253
254         unless ($hold) {
255             return $c->render( status  => 404,
256                             openapi => {error => "Hold not found"} );
257         }
258
259         my $body = $c->req->json;
260
261         my $pickup_library_id = $body->{pickup_library_id};
262
263         if (
264             defined $pickup_library_id
265             and not $hold->is_pickup_location_valid({ library_id => $pickup_library_id })
266           )
267         {
268             return $c->render(
269                 status  => 400,
270                 openapi => {
271                     error => 'The supplied pickup location is not valid'
272                 }
273             );
274         }
275
276         $pickup_library_id    //= $hold->branchcode;
277         my $priority          = $body->{priority} // $hold->priority;
278         # suspended_until can also be set to undef
279         my $suspended_until   = exists $body->{suspended_until} ? $body->{suspended_until} : $hold->suspend_until;
280
281         my $params = {
282             reserve_id    => $hold_id,
283             branchcode    => $pickup_library_id,
284             rank          => $priority,
285             suspend_until => $suspended_until ? output_pref(dt_from_string($suspended_until, 'rfc3339')) : '',
286             itemnumber    => $hold->itemnumber
287         };
288
289         C4::Reserves::ModReserve($params);
290         $hold->discard_changes; # refresh
291
292         return $c->render(
293             status  => 200,
294             openapi => $hold->to_api
295         );
296     }
297     catch {
298         $c->unhandled_exception($_);
299     };
300 }
301
302 =head3 delete
303
304 Method that handles deleting a Koha::Hold object
305
306 =cut
307
308 sub delete {
309     my $c = shift->openapi->valid_input or return;
310
311     my $hold_id = $c->validation->param('hold_id');
312     my $hold    = Koha::Holds->find($hold_id);
313
314     unless ($hold) {
315         return $c->render( status => 404, openapi => { error => "Hold not found." } );
316     }
317
318     return try {
319         $hold->cancel;
320
321         return $c->render(
322             status  => 204,
323             openapi => q{}
324         );
325     }
326     catch {
327         $c->unhandled_exception($_);
328     };
329 }
330
331 =head3 suspend
332
333 Method that handles suspending a hold
334
335 =cut
336
337 sub suspend {
338     my $c = shift->openapi->valid_input or return;
339
340     my $hold_id  = $c->validation->param('hold_id');
341     my $hold     = Koha::Holds->find($hold_id);
342     my $body     = $c->req->json;
343     my $end_date = ($body) ? $body->{end_date} : undef;
344
345     unless ($hold) {
346         return $c->render( status => 404, openapi => { error => 'Hold not found.' } );
347     }
348
349     return try {
350         my $date = ($end_date) ? dt_from_string( $end_date, 'rfc3339' ) : undef;
351         $hold->suspend_hold($date);
352         $hold->discard_changes;
353         $c->res->headers->location( $c->req->url->to_string );
354         my $suspend_end_date;
355         if ($hold->suspend_until) {
356             $suspend_end_date = output_pref({
357                 dt         => dt_from_string( $hold->suspend_until ),
358                 dateformat => 'rfc3339',
359                 dateonly   => 1
360                 }
361             );
362         }
363         return $c->render(
364             status  => 201,
365             openapi => {
366                 end_date => $suspend_end_date
367             }
368         );
369     }
370     catch {
371         if ( blessed $_ and $_->isa('Koha::Exceptions::Hold::CannotSuspendFound') ) {
372             return $c->render( status => 400, openapi => { error => "$_" } );
373         }
374
375         $c->unhandled_exception($_);
376     };
377 }
378
379 =head3 resume
380
381 Method that handles resuming a hold
382
383 =cut
384
385 sub resume {
386     my $c = shift->openapi->valid_input or return;
387
388     my $hold_id = $c->validation->param('hold_id');
389     my $hold    = Koha::Holds->find($hold_id);
390     my $body    = $c->req->json;
391
392     unless ($hold) {
393         return $c->render( status => 404, openapi => { error => 'Hold not found.' } );
394     }
395
396     return try {
397         $hold->resume;
398         return $c->render( status => 204, openapi => {} );
399     }
400     catch {
401         $c->unhandled_exception($_);
402     };
403 }
404
405 =head3 update_priority
406
407 Method that handles modifying a Koha::Hold object
408
409 =cut
410
411 sub update_priority {
412     my $c = shift->openapi->valid_input or return;
413
414     my $hold_id = $c->validation->param('hold_id');
415     my $hold = Koha::Holds->find($hold_id);
416
417     unless ($hold) {
418         return $c->render(
419             status  => 404,
420             openapi => { error => "Hold not found" }
421         );
422     }
423
424     return try {
425         my $priority = $c->req->json;
426         C4::Reserves::_FixPriority(
427             {
428                 reserve_id => $hold_id,
429                 rank       => $priority
430             }
431         );
432
433         return $c->render( status => 200, openapi => $priority );
434     }
435     catch {
436         $c->unhandled_exception($_);
437     };
438 }
439
440 =head3 pickup_locations
441
442 Method that returns the possible pickup_locations for a given hold
443 used for building the dropdown selector
444
445 =cut
446
447 sub pickup_locations {
448     my $c = shift->openapi->valid_input or return;
449
450     my $hold_id = $c->validation->param('hold_id');
451     my $hold = Koha::Holds->find( $hold_id, { prefetch => [ 'patron' ] } );
452
453     unless ($hold) {
454         return $c->render(
455             status  => 404,
456             openapi => { error => "Hold not found" }
457         );
458     }
459
460     return try {
461         my $ps_set;
462
463         if ( $hold->itemnumber ) {
464             $ps_set = $hold->item->pickup_locations( { patron => $hold->patron } );
465         }
466         else {
467             $ps_set = $hold->biblio->pickup_locations( { patron => $hold->patron } );
468         }
469
470         my $pickup_locations = $c->objects->search( $ps_set );
471         my @response = ();
472
473         if ( C4::Context->preference('AllowHoldPolicyOverride') ) {
474
475             my $libraries_rs = Koha::Libraries->search( { pickup_location => 1 } );
476             my $libraries    = $c->objects->search($libraries_rs);
477
478             @response = map {
479                 my $library = $_;
480                 $library->{needs_override} = (
481                     any { $_->{library_id} eq $library->{library_id} }
482                     @{$pickup_locations}
483                   )
484                   ? Mojo::JSON->false
485                   : Mojo::JSON->true;
486                 $library;
487             } @{$libraries};
488
489             return $c->render(
490                 status  => 200,
491                 openapi => \@response
492             );
493         }
494
495         @response = map { $_->{needs_override} = Mojo::JSON->false; $_; } @{$pickup_locations};
496
497         return $c->render(
498             status  => 200,
499             openapi => \@response
500         );
501     }
502     catch {
503         $c->unhandled_exception($_);
504     };
505 }
506
507 =head3 update_pickup_location
508
509 Method that handles modifying the pickup location of a Koha::Hold object
510
511 =cut
512
513 sub update_pickup_location {
514     my $c = shift->openapi->valid_input or return;
515
516     my $hold_id = $c->validation->param('hold_id');
517     my $body    = $c->validation->param('body');
518     my $pickup_library_id = $body->{pickup_library_id};
519
520     my $hold = Koha::Holds->find($hold_id);
521
522     unless ($hold) {
523         return $c->render(
524             status  => 404,
525             openapi => { error => "Hold not found" }
526         );
527     }
528
529     return try {
530
531         $hold->set_pickup_location({ library_id => $pickup_library_id });
532
533         return $c->render(
534             status  => 200,
535             openapi => {
536                 pickup_library_id => $pickup_library_id
537             }
538         );
539     }
540     catch {
541
542         if ( blessed $_ and $_->isa('Koha::Exceptions::Hold::InvalidPickupLocation') ) {
543             return $c->render(
544                 status  => 400,
545                 openapi => {
546                     error => "$_"
547                 }
548             );
549         }
550
551         $c->unhandled_exception($_);
552     };
553 }
554
555
556 1;