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