Bug 29543: Remove borrower variable
[koha.git] / opac / sco / sco-main.pl
1 #!/usr/bin/perl
2 #
3 # This code has been modified by Trendsetters (originally from opac-user.pl)
4 # This code has been modified by rch
5 # Parts Copyright 2010-2011, ByWater Solutions (those related to username/password auth)
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 # We're going to authenticate a self-check user.  we'll add a flag to borrowers 'selfcheck'
23 #
24 # We're in a controlled environment; we trust the user.
25 # So the selfcheck station will accept a patronid and issue items to that borrower.
26 # FIXME: NOT really a controlled environment...  We're on the internet!
27 #
28 # The checkout permission comes form the CGI cookie/session of a staff user.
29 # The patron is not really logging in here in the same way as they do on the
30 # rest of the OPAC.  So don't confuse loggedinuser with the patron user.
31 #
32 # FIXME: inputfocus not really used in TMPL
33
34 use Modern::Perl;
35
36 use CGI qw ( -utf8 );
37
38 use C4::Auth qw( in_iprange get_template_and_user checkpw );
39 use C4::Circulation qw( barcodedecode AddReturn CanBookBeIssued AddIssue CanBookBeRenewed AddRenewal );
40 use C4::Reserves;
41 use C4::Output qw( output_html_with_http_headers );
42 use C4::Members;
43 use Koha::DateUtils qw( dt_from_string );
44 use Koha::Acquisition::Currencies;
45 use Koha::Items;
46 use Koha::Patrons;
47 use Koha::Patron::Images;
48 use Koha::Patron::Messages;
49 use Koha::Plugins;
50 use Koha::Token;
51
52 my $query = CGI->new;
53
54 unless (C4::Context->preference('WebBasedSelfCheck')) {
55     # redirect to OPAC home if self-check is not enabled
56     print $query->redirect("/cgi-bin/koha/opac-main.pl");
57     exit;
58 }
59
60 unless ( in_iprange(C4::Context->preference('SelfCheckAllowByIPRanges')) ) {
61     # redirect to OPAC home if self-checkout not permitted from current IP
62     print $query->redirect("/cgi-bin/koha/opac-main.pl");
63     exit;
64 }
65
66 if (C4::Context->preference('AutoSelfCheckAllowed'))
67 {
68     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
69     my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
70     $query->param(-name=>'userid',-values=>[$AutoSelfCheckID]);
71     $query->param(-name=>'password',-values=>[$AutoSelfCheckPass]);
72     $query->param(-name=>'koha_login_context',-values=>['sco']);
73 }
74 $query->param(-name=>'sco_user_login',-values=>[1]);
75
76 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
77     {
78         template_name   => "sco/sco-main.tt",
79         flagsrequired   => { self_check => "self_checkout_module" },
80         query           => $query,
81         type            => "opac",
82     }
83 );
84
85 # Get the self checkout timeout preference, or use 120 seconds as a default
86 my $selfchecktimeout = 120000;
87 if (C4::Context->preference('SelfCheckTimeout')) { 
88     $selfchecktimeout = C4::Context->preference('SelfCheckTimeout') * 1000;
89 }
90 $template->param( SelfCheckTimeout => $selfchecktimeout );
91
92 # Checks policy laid out by SCOAllowCheckin, defaults to 'on' if preference is undefined
93 my $allowselfcheckreturns = 1;
94 if (defined C4::Context->preference('SCOAllowCheckin')) {
95     $allowselfcheckreturns = C4::Context->preference('SCOAllowCheckin');
96 }
97
98 my $issuerid = $loggedinuser;
99 my ($op, $patronid, $patronlogin, $patronpw, $barcode, $confirmed, $newissues) = (
100     $query->param("op")         || '',
101     $query->param("patronid")   || '',
102     $query->param("patronlogin")|| '',
103     $query->param("patronpw")   || '',
104     $query->param("barcode")    || '',
105     $query->param("confirmed")  || '',
106     $query->param("newissues")  || '',
107 );
108
109 $barcode = barcodedecode( $barcode ) if $barcode;
110
111 my @newissueslist = split /,/, $newissues;
112 my $issuenoconfirm = 1; #don't need to confirm on issue.
113 my $issuer   = Koha::Patrons->find( $issuerid )->unblessed;
114 my $item     = Koha::Items->find({ barcode => $barcode });
115 if (C4::Context->preference('SelfCheckoutByLogin') && !$patronid) {
116     my $dbh = C4::Context->dbh;
117     my $resval;
118     ($resval, $patronid) = checkpw($dbh, $patronlogin, $patronpw);
119 }
120
121 my $patron;
122 if ( $patronid ) {
123     Koha::Plugins->call( 'patron_barcode_transform', \$patronid );
124     $patron = Koha::Patrons->find( { cardnumber => $patronid } );
125 }
126
127 my $branch = $issuer->{branchcode};
128 my $confirm_required = 0;
129 my $return_only = 0;
130 if ($op eq "logout") {
131     $template->param( loggedout => 1 );
132     $query->param( patronid => undef, patronlogin => undef, patronpw => undef );
133 }
134 elsif ( $op eq "returnbook" && $allowselfcheckreturns ) {
135     my $success        = 0;
136     my $human_required = 0;
137     if ( C4::Context->preference("CircConfirmItemParts") ) {
138         my $item = Koha::Items->find( { barcode => $barcode } );
139         if ( defined($item)
140             && $item->materials )
141         {
142             $human_required = 1;
143         }
144     }
145
146     ($success) = AddReturn( $barcode, $branch )
147       unless $human_required;
148     $template->param( returned => $success );
149 }
150 elsif ( $patron && ( $op eq 'checkout' ) ) {
151     my $impossible  = {};
152     my $needconfirm = {};
153     ( $impossible, $needconfirm ) = CanBookBeIssued(
154         $patron,
155         $barcode,
156         undef,
157         0,
158         C4::Context->preference("AllowItemsOnHoldCheckoutSCO")
159     );
160     my $issue_error;
161     if ( $confirm_required = scalar keys %$needconfirm ) {
162         for my $error ( qw( UNKNOWN_BARCODE max_loans_allowed ISSUED_TO_ANOTHER NO_MORE_RENEWALS NOT_FOR_LOAN DEBT WTHDRAWN RESTRICTED RESERVED ITEMNOTSAMEBRANCH EXPIRED DEBARRED CARD_LOST GNA INVALID_DATE UNKNOWN_BARCODE TOO_MANY DEBT_GUARANTEES DEBT_GUARANTORS USERBLOCKEDOVERDUE PATRON_CANT PREVISSUE NOT_FOR_LOAN_FORCING ITEM_LOST ADDITIONAL_MATERIALS ) ) {
163             if ( $needconfirm->{$error} ) {
164                 $issue_error = $error;
165                 $confirmed = 0;
166                 last;
167             }
168         }
169     }
170
171     #warn "confirm_required: " . $confirm_required ;
172     if (scalar keys %$impossible) {
173
174         my $issue_error = (keys %$impossible)[0]; # FIXME This is wrong, we assume only one error and keys are not ordered
175         my $title = ( $item ) ? $item->biblio->title : '';
176
177         $template->param(
178             impossible                => $issue_error,
179             "circ_error_$issue_error" => 1,
180             title                     => $title,
181             hide_main                 => 1,
182         );
183         if ($issue_error eq 'DEBT') {
184             $template->param(DEBT => $impossible->{DEBT});
185         }
186         #warn "issue_error: " . $issue_error ;
187         if ( $issue_error eq "NO_MORE_RENEWALS" ) {
188             $return_only = 1;
189             $template->param(
190                 returnitem => 1,
191                 barcode    => $barcode,
192             );
193         }
194     } elsif ( $needconfirm->{RENEW_ISSUE} ){
195         $template->param(
196                 renew               => 1,
197                 barcode             => $barcode,
198                 confirm             => 1,
199                 confirm_renew_issue => 1,
200                 hide_main           => 1,
201         );
202     } elsif ( $confirm_required && !$confirmed ) {
203         #warn "failed confirmation";
204         $template->param(
205             impossible                => 1,
206             "circ_error_$issue_error" => 1,
207             hide_main                 => 1,
208         );
209         if ($issue_error eq 'DEBT') {
210             $template->param(DEBT => $needconfirm->{DEBT});
211         }
212     } else {
213         if ( $confirmed || $issuenoconfirm ) {    # we'll want to call getpatroninfo again to get updated issues.
214             my ( $hold_existed, $item );
215             if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
216                 # There is no easy way to know if the patron has been charged for this item.
217                 # So we check if a hold existed for this item before the check in
218                 $item = Koha::Items->find({ barcode => $barcode });
219                 $hold_existed = Koha::Holds->search(
220                     {
221                         -and => {
222                             borrowernumber => $patron->borrowernumber,
223                             -or            => {
224                                 biblionumber => $item->biblionumber,
225                                 itemnumber   => $item->itemnumber
226                             }
227                         }
228                     }
229                 )->count;
230             }
231
232             AddIssue( $patron->unblessed, $barcode );
233             $template->param( issued => 1 );
234             push @newissueslist, $barcode;
235
236             if ( $hold_existed ) {
237                 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
238                 $template->param(
239                     # If the hold existed before the check in, let's confirm that the charge line exists
240                     # Note that this should not be needed but since we do not have proper exception handling here we do it this way
241                     patron_has_hold_fee => Koha::Account::Lines->search(
242                         {
243                             borrowernumber  => $patron->borrowernumber,
244                             debit_type_code => 'RESERVE',
245                             description     => $item->biblio->title,
246                             date            => $dtf->format_date(dt_from_string)
247                         }
248                       )->count,
249                 );
250             }
251         } else {
252             $confirm_required = 1;
253             #warn "issue confirmation";
254             $template->param(
255                 confirm    => "Issuing title: " . $item->biblio->title,
256                 barcode    => $barcode,
257                 hide_main  => 1,
258                 inputfocus => 'confirm',
259             );
260         }
261     }
262 } # $op
263
264 if ( $patron && ( $op eq 'renew' ) ) {
265     my ($status,$renewerror) = CanBookBeRenewed( $patron->borrowernumber, $item->itemnumber );
266     if ($status) {
267         #warn "renewing";
268         AddRenewal( $patron->borrowernumber, $item->itemnumber, undef, undef, undef, undef, 1 );
269         push @newissueslist, $barcode;
270         $template->param( renewed => 1 );
271     }
272 }
273
274 if ($patron) {
275     my $borrowername = sprintf "%s %s", ($patron->firstname || ''), ($patron->surname || '');
276     my $pending_checkouts = $patron->pending_checkouts;
277     my @checkouts;
278     while ( my $c = $pending_checkouts->next ) {
279         my $checkout = $c->unblessed_all_relateds;
280         my ($can_be_renewed, $renew_error) = CanBookBeRenewed(
281             $patron->borrowernumber,
282             $checkout->{itemnumber},
283         );
284         $checkout->{can_be_renewed} = $can_be_renewed; # In the future this will be $checkout->can_be_renewed
285         $checkout->{renew_error} = $renew_error;
286         $checkout->{overdue} = $c->is_overdue;
287         push @checkouts, $checkout;
288     }
289
290     my $show_priority;
291     for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
292         m/priority/ and $show_priority = 1;
293     }
294
295     my $account = $patron->account;
296     my $total = $account->balance;
297     my $accountlines = $account->lines;
298
299     my $holds = $patron->holds;
300     my $waiting_holds_count = 0;
301
302     while(my $hold = $holds->next) {
303         $waiting_holds_count++ if $hold->is_waiting;
304     }
305
306     $template->param(
307         validuser => 1,
308         borrowername => $borrowername,
309         issues_count => scalar(@checkouts),
310         ISSUES => \@checkouts,
311         HOLDS => $holds,
312         newissues => join(',',@newissueslist),
313         patronid => $patronid,
314         patronlogin => $patronlogin,
315         patronpw => $patronpw,
316         waiting_holds_count => $waiting_holds_count,
317         noitemlinks => 1 ,
318         borrowernumber => $patron->borrowernumber,
319         SuspendHoldsOpac => C4::Context->preference('SuspendHoldsOpac'),
320         AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
321         howpriority   => $show_priority,
322         ACCOUNT_LINES => $accountlines,
323         total => $total,
324     );
325
326     my $patron_messages = Koha::Patron::Messages->search(
327         {
328             borrowernumber => $patron->borrowernumber,
329             message_type => 'B',
330         }
331     );
332     $template->param(
333         patron_messages => $patron_messages,
334         opacnote => $patron->opacnote,
335     );
336
337     my $inputfocus = ($return_only      == 1) ? 'returnbook' :
338                      ($confirm_required == 1) ? 'confirm'    : 'barcode' ;
339     $template->param(
340         inputfocus => $inputfocus,
341         nofines => 1,
342
343     );
344     if (C4::Context->preference('ShowPatronImageInWebBasedSelfCheck')) {
345         my $patron_image = $patron->image;
346         $template->param(
347             display_patron_image => 1,
348             csrf_token           => Koha::Token->new->generate_csrf( { session_id => scalar $query->cookie('CGISESSID') . $patron->cardnumber, id => $patron->userid } ),
349         ) if $patron_image;
350     }
351 } else {
352     $template->param(
353         patronid   => $patronid,
354         nouser     => $patronid,
355     );
356 }
357
358 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };