Bug 19458: Self-check module highlighting
[koha.git] / opac / sco / sco-main.pl
index 243dddd..49018da 100755 (executable)
@@ -6,18 +6,18 @@
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 # We're going to authenticate a self-check user.  we'll add a flag to borrowers 'selfcheck'
 #
 #
 # FIXME: inputfocus not really used in TMPL
 
-use strict;
-use warnings;
+use Modern::Perl;
 
-use CGI;
-use Digest::MD5 qw(md5_base64);
+use CGI qw ( -utf8 );
 
 use C4::Auth qw(get_template_and_user checkpw);
 use C4::Koha;
@@ -45,6 +43,12 @@ use C4::Output;
 use C4::Members;
 use C4::Biblio;
 use C4::Items;
+use Koha::DateUtils qw( dt_from_string );
+use Koha::Acquisition::Currencies;
+use Koha::Patrons;
+use Koha::Patron::Images;
+use Koha::Patron::Messages;
+use Koha::Token;
 
 my $query = new CGI;
 
@@ -56,62 +60,63 @@ unless (C4::Context->preference('WebBasedSelfCheck')) {
 
 if (C4::Context->preference('AutoSelfCheckAllowed')) 
 {
-       my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
-       my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
-       $query->param(-name=>'userid',-values=>[$AutoSelfCheckID]);
-       $query->param(-name=>'password',-values=>[$AutoSelfCheckPass]);
+    my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
+    my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
+    $query->param(-name=>'userid',-values=>[$AutoSelfCheckID]);
+    $query->param(-name=>'password',-values=>[$AutoSelfCheckPass]);
     $query->param(-name=>'koha_login_context',-values=>['sco']);
 }
-my ($template, $loggedinuser, $cookie) = get_template_and_user({
-    template_name   => "sco/sco-main.tmpl",
-    authnotrequired => 0,
-      flagsrequired => { circulate => "circulate_remaining_permissions" },
-    query => $query,
-    type  => "opac",
-    debug => 1,
-});
-if (C4::Context->preference('SelfCheckoutByLogin'))
-{
-    $template->param(authbylogin  => 1);
-}
+$query->param(-name=>'sco_user_login',-values=>[1]);
+
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "sco/sco-main.tt",
+        authnotrequired => 0,
+        flagsrequired   => { self_check => "self_checkout_module" },
+        query           => $query,
+        type            => "opac",
+        debug           => 1,
+    }
+);
 
 # Get the self checkout timeout preference, or use 120 seconds as a default
 my $selfchecktimeout = 120000;
 if (C4::Context->preference('SelfCheckTimeout')) { 
     $selfchecktimeout = C4::Context->preference('SelfCheckTimeout') * 1000;
 }
-$template->param(SelfCheckTimeout => $selfchecktimeout);
+$template->param( SelfCheckTimeout => $selfchecktimeout );
 
 # Checks policy laid out by AllowSelfCheckReturns, defaults to 'on' if preference is undefined
 my $allowselfcheckreturns = 1;
 if (defined C4::Context->preference('AllowSelfCheckReturns')) {
     $allowselfcheckreturns = C4::Context->preference('AllowSelfCheckReturns');
 }
-$template->param(AllowSelfCheckReturns => $allowselfcheckreturns);
-
 
 my $issuerid = $loggedinuser;
