(bug #3737) fix title search in order history
[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 ( not CanBookBeReserved($borrowerinfo->{borrowernumber}, $biblionumber)) {
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     $biblioitem->{itemloop} = [];
257     
258     $biblioitem->{description} =
259       $itemtypes->{ $biblioitem->{itemtype} }{description};
260
261     foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } ){
262         my $item = $iteminfos_of->{$itemnumber};
263         
264         
265         unless (C4::Context->preference('item-level_itypes')) {
266             $item->{itype} = $biblioitem->{itemtype};
267         }
268
269         $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
270         $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
271         $item->{homebranchname} = $branches->{ $item->{homebranch} }{branchname};
272
273         # if the holdingbranch is different than the homebranch, we show the
274         # holdingbranch of the document too
275         if ( $item->{homebranch} ne $item->{holdingbranch} ) {
276             $item->{holdingbranchname} =
277               $branches->{ $item->{holdingbranch} }{branchname};
278         }
279         
280         #   add information
281         $item->{itemcallnumber} = $item->{itemcallnumber};
282     
283         # if the item is currently on loan, we display its return date and
284         # change the background color
285         my $issues= GetItemIssue($itemnumber);
286         if ( $issues->{'date_due'} ) {
287             $item->{date_due} = format_date($issues->{'date_due'});
288             $item->{backgroundcolor} = 'onloan';
289         }
290
291         # checking reserve
292         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemnumber);
293         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
294
295         if ( defined $reservedate ) {
296             $item->{backgroundcolor} = 'reserved';
297             $item->{reservedate}     = format_date($reservedate);
298             $item->{ReservedForBorrowernumber}     = $reservedfor;
299             $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
300             $item->{ReservedForFirstname}     = $ItemBorrowerReserveInfo->{'firstname'};
301             $item->{ExpectedAtLibrary}     = $branches->{$expectedAt}{branchname};
302             
303         }
304
305         # Management of the notforloan document
306         if ( $item->{notforloan} ) {
307             $item->{backgroundcolor} = 'other';
308             $item->{notforloanvalue} =
309               $notforloan_label_of->{ $item->{notforloan} };
310         }
311
312         # Management of lost or long overdue items
313         if ( $item->{itemlost} ) {
314
315             # FIXME localized strings should never be in Perl code
316             $item->{message} =
317                 $item->{itemlost} == 1 ? "(lost)"
318               : $item->{itemlost} == 2 ? "(long overdue)"
319               : "";
320             $item->{backgroundcolor} = 'other';
321         }
322
323         # Check the transit status
324         my ( $transfertwhen, $transfertfrom, $transfertto ) =
325           GetTransfers($itemnumber);
326
327         if ( $transfertwhen ne '' ) {
328             $item->{transfertwhen} = format_date($transfertwhen);
329             $item->{transfertfrom} =
330               $branches->{$transfertfrom}{branchname};
331             $item->{transfertto} = $branches->{$transfertto}{branchname};
332         $item->{nocancel} = 1;
333         }
334
335         # If there is no loan, return and transfer, we show a checkbox.
336         $item->{notforloan} = $item->{notforloan} || 0;
337     
338         # if independent branches is on we need to check if the person can reserve
339         # for branches they arent logged in to
340         if ( C4::Context->preference("IndependantBranches") ) { 
341             if (! C4::Context->preference("canreservefromotherbranches")){
342                 # cant reserve items so need to check if item homebranch and userenv branch match if not we cant reserve
343                 my $userenv = C4::Context->userenv; 
344                 if ( ($userenv) && ( $userenv->{flags} %2 != 1 ) ) {
345                     $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
346                 } 
347             }
348         }
349
350         my $branch = C4::Circulation::_GetCircControlBranch($item, $borrowerinfo);
351
352         my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
353         my $policy_holdallowed = 1;
354
355         $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
356
357         if ( $branchitemrule->{'holdallowed'} == 0 ||
358                 ( $branchitemrule->{'holdallowed'} == 1 && $borrowerinfo->{'branchcode'} ne $item->{'homebranch'} ) ) {
359             $policy_holdallowed = 0;
360         }
361
362         if (IsAvailableForItemLevelRequest($itemnumber) and not $item->{cantreserve} and CanItemBeReserved($borrowerinfo->{borrowernumber}, $itemnumber)) {
363             if ( not $policy_holdallowed and C4::Context->preference( 'AllowHoldPolicyOverride' ) ) {
364                 $item->{override} = 1;
365                 $num_override++;
366             } elsif ( $policy_holdallowed ) {
367                 $item->{available} = 1;
368                 $num_available++;
369             }
370         }
371         # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
372
373         # FIXME: move this to a pm
374         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
375         $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
376         while (my $wait_hashref = $sth2->fetchrow_hashref) {
377             $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
378         }
379         push @{ $biblioitem->{itemloop} }, $item;
380     }
381
382     if ( $num_override == scalar( @{ $biblioitem->{itemloop} } ) ) { # That is, if all items require an override
383         $template->param( override_required => 1 );
384     } elsif ( $num_available == 0 ) {
385         $template->param( none_available => 1 );
386         $template->param( warnings => 1 );
387     }
388
389     push @bibitemloop, $biblioitem;
390 }
391
392 # existingreserves building
393 my @reserveloop;
394 ( $count, $reserves ) = GetReservesFromBiblionumber($biblionumber);
395 foreach my $res ( sort { $a->{found} cmp $b->{found} } @$reserves ) {
396     my %reserve;
397     my @optionloop;
398     for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
399         push(
400             @optionloop,
401             {
402                 num      => $i,
403                 selected => ( $i == $res->{priority} ),
404             }
405         );
406     }
407     my @branchloop;
408     foreach my $br ( keys %$branches ) {
409         my %abranch;
410         $abranch{'selected'}   = ( $br eq $res->{'branchcode'} );
411         $abranch{'branch'}     = $br;
412         $abranch{'branchname'} = $branches->{$br}->{'branchname'};
413         push( @branchloop, \%abranch );
414     }
415
416     if ( ( $res->{'found'} eq 'W' ) ) {
417         my $item = $res->{'itemnumber'};
418         $item = GetBiblioFromItemNumber($item,undef);
419         $reserve{'wait'}= 1; 
420         $reserve{'holdingbranch'}=$item->{'holdingbranch'};
421         $reserve{'biblionumber'}=$item->{'biblionumber'};
422         $reserve{'barcodenumber'}   = $item->{'barcode'};
423         $reserve{'wbrcode'} = $res->{'branchcode'};
424         $reserve{'itemnumber'}  = $res->{'itemnumber'};
425         $reserve{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
426         if($reserve{'holdingbranch'} eq $reserve{'wbrcode'}){
427             $reserve{'atdestination'} = 1;
428         }
429         # set found to 1 if reserve is waiting for patron pickup
430         $reserve{'found'} = 1 if $res->{'found'} eq 'W';
431     } elsif ($res->{priority} > 0) {
432         if (defined($res->{itemnumber})) {
433             my $item = GetItem($res->{itemnumber});
434             $reserve{'itemnumber'}  = $res->{'itemnumber'};
435             $reserve{'barcodenumber'}   = $item->{'barcode'};
436             $reserve{'item_level_hold'} = 1;
437         }
438     }
439     
440 #     get borrowers reserve info
441 my $reserveborrowerinfo = GetMemberDetails( $res->{'borrowernumber'}, 0);
442
443     $reserve{'date'}           = format_date( $res->{'reservedate'} );
444     $reserve{'borrowernumber'} = $res->{'borrowernumber'};
445     $reserve{'biblionumber'}   = $res->{'biblionumber'};
446     $reserve{'borrowernumber'} = $res->{'borrowernumber'};
447     $reserve{'firstname'}      = $reserveborrowerinfo->{'firstname'};
448     $reserve{'surname'}        = $reserveborrowerinfo->{'surname'};
449     $reserve{'notes'}          = $res->{'reservenotes'};
450     $reserve{'wait'}           =
451       ( ( $res->{'found'} eq 'W' ) or ( $res->{'priority'} eq '0' ) );
452     $reserve{'constrainttypea'} = ( $res->{'constrainttype'} eq 'a' );
453     $reserve{'constrainttypeo'} = ( $res->{'constrainttype'} eq 'o' );
454     $reserve{'voldesc'}         = $res->{'volumeddesc'};
455     $reserve{'ccode'}           = $res->{'ccode'};
456     $reserve{'barcode'}         = $res->{'barcode'};
457     $reserve{'priority'}    = $res->{'priority'};
458     $reserve{'branchloop'} = \@branchloop;
459     $reserve{'optionloop'} = \@optionloop;
460
461     push( @reserveloop, \%reserve );
462 }
463
464 my $default = C4::Context->userenv->{branch};
465 my @values;
466 my %label_of;
467
468 foreach my $branchcode (sort keys %{$branches} ) {
469     push @values, $branchcode;
470     $label_of{$branchcode} = $branches->{$branchcode}->{branchname};
471 }
472 my $CGIbranch = CGI::scrolling_list(
473     -name     => 'pickup',
474     -id          => 'pickup',
475     -values   => \@values,
476     -default  => $default,
477     -labels   => \%label_of,
478     -size     => 1,
479     -multiple => 0,
480 );
481
482 # get the time for the form name...
483 my $time = time();
484
485 $template->param(
486     CGIbranch   => $CGIbranch,
487     reserveloop => \@reserveloop,
488     time        => $time,
489     fixedRank   => $fixedRank,
490 );
491
492 # display infos
493 $template->param(
494     optionloop        => \@optionloop,
495     bibitemloop       => \@bibitemloop,
496     date              => $date,
497     biblionumber      => $biblionumber,
498     findborrower      => $findborrower,
499     cardnumber        => $cardnumber,
500     CGIselectborrower => $CGIselectborrower,
501     title             => $dat->{title},
502     author            => $dat->{author},
503         holdsview => 1,
504         borrower_branchname => $branches->{$borrowerinfo->{'branchcode'}}->{'branchname'},
505         borrower_branchcode => $borrowerinfo->{'branchcode'},
506 );
507
508 # printout the page
509 output_html_with_http_headers $input, $cookie, $template->output;