Bug 36785: Typo unreconized and bilbio in tags 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::ILL::Comment;
29 use Koha::ILL::Requests;
30 use Koha::ILL::Request;
31 use Koha::ILL::Batches;
32 use Koha::ILL::Request::Workflow::Availability;
33 use Koha::ILL::Request::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::ILL::Requests->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::ILL::Request->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::ILL::Request::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::ILL::Requests->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::ILL::Request->new->load_backend( $params->{backend} );
128
129         # Before request creation operations - Preparation
130         my $availability =
131           Koha::ILL::Request::Workflow::Availability->new( $params, 'staff' );
132         my $type_disclaimer =
133         Koha::ILL::Request::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::ILL::Requests->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::ILL::Requests->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::ILL::Requests->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 'cud-edit_action' ) {
219         $op =~ s/^cud-//;
220         # Handle edits to the Illrequest object.
221         # (not the Illrequestattributes)
222         # We simulate the API for backend requests for uniformity.
223         # So, init:
224         my $request = Koha::ILL::Requests->find($params->{illrequest_id});
225         my $batches = Koha::ILL::Batches->search(undef, {
226             order_by => { -asc => 'name' }
227         });
228         if ( !$params->{stage} ) {
229             my $backend_result = {
230                 error   => 0,
231                 status  => '',
232                 message => '',
233                 op  => 'edit_action',
234                 stage   => 'init',
235                 next    => '',
236                 value   => {}
237             };
238             $template->param(
239                 whole          => $backend_result,
240                 request        => $request,
241                 batches        => $batches
242             );
243         } else {
244             my $valid_patron = Koha::Patrons->find( $params->{borrowernumber} );
245             my $valid_biblio = Koha::Biblios->find( $params->{biblio_id} );
246
247             if ( $params->{borrowernumber} && !$valid_patron || $params->{biblio_id} && !$valid_biblio ){
248                 my $error_result = {
249                     error  => 1,
250                     status => $params->{borrowernumber} && !$valid_patron ? 'invalid_patron' : 'invalid_biblio',
251                     op     => 'edit_action',
252                     stage  => 'init',
253                     next   => 'illview',
254                 };
255                 $template->param(
256                     whole   => $error_result,
257                     request => $request,
258                 );
259             }else{
260                 $request->borrowernumber( $params->{borrowernumber} );
261                 $request->biblio_id( $params->{biblio_id} );
262                 $request->batch_id( $params->{batch_id} );
263                 $request->branchcode( $params->{branchcode} );
264                 $request->price_paid( $params->{price_paid} );
265                 $request->notesopac( $params->{notesopac} );
266                 $request->notesstaff( $params->{notesstaff} );
267                 my $alias =
268                     ( length $params->{status_alias} > 0 )
269                     ? $params->{status_alias}
270                     : "-1";
271                 $request->status_alias($alias);
272                 $request->store;
273                 my $backend_result = {
274                     error   => 0,
275                     status  => '',
276                     message => '',
277                     op      => 'edit_action',
278                     stage   => 'commit',
279                     next    => 'illlist',
280                     value   => {}
281                 };
282                 handle_commit_maybe( $backend_result, $request );
283             }
284         }
285
286     } elsif ( $op eq 'moderate_action' ) {
287         # Moderate action is required for an ILL submodule / syspref.
288         # Currently still needs to be implemented.
289         redirect_to_list();
290
291     } elsif ( $op eq 'delete_confirm') {
292         my $request = Koha::ILL::Requests->find($params->{illrequest_id});
293
294         $template->param(
295             request => $request
296         );
297
298     } elsif ( $op eq 'cud-delete' ) {
299
300         # Check if the request is confirmed, if not, redirect
301         # to the confirmation view
302         if ($params->{confirmed}) {
303             # We simply delete the request...
304             Koha::ILL::Requests->find( $params->{illrequest_id} )->delete;
305             # ... then return to list view.
306             redirect_to_list();
307         } else {
308             print $cgi->redirect(
309                 "/cgi-bin/koha/ill/ill-requests.pl?" .
310                 "op=delete_confirm&illrequest_id=" .
311                 $params->{illrequest_id});
312             exit;
313         }
314
315     } elsif ( $op eq 'mark_completed' ) {
316         my $request = Koha::ILL::Requests->find($params->{illrequest_id});
317         my $backend_result = $request->mark_completed($params);
318         $template->param(
319             whole => $backend_result,
320             request => $request,
321         );
322
323         # handle special commit rules & update type
324         handle_commit_maybe($backend_result, $request);
325
326     } elsif ( $op eq 'cud-generic_confirm' ) {
327         $op =~ s/^cud-//;
328         my $backend_result;
329         my $request;
330         try {
331             $request = Koha::ILL::Requests->find($params->{illrequest_id});
332             $params->{current_branchcode} = C4::Context->mybranch;
333             $backend_result = $request->generic_confirm($params);
334
335             $template->param(
336                 whole => $backend_result,
337                 request => $request,
338             );
339
340             # Prepare availability searching, if required
341             # Get the definition for the z39.50 plugin
342             if ( C4::Context->preference('ILLCheckAvailability') ) {
343                 my $availability = Koha::ILL::Request::Workflow::Availability->new(
344                     {
345                         name => 'ILL availability - z39.50',
346                         %{$request->metadata}
347                     },
348                     'partners'
349                 );
350                 my $services = $availability->get_services();
351                 # Only pass availability searching stuff to the template if
352                 # appropriate
353                 if ( scalar @{$services} > 0 ) {
354                     my $metadata = $availability->prep_metadata($request->metadata);
355                     $template->param( metadata => $metadata );
356                     $template->param(
357                         services_json => scalar encode_json($services)
358                     );
359                     $template->param( services => $services );
360                 }
361             }
362
363             $template->param( error => $params->{error} )
364                 if $params->{error};
365         }
366         catch {
367             my $error;
368             if ( ref($_) eq 'Koha::Exceptions::Ill::NoTargetEmail' ) {
369                 $error = 'no_target_email';
370             }
371             elsif ( ref($_) eq 'Koha::Exceptions::Ill::NoLibraryEmail' ) {
372                 $error = 'no_library_email';
373             }
374             else {
375                 $error = 'unknown_error';
376             }
377             print $cgi->redirect(
378                 "/cgi-bin/koha/ill/ill-requests.pl?" .
379                 "op=generic_confirm&illrequest_id=" .
380                 $params->{illrequest_id} .
381                 "&error=$error" );
382             exit;
383         };
384
385         # handle special commit rules & update type
386         handle_commit_maybe($backend_result, $request);
387     } elsif ( $op eq 'cud-check_out') {
388         $op =~ s/^cud-//;
389         my $request = Koha::ILL::Requests->find($params->{illrequest_id});
390         my $backend_result = $request->check_out($params);
391         $template->param(
392             params  => $params,
393             whole   => $backend_result,
394             request => $request
395         );
396     } elsif ( $op eq 'illlist') {
397
398         # If we receive a pre-filter, make it available to the template
399         my $possible_filters = ['borrowernumber', 'batch_id'];
400         my $active_filters = {};
401         foreach my $filter(@{$possible_filters}) {
402             if ($params->{$filter}) {
403                 # We shouldn't need to escape $filter here since we're using
404                 # a whitelist, but just to be sure...
405                 $active_filters->{uri_escape_utf8($filter)} =
406                     uri_escape_utf8(scalar $params->{$filter});
407             }
408         }
409         my @tpl_arr = ();
410         if (keys %{$active_filters}) {
411             foreach my $key (keys %{$active_filters}) {
412                 push @tpl_arr, $key . "=" . $active_filters->{$key};
413             }
414         }
415         $template->param(
416             prefilters => join("&", @tpl_arr)
417         );
418
419         if ($active_filters->{batch_id}) {
420             my $batch_id = $active_filters->{batch_id};
421             if ($batch_id) {
422                 my $batch = Koha::ILL::Batches->find($batch_id);
423                 $template->param(
424                     batch => $batch
425                 );
426             }
427         }
428
429         $template->param( table_actions => encode_json( Koha::ILL::Request->get_staff_table_actions ) );
430     } elsif ( $op eq "cud-save_comment" ) {
431         my $comment = Koha::ILL::Comment->new({
432             illrequest_id  => scalar $params->{illrequest_id},
433             borrowernumber => $patronnumber,
434             comment        => scalar $params->{comment},
435         });
436         $comment->store();
437         # Redirect to view the whole request
438         print $cgi->redirect("/cgi-bin/koha/ill/ill-requests.pl?op=illview&illrequest_id=".
439             scalar $params->{illrequest_id}
440         );
441         exit;
442
443     } elsif ( $op eq "send_notice" ) {
444         my $illrequest_id = $params->{illrequest_id};
445         my $request = Koha::ILL::Requests->find($illrequest_id);
446         my $ret = $request->send_patron_notice($params->{notice_code});
447         my $append = '';
448         if ($ret->{result} && scalar @{$ret->{result}->{success}} > 0) {
449             $append .= '&tran_success=' . join(',', @{$ret->{result}->{success}});
450         }
451         if ($ret->{result} && scalar @{$ret->{result}->{fail}} > 0) {
452             $append .= '&tran_fail=' . join(',', @{$ret->{result}->{fail}}.join(','));
453         }
454         # Redirect to view the whole request
455         print $cgi->redirect(
456             "/cgi-bin/koha/ill/ill-requests.pl?op=illview&illrequest_id=".
457             scalar $params->{illrequest_id} . $append
458         );
459         exit;
460     } elsif ( $op eq "batch_list" ) {
461         # Do not remove, it prevents us falling through to the 'else'
462     } elsif ( $op eq "batch_create" ) {
463         # Do not remove, it prevents us falling through to the 'else'
464     } else {
465         $op =~ s/^cud-//;
466         my $request = Koha::ILL::Requests->find( $params->{illrequest_id} );
467         my $backend_result = $request->custom_capability($op, $params);
468         $template->param(
469             whole => $backend_result,
470             request => $request,
471         );
472
473         # handle special commit rules & update type
474         handle_commit_maybe($backend_result, $request);
475     }
476 }
477
478 $template->param(
479     backends => $backends,
480     types    => [ "Book", "Article", "Journal" ],
481     op       => $op,
482     branches => Koha::Libraries->search,
483 );
484
485 output_html_with_http_headers( $cgi, $cookie, $template->output );
486
487 sub handle_commit_maybe {
488     my ( $backend_result, $request ) = @_;
489
490     # We need to special case 'commit'
491     if ( $backend_result->{stage} eq 'commit' ) {
492         if ( $backend_result->{next} eq 'illview' ) {
493
494             # Redirect to a view of the newly created request
495             print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
496                   . '?op=illview'
497                   . '&illrequest_id='
498                   . $request->id );
499             exit;
500         }
501         elsif ( $backend_result->{next} eq 'emigrate' ) {
502
503             # Redirect to a view of the newly created request
504             print $cgi->redirect( '/cgi-bin/koha/ill/ill-requests.pl'
505                   . '?op=migrate'
506                   . '&stage=emigrate'
507                   . '&illrequest_id='
508                   . $request->id );
509             exit;
510         }
511         else {
512             # Redirect to a requests list view
513             redirect_to_list();
514         }
515     }
516 }
517
518 sub redirect_to_list {
519     print $cgi->redirect('/cgi-bin/koha/ill/ill-requests.pl');
520     exit;
521 }
522
523 # Do any of the available backends provide batch requesting
524 sub have_batch_backends {
525     my ( $backends ) = @_;
526
527     my @have_batch = ();
528
529     foreach my $backend(@{$backends}) {
530         my $can_batch = can_batch($backend);
531         if ($can_batch) {
532             push @have_batch, $backend;
533         }
534     }
535     return \@have_batch;
536 }
537
538 # Does a given backend provide batch requests
539 # FIXME: This should be moved to Koha::Illbackend
540 sub can_batch {
541     my ( $backend ) = @_;
542     my $request = Koha::ILL::Request->new->load_backend( $backend );
543     return $request->_backend_capability( 'provides_batch_requests' );
544 }
545
546 # Get available metadata enrichment plugins
547 sub get_metadata_enrichment {
548     return [] unless C4::Context->config("enable_plugins");
549     my @candidates = Koha::Plugins->new()->GetPlugins({
550         method => 'provides_api'
551     });
552     my @services = ();
553     foreach my $plugin(@candidates) {
554         my $supported = $plugin->provides_api();
555         if ($supported->{type} eq 'search') {
556             push @services, $supported;
557         }
558     }
559     return \@services;
560 }
561
562 # Get ILL availability plugins that can help us with the batch identifier types
563 # we support
564 sub get_ill_availability {
565     my ( $services ) = @_;
566
567     my $id_types = {};
568     foreach my $service(@{$services}) {
569         foreach my $id_supported(keys %{$service->{identifiers_supported}}) {
570             $id_types->{$id_supported} = 1;
571         }
572     }
573
574     my $availability = Koha::ILL::Request::Workflow::Availability->new( $id_types, 'staff' );
575     return $availability->get_services();
576 }