-my ($op, $patronid, $patronlogin, $patronpw, $barcode, $confirmed, $timedout) = (
+my ($op, $patronid, $patronlogin, $patronpw, $barcode, $confirmed, $newissues) = (
     $query->param("op")         || '',
     $query->param("patronid")   || '',
     $query->param("patronlogin")|| '',
     $query->param("patronpw")   || '',
     $query->param("barcode")    || '',
     $query->param("confirmed")  || '',
-    $query->param("timedout")   || '', #not actually using this...
+    $query->param("newissues")  || '',
 );
-
+my @newissueslist = split /,/, $newissues;
 my $issuenoconfirm = 1; #don't need to confirm on issue.
-#warn "issuerid: " . $issuerid;
-my $issuer   = GetMemberDetails($issuerid);
+my $issuer   = Koha::Patrons->find( $issuerid )->unblessed;
 my $item     = GetItem(undef,$barcode);
 if (C4::Context->preference('SelfCheckoutByLogin') && !$patronid) {
     my $dbh = C4::Context->dbh;
     my $resval;
     ($resval, $patronid) = checkpw($dbh, $patronlogin, $patronpw);
 }
-my $borrower = GetMemberDetails(undef,$patronid);
 
+my ( $borrower, $patron );
+if ( $patronid ) {
+    $patron = Koha::Patrons->find( { cardnumber => $patronid } );
+    $borrower = $patron->unblessed if $patron;
+}
 
 my $branch = $issuer->{branchcode};
 my $confirm_required = 0;
@@ -123,31 +128,33 @@ if ($op eq "logout") {
 }
 elsif ( $op eq "returnbook" && $allowselfcheckreturns ) {
     my ($doreturn) = AddReturn( $barcode, $branch );
-    #warn "returnbook: " . $doreturn;
-    $borrower = GetMemberDetails(undef,$patronid);
 }
-elsif ( $op eq "checkout" ) {
+elsif ( $patron and $op eq "checkout" ) {
     my $impossible  = {};
     my $needconfirm = {};
-    if ( !$confirmed ) {
-        ( $impossible, $needconfirm ) = CanBookBeIssued(
-            $borrower,
-            $barcode,
-            undef,
-            0,
-            C4::Context->preference("AllowItemsOnHoldCheckout")
-        );
+    ( $impossible, $needconfirm ) = CanBookBeIssued(
+        $patron,
+        $barcode,
+        undef,
+        0,
+        C4::Context->preference("AllowItemsOnHoldCheckoutSCO")
+    );
+    my $issue_error;
+    if ( $confirm_required = scalar keys %$needconfirm ) {
+        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 USERBLOCKEDOVERDUE PATRON_CANT PREVISSUE NOT_FOR_LOAN_FORCING ITEM_LOST) ) {
+            if ( $needconfirm->{$error} ) {
+                $issue_error = $error;
+                $confirmed = 0;
+                last;
+            }
+        }
     }
-    $confirm_required = scalar keys %$needconfirm;
 
     #warn "confirm_required: " . $confirm_required ;
     if (scalar keys %$impossible) {
 
-        #  warn "impossible: numkeys: " . scalar (keys(%$impossible));
-        #warn join " ", keys %$impossible;
-        my $issue_error = (keys %$impossible)[0];
+        my $issue_error = (keys %$impossible)[0]; # FIXME This is wrong, we assume only one error and keys are not ordered
 
-        # FIXME  we assume only one error.
         $template->param(
             impossible                => $issue_error,
             "circ_error_$issue_error" => 1,
@@ -155,7 +162,7 @@ elsif ( $op eq "checkout" ) {
             hide_main                 => 1,
         );
         if ($issue_error eq 'DEBT') {
-            $template->param(amount => $impossible->{DEBT});
+            $template->param(DEBT => $impossible->{DEBT});
         }
         #warn "issue_error: " . $issue_error ;
         if ( $issue_error eq "NO_MORE_RENEWALS" ) {
@@ -168,7 +175,7 @@ elsif ( $op eq "checkout" ) {
     } elsif ( $needconfirm->{RENEW_ISSUE} ) {
         if ($confirmed) {
             #warn "renewing";
-            AddRenewal( $borrower, $item->{itemnumber} );
+            AddRenewal( $borrower->{borrowernumber}, $item->{itemnumber} );
         } else {
             #warn "renew confirmation";
             $template->param(
@@ -181,21 +188,52 @@ elsif ( $op eq "checkout" ) {
         }
     } elsif ( $confirm_required && !$confirmed ) {
         #warn "failed confirmation";
-        my $issue_error = (keys %$needconfirm)[0];
         $template->param(
-            impossible                => (keys %$needconfirm)[0],
+            impossible                => 1,
             "circ_error_$issue_error" => 1,
             hide_main                 => 1,
         );
+        if ($issue_error eq 'DEBT') {
+            $template->param(DEBT => $needconfirm->{DEBT});
+        }
     } else {
         if ( $confirmed || $issuenoconfirm ) {    # we'll want to call getpatroninfo again to get updated issues.
-            # warn "issuing book?";
+            my ( $hold_existed, $item );
+            if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
+                # There is no easy way to know if the patron has been charged for this item.
+                # So we check if a hold existed for this item before the check in
+                $item = Koha::Items->find({ barcode => $barcode });
+                $hold_existed = Koha::Holds->search(
+                    {
+                        -and => {
+                            borrowernumber => $borrower->{borrowernumber},
+                            -or            => {
+                                biblionumber => $item->biblionumber,
+                                itemnumber   => $item->itemnumber
+                            }
+                        }
+                    }
+                )->count;
+            }
             AddIssue( $borrower, $barcode );
-            # ($borrower, $flags) = getpatroninformation(undef,undef, $patronid);
-            # $template->param(
-            #   patronid => $patronid,
-            #   validuser => 1,
-            # );
+            push @newissueslist, $barcode;
+            print 'Issues \n';
+            print join(',', @newissueslist);
+            if ( $hold_existed ) {
+                my $dtf = Koha::Database->new->schema->storage->datetime_parser;
+                $template->param(
+                    # If the hold existed before the check in, let's confirm that the charge line exists
+                    # Note that this should not be needed but since we do not have proper exception handling here we do it this way
+                    patron_has_hold_fee => Koha::Account::Lines->search(
+                        {
+                            borrowernumber => $borrower->{borrowernumber},
+                            accounttype    => 'Res',
+                            description    => 'Reserve Charge - ' . $item->biblio->title,
+                            date           => $dtf->format_date(dt_from_string)
+                        }
+                      )->count,
+                );
+            }
         } else {
             $confirm_required = 1;
             #warn "issue confirmation";
@@ -209,49 +247,62 @@ elsif ( $op eq "checkout" ) {
     }
 } # $op
 
-if ($borrower->{cardnumber}) {
+if ($borrower) {
+    print 'borrower \n';
 #   warn "issuer's  branchcode: " .   $issuer->{branchcode};
 #   warn   "user's  branchcode: " . $borrower->{branchcode};
     my $borrowername = sprintf "%s %s", ($borrower->{firstname} || ''), ($borrower->{surname} || '');
-    my @issues;
-    my ($issueslist) = GetPendingIssues( $borrower->{'borrowernumber'} );
-    foreach my $it (@$issueslist) {
-        my ($renewokay, $renewerror) = CanBookBeIssued(
-            $borrower,
-            $it->{'barcode'},
-            undef,
-            0,
-            C4::Context->preference("AllowItemsOnHoldCheckout")
+    my $pending_checkouts = $patron->pending_checkouts;
+    my @checkouts;
+    while ( my $c = $pending_checkouts->next ) {
+        my $checkout = $c->unblessed_all_relateds;
+        my ($can_be_renewed, $renew_error) = CanBookBeRenewed(
+            $borrower->{borrowernumber},
+            $checkout->{itemnumber},
         );
-        $it->{'norenew'} = 1 if $renewokay->{'NO_MORE_RENEWALS'};
-        push @issues, $it;
+        $checkout->{can_be_renewed} = $can_be_renewed; # In the future this will be $checkout->can_be_renewed
+        $checkout->{renew_error} = $renew_error;
+        $checkout->{overdue} = $c->is_overdue;
+        push @checkouts, $checkout;
     }
 
     $template->param(
         validuser => 1,
         borrowername => $borrowername,
-        issues_count => scalar(@issues),
-        ISSUES => \@issues,
+        issues_count => scalar(@checkouts),
+        ISSUES => \@checkouts,
+        newissues => join(',',@newissueslist),
         patronid => $patronid,
         patronlogin => $patronlogin,
         patronpw => $patronpw,
         noitemlinks => 1 ,
+        borrowernumber => $borrower->{'borrowernumber'},
+    );
+
+    my $patron_messages = Koha::Patron::Messages->search(
+        {
+            borrowernumber => $borrower->{'borrowernumber'},
+            message_type => 'B',
+        }
+    );
+    $template->param(
+        patron_messages => $patron_messages,
+        opacnote => $borrower->{opacnote},
     );
+
     my $inputfocus = ($return_only      == 1) ? 'returnbook' :
                      ($confirm_required == 1) ? 'confirm'    : 'barcode' ;
     $template->param(
         inputfocus => $inputfocus,
-               nofines => 1,
-        "dateformat_" . C4::Context->preference('dateformat') => 1,
+        nofines => 1,
+
     );
     if (C4::Context->preference('ShowPatronImageInWebBasedSelfCheck')) {
-        my ($image, $dberror) = GetPatronImage($borrower->{cardnumber});
-        if ($image) {
-            $template->param(
-                display_patron_image => 1,
-                cardnumber           => $borrower->{cardnumber},
-            );
-        }
+        my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
+        $template->param(
+            display_patron_image => 1,
+            csrf_token           => Koha::Token->new->generate_csrf( { session_id => scalar $query->cookie('CGISESSID') . $borrower->{cardnumber}, id => $borrower->{userid}} ),
+        ) if $patron_image;
     }
 } else {
     $template->param(
@@ -260,4 +311,4 @@ if ($borrower->{cardnumber}) {
     );
 }
 
-output_html_with_http_headers $query, $cookie, $template->output;
+output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };