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