Bug 18786: Update database
[koha.git] / reserve / request.pl
blob2902de09aee2088b0faa8860f952725518b07d42
1 #!/usr/bin/perl
4 #written 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 Modern::Perl;
31 use CGI qw ( -utf8 );
32 use List::MoreUtils qw/uniq/;
33 use Date::Calc qw/Date_to_Days/;
34 use C4::Output;
35 use C4::Auth;
36 use C4::Reserves;
37 use C4::Biblio;
38 use C4::Items;
39 use C4::Koha;
40 use C4::Circulation;
41 use Koha::DateUtils;
42 use C4::Utils::DataTables::Members;
43 use C4::Members;
44 use C4::Search; # enabled_staff_search_views
46 use Koha::Biblios;
47 use Koha::DateUtils;
48 use Koha::Checkouts;
49 use Koha::Holds;
50 use Koha::IssuingRules;
51 use Koha::Items;
52 use Koha::ItemTypes;
53 use Koha::Libraries;
54 use Koha::Patrons;
56 my $dbh = C4::Context->dbh;
57 my $input = new CGI;
58 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
60 template_name => "reserve/request.tt",
61 query => $input,
62 type => "intranet",
63 authnotrequired => 0,
64 flagsrequired => { reserveforothers => 'place_holds' },
68 my $showallitems = $input->param('showallitems');
70 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
72 # Select borrowers infos
73 my $findborrower = $input->param('findborrower');
74 $findborrower = '' unless defined $findborrower;
75 $findborrower =~ s|,| |g;
76 my $borrowernumber_hold = $input->param('borrowernumber') || '';
77 my $messageborrower;
78 my $warnings;
79 my $messages;
80 my $exceeded_maxreserves;
81 my $exceeded_holds_per_record;
83 my $date = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
84 my $action = $input->param('action');
85 $action ||= q{};
87 if ( $action eq 'move' ) {
88 my $where = $input->param('where');
89 my $reserve_id = $input->param('reserve_id');
90 AlterPriority( $where, $reserve_id );
91 } elsif ( $action eq 'cancel' ) {
92 my $reserve_id = $input->param('reserve_id');
93 my $hold = Koha::Holds->find( $reserve_id );
94 $hold->cancel if $hold;
95 } elsif ( $action eq 'setLowestPriority' ) {
96 my $reserve_id = $input->param('reserve_id');
97 ToggleLowestPriority( $reserve_id );
98 } elsif ( $action eq 'toggleSuspend' ) {
99 my $reserve_id = $input->param('reserve_id');
100 my $suspend_until = $input->param('suspend_until');
101 ToggleSuspend( $reserve_id, $suspend_until );
104 if ($findborrower) {
105 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
106 if ( $patron ) {
107 $borrowernumber_hold = $patron->borrowernumber;
108 } else {
109 my $dt_params = { iDisplayLength => -1 };
110 my $results = C4::Utils::DataTables::Members::search(
112 searchmember => $findborrower,
113 dt_params => $dt_params,
116 my $borrowers = $results->{patrons};
117 if ( scalar @$borrowers == 1 ) {
118 $borrowernumber_hold = $borrowers->[0]->{borrowernumber};
119 } elsif ( @$borrowers ) {
120 $template->param( borrowers => $borrowers );
121 } else {
122 $messageborrower = "'$findborrower'";
127 my @biblionumbers = ();
128 my $biblionumber = $input->param('biblionumber');
129 my $biblionumbers = $input->param('biblionumbers');
130 if ( $biblionumbers ) {
131 @biblionumbers = split '/', $biblionumbers;
132 } else {
133 push @biblionumbers, $input->multi_param('biblionumber');
136 # FIXME multi_hold should not be a variable but depends on the number of elements in @biblionumbers
137 $template->param(multi_hold => scalar $input->param('multi_hold'));
139 # If we have the borrowernumber because we've performed an action, then we
140 # don't want to try to place another reserve.
141 if ($borrowernumber_hold && !$action) {
142 my $patron = Koha::Patrons->find( $borrowernumber_hold );
143 my $diffbranch;
145 # we check the reserves of the user, and if they can reserve a document
146 # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
148 my $reserves_count = $patron->holds->count;
150 my $new_reserves_count = scalar( @biblionumbers );
152 my $maxreserves = C4::Context->preference('maxreserves');
153 if ( $maxreserves
154 && ( $reserves_count + $new_reserves_count > $maxreserves ) )
156 my $new_reserves_allowed =
157 $maxreserves - $reserves_count > 0
158 ? $maxreserves - $reserves_count
159 : 0;
160 $warnings = 1;
161 $exceeded_maxreserves = 1;
162 $template->param(
163 new_reserves_allowed => $new_reserves_allowed,
164 new_reserves_count => $new_reserves_count,
165 reserves_count => $reserves_count,
166 maxreserves => $maxreserves,
170 # we check the date expiry of the borrower (only if there is an expiry date, otherwise, set to 1 (warn)
171 my $expiry_date = $patron->dateexpiry;
172 my $expiry = 0; # flag set if patron account has expired
173 if ($expiry_date and $expiry_date ne '0000-00-00' and
174 Date_to_Days(split /-/,$date) > Date_to_Days(split /-/,$expiry_date)) {
175 $expiry = 1;
178 # check if the borrower make the reserv in a different branch
179 if ( $patron->branchcode ne C4::Context->userenv->{'branch'} ) {
180 $diffbranch = 1;
183 my $amount_outstanding = $patron->account->balance;
184 $template->param(
185 patron => $patron,
186 expiry => $expiry,
187 diffbranch => $diffbranch,
188 messages => $messages,
189 warnings => $warnings,
190 amount_outstanding => $amount_outstanding,
194 $template->param( messageborrower => $messageborrower );
196 # FIXME launch another time GetMember perhaps until (Joubu: Why?)
197 my $patron = Koha::Patrons->find( $borrowernumber_hold );
199 my $logged_in_patron = Koha::Patrons->find( $borrowernumber );
201 my $itemdata_enumchron = 0;
202 my @biblioloop = ();
203 foreach my $biblionumber (@biblionumbers) {
204 next unless $biblionumber =~ m|^\d+$|;
206 my %biblioloopiter = ();
208 my $biblio = Koha::Biblios->find( $biblionumber );
210 my $force_hold_level;
211 if ( $patron ) {
212 { # CanBookBeReserved
213 my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber );
214 $canReserve //= '';
215 if ( $canReserve eq 'OK' ) {
217 #All is OK and we can continue
219 elsif ( $canReserve eq 'tooManyReserves' ) {
220 $exceeded_maxreserves = 1;
222 elsif ( $canReserve eq 'tooManyHoldsForThisRecord' ) {
223 $exceeded_holds_per_record = 1;
224 $biblioloopiter{$canReserve} = 1;
226 elsif ( $canReserve eq 'ageRestricted' ) {
227 $template->param( $canReserve => 1 );
228 $biblioloopiter{$canReserve} = 1;
230 else {
231 $biblioloopiter{$canReserve} = 1;
235 # For multiple holds per record, if a patron has previously placed a hold,
236 # the patron can only place more holds of the same type. That is, if the
237 # patron placed a record level hold, all the holds the patron places must
238 # be record level. If the patron placed an item level hold, all holds
239 # the patron places must be item level
240 my $holds = Koha::Holds->search(
242 borrowernumber => $patron->borrowernumber,
243 biblionumber => $biblionumber,
244 found => undef,
247 $force_hold_level = $holds->forced_hold_level();
248 $biblioloopiter{force_hold_level} = $force_hold_level;
249 $template->param( force_hold_level => $force_hold_level );
251 # For a librarian to be able to place multiple record holds for a patron for a record,
252 # we must find out what the maximum number of holds they can place for the patron is
253 my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber );
254 my $remaining_holds_for_record = $max_holds_for_record - $holds->count();
255 $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record;
256 $template->param( max_holds_for_record => $max_holds_for_record );
257 $template->param( remaining_holds_for_record => $remaining_holds_for_record );
259 { # alreadypossession
260 # Check to see if patron is allowed to place holds on records where the
261 # patron already has an item from that record checked out
262 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
263 && CheckIfIssuedToPatron( $patron->borrowernumber, $biblionumber ) )
265 $template->param( alreadypossession => 1, );
271 my $count = Koha::Holds->search( { biblionumber => $biblionumber } )->count();
272 my $totalcount = $count;
274 # FIXME think @optionloop, is maybe obsolete, or must be switchable by a systeme preference fixed rank or not
275 # make priorities options
277 my @optionloop;
278 for ( 1 .. $count + 1 ) {
279 push(
280 @optionloop,
282 num => $_,
283 selected => ( $_ == $count + 1 ),
287 # adding a fixed value for priority options
288 my $fixedRank = $count+1;
290 my %itemnumbers_of_biblioitem;
292 my @hostitems = get_hostitemnumbers_of($biblionumber);
293 my @itemnumbers;
294 if (@hostitems){
295 $template->param('hostitemsflag' => 1);
296 push(@itemnumbers, @hostitems);
299 my $items = Koha::Items->search({ -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } });
301 unless ( $items->count ) {
302 # FIXME Then why do we continue?
303 $template->param('noitems' => 1);
304 $biblioloopiter{noitems} = 1;
307 ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers,
308 ## when by definition all of the itemnumber have the same biblioitemnumber
309 my ( $iteminfos_of );
310 while ( my $item = $items->next ) {
311 $item = $item->unblessed;
312 my $biblioitemnumber = $item->{biblioitemnumber};
313 my $itemnumber = $item->{itemnumber};
314 push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
315 $iteminfos_of->{$itemnumber} = $item;
318 ## Should be same as biblionumber
319 my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
321 my $biblioiteminfos_of = {
322 map {
323 my $biblioitem = $_;
324 ( $biblioitem->{biblioitemnumber} => $biblioitem )
325 } @{ Koha::Biblioitems->search(
326 { biblioitemnumber => { -in => \@biblioitemnumbers } },
327 { select => ['biblioitemnumber', 'publicationyear', 'itemtype']}
328 )->unblessed
332 my $frameworkcode = GetFrameworkCode( $biblionumber );
333 my @notforloan_avs = Koha::AuthorisedValues->search_by_koha_field({ kohafield => 'items.notforloan', frameworkcode => $frameworkcode });
334 my $notforloan_label_of = { map { $_->authorised_value => $_->lib } @notforloan_avs };
336 my @bibitemloop;
338 my @available_itemtypes;
339 foreach my $biblioitemnumber (@biblioitemnumbers) {
340 my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
341 my $num_available = 0;
342 my $num_override = 0;
343 my $hiddencount = 0;
345 $biblioitem->{force_hold_level} = $force_hold_level;
347 if ( $biblioitem->{biblioitemnumber} ne $biblionumber ) {
348 $biblioitem->{hostitemsflag} = 1;
351 $biblioloopiter{description} = $biblioitem->{description};
352 $biblioloopiter{itypename} = $biblioitem->{description};
353 if ( $biblioitem->{itemtype} ) {
355 $biblioitem->{description} =
356 $itemtypes->{ $biblioitem->{itemtype} }{description};
358 $biblioloopiter{imageurl} =
359 getitemtypeimagelocation( 'intranet',
360 $itemtypes->{ $biblioitem->{itemtype} }{imageurl} );
363 foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } ) {
364 my $item = $iteminfos_of->{$itemnumber};
366 $item->{force_hold_level} = $force_hold_level;
368 unless (C4::Context->preference('item-level_itypes')) {
369 $item->{itype} = $biblioitem->{itemtype};
372 $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
373 $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
374 $item->{homebranch} = $item->{homebranch};
376 # if the holdingbranch is different than the homebranch, we show the
377 # holdingbranch of the document too
378 if ( $item->{homebranch} ne $item->{holdingbranch} ) {
379 $item->{holdingbranch} = $item->{holdingbranch};
382 if($item->{biblionumber} ne $biblionumber){
383 $item->{hostitemsflag} = 1;
384 $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title;
387 # if the item is currently on loan, we display its return date and
388 # change the background color
389 my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } );
390 if ( $issue ) {
391 $item->{date_due} = $issue->date_due;
392 $item->{backgroundcolor} = 'onloan';
395 # checking reserve
396 my $item_object = Koha::Items->find( $itemnumber );
397 my $holds = $item_object->current_holds;
398 if ( my $first_hold = $holds->next ) {
399 my $p = Koha::Patrons->find( $first_hold->borrowernumber );
401 $item->{backgroundcolor} = 'reserved';
402 $item->{reservedate} = output_pref({ dt => dt_from_string( $first_hold->reservedate ), dateonly => 1 }); # FIXME Should be formatted in the template
403 $item->{ReservedFor} = $p;
404 $item->{ExpectedAtLibrary} = $first_hold->branchcode;
405 $item->{waitingdate} = $first_hold->waitingdate;
408 # Management of the notforloan document
409 if ( $item->{notforloan} ) {
410 $item->{backgroundcolor} = 'other';
411 $item->{notforloanvalue} =
412 $notforloan_label_of->{ $item->{notforloan} };
415 # Management of lost or long overdue items
416 if ( $item->{itemlost} ) {
418 # FIXME localized strings should never be in Perl code
419 $item->{message} =
420 $item->{itemlost} == 1 ? "(lost)"
421 : $item->{itemlost} == 2 ? "(long overdue)"
422 : "";
423 $item->{backgroundcolor} = 'other';
424 if ($logged_in_patron->category->hidelostitems && !$showallitems) {
425 $item->{hide} = 1;
426 $hiddencount++;
430 # Check the transit status
431 my ( $transfertwhen, $transfertfrom, $transfertto ) =
432 GetTransfers($itemnumber);
434 if ( defined $transfertwhen && $transfertwhen ne '' ) {
435 $item->{transfertwhen} = output_pref({ dt => dt_from_string( $transfertwhen ), dateonly => 1 });
436 $item->{transfertfrom} = $transfertfrom;
437 $item->{transfertto} = $transfertto;
438 $item->{nocancel} = 1;
441 # If there is no loan, return and transfer, we show a checkbox.
442 $item->{notforloan} ||= 0;
444 # if independent branches is on we need to check if the person can reserve
445 # for branches they arent logged in to
446 if ( C4::Context->preference("IndependentBranches") ) {
447 if (! C4::Context->preference("canreservefromotherbranches")){
448 # cant reserve items so need to check if item homebranch and userenv branch match if not we cant reserve
449 my $userenv = C4::Context->userenv;
450 unless ( C4::Context->IsSuperLibrarian ) {
451 $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
456 if ( $patron ) {
457 my $patron_unblessed = $patron->unblessed;
458 my $branch = C4::Circulation::_GetCircControlBranch($item, $patron_unblessed);
460 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
462 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
464 my $can_item_be_reserved = CanItemBeReserved( $patron->borrowernumber, $itemnumber );
465 $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' );
467 $item->{item_level_holds} = Koha::IssuingRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } );
469 if (
470 !$item->{cantreserve}
471 && !$exceeded_maxreserves
472 && IsAvailableForItemLevelRequest($item, $patron_unblessed)
473 && $can_item_be_reserved eq 'OK'
476 $item->{available} = 1;
477 $num_available++;
479 push( @available_itemtypes, $item->{itype} );
481 elsif ( $can_item_be_reserved eq 'tooManyReserves' && C4::Context->preference('AllowHoldPolicyOverride') ) {
482 # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
483 $item->{override} = 1;
484 $num_override++;
486 push( @available_itemtypes, $item->{itype} );
489 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
491 # Show serial enumeration when needed
492 if ($item->{enumchron}) {
493 $itemdata_enumchron = 1;
497 push @{ $biblioitem->{itemloop} }, $item;
500 if ( $num_override == scalar( @{ $biblioitem->{itemloop} } ) ) { # That is, if all items require an override
501 $template->param( override_required => 1 );
502 } elsif ( $num_available == 0 ) {
503 $template->param( none_available => 1 );
504 $biblioloopiter{warn} = 1;
505 $biblioloopiter{none_avail} = 1;
507 $template->param( hiddencount => $hiddencount);
509 push @bibitemloop, $biblioitem;
512 @available_itemtypes = uniq( @available_itemtypes );
513 $template->param( available_itemtypes => \@available_itemtypes );
515 # existingreserves building
516 my @reserveloop;
517 my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } );
518 foreach my $res (
519 sort {
520 my $a_found = $a->found() || '';
521 my $b_found = $a->found() || '';
522 $a_found cmp $b_found;
523 } @reserves
526 my $priority = $res->priority();
527 my %reserve;
528 my @optionloop;
529 for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
530 push(
531 @optionloop,
533 num => $i,
534 selected => ( $i == $priority ),
539 if ( $res->is_found() ) {
540 $reserve{'holdingbranch'} = $res->item()->holdingbranch();
541 $reserve{'biblionumber'} = $res->item()->biblionumber();
542 $reserve{'barcodenumber'} = $res->item()->barcode();
543 $reserve{'wbrcode'} = $res->branchcode();
544 $reserve{'itemnumber'} = $res->itemnumber();
545 $reserve{'wbrname'} = $res->branch()->branchname();
547 if ( $reserve{'holdingbranch'} eq $reserve{'wbrcode'} ) {
549 # Just because the holdingbranch matches the reserve branch doesn't mean the item
550 # has arrived at the destination, check for an open transfer for the item as well
551 my ( $transfertwhen, $transfertfrom, $transferto ) =
552 C4::Circulation::GetTransfers( $res->itemnumber() );
553 if ( not $transferto or $transferto ne $res->branchcode() ) {
554 $reserve{'atdestination'} = 1;
558 # set found to 1 if reserve is waiting for patron pickup
559 $reserve{'found'} = $res->is_found();
560 $reserve{'intransit'} = $res->is_in_transit();
562 elsif ( $res->priority() > 0 ) {
563 if ( my $item = $res->item() ) {
564 $reserve{'itemnumber'} = $item->id();
565 $reserve{'barcodenumber'} = $item->barcode();
566 $reserve{'item_level_hold'} = 1;
570 $reserve{'expirationdate'} = output_pref( { dt => dt_from_string( $res->expirationdate ), dateonly => 1 } )
571 unless ( !defined( $res->expirationdate ) || $res->expirationdate eq '0000-00-00' );
572 $reserve{'date'} = output_pref( { dt => dt_from_string( $res->reservedate ), dateonly => 1 } );
573 $reserve{'borrowernumber'} = $res->borrowernumber();
574 $reserve{'biblionumber'} = $res->biblionumber();
575 $reserve{'patron'} = $res->borrower;
576 $reserve{'notes'} = $res->reservenotes();
577 $reserve{'waiting_date'} = $res->waitingdate();
578 $reserve{'ccode'} = $res->item() ? $res->item()->ccode() : undef;
579 $reserve{'barcode'} = $res->item() ? $res->item()->barcode() : undef;
580 $reserve{'priority'} = $res->priority();
581 $reserve{'lowestPriority'} = $res->lowestPriority();
582 $reserve{'optionloop'} = \@optionloop;
583 $reserve{'suspend'} = $res->suspend();
584 $reserve{'suspend_until'} = $res->suspend_until();
585 $reserve{'reserve_id'} = $res->reserve_id();
586 $reserve{itemtype} = $res->itemtype();
587 $reserve{branchcode} = $res->branchcode();
589 push( @reserveloop, \%reserve );
592 # get the time for the form name...
593 my $time = time();
595 $template->param(
596 time => $time,
597 fixedRank => $fixedRank,
600 # display infos
601 $template->param(
602 optionloop => \@optionloop,
603 bibitemloop => \@bibitemloop,
604 itemdata_enumchron => $itemdata_enumchron,
605 date => $date,
606 biblionumber => $biblionumber,
607 findborrower => $findborrower,
608 title => $biblio->title,
609 author => $biblio->author,
610 holdsview => 1,
611 C4::Search::enabled_staff_search_views,
614 $biblioloopiter{biblionumber} = $biblionumber;
615 $biblioloopiter{title} = $biblio->title;
616 $biblioloopiter{rank} = $fixedRank;
617 $biblioloopiter{reserveloop} = \@reserveloop;
619 if (@reserveloop) {
620 $template->param( reserveloop => \@reserveloop );
623 push @biblioloop, \%biblioloopiter;
626 $template->param( biblioloop => \@biblioloop );
627 $template->param( biblionumbers => $biblionumbers );
628 $template->param( exceeded_maxreserves => $exceeded_maxreserves );
629 $template->param( exceeded_holds_per_record => $exceeded_holds_per_record );
631 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
632 $template->param( reserve_in_future => 1 );
635 $template->param(
636 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
637 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
640 # printout the page
641 output_html_with_http_headers $input, $cookie, $template->output;
643 sub sort_borrowerlist {
644 my $borrowerslist = shift;
645 my $ref = [];
646 push @{$ref}, sort {
647 uc( $a->{surname} . $a->{firstname} ) cmp
648 uc( $b->{surname} . $b->{firstname} )
649 } @{$borrowerslist};
650 return $ref;