Convert opac-reserve to use GetBranchesLoop.
[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 $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
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 #Debug
100 #output_html_with_http_headers($query,$cookie,"<html><head></head><body> @biblionumbers </body></html>\n");
101 #exit;
102 #my %bibdata;
103 #my $rank;
104 #my $biblionumber;
105 #my $bibdata;
106 #my %itemhash;
107 #my $forloan;
108
109 #
110 #
111 # Build hashes of the requested biblio(item)s and items.
112 #
113 #
114
115 # Hash of biblionumber to biblio/biblioitems record.
116 my %biblioDataHash;
117
118 # Hash of itemnumber to item info.
119 my %itemInfoHash;
120
121 foreach my $biblioNumber (@biblionumbers) {
122
123     my $biblioData = GetBiblioData($biblioNumber);
124     $biblioDataHash{$biblioNumber} = $biblioData;
125
126     my @itemInfos = GetItemsInfo($biblioNumber);
127     $biblioData->{itemInfos} = \@itemInfos;
128     foreach my $itemInfo (@itemInfos) {
129         $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
130     }
131
132     # Compute the priority rank.
133     my ( $rank, $reserves ) = GetReservesFromBiblionumber($biblioNumber);
134     $biblioData->{reservecount} = $rank;
135     foreach my $res (@$reserves) {
136         my $found = $res->{'found'};
137         if ( $found && ($found eq 'W') ) {
138             $rank--;
139         }
140     }
141     $rank++;
142     $biblioData->{rank} = $rank;
143 }
144
145 #
146 #
147 # If this is the second time through this script, it
148 # means we are carrying out the hold request, possibly
149 # with a specific item for each biblionumber.
150 #
151 #
152 if ( $query->param('place_reserve') ) {
153
154     my $notes = $query->param('notes');
155
156     # List is composed of alternating biblio/item/branch
157     my $selectedItems = $query->param('selecteditems');
158
159     if ($query->param('reserve_mode') eq 'single') {
160         # This indicates non-JavaScript mode, so there was
161         # only a single biblio number selected.
162         my $bib = $query->param('single_bib');
163         my $item = $query->param("checkitem_$bib");
164         if ($item eq 'any') {
165             $item = '';
166         }
167         my $branch = $query->param('branch');
168         $selectedItems = "$bib/$item/$branch/";
169     }
170     
171     my @selectedItems = split /\//, $selectedItems;
172
173     # Make sure there is a biblionum/itemnum/branch triplet for each item.
174     # The itemnum can be 'any', meaning next available.
175     my $selectionCount = @selectedItems;
176     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
177         $template->param(message=>1, bad_data=>1);
178         &get_out($query, $cookie, $template->output);
179     }
180
181     while (@selectedItems) {
182         my $biblioNum = shift(@selectedItems);
183         my $itemNum   = shift(@selectedItems);
184         my $branch    = shift(@selectedItems); # i.e., branch code, not name
185
186         my $singleBranchMode = $template->param('singleBranchMode');
187         if ($singleBranchMode) {
188             $branch = $borr->{'branchcode'};
189         }
190
191         my $biblioData = $biblioDataHash{$biblioNum};
192         my $found;
193         
194         # If a specific item was selected and the pickup branch is the same as the
195         # holdingbranch, force the value $rank and $found.
196         my $rank = $biblioData->{rank};
197         if ($itemNum ne ''){
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             $itemNum = undef;
207         }
208         
209         # Here we actually do the reserveration. Stage 3.
210         AddReserve($branch, $borrowernumber, $biblioNum, 'a', [$biblioNum], $rank, $notes,
211                    $biblioData->{'title'}, $itemNum, $found);
212     }
213
214     print $query->redirect("/cgi-bin/koha/opac-user.pl#opac-user-holds");
215     exit;
216 }
217
218 #
219 #
220 # Here we check that the borrower can actually make reserves Stage 1.
221 #
222 #
223 my $noreserves     = 0;
224 my $maxoutstanding = C4::Context->preference("maxoutstanding");
225 $template->param( noreserve => 1 ) unless $maxoutstanding;
226 if ( $borr->{'amountoutstanding'} && ($borr->{'amountoutstanding'} > $maxoutstanding) ) {
227     my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
228     $template->param( message => 1 );
229     $noreserves = 1;
230     $template->param( too_much_oweing => $amount );
231 }
232 if ( $borr->{gonenoaddress} && ($borr->{gonenoaddress} eq 1) ) {
233     $noreserves = 1;
234     $template->param(
235                      message => 1,
236                      GNA     => 1
237                     );
238 }
239 if ( $borr->{lost} && ($borr->{lost} eq 1) ) {
240     $noreserves = 1;
241     $template->param(
242                      message => 1,
243                      lost    => 1
244                     );
245 }
246 if ( $borr->{debarred} && ($borr->{debarred} eq 1) ) {
247     $noreserves = 1;
248     $template->param(
249                      message  => 1,
250                      debarred => 1
251                     );
252 }
253
254 my @reserves = GetReservesFromBorrowernumber( $borrowernumber );
255 $template->param( RESERVES => \@reserves );
256 if ( scalar(@reserves) >= $MAXIMUM_NUMBER_OF_RESERVES ) {
257     $template->param( message => 1 );
258     $noreserves = 1;
259     $template->param( too_many_reserves => scalar(@reserves));
260 }
261 foreach my $res (@reserves) {
262     foreach my $biblionumber (@biblionumbers) {
263         if ( $res->{'biblionumber'} == $biblionumber && $res->{'borrowernumber'} == $borrowernumber) {
264 #            $template->param( message => 1 );
265 #            $noreserves = 1;
266 #            $template->param( already_reserved => 1 );
267             $biblioDataHash{$biblionumber}->{already_reserved} = 1;
268         }
269     }
270 }
271
272 unless ($noreserves) {
273     $template->param( select_item_types => 1 );
274 }
275
276
277 #
278 #
279 # Build the template parameters that will show the info
280 # and items for each biblionumber.
281 #
282 #
283 my $notforloan_label_of = get_notforloan_label_of();
284
285 my $biblioLoop = [];
286 my $numBibsAvailable = 0;
287 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
288 $template->param('item-level_itypes' => $itemLevelTypes);
289
290 foreach my $biblioNum (@biblionumbers) {
291
292     my $record = GetMarcBiblio($biblioNum);
293     my $subtitle = C4::Biblio::get_koha_field_from_marc('bibliosubtitle', 'subtitle', $record, '');
294     # Init the bib item with the choices for branch pickup
295     my %biblioLoopIter = ( branchChoicesLoop => $CGIbranchloop );
296
297     # Get relevant biblio data.
298     my $biblioData = $biblioDataHash{$biblioNum};
299     if (! $biblioData) {
300         $template->param(message=>1, bad_biblionumber=>$biblioNum);
301         &get_out($query, $cookie, $template->output);
302     }
303
304     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
305     $biblioLoopIter{title} = $biblioData->{title};
306     $biblioLoopIter{subtitle} = $subtitle;
307     $biblioLoopIter{author} = $biblioData->{author};
308     $biblioLoopIter{rank} = $biblioData->{rank};
309     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
310     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
311
312     if (!$itemLevelTypes && $biblioData->{itemtype}) {
313         $biblioLoopIter{description} = $itemTypes->{$biblioData->{itemtype}}{description};
314         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$biblioData->{itemtype}}{imageurl};
315     }
316
317     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
318         $debug and warn $itemInfo->{'notforloan'};
319
320         # Get reserve fee.
321         my $fee = GetReserveFee(undef, $borrowernumber, $itemInfo->{'biblionumber'}, 'a',
322                                 ( $itemInfo->{'biblioitemnumber'} ) );
323         $itemInfo->{'reservefee'} = sprintf "%.02f", ($fee ? $fee : 0.0);
324         
325         if ($itemLevelTypes && $itemInfo->{itype}) {
326             $itemInfo->{description} = $itemTypes->{$itemInfo->{itype}}{description};
327             $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$itemInfo->{itype}}{imageurl};
328         }
329         
330         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
331             $biblioLoopIter{forloan} = 1;
332         }
333     }
334
335     $biblioLoopIter{itemTypeDescription} = $itemTypes->{$biblioData->{itemtype}}{description};
336
337     $biblioLoopIter{itemLoop} = [];
338     my $numCopiesAvailable = 0;
339     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
340         my $itemNum = $itemInfo->{itemnumber};
341         my $itemLoopIter = {};
342
343         $itemLoopIter->{itemnumber} = $itemNum;
344         $itemLoopIter->{barcode} = $itemInfo->{barcode};
345         $itemLoopIter->{homeBranchName} = $branches->{$itemInfo->{homebranch}}{branchname};
346         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
347         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
348         if ($itemLevelTypes) {
349             $itemLoopIter->{description} = $itemInfo->{description};
350             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
351         }
352
353         # If the holdingbranch is different than the homebranch, we show the
354         # holdingbranch of the document too.
355         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
356             $itemLoopIter->{holdingBranchName} =
357               $branches->{ $itemInfo->{holdingbranch} }{branchname};
358         }
359
360         # If the item is currently on loan, we display its return date and
361         # change the background color.
362         my $issues= GetItemIssue($itemNum);
363         if ( $issues->{'date_due'} ) {
364             $itemLoopIter->{dateDue} = format_date($issues->{'date_due'});
365             $itemLoopIter->{backgroundcolor} = 'onloan';
366         }
367
368         # checking reserve
369         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemNum);
370         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
371
372         if ( defined $reservedate ) {
373             $itemLoopIter->{backgroundcolor} = 'reserved';
374             $itemLoopIter->{reservedate}     = format_date($reservedate);
375             $itemLoopIter->{ReservedForBorrowernumber} = $reservedfor;
376             $itemLoopIter->{ReservedForSurname}        = $ItemBorrowerReserveInfo->{'surname'};
377             $itemLoopIter->{ReservedForFirstname}      = $ItemBorrowerReserveInfo->{'firstname'};
378             $itemLoopIter->{ExpectedAtLibrary}         = $expectedAt;
379         }
380
381         $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
382         $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
383
384         # Management of the notforloan document
385         if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
386             $itemLoopIter->{backgroundcolor} = 'other';
387             $itemLoopIter->{notforloanvalue} =
388               $notforloan_label_of->{ $itemLoopIter->{notforloan} };
389         }
390
391         # Management of lost or long overdue items
392         if ( $itemInfo->{itemlost} ) {
393
394             # FIXME localized strings should never be in Perl code
395             $itemLoopIter->{message} =
396                 $itemInfo->{itemlost} == 1 ? "(lost)"
397               : $itemInfo->{itemlost} == 2 ? "(long overdue)"
398               : "";
399             $itemInfo->{backgroundcolor} = 'other';
400         }
401
402         # Check of the transfered documents
403         my ( $transfertwhen, $transfertfrom, $transfertto ) =
404           GetTransfers($itemNum);
405         if ( $transfertwhen && ($transfertwhen ne '') ) {
406             $itemLoopIter->{transfertwhen} = format_date($transfertwhen);
407             $itemLoopIter->{transfertfrom} =
408               $branches->{$transfertfrom}{branchname};
409             $itemLoopIter->{transfertto} = $branches->{$transfertto}{branchname};
410             $itemLoopIter->{nocancel} = 1;
411         }
412
413         # If there is no loan, return and transfer, we show a checkbox.
414         $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
415
416         my $branchitemrule = GetBranchItemRule( $borr->{'branchcode'}, $itemInfo->{'itype'} );
417         my $policy_holdallowed = 1;
418
419         if ( $branchitemrule->{'holdallowed'} == 0 ||
420                 ( $branchitemrule->{'holdallowed'} == 1 && $borr->{'branchcode'} ne $itemInfo->{'homebranch'} ) ) {
421             $policy_holdallowed = 0;
422         }
423
424         if (IsAvailableForItemLevelRequest($itemNum) and $policy_holdallowed) {
425             $itemLoopIter->{available} = 1;
426             $numCopiesAvailable++;
427         }
428
429         # FIXME: move this to a pm
430         my $dbh = C4::Context->dbh;
431         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
432         $sth2->execute($itemLoopIter->{ReservedForBorrowernumber}, $itemNum);
433         while (my $wait_hashref = $sth2->fetchrow_hashref) {
434             $itemLoopIter->{waitingdate} = format_date($wait_hashref->{waitingdate});
435         }
436         $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemTypes->{ $itemInfo->{itype} }{imageurl} );
437         
438         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
439     }
440
441     if ($numCopiesAvailable > 0) {
442         $numBibsAvailable++;
443         $biblioLoopIter{bib_available} = 1;
444         $biblioLoopIter{holdable} = 1;
445     }
446     if ($biblioLoopIter{already_reserved}) {
447         $biblioLoopIter{holdable} = undef;
448     }
449
450     push @$biblioLoop, \%biblioLoopIter;
451 }
452
453 if ( $numBibsAvailable == 0 ) {
454     $template->param( none_available => 1, message => 1 );
455 }
456
457 my $itemTableColspan = 5;
458 if (!$template->param('OPACItemHolds')) {
459     $itemTableColspan--;
460 }
461 if ($template->param('singleBranchMode')) {
462     $itemTableColspan--;
463 }
464 $template->param(itemtable_colspan => $itemTableColspan);
465
466 # display infos
467 $template->param(bibitemloop => $biblioLoop);
468 output_html_with_http_headers $query, $cookie, $template->output;
469