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