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