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