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