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