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