Bug 23548: (QA follow-up) tidy up code
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use CGI;
23
24 use C4::Auth qw( get_template_and_user );
25 use C4::Output qw( output_and_exit output_html_with_http_headers );
26 use Koha::Notice::Templates;
27 use Koha::AuthorisedValues;
28 use Koha::Illcomment;
29 use Koha::Illrequests;
30 use Koha::Illrequest::Availability;
31 use Koha::Libraries;
32 use Koha::Token;
33
34 use Try::Tiny qw( catch try );
35 use URI::Escape qw( uri_escape_utf8 );
36 use JSON qw( encode_json );
37
38 our $cgi = CGI->new;
39 my $illRequests = Koha::Illrequests->new;
40
41 # Grab all passed data
42 # 'our' since Plack changes the scoping
43 # of 'my'
44 our $params = $cgi->Vars();
45
46 # Leave immediately if ILLModule is disabled
47 unless ( C4::Context->preference('ILLModule') ) {
48     print $cgi->redirect("/cgi-bin/koha/errors/404.pl");
49     exit;
50 }
51
52 my $op = $params->{method} || 'illlist';
53
54 my ( $template, $patronnumber, $cookie ) = get_template_and_user( {
55     template_name => 'ill/ill-requests.tt',
56     query         => $cgi,
57     type          => 'intranet',
58     flagsrequired => { ill => '*' },
59 } );
60
61 # Are we able to actually work?
62 my $cfg = Koha::Illrequest::Config->new;
63 my $backends = $cfg->available_backends;
64 my $has_branch = $cfg->has_branch;
65 my $backends_available = ( scalar @{$backends} > 0 );
66 $template->param(
67     backends_available => $backends_available,
68     has_branch         => $has_branch
69 );
70
71 if ( $backends_available ) {
72     if ( $op eq 'illview' ) {
73         # View the details of an ILL
74         my $request = Koha::Illrequests->find($params->{illrequest_id});
75
76         # Get the details for notices that can be sent from here
77         my $notices = Koha::Notice::Templates->search(
78             {
79                 module => 'ill',
80                 code => { -in => [ 'ILL_PICKUP_READY' ,'ILL_REQUEST_UNAVAIL' ] },
81             },
82             {
83                 columns => [ qw/code name/ ],
84                 distinct => 1
85             }
86         )->unblessed;
87
88         $template->param(
89             notices    => $notices,
90             request    => $request,
91             csrf_token => Koha::Token->new->generate_csrf({
92                 session_id => scalar $cgi->cookie('CGISESSID'),
93             }),
94             ( $params->{tran_error} ?
95                 ( tran_error => $params->{tran_error} ) : () ),
96             ( $params->{tran_success} ?
97                 ( tran_success => $params->{tran_success} ) : () ),
98         );
99
100         output_and_exit( $cgi, $cookie, $template, 'unknown_ill_request' ) if !$request;
101
102         my $backend_result = $request->backend_illview($params);
103         $template->param(
104             whole      => $backend_result,
105         ) if $backend_result;
106
107
108     } elsif ( $op eq 'create' ) {
109         # We're in the process of creating a request
110         my $request = Koha::Illrequest->new->load_backend( $params->{backend} );
111         # Does this backend enable us to insert an availability stage and should
112         # we? If not, proceed as normal.
113         if (
114             # If the user has elected to continue with the request despite
115             # having viewed availability info, this flag will be set
116             C4::Context->preference("ILLCheckAvailability")
117               && !$params->{checked_availability}
118               && $request->_backend_capability( 'should_display_availability', $params )
119         ) {
120             # Establish which of the installed availability providers
121             # can service our metadata
122             my $availability = Koha::Illrequest::Availability->new($params);
123             my $services = $availability->get_services({
124                 ui_context => 'staff'
125             });
126             if (scalar @{$services} > 0) {
127                 # Modify our method so we use the correct part of the
128                 # template
129                 $op = 'availability';
130                 $params->{method} = 'availability';
131                 delete $params->{stage};
132                 # Prepare the metadata we're sending them
133                 my $metadata = $availability->prep_metadata($params);
134                 $template->param(
135                     whole         => $params,
136                     metadata      => $metadata,
137                     services_json => scalar encode_json($services),
138                     services      => $services
139                 );
140             } else {
141                 # No services can process this metadata, so continue as normal
142                 my $backend_result = $request->backend_create($params);
143                 $template->param(
144                     whole   => $backend_result,
145                     request => $request
146                 );
147                 handle_commit_maybe($backend_result, $request);
148             }
149         } else {
150             my $backend_result = $request->backend_create($params);
151             $template->param(
152                 whole   => $backend_result,
153                 request => $request
154             );
155             handle_commit_maybe($backend_result, $request);
156         }
157
158     } elsif ( $op eq 'migrate' ) {
159         # We're in the process of migrating a request
160         my $request = Koha::Illrequests->find($params->{illrequest_id});
161         my $backend_result;
162         if ( $params->{backend} ) {
163             $backend_result = $request->backend_migrate($params);
164             if ($backend_result) {
165                 $template->param(
166                     whole   => $backend_result,
167                     request => $request
168                 );
169             } else {
170                 # Backend failure, redirect back to illview
171                 print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
172                       . '?method=illview'
173                       . '&illrequest_id='
174                       . $request->id
175                       . '&error=migrate_target' );
176                 exit;
177             }
178         }
179         else {
180             $backend_result = $request->backend_migrate($params);
181             $template->param(
182                 whole   => $backend_result,
183                 request => $request
184             );
185         }
186         handle_commit_maybe( $backend_result, $request );
187
188     } elsif ( $op eq 'confirm' ) {
189         # Backend 'confirm' method
190         # confirm requires a specific request, so first, find it.
191         my $request = Koha::Illrequests->find($params->{illrequest_id});
192         my $backend_result = $request->backend_confirm($params);
193         $template->param(
194             whole   => $backend_result,
195             request => $request,
196         );
197
198         # handle special commit rules & update type
199         handle_commit_maybe($backend_result, $request);
200
201     } elsif ( $op eq 'cancel' ) {
202         # Backend 'cancel' method
203         # cancel requires a specific request, so first, find it.
204         my $request = Koha::Illrequests->find($params->{illrequest_id});
205         my $backend_result = $request->backend_cancel($params);
206         $template->param(
207             whole   => $backend_result,
208             request => $request,
209         );
210
211         # handle special commit rules & update type
212         handle_commit_maybe($backend_result, $request);
213
214     } elsif ( $op eq 'edit_action' ) {
215         # Handle edits to the Illrequest object.
216         # (not the Illrequestattributes)
217         # We simulate the API for backend requests for uniformity.
218         # So, init:
219         my $request = Koha::Illrequests->find($params->{illrequest_id});
220         if ( !$params->{stage} ) {
221             my $backend_result = {
222                 error   => 0,
223                 status  => '',
224                 message => '',
225                 method  => 'edit_action',
226                 stage   => 'init',
227                 next    => '',
228                 value   => {}
229             };
230             $template->param(
231                 whole          => $backend_result,
232                 request        => $request
233             );
234         } else {
235             # Commit:
236             # Save the changes
237             $request->borrowernumber($params->{borrowernumber});
238             $request->biblio_id($params->{biblio_id});
239             $request->branchcode($params->{branchcode});
240             $request->price_paid($params->{price_paid});
241             $request->notesopac($params->{notesopac});
242             $request->notesstaff($params->{notesstaff});
243             my $alias = (length $params->{status_alias} > 0) ?
244                 $params->{status_alias} :
245                 "-1";
246             $request->status_alias($alias);
247             $request->store;
248             my $backend_result = {
249                 error   => 0,
250                 status  => '',
251                 message => '',
252                 method  => 'edit_action',
253                 stage   => 'commit',
254                 next    => 'illlist',
255                 value   => {}
256             };
257             handle_commit_maybe($backend_result, $request);
258         }
259
260     } elsif ( $op eq 'moderate_action' ) {
261         # Moderate action is required for an ILL submodule / syspref.
262         # Currently still needs to be implemented.
263         redirect_to_list();
264
265     } elsif ( $op eq 'delete_confirm') {
266         my $request = Koha::Illrequests->find($params->{illrequest_id});
267
268         $template->param(
269             request => $request
270         );
271
272     } elsif ( $op eq 'delete' ) {
273
274         # Check if the request is confirmed, if not, redirect
275         # to the confirmation view
276         if ($params->{confirmed}) {
277             # We simply delete the request...
278             Koha::Illrequests->find( $params->{illrequest_id} )->delete;
279             # ... then return to list view.
280             redirect_to_list();
281         } else {
282             print $cgi->redirect(
283                 "/cgi-bin/koha/ill/ill-requests.pl?" .
284                 "method=delete_confirm&illrequest_id=" .
285                 $params->{illrequest_id});
286             exit;
287         }
288
289     } elsif ( $op eq 'mark_completed' ) {
290         my $request = Koha::Illrequests->find($params->{illrequest_id});
291         my $backend_result = $request->mark_completed($params);
292         $template->param(
293             whole => $backend_result,
294             request => $request,
295         );
296
297         # handle special commit rules & update type
298         handle_commit_maybe($backend_result, $request);
299
300     } elsif ( $op eq 'generic_confirm' ) {
301         my $backend_result;
302         my $request;
303         try {
304             $request = Koha::Illrequests->find($params->{illrequest_id});
305             $params->{current_branchcode} = C4::Context->mybranch;
306             $backend_result = $request->generic_confirm($params);
307
308             $template->param(
309                 whole => $backend_result,
310                 request => $request,
311             );
312
313             # Prepare availability searching, if required
314             # Get the definition for the z39.50 plugin
315             if ( C4::Context->preference('ILLCheckAvailability') ) {
316                 my $availability = Koha::Illrequest::Availability->new($request->metadata);
317                 my $services = $availability->get_services({
318                     ui_context => 'partners',
319                     metadata => {
320                         name => 'ILL availability - z39.50'
321                     }
322                 });
323                 # Only pass availability searching stuff to the template if
324                 # appropriate
325                 if ( scalar @{$services} > 0 ) {
326                     my $metadata = $availability->prep_metadata($request->metadata);
327                     $template->param( metadata => $metadata );
328                     $template->param(
329                         services_json => scalar encode_json($services)
330                     );
331                     $template->param( services => $services );
332                 }
333             }
334
335             $template->param( error => $params->{error} )
336                 if $params->{error};
337         }
338         catch {
339             my $error;
340             if ( ref($_) eq 'Koha::Exceptions::Ill::NoTargetEmail' ) {
341                 $error = 'no_target_email';
342             }
343             elsif ( ref($_) eq 'Koha::Exceptions::Ill::NoLibraryEmail' ) {
344                 $error = 'no_library_email';
345             }
346             else {
347                 $error = 'unknown_error';
348             }
349             print $cgi->redirect(
350                 "/cgi-bin/koha/ill/ill-requests.pl?" .
351                 "method=generic_confirm&illrequest_id=" .
352                 $params->{illrequest_id} .
353                 "&error=$error" );
354             exit;
355         };
356
357         # handle special commit rules & update type
358         handle_commit_maybe($backend_result, $request);
359     } elsif ( $op eq 'check_out') {
360         my $request = Koha::Illrequests->find($params->{illrequest_id});
361         my $backend_result = $request->check_out($params);
362         $template->param(
363             params  => $params,
364             whole   => $backend_result,
365             request => $request
366         );
367     } elsif ( $op eq 'illlist') {
368
369         # If we receive a pre-filter, make it available to the template
370         my $possible_filters = ['borrowernumber'];
371         my $active_filters = {};
372         foreach my $filter(@{$possible_filters}) {
373             if ($params->{$filter}) {
374                 # We shouldn't need to escape $filter here since we're using
375                 # a whitelist, but just to be sure...
376                 $active_filters->{uri_escape_utf8($filter)} =
377                     uri_escape_utf8(scalar $params->{$filter});
378             }
379         }
380         my @tpl_arr = ();
381         if (keys %{$active_filters}) {
382             foreach my $key (keys %{$active_filters}) {
383                 push @tpl_arr, $key . "=" . $active_filters->{$key};
384             }
385         }
386         $template->param(
387             prefilters => join("&", @tpl_arr)
388         );
389     } elsif ( $op eq "save_comment" ) {
390         die "Wrong CSRF token" unless Koha::Token->new->check_csrf({
391            session_id => scalar $cgi->cookie('CGISESSID'),
392            token      => scalar $cgi->param('csrf_token'),
393         });
394         my $comment = Koha::Illcomment->new({
395             illrequest_id  => scalar $params->{illrequest_id},
396             borrowernumber => $patronnumber,
397             comment        => scalar $params->{comment},
398         });
399         $comment->store();
400         # Redirect to view the whole request
401         print $cgi->redirect("/cgi-bin/koha/ill/ill-requests.pl?method=illview&illrequest_id=".
402             scalar $params->{illrequest_id}
403         );
404         exit;
405
406     } elsif ( $op eq "send_notice" ) {
407         my $illrequest_id = $params->{illrequest_id};
408         my $request = Koha::Illrequests->find($illrequest_id);
409         my $ret = $request->send_patron_notice($params->{notice_code});
410         my $append = '';
411         if ($ret->{result} && scalar @{$ret->{result}->{success}} > 0) {
412             $append .= '&tran_success=' . join(',', @{$ret->{result}->{success}});
413         }
414         if ($ret->{result} && scalar @{$ret->{result}->{fail}} > 0) {
415             $append .= '&tran_fail=' . join(',', @{$ret->{result}->{fail}}.join(','));
416         }
417         # Redirect to view the whole request
418         print $cgi->redirect(
419             "/cgi-bin/koha/ill/ill-requests.pl?method=illview&illrequest_id=".
420             scalar $params->{illrequest_id} . $append
421         );
422         exit;
423     } else {
424         my $request = Koha::Illrequests->find($params->{illrequest_id});
425         my $backend_result = $request->custom_capability($op, $params);
426         $template->param(
427             whole => $backend_result,
428             request => $request,
429         );
430
431         # handle special commit rules & update type
432         handle_commit_maybe($backend_result, $request);
433     }
434 }
435
436 $template->param(
437     backends   => $backends,
438     types      => [ "Book", "Article", "Journal" ],
439     query_type => $op,
440     branches   => Koha::Libraries->search,
441 );
442
443 output_html_with_http_headers( $cgi, $cookie, $template->output );
444
445 sub handle_commit_maybe {
446     my ( $backend_result, $request ) = @_;
447
448     # We need to special case 'commit'
449     if ( $backend_result->{stage} eq 'commit' ) {
450         if ( $backend_result->{next} eq 'illview' ) {
451
452             # Redirect to a view of the newly created request
453             print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
454                   . '?method=illview'
455                   . '&illrequest_id='
456                   . $request->id );
457             exit;
458         }
459         elsif ( $backend_result->{next} eq 'emigrate' ) {
460
461             # Redirect to a view of the newly created request
462             print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
463                   . '?method=migrate'
464                   . '&stage=emigrate'
465                   . '&illrequest_id='
466                   . $request->id );
467             exit;
468         }
469         else {
470             # Redirect to a requests list view
471             redirect_to_list();
472         }
473     }
474 }
475
476 sub redirect_to_list {
477     print $cgi->redirect('/cgi-bin/koha/ill/ill-requests.pl');
478     exit;
479 }