Bug 6739: (follow-up) fix more issues
[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 under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22
23 use CGI;
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 C4::Branch; # GetBranches
37 use Koha::DateUtils;
38
39 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
40
41 use Date::Calc qw(
42   Today
43   Add_Delta_Days
44   Date_to_Days
45 );
46
47 my $query = new CGI;
48
49 BEGIN {
50     if (C4::Context->preference('BakerTaylorEnabled')) {
51         require C4::External::BakerTaylor;
52         import C4::External::BakerTaylor qw(&image_url &link_url);
53     }
54 }
55
56 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
57     {
58         template_name   => "opac-user.tmpl",
59         query           => $query,
60         type            => "opac",
61         authnotrequired => 0,
62         flagsrequired   => { borrow => 1 },
63         debug           => 1,
64     }
65 );
66
67 my $OPACDisplayRequestPriority = (C4::Context->preference("OPACDisplayRequestPriority")) ? 1 : 0;
68 my $patronupdate = $query->param('patronupdate');
69 my $canrenew = 1;
70
71 # get borrower information ....
72 my ( $borr ) = GetMemberDetails( $borrowernumber );
73
74 my (  $today_year,   $today_month,   $today_day) = Today();
75 my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'};
76
77 $borr->{'ethnicity'} = fixEthnicity( $borr->{'ethnicity'} );
78
79 my $debar = $borr->{'debarred'};
80 my $userdebarred;
81
82 if ($debar) {
83     $userdebarred = 1;
84     $template->param( 'userdebarred' => $userdebarred );
85     if ( $debar ne "9999-12-31" ) {
86         $borr->{'userdebarreddate'} = $debar;
87     }
88 }
89
90 if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
91     $borr->{'flagged'} = 1;
92     $canrenew = 0;
93 }
94
95 if ( $borr->{'amountoutstanding'} > 5 ) {
96     $borr->{'amountoverfive'} = 1;
97 }
98 if ( 5 >= $borr->{'amountoutstanding'} && $borr->{'amountoutstanding'} > 0 ) {
99     $borr->{'amountoverzero'} = 1;
100 }
101 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
102 $no_renewal_amt ||= 0;
103
104 if (  C4::Context->preference( 'OpacRenewalAllowed' ) && $borr->{amountoutstanding} > $no_renewal_amt ) {
105     $borr->{'flagged'} = 1;
106     $canrenew = 0;
107     $template->param(
108         renewal_blocked_fines => sprintf( '%.02f', $no_renewal_amt ),
109     );
110 }
111
112 if ( $borr->{'amountoutstanding'} < 0 ) {
113     $borr->{'amountlessthanzero'} = 1;
114     $borr->{'amountoutstanding'} = -1 * ( $borr->{'amountoutstanding'} );
115 }
116
117 $borr->{'amountoutstanding'} = sprintf "%.02f", $borr->{'amountoutstanding'};
118
119 my @bordat;
120 $bordat[0] = $borr;
121
122 # Warningdate is the date that the warning starts appearing
123 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
124     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
125     if ( $days_to_expiry < 0 ) {
126         #borrower card has expired, warn the borrower
127         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
128     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
129         # borrower card soon to expire, warn the borrower
130         $borr->{'warndeparture'} = $borr->{dateexpiry};
131         if (C4::Context->preference('ReturnBeforeExpiry')){
132             $borr->{'returnbeforeexpiry'} = 1;
133         }
134     }
135 }
136
137 # pass on any renew errors to the template for displaying
138 my $renew_error = $query->param('renew_error');
139
140 $template->param(   BORROWER_INFO     => \@bordat,
141                     borrowernumber    => $borrowernumber,
142                     patron_flagged    => $borr->{flagged},
143                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
144                     surname           => $borr->{surname},
145                     showname          => $borr->{showname},
146                     RENEW_ERROR       => $renew_error,
147                     borrower          => $borr,
148                 );
149
150 #get issued items ....
151
152 my $count          = 0;
153 my $overdues_count = 0;
154 my @overdues;
155 my @issuedat;
156 my $itemtypes = GetItemTypes();
157 my $issues = GetPendingIssues($borrowernumber);
158 if ($issues){
159     foreach my $issue ( sort { $b->{date_due}->datetime() cmp $a->{date_due}->datetime() } @{$issues} ) {
160         # check for reserves
161         my ( $restype, $res, undef ) = CheckReserves( $issue->{'itemnumber'} );
162         if ( $restype ) {
163             $issue->{'reserved'} = 1;
164         }
165
166         my ( $total , $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
167         my $charges = 0;
168         foreach my $ac (@$accts) {
169             if ( $ac->{'itemnumber'} == $issue->{'itemnumber'} ) {
170                 $charges += $ac->{'amountoutstanding'}
171                   if $ac->{'accounttype'} eq 'F';
172                 $charges += $ac->{'amountoutstanding'}
173                   if $ac->{'accounttype'} eq 'L';
174             }
175         }
176         $issue->{'charges'} = $charges;
177         $issue->{'subtitle'} = GetRecordValue('subtitle', GetMarcBiblio($issue->{'biblionumber'}), GetFrameworkCode($issue->{'biblionumber'}));
178         # check if item is renewable
179         my ($status,$renewerror) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
180         ($issue->{'renewcount'},$issue->{'renewsallowed'},$issue->{'renewsleft'}) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
181         if($status && C4::Context->preference("OpacRenewalAllowed")){
182             $issue->{'status'} = $status;
183         }
184
185         if ($renewerror) {
186             $issue->{'too_many'}   = 1 if $renewerror eq 'too_many';
187             $issue->{'on_reserve'} = 1 if $renewerror eq 'on_reserve';
188
189             if ( $renewerror eq 'too_soon' ) {
190                 $issue->{'too_soon'}         = 1;
191                 $issue->{'soonestrenewdate'} = output_pref(
192                     C4::Circulation::GetSoonestRenewDate(
193                         $issue->{borrowernumber},
194                         $issue->{itemnumber}
195                     )
196                 );
197             }
198         }
199
200         if ( $issue->{'overdue'} ) {
201             push @overdues, $issue;
202             $overdues_count++;
203             $issue->{'overdue'} = 1;
204         }
205         else {
206             $issue->{'issued'} = 1;
207         }
208         # imageurl:
209         my $itemtype = $issue->{'itemtype'};
210         if ( $itemtype ) {
211             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
212             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
213         }
214         push @issuedat, $issue;
215         $count++;
216
217         my $isbn = GetNormalizedISBN($issue->{'isbn'});
218         $issue->{normalized_isbn} = $isbn;
219
220                 # My Summary HTML
221                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
222                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
223                     $issue->{title} =~ s/\/+$//; # remove trailing slash
224                     $issue->{title} =~ s/\s+$//; # remove trailing space
225                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
226                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
227                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
228                     $issue->{MySummaryHTML} = $my_summary_html;
229                 }
230     }
231 }
232 $template->param( ISSUES       => \@issuedat );
233 $template->param( issues_count => $count );
234 $template->param( canrenew     => $canrenew );
235 $template->param( OVERDUES       => \@overdues );
236 $template->param( overdues_count => $overdues_count );
237
238 my $show_barcode = C4::Members::AttributeTypes::AttributeTypeExists( ATTRIBUTE_SHOW_BARCODE );
239 if ($show_barcode) {
240     my $patron_show_barcode = GetBorrowerAttributeValue($borrowernumber, ATTRIBUTE_SHOW_BARCODE);
241     undef $show_barcode if defined($patron_show_barcode) && !$patron_show_barcode;
242 }
243 $template->param( show_barcode => 1 ) if $show_barcode;
244
245 # load the branches
246 my $branches = GetBranches();
247 my @branch_loop;
248 for my $branch_hash ( sort keys %{$branches} ) {
249     my $selected;
250     if ( C4::Context->preference('SearchMyLibraryFirst') ) {
251         $selected =
252           ( C4::Context->userenv
253               && ( $branch_hash eq C4::Context->userenv->{branch} ) );
254     }
255     push @branch_loop,
256       { value      => "branch: $branch_hash",
257         branchname => $branches->{$branch_hash}->{'branchname'},
258         selected   => $selected,
259       };
260 }
261 $template->param( branchloop => \@branch_loop );
262
263 # now the reserved items....
264 my @reserves  = GetReservesFromBorrowernumber( $borrowernumber );
265 foreach my $res (@reserves) {
266
267     if ( $res->{'expirationdate'} eq '0000-00-00' ) {
268       $res->{'expirationdate'} = '';
269     }
270     $res->{'subtitle'} = GetRecordValue('subtitle', GetMarcBiblio($res->{'biblionumber'}), GetFrameworkCode($res->{'biblionumber'}));
271     $res->{'waiting'} = 1 if $res->{'found'} eq 'W';
272     $res->{'branch'} = $branches->{ $res->{'branchcode'} }->{'branchname'};
273     my $biblioData = GetBiblioData($res->{'biblionumber'});
274     $res->{'reserves_title'} = $biblioData->{'title'};
275     if ($OPACDisplayRequestPriority) {
276         $res->{'priority'} = '' if $res->{'priority'} eq '0';
277     }
278     $res->{'suspend_until'} = C4::Dates->new( $res->{'suspend_until'}, "iso")->output("syspref") if ( $res->{'suspend_until'} );
279 }
280
281 # use Data::Dumper;
282 # warn Dumper(@reserves);
283
284 $template->param( RESERVES       => \@reserves );
285 $template->param( reserves_count => $#reserves+1 );
286 $template->param( showpriority=>1 ) if $OPACDisplayRequestPriority;
287
288 my @waiting;
289 my $wcount = 0;
290 foreach my $res (@reserves) {
291     if ( $res->{'itemnumber'} ) {
292         my $item = GetItem( $res->{'itemnumber'});
293         $res->{'holdingbranch'} =
294           $branches->{ $item->{'holdingbranch'} }->{'branchname'};
295         $res->{'branch'} = $branches->{ $res->{'branchcode'} }->{'branchname'};
296         # get document reserve status
297         my $biblioData = GetBiblioData($res->{'biblionumber'});
298         $res->{'waiting_title'} = $biblioData->{'title'};
299         if ( ( $res->{'found'} eq 'W' ) ) {
300             my $item = $res->{'itemnumber'};
301             $item = GetBiblioFromItemNumber($item,undef);
302             $res->{'wait'}= 1;
303             $res->{'holdingbranch'}=$item->{'holdingbranch'};
304             $res->{'biblionumber'}=$item->{'biblionumber'};
305             $res->{'barcode'} = $item->{'barcode'};
306             $res->{'wbrcode'} = $res->{'branchcode'};
307             $res->{'itemnumber'}    = $res->{'itemnumber'};
308             $res->{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
309             if($res->{'holdingbranch'} eq $res->{'wbrcode'}){
310                 $res->{'atdestination'} = 1;
311             }
312             # set found to 1 if reserve is waiting for patron pickup
313             $res->{'found'} = 1 if $res->{'found'} eq 'W';
314         } else {
315             my ($transfertwhen, $transfertfrom, $transfertto) = GetTransfers( $res->{'itemnumber'} );
316             if ($transfertwhen) {
317                 $res->{intransit} = 1;
318                 $res->{datesent}   = $transfertwhen;
319                 $res->{frombranch} = GetBranchName($transfertfrom);
320             }
321         }
322         push @waiting, $res;
323         $wcount++;
324     }
325     # can be cancelled
326     #$res->{'cancelable'} = 1 if ($res->{'wait'} && $res->{'atdestination'} && $res->{'found'} ne "1");
327     $res->{'cancelable'} = 1 if    ($res->{wait} and not $res->{found}) or (not $res->{wait} and not $res->{intransit});
328
329 }
330
331 $template->param( WAITING => \@waiting );
332
333 # current alert subscriptions
334 my $alerts = getalert($borrowernumber);
335 foreach ( @$alerts ) {
336     $_->{ $_->{type} } = 1;
337     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
338 }
339
340 if (C4::Context->preference('BakerTaylorEnabled')) {
341     $template->param(
342         BakerTaylorEnabled  => 1,
343         BakerTaylorImageURL => &image_url(),
344         BakerTaylorLinkURL  => &link_url(),
345         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
346     );
347 }
348
349 if (C4::Context->preference("OPACAmazonCoverImages") or 
350     C4::Context->preference("GoogleJackets") or
351     C4::Context->preference("BakerTaylorEnabled") or
352     C4::Context->preference("SyndeticsCoverImages")) {
353         $template->param(JacketImages=>1);
354 }
355
356 if ( GetMessagesCount( $borrowernumber, 'B' ) ) {
357     $template->param( bor_messages => 1 );
358 }
359
360 if ( $borr->{'opacnote'} ) {
361   $template->param( 
362     bor_messages => 1,
363     opacnote => $borr->{'opacnote'},
364   );
365 }
366
367 $template->param(
368     bor_messages_loop    => GetMessages( $borrowernumber, 'B', 'NONE' ),
369     waiting_count      => $wcount,
370     patronupdate => $patronupdate,
371     OpacRenewalAllowed => C4::Context->preference("OpacRenewalAllowed"),
372     userview => 1,
373     dateformat => C4::Context->preference("dateformat"),
374 );
375
376 $template->param(
377     SuspendHoldsOpac => C4::Context->preference('SuspendHoldsOpac'),
378     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
379     OpacHoldNotes => C4::Context->preference('OpacHoldNotes'),
380 );
381
382 output_html_with_http_headers $query, $cookie, $template->output;
383