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