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