Bug 7295: More granular permissions for baskets
[koha.git] / circ / circulation.pl
index 4c8a52a..9769731 100755 (executable)
@@ -4,6 +4,8 @@
 
 # Copyright 2000-2002 Katipo Communications
 # copyright 2010 BibLibre
+# Copyright 2011 PTFS-Europe Ltd.
+# Copyright 2012 software.coop and MJ Ray
 #
 # This file is part of Koha.
 #
@@ -24,18 +26,21 @@ use strict;
 use warnings;
 use CGI;
 use C4::Output;
+use C4::Print;
 use C4::Auth qw/:DEFAULT get_session/;
 use C4::Dates qw/format_date/;
 use C4::Branch; # GetBranches
 use C4::Koha;   # GetPrinter
 use C4::Circulation;
-use C4::Overdues qw/CheckBorrowerDebarred/;
 use C4::Members;
 use C4::Biblio;
+use C4::Search;
+use MARC::Record;
 use C4::Reserves;
 use C4::Context;
 use CGI::Session;
 use C4::Members::Attributes qw(GetBorrowerAttributes);
+use Koha::Borrower::Debarments qw(GetDebarments);
 use Koha::DateUtils;
 
 use Date::Calc qw(
@@ -92,10 +97,14 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
 my $branches = GetBranches();
 
 my @failedrenews = $query->param('failedrenew');    # expected to be itemnumbers 
-my %renew_failed;
+our %renew_failed = ();
 for (@failedrenews) { $renew_failed{$_} = 1; }
 
-my $findborrower = $query->param('findborrower');
+my @failedreturns = $query->param('failedreturn');
+our %return_failed = ();
+for (@failedreturns) { $return_failed{$_} = 1; }
+
+my $findborrower = $query->param('findborrower') || q{};
 $findborrower =~ s|,| |g;
 my $borrowernumber = $query->param('borrowernumber');
 
@@ -116,7 +125,7 @@ if (C4::Context->preference("UseTablesortForCirc")) {
     $template->param(UseTablesortForCirc => 1);
 }
 
-my $barcode        = $query->param('barcode') || '';
+my $barcode        = $query->param('barcode') || q{};
 $barcode =~  s/^\s*|\s*$//g; # remove leading/trailing whitespace
 
 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
@@ -125,9 +134,9 @@ my $duedatespec    = $query->param('duedatespec')   || $session->param('stickydu
 my $issueconfirmed = $query->param('issueconfirmed');
 my $cancelreserve  = $query->param('cancelreserve');
 my $organisation   = $query->param('organisations');
-my $print          = $query->param('print');
-my $newexpiry      = $query->param('dateexpiry');
+my $print          = $query->param('print') || q{};
 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
+my $charges        = $query->param('charges') || q{};
 
 # Check if stickyduedate is turned off
 if ( $barcode ) {
@@ -145,8 +154,7 @@ my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
 if($duedatespec_allow){
     if ($duedatespec) {
         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
-            my $tempdate = C4::Dates->new($duedatespec);
-                $datedue = $tempdate;
+                $datedue = dt_from_string($duedatespec);
         } else {
             $invalidduedate = 1;
             $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
@@ -154,7 +162,7 @@ if($duedatespec_allow){
     }
 }
 
-my $todaysdate = C4::Dates->new->output('iso');
+our $todaysdate = C4::Dates->new->output('iso');
 
 # check and see if we should print
 if ( $barcode eq '' && $print eq 'maybe' ) {
@@ -162,7 +170,7 @@ if ( $barcode eq '' && $print eq 'maybe' ) {
 }
 
 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
-if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
+if ( $barcode eq '' && $charges eq 'yes' ) {
     $template->param(
         PAYCHARGES     => 'yes',
         borrowernumber => $borrowernumber
@@ -170,7 +178,10 @@ if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
 }
 
 if ( $print eq 'yes' && $borrowernumber ne '' ) {
-    PrintIssueSlip($session->param('branch') || $branch, $borrowernumber);
+    if ( C4::Context->boolean_preference('printcirculationslips') ) {
+        my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
+        NetworkPrint($letter->{content});
+    }
     $query->param( 'borrowernumber', '' );
     $borrowernumber = '';
 }
@@ -182,8 +193,7 @@ if ( $print eq 'yes' && $borrowernumber ne '' ) {
 my $borrowerslist;
 my $message;
 if ($findborrower) {
-    my $borrowers = Search($findborrower, 'cardnumber');
-    my @borrowers = @$borrowers;
+    my $borrowers = Search($findborrower, 'cardnumber') || [];
     if (C4::Context->preference("AddPatronLists")) {
         $template->param(
             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
@@ -194,17 +204,17 @@ if ($findborrower) {
             $template->param(categories=>$categories);
         }
     }
-    if ( $#borrowers == -1 ) {
+    if ( @$borrowers == 0 ) {
         $query->param( 'findborrower', '' );
         $message = "'$findborrower'";
     }
-    elsif ( $#borrowers == 0 ) {
-        $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
+    elsif ( @$borrowers == 1 ) {
+        $borrowernumber = $borrowers->[0]->{'borrowernumber'};
+        $query->param( 'borrowernumber', $borrowernumber );
         $query->param( 'barcode',           '' );
-        $borrowernumber = $borrowers[0]->{'borrowernumber'};
     }
     else {
-        $borrowerslist = \@borrowers;
+        $borrowerslist = $borrowers;
     }
 }
 
@@ -256,13 +266,12 @@ if ($borrowernumber) {
         finetotal    => $fines
     );
 
-    my $debar = CheckBorrowerDebarred($borrowernumber);
-    if ($debar) {
-        $template->param( 'userdebarred'    => 1 );
-        $template->param( 'debarredcomment' => $borrower->{debarredcomment} );
-        if ( $debar ne "9999-12-31" ) {
-            $template->param( 'userdebarreddate' => C4::Dates::format_date($debar) );
-        }
+    $template->param(
+        'userdebarred'    => $borrower->{debarred},
+        'debarredcomment' => $borrower->{debarredcomment},
+    );
+    if ( $borrower->{debarred} ne "9999-12-31" ) {
+        $template->param( 'userdebarreddate' => C4::Dates::format_date( $borrower->{debarred} ) );
     }
 
 }
@@ -273,10 +282,46 @@ if ($borrowernumber) {
 #
 if ($barcode) {
     # always check for blockers on issuing
-    my ( $error, $question ) =
+    my ( $error, $question, $alerts ) =
     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
     my $blocker = $invalidduedate ? 1 : 0;
 
+    $template->param( alert => $alerts );
+
+    #  Get the item title for more information
+    my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
+    $template->param(
+        authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
+    );
+    # Fix for bug 7494: optional checkout-time fallback search for a book
+
+    if ( $error->{'UNKNOWN_BARCODE'}
+        && C4::Context->preference("itemBarcodeFallbackSearch") )
+    {
+     $template->param( FALLBACK => 1 );
+
+        my $query = "kw=" . $barcode;
+        my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
+
+        # if multiple hits, offer options to librarian
+        if ( $total_hits > 0 ) {
+            my @options = ();
+            foreach my $hit ( @{$results} ) {
+                my $chosen =
+                  TransformMarcToKoha( C4::Context->dbh,
+                    MARC::Record->new_from_usmarc($hit) );
+
+                # offer all barcodes individually
+                foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
+                    my %chosen_single = %{$chosen};
+                    $chosen_single{barcode} = $barcode;
+                    push( @options, \%chosen_single );
+                }
+            }
+            $template->param( options => \@options );
+        }
+    }
+
     delete $question->{'DEBT'} if ($debt_confirmed);
     foreach my $impossible ( keys %$error ) {
         $template->param(
@@ -344,16 +389,19 @@ if ($borrowernumber) {
         $getreserv{nottransfered} = 0;
 
         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
-        $getreserv{reservenumber}  = $num_res->{'reservenumber'};
+        $getreserv{reserve_id}  = $num_res->{'reserve_id'};
         $getreserv{title}          = $getiteminfo->{'title'};
+        $getreserv{subtitle}       = GetRecordValue('subtitle', GetMarcBiblio($getiteminfo->{biblionumber}), GetFrameworkCode($getiteminfo->{biblionumber}));
         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
         $getreserv{author}         = $getiteminfo->{'author'};
         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
         $getreserv{waitingat}      = GetBranchName( $num_res->{'branchcode'} );
+        $getreserv{suspend}        = $num_res->{'suspend'};
+        $getreserv{suspend_until}  = $num_res->{'suspend_until'};
         #         check if we have a waiting status for reservations
-        if ( $num_res->{'found'} eq 'W' ) {
+        if ( $num_res->{'found'} && $num_res->{'found'} eq 'W' ) {
             $getreserv{color}   = 'reserved';
             $getreserv{waiting} = 1;
 #     genarate information displaying only waiting reserves
@@ -361,6 +409,7 @@ if ($borrowernumber) {
         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
+        $getWaitingReserveInfo{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
         $getWaitingReserveInfo{waitinghere}  = 1 if $num_res->{'branchcode'} eq $branch;
@@ -382,12 +431,14 @@ if ($borrowernumber) {
 
             $getreserv{color}           = 'inwait';
             $getreserv{title}           = $getbibinfo->{'title'};
+            $getreserv{subtitle}        = GetRecordValue('subtitle', GetMarcBiblio($num_res->{biblionumber}), GetFrameworkCode($num_res->{biblionumber}));
             $getreserv{nottransfered}   = 0;
             $getreserv{itemtype}        = $itemtypeinfo->{'description'};
             $getreserv{author}          = $getbibinfo->{'author'};
             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
         }
         $getreserv{waitingposition} = $num_res->{'priority'};
+        $getreserv{expirationdate} = $num_res->{'expirationdate'};
         push( @reservloop, \%getreserv );
 
 #         if we have a reserve waiting, initiate waitingreserveloop
@@ -409,13 +460,13 @@ if ($borrowernumber) {
 # make the issued books table.
 my $todaysissues = '';
 my $previssues   = '';
-my @todaysissues;
-my @previousissues;
-my @relissues;
-my @relprevissues;
+our @todaysissues   = ();
+our @previousissues = ();
+our @relissues      = ();
+our @relprevissues  = ();
 my $displayrelissues;
 
-my $totalprice = 0;
+our $totalprice = 0;
 
 sub build_issue_data {
     my $issueslist = shift;
@@ -436,24 +487,28 @@ sub build_issue_data {
             $it->{'borrowernumber'},$it->{'itemnumber'}
         );
         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
-        my ( $restype, $reserves, undef ) = CheckReserves( $it->{'itemnumber'} );
+        my $restype = C4::Reserves::GetReserveStatus( $it->{'itemnumber'} );
         $it->{'can_renew'} = $can_renew;
         $it->{'can_confirm'} = !$can_renew && !$restype;
-        $it->{'renew_error'} = $restype;
+        $it->{'renew_error'} = ( $restype eq "Waiting" or $restype eq "Reserved" ) ? 1 : 0;
         $it->{'checkoutdate'} = C4::Dates->new($it->{'issuedate'},'iso')->output('syspref');
         $it->{'issuingbranchname'} = GetBranchName($it->{'branchcode'});
 
-        $totalprice += $it->{'replacementprice'};
+        $totalprice += $it->{'replacementprice'} || 0;
         $it->{'itemtype'} = $itemtypeinfo->{'description'};
         $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
+        $it->{'dd_sort'} = $it->{'date_due'};
         $it->{'dd'} = output_pref($it->{'date_due'});
-        $it->{'displaydate'} = format_date($it->{'issuedate'});
+        $it->{'displaydate_sort'} = $it->{'issuedate'};
+        $it->{'displaydate'} = output_pref($it->{'issuedate'});
         #$it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
         $it->{'od'} = $it->{'overdue'};
-        ($it->{'author'} eq '') and $it->{'author'} = ' ';
+        $it->{'subtitle'} = GetRecordValue('subtitle', GetMarcBiblio($it->{biblionumber}), GetFrameworkCode($it->{biblionumber}));
         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
+        $it->{'return_failed'} = $return_failed{$it->{'barcode'}};
 
-        if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
+        if ( ( $it->{'issuedate'} && $it->{'issuedate'} gt $todaysdate )
+          || ( $it->{'lastreneweddate'} && $it->{'lastreneweddate'} gt $todaysdate ) ) {
             (!$relatives) ? push @todaysissues, $it : push @relissues, $it;
         } else {
             (!$relatives) ? push @previousissues, $it : push @relprevissues, $it;
@@ -528,7 +583,6 @@ foreach my $flag ( sort keys %$flags ) {
     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
     if ( $flags->{$flag}->{'noissues'} ) {
         $template->param(
-            flagged  => 1,
             noissues => 'true',
         );
         if ( $flag eq 'GNA' ) {
@@ -560,7 +614,6 @@ foreach my $flag ( sort keys %$flags ) {
         if ( $flag eq 'CHARGES' ) {
             $template->param(
                 charges    => 'true',
-                flagged    => 1,
                 chargesmsg => $flags->{'CHARGES'}->{'message'},
                 chargesamount => $flags->{'CHARGES'}->{'amount'},
             );
@@ -575,7 +628,6 @@ foreach my $flag ( sort keys %$flags ) {
         elsif ( $flag eq 'ODUES' ) {
             $template->param(
                 odues    => 'true',
-                flagged  => 1,
                 oduesmsg => $flags->{'ODUES'}->{'message'}
             );
 
@@ -587,7 +639,6 @@ foreach my $flag ( sort keys %$flags ) {
         elsif ( $flag eq 'NOTES' ) {
             $template->param(
                 notes    => 'true',
-                flagged  => 1,
                 notesmsg => $flags->{'NOTES'}->{'message'}
             );
         }
@@ -632,8 +683,10 @@ my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
 if($bor_messages_loop){ $template->param(flagged => 1 ); }
 
 # Computes full borrower address
-my (undef, $roadttype_hashref) = &GetRoadTypes();
-my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
+my @fulladdress;
+push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
+push @fulladdress, &GetRoadTypeDetails( $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
+push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
 
 my $fast_cataloging = 0;
 if (defined getframeworkinfo('FA')) {
@@ -663,11 +716,11 @@ $template->param(
     surname           => $borrower->{'surname'},
     showname          => $borrower->{'showname'},
     category_type     => $borrower->{'category_type'},
-    dateexpiry        => format_date($newexpiry),
+    was_renewed       => $query->param('was_renewed') ? 1 : 0,
     expiry            => format_date($borrower->{'dateexpiry'}),
     categorycode      => $borrower->{'categorycode'},
     categoryname      => $borrower->{description},
-    address           => $address,
+    address           => join(' ', @fulladdress),
     address2          => $borrower->{'address2'},
     email             => $borrower->{'email'},
     emailpro          => $borrower->{'emailpro'},
@@ -700,7 +753,10 @@ $template->param(
     soundon           => C4::Context->preference("SoundOn"),
     fast_cataloging   => $fast_cataloging,
     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
-       activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
+    activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
+    SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
+    AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
+    RoutingSerials => C4::Context->preference('RoutingSerials'),
 );
 
 # save stickyduedate to session
@@ -708,7 +764,7 @@ if ($stickyduedate) {
     $session->param( 'stickyduedate', $duedatespec );
 }
 
-my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
+my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
 $template->param( picture => 1 ) if $picture;
 
 # get authorised values with type of BOR_NOTES
@@ -719,9 +775,11 @@ $template->param(
     debt_confirmed            => $debt_confirmed,
     SpecifyDueDate            => $duedatespec_allow,
     CircAutocompl             => C4::Context->preference("CircAutocompl"),
-       AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
-    dateformat                => C4::Context->preference("dateformat"),
-    DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
+    AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
+    export_remove_fields      => C4::Context->preference("ExportRemoveFields"),
+    export_with_csv_profile   => C4::Context->preference("ExportWithCsvProfile"),
     canned_bor_notes_loop     => $canned_notes,
+    debarments                => GetDebarments({ borrowernumber => $borrowernumber }),
 );
+
 output_html_with_http_headers $query, $cookie, $template->output;