Merge branch 'new/bug_4330' into kcmaster
[koha.git] / reserve / request.pl
1 #!/usr/bin/perl
2
3
4 #writen 2/1/00 by chris@katipo.oc.nz
5 # Copyright 2000-2002 Katipo Communications
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 =head1 request.pl
23
24 script to place reserves/requests
25
26 =cut
27
28 use strict;
29 use warnings;
30 use C4::Branch; # GetBranches get_branchinfos_of
31 use CGI;
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 C4::Dates qw/format_date/;
42 use C4::Members;
43 use C4::Search;         # enabled_staff_search_views
44
45 my $dbh = C4::Context->dbh;
46 my $sth;
47 my $input = new CGI;
48 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
49     {
50         template_name   => "reserve/request.tmpl",
51         query           => $input,
52         type            => "intranet",
53         authnotrequired => 0,
54         flagsrequired   => { reserveforothers => 'place_holds' },
55     }
56 );
57
58 my $multihold = $input->param('multi_hold');
59 $template->param(multi_hold => $multihold);
60 my $showallitems = $input->param('showallitems');
61
62 # get Branches and Itemtypes
63 my $branches = GetBranches();
64 my $itemtypes = GetItemTypes();
65     
66 my $default = C4::Context->userenv->{branch};
67 my @values;
68 my %label_of;
69     
70 foreach my $branchcode (sort keys %{$branches} ) {
71     push @values, $branchcode;
72     $label_of{$branchcode} = $branches->{$branchcode}->{branchname};
73 }
74 my $CGIbranch = CGI::scrolling_list(
75                                     -name     => 'pickup',
76                                     -id          => 'pickup',
77                                     -values   => \@values,
78                                     -default  => $default,
79                                     -labels   => \%label_of,
80                                     -size     => 1,
81                                     -multiple => 0,
82                                    );
83
84 # Select borrowers infos
85 my $findborrower = $input->param('findborrower');
86 $findborrower = '' unless defined $findborrower;
87 $findborrower =~ s|,| |g;
88 my $borrowernumber_hold = $input->param('borrowernumber') || '';
89 my $borrowerslist;
90 my $messageborrower;
91 my $warnings;
92 my $messages;
93
94 my $date = C4::Dates->today('iso');
95 my $action = $input->param('action');
96 $action ||= q{};
97
98 if ( $action eq 'move' ) {
99   my $where = $input->param('where');
100   my $borrowernumber = $input->param('borrowernumber');
101   my $biblionumber = $input->param('biblionumber');
102                      
103   AlterPriority( $where, $borrowernumber, $biblionumber );
104
105 } elsif ( $action eq 'cancel' ) {
106   my $borrowernumber = $input->param('borrowernumber');
107   my $biblionumber = $input->param('biblionumber');
108   CancelReserve( $biblionumber, '', $borrowernumber );
109 } elsif ( $action eq 'setLowestPriority' ) {
110   my $borrowernumber = $input->param('borrowernumber');
111   my $biblionumber   = $input->param('biblionumber');
112   ToggleLowestPriority( $borrowernumber, $biblionumber );
113 }
114
115 if ($findborrower) {
116     my ( $count, $borrowers ) =
117       SearchMember($findborrower, 'cardnumber', 'web' );
118
119     my @borrowers = @$borrowers;
120
121     if ( !@borrowers ) {
122         $messageborrower = "'$findborrower'";
123     }
124     elsif ( @borrowers == 1 ) {
125         $borrowernumber_hold = $borrowers[0]->{'borrowernumber'};
126     }
127     else {
128         $borrowerslist = \@borrowers;
129     }
130 }
131
132 if ($borrowernumber_hold) {
133     my $borrowerinfo = GetMemberDetails( $borrowernumber_hold );
134     my $diffbranch;
135     my @getreservloop;
136     my $count_reserv = 0;
137     my $maxreserves;
138
139 #   we check the reserves of the borrower, and if he can reserv a document
140 # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
141
142     my $number_reserves =
143       GetReserveCount( $borrowerinfo->{'borrowernumber'} );
144
145     if ( C4::Context->preference('maxreserves') && ($number_reserves >= C4::Context->preference('maxreserves')) ) {
146                 $warnings = 1;
147         $maxreserves = 1;
148     }
149
150     # we check the date expiry of the borrower (only if there is an expiry date, otherwise, set to 1 (warn)
151     my $expiry_date = $borrowerinfo->{dateexpiry};
152     my $expiry = 0; # flag set if patron account has expired
153     if ($expiry_date and $expiry_date ne '0000-00-00' and
154             Date_to_Days(split /-/,$date) > Date_to_Days(split /-/,$expiry_date)) {
155                 $messages = $expiry = 1;
156     }
157      
158
159     # check if the borrower make the reserv in a different branch
160     if ( $borrowerinfo->{'branchcode'} ne C4::Context->userenv->{'branch'} ) {
161                 $messages = 1;
162         $diffbranch = 1;
163     }
164
165     $template->param(
166                 borrowernumber      => $borrowerinfo->{'borrowernumber'},
167                 borrowersurname     => $borrowerinfo->{'surname'},
168                 borrowerfirstname   => $borrowerinfo->{'firstname'},
169                 borrowerstreetaddress   => $borrowerinfo->{'address'},
170                 borrowercity        => $borrowerinfo->{'city'},
171                 borrowerphone       => $borrowerinfo->{'phone'},
172                 borrowermobile      => $borrowerinfo->{'mobile'},
173                 borrowerfax         => $borrowerinfo->{'fax'},
174                 borrowerphonepro    => $borrowerinfo->{'phonepro'},
175                 borroweremail       => $borrowerinfo->{'email'},
176                 borroweremailpro    => $borrowerinfo->{'emailpro'},
177                 borrowercategory    => $borrowerinfo->{'category'},
178                 borrowerreservs     => $count_reserv,
179                 cardnumber          => $borrowerinfo->{'cardnumber'},
180                 maxreserves         => $maxreserves,
181                 expiry              => $expiry,
182                 diffbranch          => $diffbranch,
183                                 messages            => $messages,
184                                 warnings            => $warnings
185     );
186 }
187
188 $template->param( messageborrower => $messageborrower );
189
190 my $CGIselectborrower;
191 if ($borrowerslist) {
192     my @values;
193     my %labels;
194
195     foreach my $borrower (
196         sort {
197                 $a->{surname}
198               . $a->{firstname} cmp $b->{surname}
199               . $b->{firstname}
200         } @{$borrowerslist}
201       )
202     {
203         push @values, $borrower->{borrowernumber};
204
205         $labels{ $borrower->{borrowernumber} } = sprintf(
206             '%s, %s ... (%s - %s) ... %s',
207             $borrower->{surname} ||'',    $borrower->{firstname} || '',
208             $borrower->{cardnumber} || '', $borrower->{categorycode} || '',
209             $borrower->{address} || '',
210         );
211     }
212
213     $CGIselectborrower = CGI::scrolling_list(
214         -name     => 'borrowernumber',
215         -values   => \@values,
216         -labels   => \%labels,
217         -size     => 7,
218         -multiple => 0,
219     );
220 }
221
222 # FIXME launch another time GetMemberDetails perhaps until
223 my $borrowerinfo = GetMemberDetails( $borrowernumber_hold );
224
225 my @biblionumbers = ();
226 my $biblionumbers = $input->param('biblionumbers');
227 if ($multihold) {
228     @biblionumbers = split '/', $biblionumbers;
229 } else {
230     push @biblionumbers, $input->param('biblionumber');
231 }
232
233 my @biblioloop = ();
234 foreach my $biblionumber (@biblionumbers) {
235
236     my %biblioloopiter = ();
237         my $maxreserves;
238
239     my $dat          = GetBiblioData($biblionumber);
240
241     unless ( CanBookBeReserved($borrowerinfo->{borrowernumber}, $biblionumber) ) {
242                 $warnings = 1;
243         $maxreserves = 1;
244     }
245     # get existing reserves .....
246     my ( $count, $reserves ) = GetReservesFromBiblionumber($biblionumber,1);
247     my $totalcount = $count;
248     my $alreadyreserved;
249
250     foreach my $res (@$reserves) {
251         if ( defined $res->{found} && $res->{found} eq 'W' ) {
252             $count--;
253         }
254
255         if ( defined $borrowerinfo && ($borrowerinfo->{borrowernumber} eq $res->{borrowernumber}) ) {
256             $warnings = 1;
257             $alreadyreserved = 1;
258             $biblioloopiter{warn} = 1;
259             $biblioloopiter{alreadyres} = 1;
260         }
261     }
262
263     $template->param( alreadyreserved => $alreadyreserved,
264                       messages => $messages,
265                       warnings => $warnings,
266                                           maxreserves=>$maxreserves
267                                           );
268     
269     
270     # FIXME think @optionloop, is maybe obsolete, or  must be switchable by a systeme preference fixed rank or not
271     # make priorities options
272     
273     my @optionloop;
274     for ( 1 .. $count + 1 ) {
275         push(
276              @optionloop,
277              {
278               num      => $_,
279               selected => ( $_ == $count + 1 ),
280              }
281             );
282     }
283     # adding a fixed value for priority options
284     my $fixedRank = $count+1;
285
286     my @branchcodes;
287     my %itemnumbers_of_biblioitem;
288     my @itemnumbers;
289     
290     ## $items is array of 'item' table numbers
291     if (my $items = get_itemnumbers_of($biblionumber)->{$biblionumber}){
292         @itemnumbers  = @$items;
293     }
294     else {
295         $template->param('noitems' => 1);
296         $biblioloopiter{noitems} = 1;
297     }
298     
299     ## Hash of item number to 'item' table fields
300     my $iteminfos_of = GetItemInfosOf(@itemnumbers);
301     
302     ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers,
303     ## when by definition all of the itemnumber have the same biblioitemnumber
304     foreach my $itemnumber (@itemnumbers) {
305         my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
306         push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
307     }
308     
309     ## Should be same as biblionumber
310     my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
311     
312     my $notforloan_label_of = get_notforloan_label_of();
313     
314     ## Hash of biblioitemnumber to 'biblioitem' table records
315     my $biblioiteminfos_of  = GetBiblioItemInfosOf(@biblioitemnumbers);
316     
317     my @bibitemloop;
318     
319     foreach my $biblioitemnumber (@biblioitemnumbers) {
320         my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
321         my $num_available = 0;
322         my $num_override  = 0;
323         my $hiddencount   = 0;
324         
325         $biblioitem->{description} =
326           $itemtypes->{ $biblioitem->{itemtype} }{description};
327         $biblioloopiter{description} = $biblioitem->{description};
328         $biblioloopiter{itypename} = $biblioitem->{description};
329         $biblioloopiter{imageurl} =
330           getitemtypeimagelocation('intranet', $itemtypes->{$biblioitem->{itemtype}}{imageurl});
331         
332         foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )    {
333             my $item = $iteminfos_of->{$itemnumber};
334             
335             unless (C4::Context->preference('item-level_itypes')) {
336                 $item->{itype} = $biblioitem->{itemtype};
337             }
338             
339             $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
340             $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
341             $item->{homebranchname} = $branches->{ $item->{homebranch} }{branchname};
342             
343             # if the holdingbranch is different than the homebranch, we show the
344             # holdingbranch of the document too
345             if ( $item->{homebranch} ne $item->{holdingbranch} ) {
346                 $item->{holdingbranchname} =
347                   $branches->{ $item->{holdingbranch} }{branchname};
348             }
349             
350             #   add information
351             $item->{itemcallnumber} = $item->{itemcallnumber};
352             
353             # if the item is currently on loan, we display its return date and
354             # change the background color
355             my $issues= GetItemIssue($itemnumber);
356             if ( $issues->{'date_due'} ) {
357                 $item->{date_due} = format_date($issues->{'date_due'});
358                 $item->{backgroundcolor} = 'onloan';
359             }
360             
361             # checking reserve
362             my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemnumber);
363             my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
364             
365             if ( defined $reservedate ) {
366                 $item->{backgroundcolor} = 'reserved';
367                 $item->{reservedate}     = format_date($reservedate);
368                 $item->{ReservedForBorrowernumber}     = $reservedfor;
369                 $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
370                 $item->{ReservedForFirstname}     = $ItemBorrowerReserveInfo->{'firstname'};
371                 $item->{ExpectedAtLibrary}     = $branches->{$expectedAt}{branchname};
372                 
373             }
374             
375             # Management of the notforloan document
376             if ( $item->{notforloan} ) {
377                 $item->{backgroundcolor} = 'other';
378                 $item->{notforloanvalue} =
379                   $notforloan_label_of->{ $item->{notforloan} };
380             }
381      
382             # Management of lost or long overdue items
383             if ( $item->{itemlost} ) {
384                 
385                 # FIXME localized strings should never be in Perl code
386                 $item->{message} =
387                   $item->{itemlost} == 1 ? "(lost)"
388                     : $item->{itemlost} == 2 ? "(long overdue)"
389                       : "";
390                 $item->{backgroundcolor} = 'other';
391                 if (GetHideLostItemsPreference($borrowernumber) && !$showallitems) {
392                     $item->{hide} = 1;
393                     $hiddencount++;
394                 }
395             }
396             
397             # Check the transit status
398             my ( $transfertwhen, $transfertfrom, $transfertto ) =
399               GetTransfers($itemnumber);
400             
401             if ( defined $transfertwhen && $transfertwhen ne '' ) {
402                 $item->{transfertwhen} = format_date($transfertwhen);
403                 $item->{transfertfrom} =
404                   $branches->{$transfertfrom}{branchname};
405                 $item->{transfertto} = $branches->{$transfertto}{branchname};
406                 $item->{nocancel} = 1;
407             }
408             
409             # If there is no loan, return and transfer, we show a checkbox.
410             $item->{notforloan} = $item->{notforloan} || 0;
411             
412             # if independent branches is on we need to check if the person can reserve
413             # for branches they arent logged in to
414             if ( C4::Context->preference("IndependantBranches") ) { 
415                 if (! C4::Context->preference("canreservefromotherbranches")){
416                     # cant reserve items so need to check if item homebranch and userenv branch match if not we cant reserve
417                     my $userenv = C4::Context->userenv;
418                     if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
419                         $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
420                     }
421                 }
422             }
423             
424             my $branch = C4::Circulation::_GetCircControlBranch($item, $borrowerinfo);
425
426             my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
427             my $policy_holdallowed = 1;
428             
429             $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
430             
431             if ( $branchitemrule->{'holdallowed'} == 0 ||
432                  ( $branchitemrule->{'holdallowed'} == 1 && 
433                      $borrowerinfo->{'branchcode'} ne $item->{'homebranch'} ) ) {
434                 $policy_holdallowed = 0;
435             }
436             
437             if (IsAvailableForItemLevelRequest($itemnumber) and 
438                 not $item->{cantreserve} and 
439                 CanItemBeReserved($borrowerinfo->{borrowernumber}, $itemnumber) ) {
440                 if ( $policy_holdallowed ) {
441                     $item->{available} = 1;
442                     $num_available++;
443                 }
444             } elsif (C4::Context->preference( 'AllowHoldPolicyOverride' ) ) {
445                     $item->{override} = 1;
446                     $num_override++;
447             }
448             # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
449             if (C4::Context->preference( 'AllowHoldPolicyOverride' ) && !$item->{available} ) {
450                 $item->{override} = 1;
451                 $num_override++;
452             }   
453
454             # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
455             
456             # FIXME: move this to a pm
457             my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
458             $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
459             while (my $wait_hashref = $sth2->fetchrow_hashref) {
460                 $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
461             }
462             push @{ $biblioitem->{itemloop} }, $item;
463         }
464         
465         if ( $num_override == scalar( @{ $biblioitem->{itemloop} } ) ) { # That is, if all items require an override
466             $template->param( override_required => 1 );
467         } elsif ( $num_available == 0 ) {
468             $template->param( none_available => 1 );
469             $template->param( warnings => 1 );
470             $biblioloopiter{warn} = 1;
471             $biblioloopiter{none_avail} = 1;
472         }
473         $template->param( hiddencount => $hiddencount);
474         
475         push @bibitemloop, $biblioitem;
476     }
477
478     # existingreserves building
479     my @reserveloop;
480     ( $count, $reserves ) = GetReservesFromBiblionumber($biblionumber,1);
481     foreach my $res ( sort { 
482             my $a_found = $a->{found} || '';
483             my $b_found = $a->{found} || '';
484             $a_found cmp $b_found; 
485         } @$reserves ) {
486         my %reserve;
487         my @optionloop;
488         for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
489             push(
490                  @optionloop,
491                  {
492                   num      => $i,
493                   selected => ( $i == $res->{priority} ),
494                  }
495                 );
496         }
497         
498         if ( defined $res->{'found'} && $res->{'found'} eq 'W' || $res->{'found'} eq 'T' ) {
499             my $item = $res->{'itemnumber'};
500             $item = GetBiblioFromItemNumber($item,undef);
501             $reserve{'wait'}= 1; 
502             $reserve{'holdingbranch'}=$item->{'holdingbranch'};
503             $reserve{'biblionumber'}=$item->{'biblionumber'};
504             $reserve{'barcodenumber'}   = $item->{'barcode'};
505             $reserve{'wbrcode'} = $res->{'branchcode'};
506             $reserve{'itemnumber'}  = $res->{'itemnumber'};
507             $reserve{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
508             if($reserve{'holdingbranch'} eq $reserve{'wbrcode'}){
509                 $reserve{'atdestination'} = 1;
510             }
511             # set found to 1 if reserve is waiting for patron pickup
512             $reserve{'found'} = 1 if $res->{'found'} eq 'W';
513             $reserve{'intransit'} = 1 if $res->{'found'} eq 'T';
514         } elsif ($res->{priority} > 0) {
515             if (defined($res->{itemnumber})) {
516                 my $item = GetItem($res->{itemnumber});
517                 $reserve{'itemnumber'}  = $res->{'itemnumber'};
518                 $reserve{'barcodenumber'}   = $item->{'barcode'};
519                 $reserve{'item_level_hold'} = 1;
520             }
521         }
522         
523         #     get borrowers reserve info
524         my $reserveborrowerinfo = GetMemberDetails( $res->{'borrowernumber'}, 0);
525         if (C4::Context->preference('HidePatronName')){
526             $reserve{'hidename'} = 1;
527             $reserve{'cardnumber'} = $reserveborrowerinfo->{'cardnumber'};
528         }
529         $reserve{'expirationdate'} = format_date( $res->{'expirationdate'} ) 
530             unless ( !defined($res->{'expirationdate'}) || $res->{'expirationdate'} eq '0000-00-00' );
531         $reserve{'date'}           = format_date( $res->{'reservedate'} );
532         $reserve{'borrowernumber'} = $res->{'borrowernumber'};
533         $reserve{'biblionumber'}   = $res->{'biblionumber'};
534         $reserve{'borrowernumber'} = $res->{'borrowernumber'};
535         $reserve{'firstname'}      = $reserveborrowerinfo->{'firstname'};
536         $reserve{'surname'}        = $reserveborrowerinfo->{'surname'};     
537         $reserve{'notes'}          = $res->{'reservenotes'};
538         $reserve{'wait'}           =
539           ( ( defined $res->{'found'} and $res->{'found'} eq 'W' ) or ( $res->{'priority'} eq '0' ) );
540         $reserve{'constrainttypea'} = ( $res->{'constrainttype'} eq 'a' );
541         $reserve{'constrainttypeo'} = ( $res->{'constrainttype'} eq 'o' );
542         $reserve{'voldesc'}         = $res->{'volumeddesc'};
543         $reserve{'ccode'}           = $res->{'ccode'};
544         $reserve{'barcode'}         = $res->{'barcode'};
545         $reserve{'priority'}    = $res->{'priority'};
546         $reserve{'lowestPriority'}    = $res->{'lowestPriority'};
547         $reserve{'branchloop'} = GetBranchesLoop($res->{'branchcode'});
548         $reserve{'optionloop'} = \@optionloop;
549         
550         push( @reserveloop, \%reserve );
551     }
552     
553     # get the time for the form name...
554     my $time = time();
555     
556     $template->param(
557                      CGIbranch   => $CGIbranch,
558
559                      time        => $time,
560                      fixedRank   => $fixedRank,
561                     );
562     
563     # display infos
564     $template->param(
565                      optionloop        => \@optionloop,
566                      bibitemloop       => \@bibitemloop,
567                      date              => $date,
568                      biblionumber      => $biblionumber,
569                      findborrower      => $findborrower,
570                      title             => $dat->{title},
571                      author            => $dat->{author},
572                      holdsview => 1,
573                      C4::Search::enabled_staff_search_views,
574                     );
575     if (defined $borrowerinfo && exists $borrowerinfo->{'branchcode'}) {
576         $template->param(
577                      borrower_branchname => $branches->{$borrowerinfo->{'branchcode'}}->{'branchname'},
578                      borrower_branchcode => $borrowerinfo->{'branchcode'},
579         );
580     }
581     $template->param(CGIselectborrower => $CGIselectborrower) if defined $CGIselectborrower;
582
583     $biblioloopiter{biblionumber} = $biblionumber;
584     $biblioloopiter{title} = $dat->{title};
585     $biblioloopiter{rank} = $fixedRank;
586     $biblioloopiter{reserveloop} = \@reserveloop;
587
588     if (@reserveloop) {
589         $template->param( reserveloop => \@reserveloop );
590     }
591     
592
593     push @biblioloop, \%biblioloopiter;
594 }
595
596 $template->param( biblioloop => \@biblioloop );
597 $template->param( biblionumbers => $biblionumbers );
598 $template->param( DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar() );
599
600 if ($multihold) {
601     $template->param( multi_hold => 1 );
602 }
603
604 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
605     $template->param( reserve_in_future => 1 );
606 }
607     
608 # printout the page
609 output_html_with_http_headers $input, $cookie, $template->output;