Bug 11592: (QA followup) Add missing framework code to ViewPolicy filter calls
[koha.git] / opac / opac-reserve.pl
1 #!/usr/bin/perl
2
3 # Copyright Katipo Communications 2002
4 # Copyright Koha Development team 2012
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 use CGI qw ( -utf8 );
24 use C4::Auth;    # checkauth, getborrowernumber.
25 use C4::Koha;
26 use C4::Circulation;
27 use C4::Reserves;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Output;
31 use C4::Context;
32 use C4::Members;
33 use C4::Branch; # GetBranches
34 use C4::Overdues;
35 use C4::Debug;
36 use Koha::DateUtils;
37 use Koha::Libraries;
38 use Koha::Patrons;
39 use Date::Calc qw/Today Date_to_Days/;
40 use List::MoreUtils qw/uniq/;
41
42 my $maxreserves = C4::Context->preference("maxreserves");
43
44 my $query = new CGI;
45
46 # if RequestOnOpac (for placing holds) is disabled, leave immediately
47 if ( ! C4::Context->preference('RequestOnOpac') ) {
48     print $query->redirect("/cgi-bin/koha/errors/404.pl");
49     exit;
50 }
51
52 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
53     {
54         template_name   => "opac-reserve.tt",
55         query           => $query,
56         type            => "opac",
57         authnotrequired => 0,
58         debug           => 1,
59     }
60 );
61
62 my ($show_holds_count, $show_priority);
63 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
64     m/holds/o and $show_holds_count = 1;
65     m/priority/ and $show_priority = 1;
66 }
67
68 sub get_out {
69         output_html_with_http_headers(shift,shift,shift); # $query, $cookie, $template->output;
70         exit;
71 }
72
73 # get borrower information ....
74 my ( $borr ) = GetMemberDetails( $borrowernumber );
75
76 # check if this user can place a reserve, -1 means use sys pref, 0 means dont block, 1 means block
77 if ( $borr->{'BlockExpiredPatronOpacActions'} ) {
78
79     if ( $borr->{'is_expired'} ) {
80
81         # cannot reserve, their card has expired and the rules set mean this is not allowed
82         $template->param( message => 1, expired_patron => 1 );
83         get_out( $query, $cookie, $template->output );
84     }
85 }
86
87 # Pass through any reserve charge
88 if ($borr->{reservefee} > 0){
89     $template->param( RESERVE_CHARGE => sprintf("%.2f",$borr->{reservefee}));
90 }
91 # get branches and itemtypes
92 my $branches = GetBranches();
93 my $itemTypes = GetItemTypes();
94
95 # There are two ways of calling this script, with a single biblio num
96 # or multiple biblio nums.
97 my $biblionumbers = $query->param('biblionumbers');
98 my $reserveMode = $query->param('reserve_mode');
99 if ($reserveMode && ($reserveMode eq 'single')) {
100     my $bib = $query->param('single_bib');
101     $biblionumbers = "$bib/";
102 }
103 if (! $biblionumbers) {
104     $biblionumbers = $query->param('biblionumber');
105 }
106
107 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
108     $template->param(message=>1, no_biblionumber=>1);
109     &get_out($query, $cookie, $template->output);
110 }
111
112 # Pass the numbers to the page so they can be fed back
113 # when the hold is confirmed. TODO: Not necessary?
114 $template->param( biblionumbers => $biblionumbers );
115
116 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
117 my @biblionumbers = split /\//, $biblionumbers;
118 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
119     # TODO: New message?
120     $template->param(message=>1, no_biblionumber=>1);
121     &get_out($query, $cookie, $template->output);
122 }
123
124
125 # pass the pickup branch along....
126 my $branch = $query->param('branch') || $borr->{'branchcode'} || C4::Context->userenv->{branch} || '' ;
127 ($branches->{$branch}) or $branch = "";     # Confirm branch is real
128 $template->param( branch => $branch );
129
130 # make branch selection options...
131 my $branchloop = GetBranchesLoop($branch);
132
133 # Is the person allowed to choose their branch
134 my $OPACChooseBranch = (C4::Context->preference("OPACAllowUserToChooseBranch")) ? 1 : 0;
135
136 $template->param( choose_branch => $OPACChooseBranch);
137
138 #
139 #
140 # Build hashes of the requested biblio(item)s and items.
141 #
142 #
143
144 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
145 my %itemInfoHash; # Hash of itemnumber to item info.
146 foreach my $biblioNumber (@biblionumbers) {
147
148     my $biblioData = GetBiblioData($biblioNumber);
149     $biblioDataHash{$biblioNumber} = $biblioData;
150
151     my @itemInfos = GetItemsInfo($biblioNumber);
152
153     my $marcrecord= GetMarcBiblio($biblioNumber);
154
155     # flag indicating existence of at least one item linked via a host record
156     my $hostitemsflag;
157     # adding items linked via host biblios
158     my @hostitemInfos = GetHostItemsInfo($marcrecord);
159     if (@hostitemInfos){
160         $hostitemsflag =1;
161         push (@itemInfos,@hostitemInfos);
162     }
163
164     $biblioData->{itemInfos} = \@itemInfos;
165     foreach my $itemInfo (@itemInfos) {
166         $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
167     }
168
169     # Compute the priority rank.
170     my $reserves = GetReservesFromBiblionumber({ biblionumber => $biblioNumber, all_dates => 1 });
171     my $rank = scalar( @$reserves );
172     $biblioData->{reservecount} = 1;    # new reserve
173     foreach my $res (@{$reserves}) {
174         my $found = $res->{found};
175         if ( $found && $found eq 'W' ) {
176             $rank--;
177         }
178         else {
179             $biblioData->{reservecount}++;
180         }
181     }
182     $biblioData->{rank} = $rank + 1;
183 }
184
185 #
186 #
187 # If this is the second time through this script, it
188 # means we are carrying out the hold request, possibly
189 # with a specific item for each biblionumber.
190 #
191 #
192 if ( $query->param('place_reserve') ) {
193     my $reserve_cnt = 0;
194     if ($maxreserves) {
195         $reserve_cnt = GetReservesFromBorrowernumber( $borrowernumber );
196     }
197
198     # List is composed of alternating biblio/item/branch
199     my $selectedItems = $query->param('selecteditems');
200
201     if ($query->param('reserve_mode') eq 'single') {
202         # This indicates non-JavaScript mode, so there was
203         # only a single biblio number selected.
204         my $bib = $query->param('single_bib');
205         my $item = $query->param("checkitem_$bib");
206         if ($item eq 'any') {
207             $item = '';
208         }
209         my $branch = $query->param('branch');
210         $selectedItems = "$bib/$item/$branch/";
211     }
212
213     $selectedItems =~ s!/$!!;
214     my @selectedItems = split /\//, $selectedItems, -1;
215
216     # Make sure there is a biblionum/itemnum/branch triplet for each item.
217     # The itemnum can be 'any', meaning next available.
218     my $selectionCount = @selectedItems;
219     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
220         $template->param(message=>1, bad_data=>1);
221         &get_out($query, $cookie, $template->output);
222     }
223
224     my $failed_holds = 0;
225     while (@selectedItems) {
226         my $biblioNum = shift(@selectedItems);
227         my $itemNum   = shift(@selectedItems);
228         my $branch    = shift(@selectedItems);    # i.e., branch code, not name
229
230         my $canreserve = 0;
231
232         my $singleBranchMode = Koha::Libraries->search->count == 1;
233         if ( $singleBranchMode || !$OPACChooseBranch )
234         {    # single branch mode or disabled user choosing
235             $branch = $borr->{'branchcode'};
236         }
237
238 #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
239         if ( $itemNum ne '' ) {
240             my $hostbiblioNum = GetBiblionumberFromItemnumber($itemNum);
241             if ( $hostbiblioNum ne $biblioNum ) {
242                 $biblioNum = $hostbiblioNum;
243             }
244         }
245
246         my $biblioData = $biblioDataHash{$biblioNum};
247         my $found;
248
249         # Check for user supplied reserve date
250         my $startdate;
251         if (   C4::Context->preference('AllowHoldDateInFuture')
252             && C4::Context->preference('OPACAllowHoldDateInFuture') )
253         {
254             $startdate = $query->param("reserve_date_$biblioNum");
255         }
256
257         my $expiration_date = $query->param("expiration_date_$biblioNum");
258
259       # If a specific item was selected and the pickup branch is the same as the
260       # holdingbranch, force the value $rank and $found.
261         my $rank = $biblioData->{rank};
262         if ( $itemNum ne '' ) {
263             $canreserve = 1 if CanItemBeReserved( $borrowernumber, $itemNum ) eq 'OK';
264             $rank = '0' unless C4::Context->preference('ReservesNeedReturns');
265             my $item = GetItem($itemNum);
266             if ( $item->{'holdingbranch'} eq $branch ) {
267                 $found = 'W'
268                   unless C4::Context->preference('ReservesNeedReturns');
269             }
270         }
271         else {
272             $canreserve = 1 if CanBookBeReserved( $borrowernumber, $biblioNum ) eq 'OK';
273
274             # Inserts a null into the 'itemnumber' field of 'reserves' table.
275             $itemNum = undef;
276         }
277         my $notes = $query->param('notes_'.$biblioNum)||'';
278
279         if (   $maxreserves
280             && $reserve_cnt >= $maxreserves )
281         {
282             $canreserve = 0;
283         }
284
285         my $itemtype = $query->param('itemtype') || undef;
286         $itemtype = undef if $itemNum;
287
288         # Here we actually do the reserveration. Stage 3.
289         if ($canreserve) {
290             my $reserve_id = AddReserve(
291                 $branch,          $borrowernumber, $biblioNum,
292                 [$biblioNum],     $rank,           $startdate,
293                 $expiration_date, $notes,          $biblioData->{title},
294                 $itemNum,         $found,          $itemtype,
295             );
296             $failed_holds++ unless $reserve_id;
297             ++$reserve_cnt;
298         }
299     }
300
301     print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
302     exit;
303 }
304
305 #
306 #
307 # Here we check that the borrower can actually make reserves Stage 1.
308 #
309 #
310 my $noreserves     = 0;
311 my $maxoutstanding = C4::Context->preference("maxoutstanding");
312 $template->param( noreserve => 1 ) unless $maxoutstanding;
313 if ( $borr->{'amountoutstanding'} && ($borr->{'amountoutstanding'} > $maxoutstanding) ) {
314     my $amount = sprintf "%.02f", $borr->{'amountoutstanding'};
315     $template->param( message => 1 );
316     $noreserves = 1;
317     $template->param( too_much_oweing => $amount );
318 }
319
320 if ( $borr->{gonenoaddress} && ($borr->{gonenoaddress} == 1) ) {
321     $noreserves = 1;
322     $template->param(
323         message => 1,
324         GNA     => 1
325     );
326 }
327
328 if ( $borr->{lost} && ($borr->{lost} == 1) ) {
329     $noreserves = 1;
330     $template->param(
331         message => 1,
332         lost    => 1
333     );
334 }
335
336 if ( Koha::Patrons->find( $borrowernumber )->is_debarred ) {
337     $noreserves = 1;
338     $template->param(
339         message          => 1,
340         debarred         => 1,
341         debarred_comment => $borr->{debarredcomment},
342         debarred_date    => $borr->{debarred},
343     );
344 }
345
346 my @reserves = GetReservesFromBorrowernumber( $borrowernumber );
347 my $reserves_count = scalar(@reserves);
348 $template->param( RESERVES => \@reserves );
349 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
350     $template->param( message => 1 );
351     $noreserves = 1;
352     $template->param( too_many_reserves => scalar(@reserves));
353 }
354
355 unless ( $noreserves ) {
356     my $requested_reserves_count = scalar( @biblionumbers );
357     if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
358         $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
359     }
360 }
361
362 unless ($noreserves) {
363     $template->param( select_item_types => 1 );
364 }
365
366
367 #
368 #
369 # Build the template parameters that will show the info
370 # and items for each biblionumber.
371 #
372 #
373 my $notforloan_label_of = get_notforloan_label_of();
374
375 my $biblioLoop = [];
376 my $numBibsAvailable = 0;
377 my $itemdata_enumchron = 0;
378 my $anyholdable = 0;
379 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
380 $template->param('item_level_itypes' => $itemLevelTypes);
381
382 foreach my $biblioNum (@biblionumbers) {
383
384     my $record = GetMarcBiblio($biblioNum);
385     # Init the bib item with the choices for branch pickup
386     my %biblioLoopIter = ( branchloop => $branchloop );
387
388     # Get relevant biblio data.
389     my $biblioData = $biblioDataHash{$biblioNum};
390     if (! $biblioData) {
391         $template->param(message=>1, bad_biblionumber=>$biblioNum);
392         &get_out($query, $cookie, $template->output);
393     }
394
395     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
396     $biblioLoopIter{title} = $biblioData->{title};
397     $biblioLoopIter{subtitle} = GetRecordValue('subtitle', $record, GetFrameworkCode($biblioData->{biblionumber}));
398     $biblioLoopIter{author} = $biblioData->{author};
399     $biblioLoopIter{rank} = $biblioData->{rank};
400     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
401     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
402     $biblioLoopIter{mandatorynotes}=0; #FIXME: For future use
403
404     if (!$itemLevelTypes && $biblioData->{itemtype}) {
405         $biblioLoopIter{translated_description} = $itemTypes->{$biblioData->{itemtype}}{translated_description};
406         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$biblioData->{itemtype}}{imageurl};
407     }
408
409     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
410         if ($itemLevelTypes && $itemInfo->{itype}) {
411             $itemInfo->{translated_description} = $itemTypes->{$itemInfo->{itype}}{translated_description};
412             $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$itemInfo->{itype}}{imageurl};
413         }
414
415         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
416             $biblioLoopIter{forloan} = 1;
417         }
418     }
419
420     $biblioLoopIter{itemLoop} = [];
421     my $numCopiesAvailable = 0;
422     my $numCopiesOPACAvailable = 0;
423     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
424         my $itemNum = $itemInfo->{itemnumber};
425         my $itemLoopIter = {};
426
427         $itemLoopIter->{itemnumber} = $itemNum;
428         $itemLoopIter->{barcode} = $itemInfo->{barcode};
429         $itemLoopIter->{homeBranchName} = $branches->{$itemInfo->{homebranch}}{branchname};
430         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
431         $itemLoopIter->{enumchron} = $itemInfo->{enumchron};
432         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
433         if ($itemLevelTypes) {
434             $itemLoopIter->{translated_description} = $itemInfo->{translated_description};
435             $itemLoopIter->{itype} = $itemInfo->{itype};
436             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
437         }
438
439         # If the holdingbranch is different than the homebranch, we show the
440         # holdingbranch of the document too.
441         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
442             $itemLoopIter->{holdingBranchName} =
443               $branches->{ $itemInfo->{holdingbranch} }{branchname};
444         }
445
446         # If the item is currently on loan, we display its return date and
447         # change the background color.
448         my $issues= GetItemIssue($itemNum);
449         if ( $issues->{'date_due'} ) {
450             $itemLoopIter->{dateDue} = output_pref({ dt => dt_from_string($issues->{date_due}, 'sql'), as_due_date => 1 });
451             $itemLoopIter->{backgroundcolor} = 'onloan';
452         }
453
454         # checking reserve
455         my ($reservedate,$reservedfor,$expectedAt,undef,$wait) = GetReservesFromItemnumber($itemNum);
456         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
457
458         # the item could be reserved for this borrower vi a host record, flag this
459         $reservedfor //= '';
460
461         if ( defined $reservedate ) {
462             $itemLoopIter->{backgroundcolor} = 'reserved';
463             $itemLoopIter->{reservedate}     = output_pref({ dt => dt_from_string($reservedate), dateonly => 1 });
464             $itemLoopIter->{ReservedForBorrowernumber} = $reservedfor;
465             $itemLoopIter->{ReservedForSurname}        = $ItemBorrowerReserveInfo->{'surname'};
466             $itemLoopIter->{ReservedForFirstname}      = $ItemBorrowerReserveInfo->{'firstname'};
467             $itemLoopIter->{ExpectedAtLibrary}         = $expectedAt;
468             #waiting status
469             $itemLoopIter->{waitingdate} = $wait;
470         }
471
472         $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
473         $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
474
475         # Management of the notforloan document
476         if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
477             $itemLoopIter->{backgroundcolor} = 'other';
478             $itemLoopIter->{notforloanvalue} =
479               $notforloan_label_of->{ $itemLoopIter->{notforloan} };
480         }
481
482         # Management of lost or long overdue items
483         if ( $itemInfo->{itemlost} ) {
484
485             # FIXME localized strings should never be in Perl code
486             $itemLoopIter->{message} =
487                 $itemInfo->{itemlost} == 1 ? "(lost)"
488               : $itemInfo->{itemlost} == 2 ? "(long overdue)"
489               : "";
490             $itemInfo->{backgroundcolor} = 'other';
491         }
492
493         # Check of the transfered documents
494         my ( $transfertwhen, $transfertfrom, $transfertto ) =
495           GetTransfers($itemNum);
496         if ( $transfertwhen && ($transfertwhen ne '') ) {
497             $itemLoopIter->{transfertwhen} = output_pref({ dt => dt_from_string($transfertwhen), dateonly => 1 });
498             $itemLoopIter->{transfertfrom} =
499               $branches->{$transfertfrom}{branchname};
500             $itemLoopIter->{transfertto} = $branches->{$transfertto}{branchname};
501             $itemLoopIter->{nocancel} = 1;
502         }
503
504         # if the items belongs to a host record, show link to host record
505         if ( $itemInfo->{biblionumber} ne $biblioNum ) {
506             $biblioLoopIter{hostitemsflag}    = 1;
507             $itemLoopIter->{hostbiblionumber} = $itemInfo->{biblionumber};
508             $itemLoopIter->{hosttitle}        = GetBiblioData( $itemInfo->{biblionumber} )->{title};
509         }
510
511         # If there is no loan, return and transfer, we show a checkbox.
512         $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
513
514         my $branch = GetReservesControlBranch( $itemInfo, $borr );
515
516         my $policy_holdallowed = !$itemLoopIter->{already_reserved};
517         $policy_holdallowed &&=
518             IsAvailableForItemLevelRequest($itemInfo,$borr) &&
519             CanItemBeReserved($borrowernumber,$itemNum) eq 'OK';
520
521         if ($policy_holdallowed) {
522             if ( my $hold_allowed = OPACItemHoldsAllowed( $itemInfo, $borr ) ) {
523                 $itemLoopIter->{available} = 1;
524                 $numCopiesOPACAvailable++;
525                 $biblioLoopIter{force_hold} = 1 if $hold_allowed eq 'F';
526             }
527             $numCopiesAvailable++;
528         }
529
530         $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemTypes->{ $itemInfo->{itype} }{imageurl} );
531
532     # Show serial enumeration when needed
533         if ($itemLoopIter->{enumchron}) {
534             $itemdata_enumchron = 1;
535         }
536
537         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
538     }
539     $template->param( itemdata_enumchron => $itemdata_enumchron );
540
541     if ($numCopiesAvailable > 0) {
542         $numBibsAvailable++;
543         $biblioLoopIter{bib_available} = 1;
544         $biblioLoopIter{holdable} = 1;
545         $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
546     }
547     if ($biblioLoopIter{already_reserved}) {
548         $biblioLoopIter{holdable} = undef;
549         $biblioLoopIter{itemholdable} = undef;
550     }
551     if(not C4::Context->preference('AllowHoldsOnPatronsPossessions') and CheckIfIssuedToPatron($borrowernumber,$biblioNum)) {
552         $biblioLoopIter{holdable} = undef;
553         $biblioLoopIter{already_patron_possession} = 1;
554     }
555
556     $biblioLoopIter{holdable} &&= CanBookBeReserved($borrowernumber,$biblioNum) eq 'OK';
557
558     # For multiple holds per record, if a patron has previously placed a hold,
559     # the patron can only place more holds of the same type. That is, if the
560     # patron placed a record level hold, all the holds the patron places must
561     # be record level. If the patron placed an item level hold, all holds
562     # the patron places must be item level
563     my $forced_hold_level = Koha::Holds->search(
564         {
565             borrowernumber => $borrowernumber,
566             biblionumber   => $biblioNum,
567             found          => undef,
568         }
569     )->forced_hold_level();
570     if ($forced_hold_level) {
571         $biblioLoopIter{force_hold}   = 1 if $forced_hold_level eq 'item';
572         $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
573     }
574
575
576     push @$biblioLoop, \%biblioLoopIter;
577
578     $anyholdable = 1 if $biblioLoopIter{holdable};
579 }
580
581
582 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
583     $template->param( none_available => 1 );
584 }
585
586 my $show_notes=C4::Context->preference('OpacHoldNotes');
587 $template->param(OpacHoldNotes=>$show_notes);
588
589 # display infos
590 $template->param(bibitemloop => $biblioLoop);
591 # can set reserve date in future
592 if (
593     C4::Context->preference( 'AllowHoldDateInFuture' ) &&
594     C4::Context->preference( 'OPACAllowHoldDateInFuture' )
595     ) {
596     $template->param(
597             reserve_in_future         => 1,
598     );
599 }
600
601 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };