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