Bug 23710: (follow-up) Human readable error messages in request.tt, check AllowHoldPo...
[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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 use Modern::Perl;
19
20 use Mojo::Base 'Mojolicious::Controller';
21
22 use C4::Biblio;
23 use C4::Reserves;
24
25 use Koha::Items;
26 use Koha::Patrons;
27 use Koha::Holds;
28 use Koha::DateUtils;
29
30 use Try::Tiny;
31
32 =head1 API
33
34 =head2 Class methods
35
36 =head3 list
37
38 Mehtod that handles listing Koha::Hold objects
39
40 =cut
41
42 sub list {
43     my $c = shift->openapi->valid_input or return;
44
45     return try {
46         my $holds_set = Koha::Holds->new;
47         my $holds     = $c->objects->search( $holds_set, \&_to_model, \&_to_api );
48         return $c->render( status => 200, openapi => $holds );
49     }
50     catch {
51         if ( blessed $_ && $_->isa('Koha::Exceptions') ) {
52             return $c->render(
53                 status  => 500,
54                 openapi => { error => "$_" }
55             );
56         }
57         else {
58             return $c->render(
59                 status  => 500,
60                 openapi => { error => "Something went wrong, check Koha logs for details." }
61             );
62         }
63     };
64 }
65
66 =head3 add
67
68 Method that handles adding a new Koha::Hold object
69
70 =cut
71
72 sub add {
73     my $c = shift->openapi->valid_input or return;
74
75     return try {
76         my $body = $c->validation->param('body');
77
78         my $biblio;
79
80         my $biblio_id         = $body->{biblio_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         = C4::Context->preference( 'AllowHoldDateInFuture' )?$body->{hold_date}:undef;
88
89         if ( $item_id and $biblio_id ) {
90
91             # check they are consistent
92             unless ( Koha::Items->search( { itemnumber => $item_id, biblionumber => $biblio_id } )
93                 ->count > 0 )
94             {
95                 return $c->render(
96                     status  => 400,
97                     openapi => { error => "Item $item_id doesn't belong to biblio $biblio_id" }
98                 );
99             }
100             else {
101                 $biblio = Koha::Biblios->find($biblio_id);
102             }
103         }
104         elsif ($item_id) {
105             my $item = Koha::Items->find($item_id);
106
107             unless ($item) {
108                 return $c->render(
109                     status  => 404,
110                     openapi => { error => "item_id not found." }
111                 );
112             }
113             else {
114                 $biblio = $item->biblio;
115             }
116         }
117         elsif ($biblio_id) {
118             $biblio = Koha::Biblios->find($biblio_id);
119         }
120         else {
121             return $c->render(
122                 status  => 400,
123                 openapi => { error => "At least one of biblio_id, item_id should be given" }
124             );
125         }
126
127         unless ($biblio) {
128             return $c->render(
129                 status  => 400,
130                 openapi => "Biblio not found."
131             );
132         }
133
134         my $can_place_hold
135             = $item_id
136             ? C4::Reserves::CanItemBeReserved( $patron_id, $item_id )
137             : C4::Reserves::CanBookBeReserved( $patron_id, $biblio_id );
138
139         my $can_override = C4::Context->preference('AllowHoldPolicyOverride');
140
141         unless ($can_override || $can_place_hold->{status} eq 'OK' ) {
142             return $c->render(
143                 status => 403,
144                 openapi =>
145                     { error => "Hold cannot be placed. Reason: " . $can_place_hold->{status} }
146             );
147         }
148
149         my $priority = C4::Reserves::CalculatePriority($biblio_id);
150
151         # AddReserve expects date to be in syspref format
152         if ($expiration_date) {
153             $expiration_date = output_pref( dt_from_string( $expiration_date, 'rfc3339' ) );
154         }
155
156         my $hold_id = C4::Reserves::AddReserve(
157             $pickup_library_id,
158             $patron_id,
159             $biblio_id,
160             undef,    # $bibitems param is unused
161             $priority,
162             $hold_date,
163             $expiration_date,
164             $notes,
165             $biblio->title,
166             $item_id,
167             undef,    # TODO: Why not?
168             $item_type
169         );
170
171         unless ($hold_id) {
172             return $c->render(
173                 status  => 500,
174                 openapi => 'Error placing the hold. See Koha logs for details.'
175             );
176         }
177
178         my $hold = Koha::Holds->find($hold_id);
179
180         return $c->render( status => 201, openapi => _to_api($hold->TO_JSON) );
181     }
182     catch {
183         if ( blessed $_ and $_->isa('Koha::Exceptions') ) {
184             if ( $_->isa('Koha::Exceptions::Object::FKConstraint') ) {
185                 my $broken_fk = $_->broken_fk;
186
187                 if ( grep { $_ eq $broken_fk } keys %{$Koha::REST::V1::Holds::to_api_mapping} ) {
188                     $c->render(
189                         status  => 404,
190                         openapi => $Koha::REST::V1::Holds::to_api_mapping->{$broken_fk} . ' not found.'
191                     );
192                 }
193                 else {
194                     return $c->render(
195                         status  => 500,
196                         openapi => { error => "Uncaught exception: $_" }
197                     );
198                 }
199             }
200             else {
201                 return $c->render(
202                     status  => 500,
203                     openapi => { error => "$_" }
204                 );
205             }
206         }
207         else {
208             return $c->render(
209                 status  => 500,
210                 openapi => { error => "Something went wrong. check the logs." }
211             );
212         }
213     };
214 }
215
216 =head3 edit
217
218 Method that handles modifying a Koha::Hold object
219
220 =cut
221
222 sub edit {
223     my $c = shift->openapi->valid_input or return;
224
225     my $hold_id = $c->validation->param('hold_id');
226     my $hold = Koha::Holds->find( $hold_id );
227
228     unless ($hold) {
229         return $c->render( status  => 404,
230                            openapi => {error => "Hold not found"} );
231     }
232
233     my $body = $c->req->json;
234
235     my $pickup_library_id = $body->{pickup_library_id};
236     my $priority          = $body->{priority};
237     my $suspended_until   = $body->{suspended_until};
238
239     if ($suspended_until) {
240         $suspended_until = output_pref(dt_from_string($suspended_until, 'rfc3339'));
241     }
242
243     my $params = {
244         reserve_id    => $hold_id,
245         branchcode    => $pickup_library_id,
246         rank          => $priority,
247         suspend_until => $suspended_until,
248         itemnumber    => $hold->itemnumber
249     };
250
251     C4::Reserves::ModReserve($params);
252     $hold->discard_changes; # refresh
253
254     return $c->render( status => 200, openapi => _to_api( $hold->TO_JSON ) );
255 }
256
257 =head3 delete
258
259 Method that handles deleting a Koha::Hold object
260
261 =cut
262
263 sub delete {
264     my $c = shift->openapi->valid_input or return;
265
266     my $hold_id = $c->validation->param('hold_id');
267     my $hold    = Koha::Holds->find($hold_id);
268
269     unless ($hold) {
270         return $c->render( status => 404, openapi => { error => "Hold not found." } );
271     }
272
273     $hold->cancel;
274
275     return $c->render( status => 200, openapi => {} );
276 }
277
278 =head3 suspend
279
280 Method that handles suspending a hold
281
282 =cut
283
284 sub suspend {
285     my $c = shift->openapi->valid_input or return;
286
287     my $hold_id  = $c->validation->param('hold_id');
288     my $hold     = Koha::Holds->find($hold_id);
289     my $body     = $c->req->json;
290     my $end_date = ($body) ? $body->{end_date} : undef;
291
292     unless ($hold) {
293         return $c->render( status => 404, openapi => { error => 'Hold not found.' } );
294     }
295
296     return try {
297         my $date = ($end_date) ? dt_from_string( $end_date, 'rfc3339' ) : undef;
298         $hold->suspend_hold($date);
299         $hold->discard_changes;
300         $c->res->headers->location( $c->req->url->to_string );
301         return $c->render(
302             status  => 201,
303             openapi => {
304                 end_date => output_pref(
305                     {   dt         => dt_from_string( $hold->suspend_until ),
306                         dateformat => 'rfc3339',
307                         dateonly   => 1
308                     }
309                 )
310             }
311         );
312     }
313     catch {
314         if ( blessed $_ and $_->isa('Koha::Exceptions::Hold::CannotSuspendFound') ) {
315             return $c->render( status => 400, openapi => { error => "$_" } );
316         }
317         else {
318             return $c->render(
319                 status  => 500,
320                 openapi => { error => "Something went wrong. check the logs." }
321             );
322         }
323     };
324 }
325
326 =head3 resume
327
328 Method that handles resuming a hold
329
330 =cut
331
332 sub resume {
333     my $c = shift->openapi->valid_input or return;
334
335     my $hold_id = $c->validation->param('hold_id');
336     my $hold    = Koha::Holds->find($hold_id);
337     my $body    = $c->req->json;
338
339     unless ($hold) {
340         return $c->render( status => 404, openapi => { error => 'Hold not found.' } );
341     }
342
343     return try {
344         $hold->resume;
345         return $c->render( status => 204, openapi => {} );
346     }
347     catch {
348         return $c->render(
349             status  => 500,
350             openapi => { error => "Something went wrong. check the logs." }
351         );
352     };
353 }
354
355 =head3 update_priority
356
357 Method that handles modifying a Koha::Hold object
358
359 =cut
360
361 sub update_priority {
362     my $c = shift->openapi->valid_input or return;
363
364     my $hold_id = $c->validation->param('hold_id');
365     my $hold = Koha::Holds->find($hold_id);
366
367     unless ($hold) {
368         return $c->render(
369             status  => 404,
370             openapi => { error => "Hold not found" }
371         );
372     }
373
374     return try {
375         my $priority = $c->req->json;
376         C4::Reserves::_FixPriority(
377             {
378                 reserve_id => $hold_id,
379                 rank       => $priority
380             }
381         );
382
383         return $c->render( status => 200, openapi => $priority );
384     }
385     catch {
386         return $c->render(
387             status  => 500,
388             openapi => { error => "Something went wrong. check the logs." }
389         );
390     };
391 }
392
393 =head2 Internal methods
394
395 =head3 _to_api
396
397 Helper function that maps unblessed Koha::Hold objects into REST api
398 attribute names.
399
400 =cut
401
402 sub _to_api {
403     my $hold = shift;
404
405     # Rename attributes
406     foreach my $column ( keys %{ $Koha::REST::V1::Holds::to_api_mapping } ) {
407         my $mapped_column = $Koha::REST::V1::Holds::to_api_mapping->{$column};
408         if (    exists $hold->{ $column }
409              && defined $mapped_column )
410         {
411             # key != undef
412             $hold->{ $mapped_column } = delete $hold->{ $column };
413         }
414         elsif (    exists $hold->{ $column }
415                 && !defined $mapped_column )
416         {
417             # key == undef
418             delete $hold->{ $column };
419         }
420     }
421
422     return $hold;
423 }
424
425 =head3 _to_model
426
427 Helper function that maps REST api objects into Koha::Hold
428 attribute names.
429
430 =cut
431
432 sub _to_model {
433     my $hold = shift;
434
435     foreach my $attribute ( keys %{ $Koha::REST::V1::Holds::to_model_mapping } ) {
436         my $mapped_attribute = $Koha::REST::V1::Holds::to_model_mapping->{$attribute};
437         if (    exists $hold->{ $attribute }
438              && defined $mapped_attribute )
439         {
440             # key => !undef
441             $hold->{ $mapped_attribute } = delete $hold->{ $attribute };
442         }
443         elsif (    exists $hold->{ $attribute }
444                 && !defined $mapped_attribute )
445         {
446             # key => undef / to be deleted
447             delete $hold->{ $attribute };
448         }
449     }
450
451     if ( exists $hold->{lowestPriority} ) {
452         $hold->{lowestPriority} = ($hold->{lowestPriority}) ? 1 : 0;
453     }
454
455     if ( exists $hold->{suspend} ) {
456         $hold->{suspend} = ($hold->{suspend}) ? 1 : 0;
457     }
458
459     if ( exists $hold->{reservedate} ) {
460         $hold->{reservedate} = output_pref({ str => $hold->{reservedate}, dateformat => 'sql' });
461     }
462
463     if ( exists $hold->{cancellationdate} ) {
464         $hold->{cancellationdate} = output_pref({ str => $hold->{cancellationdate}, dateformat => 'sql' });
465     }
466
467     if ( exists $hold->{timestamp} ) {
468         $hold->{timestamp} = output_pref({ str => $hold->{timestamp}, dateformat => 'sql' });
469     }
470
471     if ( exists $hold->{waitingdate} ) {
472         $hold->{waitingdate} = output_pref({ str => $hold->{waitingdate}, dateformat => 'sql' });
473     }
474
475     if ( exists $hold->{expirationdate} ) {
476         $hold->{expirationdate} = output_pref({ str => $hold->{expirationdate}, dateformat => 'sql' });
477     }
478
479     if ( exists $hold->{suspend_until} ) {
480         $hold->{suspend_until} = output_pref({ str => $hold->{suspend_until}, dateformat => 'sql' });
481     }
482
483     return $hold;
484 }
485
486 =head2 Global variables
487
488 =head3 $to_api_mapping
489
490 =cut
491
492 our $to_api_mapping = {
493     reserve_id       => 'hold_id',
494     borrowernumber   => 'patron_id',
495     reservedate      => 'hold_date',
496     biblionumber     => 'biblio_id',
497     branchcode       => 'pickup_library_id',
498     notificationdate => undef,
499     reminderdate     => undef,
500     cancellationdate => 'cancelation_date',
501     reservenotes     => 'notes',
502     found            => 'status',
503     itemnumber       => 'item_id',
504     waitingdate      => 'waiting_date',
505     expirationdate   => 'expiration_date',
506     lowestPriority   => 'lowest_priority',
507     suspend          => 'suspended',
508     suspend_until    => 'suspended_until',
509     itemtype         => 'item_type',
510     item_level_hold  => 'item_level',
511 };
512
513 =head3 $to_model_mapping
514
515 =cut
516
517 our $to_model_mapping = {
518     hold_id           => 'reserve_id',
519     patron_id         => 'borrowernumber',
520     hold_date         => 'reservedate',
521     biblio_id         => 'biblionumber',
522     pickup_library_id => 'branchcode',
523     cancelation_date  => 'cancellationdate',
524     notes             => 'reservenotes',
525     status            => 'found',
526     item_id           => 'itemnumber',
527     waiting_date      => 'waitingdate',
528     expiration_date   => 'expirationdate',
529     lowest_priority   => 'lowestPriority',
530     suspended         => 'suspend',
531     suspended_until   => 'suspend_until',
532     item_type         => 'itemtype',
533     item_level        => 'item_level_hold',
534 };
535
536 1;