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