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