Fix for Bug 5971, Minor markup error in holds queue report
[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::Reserves;
51 use C4::Branch; # GetBranchName
52 use C4::Form::MessagingPreferences;
53 use C4::NewsChannels; #get slip news
54
55 #use Smart::Comments;
56 #use Data::Dumper;
57
58 use vars qw($debug);
59
60 BEGIN {
61         $debug = $ENV{DEBUG} || 0;
62 }
63
64 my $dbh = C4::Context->dbh;
65
66 my $input = new CGI;
67 $debug or $debug = $input->param('debug') || 0;
68 my $print = $input->param('print');
69 my $override_limit = $input->param("override_limit") || 0;
70 my @failedrenews = $input->param('failedrenew');
71 my @failedreturns = $input->param('failedreturn');
72 my $error = $input->param('error');
73 my %renew_failed;
74 for my $renew (@failedrenews) { $renew_failed{$renew} = 1; }
75 my %return_failed;
76 for my $failedret (@failedreturns) { $return_failed{$failedret} = 1; }
77
78 my $template_name;
79 my $quickslip = 0;
80
81 my $flagsrequired;
82 if ($print eq "page") {
83     $template_name = "members/moremember-print.tmpl";
84     $flagsrequired = { borrowers => 1 };
85 } elsif ($print eq "slip") {
86     $template_name = "members/moremember-receipt.tmpl";
87     # circ staff who process checkouts but can't edit
88     # patrons still need to be able to print receipts
89     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
90 } elsif ($print eq "qslip") {
91     $template_name = "members/moremember-receipt.tmpl";
92     $quickslip = 1;
93     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
94 } elsif ($print eq "brief") {
95     $template_name = "members/moremember-brief.tmpl";
96     $flagsrequired = { borrowers => 1 };
97 } else {
98     $template_name = "members/moremember.tmpl";
99     $flagsrequired = { borrowers => 1 };
100 }
101
102 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
103     {
104         template_name   => $template_name,
105         query           => $input,
106         type            => "intranet",
107         authnotrequired => 0,
108         flagsrequired   => $flagsrequired,
109         debug           => 1,
110     }
111 );
112 my $borrowernumber = $input->param('borrowernumber');
113
114 #start the page and read in includes
115 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
116 my $reregistration = $input->param('reregistration');
117
118 if ( not defined $data ) {
119     $template->param (unknowuser => 1);
120         output_html_with_http_headers $input, $cookie, $template->output;
121     exit;
122 }
123
124 # re-reregistration function to automatic calcul of date expiry
125 if ( $reregistration eq 'y' ) {
126         $data->{'dateexpiry'} = ExtendMemberSubscriptionTo( $borrowernumber );
127 }
128
129 my $category_type = $data->{'category_type'};
130
131 ### $category_type
132
133 # in template <TMPL_IF name="I"> => instutitional (A for Adult& C for children) 
134 $template->param( $data->{'categorycode'} => 1 ); 
135
136 $debug and printf STDERR "dates (enrolled,expiry,birthdate) raw: (%s, %s, %s)\n", map {$data->{$_}} qw(dateenrolled dateexpiry dateofbirth);
137 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
138                 my $userdate = $data->{$_};
139                 unless ($userdate) {
140                         $debug and warn sprintf "Empty \$data{%12s}", $_;
141                         $data->{$_} = '';
142                         next;
143                 }
144                 $userdate = C4::Dates->new($userdate,'iso')->output('syspref');
145                 $data->{$_} = $userdate || '';
146                 $template->param( $_ => $userdate );
147 }
148 $data->{'IS_ADULT'} = ( $data->{'categorycode'} ne 'I' );
149
150 for (qw(debarred gonenoaddress lost borrowernotes)) {
151          $data->{$_} and $template->param(flagged => 1) and last;
152 }
153
154 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
155 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
156
157 my $catcode;
158 if ( $category_type eq 'C') {
159         if ($data->{guarantorid} ) {
160         my $data2 = GetMember( 'borrowernumber' => $data->{'guarantorid'} );
161         foreach (qw(address city B_address B_city phone mobile zipcode country B_country)) {
162             $data->{$_} = $data2->{$_};
163         }
164    }
165    my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
166    my $cnt = scalar(@$catcodes);
167
168    $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
169    $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
170 }
171
172
173 if ( $data->{'ethnicity'} || $data->{'ethnotes'} ) {
174     $template->param( printethnicityline => 1 );
175 }
176 if ( $category_type eq 'A' || $category_type eq 'I') {
177     $template->param( isguarantee => 1 );
178
179     # FIXME
180     # It looks like the $i is only being returned to handle walking through
181     # the array, which is probably better done as a foreach loop.
182     #
183     my ( $count, $guarantees ) = GetGuarantees( $data->{'borrowernumber'} );
184     my @guaranteedata;
185     for ( my $i = 0 ; $i < $count ; $i++ ) {
186         push(@guaranteedata,
187             {
188                 borrowernumber => $guarantees->[$i]->{'borrowernumber'},
189                 cardnumber     => $guarantees->[$i]->{'cardnumber'},
190                 name           => $guarantees->[$i]->{'firstname'} . " "
191                                 . $guarantees->[$i]->{'surname'}
192             }
193         );
194     }
195     $template->param( guaranteeloop => \@guaranteedata );
196     ( $template->param( adultborrower => 1 ) ) if ( $category_type eq 'A' || $category_type eq 'I' );
197 }
198 else {
199     if ($data->{'guarantorid'}){
200             my ($guarantor) = GetMember( 'borrowernumber' =>$data->{'guarantorid'});
201                 $template->param(guarantor => 1);
202                 foreach (qw(borrowernumber cardnumber firstname surname)) {        
203                           $template->param("guarantor$_" => $guarantor->{$_});
204         }
205     }
206         if ($category_type eq 'C'){
207                 $template->param('C' => 1);
208         }
209 }
210
211 my %bor;
212 $bor{'borrowernumber'} = $borrowernumber;
213
214 # Converts the branchcode to the branch name
215 my $samebranch;
216 if ( C4::Context->preference("IndependantBranches") ) {
217     my $userenv = C4::Context->userenv;
218     unless ( $userenv->{flags} % 2 == 1 ) {
219         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
220     }
221     $samebranch = 1 if ( $userenv->{flags} % 2 == 1 );
222 }else{
223     $samebranch = 1;
224 }
225 my $branchdetail = GetBranchDetail( $data->{'branchcode'});
226 @{$data}{keys %$branchdetail} = values %$branchdetail; # merge in all branch columns
227
228 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
229 my $lib1 = &GetSortDetails( "Bsort1", $data->{'sort1'} );
230 my $lib2 = &GetSortDetails( "Bsort2", $data->{'sort2'} );
231 $template->param( lib1 => $lib1 ) if ($lib1);
232 $template->param( lib2 => $lib2 ) if ($lib2);
233
234 # Show OPAC privacy preference is system preference is set
235 if ( C4::Context->preference('OPACPrivacy') ) {
236     $template->param( OPACPrivacy => 1);
237     $template->param( "privacy".$data->{'privacy'} => 1);
238 }
239
240 # current issues
241 #
242 my $issue = GetPendingIssues($borrowernumber);
243 my $issuecount = scalar(@$issue);
244 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
245 my $today       = POSIX::strftime("%Y-%m-%d", localtime);       # iso format
246 my @issuedata;
247 my $overdues_exist = 0;
248 my $totalprice = 0;
249 for ( my $i = 0 ; $i < $issuecount ; $i++ ) {
250     my $datedue = $issue->[$i]{'date_due'};
251     my $issuedate = $issue->[$i]{'issuedate'};
252     $issue->[$i]{'date_due'}  = C4::Dates->new($issue->[$i]{'date_due'}, 'iso')->output('syspref');
253     $issue->[$i]{'issuedate'} = C4::Dates->new($issue->[$i]{'issuedate'},'iso')->output('syspref');
254     my $biblionumber = $issue->[$i]{'biblionumber'};
255     my %row = %{ $issue->[$i] };
256     $totalprice += $issue->[$i]{'replacementprice'};
257     $row{'replacementprice'} = $issue->[$i]{'replacementprice'};
258     # item lost, damaged loops
259     if ($row{'itemlost'}) {
260         my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
261         my $category = GetAuthValCode('items.itemlost',$fw);
262         my $lostdbh = C4::Context->dbh;
263         my $sth = $lostdbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
264         $sth->execute($category, $row{'itemlost'});
265         my $loststat = $sth->fetchrow;
266         if ($loststat) {
267            $row{'itemlost'} = $loststat;
268         }
269     }
270     if ($row{'damaged'}) {
271         my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
272         my $category = GetAuthValCode('items.damaged',$fw);
273         my $damageddbh = C4::Context->dbh;
274         my $sth = $damageddbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
275         $sth->execute($category, $row{'damaged'});
276         my $damagedstat = $sth->fetchrow;
277         if ($damagedstat) {
278            $row{'itemdamaged'} = $damagedstat;
279         }
280     }
281     # end lost, damaged
282     if ( $datedue lt $today ) {
283         $overdues_exist = 1;
284         $row{'red'} = 1;
285         }
286          if ( $issuedate eq $today ) {
287         $row{'today'} = 1; 
288          }
289
290     #find the charge for an item
291     my ( $charge, $itemtype ) =
292       GetIssuingCharges( $issue->[$i]{'itemnumber'}, $borrowernumber );
293
294     my $itemtypeinfo = getitemtypeinfo($itemtype);
295     $row{'itemtype_description'} = $itemtypeinfo->{description};
296     $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
297
298     $row{'charge'} = sprintf( "%.2f", $charge );
299
300         my ( $renewokay,$renewerror ) = CanBookBeRenewed( $borrowernumber, $issue->[$i]{'itemnumber'}, $override_limit );
301         $row{'norenew'} = !$renewokay;
302         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
303         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
304         $row{'renew_failed'}  = $renew_failed{ $issue->[$i]{'itemnumber'} };
305         $row{'return_failed'} = $return_failed{$issue->[$i]{'barcode'}};   
306     push( @issuedata, \%row );
307 }
308
309 ### ###############################################################################
310 # BUILD HTML
311 # show all reserves of this borrower, and the position of the reservation ....
312 if ($borrowernumber) {
313
314     # new op dev
315     # now we show the status of the borrower's reservations
316     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
317     my @reservloop;
318     foreach my $num_res (@borrowerreserv) {
319         my %getreserv;
320         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
321         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
322         my ( $transfertwhen, $transfertfrom, $transfertto ) =
323             GetTransfers( $num_res->{'itemnumber'} );
324
325         foreach (qw(waiting transfered nottransfered)) {
326             $getreserv{$_} = 0;
327         }
328         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
329         foreach (qw(biblionumber title author itemcallnumber )) {
330             $getreserv{$_} = $getiteminfo->{$_};
331         }
332         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
333         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
334
335         #               check if we have a waitin status for reservations
336         if ( $num_res->{'found'} eq 'W' ) {
337             $getreserv{color}   = 'reserved';
338             $getreserv{waiting} = 1;
339         }
340
341         #               check transfers with the itemnumber foud in th reservation loop
342         if ($transfertwhen) {
343             $getreserv{color}      = 'transfered';
344             $getreserv{transfered} = 1;
345             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
346             $getreserv{frombranch} = GetBranchName($transfertfrom);
347         }
348
349         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
350             and not $transfertwhen )
351         {
352             $getreserv{nottransfered}   = 1;
353             $getreserv{nottransferedby} =
354                 GetBranchName( $getiteminfo->{'holdingbranch'} );
355         }
356
357 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
358         if ( $getiteminfo->{'title'} eq '' ) {
359             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
360             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
361             $getreserv{color}           = 'inwait';
362             $getreserv{title}           = $getbibinfo->{'title'};
363             $getreserv{nottransfered}   = 0;
364             $getreserv{itemtype}        = $getbibtype->{'description'};
365             $getreserv{author}          = $getbibinfo->{'author'};
366             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
367         }
368         $getreserv{waitingposition} = $num_res->{'priority'};
369
370         push( @reservloop, \%getreserv );
371     }
372
373     # return result to the template
374     $template->param( reservloop => \@reservloop,
375         countreserv => scalar @reservloop,
376          );
377 }
378
379 # current alert subscriptions
380 my $alerts = getalert($borrowernumber);
381 foreach (@$alerts) {
382     $_->{ $_->{type} } = 1;
383     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
384 }
385
386 my $candeleteuser;
387 my $userenv = C4::Context->userenv;
388 if($userenv->{flags} % 2 == 1){
389     $candeleteuser = 1;
390 }elsif ( C4::Context->preference("IndependantBranches") ) {
391     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
392 }else{
393     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
394         $candeleteuser = 1;
395     }else{
396         $candeleteuser = 0;
397     }
398 }
399
400 # check to see if patron's image exists in the database
401 # basically this gives us a template var to condition the display of
402 # patronimage related interface on
403 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
404 $template->param( picture => 1 ) if $picture;
405
406 my $branch=C4::Context->userenv->{'branch'};
407
408 $template->param($data);
409
410 if (C4::Context->preference('ExtendedPatronAttributes')) {
411     $template->param(ExtendedPatronAttributes => 1);
412     $template->param(patron_attributes => C4::Members::Attributes::GetBorrowerAttributes($borrowernumber));
413     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
414     if (scalar(@types) == 0) {
415         $template->param(no_patron_attribute_types => 1);
416     }
417 }
418
419 if (C4::Context->preference('EnhancedMessagingPreferences')) {
420     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
421     $template->param(messaging_form_inactive => 1);
422     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
423     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
424 }
425
426 $template->param(
427     detailview => 1,
428     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
429     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
430     CANDELETEUSER    => $candeleteuser,
431     roaddetails     => $roaddetails,
432     borrowernumber  => $borrowernumber,
433     categoryname    => $data->{'description'},
434     reregistration  => $reregistration,
435     branch          => $branch,
436     todaysdate      => C4::Dates->today(),
437     totalprice      => sprintf("%.2f", $totalprice),
438     totaldue        => sprintf("%.2f", $total),
439     totaldue_raw    => $total,
440     issueloop       => \@issuedata,
441         issuecount => $issuecount,
442     overdues_exist  => $overdues_exist,
443     error           => $error,
444     $error          => 1,
445     StaffMember     => ($category_type eq 'S'),
446     is_child        => ($category_type eq 'C'),
447 #   reserveloop     => \@reservedata,
448     dateformat      => C4::Context->preference("dateformat"),
449     "dateformat_" . (C4::Context->preference("dateformat") || '') => 1,
450     samebranch     => $samebranch,
451     quickslip             => $quickslip,
452 );
453
454 #Get the slip news items
455 my $all_koha_news   = &GetNewsToDisplay("slip");
456 my $koha_news_count = scalar @$all_koha_news;
457
458 $template->param(
459     koha_news       => $all_koha_news,
460     koha_news_count => $koha_news_count
461 );
462
463 output_html_with_http_headers $input, $cookie, $template->output;