Bug 29083: Update article requests-related Koha::Patron methods to use relationships
[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 Modern::Perl;
21
22 use CGI qw ( -utf8 );
23
24 use C4::Auth qw( get_template_and_user );
25 use C4::Koha qw(
26     getitemtypeimagelocation
27     GetNormalizedISBN
28     GetNormalizedUPC
29 );
30 use C4::Circulation qw( CanBookBeRenewed GetRenewCount GetIssuingCharges GetSoonestRenewDate );
31 use C4::External::BakerTaylor qw( image_url link_url );
32 use C4::Reserves qw( GetReserveStatus );
33 use C4::Members;
34 use C4::Output qw( output_html_with_http_headers );
35 use C4::Biblio qw( GetMarcBiblio );
36 use Koha::Account::Lines;
37 use Koha::Biblios;
38 use Koha::Libraries;
39 use Koha::DateUtils qw( output_pref );
40 use Koha::Holds;
41 use Koha::Database;
42 use Koha::ItemTypes;
43 use Koha::Patron::Attribute::Types;
44 use Koha::Patrons;
45 use Koha::Patron::Messages;
46 use Koha::Patron::Discharge;
47 use Koha::Patrons;
48 use Koha::Ratings;
49 use Koha::Token;
50
51 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
52
53 use Scalar::Util qw( looks_like_number );
54 use Date::Calc qw( Date_to_Days Today );
55
56 my $query = CGI->new;
57
58 # CAS single logout handling
59 # Will print header and exit
60 C4::Context->preference('casAuthentication') and C4::Auth_with_cas::logout_if_required($query);
61
62 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
63     {
64         template_name   => "opac-user.tt",
65         query           => $query,
66         type            => "opac",
67     }
68 );
69
70 my %renewed = map { $_ => 1 } split( ':', $query->param('renewed') || '' );
71
72 my $show_priority;
73 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
74     m/priority/ and $show_priority = 1;
75 }
76
77 my $patronupdate = $query->param('patronupdate');
78 my $canrenew = 1;
79
80 $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') );
81
82 # get borrower information ....
83 my $patron = Koha::Patrons->find( $borrowernumber );
84
85 if( $query->param('update_arc') && C4::Context->preference("AllowPatronToControlAutorenewal") ){
86     die "Wrong CSRF token"
87         unless Koha::Token->new->check_csrf({
88             session_id => scalar $query->cookie('CGISESSID'),
89             token  => scalar $query->param('csrf_token'),
90         });
91
92     my $autorenew_checkouts = $query->param('borrower_autorenew_checkouts');
93     $patron->autorenew_checkouts( $autorenew_checkouts )->store() if defined $autorenew_checkouts;
94 }
95
96 my $borr = $patron->unblessed;
97 # unblessed is a hash vs. object/undef. Hence the use of curly braces here.
98 my $borcat = $borr ? $borr->{categorycode} : q{};
99
100 my (  $today_year,   $today_month,   $today_day) = Today();
101 my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'};
102
103 my $debar = Koha::Patrons->find( $borrowernumber )->is_debarred;
104 my $userdebarred;
105
106 if ($debar) {
107     $userdebarred = 1;
108     $template->param( 'userdebarred' => $userdebarred );
109     if ( $debar ne "9999-12-31" ) {
110         $borr->{'userdebarreddate'} = $debar;
111     }
112     # FIXME looks like $available is not needed
113     # If a user is discharged they have a validated discharge available
114     my $available = Koha::Patron::Discharge::count({
115         borrowernumber => $borrowernumber,
116         validated      => 1,
117     });
118     $template->param( 'discharge_available' => $available && Koha::Patron::Discharge::is_discharged({borrowernumber => $borrowernumber}) );
119 }
120
121 if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
122     $borr->{'flagged'} = 1;
123     $canrenew = 0;
124 }
125
126 my $amountoutstanding = $patron->account->balance;
127 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
128 $no_renewal_amt = undef unless looks_like_number( $no_renewal_amt );
129 my $amountoutstandingfornewal =
130   C4::Context->preference("OPACFineNoRenewalsIncludeCredit")
131   ? $amountoutstanding
132   : $patron->account->outstanding_debits->total_outstanding;
133
134 if (   C4::Context->preference('OpacRenewalAllowed')
135     && defined($no_renewal_amt)
136     && $amountoutstandingfornewal > $no_renewal_amt )
137 {
138     $borr->{'flagged'} = 1;
139     $canrenew = 0;
140     $template->param(
141         renewal_blocked_fines => $no_renewal_amt,
142         renewal_blocked_fines_amountoutstanding => $amountoutstandingfornewal,
143     );
144 }
145
146 my $maxoutstanding = C4::Context->preference('maxoutstanding');
147 if ( $amountoutstanding && ( $amountoutstanding > $maxoutstanding ) ){
148     $borr->{blockedonfines} = 1;
149 }
150
151 # Warningdate is the date that the warning starts appearing
152 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
153     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
154     if ( $days_to_expiry < 0 ) {
155         #borrower card has expired, warn the borrower
156         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
157     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
158         # borrower card soon to expire, warn the borrower
159         $borr->{'warndeparture'} = $borr->{dateexpiry};
160         if (C4::Context->preference('ReturnBeforeExpiry')){
161             $borr->{'returnbeforeexpiry'} = 1;
162         }
163     }
164 }
165
166 # pass on any renew errors to the template for displaying
167 my $renew_error = $query->param('renew_error');
168
169 $template->param(
170                     amountoutstanding => $amountoutstanding,
171                     borrowernumber    => $borrowernumber,
172                     patron_flagged    => $borr->{flagged},
173                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
174                     surname           => $borr->{surname},
175                     RENEW_ERROR       => $renew_error,
176                     borrower          => $borr,
177                     csrf_token             => Koha::Token->new->generate_csrf({
178                         session_id => scalar $query->cookie('CGISESSID'),
179                     }),
180                 );
181
182 #get issued items ....
183
184 my $count          = 0;
185 my $overdues_count = 0;
186 my @overdues;
187 my @issuedat;
188 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
189 my $pending_checkouts = $patron->pending_checkouts->search({}, { order_by => [ { -desc => 'date_due' }, { -asc => 'issue_id' } ] });
190 my $are_renewable_items = 0;
191 if ( $pending_checkouts->count ) { # Useless test
192     while ( my $c = $pending_checkouts->next ) {
193         my $issue = $c->unblessed_all_relateds;
194         # check for reserves
195         my $restype = GetReserveStatus( $issue->{'itemnumber'} );
196         if ( $restype ) {
197             $issue->{'reserved'} = 1;
198         }
199
200         # Must be moved in a module if reused
201         my $charges = Koha::Account::Lines->search(
202             {
203                 borrowernumber    => $patron->borrowernumber,
204                 amountoutstanding => { '>' => 0 },
205                 debit_type_code   => [ 'OVERDUE', 'LOST' ],
206                 itemnumber        => $issue->{itemnumber}
207             },
208         );
209         $issue->{charges} = $charges->total_outstanding;
210
211         my $rental_fines = Koha::Account::Lines->search(
212             {
213                 borrowernumber    => $patron->borrowernumber,
214                 amountoutstanding => { '>' => 0 },
215                 debit_type_code   => { 'LIKE' => 'RENT_%' },
216                 itemnumber        => $issue->{itemnumber}
217             }
218         );
219         $issue->{rentalfines} = $rental_fines->total_outstanding;
220
221         # check if item is renewable
222         my ($status,$renewerror) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
223         (
224             $issue->{'renewcount'},
225             $issue->{'renewsallowed'},
226             $issue->{'renewsleft'},
227             $issue->{'unseencount'},
228             $issue->{'unseenallowed'},
229             $issue->{'unseenleft'}
230         ) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
231         ( $issue->{'renewalfee'}, $issue->{'renewalitemtype'} ) = GetIssuingCharges( $issue->{'itemnumber'}, $borrowernumber );
232         $issue->{itemtype_object} = Koha::ItemTypes->find( Koha::Items->find( $issue->{itemnumber} )->effective_itemtype );
233         if($status && C4::Context->preference("OpacRenewalAllowed")){
234             $are_renewable_items = 1;
235             $issue->{'status'} = $status;
236         }
237
238         $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} };
239
240         if ($renewerror) {
241             $issue->{'too_many'}       = 1 if $renewerror eq 'too_many';
242             $issue->{'too_unseen'}     = 1 if $renewerror eq 'too_unseen';
243             $issue->{'on_reserve'}     = 1 if $renewerror eq 'on_reserve';
244             $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue';
245             $issue->{'auto_renew'}     = 1 if $renewerror eq 'auto_renew';
246             $issue->{'auto_too_soon'}  = 1 if $renewerror eq 'auto_too_soon';
247             $issue->{'auto_too_late'}  = 1 if $renewerror eq 'auto_too_late';
248             $issue->{'auto_too_much_oweing'}  = 1 if $renewerror eq 'auto_too_much_oweing';
249             $issue->{'item_denied_renewal'}  = 1 if $renewerror eq 'item_denied_renewal';
250
251             if ( $renewerror eq 'too_soon' ) {
252                 $issue->{'too_soon'}         = 1;
253                 $issue->{'soonestrenewdate'} = output_pref(
254                     C4::Circulation::GetSoonestRenewDate(
255                         $issue->{borrowernumber},
256                         $issue->{itemnumber}
257                     )
258                 );
259             }
260         }
261
262         if ( $c->is_overdue ) {
263             push @overdues, $issue;
264             $overdues_count++;
265             $issue->{'overdue'} = 1;
266         }
267         else {
268             $issue->{'issued'} = 1;
269         }
270         # imageurl:
271         my $itemtype = $issue->{'itemtype'};
272         if ( $itemtype ) {
273             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
274             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
275         }
276
277         if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
278             my $ratings = Koha::Ratings->search({ biblionumber => $issue->{biblionumber} });
279             $issue->{ratings} = $ratings;
280             $issue->{my_rating} = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef;
281         }
282
283         $issue->{biblio_object} = Koha::Biblios->find($issue->{biblionumber});
284         push @issuedat, $issue;
285         $count++;
286
287         my $isbn = GetNormalizedISBN($issue->{'isbn'});
288         $issue->{normalized_isbn} = $isbn;
289         my $marcrecord = GetMarcBiblio({
290             biblionumber => $issue->{'biblionumber'},
291             embed_items  => 1,
292             opac         => 1,
293             borcat       => $borcat });
294         $issue->{normalized_upc} = GetNormalizedUPC( $marcrecord, C4::Context->preference('marcflavour') );
295
296                 # My Summary HTML
297                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
298                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
299                     $issue->{title} =~ s/\/+$//; # remove trailing slash
300                     $issue->{title} =~ s/\s+$//; # remove trailing space
301                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
302                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
303                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
304                     $issue->{MySummaryHTML} = $my_summary_html;
305                 }
306     }
307 }
308 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
309 $canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count) || !$are_renewable_items;
310
311 $template->param( ISSUES       => \@issuedat );
312 $template->param( issues_count => $count );
313 $template->param( canrenew     => $canrenew );
314 $template->param( OVERDUES       => \@overdues );
315 $template->param( overdues_count => $overdues_count );
316
317 my $show_barcode = Koha::Patron::Attribute::Types->search( # FIXME we should not need this search
318     { code => ATTRIBUTE_SHOW_BARCODE } )->count;
319 if ($show_barcode) {
320     my $patron_show_barcode = $patron->get_extended_attribute(ATTRIBUTE_SHOW_BARCODE);
321     undef $show_barcode if $patron_show_barcode and not $patron_show_barcode->attribute;
322 }
323 $template->param( show_barcode => 1 ) if $show_barcode;
324
325 # now the reserved items....
326 my $reserves = Koha::Holds->search( { borrowernumber => $borrowernumber } );
327
328 $template->param(
329     RESERVES       => $reserves,
330     showpriority   => $show_priority,
331 );
332
333 if (C4::Context->preference('BakerTaylorEnabled')) {
334     $template->param(
335         BakerTaylorEnabled  => 1,
336         BakerTaylorImageURL => &image_url(),
337         BakerTaylorLinkURL  => &link_url(),
338         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
339     );
340 }
341
342 if (C4::Context->preference("OPACAmazonCoverImages") or 
343     C4::Context->preference("GoogleJackets") or
344     C4::Context->preference("BakerTaylorEnabled") or
345     C4::Context->preference("SyndeticsCoverImages") or
346     ( C4::Context->preference('OPACCustomCoverImages') and C4::Context->preference('CustomCoverImagesURL') )
347 ) {
348         $template->param(JacketImages=>1);
349 }
350
351 $template->param(
352     OverDriveCirculation => C4::Context->preference('OverDriveCirculation') || 0,
353     overdrive_error      => scalar $query->param('overdrive_error') || undef,
354     overdrive_tab        => scalar $query->param('overdrive_tab') || 0,
355     RecordedBooksCirculation => C4::Context->preference('RecordedBooksClientSecret') && C4::Context->preference('RecordedBooksLibraryID'),
356 );
357
358 my $patron_messages = Koha::Patron::Messages->search(
359     {
360         borrowernumber => $borrowernumber,
361         message_type => 'B',
362     }
363 );
364
365 if (   C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor')
366     || C4::Context->preference('AllowStaffToSetCheckoutsVisibilityForGuarantor') )
367 {
368     my @relatives;
369     # Filter out guarantees that don't want guarantor to see checkouts
370     foreach my $gr ( $patron->guarantee_relationships() ) {
371         my $g = $gr->guarantee;
372         push( @relatives, $g ) if $g->privacy_guarantor_checkouts;
373     }
374     $template->param( relatives => \@relatives );
375 }
376
377 if (   C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor')
378     || C4::Context->preference('AllowStaffToSetFinesVisibilityForGuarantor') )
379 {
380     my @relatives_with_fines;
381     # Filter out guarantees that don't want guarantor to see checkouts
382     foreach my $gr ( $patron->guarantee_relationships() ) {
383         my $g = $gr->guarantee;
384         push( @relatives_with_fines, $g ) if $g->privacy_guarantor_fines;
385     }
386     $template->param( relatives_with_fines => \@relatives_with_fines );
387 }
388
389 if ( C4::Context->preference("ArticleRequests") ) {
390     my @current_article_requests = $patron->article_requests->filter_by_current->as_list;
391     $template->param(
392         current_article_requests => \@current_article_requests,
393         current_article_requests_count => scalar @current_article_requests,
394     );
395 }
396
397 $template->param(
398     patron_messages          => $patron_messages,
399     opacnote                 => $borr->{opacnote},
400     patronupdate             => $patronupdate,
401     OpacRenewalAllowed       => C4::Context->preference("OpacRenewalAllowed"),
402     userview                 => 1,
403     SuspendHoldsOpac         => C4::Context->preference('SuspendHoldsOpac'),
404     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
405     OpacHoldNotes            => C4::Context->preference('OpacHoldNotes'),
406     failed_holds             => scalar $query->param('failed_holds'),
407 );
408
409 # if not an empty string this indicates to return
410 # back to the opac-results page
411 my $search_query = $query->param('has-search-query');
412
413 if ($search_query) {
414
415     print $query->redirect(
416         -uri    => "/cgi-bin/koha/opac-search.pl?$search_query",
417         -cookie => $cookie,
418     );
419 }
420
421 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };