Bug 13895: Add API routes for checkouts retrieval and renewal
[koha.git] / Koha / REST / V1 / Checkout.pm
1 package Koha::REST::V1::Checkout;
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::Auth qw( haspermission );
23 use C4::Context;
24 use C4::Circulation;
25 use Koha::Checkouts;
26
27 sub list {
28     my ($c, $args, $cb) = @_;
29
30     my $borrowernumber = $c->param('borrowernumber');
31     my $checkouts = C4::Circulation::GetIssues({
32         borrowernumber => $borrowernumber
33     });
34
35     $c->$cb($checkouts, 200);
36 }
37
38 sub get {
39     my ($c, $args, $cb) = @_;
40
41     my $checkout_id = $args->{checkout_id};
42     my $checkout = Koha::Checkouts->find($checkout_id);
43
44     if (!$checkout) {
45         return $c->$cb({
46             error => "Checkout doesn't exist"
47         }, 404);
48     }
49
50     return $c->$cb($checkout->unblessed, 200);
51 }
52
53 sub renew {
54     my ($c, $args, $cb) = @_;
55
56     my $checkout_id = $args->{checkout_id};
57     my $checkout = Koha::Checkouts->find($checkout_id);
58
59     if (!$checkout) {
60         return $c->$cb({
61             error => "Checkout doesn't exist"
62         }, 404);
63     }
64
65     my $borrowernumber = $checkout->borrowernumber;
66     my $itemnumber = $checkout->itemnumber;
67
68     # Disallow renewal if OpacRenewalAllowed is off and user has insufficient rights
69     unless (C4::Context->preference('OpacRenewalAllowed')) {
70         my $user = $c->stash('koha.user');
71         unless ($user && haspermission($user->userid, { circulate => "circulate_remaining_permissions" })) {
72             return $c->$cb({error => "Opac Renewal not allowed"}, 403);
73         }
74     }
75
76     my ($can_renew, $error) = C4::Circulation::CanBookBeRenewed(
77         $borrowernumber, $itemnumber);
78
79     if (!$can_renew) {
80         return $c->$cb({error => "Renewal not authorized ($error)"}, 403);
81     }
82
83     AddRenewal($borrowernumber, $itemnumber, $checkout->branchcode);
84     $checkout = Koha::Checkouts->find($checkout_id);
85
86     return $c->$cb($checkout->unblessed, 200);
87 }
88
89 1;