Bug 25716: (QA follow-up) Move additional options to etc/z3950/config.xml
[koha.git] / opac / opac-reserve.pl
1 #!/usr/bin/perl
2
3
4 # Copyright Katipo Communications 2002
5 # Copyright Koha Development team 2012
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI qw ( -utf8 );
25 use C4::Auth qw( get_template_and_user );
26 use C4::Koha qw( getitemtypeimagelocation getitemtypeimagesrc );
27 use C4::Circulation qw( GetBranchItemRule );
28 use C4::Reserves qw( CanItemBeReserved CanBookBeReserved AddReserve GetReservesControlBranch ItemsAnyAvailableAndNotRestricted IsAvailableForItemLevelRequest );
29 use C4::Biblio qw( GetBiblioData GetFrameworkCode );
30 use C4::Output qw( output_html_with_http_headers );
31 use C4::Context;
32 use C4::Members;
33 use C4::Overdues;
34
35 use Koha::AuthorisedValues;
36 use Koha::Biblios;
37 use Koha::CirculationRules;
38 use Koha::Items;
39 use Koha::ItemTypes;
40 use Koha::Checkouts;
41 use Koha::Libraries;
42 use Koha::Patrons;
43 use List::MoreUtils qw( uniq );
44
45 my $maxreserves = C4::Context->preference("maxreserves");
46
47 my $query = CGI->new;
48
49 # if OPACHoldRequests (for placing holds) is disabled, leave immediately
50 if ( ! C4::Context->preference('OPACHoldRequests') ) {
51     print $query->redirect("/cgi-bin/koha/errors/404.pl");
52     exit;
53 }
54
55 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
56     {
57         template_name   => "opac-reserve.tt",
58         query           => $query,
59         type            => "opac",
60     }
61 );
62
63 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
64 my $category = $patron->category;
65
66 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
67 unless ( $can_place_hold_if_available_at_pickup ) {
68     my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
69     if ( @patron_categories ) {
70         my $categorycode = $patron->categorycode;
71         $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
72     }
73 }
74
75 # Pass through any reserve charge
76 my $reservefee = $category->reservefee;
77 if ( $reservefee > 0){
78     $template->param( RESERVE_CHARGE => $reservefee);
79 }
80
81 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
82
83 # There are two ways of calling this script, with a single biblio num
84 # or multiple biblio nums.
85 my $biblionumbers = $query->param('biblionumbers');
86 my $reserveMode = $query->param('reserve_mode');
87 if ($reserveMode && ($reserveMode eq 'single')) {
88     my $bib = $query->param('single_bib');
89     $biblionumbers = "$bib/";
90 }
91 if (! $biblionumbers) {
92     $biblionumbers = $query->param('biblionumber');
93 }
94
95 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
96     $template->param(message=>1, no_biblionumber=>1);
97     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
98     exit;
99 }
100
101 # Pass the numbers to the page so they can be fed back
102 # when the hold is confirmed. TODO: Not necessary?
103 $template->param( biblionumbers => $biblionumbers );
104
105 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
106 my @biblionumbers = split /\//, $biblionumbers;
107 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
108     # TODO: New message?
109     $template->param(message=>1, no_biblionumber=>1);
110     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
111     exit;
112 }
113
114 #
115 #
116 # Here we check that the borrower can actually make reserves Stage 1.
117 #
118 #
119 my $noreserves     = 0;
120 if ( $category->effective_BlockExpiredPatronOpacActions ) {
121     if ( $patron->is_expired ) {
122         # cannot reserve, their card has expired and the rules set mean this is not allowed
123         $noreserves = 1;
124         $template->param( message => 1, expired_patron => 1 );
125     }
126 }
127
128 my $maxoutstanding = C4::Context->preference("maxoutstanding");
129 my $amountoutstanding = $patron->account->balance;
130 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
131     my $amount = sprintf "%.02f", $amountoutstanding;
132     $template->param( message => 1 );
133     $noreserves = 1;
134     $template->param( too_much_oweing => $amount );
135 }
136
137 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
138     $noreserves = 1;
139     $template->param(
140         message => 1,
141         GNA     => 1
142     );
143 }
144
145 if ( $patron->lost && ($patron->lost == 1) ) {
146     $noreserves = 1;
147     $template->param(
148         message => 1,
149         lost    => 1
150     );
151 }
152
153 if ( $patron->is_debarred ) {
154     $noreserves = 1;
155     $template->param(
156         message          => 1,
157         debarred         => 1,
158         debarred_comment => $patron->debarredcomment,
159         debarred_date    => $patron->debarred,
160     );
161 }
162
163 my $holds = $patron->holds;
164 my $reserves_count = $holds->count;
165 $template->param( RESERVES => $holds->unblessed );
166 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
167     $template->param( message => 1 );
168     $noreserves = 1;
169     $template->param( too_many_reserves => $holds->count );
170 }
171
172 if( $noreserves ){
173     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
174     exit;
175 }
176
177
178 # pass the pickup branch along....
179 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
180 $template->param( branch => $branch );
181
182 #
183 #
184 # Here we are carrying out the hold request, possibly
185 # with a specific item for each biblionumber.
186 #
187 #
188 if ( $query->param('place_reserve') ) {
189     my $reserve_cnt = 0;
190     if ($maxreserves) {
191         $reserve_cnt = $patron->holds->count;
192     }
193
194     # List is composed of alternating biblio/item/branch
195     my $selectedItems = $query->param('selecteditems');
196
197     if ($query->param('reserve_mode') eq 'single') {
198         # This indicates non-JavaScript mode, so there was
199         # only a single biblio number selected.
200         my $bib = $query->param('single_bib');
201         my $item = $query->param("checkitem_$bib");
202         if ($item eq 'any') {
203             $item = '';
204         }
205         my $branch = $query->param('branch');
206         $selectedItems = "$bib/$item/$branch/";
207     }
208
209     $selectedItems =~ s!/$!!;
210     my @selectedItems = split /\//, $selectedItems, -1;
211
212     # Make sure there is a biblionum/itemnum/branch triplet for each item.
213     # The itemnum can be 'any', meaning next available.
214     my $selectionCount = @selectedItems;
215     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
216         $template->param(message=>1, bad_data=>1);
217         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
218         exit;
219     }
220
221     my $failed_holds = 0;
222     while (@selectedItems) {
223         my $biblioNum = shift(@selectedItems);
224         my $itemNum   = shift(@selectedItems);
225         my $branch    = shift(@selectedItems);    # i.e., branch code, not name
226
227         my $canreserve = 0;
228
229         my $singleBranchMode = Koha::Libraries->search->count == 1;
230         if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") )
231         {    # single branch mode or disabled user choosing
232             $branch = $patron->branchcode;
233         }
234
235         # FIXME We shouldn't need to fetch the item here
236         my $item = $itemNum ? Koha::Items->find( $itemNum ) : undef;
237         # When choosing a specific item, the default pickup library should be dictated by the default hold policy
238         if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $item ) {
239             my $type = $item->effective_itemtype;
240             my $rule = GetBranchItemRule( $patron->branchcode, $type );
241
242             if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) {
243                 $branch = $patron->branchcode;
244             } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){
245                 $branch = $item->homebranch;
246             } else {
247                 my $policy = $rule->{hold_fulfillment_policy};
248                 $branch = $item->$policy;
249             }
250         }
251
252         # if we have an item, we are placing the hold on the item's bib, in case of analytics
253         if ( $item ) {
254             $biblioNum = $item->biblionumber;
255         }
256
257         # Check for user supplied reserve date
258         my $startdate;
259         if (   C4::Context->preference('AllowHoldDateInFuture')
260             && C4::Context->preference('OPACAllowHoldDateInFuture') )
261         {
262             $startdate = $query->param("reserve_date_$biblioNum");
263         }
264
265         my $patron_expiration_date = $query->param("expiration_date_$biblioNum");
266
267         my $itemtype = $query->param('itemtype') || undef;
268         $itemtype = undef if $itemNum;
269
270         my $biblio = Koha::Biblios->find($biblioNum);
271         my $rank = $biblio->holds->search( { found => [ { "!=" => "W" }, undef ] } )->count + 1;
272         if ( $item ) {
273             $canreserve = 1 if CanItemBeReserved( $patron, $item, $branch )->{status} eq 'OK';
274         }
275         else {
276             $canreserve = 1
277               if CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status} eq 'OK';
278
279             # Inserts a null into the 'itemnumber' field of 'reserves' table.
280             $itemNum = undef;
281         }
282         my $notes = $query->param('notes_'.$biblioNum)||'';
283
284         if (   $maxreserves
285             && $reserve_cnt >= $maxreserves )
286         {
287             $canreserve = 0;
288         }
289
290         unless ( $can_place_hold_if_available_at_pickup ) {
291             my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
292             my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
293             my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
294             if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
295                 $canreserve = 0
296             }
297         }
298
299         # Here we actually do the reserveration. Stage 3.
300         if ($canreserve) {
301             my $reserve_id = AddReserve(
302                 {
303                     branchcode       => $branch,
304                     borrowernumber   => $borrowernumber,
305                     biblionumber     => $biblioNum,
306                     priority         => $rank,
307                     reservation_date => $startdate,
308                     expiration_date  => $patron_expiration_date,
309                     notes            => $notes,
310                     title            => $biblio->title,
311                     itemnumber       => $itemNum,
312                     found            => undef,
313                     itemtype         => $itemtype,
314                 }
315             );
316             $failed_holds++ unless $reserve_id;
317             ++$reserve_cnt;
318         }
319     }
320
321     print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
322     exit;
323 }
324
325 #
326 #
327 # Build hashes of the requested biblio(item)s and items.
328 #
329 #
330
331 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
332 foreach my $biblioNumber (@biblionumbers) {
333
334     my $biblioData = GetBiblioData($biblioNumber);
335     $biblioDataHash{$biblioNumber} = $biblioData;
336
337     my $biblio = Koha::Biblios->find( $biblioNumber );
338     next unless $biblio;
339
340     my $items = Koha::Items->search_ordered(
341         [
342             biblionumber => $biblioNumber,
343             'me.itemnumber' => {
344                 -in => [
345                     $biblio->host_items->get_column('itemnumber')
346                 ]
347             }
348         ],
349         { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] }
350     )->filter_by_visible_in_opac({ patron => $patron });
351
352     $biblioData->{items} = [$items->as_list]; # FIXME Potentially a lot in memory here!
353
354     # Compute the priority rank.
355     $biblioData->{object} = $biblio;
356     my $reservecount = $biblio->holds->search({ found => [ {"!=" => "W"},undef] })->count;
357     $biblioData->{reservecount} = $reservecount;
358     $biblioData->{rank} = $reservecount + 1;
359 }
360
361
362 my $requested_reserves_count = scalar( @biblionumbers );
363 if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
364     $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
365 }
366
367 $template->param( select_item_types => 1 );
368
369
370 #
371 #
372 # Build the template parameters that will show the info
373 # and items for each biblionumber.
374 #
375 #
376
377 my $biblioLoop = [];
378 my $numBibsAvailable = 0;
379 my $itemdata_enumchron = 0;
380 my $itemdata_ccode = 0;
381 my $anyholdable = 0;
382 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
383 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
384 $template->param('item_level_itypes' => $itemLevelTypes);
385
386 my $patron_unblessed = $patron->unblessed;
387 foreach my $biblioNum (@biblionumbers) {
388
389     # Init the bib item with the choices for branch pickup
390     my %biblioLoopIter;
391
392     # Get relevant biblio data.
393     my $biblioData = $biblioDataHash{$biblioNum};
394     if (! $biblioData) {
395         $template->param(message=>1, bad_biblionumber=>$biblioNum);
396         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
397         exit;
398     }
399
400     my @not_available_at = ();
401     my $biblio = $biblioData->{object};
402     foreach my $library ( $pickup_locations->as_list ) {
403         push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
404     }
405
406     my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
407     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
408     $biblioLoopIter{title} = $biblioData->{title};
409     $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
410     $biblioLoopIter{medium} = $biblioData->{medium};
411     $biblioLoopIter{part_number} = $biblioData->{part_number};
412     $biblioLoopIter{part_name} = $biblioData->{part_name};
413     $biblioLoopIter{author} = $biblioData->{author};
414     $biblioLoopIter{rank} = $biblioData->{rank};
415     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
416     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
417
418     if (!$itemLevelTypes && $biblioData->{itemtype}) {
419         $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
420         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
421     }
422
423
424
425     $biblioLoopIter{itemLoop} = [];
426     my $numCopiesAvailable = 0;
427     my $numCopiesOPACAvailable = 0;
428     # iterating through all items first to check if any of them available
429     # to pass this value further inside down to IsAvailableForItemLevelRequest to
430     # it's complicated logic to analyse.
431     # (before this loop was inside that sub loop so it was O(n^2) )
432     my $items_any_available;
433     $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioNum, patron => $patron }) if $patron;
434     foreach my $item (@{$biblioData->{items}}) {
435
436         my $item_info = $item->unblessed;
437         $item_info->{holding_branch} = $item->holding_branch;
438         $item_info->{home_branch}    = $item->home_branch;
439         if ($itemLevelTypes) {
440             my $itemtype = $item->itemtype;
441             $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac',
442                 $itemtypes->{ $itemtype->itemtype }->{'imageurl'} );
443             $item_info->{'translated_description'} =
444               $itemtypes->{ $itemtype->itemtype }->{translated_description};
445         }
446
447         # checking for holds
448         my $holds = $item->current_holds;
449         if ( my $first_hold = $holds->next ) {
450             $item_info->{first_hold} = $first_hold;
451         }
452
453         $item_info->{checkout} = $item->checkout;
454
455         # Check of the transferred documents
456         my $transfer = $item->get_transfer;
457         if ( $transfer && $transfer->in_transit ) {
458             $item_info->{transfertwhen} = $transfer->datesent;
459             $item_info->{transfertfrom} = $transfer->frombranch;
460             $item_info->{transfertto} = $transfer->tobranch;
461             $item_info->{nocancel} = 1;
462         }
463
464         # if the items belongs to a host record, show link to host record
465         if ( $item_info->{biblionumber} ne $biblioNum ) {
466             $item_info->{hostbiblionumber} = $item->biblionumber;
467             $item_info->{hosttitle}        = Koha::Biblios->find( $item_info->{biblionumber} )->title;
468         }
469
470         my $branch = GetReservesControlBranch( $item_info, $patron_unblessed );
471
472         # items_any_available defined outside of the current loop,
473         # so we avoiding loop inside IsAvailableForItemLevelRequest:
474         my $policy_holdallowed =
475             CanItemBeReserved( $patron, $item )->{status} eq 'OK' &&
476             IsAvailableForItemLevelRequest($item, $patron, undef, $items_any_available);
477
478         if ($policy_holdallowed) {
479             my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
480             if ( $opac_hold_policy ne 'N' ) { # If Y or F
481                 $item_info->{available} = 1;
482                 $numCopiesOPACAvailable++;
483                 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
484             }
485             $numCopiesAvailable++;
486
487             unless ( $can_place_hold_if_available_at_pickup ) {
488                 my $items_in_this_library = Koha::Items->search({ biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch });
489                 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
490                 if ( $items_in_this_library->count > $nb_of_items_issued ) {
491                     push @not_available_at, $item->holdingbranch;
492                 }
493             }
494         }
495
496         # Show serial enumeration when needed
497         if ($item_info->{enumchron}) {
498             $itemdata_enumchron = 1;
499         }
500         # Show collection when needed
501         if ($item_info->{ccode}) {
502             $itemdata_ccode = 1;
503         }
504
505         push @{$biblioLoopIter{itemLoop}}, $item_info;
506     }
507     $template->param(
508         itemdata_enumchron => $itemdata_enumchron,
509         itemdata_ccode     => $itemdata_ccode,
510     );
511
512     if ($numCopiesAvailable > 0) {
513         $numBibsAvailable++;
514         $biblioLoopIter{bib_available} = 1;
515         $biblioLoopIter{holdable} = 1;
516         $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
517     }
518     if ($biblioLoopIter{already_reserved}) {
519         $biblioLoopIter{holdable} = undef;
520         $biblioLoopIter{itemholdable} = undef;
521     }
522     if ( $biblioLoopIter{holdable} ) {
523         @not_available_at = uniq @not_available_at;
524         $biblioLoopIter{not_available_at} = \@not_available_at ;
525     }
526
527     unless ( $can_place_hold_if_available_at_pickup ) {
528         @not_available_at = uniq @not_available_at;
529         $biblioLoopIter{not_available_at} = \@not_available_at ;
530         # The record is not holdable is not available at any of the libraries
531         if ( Koha::Libraries->search->count == @not_available_at ) {
532             $biblioLoopIter{holdable} = 0;
533         }
534     }
535
536     my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
537     $biblioLoopIter{holdable} &&= $status eq 'OK';
538     $biblioLoopIter{$status} = 1;
539
540     if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) {
541         # build the allowed item types loop
542         my $rs = $biblio->items->search_ordered(
543             undef,
544             {   select => [ { distinct => 'itype' } ],
545                 as     => 'item_type'
546             }
547         );
548
549         my @item_types =
550           grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' }
551           $rs->get_column('item_type');
552
553         $biblioLoopIter{allowed_item_types} = \@item_types;
554     }
555
556     if ( $status eq 'recall' ) {
557         $biblioLoopIter{recall} = 1;
558     }
559
560     # For multiple holds per record, if a patron has previously placed a hold,
561     # the patron can only place more holds of the same type. That is, if the
562     # patron placed a record level hold, all the holds the patron places must
563     # be record level. If the patron placed an item level hold, all holds
564     # the patron places must be item level
565     my $forced_hold_level = Koha::Holds->search(
566         {
567             borrowernumber => $borrowernumber,
568             biblionumber   => $biblioNum,
569             found          => undef,
570         }
571     )->forced_hold_level();
572     if ($forced_hold_level) {
573         $biblioLoopIter{force_hold}   = 1 if $forced_hold_level eq 'item';
574         $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
575         $biblioLoopIter{forced_hold_level} = $forced_hold_level;
576     }
577
578
579     push @$biblioLoop, \%biblioLoopIter;
580
581     $anyholdable = 1 if $biblioLoopIter{holdable};
582 }
583
584 unless ($pickup_locations->count) {
585     $numBibsAvailable = 0;
586     $anyholdable = 0;
587     $template->param(
588         message => 1,
589         no_pickup_locations => 1
590     );
591 }
592
593 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
594     $template->param( none_available => 1 );
595 }
596
597 if (scalar @biblionumbers > 1) {
598     $template->param( multi_hold => 1);
599 }
600
601 my $show_notes=C4::Context->preference('OpacHoldNotes');
602 $template->param(OpacHoldNotes=>$show_notes);
603
604 # display infos
605 $template->param(bibitemloop => $biblioLoop);
606 # can set reserve date in future
607 if (
608     C4::Context->preference( 'AllowHoldDateInFuture' ) &&
609     C4::Context->preference( 'OPACAllowHoldDateInFuture' )
610     ) {
611     $template->param(
612             reserve_in_future         => 1,
613     );
614 }
615
616 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };