e4f7ba1125d2100f9d3b22117d8ba3ff8a3aec71
[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 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 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         my $attributes = {};
47         my $args = $c->validation->output;
48         my ( $params, $reserved_params ) = $c->extract_reserved_params( $args );
49
50         # Merge sorting into query attributes
51         $c->dbic_merge_sorting({ attributes => $attributes, params => $reserved_params });
52
53         # Merge pagination into query attributes
54         $c->dbic_merge_pagination({ filter => $attributes, params => $reserved_params });
55
56         my $restricted = $args->{restricted};
57
58         $params = _to_model($params)
59             if defined $params;
60         # deal with string params
61         $params = $c->build_query_params( $params, $reserved_params );
62
63         # translate 'restricted' => 'debarred'
64         $params->{debarred} = { '!=' => undef }
65           if $restricted;
66
67         my $patrons = Koha::Patrons->search( $params, $attributes );
68         if ( $patrons->is_paged ) {
69             $c->add_pagination_headers(
70                 {
71                     total  => $patrons->pager->total_entries,
72                     params => $args,
73                 }
74             );
75         }
76         my @patrons = $patrons->as_list;
77         @patrons = map { _to_api( $_->TO_JSON ) } @patrons;
78         return $c->render( status => 200, openapi => \@patrons );
79     }
80     catch {
81         if ( $_->isa('DBIx::Class::Exception') ) {
82             return $c->render(
83                 status  => 500,
84                 openapi => { error => $_->{msg} }
85             );
86         }
87         else {
88             return $c->render(
89                 status  => 500,
90                 openapi => { error => "Something went wrong, check the logs." }
91             );
92         }
93     };
94 }
95
96
97 =head3 get
98
99 Controller function that handles retrieving a single Koha::Patron object
100
101 =cut
102
103 sub get {
104     my $c = shift->openapi->valid_input or return;
105
106     my $patron_id = $c->validation->param('patron_id');
107     my $patron    = Koha::Patrons->find($patron_id);
108
109     unless ($patron) {
110         return $c->render( status => 404, openapi => { error => "Patron not found." } );
111     }
112
113     return $c->render( status => 200, openapi => _to_api( $patron->TO_JSON ) );
114 }
115
116 =head3 add
117
118 Controller function that handles adding a new Koha::Patron object
119
120 =cut
121
122 sub add {
123     my $c = shift->openapi->valid_input or return;
124
125     return try {
126
127         my $body = _to_model( $c->validation->param('body') );
128
129         my $patron = Koha::Patron->new( _to_model($body) )->store;
130         $patron    = _to_api( $patron->TO_JSON );
131
132         return $c->render( status => 201, openapi => $patron );
133     }
134     catch {
135         unless ( blessed $_ && $_->can('rethrow') ) {
136             return $c->render(
137                 status  => 500,
138                 openapi => { error => "Something went wrong, check Koha logs for details." }
139             );
140         }
141         if ( $_->isa('Koha::Exceptions::Object::DuplicateID') ) {
142             return $c->render(
143                 status  => 409,
144                 openapi => { error => $_->error, conflict => $_->duplicate_id }
145             );
146         }
147         elsif ( $_->isa('Koha::Exceptions::Object::FKConstraint') ) {
148             return $c->render(
149                 status  => 400,
150                 openapi => {
151                           error => "Given "
152                         . $Koha::REST::V1::Patrons::to_api_mapping->{ $_->broken_fk }
153                         . " does not exist"
154                 }
155             );
156         }
157         elsif ( $_->isa('Koha::Exceptions::BadParameter') ) {
158             return $c->render(
159                 status  => 400,
160                 openapi => {
161                           error => "Given "
162                         . $Koha::REST::V1::Patrons::to_api_mapping->{ $_->parameter }
163                         . " does not exist"
164                 }
165             );
166         }
167         else {
168             return $c->render(
169                 status  => 500,
170                 openapi => { error => "Something went wrong, check Koha logs for details." }
171             );
172         }
173     };
174 }
175
176
177 =head3 update
178
179 Controller function that handles updating a Koha::Patron object
180
181 =cut
182
183 sub update {
184     my $c = shift->openapi->valid_input or return;
185
186     my $patron_id = $c->validation->param('patron_id');
187     my $patron    = Koha::Patrons->find( $patron_id );
188
189     unless ($patron) {
190          return $c->render(
191              status  => 404,
192              openapi => { error => "Patron not found" }
193          );
194      }
195
196     return try {
197         my $body = _to_model($c->validation->param('body'));
198
199         $patron->set($body)->store;
200         $patron->discard_changes;
201         return $c->render( status => 200, openapi => $patron );
202     }
203     catch {
204         unless ( blessed $_ && $_->can('rethrow') ) {
205             return $c->render(
206                 status  => 500,
207                 openapi => {
208                     error => "Something went wrong, check Koha logs for details."
209                 }
210             );
211         }
212         if ( $_->isa('Koha::Exceptions::Object::DuplicateID') ) {
213             return $c->render(
214                 status  => 409,
215                 openapi => { error => $_->error, conflict => $_->duplicate_id }
216             );
217         }
218         elsif ( $_->isa('Koha::Exceptions::Object::FKConstraint') ) {
219             return $c->render(
220                 status  => 400,
221                 openapi => { error => "Given " .
222                             $Koha::REST::V1::Patrons::to_api_mapping->{$_->broken_fk}
223                             . " does not exist" }
224             );
225         }
226         elsif ( $_->isa('Koha::Exceptions::MissingParameter') ) {
227             return $c->render(
228                 status  => 400,
229                 openapi => {
230                     error      => "Missing mandatory parameter(s)",
231                     parameters => $_->parameter
232                 }
233             );
234         }
235         elsif ( $_->isa('Koha::Exceptions::BadParameter') ) {
236             return $c->render(
237                 status  => 400,
238                 openapi => {
239                     error      => "Invalid parameter(s)",
240                     parameters => $_->parameter
241                 }
242             );
243         }
244         elsif ( $_->isa('Koha::Exceptions::NoChanges') ) {
245             return $c->render(
246                 status  => 204,
247                 openapi => { error => "No changes have been made" }
248             );
249         }
250         else {
251             return $c->render(
252                 status  => 500,
253                 openapi => {
254                     error =>
255                       "Something went wrong, check Koha logs for details."
256                 }
257             );
258         }
259     };
260 }
261
262 =head3 delete
263
264 Controller function that handles deleting a Koha::Patron object
265
266 =cut
267
268 sub delete {
269     my $c = shift->openapi->valid_input or return;
270
271     my $patron;
272
273     return try {
274         $patron = Koha::Patrons->find( $c->validation->param('patron_id') );
275
276         # check if loans, reservations, debarrment, etc. before deletion!
277         my $res = $patron->delete;
278         return $c->render( status => 200, openapi => {} );
279     }
280     catch {
281         unless ($patron) {
282             return $c->render(
283                 status  => 404,
284                 openapi => { error => "Patron not found" }
285             );
286         }
287         else {
288             return $c->render(
289                 status  => 500,
290                 openapi => {
291                     error =>
292                       "Something went wrong, check Koha logs for details."
293                 }
294             );
295         }
296     };
297 }
298
299 =head3 _to_api
300
301 Helper function that maps unblessed Koha::Patron objects into REST api
302 attribute names.
303
304 =cut
305
306 sub _to_api {
307     my $patron    = shift;
308     my $patron_id = $patron->{ borrowernumber };
309
310     # Rename attributes
311     foreach my $column ( keys %{ $Koha::REST::V1::Patrons::to_api_mapping } ) {
312         my $mapped_column = $Koha::REST::V1::Patrons::to_api_mapping->{$column};
313         if (    exists $patron->{ $column }
314              && defined $mapped_column )
315         {
316             # key != undef
317             $patron->{ $mapped_column } = delete $patron->{ $column };
318         }
319         elsif (    exists $patron->{ $column }
320                 && !defined $mapped_column )
321         {
322             # key == undef
323             delete $patron->{ $column };
324         }
325     }
326
327     # Calculate the 'restricted' field
328     my $patron_obj = Koha::Patrons->find( $patron_id );
329     $patron->{ restricted } = ($patron_obj->is_debarred) ? Mojo::JSON->true : Mojo::JSON->false;
330
331     return $patron;
332 }
333
334 =head3 _to_model
335
336 Helper function that maps REST api objects into Koha::Patron
337 attribute names.
338
339 =cut
340
341 sub _to_model {
342     my $patron = shift;
343
344     foreach my $attribute ( keys %{ $Koha::REST::V1::Patrons::to_model_mapping } ) {
345         my $mapped_attribute = $Koha::REST::V1::Patrons::to_model_mapping->{$attribute};
346         if (    exists $patron->{ $attribute }
347              && defined $mapped_attribute )
348         {
349             # key => !undef
350             $patron->{ $mapped_attribute } = delete $patron->{ $attribute };
351         }
352         elsif (    exists $patron->{ $attribute }
353                 && !defined $mapped_attribute )
354         {
355             # key => undef / to be deleted
356             delete $patron->{ $attribute };
357         }
358     }
359
360     # TODO: Get rid of this once write operations are based on Koha::Patron
361     if ( exists $patron->{lost} ) {
362         $patron->{lost} = ($patron->{lost}) ? 1 : 0;
363     }
364
365     if ( exists $patron->{ gonenoaddress} ) {
366         $patron->{gonenoaddress} = ($patron->{gonenoaddress}) ? 1 : 0;
367     }
368
369     if ( exists $patron->{lastseen} ) {
370         $patron->{lastseen} = output_pref({ str => $patron->{lastseen}, dateformat => 'sql' });
371     }
372
373     if ( exists $patron->{updated_on} ) {
374         $patron->{updated_on} = output_pref({ str => $patron->{updated_on}, dateformat => 'sql' });
375     }
376
377     return $patron;
378 }
379
380 =head2 Global variables
381
382 =head3 $to_api_mapping
383
384 =cut
385
386 our $to_api_mapping = {
387     borrowernotes       => 'staff_notes',
388     borrowernumber      => 'patron_id',
389     branchcode          => 'library_id',
390     categorycode        => 'category_id',
391     checkprevcheckout   => 'check_previous_checkout',
392     contactfirstname    => undef, # Unused
393     contactname         => undef, # Unused
394     contactnote         => 'altaddress_notes',
395     contacttitle        => undef, # Unused
396     dateenrolled        => 'date_enrolled',
397     dateexpiry          => 'expiry_date',
398     dateofbirth         => 'date_of_birth',
399     debarred            => undef, # replaced by 'restricted'
400     debarredcomment     => undef, # calculated, API consumers will use /restrictions instead
401     emailpro            => 'secondary_email',
402     flags               => undef, # permissions manipulation handled in /permissions
403     flgAnonymized       => 'anonymized',
404     gonenoaddress       => 'incorrect_address',
405     guarantorid         => 'guarantor_id',
406     lastseen            => 'last_seen',
407     lost                => 'patron_card_lost',
408     opacnote            => 'opac_notes',
409     othernames          => 'other_name',
410     password            => undef, # password manipulation handled in /password
411     phonepro            => 'secondary_phone',
412     relationship        => 'relationship_type',
413     sex                 => 'gender',
414     smsalertnumber      => 'sms_number',
415     sort1               => 'statistics_1',
416     sort2               => 'statistics_2',
417     streetnumber        => 'street_number',
418     streettype          => 'street_type',
419     zipcode             => 'postal_code',
420     B_address           => 'altaddress_address',
421     B_address2          => 'altaddress_address2',
422     B_city              => 'altaddress_city',
423     B_country           => 'altaddress_country',
424     B_email             => 'altaddress_email',
425     B_phone             => 'altaddress_phone',
426     B_state             => 'altaddress_state',
427     B_streetnumber      => 'altaddress_street_number',
428     B_streettype        => 'altaddress_street_type',
429     B_zipcode           => 'altaddress_postal_code',
430     altcontactaddress1  => 'altcontact_address',
431     altcontactaddress2  => 'altcontact_address2',
432     altcontactaddress3  => 'altcontact_city',
433     altcontactcountry   => 'altcontact_country',
434     altcontactfirstname => 'altcontact_firstname',
435     altcontactphone     => 'altcontact_phone',
436     altcontactsurname   => 'altcontact_surname',
437     altcontactstate     => 'altcontact_state',
438     altcontactzipcode   => 'altcontact_postal_code'
439 };
440
441 =head3 $to_model_mapping
442
443 =cut
444
445 our $to_model_mapping = {
446     altaddress_notes         => 'contactnote',
447     anonymized               => 'flgAnonymized',
448     category_id              => 'categorycode',
449     check_previous_checkout  => 'checkprevcheckout',
450     date_enrolled            => 'dateenrolled',
451     date_of_birth            => 'dateofbirth',
452     expiry_date              => 'dateexpiry',
453     gender                   => 'sex',
454     guarantor_id             => 'guarantorid',
455     incorrect_address        => 'gonenoaddress',
456     last_seen                => 'lastseen',
457     library_id               => 'branchcode',
458     opac_notes               => 'opacnote',
459     other_name               => 'othernames',
460     patron_card_lost         => 'lost',
461     patron_id                => 'borrowernumber',
462     postal_code              => 'zipcode',
463     relationship_type        => 'relationship',
464     restricted               => undef,
465     secondary_email          => 'emailpro',
466     secondary_phone          => 'phonepro',
467     sms_number               => 'smsalertnumber',
468     staff_notes              => 'borrowernotes',
469     statistics_1             => 'sort1',
470     statistics_2             => 'sort2',
471     street_number            => 'streetnumber',
472     street_type              => 'streettype',
473     altaddress_address       => 'B_address',
474     altaddress_address2      => 'B_address2',
475     altaddress_city          => 'B_city',
476     altaddress_country       => 'B_country',
477     altaddress_email         => 'B_email',
478     altaddress_phone         => 'B_phone',
479     altaddress_state         => 'B_state',
480     altaddress_street_number => 'B_streetnumber',
481     altaddress_street_type   => 'B_streettype',
482     altaddress_postal_code   => 'B_zipcode',
483     altcontact_firstname     => 'altcontactfirstname',
484     altcontact_surname       => 'altcontactsurname',
485     altcontact_address       => 'altcontactaddress1',
486     altcontact_address2      => 'altcontactaddress2',
487     altcontact_city          => 'altcontactaddress3',
488     altcontact_state         => 'altcontactstate',
489     altcontact_postal_code   => 'altcontactzipcode',
490     altcontact_country       => 'altcontactcountry',
491     altcontact_phone         => 'altcontactphone'
492 };
493
494 1;