Bug 16996: Do not explode if mandatory fields are missing
[koha.git] / reserve / request.pl
blob1980abb9e4c60ec8cf2c20c8bfa570dab83787e8
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 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 Koha::DateUtils;
43 use C4::Utils::DataTables::Members;
44 use C4::Members;
45 use C4::Search; # enabled_staff_search_views
46 use Koha::DateUtils;
47 use Koha::Holds;
48 use Koha::Libraries;
50 my $dbh = C4::Context->dbh;
51 my $input = new CGI;
52 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
54 template_name => "reserve/request.tt",
55 query => $input,
56 type => "intranet",
57 authnotrequired => 0,
58 flagsrequired => { reserveforothers => 'place_holds' },
62 my $multihold = $input->param('multi_hold');
63 $template->param(multi_hold => $multihold);
64 my $showallitems = $input->param('showallitems');
66 # get Branches and Itemtypes
67 my $branches = GetBranches();
68 my $itemtypes = GetItemTypes();
70 my $userbranch = '';
71 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
72 $userbranch = C4::Context->userenv->{'branch'};
76 # Select borrowers infos
77 my $findborrower = $input->param('findborrower');
78 $findborrower = '' unless defined $findborrower;
79 $findborrower =~ s|,| |g;
80 my $borrowernumber_hold = $input->param('borrowernumber') || '';
81 my $messageborrower;
82 my $warnings;
83 my $messages;
84 my $exceeded_maxreserves;
86 my $date = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
87 my $action = $input->param('action');
88 $action ||= q{};
90 if ( $action eq 'move' ) {
91 my $where = $input->param('where');
92 my $reserve_id = $input->param('reserve_id');
93 AlterPriority( $where, $reserve_id );
94 } elsif ( $action eq 'cancel' ) {
95 my $reserve_id = $input->param('reserve_id');
96 CancelReserve({ reserve_id => $reserve_id });
97 } elsif ( $action eq 'setLowestPriority' ) {
98 my $reserve_id = $input->param('reserve_id');
99 ToggleLowestPriority( $reserve_id );
100 } elsif ( $action eq 'toggleSuspend' ) {
101 my $reserve_id = $input->param('reserve_id');
102 my $suspend_until = $input->param('suspend_until');
103 ToggleSuspend( $reserve_id, $suspend_until );
106 if ($findborrower) {
107 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
108 if ( $borrower ) {
109 $borrowernumber_hold = $borrower->{borrowernumber};
110 } else {
111 my $dt_params = { iDisplayLength => -1 };
112 my $results = C4::Utils::DataTables::Members::search(
114 searchmember => $findborrower,
115 dt_params => $dt_params,
118 my $borrowers = $results->{patrons};
119 if ( scalar @$borrowers == 1 ) {
120 $borrowernumber_hold = $borrowers->[0]->{borrowernumber};
121 } elsif ( @$borrowers ) {
122 $template->param( borrowers => $borrowers );
123 } else {
124 $messageborrower = "'$findborrower'";
129 my @biblionumbers = ();
130 my $biblionumbers = $input->param('biblionumbers');
131 if ($multihold) {
132 @biblionumbers = split '/', $biblionumbers;
133 } else {
134 push @biblionumbers, $input->multi_param('biblionumber');
138 # If we have the borrowernumber because we've performed an action, then we
139 # don't want to try to place another reserve.
140 if ($borrowernumber_hold && !$action) {
141 my $borrowerinfo = GetMember( borrowernumber => $borrowernumber_hold );
142 my $diffbranch;
144 # we check the reserves of the borrower, and if he can reserv a document
145 # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
147 my $reserves_count =
148 GetReserveCount( $borrowerinfo->{'borrowernumber'} );
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 = $borrowerinfo->{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 ( $borrowerinfo->{'branchcode'} ne C4::Context->userenv->{'branch'} ) {
180 $diffbranch = 1;
183 my $is_debarred = Koha::Patrons->find( $borrowerinfo->{borrowernumber} )->is_debarred;
184 $template->param(
185 borrowernumber => $borrowerinfo->{'borrowernumber'},
186 borrowersurname => $borrowerinfo->{'surname'},
187 borrowerfirstname => $borrowerinfo->{'firstname'},
188 borrowerstreetaddress => $borrowerinfo->{'address'},
189 borrowercity => $borrowerinfo->{'city'},
190 borrowerphone => $borrowerinfo->{'phone'},
191 borrowermobile => $borrowerinfo->{'mobile'},
192 borrowerfax => $borrowerinfo->{'fax'},
193 borrowerphonepro => $borrowerinfo->{'phonepro'},
194 borroweremail => $borrowerinfo->{'email'},
195 borroweremailpro => $borrowerinfo->{'emailpro'},
196 borrowercategory => $borrowerinfo->{'category'},
197 cardnumber => $borrowerinfo->{'cardnumber'},
198 expiry => $expiry,
199 diffbranch => $diffbranch,
200 messages => $messages,
201 warnings => $warnings,
202 restricted => $is_debarred,
203 amount_outstanding => GetMemberAccountRecords($borrowerinfo->{borrowernumber}),
207 $template->param( messageborrower => $messageborrower );
209 # FIXME launch another time GetMember perhaps until
210 my $borrowerinfo = GetMember( borrowernumber => $borrowernumber_hold );
212 my $itemdata_enumchron = 0;
213 my @biblioloop = ();
214 foreach my $biblionumber (@biblionumbers) {
215 next unless $biblionumber =~ m|^\d+$|;
217 my %biblioloopiter = ();
219 my $dat = GetBiblioData($biblionumber);
221 my $canReserve = CanBookBeReserved( $borrowerinfo->{borrowernumber}, $biblionumber );
222 $canReserve //= '';
223 if ( $canReserve eq 'OK' ) {
225 #All is OK and we can continue
227 elsif ( $canReserve eq 'tooManyReserves' ) {
228 $exceeded_maxreserves = 1;
230 elsif ( $canReserve eq 'ageRestricted' ) {
231 $template->param( $canReserve => 1 );
232 $biblioloopiter{$canReserve} = 1;
234 else {
235 $biblioloopiter{$canReserve} = 1;
238 my $alreadypossession;
239 if (not C4::Context->preference('AllowHoldsOnPatronsPossessions') and CheckIfIssuedToPatron($borrowerinfo->{borrowernumber},$biblionumber)) {
240 $alreadypossession = 1;
243 # get existing reserves .....
244 my $reserves = GetReservesFromBiblionumber({ biblionumber => $biblionumber, all_dates => 1 });
245 my $count = scalar( @$reserves );
246 my $totalcount = $count;
247 my $holds_count = 0;
248 my $alreadyreserved = 0;
250 foreach my $res (@$reserves) {
251 if ( defined $res->{found} ) { # found can be 'W' or 'T'
252 $count--;
255 if ( defined $borrowerinfo && defined($borrowerinfo->{borrowernumber}) && ($borrowerinfo->{borrowernumber} eq $res->{borrowernumber}) ) {
256 $holds_count++;
260 if ( $holds_count ) {
261 $alreadyreserved = 1;
262 $biblioloopiter{warn} = 1;
263 $biblioloopiter{alreadyres} = 1;
266 $template->param(
267 alreadyreserved => $alreadyreserved,
268 alreadypossession => $alreadypossession,
271 # FIXME think @optionloop, is maybe obsolete, or must be switchable by a systeme preference fixed rank or not
272 # make priorities options
274 my @optionloop;
275 for ( 1 .. $count + 1 ) {
276 push(
277 @optionloop,
279 num => $_,
280 selected => ( $_ == $count + 1 ),
284 # adding a fixed value for priority options
285 my $fixedRank = $count+1;
287 my %itemnumbers_of_biblioitem;
288 my @itemnumbers;
290 ## $items is array of 'item' table numbers
291 if (my $items = get_itemnumbers_of($biblionumber)->{$biblionumber}){
292 @itemnumbers = @$items;
294 my @hostitems = get_hostitemnumbers_of($biblionumber);
295 if (@hostitems){
296 $template->param('hostitemsflag' => 1);
297 push(@itemnumbers, @hostitems);
300 if (!@itemnumbers) {
301 $template->param('noitems' => 1);
302 $biblioloopiter{noitems} = 1;
305 ## Hash of item number to 'item' table fields
306 my $iteminfos_of = GetItemInfosOf(@itemnumbers);
308 ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers,
309 ## when by definition all of the itemnumber have the same biblioitemnumber
310 foreach my $itemnumber (@itemnumbers) {
311 my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
312 push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
315 ## Should be same as biblionumber
316 my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
318 my $notforloan_label_of = get_notforloan_label_of();
320 ## Hash of biblioitemnumber to 'biblioitem' table records
321 my $biblioiteminfos_of = GetBiblioItemInfosOf(@biblioitemnumbers);
323 my @bibitemloop;
325 my @available_itemtypes;
326 foreach my $biblioitemnumber (@biblioitemnumbers) {
327 my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
328 my $num_available = 0;
329 my $num_override = 0;
330 my $hiddencount = 0;
332 if ( $biblioitem->{biblioitemnumber} ne $biblionumber ) {
333 $biblioitem->{hostitemsflag} = 1;
336 $biblioloopiter{description} = $biblioitem->{description};
337 $biblioloopiter{itypename} = $biblioitem->{description};
338 if ( $biblioitem->{itemtype} ) {
340 $biblioitem->{description} =
341 $itemtypes->{ $biblioitem->{itemtype} }{description};
343 $biblioloopiter{imageurl} =
344 getitemtypeimagelocation( 'intranet',
345 $itemtypes->{ $biblioitem->{itemtype} }{imageurl} );
348 foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } ) {
349 my $item = $iteminfos_of->{$itemnumber};
351 unless (C4::Context->preference('item-level_itypes')) {
352 $item->{itype} = $biblioitem->{itemtype};
355 $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
356 $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
357 $item->{homebranchname} = $branches->{ $item->{homebranch} }{branchname};
359 # if the holdingbranch is different than the homebranch, we show the
360 # holdingbranch of the document too
361 if ( $item->{homebranch} ne $item->{holdingbranch} ) {
362 $item->{holdingbranchname} =
363 $branches->{ $item->{holdingbranch} }{branchname};
366 if($item->{biblionumber} ne $biblionumber){
367 $item->{hostitemsflag}=1;
368 $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
371 # if the item is currently on loan, we display its return date and
372 # change the background color
373 my $issues= GetItemIssue($itemnumber);
374 if ( $issues->{'date_due'} ) {
375 $item->{date_due} = $issues->{date_due_sql};
376 $item->{backgroundcolor} = 'onloan';
379 # checking reserve
380 my ($reservedate,$reservedfor,$expectedAt,$reserve_id,$wait) = GetReservesFromItemnumber($itemnumber);
381 if ( defined $reservedate ) {
382 my $ItemBorrowerReserveInfo = GetMember( borrowernumber => $reservedfor );
384 $item->{backgroundcolor} = 'reserved';
385 $item->{reservedate} = output_pref({ dt => dt_from_string( $reservedate ), dateonly => 1 });
386 $item->{ReservedForBorrowernumber} = $reservedfor;
387 $item->{ReservedForSurname} = $ItemBorrowerReserveInfo->{'surname'};
388 $item->{ReservedForFirstname} = $ItemBorrowerReserveInfo->{'firstname'};
389 $item->{ExpectedAtLibrary} = $branches->{$expectedAt}{branchname};
390 $item->{waitingdate} = $wait;
393 # Management of the notforloan document
394 if ( $item->{notforloan} ) {
395 $item->{backgroundcolor} = 'other';
396 $item->{notforloanvalue} =
397 $notforloan_label_of->{ $item->{notforloan} };
400 # Management of lost or long overdue items
401 if ( $item->{itemlost} ) {
403 # FIXME localized strings should never be in Perl code
404 $item->{message} =
405 $item->{itemlost} == 1 ? "(lost)"
406 : $item->{itemlost} == 2 ? "(long overdue)"
407 : "";
408 $item->{backgroundcolor} = 'other';
409 if (GetHideLostItemsPreference($borrowernumber) && !$showallitems) {
410 $item->{hide} = 1;
411 $hiddencount++;
415 # Check the transit status
416 my ( $transfertwhen, $transfertfrom, $transfertto ) =
417 GetTransfers($itemnumber);
419 if ( defined $transfertwhen && $transfertwhen ne '' ) {
420 $item->{transfertwhen} = output_pref({ dt => dt_from_string( $transfertwhen ), dateonly => 1 });
421 $item->{transfertfrom} =
422 $branches->{$transfertfrom}{branchname};
423 $item->{transfertto} = $branches->{$transfertto}{branchname};
424 $item->{nocancel} = 1;
427 # If there is no loan, return and transfer, we show a checkbox.
428 $item->{notforloan} ||= 0;
430 # if independent branches is on we need to check if the person can reserve
431 # for branches they arent logged in to
432 if ( C4::Context->preference("IndependentBranches") ) {
433 if (! C4::Context->preference("canreservefromotherbranches")){
434 # cant reserve items so need to check if item homebranch and userenv branch match if not we cant reserve
435 my $userenv = C4::Context->userenv;
436 unless ( C4::Context->IsSuperLibrarian ) {
437 $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
442 my $branch = C4::Circulation::_GetCircControlBranch($item, $borrowerinfo);
444 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
446 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
448 if (
449 !$item->{cantreserve}
450 && !$exceeded_maxreserves
451 && IsAvailableForItemLevelRequest($item, $borrowerinfo)
452 && CanItemBeReserved(
453 $borrowerinfo->{borrowernumber}, $itemnumber
454 ) eq 'OK'
457 $item->{available} = 1;
458 $num_available++;
460 push( @available_itemtypes, $item->{itype} );
462 elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) {
463 # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
464 $item->{override} = 1;
465 $num_override++;
468 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
470 # Show serial enumeration when needed
471 if ($item->{enumchron}) {
472 $itemdata_enumchron = 1;
475 push @{ $biblioitem->{itemloop} }, $item;
478 if ( $num_override == scalar( @{ $biblioitem->{itemloop} } ) ) { # That is, if all items require an override
479 $template->param( override_required => 1 );
480 } elsif ( $num_available == 0 ) {
481 $template->param( none_available => 1 );
482 $biblioloopiter{warn} = 1;
483 $biblioloopiter{none_avail} = 1;
485 $template->param( hiddencount => $hiddencount);
487 push @bibitemloop, $biblioitem;
490 @available_itemtypes = uniq( @available_itemtypes );
491 $template->param( available_itemtypes => \@available_itemtypes );
493 # existingreserves building
494 my @reserveloop;
495 my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } );
496 foreach my $res (
497 sort {
498 my $a_found = $a->found() || '';
499 my $b_found = $a->found() || '';
500 $a_found cmp $b_found;
501 } @reserves
504 my %reserve;
505 my @optionloop;
506 for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
507 push(
508 @optionloop,
510 num => $i,
511 selected => ( $i == $res->priority() ),
516 if ( $res->is_found() ) {
517 $reserve{'holdingbranch'} = $res->item()->holdingbranch();
518 $reserve{'biblionumber'} = $res->item()->biblionumber();
519 $reserve{'barcodenumber'} = $res->item()->barcode();
520 $reserve{'wbrcode'} = $res->branchcode();
521 $reserve{'itemnumber'} = $res->itemnumber();
522 $reserve{'wbrname'} = $res->branch()->branchname();
524 if ( $reserve{'holdingbranch'} eq $reserve{'wbrcode'} ) {
526 # Just because the holdingbranch matches the reserve branch doesn't mean the item
527 # has arrived at the destination, check for an open transfer for the item as well
528 my ( $transfertwhen, $transfertfrom, $transferto ) =
529 C4::Circulation::GetTransfers( $res->itemnumber() );
530 if ( not $transferto or $transferto ne $res->branchcode() ) {
531 $reserve{'atdestination'} = 1;
535 # set found to 1 if reserve is waiting for patron pickup
536 $reserve{'found'} = $res->is_found();
537 $reserve{'intransit'} = $res->is_in_transit();
539 elsif ( $res->priority() > 0 ) {
540 if ( my $item = $res->item() ) {
541 $reserve{'itemnumber'} = $item->id();
542 $reserve{'barcodenumber'} = $item->barcode();
543 $reserve{'item_level_hold'} = 1;
547 # get borrowers reserve info
548 if ( C4::Context->preference('HidePatronName') ) {
549 $reserve{'hidename'} = 1;
550 $reserve{'cardnumber'} = $res->borrower()->cardnumber();
552 $reserve{'expirationdate'} = output_pref( { dt => dt_from_string( $res->expirationdate ), dateonly => 1 } )
553 unless ( !defined( $res->expirationdate ) || $res->expirationdate eq '0000-00-00' );
554 $reserve{'date'} = output_pref( { dt => dt_from_string( $res->reservedate ), dateonly => 1 } );
555 $reserve{'borrowernumber'} = $res->borrowernumber();
556 $reserve{'biblionumber'} = $res->biblionumber();
557 $reserve{'borrowernumber'} = $res->borrowernumber();
558 $reserve{'firstname'} = $res->borrower()->firstname();
559 $reserve{'surname'} = $res->borrower()->surname();
560 $reserve{'notes'} = $res->reservenotes();
561 $reserve{'waiting_date'} = $res->waitingdate();
562 $reserve{'waiting_until'} = $res->is_waiting() ? $res->waiting_expires_on() : undef;
563 $reserve{'ccode'} = $res->item() ? $res->item()->ccode() : undef;
564 $reserve{'barcode'} = $res->item() ? $res->item()->barcode() : undef;
565 $reserve{'priority'} = $res->priority();
566 $reserve{'lowestPriority'} = $res->lowestPriority();
567 $reserve{'optionloop'} = \@optionloop;
568 $reserve{'suspend'} = $res->suspend();
569 $reserve{'suspend_until'} = $res->suspend_until();
570 $reserve{'reserve_id'} = $res->reserve_id();
571 $reserve{itemtype} = $res->itemtype();
573 if ( C4::Context->preference('IndependentBranches') && $flags->{'superlibrarian'} != 1 ) {
574 $reserve{'branchloop'} = [ Koha::Libraries->find( $res->branchcode() ) ];
576 else {
577 $reserve{'branchloop'} = GetBranchesLoop( $res->branchcode() );
580 push( @reserveloop, \%reserve );
583 # get the time for the form name...
584 my $time = time();
586 $template->param(
587 branchloop => GetBranchesLoop($userbranch),
588 time => $time,
589 fixedRank => $fixedRank,
592 # display infos
593 $template->param(
594 optionloop => \@optionloop,
595 bibitemloop => \@bibitemloop,
596 itemdata_enumchron => $itemdata_enumchron,
597 date => $date,
598 biblionumber => $biblionumber,
599 findborrower => $findborrower,
600 title => $dat->{title},
601 author => $dat->{author},
602 holdsview => 1,
603 C4::Search::enabled_staff_search_views,
605 if (defined $borrowerinfo && exists $borrowerinfo->{'branchcode'}) {
606 $template->param(
607 borrower_branchname => $branches->{$borrowerinfo->{'branchcode'}}->{'branchname'},
608 borrower_branchcode => $borrowerinfo->{'branchcode'},
612 $biblioloopiter{biblionumber} = $biblionumber;
613 $biblioloopiter{title} = $dat->{title};
614 $biblioloopiter{rank} = $fixedRank;
615 $biblioloopiter{reserveloop} = \@reserveloop;
617 if (@reserveloop) {
618 $template->param( reserveloop => \@reserveloop );
621 push @biblioloop, \%biblioloopiter;
624 $template->param( biblioloop => \@biblioloop );
625 $template->param( biblionumbers => $biblionumbers );
626 $template->param( exceeded_maxreserves => $exceeded_maxreserves );
628 if ($multihold) {
629 $template->param( multi_hold => 1 );
632 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
633 $template->param( reserve_in_future => 1 );
636 $template->param(
637 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
638 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
641 # printout the page
642 output_html_with_http_headers $input, $cookie, $template->output;
644 sub sort_borrowerlist {
645 my $borrowerslist = shift;
646 my $ref = [];
647 push @{$ref}, sort {
648 uc( $a->{surname} . $a->{firstname} ) cmp
649 uc( $b->{surname} . $b->{firstname} )
650 } @{$borrowerslist};
651 return $ref;