Bug 3150: Move emails for sending cart and list contents to notices
[koha-ffzg.git] / circ / pendingreserves.pl
index 68e57a0..21016bc 100755 (executable)
@@ -21,16 +21,17 @@ use Modern::Perl;
 
 use constant PULL_INTERVAL => 2;
 use List::MoreUtils qw( uniq );
+use YAML::XS;
+use Encode;
 
 use C4::Context;
-use C4::Output;
+use C4::Output qw( output_html_with_http_headers );
 use CGI qw ( -utf8 );
-use C4::Auth;
-use C4::Debug;
-use C4::Items qw( ModItemTransfer );
+use C4::Auth qw( get_template_and_user );
+use C4::Items;
 use C4::Reserves qw( ModReserveCancelAll );
 use Koha::Biblios;
-use Koha::DateUtils;
+use Koha::DateUtils qw( dt_from_string );
 use Koha::Holds;
 use DateTime::Duration;
 
@@ -48,7 +49,6 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
         query           => $input,
         type            => "intranet",
         flagsrequired   => { circulate => "circulate_remaining_permissions" },
-        debug           => 1,
     }
 );
 
@@ -84,13 +84,13 @@ if ( $op eq 'cancel_reserve' and $reserve_id ) {
                 },
             );
             if ( $letter ) {
-                my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
+                my $from_address = $library->from_email_address;
 
                 C4::Letters::EnqueueLetter(
                     {   letter                 => $letter,
                         borrowernumber         => $patron->borrowernumber,
                         message_transport_type => 'email',
-                        from_address           => $admin_email_address,
+                        from_address           => $from_address,
                     }
                 );
                 unless ( $patron->notice_email_address ) {
@@ -109,7 +109,7 @@ if ( $op eq 'cancel_reserve' and $reserve_id ) {
         if ( my $yaml = C4::Context->preference('UpdateItemWhenLostFromHoldList') ) {
             $yaml = "$yaml\n\n";  # YAML is anal on ending \n. Surplus does not hurt
             my $assignments;
-            eval { $assignments = YAML::Load($yaml); };
+            eval { $assignments = YAML::XS::Load(Encode::encode_utf8($yaml)); };
             if ($@) {
                 warn "Unable to parse UpdateItemWhenLostFromHoldList syspref : $@" if $@;
             }
@@ -155,12 +155,13 @@ unless ( $enddate ) {
 
 # building query parameters
 my %where = (
-    'reserve.found' => undef,
-    'reserve.suspend' => 0,
+    'me.found' => undef,
+    'me.priority' => { '!=' => 0 },
+    'me.suspend' => 0,
     'itembib.itemlost' => 0,
     'itembib.withdrawn' => 0,
     'itembib.notforloan' => 0,
-    'itembib.itemnumber' => { -not_in => \'SELECT itemnumber FROM branchtransfers WHERE datearrived IS NULL' }
+    'itembib.itemnumber' => { -not_in => \'SELECT itemnumber FROM branchtransfers WHERE datearrived IS NULL AND datecancelled IS NULL' }
 );
 
 # date boundaries
@@ -168,11 +169,11 @@ my $dtf = Koha::Database->new->schema->storage->datetime_parser;
 my $startdate_iso = $dtf->format_date($startdate);
 my $enddate_iso   = $dtf->format_date($enddate);
 if ( $startdate_iso && $enddate_iso ){
-    $where{'reserve.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
+    $where{'me.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
 } elsif ( $startdate_iso ){
-    $where{'reserve.reservedate'} = { '>=', $startdate_iso };
+    $where{'me.reservedate'} = { '>=', $startdate_iso };
 } elsif ( $enddate_iso ){
-    $where{'reserve.reservedate'} = { '<=', $enddate_iso };
+    $where{'me.reservedate'} = { '<=', $enddate_iso };
 }
 
 # Bug 21320
@@ -180,42 +181,75 @@ if ( !C4::Context->preference('AllowHoldsOnDamagedItems') ){
     $where{'itembib.damaged'} = 0;
 }
 
-if ( C4::Context->preference('IndependentBranches') ){
-    $where{'itembib.holdingbranch'} = C4::Context->userenv->{'branch'};
+if ( C4::Context->only_my_library() ){
+    $where{'me.branchcode'} = C4::Context->userenv->{'branch'};
 }
 
 # get all distinct unfulfilled reserves
-my $distinct_holds = Koha::Holds->search(
+my $holds = Koha::Holds->search(
     { %where },
-    { join => 'itembib', alias => 'reserve', columns => [ 'biblionumber' ] }
+    { join => 'itembib', distinct => 1, columns => qw[me.biblionumber] }
 );
-my @biblionumbers = uniq $distinct_holds->get_column('biblionumber');
 
-my @branchtransfers = map { $_->itemnumber } Koha::Item::Transfers->search({ datearrived => undef }, { columns => [ 'itemnumber' ], collapse => 1 });
-my @waiting_holds = map { $_->itemnumber } Koha::Holds->search({'found' => 'W'}, { columns => [ 'itemnumber' ], collapse => 1 });
-
-my @all_items = Koha::Items->search(
-    {
-        biblionumber => { in => \@biblionumbers },
-        itemlost     => 0,
-        withdrawn    => 0,
-        notforloan   => 0,
-        onloan       => undef,
-        itemnumber   => { -not_in => [ @branchtransfers, @waiting_holds ] },
-    }
-);
+my @biblionumbers = $holds->get_column('biblionumber');
 
 my $all_items;
-foreach my $item ( @all_items ) {
-    push @{$all_items->{$item->biblionumber}}, $item;
+if ( $holds->count ) {
+    foreach my $item ( $holds->get_items_that_can_fill->as_list ) {
+        push @{ $all_items->{ $item->biblionumber } }, $item;
+    }
 }
 
+# patrons count per biblio
+my $patrons_count = {
+    map { $_->{biblionumber} => $_->{patrons_count} } @{ Koha::Holds->search(
+            { 'suspend' => 0 },
+            {
+                select   => [ 'biblionumber', { count => { distinct => 'borrowernumber' } } ],
+                as       => [qw( biblionumber patrons_count )],
+                group_by => [qw( biblionumber )]
+            },
+        )->unblessed
+    }
+};
+
+my $holds_biblios_map = {
+    map { $_->{biblionumber} => $_->{reserve_id} } @{ Koha::Holds->search(
+            {%where},
+            {
+                join    => ['itembib', 'biblio'],
+                select  => ['me.biblionumber', 'me.reserve_id'],
+                order_by => { -desc => 'priority' }
+            }
+        )->unblessed
+    }
+};
+
+my $all_holds = {
+    map { $_->biblionumber => $_ } @{ Koha::Holds->search(
+            { reserve_id => [ values %$holds_biblios_map ]},
+            {
+                prefetch => [ 'borrowernumber', 'itembib', 'biblio', 'item_group' ],
+            }
+        )->as_list
+    }
+};
 
-# make final reserves hash and fill with info
-my $reserves;
+# make final holds_info array and fill with info
+my @holds_info;
+my $seen = {};
 foreach my $bibnum ( @biblionumbers ){
+    # Skip this record if it's already been handled
+    next if $seen->{$bibnum};
+    $seen->{$bibnum} = 1;
 
+    my $hold_info;
     my $items = $all_items->{$bibnum};
+    my $items_count = defined $items ? scalar @$items : 0;
+    my $pull_count = $items_count <= $patrons_count->{$bibnum} ? $items_count : $patrons_count->{$bibnum};
+    if ( $pull_count == 0 ) {
+        next;
+    }
 
     # get available item types for each biblio
     my @res_itemtypes;
@@ -229,64 +263,56 @@ foreach my $bibnum ( @biblionumbers ){
             }
         )->get_column('itemtype');
     }
-    $reserves->{$bibnum}->{itemtypes} = \@res_itemtypes;
-
-    # get available locations for each biblio
-    $reserves->{$bibnum}->{locations} = [ uniq map { defined $_->location ? $_->location : () } @$items ];
-
-    # get available callnumbers for each biblio
-    $reserves->{$bibnum}->{callnumbers} = [ uniq map { defined $_->itemcallnumber ? $_->itemcallnumber : () } @$items ];
-
-    # get available enumchrons for each biblio
-    $reserves->{$bibnum}->{enumchrons} = [ uniq map { defined $_->enumchron ? $_->enumchron : () } @$items ];
-
-    # get available copynumbers for each biblio
-    $reserves->{$bibnum}->{copynumbers} = [ uniq map { defined $_->copynumber ? $_->copynumber : () } @$items ];
-
-    # get available barcodes for each biblio
-    $reserves->{$bibnum}->{barcodes} = [ uniq map { defined $_->barcode ? $_->barcode : () } @$items ];
+    $hold_info->{itemtypes} = \@res_itemtypes;
+
+    my $res_info = $all_holds->{$bibnum};
+
+    # get available values for each biblio
+    my $fields = {
+        collections     => 'ccode',
+        locations       => 'location',
+        callnumbers     => 'itemcallnumber',
+        enumchrons      => 'enumchron',
+        copynumbers     => 'copynumber',
+        barcodes        => 'barcode',
+        holdingbranches => 'holdingbranch'
+    };
+
+    while (
+        my ( $key, $field ) = each %$fields )
+    {
+        $hold_info->{$key} =
+          [ uniq map { defined $_->$field ? $_->$field : () } @$items ];
+    }
 
-    # get available holding branches for each biblio
-    $reserves->{$bibnum}->{holdingbranches} = [ uniq map { defined $_->holdingbranch ? $_->holdingbranch : () } @$items ];
+    if ( $res_info->item_group ) {
+       $hold_info->{barcodes} = [ uniq map { defined $_->barcode && $_->item_group && ( $_->item_group->id == $res_info->item_group_id )  ? $_->barcode : () } @$items ];
+    }
 
     # items available
-    my $items_count = scalar @$items;
-    $reserves->{$bibnum}->{items_count} = $items_count;
+    $hold_info->{items_count} = $items_count;
 
     # patrons with holds
-    my $patrons_count = Koha::Holds->search(
-        { biblionumber => $bibnum },
-        { select => [ { distinct => 'borrowernumber' } ] }
-    )->count;
-    $reserves->{$bibnum}->{patrons_count} = $patrons_count;
+    $hold_info->{patrons_count} = $patrons_count->{$bibnum};
 
-    my $pull_count = $items_count <= $patrons_count ? $items_count : $patrons_count;
-    if ( $pull_count == 0 ) {
-        delete($reserves->{$bibnum});
-        next;
-    }
-    $reserves->{$bibnum}->{pull_count} = $pull_count;
+    # number of items to pull
+    $hold_info->{pull_count} = $pull_count;
 
     # get other relevant information
-    my $res_info = Koha::Holds->search(
-        { 'reserve.biblionumber' => $bibnum, %where },
-        { prefetch => [ 'borrowernumber', 'itembib', 'biblio' ],
-          order_by => 'priority',
-          alias => 'reserve'
-        }
-    )->next; # get first item in results
-    $reserves->{$bibnum}->{borrower} = $res_info->borrower;
-    $reserves->{$bibnum}->{item} = $res_info->item;
-    $reserves->{$bibnum}->{biblio} = $res_info->biblio;
-    $reserves->{$bibnum}->{reserve} = $res_info;
+    $hold_info->{patron} = $res_info->patron;
+    $hold_info->{item}   = $res_info->item;
+    $hold_info->{biblio} = $res_info->biblio;
+    $hold_info->{hold}   = $res_info;
+    $hold_info->{item_group} = $res_info->item_group;
+
+    push @holds_info, $hold_info;
 }
 
 $template->param(
     todaysdate          => $today,
     from                => $startdate,
     to                  => $enddate,
-    reserves            => $reserves,
-    "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
+    holds_info          => \@holds_info,
     HoldsToPullStartDate => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL,
     HoldsToPullEndDate  => C4::Context->preference('ConfirmFutureHolds') || 0,
     messages            => \@messages,