Bug 20640: (follow-up) Degrade gracefully on error
[koha.git] / ill / ill-requests.pl
1 #!/usr/bin/perl
2
3 # Copyright 2013 PTFS-Europe Ltd and Mark Gavillet
4 # Copyright 2014 PTFS-Europe Ltd
5 #
6 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use Modern::Perl;
21
22 use CGI;
23
24 use C4::Auth;
25 use C4::Output;
26 use Koha::AuthorisedValues;
27 use Koha::Illcomment;
28 use Koha::Illrequests;
29 use Koha::Libraries;
30 use Koha::Token;
31
32 use Try::Tiny;
33
34 our $cgi = CGI->new;
35 my $illRequests = Koha::Illrequests->new;
36
37 # Grab all passed data
38 # 'our' since Plack changes the scoping
39 # of 'my'
40 our $params = $cgi->Vars();
41
42 # Leave immediately if ILLModule is disabled
43 unless ( C4::Context->preference('ILLModule') ) {
44     print $cgi->redirect("/cgi-bin/koha/errors/404.pl");
45     exit;
46 }
47
48 my $op = $params->{method} || 'illlist';
49
50 my ( $template, $patronnumber, $cookie ) = get_template_and_user( {
51     template_name => 'ill/ill-requests.tt',
52     query         => $cgi,
53     type          => 'intranet',
54     flagsrequired => { ill => '*' },
55 } );
56
57 # Are we able to actually work?
58 my $cfg = Koha::Illrequest::Config->new;
59 my $backends = $cfg->available_backends;
60 my $has_branch = $cfg->has_branch;
61 my $backends_available = ( scalar @{$backends} > 0 );
62 $template->param(
63     backends_available => $backends_available,
64     has_branch         => $has_branch
65 );
66
67 if ( $backends_available ) {
68     if ( $op eq 'illview' ) {
69         # View the details of an ILL
70         my $request = Koha::Illrequests->find($params->{illrequest_id});
71
72         $template->param(
73             request    => $request,
74             csrf_token => Koha::Token->new->generate_csrf({
75                 session_id => scalar $cgi->cookie('CGISESSID'),
76             }),
77         );
78
79     } elsif ( $op eq 'create' ) {
80         # We're in the process of creating a request
81         my $request = Koha::Illrequest->new->load_backend( $params->{backend} );
82         my $backend_result = $request->backend_create($params);
83         $template->param(
84             whole   => $backend_result,
85             request => $request
86         );
87         handle_commit_maybe($backend_result, $request);
88
89     } elsif ( $op eq 'migrate' ) {
90         # We're in the process of migrating a request
91         my $request = Koha::Illrequests->find($params->{illrequest_id});
92         my $backend_result;
93         if ( $params->{backend} ) {
94             my $new_request = Koha::Illrequest->new->load_backend( $params->{backend} );
95             $backend_result = $new_request->backend_migrate($params);
96             if ($backend_result) {
97                 $template->param(
98                     whole   => $backend_result,
99                     request => $new_request
100                 );
101             } else {
102                 # backend failure
103                 $backend_result = {
104                     stage => 'commit',
105                     next  => 'illview',
106                     error => {
107                         message => 'Migrating to backedn does not support migrate',
108                         status => 'Migrating to backedn does not support migrate'
109                     }
110                 };
111                 $template->param(
112                     whole   => $backend_result,
113                     request => $request
114                 );
115             }
116         }
117         else {
118             $request = Koha::Illrequests->find( $params->{illrequest_id} );
119             $backend_result = $request->backend_migrate($params);
120             $template->param(
121                 whole   => $backend_result,
122                 request => $request
123             );
124         }
125         handle_commit_maybe( $backend_result, $request );
126
127     } elsif ( $op eq 'confirm' ) {
128         # Backend 'confirm' method
129         # confirm requires a specific request, so first, find it.
130         my $request = Koha::Illrequests->find($params->{illrequest_id});
131         my $backend_result = $request->backend_confirm($params);
132         $template->param(
133             whole   => $backend_result,
134             request => $request,
135         );
136
137         # handle special commit rules & update type
138         handle_commit_maybe($backend_result, $request);
139
140     } elsif ( $op eq 'cancel' ) {
141         # Backend 'cancel' method
142         # cancel requires a specific request, so first, find it.
143         my $request = Koha::Illrequests->find($params->{illrequest_id});
144         my $backend_result = $request->backend_cancel($params);
145         $template->param(
146             whole   => $backend_result,
147             request => $request,
148         );
149
150         # handle special commit rules & update type
151         handle_commit_maybe($backend_result, $request);
152
153     } elsif ( $op eq 'edit_action' ) {
154         # Handle edits to the Illrequest object.
155         # (not the Illrequestattributes)
156         # We simulate the API for backend requests for uniformity.
157         # So, init:
158         my $request = Koha::Illrequests->find($params->{illrequest_id});
159         if ( !$params->{stage} ) {
160             my $backend_result = {
161                 error   => 0,
162                 status  => '',
163                 message => '',
164                 method  => 'edit_action',
165                 stage   => 'init',
166                 next    => '',
167                 value   => {}
168             };
169             $template->param(
170                 whole   => $backend_result,
171                 request => $request
172             );
173         } else {
174             # Commit:
175             # Save the changes
176             $request->borrowernumber($params->{borrowernumber});
177             $request->biblio_id($params->{biblio_id});
178             $request->branchcode($params->{branchcode});
179             $request->price_paid($params->{price_paid});
180             $request->notesopac($params->{notesopac});
181             $request->notesstaff($params->{notesstaff});
182             $request->store;
183             my $backend_result = {
184                 error   => 0,
185                 status  => '',
186                 message => '',
187                 method  => 'edit_action',
188                 stage   => 'commit',
189                 next    => 'illlist',
190                 value   => {}
191             };
192             handle_commit_maybe($backend_result, $request);
193         }
194
195     } elsif ( $op eq 'moderate_action' ) {
196         # Moderate action is required for an ILL submodule / syspref.
197         # Currently still needs to be implemented.
198         redirect_to_list();
199
200     } elsif ( $op eq 'delete_confirm') {
201         my $request = Koha::Illrequests->find($params->{illrequest_id});
202
203         $template->param(
204             request => $request
205         );
206
207     } elsif ( $op eq 'delete' ) {
208
209         # Check if the request is confirmed, if not, redirect
210         # to the confirmation view
211         if ($params->{confirmed}) {
212             # We simply delete the request...
213             Koha::Illrequests->find( $params->{illrequest_id} )->delete;
214             # ... then return to list view.
215             redirect_to_list();
216         } else {
217             print $cgi->redirect(
218                 "/cgi-bin/koha/ill/ill-requests.pl?" .
219                 "method=delete_confirm&illrequest_id=" .
220                 $params->{illrequest_id});
221             exit;
222         }
223
224     } elsif ( $op eq 'mark_completed' ) {
225         my $request = Koha::Illrequests->find($params->{illrequest_id});
226         my $backend_result = $request->mark_completed($params);
227         $template->param(
228             whole => $backend_result,
229             request => $request,
230         );
231
232         # handle special commit rules & update type
233         handle_commit_maybe($backend_result, $request);
234
235     } elsif ( $op eq 'generic_confirm' ) {
236         my $backend_result;
237         my $request;
238         try {
239             $request = Koha::Illrequests->find($params->{illrequest_id});
240             $params->{current_branchcode} = C4::Context->mybranch;
241             $backend_result = $request->generic_confirm($params);
242             $template->param(
243                 whole => $backend_result,
244                 request => $request,
245             );
246             $template->param( error => $params->{error} )
247                 if $params->{error};
248         }
249         catch {
250             my $error;
251             if ( $_->isa( 'Koha::Exceptions::Ill::NoTargetEmail' ) ) {
252                 $error = 'no_target_email';
253             }
254             elsif ( $_->isa( 'Koha::Exceptions::Ill::NoLibraryEmail' ) ) {
255                 $error = 'no_library_email';
256             }
257             else {
258                 $error = 'unknown_error';
259             }
260             print $cgi->redirect(
261                 "/cgi-bin/koha/ill/ill-requests.pl?" .
262                 "method=generic_confirm&illrequest_id=" .
263                 $params->{illrequest_id} .
264                 "&error=$error" );
265             exit;
266         };
267
268         # handle special commit rules & update type
269         handle_commit_maybe($backend_result, $request);
270     } elsif ( $op eq 'illlist') {
271
272         # If we receive a pre-filter, make it available to the template
273         my $possible_filters = ['borrowernumber'];
274         my $active_filters = [];
275         foreach my $filter(@{$possible_filters}) {
276             if ($params->{$filter}) {
277                 push @{$active_filters},
278                     { name => $filter, value => $params->{$filter}};
279             }
280         }
281         if (scalar @{$active_filters} > 0) {
282             $template->param(
283                 prefilters => $active_filters
284             );
285         }
286
287     } elsif ( $op eq "save_comment" ) {
288         die "Wrong CSRF token" unless Koha::Token->new->check_csrf({
289            session_id => scalar $cgi->cookie('CGISESSID'),
290            token      => scalar $cgi->param('csrf_token'),
291         });
292         my $comment = Koha::Illcomment->new({
293             illrequest_id  => scalar $params->{illrequest_id},
294             borrowernumber => $patronnumber,
295             comment        => scalar $params->{comment},
296         });
297         $comment->store();
298         # Redirect to view the whole request
299         print $cgi->redirect("/cgi-bin/koha/ill/ill-requests.pl?method=illview&illrequest_id=".
300             scalar $params->{illrequest_id}
301         );
302         exit;
303
304     } else {
305         my $request = Koha::Illrequests->find($params->{illrequest_id});
306         my $backend_result = $request->custom_capability($op, $params);
307         $template->param(
308             whole => $backend_result,
309             request => $request,
310         );
311
312         # handle special commit rules & update type
313         handle_commit_maybe($backend_result, $request);
314     }
315 }
316
317 $template->param(
318     backends   => $backends,
319     types      => [ "Book", "Article", "Journal" ],
320     query_type => $op,
321     branches   => scalar Koha::Libraries->search,
322 );
323
324 output_html_with_http_headers( $cgi, $cookie, $template->output );
325
326 sub handle_commit_maybe {
327     my ( $backend_result, $request ) = @_;
328
329     # We need to special case 'commit'
330     if ( $backend_result->{stage} eq 'commit' ) {
331         if ( $backend_result->{next} eq 'illview' ) {
332
333             # Redirect to a view of the newly created request
334             print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
335                   . '?method=illview'
336                   . '&illrequest_id='
337                   . $request->id );
338             exit;
339         }
340         elsif ( $backend_result->{next} eq 'emigrate' ) {
341
342             # Redirect to a view of the newly created request
343             print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
344                   . '?method=migrate'
345                   . '&stage=emigrate'
346                   . '&illrequest_id='
347                   . $request->id );
348             exit;
349         }
350         else {
351             # Redirect to a requests list view
352             redirect_to_list();
353         }
354     }
355 }
356
357 sub redirect_to_list {
358     print $cgi->redirect('/cgi-bin/koha/ill/ill-requests.pl');
359     exit;
360 }