Bug 9394: (follow-up) restore ability to cancel holds from the patron summary
[koha.git] / members / moremember.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21
22 =head1 moremember.pl
23
24  script to do a borrower enquiry/bring up borrower details etc
25  Displays all the details about a borrower
26  written 20/12/99 by chris@katipo.co.nz
27  last modified 21/1/2000 by chris@katipo.co.nz
28  modified 31/1/2001 by chris@katipo.co.nz
29    to not allow items on request to be renewed
30
31  needs html removed and to use the C4::Output more, but its tricky
32
33 =cut
34
35 use strict;
36 #use warnings; FIXME - Bug 2505
37 use CGI;
38 use C4::Context;
39 use C4::Auth;
40 use C4::Output;
41 use C4::Members;
42 use C4::Members::Attributes;
43 use C4::Members::AttributeTypes;
44 use C4::Dates;
45 use C4::Reserves;
46 use C4::Circulation;
47 use C4::Koha;
48 use C4::Letters;
49 use C4::Biblio;
50 use C4::Branch; # GetBranchName
51 use C4::Overdues qw/CheckBorrowerDebarred/;
52 use C4::Form::MessagingPreferences;
53 use List::MoreUtils qw/uniq/;
54 use C4::Members::Attributes qw(GetBorrowerAttributes);
55
56 #use Smart::Comments;
57 #use Data::Dumper;
58 use DateTime;
59 use Koha::DateUtils;
60
61 use vars qw($debug);
62
63 BEGIN {
64         $debug = $ENV{DEBUG} || 0;
65 }
66
67 my $dbh = C4::Context->dbh;
68
69 my $input = CGI->new;
70 $debug or $debug = $input->param('debug') || 0;
71 my $print = $input->param('print');
72 my $override_limit = $input->param("override_limit") || 0;
73 my @failedrenews = $input->param('failedrenew');
74 my @failedreturns = $input->param('failedreturn');
75 my $error = $input->param('error');
76 my %renew_failed;
77 for my $renew (@failedrenews) { $renew_failed{$renew} = 1; }
78 my %return_failed;
79 for my $failedret (@failedreturns) { $return_failed{$failedret} = 1; }
80
81 my $template_name;
82 my $quickslip = 0;
83
84 my $flagsrequired;
85 if ($print eq "page") {
86     $template_name = "members/moremember-print.tmpl";
87     # circ staff who process checkouts but can't edit
88     # patrons still need to be able to access print view
89     $flagsrequired = { circulate => "circulate_remaining_permissions" };
90 } elsif ($print eq "slip") {
91     $template_name = "members/moremember-receipt.tmpl";
92     # circ staff who process checkouts but can't edit
93     # patrons still need to be able to print receipts
94     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
95 } elsif ($print eq "qslip") {
96     $template_name = "members/moremember-receipt.tmpl";
97     $quickslip = 1;
98     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
99 } elsif ($print eq "brief") {
100     $template_name = "members/moremember-brief.tmpl";
101     $flagsrequired = { borrowers => 1 };
102 } else {
103     $template_name = "members/moremember.tmpl";
104     $flagsrequired = { borrowers => 1 };
105 }
106
107 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
108     {
109         template_name   => $template_name,
110         query           => $input,
111         type            => "intranet",
112         authnotrequired => 0,
113         flagsrequired   => $flagsrequired,
114         debug           => 1,
115     }
116 );
117 my $borrowernumber = $input->param('borrowernumber');
118
119 #start the page and read in includes
120 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
121
122 if ( not defined $data ) {
123     $template->param (unknowuser => 1);
124         output_html_with_http_headers $input, $cookie, $template->output;
125     exit;
126 }
127
128 my $category_type = $data->{'category_type'};
129
130 ### $category_type
131
132 $debug and printf STDERR "dates (enrolled,expiry,birthdate) raw: (%s, %s, %s)\n", map {$data->{$_}} qw(dateenrolled dateexpiry dateofbirth);
133 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
134                 my $userdate = $data->{$_};
135                 unless ($userdate) {
136                         $debug and warn sprintf "Empty \$data{%12s}", $_;
137                         $data->{$_} = '';
138                         next;
139                 }
140                 $userdate = C4::Dates->new($userdate,'iso')->output('syspref');
141                 $data->{$_} = $userdate || '';
142                 $template->param( $_ => $userdate );
143 }
144 $data->{'IS_ADULT'} = ( $data->{'categorycode'} ne 'I' );
145
146 for (qw(gonenoaddress lost borrowernotes)) {
147          $data->{$_} and $template->param(flagged => 1) and last;
148 }
149
150 my $debar = CheckBorrowerDebarred($borrowernumber);
151 if ($debar) {
152     $template->param( 'userdebarred' => 1, 'flagged' => 1 );
153     if ( $debar ne "9999-12-31" ) {
154         $template->param( 'userdebarreddate' => C4::Dates::format_date($debar) );
155         $template->param( 'debarredcomment'  => $data->{debarredcomment} );
156     }
157 }
158
159 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
160 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
161
162 my $catcode;
163 if ( $category_type eq 'C') {
164    my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
165    my $cnt = scalar(@$catcodes);
166
167    $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
168    $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
169 }
170
171
172 if ( $data->{'ethnicity'} || $data->{'ethnotes'} ) {
173     $template->param( printethnicityline => 1 );
174 }
175 if ( $category_type eq 'A' || $category_type eq 'I') {
176     $template->param( isguarantee => 1 );
177
178     # FIXME
179     # It looks like the $i is only being returned to handle walking through
180     # the array, which is probably better done as a foreach loop.
181     #
182     my ( $count, $guarantees ) = GetGuarantees( $data->{'borrowernumber'} );
183     my @guaranteedata;
184     for ( my $i = 0 ; $i < $count ; $i++ ) {
185         push(@guaranteedata,
186             {
187                 borrowernumber => $guarantees->[$i]->{'borrowernumber'},
188                 cardnumber     => $guarantees->[$i]->{'cardnumber'},
189                 name           => $guarantees->[$i]->{'firstname'} . " "
190                                 . $guarantees->[$i]->{'surname'}
191             }
192         );
193     }
194     $template->param( guaranteeloop => \@guaranteedata );
195     ( $template->param( adultborrower => 1 ) ) if ( $category_type eq 'A' || $category_type eq 'I' );
196 }
197 else {
198     if ($data->{'guarantorid'}){
199             my ($guarantor) = GetMember( 'borrowernumber' =>$data->{'guarantorid'});
200                 $template->param(guarantor => 1);
201                 foreach (qw(borrowernumber cardnumber firstname surname)) {        
202                           $template->param("guarantor$_" => $guarantor->{$_});
203         }
204     }
205         if ($category_type eq 'C'){
206                 $template->param('C' => 1);
207         }
208 }
209
210 my %bor;
211 $bor{'borrowernumber'} = $borrowernumber;
212
213 # Converts the branchcode to the branch name
214 my $samebranch;
215 if ( C4::Context->preference("IndependentBranches") ) {
216     my $userenv = C4::Context->userenv;
217     unless ( $userenv->{flags} % 2 == 1 ) {
218         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
219     }
220     $samebranch = 1 if ( $userenv->{flags} % 2 == 1 );
221 }else{
222     $samebranch = 1;
223 }
224 my $branchdetail = GetBranchDetail( $data->{'branchcode'});
225 @{$data}{keys %$branchdetail} = values %$branchdetail; # merge in all branch columns
226
227 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
228 my $lib1 = &GetSortDetails( "Bsort1", $data->{'sort1'} );
229 my $lib2 = &GetSortDetails( "Bsort2", $data->{'sort2'} );
230 $template->param( lib1 => $lib1 ) if ($lib1);
231 $template->param( lib2 => $lib2 ) if ($lib2);
232
233 # Show OPAC privacy preference is system preference is set
234 if ( C4::Context->preference('OPACPrivacy') ) {
235     $template->param( OPACPrivacy => 1);
236     $template->param( "privacy".$data->{'privacy'} => 1);
237 }
238
239 # current issues
240 #
241 my @borrowernumbers = GetMemberRelatives($borrowernumber);
242 my $issue       = GetPendingIssues($borrowernumber);
243 my $relissue    = [];
244 if ( @borrowernumbers ) {
245     $relissue    = GetPendingIssues(@borrowernumbers);
246 }
247 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
248 my $today       = DateTime->now( time_zone => C4::Context->tz);
249 $today->truncate(to => 'day');
250 my @borrowers_with_issues;
251 my $overdues_exist = 0;
252 my $totalprice = 0;
253
254 my @issuedata = build_issue_data($issue);
255 my @relissuedata = build_issue_data($relissue);
256
257
258 ### ###############################################################################
259 # BUILD HTML
260 # show all reserves of this borrower, and the position of the reservation ....
261 if ($borrowernumber) {
262
263     # new op dev
264     # now we show the status of the borrower's reservations
265     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
266     my @reservloop;
267     foreach my $num_res (@borrowerreserv) {
268         my %getreserv;
269         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
270         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
271         my ( $transfertwhen, $transfertfrom, $transfertto ) =
272             GetTransfers( $num_res->{'itemnumber'} );
273
274         foreach (qw(waiting transfered nottransfered)) {
275             $getreserv{$_} = 0;
276         }
277         $getreserv{reservedate}  = $num_res->{'reservedate'};
278         foreach (qw(biblionumber title author itemcallnumber )) {
279             $getreserv{$_} = $getiteminfo->{$_};
280         }
281         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
282         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
283
284         #               check if we have a waitin status for reservations
285         if ( $num_res->{'found'} eq 'W' ) {
286             $getreserv{color}   = 'reserved';
287             $getreserv{waiting} = 1;
288         }
289
290         #               check transfers with the itemnumber foud in th reservation loop
291         if ($transfertwhen) {
292             $getreserv{color}      = 'transfered';
293             $getreserv{transfered} = 1;
294             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
295             $getreserv{frombranch} = GetBranchName($transfertfrom);
296         }
297
298         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
299             and not $transfertwhen )
300         {
301             $getreserv{nottransfered}   = 1;
302             $getreserv{nottransferedby} =
303                 GetBranchName( $getiteminfo->{'holdingbranch'} );
304         }
305
306 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
307         if ( $getiteminfo->{'title'} eq '' ) {
308             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
309             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
310             $getreserv{color}           = 'inwait';
311             $getreserv{title}           = $getbibinfo->{'title'};
312             $getreserv{nottransfered}   = 0;
313             $getreserv{itemtype}        = $getbibtype->{'description'};
314             $getreserv{author}          = $getbibinfo->{'author'};
315             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
316         }
317         $getreserv{waitingposition} = $num_res->{'priority'};
318         $getreserv{suspend} = $num_res->{'suspend'};
319         $getreserv{suspend_until} = $num_res->{'suspend_until'};
320         $getreserv{expirationdate} = $num_res->{'expirationdate'};
321         $getreserv{reserve_id} = $num_res->{'reserve_id'};
322
323         push( @reservloop, \%getreserv );
324     }
325
326     # return result to the template
327     $template->param( reservloop => \@reservloop,
328         countreserv => scalar @reservloop,
329          );
330 }
331
332 # current alert subscriptions
333 my $alerts = getalert($borrowernumber);
334 foreach (@$alerts) {
335     $_->{ $_->{type} } = 1;
336     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
337 }
338
339 my $candeleteuser;
340 my $userenv = C4::Context->userenv;
341 if($userenv->{flags} % 2 == 1){
342     $candeleteuser = 1;
343 }elsif ( C4::Context->preference("IndependentBranches") ) {
344     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
345 }else{
346     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
347         $candeleteuser = 1;
348     }else{
349         $candeleteuser = 0;
350     }
351 }
352
353 # check to see if patron's image exists in the database
354 # basically this gives us a template var to condition the display of
355 # patronimage related interface on
356 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
357 $template->param( picture => 1 ) if $picture;
358
359 my $branch=C4::Context->userenv->{'branch'};
360
361 $template->param(%$data);
362
363 if (C4::Context->preference('ExtendedPatronAttributes')) {
364     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
365     my @classes = uniq( map {$_->{class}} @$attributes );
366     @classes = sort @classes;
367
368     my @attributes_loop;
369     for my $class (@classes) {
370         my @items;
371         for my $attr (@$attributes) {
372             push @items, $attr if $attr->{class} eq $class
373         }
374         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
375         push @attributes_loop, {
376             class => $class,
377             items => \@items,
378             lib   => $lib,
379         };
380     }
381
382     $template->param(
383         ExtendedPatronAttributes => 1,
384         attributes_loop => \@attributes_loop
385     );
386
387     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
388     if (scalar(@types) == 0) {
389         $template->param(no_patron_attribute_types => 1);
390     }
391 }
392
393 if (C4::Context->preference('EnhancedMessagingPreferences')) {
394     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
395     $template->param(messaging_form_inactive => 1);
396     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
397     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
398     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
399 }
400
401 # in template <TMPL_IF name="I"> => instutitional (A for Adult, C for children) 
402 $template->param( $data->{'categorycode'} => 1 ); 
403 $template->param(
404     detailview => 1,
405     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
406     CANDELETEUSER    => $candeleteuser,
407     roaddetails     => $roaddetails,
408     borrowernumber  => $borrowernumber,
409     othernames      => $data->{'othernames'},
410     categoryname    => $data->{'description'},
411     was_renewed     => $input->param('was_renewed') ? 1 : 0,
412     branch          => $branch,
413     todaysdate      => C4::Dates->today(),
414     totalprice      => sprintf("%.2f", $totalprice),
415     totaldue        => sprintf("%.2f", $total),
416     totaldue_raw    => $total,
417     issueloop       => @issuedata,
418     relissueloop    => @relissuedata,
419     overdues_exist  => $overdues_exist,
420     error           => $error,
421     StaffMember     => ($category_type eq 'S'),
422     is_child        => ($category_type eq 'C'),
423 #   reserveloop     => \@reservedata,
424     samebranch     => $samebranch,
425     quickslip             => $quickslip,
426     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
427     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
428     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
429     RoutingSerials => C4::Context->preference('RoutingSerials'),
430 );
431 $template->param( $error => 1 ) if $error;
432
433 output_html_with_http_headers $input, $cookie, $template->output;
434
435 sub build_issue_data {
436     my $issues = shift;
437
438     my $localissue;
439
440     foreach my $issue ( @{$issues} ) {
441
442         # Getting borrower details
443         my $memberdetails = GetMemberDetails( $issue->{borrowernumber} );
444         $issue->{borrowername} =
445           $memberdetails->{firstname} . ' ' . $memberdetails->{surname};
446         $issue->{cardnumber} = $memberdetails->{cardnumber};
447         my $issuedate;
448         if ($issue->{issuedate} ) {
449            $issuedate = $issue->{issuedate}->clone();
450         }
451
452         my $biblionumber = $issue->{biblionumber};
453         $issue->{issuingbranchname} = GetBranchName($issue->{branchcode});
454         my %row          = %{$issue};
455         $totalprice += $issue->{replacementprice};
456
457         # item lost, damaged loops
458         if ( $row{'itemlost'} ) {
459             my $fw       = GetFrameworkCode( $issue->{biblionumber} );
460             my $category = GetAuthValCode( 'items.itemlost', $fw );
461             my $lostdbh  = C4::Context->dbh;
462             my $sth      = $lostdbh->prepare(
463 "select lib from authorised_values where category=? and authorised_value =? "
464             );
465             $sth->execute( $category, $row{'itemlost'} );
466             my $loststat = $sth->fetchrow;
467             if ($loststat) {
468                 $row{'itemlost'} = $loststat;
469             }
470         }
471         if ( $row{'damaged'} ) {
472             my $fw         = GetFrameworkCode( $issue->{biblionumber} );
473             my $category   = GetAuthValCode( 'items.damaged', $fw );
474             my $damageddbh = C4::Context->dbh;
475             my $sth        = $damageddbh->prepare(
476 "select lib from authorised_values where category=? and authorised_value =? "
477             );
478             $sth->execute( $category, $row{'damaged'} );
479             my $damagedstat = $sth->fetchrow;
480             if ($damagedstat) {
481                 $row{'itemdamaged'} = $damagedstat;
482             }
483         }
484
485         # end lost, damaged
486         if ( $issue->{overdue} ) {
487             $overdues_exist = 1;
488             $row{red} = 1;
489         }
490         if ($issuedate) {
491             $issuedate->truncate( to => 'day' );
492             if ( DateTime->compare( $issuedate, $today ) == 0 ) {
493                 $row{today} = 1;
494             }
495         }
496
497         #find the charge for an item
498         my ( $charge, $itemtype ) =
499           GetIssuingCharges( $issue->{itemnumber}, $borrowernumber );
500
501         my $itemtypeinfo = getitemtypeinfo($itemtype);
502         $row{'itemtype_description'} = $itemtypeinfo->{description};
503         $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
504
505         $row{'charge'} = sprintf( "%.2f", $charge );
506
507         my ( $renewokay, $renewerror ) =
508           CanBookBeRenewed( $borrowernumber, $issue->{itemnumber},
509             $override_limit );
510         $row{'norenew'} = !$renewokay;
511         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
512         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
513         $row{renew_failed}  = $renew_failed{ $issue->{itemnumber} };
514         $row{return_failed} = $return_failed{ $issue->{barcode} };
515         push( @{$localissue}, \%row );
516     }
517     return $localissue;
518 }