Bug 27353: Set X-Base-Total-Count header for REST API
[koha.git] / Koha / REST / V1 / Patrons.pm
1 package Koha::REST::V1::Patrons;
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 Koha::DateUtils;
23 use Koha::Patrons;
24
25 use Scalar::Util qw(blessed);
26 use Try::Tiny;
27
28 =head1 NAME
29
30 Koha::REST::V1::Patrons
31
32 =head1 API
33
34 =head2 Methods
35
36 =head3 list
37
38 Controller function that handles listing Koha::Patron objects
39
40 =cut
41
42 sub list {
43     my $c = shift->openapi->valid_input or return;
44
45     return try {
46
47         my $patrons_rs = Koha::Patrons->new;
48         my $args = $c->validation->output;
49         my $attributes = {};
50
51         # Extract reserved params
52         my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($args);
53
54         my $restricted = delete $filtered_params->{restricted};
55
56         # Merge sorting into query attributes
57         $c->dbic_merge_sorting(
58             {
59                 attributes => $attributes,
60                 params     => $reserved_params,
61                 result_set => $patrons_rs
62             }
63         );
64
65         # Merge pagination into query attributes
66         $c->dbic_merge_pagination(
67             {
68                 filter => $attributes,
69                 params => $reserved_params
70             }
71         );
72
73         if ( defined $filtered_params ) {
74
75             # Apply the mapping function to the passed params
76             $filtered_params = $patrons_rs->attributes_from_api($filtered_params);
77             $filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
78         }
79
80         # translate 'restricted' => 'debarred'
81         $filtered_params->{debarred} = { '!=' => undef }
82           if $restricted;
83
84         my $patrons = $patrons_rs->search( $filtered_params, $attributes );
85         my $total   = $patrons_rs->search->count;
86
87         $c->add_pagination_headers(
88             {
89                 total      => ($patrons->is_paged ? $patrons->pager->total_entries : $patrons->count),
90                 base_total => $total,
91                 params => $args,
92             }
93         );
94
95         return $c->render( status => 200, openapi => $patrons->to_api );
96     }
97     catch {
98         $c->unhandled_exception($_);
99     };
100 }
101
102
103 =head3 get
104
105 Controller function that handles retrieving a single Koha::Patron object
106
107 =cut
108
109 sub get {
110     my $c = shift->openapi->valid_input or return;
111
112     return try {
113         my $patron_id = $c->validation->param('patron_id');
114         my $patron    = Koha::Patrons->find($patron_id);
115
116         unless ($patron) {
117             return $c->render( status => 404, openapi => { error => "Patron not found." } );
118         }
119
120         return $c->render( status => 200, openapi => $patron->to_api );
121     }
122     catch {
123         $c->unhandled_exception($_);
124     };
125 }
126
127 =head3 add
128
129 Controller function that handles adding a new Koha::Patron object
130
131 =cut
132
133 sub add {
134     my $c = shift->openapi->valid_input or return;
135
136     return try {
137
138         my $patron = Koha::Patron->new_from_api( $c->validation->param('body') )->store;
139
140         $c->res->headers->location( $c->req->url->to_string . '/' . $patron->borrowernumber );
141         return $c->render(
142             status  => 201,
143             openapi => $patron->to_api
144         );
145     }
146     catch {
147
148         my $to_api_mapping = Koha::Patron->new->to_api_mapping;
149
150         unless ( blessed $_ && $_->can('rethrow') ) {
151             return $c->render(
152                 status  => 500,
153                 openapi => { error => "Something went wrong, check Koha logs for details." }
154             );
155         }
156         if ( $_->isa('Koha::Exceptions::Object::DuplicateID') ) {
157             return $c->render(
158                 status  => 409,
159                 openapi => { error => $_->error, conflict => $_->duplicate_id }
160             );
161         }
162         elsif ( $_->isa('Koha::Exceptions::Object::FKConstraint') ) {
163             return $c->render(
164                 status  => 400,
165                 openapi => {
166                           error => "Given "
167                         . $to_api_mapping->{ $_->broken_fk }
168                         . " does not exist"
169                 }
170             );
171         }
172         elsif ( $_->isa('Koha::Exceptions::BadParameter') ) {
173             return $c->render(
174                 status  => 400,
175                 openapi => {
176                           error => "Given "
177                         . $to_api_mapping->{ $_->parameter }
178                         . " does not exist"
179                 }
180             );
181         }
182         else {
183             $c->unhandled_exception($_);
184         }
185     };
186 }
187
188
189 =head3 update
190
191 Controller function that handles updating a Koha::Patron object
192
193 =cut
194
195 sub update {
196     my $c = shift->openapi->valid_input or return;
197
198     my $patron_id = $c->validation->param('patron_id');
199     my $patron    = Koha::Patrons->find( $patron_id );
200
201     unless ($patron) {
202          return $c->render(
203              status  => 404,
204              openapi => { error => "Patron not found" }
205          );
206      }
207
208     return try {
209         my $body = $c->validation->param('body');
210         my $user = $c->stash('koha.user');
211
212         if (
213                 $patron->is_superlibrarian
214             and !$user->is_superlibrarian
215             and (  exists $body->{email}
216                 or exists $body->{secondary_email}
217                 or exists $body->{altaddress_email} )
218           )
219         {
220             foreach my $email_field ( qw(email secondary_email altaddress_email) ) {
221                 my $exists_email = exists $body->{$email_field};
222                 next unless $exists_email;
223
224                 # exists, verify if we are asked to change it
225                 my $put_email      = $body->{$email_field};
226                 # As of writing this patch, 'email' is the only unmapped field
227                 # (i.e. it preserves its name, hence this fallback)
228                 my $db_email_field = $patron->to_api_mapping->{$email_field} // 'email';
229                 my $db_email       = $patron->$db_email_field;
230
231                 return $c->render(
232                     status  => 403,
233                     openapi => { error => "Not enough privileges to change a superlibrarian's email" }
234                   )
235                   unless ( !defined $put_email and !defined $db_email )
236                   or (  defined $put_email
237                     and defined $db_email
238                     and $put_email eq $db_email );
239             }
240         }
241
242         $patron->set_from_api($c->validation->param('body'))->store;
243         $patron->discard_changes;
244         return $c->render( status => 200, openapi => $patron->to_api );
245     }
246     catch {
247         unless ( blessed $_ && $_->can('rethrow') ) {
248             return $c->render(
249                 status  => 500,
250                 openapi => {
251                     error => "Something went wrong, check Koha logs for details."
252                 }
253             );
254         }
255         if ( $_->isa('Koha::Exceptions::Object::DuplicateID') ) {
256             return $c->render(
257                 status  => 409,
258                 openapi => { error => $_->error, conflict => $_->duplicate_id }
259             );
260         }
261         elsif ( $_->isa('Koha::Exceptions::Object::FKConstraint') ) {
262             return $c->render(
263                 status  => 400,
264                 openapi => { error => "Given " .
265                             $patron->to_api_mapping->{$_->broken_fk}
266                             . " does not exist" }
267             );
268         }
269         elsif ( $_->isa('Koha::Exceptions::MissingParameter') ) {
270             return $c->render(
271                 status  => 400,
272                 openapi => {
273                     error      => "Missing mandatory parameter(s)",
274                     parameters => $_->parameter
275                 }
276             );
277         }
278         elsif ( $_->isa('Koha::Exceptions::BadParameter') ) {
279             return $c->render(
280                 status  => 400,
281                 openapi => {
282                     error      => "Invalid parameter(s)",
283                     parameters => $_->parameter
284                 }
285             );
286         }
287         elsif ( $_->isa('Koha::Exceptions::NoChanges') ) {
288             return $c->render(
289                 status  => 204,
290                 openapi => { error => "No changes have been made" }
291             );
292         }
293         else {
294             $c->unhandled_exception($_);
295         }
296     };
297 }
298
299 =head3 delete
300
301 Controller function that handles deleting a Koha::Patron object
302
303 =cut
304
305 sub delete {
306     my $c = shift->openapi->valid_input or return;
307
308     my $patron = Koha::Patrons->find( $c->validation->param('patron_id') );
309
310     unless ( $patron ) {
311         return $c->render(
312             status  => 404,
313             openapi => { error => "Patron not found" }
314         );
315     }
316
317     return try {
318
319         $patron->delete;
320         return $c->render(
321             status  => 204,
322             openapi => q{}
323         );
324     } catch {
325         if ( blessed $_ && $_->isa('Koha::Exceptions::Patron::FailedDeleteAnonymousPatron') ) {
326             return $c->render(
327                 status  => 403,
328                 openapi => { error => "Anonymous patron cannot be deleted" }
329             );
330         }
331
332         $c->unhandled_exception($_);
333     };
334 }
335
336 =head3 guarantors_can_see_charges
337
338 Method for setting whether guarantors can see the patron's charges.
339
340 =cut
341
342 sub guarantors_can_see_charges {
343     my $c = shift->openapi->valid_input or return;
344
345     return try {
346         if ( C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor') ) {
347             my $patron = $c->stash( 'koha.user' );
348             my $privacy_setting = ($c->req->json->{allowed}) ? 1 : 0;
349
350             $patron->privacy_guarantor_fines( $privacy_setting )->store;
351
352             return $c->render(
353                 status  => 200,
354                 openapi => {}
355             );
356         }
357         else {
358             return $c->render(
359                 status  => 403,
360                 openapi => {
361                     error =>
362                       'The current configuration doesn\'t allow the requested action.'
363                 }
364             );
365         }
366     }
367     catch {
368         $c->unhandled_exception($_);
369     };
370 }
371
372 =head3 guarantors_can_see_checkouts
373
374 Method for setting whether guarantors can see the patron's checkouts.
375
376 =cut
377
378 sub guarantors_can_see_checkouts {
379     my $c = shift->openapi->valid_input or return;
380
381     return try {
382         if ( C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor') ) {
383             my $patron = $c->stash( 'koha.user' );
384             my $privacy_setting = ( $c->req->json->{allowed} ) ? 1 : 0;
385
386             $patron->privacy_guarantor_checkouts( $privacy_setting )->store;
387
388             return $c->render(
389                 status  => 200,
390                 openapi => {}
391             );
392         }
393         else {
394             return $c->render(
395                 status  => 403,
396                 openapi => {
397                     error =>
398                       'The current configuration doesn\'t allow the requested action.'
399                 }
400             );
401         }
402     }
403     catch {
404         $c->unhandled_exception($_);
405     };
406 }
407
408 1;