Fix for Bug 5715, Adding note about ReservesMaxPickUpDelay value
[koha.git] / opac / opac-reserve.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18 use strict;
19 use warnings;
20 use CGI;
21 use C4::Auth;    # checkauth, getborrowernumber.
22 use C4::Koha;
23 use C4::Circulation;
24 use C4::Reserves;
25 use C4::Biblio;
26 use C4::Items;
27 use C4::Output;
28 use C4::Dates qw/format_date/;
29 use C4::Context;
30 use C4::Members;
31 use C4::Branch; # GetBranches
32 use C4::Debug;
33 # use Data::Dumper;
34
35 my $MAXIMUM_NUMBER_OF_RESERVES = C4::Context->preference("maxreserves");
36
37 my $query = new CGI;
38 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
39     {
40         template_name   => "opac-reserve.tmpl",
41         query           => $query,
42         type            => "opac",
43         authnotrequired => 0,
44         flagsrequired   => { borrow => 1 },
45         debug           => 1,
46     }
47 );
48 my $OPACDisplayRequestPriority = (C4::Context->preference("OPACDisplayRequestPriority")) ? 1 : 0;
49 sub get_out ($$$) {
50         output_html_with_http_headers(shift,shift,shift); # $query, $cookie, $template->output;
51         exit;
52 }
53
54 # get borrower information ....
55 my ( $borr ) = GetMemberDetails( $borrowernumber );
56
57 # get branches and itemtypes
58 my $branches = GetBranches();
59 my $itemTypes = GetItemTypes();
60
61 # There are two ways of calling this script, with a single biblio num
62 # or multiple biblio nums.
63 my $biblionumbers = $query->param('biblionumbers');
64 my $reserveMode = $query->param('reserve_mode');
65 if ($reserveMode && ($reserveMode eq 'single')) {
66     my $bib = $query->param('single_bib');
67     $biblionumbers = "$bib/";
68 }
69 if (! $biblionumbers) {
70     $biblionumbers = $query->param('biblionumber');
71 }
72
73 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
74     $template->param(message=>1, no_biblionumber=>1);
75     &get_out($query, $cookie, $template->output);
76 }
77
78 # Pass the numbers to the page so they can be fed back
79 # when the hold is confirmed. TODO: Not necessary?
80 $template->param( biblionumbers => $biblionumbers );
81
82 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
83 my @biblionumbers = split /\//, $biblionumbers;
84 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
85     # TODO: New message?
86     $template->param(message=>1, no_biblionumber=>1);
87     &get_out($query, $cookie, $template->output);
88 }
89
90 # pass the pickup branch along....
91 my $branch = $query->param('branch') || C4::Context->userenv->{branch} || '' ;
92 ($branches->{$branch}) or $branch = "";     # Confirm branch is real
93 $template->param( branch => $branch );
94
95 # make branch selection options...
96 my $CGIbranchloop = GetBranchesLoop($branch);
97 $template->param( CGIbranch => $CGIbranchloop );
98
99 #
100 #
101 # Build hashes of the requested biblio(item)s and items.
102 #
103 #
104
105 # Hash of biblionumber to biblio/biblioitems record.
106 my %biblioDataHash;
107
108 # Hash of itemnumber to item info.
109 my %itemInfoHash;
110
111 foreach my $biblioNumber (@biblionumbers) {
112
113     my $biblioData = GetBiblioData($biblioNumber);
114     $biblioDataHash{$biblioNumber} = $biblioData;
115
116     my @itemInfos = GetItemsInfo($biblioNumber);
117     $biblioData->{itemInfos} = \@itemInfos;
118     foreach my $itemInfo (@itemInfos) {
119         $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
120     }
121
122     # Compute the priority rank.
123     my ( $rank, $reserves ) = GetReservesFromBiblionumber($biblioNumber,1);
124     $biblioData->{reservecount} = $rank;
125     foreach my $res (@$reserves) {
126         my $found = $res->{'found'};
127         if ( $found && ($found eq 'W') ) {
128             $rank--;
129         }
130     }
131     $rank++;
132     $biblioData->{rank} = $rank;
133 }
134
135 #
136 #
137 # If this is the second time through this script, it
138 # means we are carrying out the hold request, possibly
139 # with a specific item for each biblionumber.
140 #
141 #
142 if ( $query->param('place_reserve') ) {
143     my $notes = $query->param('notes');
144         my $canreserve=0;
145
146     # List is composed of alternating biblio/item/branch
147     my $selectedItems = $query->param('selecteditems');
148
149     if ($query->param('reserve_mode') eq 'single') {
150         # This indicates non-JavaScript mode, so there was
151         # only a single biblio number selected.
152         my $bib = $query->param('single_bib');
153         my $item = $query->param("checkitem_$bib");
154         if ($item eq 'any') {
155             $item = '';
156         }
157         my $branch = $query->param('branch');
158         $selectedItems = "$bib/$item/$branch/";
159     }
160
161     $selectedItems =~ s!/$!!;
162     my @selectedItems = split /\//, $selectedItems, -1;
163
164     # Make sure there is a biblionum/itemnum/branch triplet for each item.
165     # The itemnum can be 'any', meaning next available.
166     my $selectionCount = @selectedItems;
167     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
168         $template->param(message=>1, bad_data=>1);
169         &get_out($query, $cookie, $template->output);
170     }
171
172     while (@selectedItems) {
173         my $biblioNum = shift(@selectedItems);
174         my $itemNum   = shift(@selectedItems);
175         my $branch    = shift(@selectedItems); # i.e., branch code, not name
176
177         my $singleBranchMode = $template->param('singleBranchMode');
178         if ($singleBranchMode) {
179             $branch = $borr->{'branchcode'};
180         }
181
182         my $biblioData = $biblioDataHash{$biblioNum};
183         my $found;
184
185         # Check for user supplied reserve date
186         my $startdate;
187         if (
188             C4::Context->preference( 'AllowHoldDateInFuture' ) &&
189             C4::Context->preference( 'OPACAllowHoldDateInFuture' )
190             ) {
191             $startdate = $query->param("reserve_date_$biblioNum");
192         }
193         
194         my $expiration_date = $query->param("expiration_date_$biblioNum");
195
196         # If a specific item was selected and the pickup branch is the same as the
197         # holdingbranch, force the value $rank and $found.
198         my $rank = $biblioData->{rank};
199         if ($itemNum ne ''){
200                 $canreserve = 1 if CanItemBeReserved($borrowernumber,$itemNum);
201             $rank = '0' unless C4::Context->preference('ReservesNeedReturns');
202             my $item = GetItem($itemNum);
203             if ( $item->{'holdingbranch'} eq $branch ){
204                 $found = 'W' unless C4::Context->preference('ReservesNeedReturns');
205             }
206         }
207         else {
208                 $canreserve = 1 if CanBookBeReserved($borrowernumber,$biblioNum);
209             # Inserts a null into the 'itemnumber' field of 'reserves' table.
210             $itemNum = undef;
211         }
212
213         # Here we actually do the reserveration. Stage 3.
214         AddReserve($branch, $borrowernumber, $biblioNum, 'a', [$biblioNum], $rank, $startdate, $expiration_date, $notes,
215                    $biblioData->{'title'}, $itemNum, $found) if ($canreserve);
216     }
217
218     print $query->redirect("/cgi-bin/koha/opac-user.pl#opac-user-holds");
219     exit;
220 }
221
222 #
223 #
224 # Here we check that the borrower can actually make reserves Stage 1.
225 #
226 #
227 my $noreserves     = 0;
228 my $maxoutstanding = C4::Context->preference("maxoutstanding");
229 $template->param( noreserve => 1 ) unless $maxoutstanding;
230 if ( $borr->{'amountoutstanding'} && ($borr->{'amountoutstanding'} > $maxoutstanding) ) {
231     my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
232     $template->param( message => 1 );
233     $noreserves = 1;
234     $template->param( too_much_oweing => $amount );
235 }
236 if ( $borr->{gonenoaddress} && ($borr->{gonenoaddress} eq 1) ) {
237     $noreserves = 1;
238     $template->param(
239                      message => 1,
240                      GNA     => 1
241                     );
242 }
243 if ( $borr->{lost} && ($borr->{lost} eq 1) ) {
244     $noreserves = 1;
245     $template->param(
246                      message => 1,
247                      lost    => 1
248                     );
249 }
250 if ( $borr->{debarred} && ($borr->{debarred} eq 1) ) {
251     $noreserves = 1;
252     $template->param(
253                      message  => 1,
254                      debarred => 1
255                     );
256 }
257
258 my @reserves = GetReservesFromBorrowernumber( $borrowernumber );
259 $template->param( RESERVES => \@reserves );
260 if ( $MAXIMUM_NUMBER_OF_RESERVES && (scalar(@reserves) >= $MAXIMUM_NUMBER_OF_RESERVES) ) {
261     $template->param( message => 1 );
262     $noreserves = 1;
263     $template->param( too_many_reserves => scalar(@reserves));
264 }
265 foreach my $res (@reserves) {
266     foreach my $biblionumber (@biblionumbers) {
267         if ( $res->{'biblionumber'} == $biblionumber && $res->{'borrowernumber'} == $borrowernumber) {
268 #            $template->param( message => 1 );
269 #            $noreserves = 1;
270 #            $template->param( already_reserved => 1 );
271             $biblioDataHash{$biblionumber}->{already_reserved} = 1;
272         }
273     }
274 }
275
276 unless ($noreserves) {
277     $template->param( select_item_types => 1 );
278 }
279
280
281 #
282 #
283 # Build the template parameters that will show the info
284 # and items for each biblionumber.
285 #
286 #
287 my $notforloan_label_of = get_notforloan_label_of();
288
289 my $biblioLoop = [];
290 my $numBibsAvailable = 0;
291 my $itemdata_enumchron = 0;
292 my $anyholdable;
293 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
294 $template->param('item_level_itypes' => $itemLevelTypes);
295
296 foreach my $biblioNum (@biblionumbers) {
297
298     my $record = GetMarcBiblio($biblioNum);
299     # Init the bib item with the choices for branch pickup
300     my %biblioLoopIter = ( branchChoicesLoop => $CGIbranchloop );
301
302     # Get relevant biblio data.
303     my $biblioData = $biblioDataHash{$biblioNum};
304     if (! $biblioData) {
305         $template->param(message=>1, bad_biblionumber=>$biblioNum);
306         &get_out($query, $cookie, $template->output);
307     }
308
309     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
310     $biblioLoopIter{title} = $biblioData->{title};
311     $biblioLoopIter{subtitle} = GetRecordValue('subtitle', $record, GetFrameworkCode($biblioData->{biblionumber}));
312     $biblioLoopIter{author} = $biblioData->{author};
313     $biblioLoopIter{rank} = $biblioData->{rank};
314     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
315     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
316
317     if (!$itemLevelTypes && $biblioData->{itemtype}) {
318         $biblioLoopIter{description} = $itemTypes->{$biblioData->{itemtype}}{description};
319         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$biblioData->{itemtype}}{imageurl};
320     }
321
322     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
323         $debug and warn $itemInfo->{'notforloan'};
324
325         # Get reserve fee.
326         my $fee = GetReserveFee(undef, $borrowernumber, $itemInfo->{'biblionumber'}, 'a',
327                                 ( $itemInfo->{'biblioitemnumber'} ) );
328         $itemInfo->{'reservefee'} = sprintf "%.02f", ($fee ? $fee : 0.0);
329
330         if ($itemLevelTypes && $itemInfo->{itype}) {
331             $itemInfo->{description} = $itemTypes->{$itemInfo->{itype}}{description};
332             $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$itemInfo->{itype}}{imageurl};
333         }
334
335         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
336             $biblioLoopIter{forloan} = 1;
337         }
338     }
339
340     $biblioLoopIter{itemLoop} = [];
341     my $numCopiesAvailable = 0;
342     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
343         my $itemNum = $itemInfo->{itemnumber};
344         my $itemLoopIter = {};
345
346         $itemLoopIter->{itemnumber} = $itemNum;
347         $itemLoopIter->{barcode} = $itemInfo->{barcode};
348         $itemLoopIter->{homeBranchName} = $branches->{$itemInfo->{homebranch}}{branchname};
349         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
350         $itemLoopIter->{enumchron} = $itemInfo->{enumchron};
351         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
352         if ($itemLevelTypes) {
353             $itemLoopIter->{description} = $itemInfo->{description};
354             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
355         }
356
357         # If the holdingbranch is different than the homebranch, we show the
358         # holdingbranch of the document too.
359         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
360             $itemLoopIter->{holdingBranchName} =
361               $branches->{ $itemInfo->{holdingbranch} }{branchname};
362         }
363
364         # If the item is currently on loan, we display its return date and
365         # change the background color.
366         my $issues= GetItemIssue($itemNum);
367         if ( $issues->{'date_due'} ) {
368             $itemLoopIter->{dateDue} = format_date($issues->{'date_due'});
369             $itemLoopIter->{backgroundcolor} = 'onloan';
370         }
371
372         # checking reserve
373         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemNum);
374         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
375
376         if ( defined $reservedate ) {
377             $itemLoopIter->{backgroundcolor} = 'reserved';
378             $itemLoopIter->{reservedate}     = format_date($reservedate);
379             $itemLoopIter->{ReservedForBorrowernumber} = $reservedfor;
380             $itemLoopIter->{ReservedForSurname}        = $ItemBorrowerReserveInfo->{'surname'};
381             $itemLoopIter->{ReservedForFirstname}      = $ItemBorrowerReserveInfo->{'firstname'};
382             $itemLoopIter->{ExpectedAtLibrary}         = $expectedAt;
383         }
384
385         $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
386         $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
387
388         # Management of the notforloan document
389         if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
390             $itemLoopIter->{backgroundcolor} = 'other';
391             $itemLoopIter->{notforloanvalue} =
392               $notforloan_label_of->{ $itemLoopIter->{notforloan} };
393         }
394
395         # Management of lost or long overdue items
396         if ( $itemInfo->{itemlost} ) {
397
398             # FIXME localized strings should never be in Perl code
399             $itemLoopIter->{message} =
400                 $itemInfo->{itemlost} == 1 ? "(lost)"
401               : $itemInfo->{itemlost} == 2 ? "(long overdue)"
402               : "";
403             $itemInfo->{backgroundcolor} = 'other';
404         }
405
406         # Check of the transfered documents
407         my ( $transfertwhen, $transfertfrom, $transfertto ) =
408           GetTransfers($itemNum);
409         if ( $transfertwhen && ($transfertwhen ne '') ) {
410             $itemLoopIter->{transfertwhen} = format_date($transfertwhen);
411             $itemLoopIter->{transfertfrom} =
412               $branches->{$transfertfrom}{branchname};
413             $itemLoopIter->{transfertto} = $branches->{$transfertto}{branchname};
414             $itemLoopIter->{nocancel} = 1;
415         }
416
417         # If there is no loan, return and transfer, we show a checkbox.
418         $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
419
420         my $branch = C4::Circulation::_GetCircControlBranch($itemLoopIter, $borr);
421
422         my $branchitemrule = GetBranchItemRule( $branch, $itemInfo->{'itype'} );
423         my $policy_holdallowed = 1;
424
425         if ( $branchitemrule->{'holdallowed'} == 0 ||
426                 ( $branchitemrule->{'holdallowed'} == 1 && $borr->{'branchcode'} ne $itemInfo->{'homebranch'} ) ) {
427             $policy_holdallowed = 0;
428         }
429
430         if (IsAvailableForItemLevelRequest($itemNum) and $policy_holdallowed and CanItemBeReserved($borrowernumber,$itemNum)) {
431             $itemLoopIter->{available} = 1;
432             $numCopiesAvailable++;
433         }
434
435         # FIXME: move this to a pm
436         my $dbh = C4::Context->dbh;
437         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
438         $sth2->execute($itemLoopIter->{ReservedForBorrowernumber}, $itemNum);
439         while (my $wait_hashref = $sth2->fetchrow_hashref) {
440             $itemLoopIter->{waitingdate} = format_date($wait_hashref->{waitingdate});
441         }
442         $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemTypes->{ $itemInfo->{itype} }{imageurl} );
443
444     # Show serial enumeration when needed
445     if ($itemLoopIter->{enumchron}) {
446         $itemdata_enumchron = 1;
447     }
448     $template->param( itemdata_enumchron => $itemdata_enumchron );
449
450         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
451     }
452
453     if ($numCopiesAvailable > 0) {
454         $numBibsAvailable++;
455         $biblioLoopIter{bib_available} = 1;
456         $biblioLoopIter{holdable} = 1;
457         $anyholdable = 1;
458     }
459     if ($biblioLoopIter{already_reserved}) {
460         $biblioLoopIter{holdable} = undef;
461         $anyholdable = undef;
462     }
463     if(not CanBookBeReserved($borrowernumber,$biblioNum)){
464         $biblioLoopIter{holdable} = undef;
465         $anyholdable = undef;
466     }
467
468     push @$biblioLoop, \%biblioLoopIter;
469 }
470
471 if ( $numBibsAvailable == 0 || !$anyholdable) {
472     $template->param( none_available => 1 );
473 }
474
475 my $itemTableColspan = 5;
476 if (!$template->param('OPACItemHolds')) {
477     $itemTableColspan--;
478 }
479 if ($template->param('singleBranchMode')) {
480     $itemTableColspan--;
481 }
482 $template->param(itemtable_colspan => $itemTableColspan);
483
484 # display infos
485 $template->param(bibitemloop => $biblioLoop);
486 $template->param( showpriority=>1 ) if $OPACDisplayRequestPriority;
487 # can set reserve date in future
488 if (
489     C4::Context->preference( 'AllowHoldDateInFuture' ) &&
490     C4::Context->preference( 'OPACAllowHoldDateInFuture' )
491     ) {
492     $template->param(
493             reserve_in_future         => 1,
494     );
495 }
496
497 $template->param( DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar() );
498
499 output_html_with_http_headers $query, $cookie, $template->output;
500