LP 1819796: Fix method call on undefined value in generate_fines
[evergreen-equinox.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / Publisher / action.pm
index b81e847..4a49804 100644 (file)
@@ -3,16 +3,16 @@ use parent qw/OpenILS::Application::Storage::Publisher/;
 use strict;
 use warnings;
 use OpenSRF::Utils::Logger qw/:level :logger/;
-use OpenSRF::Utils qw/:datetime/;
+use OpenILS::Utils::DateTime qw/:datetime/;
 use OpenSRF::Utils::JSON;
 use OpenSRF::AppSession;
 use OpenSRF::EX qw/:try/;
 use OpenILS::Utils::Fieldmapper;
 use OpenILS::Utils::PermitHold;
+use OpenILS::Utils::CStoreEditor qw/:funcs/;
 use DateTime;
 use DateTime::Format::ISO8601;
 use OpenILS::Utils::Penalty;
-use POSIX qw(ceil);
 use OpenILS::Application::Circ::CircCommon;
 use OpenILS::Application::AppUtils;
 my $U = "OpenILS::Application::AppUtils";
@@ -58,12 +58,12 @@ sub isTrue {
 
 sub ou_ancestor_setting_value_or_cache {
     # cache should be specific to setting
-    my ($actor, $org_id, $setting, $cache) = @_;
+    my ($e, $org_id, $setting, $cache) = @_;
 
     if (not exists $cache->{$org_id}) {
-        my $r = $actor->request(
-            'open-ils.actor.ou_setting.ancestor_default', $org_id, $setting
-        )->gather(1);
+        my $r = $U->ou_ancestor_setting(
+            $org_id, $setting, $e # undef $e is ok
+        );
 
         if ($r) {
             $cache->{$org_id} = $r->{value};
@@ -147,16 +147,31 @@ __PACKAGE__->register_method(
 );
 
 
+# partition -- if set, an 'undef' will be inserted into the result list
+# between the last circulation and the first reservation.  This is
+# useful in conjunction with 'idlist' so the caller can tell what type 
+# of transaction the ID refers to without having to query the DB.
+# skip_no_fines - filter out transactions which will never be billed, 
+# e.g. circs with a $0 max fine or $0 recurring fine.
 sub overdue_circs {
     my $upper_interval = shift || '1 millennium';
     my $idlist = shift;
+    my $partition = shift;
+    my $skip_no_fines = shift;
+
+    # Only retrieve ID's in the initial query if that's all the caller needs.
+    my $contents = $idlist ? 'id' : '*';
+
+    my $fines_filter = $skip_no_fines ? 
+        'AND recurring_fine <> 0 AND max_fine <> 0' : '';
 
     my $c_t = action::circulation->table;
 
     my $sql = <<"    SQL";
-        SELECT  *
+        SELECT  $contents
           FROM  $c_t
           WHERE stop_fines IS NULL
+            $fines_filter
             AND due_date < ( CURRENT_TIMESTAMP - grace_period )
             AND fine_interval < ?::INTERVAL
     SQL
@@ -166,11 +181,17 @@ sub overdue_circs {
 
     my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
 
+    push (@circs, undef) if $partition;
+
+    $fines_filter = $skip_no_fines ? 
+        'AND fine_amount <> 0 AND max_fine <> 0' : '';
+
     $c_t = booking::reservation->table;
     $sql = <<"    SQL";
-        SELECT  *
+        SELECT  $contents
           FROM  $c_t
           WHERE return_time IS NULL
+            $fines_filter
             AND end_time < ( CURRENT_TIMESTAMP )
             AND fine_interval IS NOT NULL
             AND cancel_time IS NULL
@@ -289,7 +310,8 @@ sub grab_overdue {
 
     my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
     
-    $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
+    $client->respond( $idlist ? $_ : $_->to_fieldmapper ) 
+        for ( overdue_circs('', $idlist, undef, 1) );
 
     return undef;
 
@@ -302,7 +324,8 @@ __PACKAGE__->register_method(
     signature       => q/
         Return list of overdue circulations and reservations to be used for fine generation.
         Despite the name, this is not a generic method for retrieving all overdue loans,
-        as it excludes loans that have already hit the maximum fine limit.
+        as it excludes loans that have already hit the maximum fine limit
+        and transactions which do not accrue fines.
 /,
 );
 __PACKAGE__->register_method(
@@ -340,8 +363,8 @@ sub get_hold_sort_order {
     # Return only the keys of our hash, sorted by value,
     # keys for null values omitted.
     return [
-        grep { defined $row->{$_} } (
-            sort {$row->{$a} cmp $row->{$b}} keys %$row
+        sort { $row->{$a} <=> $row->{$b} } (
+          grep { defined $row->{$_} } keys %$row
         )
     ];
 }
@@ -397,6 +420,7 @@ sub build_hold_sort_clause {
                 COALESCE(dest_recv_time, source_send_time) AS moment
             FROM action.transit_copy
             WHERE target_copy = %d
+            AND cancel_time IS NULL
             ORDER BY moment DESC LIMIT 1
         ) UNION (
             SELECT
@@ -481,7 +505,8 @@ sub build_hold_sort_clause {
         WHERE
             atc.target_copy = %d AND
             (atc.dest = %d OR atc.source = %d) AND
-            atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
+            atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval) AND
+            atc.cancel_time IS NULL
     ) AS result FROM copy_has_not_been_home
 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
         $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
@@ -969,321 +994,96 @@ __PACKAGE__->register_method(
     method          => 'find_usr_summary_surveys',
 );
 
-sub seconds_to_interval_hash {
-        my $interval = shift;
-        my $limit = shift || 's';
-        $limit =~ s/^(.)/$1/o;
-
-        my %output;
-
-        my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
-        my ($year, $month, $week, $day, $hour, $minute, $second) =
-                ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
-
-        if ($y = int($interval / (60 * 60 * 24 * 365))) {
-                $output{$year} = $y;
-                $ym = $interval % (60 * 60 * 24 * 365);
-        } else {
-                $ym = $interval;
-        }
-        return %output if ($limit eq 'y');
-
-        if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
-                $output{$month} = $M;
-                $Mm = $ym % ((60 * 60 * 24 * 365)/12);
-        } else {
-                $Mm = $ym;
-        }
-        return %output if ($limit eq 'M');
-
-        if ($w = int($Mm / 604800)) {
-                $output{$week} = $w;
-                $wm = $Mm % 604800;
-        } else {
-                $wm = $Mm;
-        }
-        return %output if ($limit eq 'w');
-
-        if ($d = int($wm / 86400)) {
-                $output{$day} = $d;
-                $dm = $wm % 86400;
-        } else {
-                $dm = $wm;
-        }
-        return %output if ($limit eq 'd');
-
-        if ($h = int($dm / 3600)) {
-                $output{$hour} = $h;
-                $hm = $dm % 3600;
-        } else {
-                $hm = $dm;
-        }
-        return %output if ($limit eq 'h');
-
-        if ($m = int($hm / 60)) {
-                $output{$minute} = $m;
-                $mm = $hm % 60;
-        } else {
-                $mm = $hm;
-        }
-        return %output if ($limit eq 'm');
-
-        if ($s = int($mm)) {
-                $output{$second} = $s;
-        } else {
-                $output{$second} = 0 unless (keys %output);
-        }
-        return %output;
-}
-
-
 sub generate_fines {
     my $self = shift;
     my $client = shift;
-    my $circ = shift;
-    my $overbill = shift;
-
-    local $OpenILS::Application::Storage::WRITE = 1;
-
-    my @circs;
-    if ($circ) {
-        push @circs,
-            action::circulation->search_where( { id => $circ, stop_fines => undef } ),
-            booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
+    my $circ_id = shift;
+
+    my $circs;
+    my $editor = new_editor;
+    if ($circ_id) {
+        $circs = $editor->search_action_circulation( { id => $circ_id, stop_fines => undef } );
+        unless (@$circs) {
+            $circs = $editor->search_booking_reservation( { id => $circ_id, return_time => undef, cancel_time => undef } );
+        }
     } else {
-        push @circs, overdue_circs();
+        $circs = [overdue_circs(undef, 1, 1, 1)];
     }
 
-    my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
-
-    my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
-    for my $c (@circs) {
-
-        my $ctype = ref($c);
-        $ctype =~ s/^.+::(\w+)$/$1/;
-    
-        my $due_date_method = 'due_date';
-        my $target_copy_method = 'target_copy';
-        my $circ_lib_method = 'circ_lib';
-        my $recurring_fine_method = 'recurring_fine';
-        my $is_reservation = 0;
-        if ($ctype eq 'reservation') {
-            $is_reservation = 1;
-            $due_date_method = 'end_time';
-            $target_copy_method = 'current_resource';
-            $circ_lib_method = 'pickup_lib';
-            $recurring_fine_method = 'fine_amount';
-            next unless ($c->fine_interval);
-        }
-        #TODO: reservation grace periods
-        my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
-
-        eval {
-            if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
-                $log->debug("Cleaning up after previous transaction\n");
-                $self->method_lookup('open-ils.storage.transaction.rollback')->run;
-            }
-            $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
-            $log->info(
-                sprintf("Processing %s %d...",
-                    ($is_reservation ? "reservation" : "circ"), $c->id
-                )
-            );
-
-
-            my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
-    
-            my $due = $due_dt->epoch;
-            my $now = time;
-
-            my $fine_interval = $c->fine_interval;
-            $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
-            $fine_interval = interval_to_seconds( $fine_interval );
-    
-            if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
-                $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
-                $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
-                return;
-            }
-
-            if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {    
-                my $tz_offset_s = 0;
-                if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
-                    $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
-                }
-    
-                $due -= ($due % $fine_interval) + $tz_offset_s;
-                $now -= ($now % $fine_interval) + $tz_offset_s;
-            }
-    
-            $client->respond(
-                "ARG! Overdue $ctype ".$c->id.
-                " for item ".$c->$target_copy_method.
-                " (user ".$c->usr.").\n".
-                "\tItem was due on or before: ".localtime($due)."\n");
-    
-            my @fines = money::billing->search_where(
-                { xact => $c->id,
-                  btype => 1,
-                  billing_ts => { '>' => $c->$due_date_method } },
-                { order_by => 'billing_ts DESC'}
-            );
-
-            my $f_idx = 0;
-            my $fine = $fines[$f_idx] if (@fines);
-            if ($overbill) {
-                $fine = $fines[++$f_idx] while ($fine and $fine->voided);
-            }
-
-            my $current_fine_total = 0;
-            $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
-    
-            my $last_fine;
-            if ($fine) {
-                $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
-                $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
-            } else {
-                $log->info( "Potential first billing for circ ".$c->id );
-                $last_fine = $due;
-
-                $grace_period = OpenILS::Application::Circ::CircCommon->extend_grace_period($c->$circ_lib_method->to_fieldmapper->id,$c->$due_date_method,$grace_period,undef,$hoo{$c->$circ_lib_method});
-            }
-
-            return if ($last_fine > $now);
-            # Generate fines for each past interval, including the one we are inside
-            my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
-
-            if ( $last_fine == $due                         # we have no fines yet
-                 && $grace_period                           # and we have a grace period
-                 && $now < $due + $grace_period             # and some date math says were are within the grace period
-            ) {
-                $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
-                $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
-                return;
-            }
-
-            $client->respond( "\t$pending_fine_count pending fine(s)\n" );
-            return unless ($pending_fine_count);
-
-            my $recurring_fine = int($c->$recurring_fine_method * 100);
-            my $max_fine = int($c->max_fine * 100);
-
-            my $skip_closed_check = $U->ou_ancestor_setting_value(
-                $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
-            $skip_closed_check = $U->is_true($skip_closed_check);
-
-            my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
-                $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.truncate_to_max_fine');
-            $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
-
-            my ($latest_billing_ts, $latest_amount) = ('',0);
-            for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
-    
-                if ($current_fine_total >= $max_fine) {
-                    $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
-                    $client->respond(
-                        "\tMaximum fine level of ".$c->max_fine.
-                        " reached for this $ctype.\n".
-                        "\tNo more fines will be generated.\n" );
-                    last;
-                }
-                
-                # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
-                my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
-                my $current_bill_count = $bill;
-                while ( $current_bill_count ) {
-                    $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
-                    $current_bill_count--;
-                }
-
-                my $timestamptz = $billing_ts->strftime('%FT%T%z');
-                if (!$skip_closed_check) {
-                    my $dow = $billing_ts->day_of_week_0();
-                    my $dow_open = "dow_${dow}_open";
-                    my $dow_close = "dow_${dow}_close";
-
-                    if (my $h = $hoo{$c->$circ_lib_method}) {
-                        next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
-                    }
-    
-                    my @cl = actor::org_unit::closed_date->search_where(
-                            { close_start   => { '<=' => $timestamptz },
-                              close_end => { '>=' => $timestamptz },
-                              org_unit  => $c->$circ_lib_method }
-                    );
-                    next if (@cl);
-                }
-
-                # The billing amount for this billing normally ought to be the recurring fine amount.
-                # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
-                # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
-                my $this_billing_amount = $recurring_fine;
-                if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
-                    $this_billing_amount = ($max_fine - $current_fine_total);
-                }
-                $current_fine_total += $this_billing_amount;
-                $latest_amount += $this_billing_amount;
-                $latest_billing_ts = $timestamptz;
-
-                money::billing->create(
-                    { xact      => ''.$c->id,
-                      note      => "System Generated Overdue Fine",
-                      billing_type  => "Overdue materials",
-                      btype     => 1,
-                      amount    => sprintf('%0.2f', $this_billing_amount/100),
-                      billing_ts    => $timestamptz,
-                    }
-                );
-
-            }
-
-            $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
-                if ($latest_billing_ts and $latest_amount);
-
-            $self->method_lookup('open-ils.storage.transaction.commit')->run;
+    return OpenILS::Application::Circ::CircCommon->generate_fines({circs => $circs, conn => $client})
+}
+__PACKAGE__->register_method(
+    api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
+    api_level       => 1,
+    stream      => 1,
+    method          => 'generate_fines',
+);
 
-            if(1) { 
 
-                # Caluclate penalties inline
-                OpenILS::Utils::Penalty->calculate_penalties(
-                    undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
+sub MR_records_matching_format {
+    my $self = shift;
+    my $client = shift;
+    my $MR = shift;
+    my $filter = shift;
+    my $org = shift;
+    # include all visible copies, regardless of holdability
+    my $opac_visible = shift;
+
+    # find filters for MR holds
+    my $mr_filter;
+    if (defined($filter)) {
+        ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
+            'SELECT metabib.compile_composite_attr(?)',
+            {},
+            $filter
+        )};
+    }
 
-            } else {
+    my $records = [metabib::metarecord->retrieve($MR)->source_records];
 
-                # Calculate penalties with an aysnc call to the penalty server.  This approach
-                # may lead to duplicate penalties since multiple penalty processes for a
-                # given user may be running at the same time. Leave this here for reference 
-                # in case we later find that asyc calls are needed in some environments.
-                $penalty->request(
-                    'open-ils.penalty.patron_penalty.calculate',
-                    { patronid  => ''.$c->usr,
-                    context_org => ''.$c->$circ_lib_method,
-                    update  => 1,
-                    background  => 1,
-                    }
-                )->gather(1);
-            }
+    my $vis_q = 'asset.record_has_holdable_copy(?,?)';
+    if ($opac_visible) {
+        $vis_q = <<'        SQL';
+            EXISTS(
+                SELECT  1
+                  FROM  asset.patron_default_visibility_mask() mask,
+                        asset.copy_vis_attr_cache v
+                        JOIN asset.copy c ON (
+                            c.id = v.target_copy
+                            AND v.record = ?
+                            AND c.circ_lib IN (
+                                SELECT id FROM actor.org_unit_descendants(?)
+                            )
+                        )
+                  WHERE v.vis_attr_vector @@ mask.c_attrs::query_int
+            )
+        SQL
+    }
 
-        };
+    my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
+    my @args = ( $mr_filter, $org );
+    if (!$mr_filter) {
+        $q = "SELECT true WHERE $vis_q";
+        @args = ( $org );
+    }
 
-        if ($@) {
-            my $e = $@;
-            $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
-            $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
-            $self->method_lookup('open-ils.storage.transaction.rollback')->run;
-            last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
-        }
+    for my $r ( map { isTrue($_->deleted) ?  () : ($_->id) } @$records ) {
+        # the map{} below is tricky. it puts the record ID in front of each param. see $q above
+        $client->respond($r)
+            if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
     }
+
+    return; # discard final l-val
 }
 __PACKAGE__->register_method(
-    api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
+    api_name        => 'open-ils.storage.metarecord.filtered_records',
     api_level       => 1,
-    stream      => 1,
-    method          => 'generate_fines',
+    stream          => 1,
+    argc            => 2,
+    method          => 'MR_records_matching_format',
 );
 
 
-
 sub new_hold_copy_targeter {
     my $self = shift;
     my $client = shift;
@@ -1300,7 +1100,7 @@ sub new_hold_copy_targeter {
 
     try {
         if ($one_hold) {
-            $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
+            $self->method_lookup('open-ils.storage.transaction.begin')->run();
             $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
         } elsif ( $check_expire ) {
 
@@ -1385,6 +1185,7 @@ sub new_hold_copy_targeter {
 
     my @successes;
     my $actor = OpenSRF::AppSession->create('open-ils.actor');
+    my $editor = new_editor;
 
     my $target_when_closed = {};
     my $target_when_closed_if_at_pickup_lib = {};
@@ -1396,7 +1197,7 @@ sub new_hold_copy_targeter {
                 $log->debug("Cleaning up after previous transaction\n");
                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
             }
-            $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
+            $self->method_lookup('open-ils.storage.transaction.begin')->run();
             $log->info("Processing hold ".$hold->id."...\n");
 
             #first, re-fetch the hold, to make sure it's not captured already
@@ -1410,7 +1211,7 @@ sub new_hold_copy_targeter {
             $_->delete for (@oldmaps);
 
             if ($hold->expire_time) {
-                my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
+                my $ex_time = $parser->parse_datetime( clean_ISO8601( $hold->expire_time ) );
                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
 
                     # cancel cause = un-targeted expiration
@@ -1432,41 +1233,23 @@ sub new_hold_copy_targeter {
 
             my $all_copies = [];
 
-            # find filters for MR holds
-            my ($types, $formats, $lang);
-            if (defined($hold->holdable_formats)) {
-                ($types, $formats, $lang) = split '-', $hold->holdable_formats;
-            }
-
             # find all the potential copies
             if ($hold->hold_type eq 'M') {
-                my $records = [
-                    map {
-                        isTrue($_->deleted) ?  () : ($_->id)
-                    } metabib::metarecord->retrieve($hold->target)->source_records
-                ];
-                if(@$records > 0) {
-                    for my $r ( map
-                            {$_->record}
-                            metabib::record_descriptor
-                                ->search(
-                                    record => $records,
-                                    ( $types   ? (item_type => [split '', $types])   : () ),
-                                    ( $formats ? (item_form => [split '', $formats]) : () ),
-                                    ( $lang    ? (item_lang => $lang)                : () ),
-                                )
-                    ) {
-                        my ($rtree) = $self
-                            ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
-                            ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
-
-                        for my $cn ( @{ $rtree->call_numbers } ) {
-                            push @$all_copies,
-                                asset::copy->search_where(
-                                    { id => [map {$_->id} @{ $cn->copies }],
-                                      deleted => 'f' }
-                                ) if ($cn && @{ $cn->copies });
-                        }
+                for my $r_id (
+                    $self->method_lookup(
+                        'open-ils.storage.metarecord.filtered_records'
+                    )->run( $hold->target, $hold->holdable_formats )
+                ) {
+                    my ($rtree) = $self
+                        ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
+                        ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
+
+                    for my $cn ( @{ $rtree->call_numbers } ) {
+                        push @$all_copies,
+                            asset::copy->search_where(
+                                { id => [map {$_->id} @{ $cn->copies }],
+                                  deleted => 'f' }
+                            ) if ($cn && @{ $cn->copies });
                     }
                 }
             } elsif ($hold->hold_type eq 'T') {
@@ -1553,15 +1336,17 @@ sub new_hold_copy_targeter {
             $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
 
             # map the potentials, so that we can pick up checkins
-            # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
-            # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
+            my $hold_copy_map = {};
+            $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
+                for (
+                    map {
+                        action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
+                    } @$all_copies
+                );
+
             my $pu_lib = ''.$hold->pickup_lib;
-            my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold );
+            my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
             $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
-            for my $prox ( keys %$prox_list ) {
-                action::hold_copy_map->create( { proximity => $prox, hold => $hold->id, target_copy => $_ } )
-                    for keys( %{{ map { $_->id => 1 } @{$$prox_list{$prox}} }} );
-            }
 
             #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
 
@@ -1575,7 +1360,7 @@ sub new_hold_copy_targeter {
 
                 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
                     $ignore_closing = ou_ancestor_setting_value_or_cache(
-                        $actor,
+                        $editor,
                         ''.$c->circ_lib,
                         'circ.holds.target_when_closed_if_at_pickup_lib',
                         $target_when_closed_if_at_pickup_lib
@@ -1584,7 +1369,7 @@ sub new_hold_copy_targeter {
                 if (not $ignore_closing) {  # one more chance to find a reason
                                             # to ignore OU closedness.
                     $ignore_closing = ou_ancestor_setting_value_or_cache(
-                        $actor,
+                        $editor,
                         ''.$c->circ_lib,
                         'circ.holds.target_when_closed',
                         $target_when_closed
@@ -1645,16 +1430,16 @@ sub new_hold_copy_targeter {
             $prox_list = create_prox_list(
                 $self, $pu_lib,
                 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
-                $hold
+                $hold, $hold_copy_map
             );
 
             $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
 
-            my $min_prox = [ sort keys %$prox_list ]->[0];
+            my $min_prox = [ sort {$a<=>$b} keys %$prox_list ]->[0];
             my $best;
             if  ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
                 $best = $good_copies[0] if(scalar @good_copies);
-            } else {
+            } elsif (defined $min_prox) {
                 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
             }
 
@@ -1663,9 +1448,9 @@ sub new_hold_copy_targeter {
             if (!$best) {
                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
 
-                $self->{max_loops}{$pu_lib} = $actor->request(
-                    'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
-                )->gather(1);
+                $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
+                    $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
+                );
 
                 if (defined($self->{max_loops}{$pu_lib})) {
                     $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
@@ -1746,7 +1531,7 @@ sub new_hold_copy_targeter {
                         die "OK\n";
                     }
 
-                    $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold );
+                    $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
 
                     $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
 
@@ -1781,7 +1566,6 @@ sub new_hold_copy_targeter {
                     ) &&
                 ( OpenILS::Utils::PermitHold::permit_copy_hold(
                     { title => $old_best->call_number->record->to_fieldmapper,
-                      title_descriptor => $old_best->call_number->record->record_descriptor->next->to_fieldmapper,
                       patron => $hold->usr->to_fieldmapper,
                       copy => $old_best->to_fieldmapper,
                       requestor => $hold->requestor->to_fieldmapper,
@@ -1870,7 +1654,7 @@ sub process_recall {
 
     $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
 
-    my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
+    my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval));
 
     # Iterate over the checked-out copies to find a copy with a
     # loan period longer than the recall threshold:
@@ -1884,15 +1668,24 @@ sub process_recall {
         my $circ = $circs->[0];
         $log->info("Recalling circ ID : " . $circ->id);
 
+        my $old_due_date = DateTime::Format::ISO8601->parse_datetime(clean_ISO8601($circ->due_date));
+
         # Give the user a new due date of either a full recall threshold,
         # or the return interval, whichever is further in the future
-        my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
-        if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
+        my $threshold_date = DateTime::Format::ISO8601->parse_datetime(clean_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold));
+        if (DateTime->compare($threshold_date, $return_date) == 1) {
+            # extend $return_date to threshold
             $return_date = $threshold_date;
         }
+        # But don't go past the original due date
+        # (the threshold should not be past the due date, but manual edits can cause it to be)
+        if (DateTime->compare($return_date, $old_due_date) == 1) {
+            # truncate $return_date to due date
+            $return_date = $old_due_date;
+        }
 
         my $update_fields = {
-            due_date => $return_date,
+            due_date => $return_date->iso8601(),
             renewal_remaining => 0,
         };
 
@@ -1928,7 +1721,7 @@ sub reservation_targeter {
 
     try {
         if ($one_reservation) {
-            $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
+            $self->method_lookup('open-ils.storage.transaction.begin')->run();
             $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
         } else {
 
@@ -1956,7 +1749,7 @@ sub reservation_targeter {
                 $log->debug("Cleaning up after previous transaction\n");
                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
             }
-            $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
+            $self->method_lookup('open-ils.storage.transaction.begin')->run();
             $log->info("Processing reservation ".$bresv->id."...\n");
 
             #first, re-fetch the hold, to make sure it's not captured already
@@ -1965,7 +1758,7 @@ sub reservation_targeter {
 
             die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
 
-            my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
+            my $end_time = $parser->parse_datetime( clean_ISO8601( $bresv->end_time ) );
             if (DateTime->compare($end_time, DateTime->now) < 0) {
 
                 # cancel cause = un-targeted expiration
@@ -2040,8 +1833,8 @@ sub reservation_targeter {
 
                     if (@$circs) {
                         my $due_date = $circs->[0]->due_date;
-                        $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
-                        my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
+                        $due_date = $parser->parse_datetime( clean_ISO8601( $due_date ) );
+                        my $start_time = $parser->parse_datetime( clean_ISO8601( $bresv->start_time ) );
                         if (DateTime->compare($start_time, $due_date) < 0) {
                             $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
                             next;
@@ -2207,7 +2000,7 @@ sub choose_nearest_copy {
     my $hold = shift;
     my $prox_list = shift;
 
-    for my $p ( sort keys %$prox_list ) {
+    for my $p ( sort {$a<=>$b} keys %$prox_list ) {
         next unless (ref $$prox_list{$p});
 
         my @capturable = @{ $$prox_list{$p} };
@@ -2218,7 +2011,6 @@ sub choose_nearest_copy {
         while (my ($c) = splice(@capturable, $rand, 1)) {
             return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
                 { title => $c->call_number->record->to_fieldmapper,
-                  title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
                   patron => $hold->usr->to_fieldmapper,
                   copy => $c->to_fieldmapper,
                   requestor => $hold->requestor->to_fieldmapper,
@@ -2240,19 +2032,20 @@ sub create_prox_list {
     my $lib = shift;
     my $copies = shift;
     my $hold = shift;
-
-    my $actor = OpenSRF::AppSession->create('open-ils.actor');
+    my $hold_copy_map = shift || {};
 
     my %prox_list;
+    my $editor = new_editor;
     for my $cp (@$copies) {
-        my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold );
+        my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
+        ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
         next unless (defined($prox));
 
         my $copy_circ_lib = ''.$cp->circ_lib;
         # Fetch the weighting value for hold targeting, defaulting to 1
-        $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
-            'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
-        )->gather(1);
+        $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
+            $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
+        );
         $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
         $self->{target_weight}{$copy_circ_lib} ||= 1;
 
@@ -2323,32 +2116,332 @@ sub title_hold_capture {
     $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
 }
 
-sub metarecord_hold_capture {
+
+sub wide_hold_data {
     my $self = shift;
-    my $hold = shift;
+    my $client = shift;
+    my $restrictions = shift; # hashref of field restrictions {f1=>undef,f2=>[1,2,3],f3=>'foo',f4=>{not=>undef}}
+    my $order_by = shift; # arrayref of hashrefs of ORDER BY clause, [{field =>{dir=>'desc',nulls=>'last'}}]
+    my $limit = shift;
+    my $offset = shift;
 
-    my $titles;
-    try {
-        $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
+    $order_by = [$order_by] if (ref($order_by) !~ /ARRAY/);
     
-    } catch Error with {
-        my $e = shift;
-        die "Could not retrieve initial title list:\n\n$e\n";
-    };
+    $log->info('Received '. keys(%$restrictions) .' restrictions');
+    return 0 unless (ref $restrictions and keys %$restrictions);
+
+    # force this to either 'true' or 'false'
+    my $is_staff_request = delete($$restrictions{is_staff_request}) || 'false';
+    $is_staff_request = 'false' if (!grep {$is_staff_request eq $_} qw/true false/);
+
+    # option to filter for the latest captured hold for a given copy
+    my $last_captured_hold = delete($$restrictions{last_captured_hold}) || 'false';
+    $last_captured_hold = $last_captured_hold eq 'true' ? 1 : 0;
+
+    my $initial_condition = 'TRUE';
+    if ($last_captured_hold) {
+        $initial_condition = <<"        SQL";
+            (h.capture_time IS NULL OR (h.id = (
+                SELECT  id
+                  FROM  action.hold_request recheck
+                  WHERE recheck.current_copy = cp.id
+                  ORDER BY capture_time DESC
+                  LIMIT 1
+            )))
+        SQL
+    }
 
-    try {
-        my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
+    my $select = <<"    SQL";
+WITH
+    t_field AS (SELECT field FROM config.display_field_map WHERE name = 'title'),
+    a_field AS (SELECT field FROM config.display_field_map WHERE name = 'author')
+SELECT  h.id, h.request_time, h.capture_time, h.fulfillment_time, h.checkin_time,
+        h.return_time, h.prev_check_time, h.expire_time, h.cancel_time, h.cancel_cause,
+        h.cancel_note, h.target, h.current_copy, h.fulfillment_staff, h.fulfillment_lib,
+        h.request_lib, h.requestor, h.usr, h.selection_ou, h.selection_depth, h.pickup_lib,
+        h.hold_type, h.holdable_formats, h.phone_notify, h.email_notify, h.sms_notify,
+        h.sms_carrier, h.frozen, h.thaw_date, h.shelf_time, h.cut_in_line, h.mint_condition,
+        h.shelf_expire_time, h.current_shelf_lib, h.behind_desk,
+
+        CASE WHEN h.cancel_time IS NOT NULL THEN 6
+             WHEN h.frozen AND h.capture_time IS NULL THEN 7
+             WHEN h.current_shelf_lib IS NOT NULL AND h.current_shelf_lib <> h.pickup_lib THEN 8
+             WHEN h.fulfillment_time IS NOT NULL THEN 9
+             WHEN h.current_copy IS NULL THEN 1
+             WHEN h.capture_time IS NULL THEN 2
+             WHEN cp.status = 6 THEN 3
+             WHEN EXTRACT(EPOCH FROM COALESCE(NULLIF(BTRIM(hold_wait_time.value,'"'),''),'0 seconds')::INTERVAL) = 0 THEN 4
+             WHEN h.shelf_time + COALESCE(NULLIF(BTRIM(hold_wait_time.value,'"'),''),'0 seconds')::INTERVAL > NOW() THEN 5
+             ELSE 4
+        END AS hold_status,
+
+        (h.shelf_expire_time < NOW() OR h.cancel_time IS NOT NULL OR (h.current_shelf_lib IS NOT NULL AND h.current_shelf_lib <> h.pickup_lib)) AS clear_me,
+
+        (h.usr <> h.requestor) AS is_staff_hold,
+
+        cc.id AS cc_id, cc.label AS cc_label,
+
+        pl.id AS pl_id, pl.parent_ou AS pl_parent_ou, pl.ou_type AS pl_ou_type,
+        pl.ill_address AS pl_ill_address, pl.holds_address AS pl_holds_address,
+        pl.mailing_address AS pl_mailing_address, pl.billing_address AS pl_billing_address,
+        pl.shortname AS pl_shortname, pl.name AS pl_name, pl.email AS pl_email,
+        pl.phone AS pl_phone, pl.opac_visible AS pl_opac_visible, pl.fiscal_calendar AS pl_fiscal_calendar,
+
+        tr.id AS tr_id, tr.source_send_time AS tr_source_send_time, tr.dest_recv_time AS tr_dest_recv_time,
+        tr.target_copy AS tr_target_copy, tr.source AS tr_source, tr.dest AS tr_dest, tr.prev_hop AS tr_prev_hop,
+        tr.copy_status AS tr_copy_status, tr.persistant_transfer AS tr_persistant_transfer,
+        tr.prev_dest AS tr_prev_dest, tr.hold AS tr_hold, tr.cancel_time AS tr_cancel_time,
+
+        notes.count AS note_count,
+
+        u.id AS usr_id, u.card AS usr_card, u.profile AS usr_profile, u.usrname AS usr_usrname,
+        u.email AS usr_email, u.standing AS usr_standing, u.ident_type AS usr_ident_type,
+        u.ident_value AS usr_ident_value, u.ident_type2 AS usr_ident_type2,
+        u.ident_value2 AS usr_ident_value2, u.net_access_level AS usr_net_access_level,
+        u.photo_url AS usr_photo_url, u.prefix AS usr_prefix, u.first_given_name AS usr_first_given_name,
+        u.second_given_name AS usr_second_given_name, u.family_name AS usr_family_name,
+        u.suffix AS usr_suffix, u.alias AS usr_alias, u.day_phone AS usr_day_phone,
+        u.evening_phone AS usr_evening_phone, u.other_phone AS usr_other_phone,
+        u.mailing_address AS usr_mailing_address, u.billing_address AS usr_billing_address,
+        u.home_ou AS usr_home_ou, u.dob AS usr_dob, u.active AS usr_active,
+        u.master_account AS usr_master_account, u.super_user AS usr_super_user,
+        u.barred AS usr_barred, u.deleted AS usr_deleted, u.juvenile AS usr_juvenile,
+        u.usrgroup AS usr_usrgroup, u.claims_returned_count AS usr_claims_returned_count,
+        u.credit_forward_balance AS usr_credit_forward_balance, u.last_xact_id AS usr_last_xact_id,
+        u.alert_message AS usr_alert_message, u.create_date AS usr_create_date,
+        u.expire_date AS usr_expire_date, u.claims_never_checked_out_count AS usr_claims_never_checked_out_count,
+        u.last_update_time AS usr_last_update_time,
+
+        CASE WHEN u.alias IS NOT NULL THEN
+            u.alias
+        ELSE
+            u.first_given_name
+        END AS usr_alias_or_first_given_name,
+
+        CASE WHEN u.alias IS NOT NULL THEN
+            u.alias
+        ELSE
+            REGEXP_REPLACE(ARRAY_TO_STRING(ARRAY[
+                COALESCE(u.family_name, ''),
+                COALESCE(u.suffix, ''),
+                ', ',
+                COALESCE(u.prefix, ''),
+                COALESCE(u.first_given_name, ''),
+                COALESCE(u.second_given_name, '')
+            ], ' '), E'\\s+,', ',')
+        END AS usr_alias_or_display_name,
+
+        REGEXP_REPLACE(ARRAY_TO_STRING(ARRAY[
+            COALESCE(u.family_name, ''),
+            COALESCE(u.suffix, ''),
+            ', ',
+            COALESCE(u.prefix, ''),
+            COALESCE(u.first_given_name, ''),
+            COALESCE(u.second_given_name, '')
+        ], ' '), E'\\s+,', ',') AS usr_display_name,
+
+        uc.id AS ucard_id, uc.barcode AS ucard_barcode, uc.usr AS ucard_usr, uc.active AS ucard_active,
+
+        ru.id AS rusr_id, ru.card AS rusr_card, ru.profile AS rusr_profile, ru.usrname AS rusr_usrname,
+        ru.email AS rusr_email, ru.standing AS rusr_standing, ru.ident_type AS rusr_ident_type,
+        ru.ident_value AS rusr_ident_value, ru.ident_type2 AS rusr_ident_type2,
+        ru.ident_value2 AS rusr_ident_value2, ru.net_access_level AS rusr_net_access_level,
+        ru.photo_url AS rusr_photo_url, ru.prefix AS rusr_prefix, ru.first_given_name AS rusr_first_given_name,
+        ru.second_given_name AS rusr_second_given_name, ru.family_name AS rusr_family_name,
+        ru.suffix AS rusr_suffix, ru.alias AS rusr_alias, ru.day_phone AS rusr_day_phone,
+        ru.evening_phone AS rusr_evening_phone, ru.other_phone AS rusr_other_phone,
+        ru.mailing_address AS rusr_mailing_address, ru.billing_address AS rusr_billing_address,
+        ru.home_ou AS rusr_home_ou, ru.dob AS rusr_dob, ru.active AS rusr_active,
+        ru.master_account AS rusr_master_account, ru.super_user AS rusr_super_user,
+        ru.barred AS rusr_barred, ru.deleted AS rusr_deleted, ru.juvenile AS rusr_juvenile,
+        ru.usrgroup AS rusr_usrgroup, ru.claims_returned_count AS rusr_claims_returned_count,
+        ru.credit_forward_balance AS rusr_credit_forward_balance, ru.last_xact_id AS rusr_last_xact_id,
+        ru.alert_message AS rusr_alert_message, ru.create_date AS rusr_create_date,
+        ru.expire_date AS rusr_expire_date, ru.claims_never_checked_out_count AS rusr_claims_never_checked_out_count,
+        ru.last_update_time AS rusr_last_update_time,
+
+        ruc.id AS rucard_id, ruc.barcode AS rucard_barcode, ruc.usr AS rucard_usr, ruc.active AS rucard_active,
+
+        cp.id AS cp_id, cp.circ_lib AS cp_circ_lib, cp.creator AS cp_creator, cp.call_number AS cp_call_number,
+        cp.editor AS cp_editor, cp.create_date AS cp_create_date, cp.edit_date AS cp_edit_date,
+        cp.copy_number AS cp_copy_number, cp.status AS cp_status, cp.location AS cp_location,
+        cp.loan_duration AS cp_loan_duration, cp.fine_level AS cp_fine_level, cp.age_protect AS cp_age_protect,
+        cp.circulate AS cp_circulate, cp.deposit AS cp_deposit, cp.ref AS cp_ref, cp.holdable AS cp_holdable,
+        cp.deposit_amount AS cp_deposit_amount, cp.price AS cp_price, cp.barcode AS cp_barcode,
+        cp.circ_modifier AS cp_circ_modifier, cp.circ_as_type AS cp_circ_as_type, cp.dummy_title AS cp_dummy_title,
+        cp.dummy_author AS cp_dummy_author, cp.alert_message AS cp_alert_message, cp.opac_visible AS cp_opac_visible,
+        cp.deleted AS cp_deleted, cp.floating AS cp_floating, cp.dummy_isbn AS cp_dummy_isbn,
+        cp.status_changed_time AS cp_status_change_time, cp.active_date AS cp_active_date,
+        cp.mint_condition AS cp_mint_condition, cp.cost AS cp_cost,
+
+        cs.id AS cs_id, cs.name AS cs_name, cs.holdable AS cs_holdable, cs.opac_visible AS cs_opac_visible,
+        cs.copy_active AS cs_copy_active, cs.restrict_copy_delete AS cs_restrict_copy_delete,
+        cs.is_available AS cs_is_available,
+
+        siss.label AS issuance_label,
+
+        cn.id AS cn_id, cn.creator AS cn_creator, cn.create_date AS cn_create_date, cn.editor AS cn_editor,
+        cn.edit_date AS cn_edit_date, cn.record AS cn_record, cn.owning_lib AS cn_owning_lib, cn.label AS cn_label,
+        cn.deleted AS cn_deleted, cn.prefix AS cn_prefix, cn.suffix AS cn_suffix, cn.label_class AS cn_label_class,
+        cn.label_sortkey AS cn_label_sortkey,
+
+        p.id AS p_id, p.record AS p_record, p.label AS p_label, p.label_sortkey AS p_label_sortkey, p.deleted AS p_deleted,
+
+        acnp.label AS ancp_label, acns.label AS ancs_label,
+        TRIM(acnp.label || ' ' || cn.label || ' ' || acns.label) AS cn_full_label,
+
+        r.bib_record AS record_id,
+
+        t.value AS title,
+        a.value AS author,
+
+        acpl.id AS acpl_id, acpl.name AS acpl_name, acpl.owning_lib AS acpl_owning_lib, acpl.holdable AS acpl_holdable,
+        acpl.hold_verify AS acpl_hold_verify, acpl.opac_visible AS acpl_opac_visible, acpl.circulate AS acpl_circulate,
+        acpl.label_prefix AS acpl_label_prefix, acpl.label_suffix AS acpl_label_suffix,
+        acpl.checkin_alert AS acpl_checkin_alert, acpl.deleted AS acpl_deleted, acpl.url AS acpl_url,
+
+        COALESCE(acplo.position, acpl_ordered.fallback_position) AS copy_location_order_position,
+
+        ROW_NUMBER() OVER (
+            PARTITION BY r.bib_record
+            ORDER BY h.cut_in_line DESC NULLS LAST, h.request_time ASC
+        ) AS relative_queue_position,
+
+        EXTRACT(EPOCH FROM COALESCE(
+            NULLIF(BTRIM(default_estimated_wait_interval.value,'"'),''),
+            '0 seconds'
+        )::INTERVAL) AS default_estimated_wait,
+
+        EXTRACT(EPOCH FROM COALESCE(
+            NULLIF(BTRIM(min_estimated_wait_interval.value,'"'),''),
+            '0 seconds'
+        )::INTERVAL) AS min_estimated_wait,
+
+        COALESCE(hold_wait.potenials,0) AS potentials,
+        COALESCE(hold_wait.other_holds,0) AS other_holds,
+        COALESCE(hold_wait.total_wait_time,0) AS total_wait_time,
+
+        n.count AS notification_count,
+        n.max AS last_notification_time
+
+  FROM  action.hold_request h
+        JOIN reporter.hold_request_record r ON (r.id = h.id)
+        JOIN actor.usr u ON (u.id = h.usr)
+        JOIN actor.card uc ON (uc.id = u.card)
+        JOIN actor.usr ru ON (ru.id = h.requestor)
+        JOIN actor.card ruc ON (ruc.id = ru.card)
+        JOIN actor.org_unit pl ON (h.pickup_lib = pl.id)
+        JOIN t_field ON TRUE
+        JOIN a_field ON TRUE
+        LEFT JOIN action.hold_request_cancel_cause cc ON (h.cancel_cause = cc.id)
+        LEFT JOIN biblio.monograph_part p ON (h.hold_type = 'P' AND p.id = h.target)
+        LEFT JOIN serial.issuance siss ON (h.hold_type = 'I' AND siss.id = h.target)
+        LEFT JOIN asset.copy cp ON (h.current_copy = cp.id OR (h.hold_type IN ('C','F','R') AND cp.id = h.target))
+        LEFT JOIN config.copy_status cs ON (cp.status = cs.id)
+        LEFT JOIN asset.copy_location acpl ON (cp.location = acpl.id)
+        LEFT JOIN asset.copy_location_order acplo ON (cp.location = acplo.location AND cp.circ_lib = acplo.org)
+        LEFT JOIN (
+            SELECT *, (ROW_NUMBER() OVER (ORDER BY name) + 1000000) AS fallback_position
+            FROM asset.copy_location
+        ) acpl_ordered ON (acpl_ordered.id = cp.location)
+        LEFT JOIN asset.call_number cn ON (cn.id = cp.call_number OR (h.hold_type = 'V' AND cn.id = h.target))
+        LEFT JOIN asset.call_number_prefix acnp ON (cn.prefix = acnp.id)
+        LEFT JOIN asset.call_number_suffix acns ON (cn.suffix = acns.id)
+        LEFT JOIN LATERAL (SELECT * FROM action.hold_transit_copy WHERE h.id = hold ORDER BY id DESC LIMIT 1) tr ON TRUE
+        LEFT JOIN LATERAL (SELECT COUNT(*) FROM action.hold_request_note WHERE h.id = hold AND (pub = TRUE OR staff = $is_staff_request)) notes ON TRUE
+        LEFT JOIN LATERAL (SELECT COUNT(*), MAX(notify_time) FROM action.hold_notification WHERE h.id = hold) n ON TRUE
+        LEFT JOIN LATERAL (SELECT FIRST(value) AS value FROM metabib.display_entry WHERE source = r.bib_record AND field = t_field.field) t ON TRUE
+        LEFT JOIN LATERAL (SELECT FIRST(value) AS value FROM metabib.display_entry WHERE source = r.bib_record AND field = a_field.field) a ON TRUE
+        LEFT JOIN LATERAL actor.org_unit_ancestor_setting('circ.holds.default_estimated_wait_interval',u.home_ou) AS default_estimated_wait_interval ON TRUE
+        LEFT JOIN LATERAL actor.org_unit_ancestor_setting('circ.holds.min_estimated_wait_interval',u.home_ou) AS min_estimated_wait_interval ON TRUE
+        LEFT JOIN LATERAL actor.org_unit_ancestor_setting('circ.hold_shelf_status_delay',h.pickup_lib) AS hold_wait_time ON TRUE,
+        LATERAL (
+            SELECT  COUNT(*) AS potenials,
+                    COUNT(DISTINCT hold) AS other_holds,
+                    SUM(
+                        EXTRACT(EPOCH FROM
+                            COALESCE(
+                                cm.avg_wait_time,
+                                COALESCE(NULLIF(BTRIM(default_estimated_wait_interval.value,'"'),''),'0 seconds')::INTERVAL
+                            )
+                        )
+                    ) AS total_wait_time
+              FROM  action.hold_copy_map m
+                    JOIN asset.copy cp ON (cp.id = m.target_copy)
+                    LEFT JOIN config.circ_modifier cm ON (cp.circ_modifier = cm.code)
+              WHERE m.hold = h.id
+        ) AS hold_wait
+  WHERE $initial_condition
+    SQL
 
-        $titles = [ biblio::record_entry->search( id => \@recs ) ];
-    
-    } catch Error with {
-        my $e = shift;
-        die "Could not retrieve format-pruned title list:\n\n$e\n";
-    };
+    my %field_map = (
+        record_id => 'r.bib_record',
+        usr_id => 'u.id',
+        cs_id => 'cs.id',
+        cp_id => 'cp.id',
+        cp_deleted => 'cp.deleted',
+        cancel_time => 'h.cancel_time',
+        tr_cancel_time => 'tr.cancel_time',
+    );
+
+    my $restricted = 0;
+    for my $r (keys %$restrictions) {
+        my $real = $field_map{$r} || $r;
+        next if ($r =~ /[^a-z_.]/); # skip obvious bad inputs
 
+        my $not = '';
+        if (ref($$restrictions{$r}) and ref($$restrictions{$r}) =~ /HASH/) {
+            $not = 'NOT';
+            $$restrictions{$r} = $$restrictions{$r}{not};
+        }
+
+        if (!defined($$restrictions{$r})) { 
+            $select .= " AND $real IS $not NULL ";
+        } elsif (ref($$restrictions{$r})) { 
+            $select .= " AND $real $not IN (\$_$$\$" . join("\$_$$\$,\$_$$\$", @{$$restrictions{$r}}) . "\$_$$\$)";
+        } else {
+            $not = '!' if $not;
+            $select .= " AND $real $not= \$_$$\$$$restrictions{$r}\$_$$\$";
+        }
+
+        $restricted++;
+    }
+
+    return 0 unless $restricted;
+
+    my @ob;
+    for my $o (@$order_by) {
+        next unless $o;
+        my ($r) = keys %$o;
+        next if ($r =~ /[^a-z_.]/); # skip obvious bad inputs
+        my $real = $field_map{$r} || $r;
+        push(@ob, $real);
+        $ob[-1] .= ' DESC' if ($$o{$r}->{dir} and $$o{$r}->{dir} =~ /^d/i);
+        $ob[-1] .= ' NULLS LAST' if ($$o{$r}->{nulls} and $$o{$r}->{nulls} =~ /^l/i);
+        $ob[-1] .= ' NULLS FIRST' if ($$o{$r}->{nulls} and $$o{$r}->{nulls} =~ /^f/i);
+    }
 
-    $cache{titles}{$_->id} = $_ for (@$titles);
-    $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
+    $select .= ' ORDER BY ' . join(', ', @ob) if (@ob);
+    $select .= ' LIMIT ' . $limit if ($limit and $limit =~ /^\d+$/);
+    $select .= ' OFFSET ' . $offset if ($offset and $offset =~ /^\d+$/);
+
+    my $sth = action::hold_request->db_Main->prepare($select);
+    $sth->execute();
+
+    my @list = $sth->fetchall_hash;
+    $client->respond(scalar(@list)); # send the row count first, for progress tracking
+    $client->respond( $_ ) for (@list);
+
+    $client->respond_complete;
 }
+__PACKAGE__->register_method(
+    api_name        => 'open-ils.storage.action.live_holds.wide_hash',
+    api_level       => 1,
+    stream          => 1,
+    max_bundle_count=> 1,
+    method          => 'wide_hold_data',
+);
+
 
 1;
+