Bug 17600: Standardize our EXPORT_OK
[srvgit] / 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( 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::Token;
50
51 my $query = CGI->new;
52
53 unless (C4::Context->preference('WebBasedSelfCheck')) {
54     # redirect to OPAC home if self-check is not enabled
55     print $query->redirect("/cgi-bin/koha/opac-main.pl");
56     exit;
57 }
58
59 unless ( in_iprange(C4::Context->preference('SelfCheckAllowByIPRanges')) ) {
60     # redirect to OPAC home if self-checkout not permitted from current IP
61     print $query->redirect("/cgi-bin/koha/opac-main.pl");
62     exit;
63 }
64
65 if (C4::Context->preference('AutoSelfCheckAllowed'))
66 {
67     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
68     my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
69     $query->param(-name=>'userid',-values=>[$AutoSelfCheckID]);
70     $query->param(-name=>'password',-values=>[$AutoSelfCheckPass]);
71     $query->param(-name=>'koha_login_context',-values=>['sco']);
72 }
73 $query->param(-name=>'sco_user_login',-values=>[1]);
74
75 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
76     {
77         template_name   => "sco/sco-main.tt",
78         flagsrequired   => { self_check => "self_checkout_module" },
79         query           => $query,
80         type            => "opac",
81     }
82 );
83
84 # Get the self checkout timeout preference, or use 120 seconds as a default
85 my $selfchecktimeout = 120000;
86 if (C4::Context->preference('SelfCheckTimeout')) { 
87     $selfchecktimeout = C4::Context->preference('SelfCheckTimeout') * 1000;
88 }
89 $template->param( SelfCheckTimeout => $selfchecktimeout );
90
91 # Checks policy laid out by SCOAllowCheckin, defaults to 'on' if preference is undefined
92 my $allowselfcheckreturns = 1;
93 if (defined C4::Context->preference('SCOAllowCheckin')) {
94     $allowselfcheckreturns = C4::Context->preference('SCOAllowCheckin');
95 }
96
97 my $issuerid = $loggedinuser;
98 my ($op, $patronid, $patronlogin, $patronpw, $barcode, $confirmed, $newissues) = (
99     $query->param("op")         || '',
100     $query->param("patronid")   || '',
101     $query->param("patronlogin")|| '',
102     $query->param("patronpw")   || '',
103     $query->param("barcode")    || '',
104     $query->param("confirmed")  || '',
105     $query->param("newissues")  || '',
106 );
107
108 my @newissueslist = split /,/, $newissues;
109 my $issuenoconfirm = 1; #don't need to confirm on issue.
110 my $issuer   = Koha::Patrons->find( $issuerid )->unblessed;
111 my $item     = Koha::Items->find({ barcode => $barcode });
112 if (C4::Context->preference('SelfCheckoutByLogin') && !$patronid) {
113     my $dbh = C4::Context->dbh;
114     my $resval;
115     ($resval, $patronid) = checkpw($dbh, $patronlogin, $patronpw);
116 }
117
118 my ( $borrower, $patron );
119 if ( $patronid ) {
120     $patron = Koha::Patrons->find( { cardnumber => $patronid } );
121     $borrower = $patron->unblessed if $patron;
122 }
123
124 my $branch = $issuer->{branchcode};
125 my $confirm_required = 0;
126 my $return_only = 0;
127 #warn "issuer cardnumber: " .   $issuer->{cardnumber};
128 #warn "patron cardnumber: " . $borrower->{cardnumber};
129 if ($op eq "logout") {
130     $template->param( loggedout => 1 );
131     $query->param( patronid => undef, patronlogin => undef, patronpw => undef );
132 }
133 elsif ( $op eq "returnbook" && $allowselfcheckreturns ) {
134     my $success        = 0;
135     my $human_required = 0;
136     if ( C4::Context->preference("CircConfirmItemParts") ) {
137         my $item = Koha::Items->find( { barcode => $barcode } );
138         if ( defined($item)
139             && $item->materials )
140         {
141             $human_required = 1;
142         }
143     }
144
145     ($success) = AddReturn( $barcode, $branch )
146       unless $human_required;
147     $template->param( returned => $success );
148 }
149 elsif ( $patron && ( $op eq 'checkout' ) ) {
150     my $impossible  = {};
151     my $needconfirm = {};
152     ( $impossible, $needconfirm ) = CanBookBeIssued(
153         $patron,
154         $barcode,
155         undef,
156         0,
157         C4::Context->preference("AllowItemsOnHoldCheckoutSCO")
158     );
159     my $issue_error;
160     if ( $confirm_required = scalar keys %$needconfirm ) {
161         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 ) ) {
162             if ( $needconfirm->{$error} ) {
163                 $issue_error = $error;
164                 $confirmed = 0;
165                 last;
166             }
167         }
168     }
169
170     #warn "confirm_required: " . $confirm_required ;
171     if (scalar keys %$impossible) {
172
173         my $issue_error = (keys %$impossible)[0]; # FIXME This is wrong, we assume only one error and keys are not ordered
174         my $title = ( $item ) ? $item->biblio->title : '';
175
176         $template->param(
177             impossible                => $issue_error,
178             "circ_error_$issue_error" => 1,
179             title                     => $title,
180             hide_main                 => 1,
181         );
182         if ($issue_error eq 'DEBT') {
183             $template->param(DEBT => $impossible->{DEBT});
184         }
185         #warn "issue_error: " . $issue_error ;
186         if ( $issue_error eq "NO_MORE_RENEWALS" ) {
187             $return_only = 1;
188             $template->param(
189                 returnitem => 1,
190                 barcode    => $barcode,
191             );
192         }
193     } elsif ( $needconfirm->{RENEW_ISSUE} ){
194         $template->param(
195                 renew               => 1,
196                 barcode             => $barcode,
197                 confirm             => 1,
198                 confirm_renew_issue => 1,
199                 hide_main           => 1,
200         );
201     } elsif ( $confirm_required && !$confirmed ) {
202         #warn "failed confirmation";
203         $template->param(
204             impossible                => 1,
205             "circ_error_$issue_error" => 1,
206             hide_main                 => 1,
207         );
208         if ($issue_error eq 'DEBT') {
209             $template->param(DEBT => $needconfirm->{DEBT});
210         }
211     } else {
212         if ( $confirmed || $issuenoconfirm ) {    # we'll want to call getpatroninfo again to get updated issues.
213             my ( $hold_existed, $item );
214             if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
215                 # There is no easy way to know if the patron has been charged for this item.
216                 # So we check if a hold existed for this item before the check in
217                 $item = Koha::Items->find({ barcode => $barcode });
218                 $hold_existed = Koha::Holds->search(
219                     {
220                         -and => {
221                             borrowernumber => $borrower->{borrowernumber},
222                             -or            => {
223                                 biblionumber => $item->biblionumber,
224                                 itemnumber   => $item->itemnumber
225                             }
226                         }
227                     }
228                 )->count;
229             }
230
231             AddIssue( $borrower, $barcode );
232             $template->param( issued => 1 );
233             push @newissueslist, $barcode;
234
235             if ( $hold_existed ) {
236                 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
237                 $template->param(
238                     # If the hold existed before the check in, let's confirm that the charge line exists
239                     # Note that this should not be needed but since we do not have proper exception handling here we do it this way
240                     patron_has_hold_fee => Koha::Account::Lines->search(
241                         {
242                             borrowernumber  => $borrower->{borrowernumber},
243                             debit_type_code => 'RESERVE',
244                             description     => $item->biblio->title,
245                             date            => $dtf->format_date(dt_from_string)
246                         }
247                       )->count,
248                 );
249             }
250         } else {
251             $confirm_required = 1;
252             #warn "issue confirmation";
253             $template->param(
254                 confirm    => "Issuing title: " . $item->biblio->title,
255                 barcode    => $barcode,
256                 hide_main  => 1,
257                 inputfocus => 'confirm',
258             );
259         }
260     }
261 } # $op
262
263 if ( $patron && ( $op eq 'renew' ) ) {
264     my ($status,$renewerror) = CanBookBeRenewed( $borrower->{borrowernumber}, $item->itemnumber );
265     if ($status) {
266         #warn "renewing";
267         AddRenewal( $borrower->{borrowernumber}, $item->itemnumber, undef, undef, undef, undef, 1 );
268         push @newissueslist, $barcode;
269         $template->param( renewed => 1 );
270     }
271 }
272
273 if ($borrower) {
274 #   warn "issuer's  branchcode: " .   $issuer->{branchcode};
275 #   warn   "user's  branchcode: " . $borrower->{branchcode};
276     my $borrowername = sprintf "%s %s", ($borrower->{firstname} || ''), ($borrower->{surname} || '');
277     my $pending_checkouts = $patron->pending_checkouts;
278     my @checkouts;
279     while ( my $c = $pending_checkouts->next ) {
280         my $checkout = $c->unblessed_all_relateds;
281         my ($can_be_renewed, $renew_error) = CanBookBeRenewed(
282             $borrower->{borrowernumber},
283             $checkout->{itemnumber},
284         );
285         $checkout->{can_be_renewed} = $can_be_renewed; # In the future this will be $checkout->can_be_renewed
286         $checkout->{renew_error} = $renew_error;
287         $checkout->{overdue} = $c->is_overdue;
288         push @checkouts, $checkout;
289     }
290
291     my $show_priority;
292     for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
293         m/priority/ and $show_priority = 1;
294     }
295
296     my $account = $patron->account;
297     my $total = $account->balance;
298     my $accountlines = $account->lines;
299
300     my $holds = $patron->holds;
301     my $waiting_holds_count = 0;
302
303     while(my $hold = $holds->next) {
304         $waiting_holds_count++ if $hold->is_waiting;
305     }
306
307     $template->param(
308         validuser => 1,
309         borrowername => $borrowername,
310         issues_count => scalar(@checkouts),
311         ISSUES => \@checkouts,
312         HOLDS => $holds,
313         newissues => join(',',@newissueslist),
314         patronid => $patronid,
315         patronlogin => $patronlogin,
316         patronpw => $patronpw,
317         waiting_holds_count => $waiting_holds_count,
318         noitemlinks => 1 ,
319         borrowernumber => $borrower->{'borrowernumber'},
320         SuspendHoldsOpac => C4::Context->preference('SuspendHoldsOpac'),
321         AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
322         howpriority   => $show_priority,
323         ACCOUNT_LINES => $accountlines,
324         total => $total,
325     );
326
327     my $patron_messages = Koha::Patron::Messages->search(
328         {
329             borrowernumber => $borrower->{'borrowernumber'},
330             message_type => 'B',
331         }
332     );
333     $template->param(
334         patron_messages => $patron_messages,
335         opacnote => $borrower->{opacnote},
336     );
337
338     my $inputfocus = ($return_only      == 1) ? 'returnbook' :
339                      ($confirm_required == 1) ? 'confirm'    : 'barcode' ;
340     $template->param(
341         inputfocus => $inputfocus,
342         nofines => 1,
343
344     );
345     if (C4::Context->preference('ShowPatronImageInWebBasedSelfCheck')) {
346         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
347         $template->param(
348             display_patron_image => 1,
349             csrf_token           => Koha::Token->new->generate_csrf( { session_id => scalar $query->cookie('CGISESSID') . $borrower->{cardnumber}, id => $borrower->{userid}} ),
350         ) if $patron_image;
351     }
352 } else {
353     $template->param(
354         patronid   => $patronid,
355         nouser     => $patronid,
356     );
357 }
358
359 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };