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