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