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