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