(bug #3819) still fixing holds policies
[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 with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 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 => 1 },
55     }
56 );
57
58 # get Branches and Itemtypes
59 my $branches = GetBranches();
60 my $itemtypes = GetItemTypes();
61
62 # get biblio information....
63 my $biblionumber = $input->param('biblionumber');
64 my $dat          = GetBiblioData($biblionumber);
65
66 # Select borrowers infos
67 my $findborrower = $input->param('findborrower');
68 $findborrower =~ s|,| |g;
69 my $cardnumber = $input->param('cardnumber');
70 my $borrowerslist;
71 my $messageborrower;
72 my $warnings;
73 my $messages;
74
75 my $date = C4::Dates->today('iso');
76
77 if ($findborrower) {
78     my ( $count, $borrowers ) =
79       SearchMember($findborrower, 'cardnumber', 'web' );
80
81     my @borrowers = @$borrowers;
82
83     if ( $#borrowers == -1 ) {
84         $input->param( 'findborrower', '' );
85         $messageborrower = "'$findborrower'";
86     }
87     elsif ( $#borrowers == 0 ) {
88         $input->param( 'cardnumber', $borrowers[0]->{'cardnumber'} );
89         $cardnumber = $borrowers[0]->{'cardnumber'};
90     }
91     else {
92         $borrowerslist = \@borrowers;
93     }
94 }
95
96 if ($cardnumber) {
97     my $borrowerinfo = GetMemberDetails( 0, $cardnumber );
98     my $diffbranch;
99     my @getreservloop;
100     my $count_reserv = 0;
101     my $maxreserves;
102
103 #   we check the reserves of the borrower, and if he can reserv a document
104 # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
105
106     my $number_reserves =
107       GetReserveCount( $borrowerinfo->{'borrowernumber'} );
108
109     if ( $number_reserves > C4::Context->preference('maxreserves') ) {
110                 $warnings = 1;
111         $maxreserves = 1;
112     }
113
114     # we check the date expiry of the borrower (only if there is an expiry date, otherwise, set to 1 (warn)
115     my $expiry_date = $borrowerinfo->{dateexpiry};
116     my $expiry = 0; # flag set if patron account has expired
117     if ($expiry_date and $expiry_date ne '0000-00-00' and
118             Date_to_Days(split (/-/,$date)) > Date_to_Days(split (/-/,$expiry_date))) {
119                 $messages = $expiry = 1;
120     }else{
121         $expiry = 0;
122     }
123
124
125     # check if the borrower make the reserv in a different branch
126     if ( $borrowerinfo->{'branchcode'} ne C4::Context->userenv->{'branch'} ) {
127                 $messages = 1;
128         $diffbranch = 1;
129     }
130
131     $template->param(
132                 borrowernumber => $borrowerinfo->{'borrowernumber'},
133                 borrowersurname   => $borrowerinfo->{'surname'},
134                 borrowerfirstname => $borrowerinfo->{'firstname'},
135                 borrowerstreetaddress => $borrowerinfo->{'address'},
136                 borrowercity => $borrowerinfo->{'city'},
137                 borrowerphone => $borrowerinfo->{'phone'},
138                 borrowermobile => $borrowerinfo->{'mobile'},
139                 borrowerfax => $borrowerinfo->{'fax'},
140                 borrowerphonepro => $borrowerinfo->{'phonepro'},
141                 borroweremail => $borrowerinfo->{'email'},
142                 borroweremailpro => $borrowerinfo->{'emailpro'},
143                 borrowercategory => $borrowerinfo->{'category'},
144                 borrowerreservs   => $count_reserv,
145                 maxreserves       => $maxreserves,
146                 expiry            => $expiry,
147                 diffbranch        => $diffbranch,
148                                 messages => $messages,
149                                 warnings => $warnings
150     );
151 }
152
153 $template->param( messageborrower => $messageborrower );
154
155 my $CGIselectborrower;
156 if ($borrowerslist) {
157     my @values;
158     my %labels;
159
160     foreach my $borrower (
161         sort {
162                 $a->{surname}
163               . $a->{firstname} cmp $b->{surname}
164               . $b->{firstname}
165         } @{$borrowerslist}
166       )
167     {
168         push @values, $borrower->{cardnumber};
169
170         $labels{ $borrower->{cardnumber} } = sprintf(
171             '%s, %s ... (%s - %s) ... %s',
172             $borrower->{surname},    $borrower->{firstname},
173             $borrower->{cardnumber}, $borrower->{categorycode},
174             $borrower->{address},
175         );
176     }
177
178     $CGIselectborrower = CGI::scrolling_list(
179         -name     => 'cardnumber',
180         -values   => \@values,
181         -labels   => \%labels,
182         -size     => 7,
183         -multiple => 0,
184     );
185 }
186
187 # get existing reserves .....
188 my ( $count, $reserves ) = GetReservesFromBiblionumber($biblionumber);
189 my $totalcount = $count;
190 my $alreadyreserved;
191
192 # FIXME launch another time GetMemberDetails perhaps until
193 my $borrowerinfo = GetMemberDetails( 0, $cardnumber );
194
195 foreach my $res (@$reserves) {
196     if ( ( $res->{found} eq 'W' ) ) {
197         $count--;
198     }
199
200     if ( $borrowerinfo->{borrowernumber} eq $res->{borrowernumber} ) {
201                 $warnings = 1;
202         $alreadyreserved = 1;
203     }
204 }
205
206 $template->param( alreadyreserved => $alreadyreserved,
207                                 messages => $messages,
208                                 warnings => $warnings );
209
210 # FIXME think @optionloop, is maybe obsolete, or  must be switchable by a systeme preference fixed rank or not
211 # make priorities options
212
213 my @optionloop;
214 for ( 1 .. $count + 1 ) {
215     push(
216         @optionloop,
217         {
218             num      => $_,
219             selected => ( $_ == $count + 1 ),
220         }
221     );
222 }
223 # adding a fixed value for priority options
224 my $fixedRank = $count+1;
225
226 my @branchcodes;
227 my %itemnumbers_of_biblioitem;
228 my @itemnumbers;
229
230 if (my $items = get_itemnumbers_of($biblionumber)->{$biblionumber}){
231         @itemnumbers  = @$items;
232 }
233 else {
234         $template->param('noitems' => 1);
235 }
236         
237 my $iteminfos_of = GetItemInfosOf(@itemnumbers);
238
239 foreach my $itemnumber (@itemnumbers) {
240     my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
241     push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
242 }
243
244 my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
245
246 my $notforloan_label_of = get_notforloan_label_of();
247 my $biblioiteminfos_of  = GetBiblioItemInfosOf(@biblioitemnumbers);
248
249 my @bibitemloop;
250
251 foreach my $biblioitemnumber (@biblioitemnumbers) {
252     my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
253
254     my $num_available;
255     my $num_override;
256
257     $biblioitem->{description} =
258       $itemtypes->{ $biblioitem->{itemtype} }{description};
259
260     foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } ){
261         my $item = $iteminfos_of->{$itemnumber};
262         unless (C4::Context->preference('item-level_itypes')) {
263             $item->{itype} = $biblioitem->{itemtype};
264         }
265
266         $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
267         $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
268         $item->{homebranchname} = $branches->{ $item->{homebranch} }{branchname};
269
270         # if the holdingbranch is different than the homebranch, we show the
271         # holdingbranch of the document too
272         if ( $item->{homebranch} ne $item->{holdingbranch} ) {
273             $item->{holdingbranchname} =
274               $branches->{ $item->{holdingbranch} }{branchname};
275         }
276         
277         #   add information
278         $item->{itemcallnumber} = $item->{itemcallnumber};
279     
280         # if the item is currently on loan, we display its return date and
281         # change the background color
282         my $issues= GetItemIssue($itemnumber);
283         if ( $issues->{'date_due'} ) {
284             $item->{date_due} = format_date($issues->{'date_due'});
285             $item->{backgroundcolor} = 'onloan';
286         }
287
288         # checking reserve
289         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemnumber);
290         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
291
292         if ( defined $reservedate ) {
293             $item->{backgroundcolor} = 'reserved';
294             $item->{reservedate}     = format_date($reservedate);
295             $item->{ReservedForBorrowernumber}     = $reservedfor;
296             $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
297             $item->{ReservedForFirstname}     = $ItemBorrowerReserveInfo->{'firstname'};
298             $item->{ExpectedAtLibrary}     = $branches->{$expectedAt}{branchname};
299             
300         }
301
302         # Management of the notforloan document
303         if ( $item->{notforloan} ) {
304             $item->{backgroundcolor} = 'other';
305             $item->{notforloanvalue} =
306               $notforloan_label_of->{ $item->{notforloan} };
307         }
308
309         # Management of lost or long overdue items
310         if ( $item->{itemlost} ) {
311
312             # FIXME localized strings should never be in Perl code
313             $item->{message} =
314                 $item->{itemlost} == 1 ? "(lost)"
315               : $item->{itemlost} == 2 ? "(long overdue)"
316               : "";
317             $item->{backgroundcolor} = 'other';
318         }
319
320         # Check the transit status
321         my ( $transfertwhen, $transfertfrom, $transfertto ) =
322           GetTransfers($itemnumber);
323
324         if ( $transfertwhen ne '' ) {
325             $item->{transfertwhen} = format_date($transfertwhen);
326             $item->{transfertfrom} =
327               $branches->{$transfertfrom}{branchname};
328             $item->{transfertto} = $branches->{$transfertto}{branchname};
329         $item->{nocancel} = 1;
330         }
331
332         # If there is no loan, return and transfer, we show a checkbox.
333         $item->{notforloan} = $item->{notforloan} || 0;
334     
335         # if independent branches is on we need to check if the person can reserve
336         # for branches they arent logged in to
337         if ( C4::Context->preference("IndependantBranches") ) { 
338             if (! C4::Context->preference("canreservefromotherbranches")){
339                 # cant reserve items so need to check if item homebranch and userenv branch match if not we cant reserve
340                 my $userenv = C4::Context->userenv; 
341                 if ( ($userenv) && ( $userenv->{flags} %2 != 1 ) ) {
342                     $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
343                 } 
344             }
345         }
346
347
348         my $branchitemrule = GetBranchItemRule( $item->{'homebranch'}, $item->{'itype'} );
349         my $policy_holdallowed = 1;
350
351         $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
352
353         if ( $branchitemrule->{'holdallowed'} == 0 ||
354                 ( $branchitemrule->{'holdallowed'} == 1 && $borrowerinfo->{'branchcode'} ne $item->{'homebranch'} ) ) {
355             $policy_holdallowed = 0;
356         }
357
358         if (IsAvailableForItemLevelRequest($itemnumber) and not $item->{cantreserve}) {
359             if ( not $policy_holdallowed and C4::Context->preference( 'AllowHoldPolicyOverride' ) ) {
360                 $item->{override} = 1;
361                 $num_override++;
362             } elsif ( $policy_holdallowed ) {
363                 $item->{available} = 1;
364                 $num_available++;
365             }
366         }
367         # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
368
369         # FIXME: move this to a pm
370         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
371         $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
372         while (my $wait_hashref = $sth2->fetchrow_hashref) {
373             $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
374         }
375         push @{ $biblioitem->{itemloop} }, $item;
376     }
377
378     if ( $num_override == scalar( @{ $biblioitem->{itemloop} } ) ) { # That is, if all items require an override
379         $template->param( override_required => 1 );
380     } elsif ( $num_available == 0 ) {
381         $template->param( none_available => 1 );
382         $template->param( warnings => 1 );
383     }
384
385     push @bibitemloop, $biblioitem;
386 }
387
388 # existingreserves building
389 my @reserveloop;
390 ( $count, $reserves ) = GetReservesFromBiblionumber($biblionumber);
391 foreach my $res ( sort { $a->{found} cmp $b->{found} } @$reserves ) {
392     my %reserve;
393     my @optionloop;
394     for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
395         push(
396             @optionloop,
397             {
398                 num      => $i,
399                 selected => ( $i == $res->{priority} ),
400             }
401         );
402     }
403     my @branchloop;
404     foreach my $br ( keys %$branches ) {
405         my %abranch;
406         $abranch{'selected'}   = ( $br eq $res->{'branchcode'} );
407         $abranch{'branch'}     = $br;
408         $abranch{'branchname'} = $branches->{$br}->{'branchname'};
409         push( @branchloop, \%abranch );
410     }
411
412     if ( ( $res->{'found'} eq 'W' ) ) {
413         my $item = $res->{'itemnumber'};
414         $item = GetBiblioFromItemNumber($item,undef);
415         $reserve{'wait'}= 1; 
416         $reserve{'holdingbranch'}=$item->{'holdingbranch'};
417         $reserve{'biblionumber'}=$item->{'biblionumber'};
418         $reserve{'barcodenumber'}   = $item->{'barcode'};
419         $reserve{'wbrcode'} = $res->{'branchcode'};
420         $reserve{'itemnumber'}  = $res->{'itemnumber'};
421         $reserve{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
422         if($reserve{'holdingbranch'} eq $reserve{'wbrcode'}){
423             $reserve{'atdestination'} = 1;
424         }
425         # set found to 1 if reserve is waiting for patron pickup
426         $reserve{'found'} = 1 if $res->{'found'} eq 'W';
427     } elsif ($res->{priority} > 0) {
428         if (defined($res->{itemnumber})) {
429             my $item = GetItem($res->{itemnumber});
430             $reserve{'itemnumber'}  = $res->{'itemnumber'};
431             $reserve{'barcodenumber'}   = $item->{'barcode'};
432             $reserve{'item_level_hold'} = 1;
433         }
434     }
435     
436 #     get borrowers reserve info
437 my $reserveborrowerinfo = GetMemberDetails( $res->{'borrowernumber'}, 0);
438
439     $reserve{'date'}           = format_date( $res->{'reservedate'} );
440     $reserve{'borrowernumber'} = $res->{'borrowernumber'};
441     $reserve{'biblionumber'}   = $res->{'biblionumber'};
442     $reserve{'borrowernumber'} = $res->{'borrowernumber'};
443     $reserve{'firstname'}      = $reserveborrowerinfo->{'firstname'};
444     $reserve{'surname'}        = $reserveborrowerinfo->{'surname'};
445     $reserve{'notes'}          = $res->{'reservenotes'};
446     $reserve{'wait'}           =
447       ( ( $res->{'found'} eq 'W' ) or ( $res->{'priority'} eq '0' ) );
448     $reserve{'constrainttypea'} = ( $res->{'constrainttype'} eq 'a' );
449     $reserve{'constrainttypeo'} = ( $res->{'constrainttype'} eq 'o' );
450     $reserve{'voldesc'}         = $res->{'volumeddesc'};
451     $reserve{'ccode'}           = $res->{'ccode'};
452     $reserve{'barcode'}         = $res->{'barcode'};
453     $reserve{'priority'}    = $res->{'priority'};
454     $reserve{'branchloop'} = \@branchloop;
455     $reserve{'optionloop'} = \@optionloop;
456
457     push( @reserveloop, \%reserve );
458 }
459
460 my $default = C4::Context->userenv->{branch};
461 my @values;
462 my %label_of;
463
464 foreach my $branchcode (sort keys %{$branches} ) {
465     push @values, $branchcode;
466     $label_of{$branchcode} = $branches->{$branchcode}->{branchname};
467 }
468 my $CGIbranch = CGI::scrolling_list(
469     -name     => 'pickup',
470     -id          => 'pickup',
471     -values   => \@values,
472     -default  => $default,
473     -labels   => \%label_of,
474     -size     => 1,
475     -multiple => 0,
476 );
477
478 # get the time for the form name...
479 my $time = time();
480
481 $template->param(
482     CGIbranch   => $CGIbranch,
483     reserveloop => \@reserveloop,
484     time        => $time,
485     fixedRank   => $fixedRank,
486 );
487
488 # display infos
489 $template->param(
490     optionloop        => \@optionloop,
491     bibitemloop       => \@bibitemloop,
492     date              => $date,
493     biblionumber      => $biblionumber,
494     findborrower      => $findborrower,
495     cardnumber        => $cardnumber,
496     CGIselectborrower => $CGIselectborrower,
497     title             => $dat->{title},
498     author            => $dat->{author},
499         holdsview => 1,
500         borrower_branchname => $branches->{$borrowerinfo->{'branchcode'}}->{'branchname'},
501         borrower_branchcode => $borrowerinfo->{'branchcode'},
502 );
503
504 # printout the page
505 output_html_with_http_headers $input, $cookie, $template->output;