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