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