Bug 23805: Update 'Pay' to 'PAYMENT' for consistency
[koha.git] / Koha / REST / V1 / Patrons / Account.pm
1 package Koha::REST::V1::Patrons::Account;
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::Patrons;
23
24 use Scalar::Util qw(blessed);
25 use Try::Tiny;
26
27 =head1 NAME
28
29 Koha::REST::V1::Patrons::Account
30
31 =head1 API
32
33 =head2 Methods
34
35 =head3 get
36
37 Controller function that handles retrieving a patron's account balance
38
39 =cut
40
41 sub get {
42     my $c = shift->openapi->valid_input or return;
43
44     my $patron_id = $c->validation->param('patron_id');
45     my $patron    = Koha::Patrons->find($patron_id);
46
47     unless ($patron) {
48         return $c->render( status => 404, openapi => { error => "Patron not found." } );
49     }
50
51     my $account = $patron->account;
52
53     # get outstanding debits and credits
54     my $debits  = $account->outstanding_debits;
55     my $credits = $account->outstanding_credits;
56
57     return $c->render(
58         status  => 200,
59         openapi => {
60             balance => $account->balance,
61             outstanding_debits => {
62                 total => $debits->total_outstanding,
63                 lines => $debits->to_api
64             },
65             outstanding_credits => {
66                 total => $credits->total_outstanding,
67                 lines => $credits->to_api
68               }
69         }
70     );
71 }
72
73 =head3 add_credit
74
75 Controller function that handles adding a credit to a patron's account
76
77 =cut
78
79 sub add_credit {
80     my $c = shift->openapi->valid_input or return;
81
82     my $patron_id = $c->validation->param('patron_id');
83     my $patron    = Koha::Patrons->find($patron_id);
84     my $user      = $c->stash('koha.user');
85
86
87     unless ($patron) {
88         return $c->render( status => 404, openapi => { error => "Patron not found." } );
89     }
90
91     my $account = $patron->account;
92     my $body    = $c->validation->param('body');
93
94     return try {
95         my $credit_type = $body->{credit_type} || 'PAYMENT';    # default to 'PAYMENT'
96         my $amount = $body->{amount};                           # mandatory, validated by openapi
97
98         unless ( $amount > 0 ) {  # until we support newer JSON::Validator and thus minimumExclusive
99             Koha::Exceptions::BadParameter->throw( { parameter => 'amount' } );
100         }
101
102         # read the rest of the params
103         my $payment_type = $body->{payment_type};
104         my $description  = $body->{description};
105         my $note         = $body->{note};
106         my $library_id   = $body->{library_id};
107
108         my $credit = $account->add_credit(
109             {   amount       => $amount,
110                 type         => $credit_type,
111                 payment_type => $payment_type,
112                 description  => $description,
113                 note         => $note,
114                 user_id      => $user->id,
115                 interface    => 'api',
116                 library_id   => $library_id
117             }
118         );
119         $credit->discard_changes;
120
121         my $date = $body->{date};
122         $credit->date( $date )->store
123             if $date;
124
125         my $debits_ids = $body->{account_lines_ids};
126         my $debits;
127         $debits = Koha::Account::Lines->search({ accountlines_id => { -in => $debits_ids } })
128             if $debits_ids;
129
130         my $outstanding_credit = $credit->amountoutstanding;
131         if ($debits) {
132             # pay them!
133             $outstanding_credit = $credit->apply({ debits => [ $debits->as_list ], offset_type => 'payment' });
134         }
135
136         if ($outstanding_credit) {
137             my $outstanding_debits = $account->outstanding_debits;
138             $credit->apply({ debits => [ $outstanding_debits->as_list ], offset_type => 'payment' });
139         }
140
141         return $c->render( status => 200, openapi => { account_line_id => $credit->id } );
142     }
143     catch {
144         if ( blessed $_ && $_->can('rethrow') ) {
145             return $c->render(
146                 status  => 400,
147                 openapi => { error => "$_" }
148             );
149         }
150         else {
151             # Exception, rely on the stringified exception
152             return $c->render(
153                 status  => 500,
154                 openapi => { error => "Something went wrong, check the logs" }
155             );
156         }
157     };
158 }
159
160
161 =head3 _to_api
162
163 Helper function that maps unblessed Koha::Account::Line objects
164 into REST API attribute names.
165
166 =cut
167
168 sub _to_api {
169     my $account_line = shift;
170
171     # Rename attributes
172     foreach my $column ( keys %{ $Koha::REST::V1::Patrons::Account::to_api_mapping } ) {
173         my $mapped_column = $Koha::REST::V1::Patrons::Account::to_api_mapping->{$column};
174         if (    exists $account_line->{ $column }
175              && defined $mapped_column )
176         {
177             # key != undef
178             $account_line->{ $mapped_column } = delete $account_line->{ $column };
179         }
180         elsif (    exists $account_line->{ $column }
181                 && !defined $mapped_column )
182         {
183             # key == undef
184             delete $account_line->{ $column };
185         }
186     }
187
188     return $account_line;
189 }
190
191 =head3 _to_model
192
193 Helper function that maps REST API objects into Koha::Account::Line
194 attribute names.
195
196 =cut
197
198 sub _to_model {
199     my $account_line = shift;
200
201     foreach my $attribute ( keys %{ $Koha::REST::V1::Patrons::Account::to_model_mapping } ) {
202         my $mapped_attribute = $Koha::REST::V1::Patrons::Account::to_model_mapping->{$attribute};
203         if (    exists $account_line->{ $attribute }
204              && defined $mapped_attribute )
205         {
206             # key => !undef
207             $account_line->{ $mapped_attribute } = delete $account_line->{ $attribute };
208         }
209         elsif (    exists $account_line->{ $attribute }
210                 && !defined $mapped_attribute )
211         {
212             # key => undef / to be deleted
213             delete $account_line->{ $attribute };
214         }
215     }
216
217     return $account_line;
218 }
219
220 =head2 Global variables
221
222 =head3 $to_api_mapping
223
224 =cut
225
226 our $to_api_mapping = {
227     accountlines_id   => 'account_line_id',
228     credit_type_code  => 'credit_type',
229     debit_type_code   => 'debit_type',
230     amountoutstanding => 'amount_outstanding',
231     borrowernumber    => 'patron_id',
232     branchcode        => 'library_id',
233     issue_id          => 'checkout_id',
234     itemnumber        => 'item_id',
235     manager_id        => 'user_id',
236     note              => 'internal_note',
237 };
238
239 =head3 $to_model_mapping
240
241 =cut
242
243 our $to_model_mapping = {
244     account_line_id    => 'accountlines_id',
245     credit_type        => 'credit_type_code',
246     debit_type         => 'debit_type_code',
247     amount_outstanding => 'amountoutstanding',
248     checkout_id        => 'issue_id',
249     internal_note      => 'note',
250     item_id            => 'itemnumber',
251     library_id         => 'branchcode',
252     patron_id          => 'borrowernumber',
253     user_id            => 'manager_id'
254 };
255
256 1;