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