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