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