Fix for bug 1740, opac reserves
[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 require Exporter;
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 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 # get borrower information ....
49 my ( $borr, $flags ) = GetMemberDetails( $borrowernumber );
50
51 # get branches and itemtypes
52 my $branches = GetBranches();
53 my $itemtypes = GetItemTypes();
54
55 # get biblionumber.....
56 my $biblionumber = $query->param('biblionumber');
57
58 my $bibdata = GetBiblioData($biblionumber);
59 $template->param($bibdata);
60 $template->param( biblionumber => $biblionumber );
61
62 # get the rank number....
63 my ( $rank, $reserves ) = GetReservesFromBiblionumber( $biblionumber);
64 $template->param( reservecount => $rank );
65
66 foreach my $res (@$reserves) {
67     if ( $res->{'found'} eq 'W' ) {
68         $rank--;
69     }
70 }
71
72 $rank++;
73 $template->param( rank => $rank );
74
75 # pass the pickup branch along....
76 my $branch = $query->param('branch');
77 $template->param( branch => $branch );
78
79 # make sure it's a real branch
80 if ( !$branches->{$branch} ) {
81     $branch = '';
82 }
83 $template->param( branchname => $branches->{$branch}->{'branchname'} );
84
85 # make branch selection options...
86 my @branches;
87 my @select_branch;
88 my %select_branches;
89
90 my @CGIbranchlooparray;
91
92 foreach my $branch ( keys %$branches ) {
93     if ($branch) {
94         my %line;
95         $line{branch} = $branches->{$branch}->{'branchname'};
96         $line{value}  = $branch;
97         if ($line{value} eq C4::Context->userenv->{'branch'}) {
98             $line{selected} = 1;
99         }
100         push @CGIbranchlooparray, \%line;
101     }
102 }
103 @CGIbranchlooparray =
104   sort { $a->{branch} cmp $b->{branch} } @CGIbranchlooparray;
105 my $CGIbranchloop = \@CGIbranchlooparray;
106 $template->param( CGIbranch => $CGIbranchloop );
107
108 #### THIS IS A BIT OF A HACK BECAUSE THE BIBLIOITEMS DATA IS A LITTLE MESSED UP!
109 # get the itemtype data....
110 my @items = GetItemsInfo($biblionumber);
111 #######################################################
112 # old version, add so that old templates still work
113 my %types_old;
114 foreach my $itm (@items) {
115     my $ity = $itm->{'itemtype'};
116     unless ( $types_old{$ity} ) {
117         $types_old{$ity}->{'itemtype'} = $ity;
118         $types_old{$ity}->{'branchinfo'}->{ $itm->{'branchcode'} } = 1;
119         $types_old{$ity}->{'description'} = $itm->{'description'};
120     }
121     else {
122         $types_old{$ity}->{'branchinfo'}->{ $itm->{'branchcode'} }++;
123     }
124 }
125
126 foreach my $type ( values %types_old ) {
127     my $copies = "";
128     foreach my $bc ( keys %{ $type->{'branchinfo'} } ) {
129         $copies .=
130             $branches->{$bc}->{'branchname'} . "("
131           . $type->{'branchinfo'}->{$bc} . ")";
132     }
133     $type->{'copies'} = $copies;
134 }
135
136 my @types_old = values %types_old;
137
138 # end old version
139 ################################
140
141 my @temp;
142 foreach my $itm (@items) {
143     push @temp, $itm if $itm->{'itemtype'};
144 }
145 @items = @temp;
146 my $itemcount = @items;
147 $template->param( itemcount => $itemcount );
148
149 my %types;
150 my %itemtypes;
151 my @duedates;
152 #die @items;
153 foreach my $itm (@items) {
154     push @duedates, { date_due => format_date( $itm->{'date_due'} ) }
155       if defined $itm->{'date_due'};
156     $itm->{ $itm->{'publictype'} } = 1;
157     my $fee = GetReserveFee( undef, $borrowernumber, $itm->{'biblionumber'},
158         'a', ( $itm->{'biblioitemnumber'} ) );
159     $fee = sprintf "%.02f", $fee;
160     $itm->{'reservefee'} = $fee;
161     my $pty = $itm->{'publictype'};
162     $itemtypes{ $itm->{'itemtype'} } = $itm;
163     unless ( $types{$pty} ) {
164         $types{$pty}->{'count'} = 1;
165         $types{$pty}->{ $itm->{'itemtype'} } = 1;
166         push @{ $types{$pty}->{'items'} }, $itm;
167     }
168     else {
169         unless ( $types{$pty}->{ $itm->{'itemtype'} } ) {
170             $types{$pty}->{'count'}++;
171             $types{$pty}->{ $itm->{'itemtype'} } = 1;
172             push @{ $types{$pty}->{'items'} }, $itm;
173         }
174     }
175 }
176
177 $template->param( ITEMS => \@duedates );
178
179 my $width = keys %types;
180 my @publictypes = sort { $b->{'count'} <=> $a->{'count'} } values %types;
181 my $typecount;
182 foreach my $pt (@publictypes) {
183     $typecount += $pt->{'count'};
184 }
185 $template->param( onlyone => 1 ) if $typecount == 1;
186
187 my @typerows;
188 for ( my $rownum = 0 ; $rownum < $publictypes[0]->{'count'} ; $rownum++ ) {
189     my @row;
190     foreach my $pty (@publictypes) {
191         my @items = @{ $pty->{'items'} };
192         push @row, $items[$rownum] if defined $items[$rownum];
193     }
194     my $last = @row;
195     $row[ $last - 1 ]->{'last'} = 1 if $last == $width;
196     my $fill = ( $width - $last ) * 2;
197     $fill-- if $fill;
198     push @typerows, { ROW => \@row, fill => $fill };
199 }
200 $template->param( TYPE_ROWS => \@typerows );
201 $width = 2 * $width - 1;
202 $template->param( totalwidth => 2 * $width - 1, );
203
204 if ( $query->param('place_reserve') ) {
205     my @bibitems=$query->param('biblioitem');
206     my $notes=$query->param('notes');
207     my $checkitem=$query->param('checkitem');
208     my $found;
209     
210     #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.
211     if ($checkitem ne ''){
212         $rank = '0' unless C4::Context->preference('ReservesNeedReturns');
213         my $item = $checkitem;
214         $item = GetItem($item);
215         if ( $item->{'holdingbranch'} eq $branch ){
216             $found = 'W' unless C4::Context->preference('ReservesNeedReturns');
217         }
218     }
219         
220         my $count=@bibitems;
221     @bibitems=sort @bibitems;
222     my $i2=1;
223     my @realbi;
224     $realbi[0]=$bibitems[0];
225     for (my $i=1;$i<$count;$i++) {
226         my $i3=$i2-1;
227         if ($realbi[$i3] ne $bibitems[$i]) {
228             $realbi[$i2]=$bibitems[$i];
229             $i2++;
230         }
231     }
232     # here we actually do the reserveration. Stage 3.
233     if ($query->param('request') eq 'any'){
234         # place a request on 1st available
235         AddReserve($branch,$borrowernumber,$biblionumber,'a',\@realbi,$rank,$notes,$bibdata->{'title'},$checkitem,$found);
236     } else {
237         AddReserve($branch,$borrowernumber,$biblionumber,'a',\@realbi,$rank,$notes,$bibdata->{'title'},$checkitem, $found);
238     }
239     print $query->redirect("/cgi-bin/koha/opac-user.pl");
240 }
241 else {
242
243     # Here we check that the borrower can actually make reserves Stage 1.
244     my $noreserves     = 0;
245     my $maxoutstanding = C4::Context->preference("maxoutstanding");
246     $template->param( noreserve => 1 ) unless $maxoutstanding;
247     if ( $borr->{'amountoutstanding'} > $maxoutstanding ) {
248         my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
249         $template->param( message => 1 );
250         $noreserves = 1;
251         $template->param( too_much_oweing => $amount );
252     }
253     if ( $borr->{gonenoaddress} eq 1 ) {
254         $noreserves = 1;
255         $template->param(
256             message => 1,
257             GNA     => 1
258         );
259     }
260     if ( $borr->{lost} eq 1 ) {
261         $noreserves = 1;
262         $template->param(
263             message => 1,
264             lost    => 1
265         );
266     }
267     if ( $borr->{debarred} eq 1 ) {
268         $noreserves = 1;
269         $template->param(
270             message  => 1,
271             debarred => 1
272         );
273     }
274     my @reserves = GetReservesFromBorrowernumber( $borrowernumber );
275     $template->param( RESERVES => \@reserves );
276     if ( scalar(@$reserves) >= $MAXIMUM_NUMBER_OF_RESERVES ) {
277         $template->param( message => 1 );
278         $noreserves = 1;
279         $template->param( too_many_reserves => scalar($reserves));
280     }
281     foreach my $res (@$reserves) {
282         if ( $res->{'biblionumber'} == $biblionumber && $res->{'borrowernumber'} == $borrowernumber) {
283             $template->param( message => 1 );
284             $noreserves = 1;
285             $template->param( already_reserved => 1 );
286         }
287     }
288     unless ($noreserves) {
289         $template->param( TYPES             => \@types_old );
290         $template->param( select_item_types => 1 );
291     }
292 }
293
294
295 my %itemnumbers_of_biblioitem;
296 my @itemnumbers  = @{ get_itemnumbers_of($biblionumber)->{$biblionumber} };
297 my $iteminfos_of = GetItemInfosOf(@itemnumbers);
298
299 foreach my $itemnumber (@itemnumbers) {
300     my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
301     push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
302 }
303
304 my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
305
306 my $notforloan_label_of = get_notforloan_label_of();
307 my $biblioiteminfos_of  = GetBiblioItemInfosOf(@biblioitemnumbers);
308
309 my @itemtypes;
310 foreach my $biblioitemnumber (@biblioitemnumbers) {
311     push @itemtypes, $biblioiteminfos_of->{$biblioitemnumber}{itemtype};
312 }
313
314 my @bibitemloop;
315
316 foreach my $biblioitemnumber (@biblioitemnumbers) {
317     my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
318
319     $biblioitem->{description} =
320       $itemtypes->{ $biblioitem->{itemtype} }{description};
321
322     foreach
323       my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )
324     {
325         my $item = $iteminfos_of->{$itemnumber};
326
327         $item->{homebranchname} =
328           $branches->{ $item->{homebranch} }{branchname};
329
330         # if the holdingbranch is different than the homebranch, we show the
331         # holdingbranch of the document too
332         if ( $item->{homebranch} ne $item->{holdingbranch} ) {
333             $item->{holdingbranchname} =
334               $branches->{ $item->{holdingbranch} }{branchname};
335         }
336         
337 #       add information
338         $item->{itemcallnumber} = $item->{itemcallnumber};
339         
340         # if the item is currently on loan, we display its return date and
341         # change the background color
342         my $issues= GetItemIssue($itemnumber);
343         if ( $issues->{'date_due'} ) {
344             $item->{date_due} = format_date($issues->{'date_due'});
345             $item->{backgroundcolor} = 'onloan';
346         }
347
348         # checking reserve
349         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemnumber);
350         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
351
352         if ( defined $reservedate ) {
353             $item->{backgroundcolor} = 'reserved';
354             $item->{reservedate}     = format_date($reservedate);
355             $item->{ReservedForBorrowernumber}     = $reservedfor;
356             $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
357             $item->{ReservedForFirstname}     = $ItemBorrowerReserveInfo->{'firstname'};
358             $item->{ExpectedAtLibrary}     = $expectedAt;
359             
360         }
361
362         # Management of the notforloan document
363         if ( $item->{notforloan} ) {
364             $item->{backgroundcolor} = 'other';
365             $item->{notforloanvalue} =
366               $notforloan_label_of->{ $item->{notforloan} };
367         }
368
369         # Management of lost or long overdue items
370         if ( $item->{itemlost} ) {
371
372             # FIXME localized strings should never be in Perl code
373             $item->{message} =
374                 $item->{itemlost} == 1 ? "(lost)"
375               : $item->{itemlost} == 2 ? "(long overdue)"
376               : "";
377             $item->{backgroundcolor} = 'other';
378         }
379
380         # Check of the transfered documents
381         my ( $transfertwhen, $transfertfrom, $transfertto ) =
382           GetTransfers($itemnumber);
383
384         if ( $transfertwhen ne '' ) {
385             $item->{transfertwhen} = format_date($transfertwhen);
386             $item->{transfertfrom} =
387               $branches->{$transfertfrom}{branchname};
388             $item->{transfertto} = $branches->{$transfertto}{branchname};
389                 $item->{nocancel} = 1;
390         }
391
392         # If there is no loan, return and transfer, we show a checkbox.
393         $item->{notforloan} = $item->{notforloan} || 0;
394
395         # FIXME: every library will define this differently
396         # An item is available only if:
397         if (
398             not defined $reservedate    # not reserved yet
399             and $issues->{'date_due'} eq ''         # not currently on loan
400             and not $item->{itemlost}   # not lost
401             and not $item->{notforloan} # not forbidden to loan
402             and $transfertwhen eq ''    # not currently on transfert
403           )
404         {
405             $item->{available} = 1;
406         }
407
408         # FIXME: move this to a pm
409         my $dbh = C4::Context->dbh;
410         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W' AND cancellationdate IS NULL");
411         $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
412         while (my $wait_hashref = $sth2->fetchrow_hashref) {
413             $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
414         }
415         $item->{imageurl} = getitemtypeimagesrc() . "/".$itemtypes->{ $item->{itype} }{imageurl};
416         push @{ $biblioitem->{itemloop} }, $item;
417     }
418
419     push @bibitemloop, $biblioitem;
420 }
421
422 # display infos
423 $template->param(
424     bibitemloop       => \@bibitemloop,
425 );
426 output_html_with_http_headers $query, $cookie, $template->output;
427
428 # Local Variables:
429 # tab-width: 8
430 # End: