46c5baf39cc6212eca3fa49be7c260ea702a5f44
[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 CGI;
20 use C4::Biblio;
21 use C4::Items;
22 use C4::Auth;    # checkauth, getborrowernumber.
23 use C4::Koha;
24 use C4::Circulation;
25 use C4::Reserves;
26 use C4::Output;
27 use C4::Dates qw/format_date/;
28 use C4::Context;
29 use C4::Members;
30 use C4::Branch; # GetBranches
31 use C4::Debug;
32 # use Data::Dumper;
33
34 my $MAXIMUM_NUMBER_OF_RESERVES = C4::Context->preference("maxreserves");
35
36 my $query = new CGI;
37 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
38     {
39         template_name   => "opac-reserve.tmpl",
40         query           => $query,
41         type            => "opac",
42         authnotrequired => 0,
43         flagsrequired   => { borrow => 1 },
44         debug           => 1,
45     }
46 );
47
48 sub get_out ($$$) {
49         output_html_with_http_headers(shift,shift,shift); # $query, $cookie, $template->output;
50         exit;
51 }
52
53 # get borrower information ....
54 my ( $borr ) = GetMemberDetails( $borrowernumber );
55
56 # get branches and itemtypes
57 my $branches = GetBranches();
58 my $itemtypes = GetItemTypes();
59
60 # get biblionumber.....
61 my $biblionumber = $query->param('biblionumber');
62 if (! $biblionumber) {
63         $template->param(message=>1,no_biblionumber=>1);
64         &get_out($query, $cookie, $template->output);
65 }
66 $template->param( biblionumber => $biblionumber );
67
68 my $bibdata = GetBiblioData($biblionumber);
69 if (! $bibdata) {
70         $template->param(message=>1,bad_biblionumber=>$biblionumber);
71         &get_out($query, $cookie, $template->output);
72 }
73 $template->param($bibdata);             # FIXME: bad form.
74
75 # get the rank number....
76 my ( $rank, $reserves ) = GetReservesFromBiblionumber( $biblionumber);
77 $template->param( reservecount => $rank );
78
79 foreach my $res (@$reserves) {
80     if ( $res->{'found'} eq 'W' ) {
81         $rank--;
82     }
83 }
84
85 $rank++;
86 $template->param( rank => $rank );
87
88 # pass the pickup branch along....
89 my $branch = $query->param('branch');
90 $template->param( branch => $branch );
91
92 # make sure it's a real branch
93 if ( !$branches->{$branch} ) {
94     $branch = '';
95 }
96 $template->param( branchname => $branches->{$branch}->{'branchname'} );
97
98 # make branch selection options...
99 my @branches;
100 my @select_branch;
101 my %select_branches;
102
103 my @CGIbranchlooparray;
104
105 foreach my $branch ( keys %$branches ) {
106     if ($branch) {
107         my %line;
108         $line{branch} = $branches->{$branch}->{'branchname'};
109         $line{value}  = $branch;
110         if ($line{value} eq C4::Context->userenv->{'branch'}) {
111             $line{selected} = 1;
112         }
113         push @CGIbranchlooparray, \%line;
114     }
115 }
116 @CGIbranchlooparray = sort { $a->{branch} cmp $b->{branch} } @CGIbranchlooparray;
117 my $CGIbranchloop = \@CGIbranchlooparray;
118 $template->param( CGIbranch => $CGIbranchloop );
119
120 my @items = GetItemsInfo($biblionumber);
121
122 # an item was previously required to have an itemtype in order to be reserved.
123 # this behavior removed to fix bug 1891 .
124 # my @items = grep { (C4::Context->preference('item-level_itypes') ? $_->{'itype'} : $_->{'itemtype'} ) } @all_items ;
125
126 $template->param( itemcount => scalar(@items) );
127
128 my %itemhash;
129 my $forloan;
130 foreach my $itm (@items) {
131         $debug and warn $itm->{'notforloan'};
132     my $fee = GetReserveFee( undef, $borrowernumber, $itm->{'biblionumber'}, 'a', ( $itm->{'biblioitemnumber'} ) );
133     $itm->{'reservefee'} = sprintf "%.02f", $fee;
134     # pass itype to itemtype for display purposes.  
135     $itm->{'itemtype'} = $itm->{'itype'} if(C4::Context->preference('item-level_itypes'));      
136         $itemhash{$itm->{'itemnumber'}}=$itm;
137     if (!$itm->{'notforloan'} && !($itm->{'itemnotforloan'} > 0)){
138                 $forloan=1;
139         }
140 }
141
142 if ( $query->param('place_reserve') ) {
143     my @bibitems=$query->param('biblioitem');
144     my $notes=$query->param('notes');
145     my $checkitem=$query->param('checkitem');
146     my $found;
147     
148 #    #if we have an item selectionned, and the pickup branch is the same as the holdingbranch of the document, we force the value $rank and $found.
149 #    if ($checkitem ne ''){
150 #        $rank = '0' unless C4::Context->preference('ReservesNeedReturns');
151 #        my $item = $checkitem;
152 #        $item = GetItem($item);
153 #        if ( $item->{'holdingbranch'} eq $branch ){
154 #            $found = 'W' unless C4::Context->preference('ReservesNeedReturns');
155     my @selectedItems = split /\//, $selectedItems;
156
157     # Make sure there is a biblionum/itemnum/branch triplet for each item.
158     # The itemnum can be 'any', meaning next available.
159     my $selectionCount = @selectedItems;
160     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
161         $template->param(message=>1, bad_data=>1);
162         &get_out($query, $cookie, $template->output);
163     }
164
165     while (@selectedItems) {
166         my $biblioNum = shift(@selectedItems);
167         my $itemNum   = shift(@selectedItems);
168         my $branch    = shift(@selectedItems); # i.e., branch code, not name
169
170         my $singleBranchMode = $template->param('singleBranchMode');
171         if ($singleBranchMode) {
172             $branch = $borr->{'branchcode'};
173         }
174     }
175         
176         my $count=@bibitems;
177     @bibitems=sort @bibitems;
178     my $i2=1;
179     my @realbi;
180     $realbi[0]=$bibitems[0];
181     for (my $i=1;$i<$count;$i++) {
182         my $i3=$i2-1;
183         if ($realbi[$i3] ne $bibitems[$i]) {
184             $realbi[$i2]=$bibitems[$i];
185             $i2++;
186         }
187     }
188     # here we actually do the reserveration. Stage 3.
189     if ($query->param('request') eq 'any'){
190         # place a request on 1st available
191         AddReserve($branch,$borrowernumber,$biblionumber,'a',\@realbi,$rank,$notes,$bibdata->{'title'},$checkitem,$found);
192     } else {
193         AddReserve($branch,$borrowernumber,$biblionumber,'a',\@realbi,$rank,$notes,$bibdata->{'title'},$checkitem, $found);
194     }
195     print $query->redirect("/cgi-bin/koha/opac-user.pl#opac-user-holds");
196 }
197 else {
198
199     # Here we check that the borrower can actually make reserves Stage 1.
200     my $noreserves     = 0;
201     my $maxoutstanding = C4::Context->preference("maxoutstanding");
202     $template->param( noreserve => 1 ) unless $maxoutstanding;
203     if ( $borr->{'amountoutstanding'} > $maxoutstanding ) {
204         my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
205         $template->param( message => 1 );
206         $noreserves = 1;
207         $template->param( too_much_oweing => $amount );
208     }
209     if ( $borr->{gonenoaddress} eq 1 ) {
210         $noreserves = 1;
211         $template->param(
212             message => 1,
213             GNA     => 1
214         );
215     }
216     if ( $borr->{lost} eq 1 ) {
217         $noreserves = 1;
218         $template->param(
219             message => 1,
220             lost    => 1
221         );
222     }
223     if ( $borr->{debarred} eq 1 ) {
224         $noreserves = 1;
225         $template->param(
226             message  => 1,
227             debarred => 1
228         );
229     }
230     my @reserves = GetReservesFromBorrowernumber( $borrowernumber );
231     $template->param( RESERVES => \@reserves );
232     if ( scalar(@reserves) >= $MAXIMUM_NUMBER_OF_RESERVES ) {
233         $template->param( message => 1 );
234         $noreserves = 1;
235         $template->param( too_many_reserves => scalar(@reserves));
236     }
237     foreach my $res (@reserves) {
238         if ( $res->{'biblionumber'} == $biblionumber && $res->{'borrowernumber'} == $borrowernumber) {
239             $template->param( message => 1 );
240             $noreserves = 1;
241             $template->param( already_reserved => 1 );
242         }
243     }
244     unless ($noreserves) {
245         $template->param( select_item_types => 1 );
246     }
247 }
248
249
250 my %itemnumbers_of_biblioitem;
251 my @itemnumbers  = @{ get_itemnumbers_of($biblionumber)->{$biblionumber} };
252 my $iteminfos_of = GetItemInfosOf(@itemnumbers);
253
254 foreach my $itemnumber (@itemnumbers) {
255     my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
256     push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
257 }
258
259 my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
260
261 my $notforloan_label_of = get_notforloan_label_of();
262 my $biblioiteminfos_of  = GetBiblioItemInfosOf(@biblioitemnumbers);
263
264 my @itemtypes;
265 foreach my $biblioitemnumber (@biblioitemnumbers) {
266     push @itemtypes, $biblioiteminfos_of->{$biblioitemnumber}{itemtype};
267 }
268
269 my @bibitemloop;
270
271 foreach my $biblioitemnumber (@biblioitemnumbers) {
272     my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
273
274     # Get relevant biblio data.
275     my $biblioData = $biblioDataHash{$biblioNum};
276     if (! $biblioData) {
277         $template->param(message=>1, bad_biblionumber=>$biblioNum);
278         &get_out($query, $cookie, $template->output);
279     }
280
281     foreach
282       my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )
283     {
284                 my $item = $itemhash{$itemnumber};
285
286         $item->{homebranchname} =
287           $branches->{ $item->{homebranch} }{branchname};
288
289         # if the holdingbranch is different than the homebranch, we show the
290         # holdingbranch of the document too
291         if ( $item->{homebranch} ne $item->{holdingbranch} ) {
292             $item->{holdingbranchname} =
293               $branches->{ $item->{holdingbranch} }{branchname};
294         }
295         
296         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
297             $biblioLoopIter{forloan} = 1;
298         }
299     }
300
301     $biblioLoopIter{itemTypeDescription} = $itemTypes->{$biblioData->{itemtype}}{description};
302
303     $biblioLoopIter{itemLoop} = [];
304     my $numCopiesAvailable = 0;
305     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
306         my $itemNum = $itemInfo->{itemnumber};
307         my $itemLoopIter = {};
308
309         $itemLoopIter->{itemnumber} = $itemNum;
310         $itemLoopIter->{barcode} = $itemInfo->{barcode};
311         $itemLoopIter->{homeBranchName} = $branches->{$itemInfo->{homebranch}}{branchname};
312         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
313         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
314         if ($itemLevelTypes) {
315             $itemLoopIter->{description} = $itemInfo->{description};
316             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
317         }
318
319         # If the holdingbranch is different than the homebranch, we show the
320         # holdingbranch of the document too.
321         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
322             $itemLoopIter->{holdingBranchName} =
323               $branches->{ $itemInfo->{holdingbranch} }{branchname};
324         }
325
326         # If the item is currently on loan, we display its return date and
327         # change the background color.
328         my $issues= GetItemIssue($itemNum);
329         if ( $issues->{'date_due'} ) {
330             $item->{date_due} = format_date($issues->{'date_due'});
331             $item->{backgroundcolor} = 'onloan';
332         }
333
334         # checking reserve
335         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemnumber);
336         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
337
338         if ( defined $reservedate ) {
339             $itemLoopIter->{backgroundcolor} = 'reserved';
340             $itemLoopIter->{reservedate}     = format_date($reservedate);
341             $itemLoopIter->{ReservedForBorrowernumber} = $reservedfor;
342             $itemLoopIter->{ReservedForSurname}        = $ItemBorrowerReserveInfo->{'surname'};
343             $itemLoopIter->{ReservedForFirstname}      = $ItemBorrowerReserveInfo->{'firstname'};
344             $itemLoopIter->{ExpectedAtLibrary}         = $expectedAt;
345         }
346
347         # Management of the notforloan document
348         if ( $item->{notforloan} || $item->{itemnotforloan}) {
349             $item->{backgroundcolor} = 'other';
350             $item->{notforloanvalue} =
351               $notforloan_label_of->{ $item->{notforloan} };
352         }
353
354         # Management of lost or long overdue items
355         if ( $item->{itemlost} ) {
356
357             # FIXME localized strings should never be in Perl code
358             $item->{message} =
359                 $item->{itemlost} == 1 ? "(lost)"
360               : $item->{itemlost} == 2 ? "(long overdue)"
361               : "";
362             $item->{backgroundcolor} = 'other';
363         }
364
365         # Check of the transfered documents
366         my ( $transfertwhen, $transfertfrom, $transfertto ) =
367           GetTransfers($itemnumber);
368
369         if ( $transfertwhen ne '' ) {
370             $item->{transfertwhen} = format_date($transfertwhen);
371             $item->{transfertfrom} =
372               $branches->{$transfertfrom}{branchname};
373             $item->{transfertto} = $branches->{$transfertto}{branchname};
374                 $item->{nocancel} = 1;
375         }
376
377         # If there is no loan, return and transfer, we show a checkbox.
378         $item->{notforloan} = $item->{notforloan} || 0;
379
380         if (IsAvailableForItemLevelRequest($itemnumber)) {
381             $item->{available} = 1;
382         }
383
384         # FIXME: move this to a pm
385         my $dbh = C4::Context->dbh;
386         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
387         $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
388         while (my $wait_hashref = $sth2->fetchrow_hashref) {
389             $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
390         }
391             $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemTypes->{ $itemInfo->{itype} }{imageurl} );
392         
393         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
394     }
395
396     if ($numCopiesAvailable > 0) {
397         $numBibsAvailable++;
398         $biblioLoopIter{bib_available} = 1;
399         $biblioLoopIter{holdable} = 1;
400     }
401     if ($biblioLoopIter{already_reserved}) {
402         $biblioLoopIter{holdable} = undef;
403     }
404
405     push @bibitemloop, $biblioitem;
406 }
407
408 if ( $numBibsAvailable == 0 ) {
409     $template->param( none_available => 1, message => 1 );
410 }
411
412 my $itemTableColspan = 5;
413 if (!$template->param('OPACItemHolds')) {
414     $itemTableColspan--;
415 }
416 if ($template->param('singleBranchMode')) {
417     $itemTableColspan--;
418 }
419 $template->param(itemtable_colspan => $itemTableColspan);
420
421 # display infos
422 $template->param(
423         forloan           => $forloan,
424     bibitemloop       => \@bibitemloop,
425 );
426 output_html_with_http_headers $query, $cookie, $template->output;
427