Bug 14057: Inventory is painfully slow
[koha.git] / reserve / request.pl
blobc30fb212202516134b2a56aa2709acdaf7e862fe
1 #!/usr/bin/perl
4 #writen 2/1/00 by chris@katipo.oc.nz
5 # Copyright 2000-2002 Katipo Communications
6 # Parts Copyright 2011 Catalyst IT
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 =head1 request.pl
25 script to place reserves/requests
27 =cut
29 use strict;
30 use warnings;
31 use C4::Branch;
32 use CGI qw ( -utf8 );
33 use List::MoreUtils qw/uniq/;
34 use Date::Calc qw/Date_to_Days/;
35 use C4::Output;
36 use C4::Auth;
37 use C4::Reserves;
38 use C4::Biblio;
39 use C4::Items;
40 use C4::Koha;
41 use C4::Circulation;
42 use C4::Dates qw/format_date/;
43 use C4::Utils::DataTables::Members;
44 use C4::Members;
45 use C4::Search; # enabled_staff_search_views
46 use Koha::DateUtils;
48 my $dbh = C4::Context->dbh;
49 my $sth;
50 my $input = new CGI;
51 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
53 template_name => "reserve/request.tt",
54 query => $input,
55 type => "intranet",
56 authnotrequired => 0,
57 flagsrequired => { reserveforothers => 'place_holds' },
61 my $multihold = $input->param('multi_hold');
62 $template->param(multi_hold => $multihold);
63 my $showallitems = $input->param('showallitems');
65 # get Branches and Itemtypes
66 my $branches = GetBranches();
67 my $itemtypes = GetItemTypes();
69 my $userbranch = '';
70 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
71 $userbranch = C4::Context->userenv->{'branch'};
75 # Select borrowers infos
76 my $findborrower = $input->param('findborrower');
77 $findborrower = '' unless defined $findborrower;
78 $findborrower =~ s|,| |g;
79 my $borrowernumber_hold = $input->param('borrowernumber') || '';
80 my $messageborrower;
81 my $maxreserves;
82 my $warnings;
83 my $messages;
85 my $date = C4::Dates->today('iso');
86 my $action = $input->param('action');
87 $action ||= q{};
89 if ( $action eq 'move' ) {
90 my $where = $input->param('where');
91 my $reserve_id = $input->param('reserve_id');
92 AlterPriority( $where, $reserve_id );
93 } elsif ( $action eq 'cancel' ) {
94 my $reserve_id = $input->param('reserve_id');
95 CancelReserve({ reserve_id => $reserve_id });
96 } elsif ( $action eq 'setLowestPriority' ) {
97 my $reserve_id = $input->param('reserve_id');
98 ToggleLowestPriority( $reserve_id );
99 } elsif ( $action eq 'toggleSuspend' ) {
100 my $reserve_id = $input->param('reserve_id');
101 my $suspend_until = $input->param('suspend_until');
102 ToggleSuspend( $reserve_id, $suspend_until );
105 if ($findborrower) {
106 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
107 if ( $borrower ) {
108 $borrowernumber_hold = $borrower->{borrowernumber};
109 } else {
110 my $dt_params = { iDisplayLength => -1 };
111 my $results = C4::Utils::DataTables::Members::search(
113 searchmember => $findborrower,
114 dt_params => $dt_params,
117 my $borrowers = $results->{patrons};
118 if ( scalar @$borrowers == 1 ) {
119 $borrowernumber_hold = $borrowers->[0]->{borrowernumber};
120 } elsif ( @$borrowers ) {
121 $template->param( borrowers => $borrowers );
122 } else {
123 $messageborrower = "'$findborrower'";
128 # If we have the borrowernumber because we've performed an action, then we
129 # don't want to try to place another reserve.
130 if ($borrowernumber_hold && !$action) {
131 my $borrowerinfo = GetMember( borrowernumber => $borrowernumber_hold );
132 my $diffbranch;
133 my @getreservloop;
134 my $count_reserv = 0;
136 # we check the reserves of the borrower, and if he can reserv a document
137 # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
139 my $number_reserves =
140 GetReserveCount( $borrowerinfo->{'borrowernumber'} );
142 if ( C4::Context->preference('maxreserves') && ($number_reserves >= C4::Context->preference('maxreserves')) ) {
143 $warnings = 1;
144 $maxreserves = 1;
147 # we check the date expiry of the borrower (only if there is an expiry date, otherwise, set to 1 (warn)
148 my $expiry_date = $borrowerinfo->{dateexpiry};
149 my $expiry = 0; # flag set if patron account has expired
150 if ($expiry_date and $expiry_date ne '0000-00-00' and
151 Date_to_Days(split /-/,$date) > Date_to_Days(split /-/,$expiry_date)) {
152 $expiry = 1;
155 # check if the borrower make the reserv in a different branch
156 if ( $borrowerinfo->{'branchcode'} ne C4::Context->userenv->{'branch'} ) {
157 $diffbranch = 1;
160 $template->param(
161 borrowernumber => $borrowerinfo->{'borrowernumber'},
162 borrowersurname => $borrowerinfo->{'surname'},
163 borrowerfirstname => $borrowerinfo->{'firstname'},
164 borrowerstreetaddress => $borrowerinfo->{'address'},
165 borrowercity => $borrowerinfo->{'city'},
166 borrowerphone => $borrowerinfo->{'phone'},
167 borrowermobile => $borrowerinfo->{'mobile'},
168 borrowerfax => $borrowerinfo->{'fax'},
169 borrowerphonepro => $borrowerinfo->{'phonepro'},
170 borroweremail => $borrowerinfo->{'email'},
171 borroweremailpro => $borrowerinfo->{'emailpro'},
172 borrowercategory => $borrowerinfo->{'category'},
173 borrowerreservs => $count_reserv,
174 cardnumber => $borrowerinfo->{'cardnumber'},
175 expiry => $expiry,
176 diffbranch => $diffbranch,
177 messages => $messages,
178 warnings => $warnings
182 $template->param( messageborrower => $messageborrower );
184 # FIXME launch another time GetMember perhaps until
185 my $borrowerinfo = GetMember( borrowernumber => $borrowernumber_hold );
187 my @biblionumbers = ();
188 my $biblionumbers = $input->param('biblionumbers');
189 if ($multihold) {
190 @biblionumbers = split '/', $biblionumbers;
191 } else {
192 push @biblionumbers, $input->param('biblionumber');
195 my $itemdata_enumchron = 0;
196 my @biblioloop = ();
197 foreach my $biblionumber (@biblionumbers) {
199 my %biblioloopiter = ();
201 my $dat = GetBiblioData($biblionumber);
203 my $canReserve = CanBookBeReserved( $borrowerinfo->{borrowernumber}, $biblionumber );
204 if ( $canReserve eq 'OK' ) {
206 #All is OK and we can continue
208 elsif ( $canReserve eq 'tooManyReserves' ) {
209 $maxreserves = 1;
211 elsif ( $canReserve eq 'ageRestricted' ) {
212 $template->param( $canReserve => 1 );
213 $biblioloopiter{$canReserve} = 1;
215 else {
216 $biblioloopiter{$canReserve} = 1;
219 my $alreadypossession;
220 if (not C4::Context->preference('AllowHoldsOnPatronsPossessions') and CheckIfIssuedToPatron($borrowerinfo->{borrowernumber},$biblionumber)) {
221 $alreadypossession = 1;
224 # get existing reserves .....
225 my $reserves = GetReservesFromBiblionumber({ biblionumber => $biblionumber, all_dates => 1 });
226 my $count = scalar( @$reserves );
227 my $totalcount = $count;
228 my $holds_count = 0;
229 my $alreadyreserved = 0;
231 foreach my $res (@$reserves) {
232 if ( defined $res->{found} ) { # found can be 'W' or 'T'
233 $count--;
236 if ( defined $borrowerinfo && defined($borrowerinfo->{borrowernumber}) && ($borrowerinfo->{borrowernumber} eq $res->{borrowernumber}) ) {
237 $holds_count++;
241 if ( $holds_count ) {
242 $alreadyreserved = 1;
243 $biblioloopiter{warn} = 1;
244 $biblioloopiter{alreadyres} = 1;
247 $template->param(
248 alreadyreserved => $alreadyreserved,
249 alreadypossession => $alreadypossession,
252 # FIXME think @optionloop, is maybe obsolete, or must be switchable by a systeme preference fixed rank or not
253 # make priorities options
255 my @optionloop;
256 for ( 1 .. $count + 1 ) {
257 push(
258 @optionloop,
260 num => $_,
261 selected => ( $_ == $count + 1 ),
265 # adding a fixed value for priority options
266 my $fixedRank = $count+1;
268 my @branchcodes;
269 my %itemnumbers_of_biblioitem;
270 my @itemnumbers;
272 ## $items is array of 'item' table numbers
273 if (my $items = get_itemnumbers_of($biblionumber)->{$biblionumber}){
274 @itemnumbers = @$items;
276 my @hostitems = get_hostitemnumbers_of($biblionumber);
277 if (@hostitems){
278 $template->param('hostitemsflag' => 1);
279 push(@itemnumbers, @hostitems);
282 if (!@itemnumbers) {
283 $template->param('noitems' => 1);
284 $biblioloopiter{noitems} = 1;
287 ## Hash of item number to 'item' table fields
288 my $iteminfos_of = GetItemInfosOf(@itemnumbers);
290 ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers,
291 ## when by definition all of the itemnumber have the same biblioitemnumber
292 foreach my $itemnumber (@itemnumbers) {
293 my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
294 push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
297 ## Should be same as biblionumber
298 my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
300 my $notforloan_label_of = get_notforloan_label_of();
302 ## Hash of biblioitemnumber to 'biblioitem' table records
303 my $biblioiteminfos_of = GetBiblioItemInfosOf(@biblioitemnumbers);
305 my @bibitemloop;
307 foreach my $biblioitemnumber (@biblioitemnumbers) {
308 my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
309 my $num_available = 0;
310 my $num_override = 0;
311 my $hiddencount = 0;
313 $biblioitem->{description} =
314 $itemtypes->{ $biblioitem->{itemtype} }{description};
315 if($biblioitem->{biblioitemnumber} ne $biblionumber){
316 $biblioitem->{hostitemsflag}=1;
318 $biblioloopiter{description} = $biblioitem->{description};
319 $biblioloopiter{itypename} = $biblioitem->{description};
320 $biblioloopiter{imageurl} =
321 getitemtypeimagelocation('intranet', $itemtypes->{$biblioitem->{itemtype}}{imageurl});
323 foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } ) {
324 my $item = $iteminfos_of->{$itemnumber};
326 unless (C4::Context->preference('item-level_itypes')) {
327 $item->{itype} = $biblioitem->{itemtype};
330 $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
331 $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
332 $item->{homebranchname} = $branches->{ $item->{homebranch} }{branchname};
334 # if the holdingbranch is different than the homebranch, we show the
335 # holdingbranch of the document too
336 if ( $item->{homebranch} ne $item->{holdingbranch} ) {
337 $item->{holdingbranchname} =
338 $branches->{ $item->{holdingbranch} }{branchname};
341 if($item->{biblionumber} ne $biblionumber){
342 $item->{hostitemsflag}=1;
343 $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
346 # if the item is currently on loan, we display its return date and
347 # change the background color
348 my $issues= GetItemIssue($itemnumber);
349 if ( $issues->{'date_due'} ) {
350 $item->{date_due} = $issues->{date_due_sql};
351 $item->{backgroundcolor} = 'onloan';
354 # checking reserve
355 my ($reservedate,$reservedfor,$expectedAt,$reserve_id,$wait) = GetReservesFromItemnumber($itemnumber);
356 if ( defined $reservedate ) {
357 my $ItemBorrowerReserveInfo = GetMember( borrowernumber => $reservedfor );
359 $item->{backgroundcolor} = 'reserved';
360 $item->{reservedate} = format_date($reservedate);
361 $item->{ReservedForBorrowernumber} = $reservedfor;
362 $item->{ReservedForSurname} = $ItemBorrowerReserveInfo->{'surname'};
363 $item->{ReservedForFirstname} = $ItemBorrowerReserveInfo->{'firstname'};
364 $item->{ExpectedAtLibrary} = $branches->{$expectedAt}{branchname};
365 $item->{waitingdate} = $wait;
368 # Management of the notforloan document
369 if ( $item->{notforloan} ) {
370 $item->{backgroundcolor} = 'other';
371 $item->{notforloanvalue} =
372 $notforloan_label_of->{ $item->{notforloan} };
375 # Management of lost or long overdue items
376 if ( $item->{itemlost} ) {
378 # FIXME localized strings should never be in Perl code
379 $item->{message} =
380 $item->{itemlost} == 1 ? "(lost)"
381 : $item->{itemlost} == 2 ? "(long overdue)"
382 : "";
383 $item->{backgroundcolor} = 'other';
384 if (GetHideLostItemsPreference($borrowernumber) && !$showallitems) {
385 $item->{hide} = 1;
386 $hiddencount++;
390 # Check the transit status
391 my ( $transfertwhen, $transfertfrom, $transfertto ) =
392 GetTransfers($itemnumber);
394 if ( defined $transfertwhen && $transfertwhen ne '' ) {
395 $item->{transfertwhen} = format_date($transfertwhen);
396 $item->{transfertfrom} =
397 $branches->{$transfertfrom}{branchname};
398 $item->{transfertto} = $branches->{$transfertto}{branchname};
399 $item->{nocancel} = 1;
402 # If there is no loan, return and transfer, we show a checkbox.
403 $item->{notforloan} ||= 0;
405 # if independent branches is on we need to check if the person can reserve
406 # for branches they arent logged in to
407 if ( C4::Context->preference("IndependentBranches") ) {
408 if (! C4::Context->preference("canreservefromotherbranches")){
409 # cant reserve items so need to check if item homebranch and userenv branch match if not we cant reserve
410 my $userenv = C4::Context->userenv;
411 unless ( C4::Context->IsSuperLibrarian ) {
412 $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
417 my $branch = C4::Circulation::_GetCircControlBranch($item, $borrowerinfo);
419 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
420 my $policy_holdallowed = 1;
422 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
424 if ( $branchitemrule->{'holdallowed'} == 0 ||
425 ( $branchitemrule->{'holdallowed'} == 1 &&
426 $borrowerinfo->{'branchcode'} ne $item->{'homebranch'} ) ) {
427 $policy_holdallowed = 0;
430 if (
431 $policy_holdallowed
432 && !$item->{cantreserve}
433 && IsAvailableForItemLevelRequest($item, $borrowerinfo)
434 && CanItemBeReserved(
435 $borrowerinfo->{borrowernumber}, $itemnumber
436 ) eq 'OK'
439 $item->{available} = 1;
440 $num_available++;
442 elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) {
443 # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
444 $item->{override} = 1;
445 $num_override++;
448 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
450 # Show serial enumeration when needed
451 if ($item->{enumchron}) {
452 $itemdata_enumchron = 1;
455 push @{ $biblioitem->{itemloop} }, $item;
458 if ( $num_override == scalar( @{ $biblioitem->{itemloop} } ) ) { # That is, if all items require an override
459 $template->param( override_required => 1 );
460 } elsif ( $num_available == 0 ) {
461 $template->param( none_available => 1 );
462 $biblioloopiter{warn} = 1;
463 $biblioloopiter{none_avail} = 1;
465 $template->param( hiddencount => $hiddencount);
467 push @bibitemloop, $biblioitem;
470 # existingreserves building
471 my @reserveloop;
472 $reserves = GetReservesFromBiblionumber({ biblionumber => $biblionumber, all_dates => 1 });
473 foreach my $res ( sort {
474 my $a_found = $a->{found} || '';
475 my $b_found = $a->{found} || '';
476 $a_found cmp $b_found;
477 } @$reserves ) {
478 my %reserve;
479 my @optionloop;
480 for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
481 push(
482 @optionloop,
484 num => $i,
485 selected => ( $i == $res->{priority} ),
490 if ( defined $res->{'found'} && ($res->{'found'} eq 'W' || $res->{'found'} eq 'T' )) {
491 my $item = $res->{'itemnumber'};
492 $item = GetBiblioFromItemNumber($item,undef);
493 $reserve{'wait'}= 1;
494 $reserve{'holdingbranch'}=$item->{'holdingbranch'};
495 $reserve{'biblionumber'}=$item->{'biblionumber'};
496 $reserve{'barcodenumber'} = $item->{'barcode'};
497 $reserve{'wbrcode'} = $res->{'branchcode'};
498 $reserve{'itemnumber'} = $res->{'itemnumber'};
499 $reserve{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
500 if($reserve{'holdingbranch'} eq $reserve{'wbrcode'}){
501 # Just because the holdingbranch matches the reserve branch doesn't mean the item
502 # has arrived at the destination, check for an open transfer for the item as well
503 my ( $transfertwhen, $transfertfrom, $transferto ) = C4::Circulation::GetTransfers( $res->{itemnumber} );
504 if ( not $transferto or $transferto ne $res->{branchcode} ) {
505 $reserve{'atdestination'} = 1;
508 # set found to 1 if reserve is waiting for patron pickup
509 $reserve{'found'} = 1 if $res->{'found'} eq 'W';
510 $reserve{'intransit'} = 1 if $res->{'found'} eq 'T';
511 } elsif ($res->{priority} > 0) {
512 if (defined($res->{itemnumber})) {
513 my $item = GetItem($res->{itemnumber});
514 $reserve{'itemnumber'} = $res->{'itemnumber'};
515 $reserve{'barcodenumber'} = $item->{'barcode'};
516 $reserve{'item_level_hold'} = 1;
520 # get borrowers reserve info
521 my $reserveborrowerinfo = GetMember( borrowernumber => $res->{'borrowernumber'} );
522 if (C4::Context->preference('HidePatronName')){
523 $reserve{'hidename'} = 1;
524 $reserve{'cardnumber'} = $reserveborrowerinfo->{'cardnumber'};
526 $reserve{'expirationdate'} = format_date( $res->{'expirationdate'} )
527 unless ( !defined($res->{'expirationdate'}) || $res->{'expirationdate'} eq '0000-00-00' );
528 $reserve{'date'} = format_date( $res->{'reservedate'} );
529 $reserve{'borrowernumber'} = $res->{'borrowernumber'};
530 $reserve{'biblionumber'} = $res->{'biblionumber'};
531 $reserve{'borrowernumber'} = $res->{'borrowernumber'};
532 $reserve{'firstname'} = $reserveborrowerinfo->{'firstname'};
533 $reserve{'surname'} = $reserveborrowerinfo->{'surname'};
534 $reserve{'notes'} = $res->{'reservenotes'};
535 $reserve{'wait'} =
536 ( ( defined $res->{'found'} and $res->{'found'} eq 'W' ) or ( $res->{'priority'} eq '0' ) );
537 $reserve{'constrainttypea'} = ( $res->{'constrainttype'} eq 'a' );
538 $reserve{'constrainttypeo'} = ( $res->{'constrainttype'} eq 'o' );
539 $reserve{'voldesc'} = $res->{'volumeddesc'};
540 $reserve{'ccode'} = $res->{'ccode'};
541 $reserve{'barcode'} = $res->{'barcode'};
542 $reserve{'priority'} = $res->{'priority'};
543 $reserve{'lowestPriority'} = $res->{'lowestPriority'};
544 $reserve{'optionloop'} = \@optionloop;
545 $reserve{'suspend'} = $res->{'suspend'};
546 $reserve{'suspend_until'} = $res->{'suspend_until'};
547 $reserve{'reserve_id'} = $res->{'reserve_id'};
549 if ( C4::Context->preference('IndependentBranches') && $flags->{'superlibrarian'} != 1 ) {
550 $reserve{'branchloop'} = [ GetBranchDetail($res->{'branchcode'}) ];
551 } else {
552 $reserve{'branchloop'} = GetBranchesLoop($res->{'branchcode'});
555 push( @reserveloop, \%reserve );
558 # get the time for the form name...
559 my $time = time();
561 $template->param(
562 branchloop => GetBranchesLoop($userbranch),
563 time => $time,
564 fixedRank => $fixedRank,
567 # display infos
568 $template->param(
569 optionloop => \@optionloop,
570 bibitemloop => \@bibitemloop,
571 itemdata_enumchron => $itemdata_enumchron,
572 date => $date,
573 biblionumber => $biblionumber,
574 findborrower => $findborrower,
575 title => $dat->{title},
576 author => $dat->{author},
577 holdsview => 1,
578 C4::Search::enabled_staff_search_views,
580 if (defined $borrowerinfo && exists $borrowerinfo->{'branchcode'}) {
581 $template->param(
582 borrower_branchname => $branches->{$borrowerinfo->{'branchcode'}}->{'branchname'},
583 borrower_branchcode => $borrowerinfo->{'branchcode'},
587 $biblioloopiter{biblionumber} = $biblionumber;
588 $biblioloopiter{title} = $dat->{title};
589 $biblioloopiter{rank} = $fixedRank;
590 $biblioloopiter{reserveloop} = \@reserveloop;
592 if (@reserveloop) {
593 $template->param( reserveloop => \@reserveloop );
596 push @biblioloop, \%biblioloopiter;
599 $template->param( biblioloop => \@biblioloop );
600 $template->param( biblionumbers => $biblionumbers );
601 $template->param( maxreserves => $maxreserves );
603 if ($multihold) {
604 $template->param( multi_hold => 1 );
607 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
608 $template->param( reserve_in_future => 1 );
611 $template->param(
612 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
613 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
616 # printout the page
617 output_html_with_http_headers $input, $cookie, $template->output;
619 sub sort_borrowerlist {
620 my $borrowerslist = shift;
621 my $ref = [];
622 push @{$ref}, sort {
623 uc( $a->{surname} . $a->{firstname} ) cmp
624 uc( $b->{surname} . $b->{firstname} )
625 } @{$borrowerslist};
626 return $ref;