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