(bug #3743) fix acquisition stats ordering
[koha.git] / members / moremember.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20
21 =head1 moremember.pl
22
23  script to do a borrower enquiry/bring up borrower details etc
24  Displays all the details about a borrower
25  written 20/12/99 by chris@katipo.co.nz
26  last modified 21/1/2000 by chris@katipo.co.nz
27  modified 31/1/2001 by chris@katipo.co.nz
28    to not allow items on request to be renewed
29
30  needs html removed and to use the C4::Output more, but its tricky
31
32 =cut
33
34 use strict;
35 #use warnings; FIXME - Bug 2505
36 use CGI;
37 use C4::Context;
38 use C4::Auth;
39 use C4::Output;
40 use C4::Members;
41 use C4::Members::Attributes;
42 use C4::Members::AttributeTypes;
43 use C4::Dates;
44 use C4::Reserves;
45 use C4::Circulation;
46 use C4::Koha;
47 use C4::Letters;
48 use C4::Biblio;
49 use C4::Reserves;
50 use C4::Branch; # GetBranchName
51 use C4::Form::MessagingPreferences;
52 use C4::NewsChannels; #get slip news
53
54 #use Smart::Comments;
55 #use Data::Dumper;
56
57 use vars qw($debug);
58
59 BEGIN {
60         $debug = $ENV{DEBUG} || 0;
61 }
62
63 my $dbh = C4::Context->dbh;
64
65 my $input = new CGI;
66 $debug or $debug = $input->param('debug') || 0;
67 my $print = $input->param('print');
68 my $override_limit = $input->param("override_limit") || 0;
69 my @failedrenews = $input->param('failedrenew');
70 my @failedreturns = $input->param('failedreturn');
71 my $error = $input->param('error');
72 my %renew_failed;
73 for my $renew (@failedrenews) { $renew_failed{$renew} = 1; }
74 my %return_failed;
75 for my $failedret (@failedreturns) { $return_failed{$failedret} = 1; }
76
77 my $template_name;
78 my $quickslip = 0;
79
80 my $flagsrequired;
81 if ($print eq "page") {
82     $template_name = "members/moremember-print.tmpl";
83     $flagsrequired = { borrowers => 1 };
84 } elsif ($print eq "slip") {
85     $template_name = "members/moremember-receipt.tmpl";
86     # circ staff who process checkouts but can't edit
87     # patrons still need to be able to print receipts
88     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
89 } elsif ($print eq "qslip") {
90     $template_name = "members/moremember-receipt.tmpl";
91     $quickslip = 1;
92     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
93 } elsif ($print eq "brief") {
94     $template_name = "members/moremember-brief.tmpl";
95     $flagsrequired = { borrowers => 1 };
96 } else {
97     $template_name = "members/moremember.tmpl";
98     $flagsrequired = { borrowers => 1 };
99 }
100
101 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
102     {
103         template_name   => $template_name,
104         query           => $input,
105         type            => "intranet",
106         authnotrequired => 0,
107         flagsrequired   => $flagsrequired,
108         debug           => 1,
109     }
110 );
111 my $borrowernumber = $input->param('borrowernumber');
112
113 #start the page and read in includes
114 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
115 my $reregistration = $input->param('reregistration');
116
117 if ( not defined $data ) {
118     $template->param (unknowuser => 1);
119         output_html_with_http_headers $input, $cookie, $template->output;
120     exit;
121 }
122
123 # re-reregistration function to automatic calcul of date expiry
124 if ( $reregistration eq 'y' ) {
125         $data->{'dateexpiry'} = ExtendMemberSubscriptionTo( $borrowernumber );
126 }
127
128 my $category_type = $data->{'category_type'};
129
130 ### $category_type
131
132 # in template <TMPL_IF name="I"> => instutitional (A for Adult& C for children) 
133 $template->param( $data->{'categorycode'} => 1 ); 
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         if ($data->{'guarantorid'} ne '0' ) {
159         my $data2 = GetMember( 'borrowernumber' => $data->{'guarantorid'} );
160         foreach (qw(address city B_address B_city phone mobile zipcode country B_country)) {
161             $data->{$_} = $data2->{$_};
162         }
163    }
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("IndependantBranches") ) {
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 # current issues
234 #
235 my $issue = GetPendingIssues($borrowernumber);
236 my $issuecount = scalar(@$issue);
237 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
238 my $today       = POSIX::strftime("%Y-%m-%d", localtime);       # iso format
239 my @issuedata;
240 my $overdues_exist = 0;
241 my $totalprice = 0;
242 for ( my $i = 0 ; $i < $issuecount ; $i++ ) {
243     my $datedue = $issue->[$i]{'date_due'};
244     my $issuedate = $issue->[$i]{'issuedate'};
245     $issue->[$i]{'date_due'}  = C4::Dates->new($issue->[$i]{'date_due'}, 'iso')->output('syspref');
246     $issue->[$i]{'issuedate'} = C4::Dates->new($issue->[$i]{'issuedate'},'iso')->output('syspref');
247     my $biblionumber = $issue->[$i]{'biblionumber'};
248     my %row = %{ $issue->[$i] };
249     $totalprice += $issue->[$i]{'replacementprice'};
250     $row{'replacementprice'} = $issue->[$i]{'replacementprice'};
251     # item lost, damaged loops
252     if ($row{'itemlost'}) {
253         my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
254         my $category = GetAuthValCode('items.itemlost',$fw);
255         my $lostdbh = C4::Context->dbh;
256         my $sth = $lostdbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
257         $sth->execute($category, $row{'itemlost'});
258         my $loststat = $sth->fetchrow;
259         if ($loststat) {
260            $row{'itemlost'} = $loststat;
261         }
262     }
263     if ($row{'damaged'}) {
264         my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
265         my $category = GetAuthValCode('items.damaged',$fw);
266         my $damageddbh = C4::Context->dbh;
267         my $sth = $damageddbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
268         $sth->execute($category, $row{'damaged'});
269         my $damagedstat = $sth->fetchrow;
270         if ($damagedstat) {
271            $row{'itemdamaged'} = $damagedstat;
272         }
273     }
274     # end lost, damaged
275     if ( $datedue lt $today ) {
276         $overdues_exist = 1;
277         $row{'red'} = 1;
278         }
279          if ( $issuedate eq $today ) {
280         $row{'today'} = 1; 
281          }
282
283     #find the charge for an item
284     my ( $charge, $itemtype ) =
285       GetIssuingCharges( $issue->[$i]{'itemnumber'}, $borrowernumber );
286
287     my $itemtypeinfo = getitemtypeinfo($itemtype);
288     $row{'itemtype_description'} = $itemtypeinfo->{description};
289     $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
290
291     $row{'charge'} = sprintf( "%.2f", $charge );
292
293         my ( $renewokay,$renewerror ) = CanBookBeRenewed( $borrowernumber, $issue->[$i]{'itemnumber'}, $override_limit );
294         $row{'norenew'} = !$renewokay;
295         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
296         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
297         $row{'renew_failed'}  = $renew_failed{ $issue->[$i]{'itemnumber'} };
298         $row{'return_failed'} = $return_failed{$issue->[$i]{'barcode'}};   
299     push( @issuedata, \%row );
300 }
301
302 ### ###############################################################################
303 # BUILD HTML
304 # show all reserves of this borrower, and the position of the reservation ....
305 if ($borrowernumber) {
306
307     # new op dev
308     # now we show the status of the borrower's reservations
309     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
310     my @reservloop;
311     foreach my $num_res (@borrowerreserv) {
312         my %getreserv;
313         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
314         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
315         my ( $transfertwhen, $transfertfrom, $transfertto ) =
316             GetTransfers( $num_res->{'itemnumber'} );
317
318         foreach (qw(waiting transfered nottransfered)) {
319             $getreserv{$_} = 0;
320         }
321         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
322         foreach (qw(biblionumber title author itemcallnumber )) {
323             $getreserv{$_} = $getiteminfo->{$_};
324         }
325         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
326         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
327
328         #               check if we have a waitin status for reservations
329         if ( $num_res->{'found'} eq 'W' ) {
330             $getreserv{color}   = 'reserved';
331             $getreserv{waiting} = 1;
332         }
333
334         #               check transfers with the itemnumber foud in th reservation loop
335         if ($transfertwhen) {
336             $getreserv{color}      = 'transfered';
337             $getreserv{transfered} = 1;
338             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
339             $getreserv{frombranch} = GetBranchName($transfertfrom);
340         }
341
342         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
343             and not $transfertwhen )
344         {
345             $getreserv{nottransfered}   = 1;
346             $getreserv{nottransferedby} =
347                 GetBranchName( $getiteminfo->{'holdingbranch'} );
348         }
349
350 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
351         if ( $getiteminfo->{'title'} eq '' ) {
352             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
353             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
354             $getreserv{color}           = 'inwait';
355             $getreserv{title}           = $getbibinfo->{'title'};
356             $getreserv{nottransfered}   = 0;
357             $getreserv{itemtype}        = $getbibtype->{'description'};
358             $getreserv{author}          = $getbibinfo->{'author'};
359             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
360         }
361         $getreserv{waitingposition} = $num_res->{'priority'};
362
363         push( @reservloop, \%getreserv );
364     }
365
366     # return result to the template
367     $template->param( reservloop => \@reservloop,
368         countreserv => scalar @reservloop,
369          );
370 }
371
372 # current alert subscriptions
373 my $alerts = getalert($borrowernumber);
374 foreach (@$alerts) {
375     $_->{ $_->{type} } = 1;
376     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
377 }
378
379 my $candeleteuser;
380 my $userenv = C4::Context->userenv;
381 if($userenv->{flags} % 2 == 1){
382     $candeleteuser = 1;
383 }elsif ( C4::Context->preference("IndependantBranches") ) {
384     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
385 }else{
386     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
387         $candeleteuser = 1;
388     }else{
389         $candeleteuser = 0;
390     }
391 }
392
393 # check to see if patron's image exists in the database
394 # basically this gives us a template var to condition the display of
395 # patronimage related interface on
396 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
397 $template->param( picture => 1 ) if $picture;
398
399 my $branch=C4::Context->userenv->{'branch'};
400
401 $template->param($data);
402
403 if (C4::Context->preference('ExtendedPatronAttributes')) {
404     $template->param(ExtendedPatronAttributes => 1);
405     $template->param(patron_attributes => C4::Members::Attributes::GetBorrowerAttributes($borrowernumber));
406     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
407     if (scalar(@types) == 0) {
408         $template->param(no_patron_attribute_types => 1);
409     }
410 }
411
412 if (C4::Context->preference('EnhancedMessagingPreferences')) {
413     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
414     $template->param(messaging_form_inactive => 1);
415     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
416     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
417 }
418
419 $template->param(
420     detailview => 1,
421     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
422     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
423     CANDELETEUSER    => $candeleteuser,
424     roaddetails     => $roaddetails,
425     borrowernumber  => $borrowernumber,
426     categoryname    => $data->{'description'},
427     reregistration  => $reregistration,
428     branch          => $branch,
429     todaysdate      => C4::Dates->today(),
430     totalprice      => sprintf("%.2f", $totalprice),
431     totaldue        => sprintf("%.2f", $total),
432     totaldue_raw    => $total,
433     issueloop       => \@issuedata,
434         issuecount => $issuecount,
435     overdues_exist  => $overdues_exist,
436     error           => $error,
437     $error          => 1,
438     StaffMember     => ($category_type eq 'S'),
439     is_child        => ($category_type eq 'C'),
440 #   reserveloop     => \@reservedata,
441     dateformat      => C4::Context->preference("dateformat"),
442     "dateformat_" . (C4::Context->preference("dateformat") || '') => 1,
443     samebranch     => $samebranch,
444     quickslip             => $quickslip,
445 );
446
447 #Get the slip news items
448 my $all_koha_news   = &GetNewsToDisplay("slip");
449 my $koha_news_count = scalar @$all_koha_news;
450
451 $template->param(
452     koha_news       => $all_koha_news,
453     koha_news_count => $koha_news_count
454 );
455
456 output_html_with_http_headers $input, $cookie, $template->output;