Bug 15738: Show rental fees on OPAC summary page
[koha.git] / opac / opac-user.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 # parts copyright 2010 BibLibre
5 #
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22
23 use CGI qw ( -utf8 );
24
25 use C4::Auth;
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Reserves;
29 use C4::Members;
30 use C4::Members::AttributeTypes;
31 use C4::Members::Attributes qw/GetBorrowerAttributeValue/;
32 use C4::Output;
33 use C4::Biblio;
34 use C4::Items;
35 use C4::Letters;
36 use Koha::DateUtils;
37 use Koha::Holds;
38 use Koha::Database;
39 use Koha::ItemTypes;
40 use Koha::Patron::Attribute::Types;
41 use Koha::Patron::Messages;
42 use Koha::Patron::Discharge;
43 use Koha::Patrons;
44
45 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
46
47 use Scalar::Util qw(looks_like_number);
48 use Date::Calc qw(
49   Today
50   Add_Delta_Days
51   Date_to_Days
52 );
53
54 my $query = new CGI;
55
56 BEGIN {
57     if (C4::Context->preference('BakerTaylorEnabled')) {
58         require C4::External::BakerTaylor;
59         import C4::External::BakerTaylor qw(&image_url &link_url);
60     }
61 }
62
63 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
64     {
65         template_name   => "opac-user.tt",
66         query           => $query,
67         type            => "opac",
68         authnotrequired => 0,
69         debug           => 1,
70     }
71 );
72
73 my %renewed = map { $_ => 1 } split( ':', $query->param('renewed') );
74
75 my $show_priority;
76 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
77     m/priority/ and $show_priority = 1;
78 }
79
80 my $patronupdate = $query->param('patronupdate');
81 my $canrenew = 1;
82
83 $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') );
84
85 if (!$borrowernumber) {
86     $template->param( adminWarning => 1 );
87 }
88
89 # get borrower information ....
90 my ( $borr ) = GetMember( borrowernumber => $borrowernumber );
91
92 my (  $today_year,   $today_month,   $today_day) = Today();
93 my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'};
94
95 my $debar = Koha::Patrons->find( $borrowernumber )->is_debarred;
96 my $userdebarred;
97
98 if ($debar) {
99     $userdebarred = 1;
100     $template->param( 'userdebarred' => $userdebarred );
101     if ( $debar ne "9999-12-31" ) {
102         $borr->{'userdebarreddate'} = $debar;
103     }
104     # FIXME looks like $available is not needed
105     # If a user is discharged they have a validated discharge available
106     my $available = Koha::Patron::Discharge::count({
107         borrowernumber => $borrowernumber,
108         validated      => 1,
109     });
110     $template->param( 'discharge_available' => $available && Koha::Patron::Discharge::is_discharged({borrowernumber => $borrowernumber}) );
111 }
112
113 if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
114     $borr->{'flagged'} = 1;
115     $canrenew = 0;
116 }
117
118 my ( $amountoutstanding ) = GetMemberAccountRecords($borrowernumber);
119 if ( $amountoutstanding > 5 ) {
120     $borr->{'amountoverfive'} = 1;
121 }
122 if ( 5 >= $amountoutstanding && $amountoutstanding > 0 ) {
123     $borr->{'amountoverzero'} = 1;
124 }
125 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
126 $no_renewal_amt = undef unless looks_like_number( $no_renewal_amt );
127
128 if (   C4::Context->preference('OpacRenewalAllowed')
129     && defined($no_renewal_amt)
130     && $amountoutstanding > $no_renewal_amt )
131 {
132     $borr->{'flagged'} = 1;
133     $canrenew = 0;
134     $template->param(
135         renewal_blocked_fines => $no_renewal_amt,
136         renewal_blocked_fines_amountoutstanding => $amountoutstanding,
137     );
138 }
139
140 if ( $amountoutstanding < 0 ) {
141     $borr->{'amountlessthanzero'} = 1;
142     $amountoutstanding = -1 * ( $amountoutstanding );
143 }
144
145 # Warningdate is the date that the warning starts appearing
146 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
147     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
148     if ( $days_to_expiry < 0 ) {
149         #borrower card has expired, warn the borrower
150         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
151     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
152         # borrower card soon to expire, warn the borrower
153         $borr->{'warndeparture'} = $borr->{dateexpiry};
154         if (C4::Context->preference('ReturnBeforeExpiry')){
155             $borr->{'returnbeforeexpiry'} = 1;
156         }
157     }
158 }
159
160 # pass on any renew errors to the template for displaying
161 my $renew_error = $query->param('renew_error');
162
163 $template->param(   BORROWER_INFO     => $borr,
164                     amountoutstanding => $amountoutstanding,
165                     borrowernumber    => $borrowernumber,
166                     patron_flagged    => $borr->{flagged},
167                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
168                     surname           => $borr->{surname},
169                     RENEW_ERROR       => $renew_error,
170                     borrower          => $borr,
171                 );
172
173 #get issued items ....
174
175 my $count          = 0;
176 my $overdues_count = 0;
177 my @overdues;
178 my @issuedat;
179 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
180 my $issues = GetPendingIssues($borrowernumber);
181 if ($issues){
182     foreach my $issue ( sort { $b->{date_due}->datetime() cmp $a->{date_due}->datetime() } @{$issues} ) {
183         # check for reserves
184         my $restype = GetReserveStatus( $issue->{'itemnumber'} );
185         if ( $restype ) {
186             $issue->{'reserved'} = 1;
187         }
188
189         my ( $total , $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
190         my $charges = 0;
191         my $rentalfines = 0;
192         foreach my $ac (@$accts) {
193             if ( $ac->{'itemnumber'} == $issue->{'itemnumber'} ) {
194                 $charges += $ac->{'amountoutstanding'}
195                   if $ac->{'accounttype'} eq 'F';
196                 $charges += $ac->{'amountoutstanding'}
197                   if $ac->{'accounttype'} eq 'FU';
198                 $charges += $ac->{'amountoutstanding'}
199                   if $ac->{'accounttype'} eq 'L';
200                 $rentalfines += $ac->{'amountoutstanding'}
201                   if $ac->{'accounttype'} eq 'Rent';
202             }
203         }
204         $issue->{'charges'} = $charges;
205         $issue->{'rentalfines'} = $rentalfines;
206         my $marcrecord = GetMarcBiblio( $issue->{'biblionumber'} );
207         $issue->{'subtitle'} = GetRecordValue('subtitle', $marcrecord, GetFrameworkCode($issue->{'biblionumber'}));
208         # check if item is renewable
209         my ($status,$renewerror) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
210         ($issue->{'renewcount'},$issue->{'renewsallowed'},$issue->{'renewsleft'}) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
211         if($status && C4::Context->preference("OpacRenewalAllowed")){
212             $issue->{'status'} = $status;
213         }
214
215         $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} };
216
217         if ($renewerror) {
218             $issue->{'too_many'}       = 1 if $renewerror eq 'too_many';
219             $issue->{'on_reserve'}     = 1 if $renewerror eq 'on_reserve';
220             $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue';
221             $issue->{'auto_renew'}     = 1 if $renewerror eq 'auto_renew';
222             $issue->{'auto_too_soon'}  = 1 if $renewerror eq 'auto_too_soon';
223             $issue->{'auto_too_late'}  = 1 if $renewerror eq 'auto_too_late';
224
225             if ( $renewerror eq 'too_soon' ) {
226                 $issue->{'too_soon'}         = 1;
227                 $issue->{'soonestrenewdate'} = output_pref(
228                     C4::Circulation::GetSoonestRenewDate(
229                         $issue->{borrowernumber},
230                         $issue->{itemnumber}
231                     )
232                 );
233             }
234         }
235
236         if ( $issue->{'overdue'} ) {
237             push @overdues, $issue;
238             $overdues_count++;
239             $issue->{'overdue'} = 1;
240         }
241         else {
242             $issue->{'issued'} = 1;
243         }
244         # imageurl:
245         my $itemtype = $issue->{'itemtype'};
246         if ( $itemtype ) {
247             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
248             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
249         }
250         push @issuedat, $issue;
251         $count++;
252
253         my $isbn = GetNormalizedISBN($issue->{'isbn'});
254         $issue->{normalized_isbn} = $isbn;
255         $issue->{normalized_upc} = GetNormalizedUPC( $marcrecord, C4::Context->preference('marcflavour') );
256
257                 # My Summary HTML
258                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
259                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
260                     $issue->{title} =~ s/\/+$//; # remove trailing slash
261                     $issue->{title} =~ s/\s+$//; # remove trailing space
262                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
263                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
264                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
265                     $issue->{MySummaryHTML} = $my_summary_html;
266                 }
267     }
268 }
269 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
270 $canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count);
271 $template->param( ISSUES       => \@issuedat );
272 $template->param( issues_count => $count );
273 $template->param( canrenew     => $canrenew );
274 $template->param( OVERDUES       => \@overdues );
275 $template->param( overdues_count => $overdues_count );
276
277 my $show_barcode = Koha::Patron::Attribute::Types->search(
278     { code => ATTRIBUTE_SHOW_BARCODE } )->count;
279 if ($show_barcode) {
280     my $patron_show_barcode = GetBorrowerAttributeValue($borrowernumber, ATTRIBUTE_SHOW_BARCODE);
281     undef $show_barcode if defined($patron_show_barcode) && !$patron_show_barcode;
282 }
283 $template->param( show_barcode => 1 ) if $show_barcode;
284
285 # now the reserved items....
286 my $reserves = Koha::Holds->search( { borrowernumber => $borrowernumber } );
287
288 $template->param(
289     RESERVES       => $reserves,
290     showpriority   => $show_priority,
291 );
292
293 # current alert subscriptions
294 my $alerts = getalert($borrowernumber);
295 foreach ( @$alerts ) {
296     $_->{ $_->{type} } = 1;
297     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
298 }
299
300 if (C4::Context->preference('BakerTaylorEnabled')) {
301     $template->param(
302         BakerTaylorEnabled  => 1,
303         BakerTaylorImageURL => &image_url(),
304         BakerTaylorLinkURL  => &link_url(),
305         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
306     );
307 }
308
309 if (C4::Context->preference("OPACAmazonCoverImages") or 
310     C4::Context->preference("GoogleJackets") or
311     C4::Context->preference("BakerTaylorEnabled") or
312     C4::Context->preference("SyndeticsCoverImages")) {
313         $template->param(JacketImages=>1);
314 }
315
316 $template->param(
317     OverDriveCirculation => C4::Context->preference('OverDriveCirculation') || 0,
318     overdrive_error      => $query->param('overdrive_error') || undef,
319     overdrive_tab        => $query->param('overdrive_tab') || 0,
320 );
321
322 my $patron_messages = Koha::Patron::Messages->search(
323     {
324         borrowernumber => $borrowernumber,
325         message_type => 'B',
326     }
327 );
328
329 if (   C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor')
330     || C4::Context->preference('AllowStaffToSetCheckoutsVisibilityForGuarantor') )
331 {
332     my @relatives =
333       Koha::Database->new()->schema()->resultset("Borrower")->search(
334         {
335             privacy_guarantor_checkouts => 1,
336             'me.guarantorid'           => $borrowernumber
337         },
338         { prefetch => [ { 'issues' => { 'item' => 'biblio' } } ] }
339       );
340     $template->param( relatives => \@relatives );
341 }
342
343 $template->param(
344     borrower                 => scalar Koha::Patrons->find($borrowernumber),
345     patron_messages          => $patron_messages,
346     opacnote                 => $borr->{opacnote},
347     patronupdate             => $patronupdate,
348     OpacRenewalAllowed       => C4::Context->preference("OpacRenewalAllowed"),
349     userview                 => 1,
350     SuspendHoldsOpac         => C4::Context->preference('SuspendHoldsOpac'),
351     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
352     OpacHoldNotes            => C4::Context->preference('OpacHoldNotes'),
353     failed_holds             => scalar $query->param('failed_holds'),
354 );
355
356 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };