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