]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/110.hold_matrix.sql
LP1894131 Sticky catalog holdings org select
[Evergreen.git] / Open-ILS / src / sql / Pg / 110.hold_matrix.sql
1 /*
2
3 -- If, for some reason, you need to reload this chunk of the schema
4 -- just use the following two statements to remove the tables before
5 -- running the rest of the file.  See 950.data.seed-values.sql for
6 -- the one default entry to add back to config.hold_matrix_matchpoint.
7
8 DROP TABLE config.hold_matrix_matchpoint CASCADE;
9 DROP TABLE config.hold_matrix_test CASCADE;
10
11 */
12
13 BEGIN;
14
15
16 --
17 --                 ****** Which ruleset and tests to use *******
18 --
19 -- * Most specific range for org_unit and grp wins.
20 --
21 -- * circ_modifier match takes precidence over marc_type match, if circ_modifier is set here
22 --
23 -- * marc_type is first checked against the circ_as_type from the copy, then the item type from the marc record
24 --
25 -- * If neither circ_modifier nor marc_type is set (both are NULLABLE) then the entry defines the default
26 --   ruleset and tests for the OU + group (like BOOK in PINES)
27 --
28
29
30
31 CREATE TABLE config.hold_matrix_matchpoint (
32     id                      SERIAL    PRIMARY KEY,
33     active                  BOOL    NOT NULL DEFAULT TRUE,
34     strict_ou_match         BOOL    NOT NULL DEFAULT FALSE,
35     -- Match Fields
36     user_home_ou            INT        REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
37     request_ou              INT        REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
38     pickup_ou               INT        REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
39     item_owning_ou          INT        REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
40     item_circ_ou            INT        REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
41     usr_grp                 INT        REFERENCES permission.grp_tree (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top applicable group from the group tree; will need descendents and prox functions for filtering
42     requestor_grp           INT        NOT NULL REFERENCES permission.grp_tree (id) DEFERRABLE INITIALLY DEFERRED,    -- Set to the top applicable group from the group tree; will need descendents and prox functions for filtering
43     circ_modifier           TEXT    REFERENCES config.circ_modifier (code) DEFERRABLE INITIALLY DEFERRED,
44     marc_type               TEXT,
45     marc_form               TEXT,
46     marc_bib_level          TEXT,
47     marc_vr_format          TEXT,
48     juvenile_flag           BOOL,
49     ref_flag                BOOL,
50     item_age                INTERVAL,
51     -- "Result" Fields
52     holdable                BOOL    NOT NULL DEFAULT TRUE,                -- Hard "can't hold" flag requiring an override
53     distance_is_from_owner  BOOL    NOT NULL DEFAULT FALSE,                -- How to calculate transit_range.  True means owning lib, false means copy circ lib
54     transit_range           INT        REFERENCES actor.org_unit_type (id) DEFERRABLE INITIALLY DEFERRED,        -- Can circ inside range of cn.owner/cp.circ_lib at depth of the org_unit_type specified here
55     max_holds               INT,                            -- Total hold requests must be less than this, NULL means skip (always pass)
56     include_frozen_holds    BOOL    NOT NULL DEFAULT TRUE,                -- Include frozen hold requests in the count for max_holds test
57     stop_blocked_user       BOOL    NOT NULL DEFAULT FALSE,                -- Stop users who cannot check out items from placing holds
58     age_hold_protect_rule   INT        REFERENCES config.rule_age_hold_protect (id) DEFERRABLE INITIALLY DEFERRED,    -- still not sure we want to move this off the copy
59     description             TEXT
60 );
61
62 -- Nulls don't count for a constraint match, so we have to coalesce them into something that does.
63 CREATE UNIQUE INDEX chmm_once_per_paramset ON config.hold_matrix_matchpoint (COALESCE(user_home_ou::TEXT, ''), COALESCE(request_ou::TEXT, ''), COALESCE(pickup_ou::TEXT, ''), COALESCE(item_owning_ou::TEXT, ''), COALESCE(item_circ_ou::TEXT, ''), COALESCE(usr_grp::TEXT, ''), COALESCE(requestor_grp::TEXT, ''), COALESCE(circ_modifier, ''), COALESCE(marc_type, ''), COALESCE(marc_form, ''), COALESCE(marc_bib_level, ''), COALESCE(marc_vr_format, ''), COALESCE(juvenile_flag::TEXT, ''), COALESCE(ref_flag::TEXT, ''), COALESCE(item_age::TEXT, '')) WHERE active;
64
65 CREATE OR REPLACE FUNCTION action.find_hold_matrix_matchpoint(pickup_ou integer, request_ou integer, match_item bigint, match_user integer, match_requestor integer)
66   RETURNS integer AS
67 $func$
68 DECLARE
69     requestor_object    actor.usr%ROWTYPE;
70     user_object         actor.usr%ROWTYPE;
71     item_object         asset.copy%ROWTYPE;
72     item_cn_object      asset.call_number%ROWTYPE;
73     my_item_age         INTERVAL;
74     rec_descriptor      metabib.rec_descriptor%ROWTYPE;
75     matchpoint          config.hold_matrix_matchpoint%ROWTYPE;
76     weights             config.hold_matrix_weights%ROWTYPE;
77     denominator         NUMERIC(6,2);
78     v_pickup_ou         ALIAS FOR pickup_ou;
79     v_request_ou         ALIAS FOR request_ou;
80 BEGIN
81     SELECT INTO user_object         * FROM actor.usr                WHERE id = match_user;
82     SELECT INTO requestor_object    * FROM actor.usr                WHERE id = match_requestor;
83     SELECT INTO item_object         * FROM asset.copy               WHERE id = match_item;
84     SELECT INTO item_cn_object      * FROM asset.call_number        WHERE id = item_object.call_number;
85     SELECT INTO rec_descriptor      * FROM metabib.rec_descriptor   WHERE record = item_cn_object.record;
86
87     SELECT INTO my_item_age age(coalesce(item_object.active_date, now()));
88
89     -- The item's owner should probably be the one determining if the item is holdable
90     -- How to decide that is debatable. Decided to default to the circ library (where the item lives)
91     -- This flag will allow for setting it to the owning library (where the call number "lives")
92     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.weight_owner_not_circ' AND enabled;
93
94     -- Grab the closest set circ weight setting.
95     IF NOT FOUND THEN
96         -- Default to circ library
97         SELECT INTO weights hw.*
98           FROM config.weight_assoc wa
99                JOIN config.hold_matrix_weights hw ON (hw.id = wa.hold_weights)
100                JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) d ON (wa.org_unit = d.id)
101           WHERE active
102           ORDER BY d.distance
103           LIMIT 1;
104     ELSE
105         -- Flag is set, use owning library
106         SELECT INTO weights hw.*
107           FROM config.weight_assoc wa
108                JOIN config.hold_matrix_weights hw ON (hw.id = wa.hold_weights)
109                JOIN actor.org_unit_ancestors_distance( item_cn_object.owning_lib ) d ON (wa.org_unit = d.id)
110           WHERE active
111           ORDER BY d.distance
112           LIMIT 1;
113     END IF;
114
115     -- No weights? Bad admin! Defaults to handle that anyway.
116     IF weights.id IS NULL THEN
117         weights.user_home_ou    := 5.0;
118         weights.request_ou      := 5.0;
119         weights.pickup_ou       := 5.0;
120         weights.item_owning_ou  := 5.0;
121         weights.item_circ_ou    := 5.0;
122         weights.usr_grp         := 7.0;
123         weights.requestor_grp   := 8.0;
124         weights.circ_modifier   := 4.0;
125         weights.marc_type       := 3.0;
126         weights.marc_form       := 2.0;
127         weights.marc_bib_level  := 1.0;
128         weights.marc_vr_format  := 1.0;
129         weights.juvenile_flag   := 4.0;
130         weights.ref_flag        := 0.0;
131         weights.item_age        := 0.0;
132     END IF;
133
134     -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
135     -- If you break your org tree with funky parenting this may be wrong
136     -- Note: This CTE is duplicated in the find_circ_matrix_matchpoint function, and it may be a good idea to split it off to a function
137     -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
138     WITH all_distance(distance) AS (
139             SELECT depth AS distance FROM actor.org_unit_type
140         UNION
141             SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
142         )
143     SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
144
145     -- To ATTEMPT to make this work like it used to, make it reverse the user/requestor profile ids.
146     -- This may be better implemented as part of the upgrade script?
147     -- Set usr_grp = requestor_grp, requestor_grp = 1 or something when this flag is already set
148     -- Then remove this flag, of course.
149     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.usr_not_requestor' AND enabled;
150
151     IF FOUND THEN
152         -- Note: This, to me, is REALLY hacky. I put it in anyway.
153         -- If you can't tell, this is a single call swap on two variables.
154         SELECT INTO user_object.profile, requestor_object.profile
155                     requestor_object.profile, user_object.profile;
156     END IF;
157
158     -- Select the winning matchpoint into the matchpoint variable for returning
159     SELECT INTO matchpoint m.*
160       FROM  config.hold_matrix_matchpoint m
161             /*LEFT*/ JOIN permission.grp_ancestors_distance( requestor_object.profile ) rpgad ON m.requestor_grp = rpgad.id
162             LEFT JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.usr_grp = upgad.id
163             LEFT JOIN actor.org_unit_ancestors_distance( v_pickup_ou ) puoua ON m.pickup_ou = puoua.id
164             LEFT JOIN actor.org_unit_ancestors_distance( v_request_ou ) rqoua ON m.request_ou = rqoua.id
165             LEFT JOIN actor.org_unit_ancestors_distance( item_cn_object.owning_lib ) cnoua ON m.item_owning_ou = cnoua.id
166             LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.item_circ_ou = iooua.id
167             LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou  ) uhoua ON m.user_home_ou = uhoua.id
168       WHERE m.active
169             -- Permission Groups
170          -- AND (m.requestor_grp        IS NULL OR upgad.id IS NOT NULL) -- Optional Requestor Group?
171             AND (m.usr_grp              IS NULL OR upgad.id IS NOT NULL)
172             -- Org Units
173             AND (m.pickup_ou            IS NULL OR (puoua.id IS NOT NULL AND (puoua.distance = 0 OR NOT m.strict_ou_match)))
174             AND (m.request_ou           IS NULL OR (rqoua.id IS NOT NULL AND (rqoua.distance = 0 OR NOT m.strict_ou_match)))
175             AND (m.item_owning_ou       IS NULL OR (cnoua.id IS NOT NULL AND (cnoua.distance = 0 OR NOT m.strict_ou_match)))
176             AND (m.item_circ_ou         IS NULL OR (iooua.id IS NOT NULL AND (iooua.distance = 0 OR NOT m.strict_ou_match)))
177             AND (m.user_home_ou         IS NULL OR (uhoua.id IS NOT NULL AND (uhoua.distance = 0 OR NOT m.strict_ou_match)))
178             -- Static User Checks
179             AND (m.juvenile_flag        IS NULL OR m.juvenile_flag = user_object.juvenile)
180             -- Static Item Checks
181             AND (m.circ_modifier        IS NULL OR m.circ_modifier = item_object.circ_modifier)
182             AND (m.marc_type            IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
183             AND (m.marc_form            IS NULL OR m.marc_form = rec_descriptor.item_form)
184             AND (m.marc_bib_level       IS NULL OR m.marc_bib_level = rec_descriptor.bib_level)
185             AND (m.marc_vr_format       IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
186             AND (m.ref_flag             IS NULL OR m.ref_flag = item_object.ref)
187             AND (m.item_age             IS NULL OR (my_item_age IS NOT NULL AND m.item_age > my_item_age))
188       ORDER BY
189             -- Permission Groups
190             CASE WHEN rpgad.distance    IS NOT NULL THEN 2^(2*weights.requestor_grp - (rpgad.distance/denominator)) ELSE 0.0 END +
191             CASE WHEN upgad.distance    IS NOT NULL THEN 2^(2*weights.usr_grp - (upgad.distance/denominator)) ELSE 0.0 END +
192             -- Org Units
193             CASE WHEN puoua.distance    IS NOT NULL THEN 2^(2*weights.pickup_ou - (puoua.distance/denominator)) ELSE 0.0 END +
194             CASE WHEN rqoua.distance    IS NOT NULL THEN 2^(2*weights.request_ou - (rqoua.distance/denominator)) ELSE 0.0 END +
195             CASE WHEN cnoua.distance    IS NOT NULL THEN 2^(2*weights.item_owning_ou - (cnoua.distance/denominator)) ELSE 0.0 END +
196             CASE WHEN iooua.distance    IS NOT NULL THEN 2^(2*weights.item_circ_ou - (iooua.distance/denominator)) ELSE 0.0 END +
197             CASE WHEN uhoua.distance    IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
198             -- Static User Checks       -- Note: 4^x is equiv to 2^(2*x)
199             CASE WHEN m.juvenile_flag   IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
200             -- Static Item Checks
201             CASE WHEN m.circ_modifier   IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
202             CASE WHEN m.marc_type       IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
203             CASE WHEN m.marc_form       IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
204             CASE WHEN m.marc_vr_format  IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
205             CASE WHEN m.ref_flag        IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END +
206             -- Item age has a slight adjustment to weight based on value.
207             -- This should ensure that a shorter age limit comes first when all else is equal.
208             -- NOTE: This assumes that intervals will normally be in days.
209             CASE WHEN m.item_age            IS NOT NULL THEN 4^weights.item_age - 86400/EXTRACT(EPOCH FROM m.item_age) ELSE 0.0 END DESC,
210             -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
211             -- This prevents "we changed the table order by updating a rule, and we started getting different results"
212             m.id;
213
214     -- Return just the ID for now
215     RETURN matchpoint.id;
216 END;
217 $func$ LANGUAGE 'plpgsql';
218
219 CREATE TYPE action.matrix_test_result AS ( success BOOL, matchpoint INT, fail_part TEXT );
220 CREATE OR REPLACE FUNCTION action.hold_request_permit_test( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT, retargetting BOOL ) RETURNS SETOF action.matrix_test_result AS $func$
221 DECLARE
222     matchpoint_id        INT;
223     user_object        actor.usr%ROWTYPE;
224     age_protect_object    config.rule_age_hold_protect%ROWTYPE;
225     standing_penalty    config.standing_penalty%ROWTYPE;
226     transit_range_ou_type    actor.org_unit_type%ROWTYPE;
227     transit_source        actor.org_unit%ROWTYPE;
228     item_object        asset.copy%ROWTYPE;
229     item_cn_object     asset.call_number%ROWTYPE;
230     item_status_object  config.copy_status%ROWTYPE;
231     item_location_object    asset.copy_location%ROWTYPE;
232     ou_skip              actor.org_unit_setting%ROWTYPE;
233     calc_age_prox        actor.org_unit_setting%ROWTYPE;
234     result            action.matrix_test_result;
235     hold_test        config.hold_matrix_matchpoint%ROWTYPE;
236     use_active_date   TEXT;
237     prox_ou           INT;
238     age_protect_date  TIMESTAMP WITH TIME ZONE;
239     hold_count        INT;
240     hold_transit_prox    NUMERIC;
241     frozen_hold_count    INT;
242     context_org_list    INT[];
243     done            BOOL := FALSE;
244     hold_penalty TEXT;
245     v_pickup_ou ALIAS FOR pickup_ou;
246     v_request_ou ALIAS FOR request_ou;
247     item_prox INT;
248     pickup_prox INT;
249 BEGIN
250     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
251     SELECT INTO context_org_list ARRAY_AGG(id) FROM actor.org_unit_full_path( v_pickup_ou );
252
253     result.success := TRUE;
254
255     -- The HOLD penalty block only applies to new holds.
256     -- The CAPTURE penalty block applies to existing holds.
257     hold_penalty := 'HOLD';
258     IF retargetting THEN
259         hold_penalty := 'CAPTURE';
260     END IF;
261
262     -- Fail if we couldn't find a user
263     IF user_object.id IS NULL THEN
264         result.fail_part := 'no_user';
265         result.success := FALSE;
266         done := TRUE;
267         RETURN NEXT result;
268         RETURN;
269     END IF;
270
271     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
272
273     -- Fail if we couldn't find a copy
274     IF item_object.id IS NULL THEN
275         result.fail_part := 'no_item';
276         result.success := FALSE;
277         done := TRUE;
278         RETURN NEXT result;
279         RETURN;
280     END IF;
281
282     SELECT INTO matchpoint_id action.find_hold_matrix_matchpoint(v_pickup_ou, v_request_ou, match_item, match_user, match_requestor);
283     result.matchpoint := matchpoint_id;
284
285     SELECT INTO ou_skip * FROM actor.org_unit_setting WHERE name = 'circ.holds.target_skip_me' AND org_unit = item_object.circ_lib;
286
287     -- Fail if the circ_lib for the item has circ.holds.target_skip_me set to true
288     IF ou_skip.id IS NOT NULL AND ou_skip.value = 'true' THEN
289         result.fail_part := 'circ.holds.target_skip_me';
290         result.success := FALSE;
291         done := TRUE;
292         RETURN NEXT result;
293         RETURN;
294     END IF;
295
296     -- Fail if user is barred
297     IF user_object.barred IS TRUE THEN
298         result.fail_part := 'actor.usr.barred';
299         result.success := FALSE;
300         done := TRUE;
301         RETURN NEXT result;
302         RETURN;
303     END IF;
304
305     SELECT INTO item_cn_object * FROM asset.call_number WHERE id = item_object.call_number;
306     SELECT INTO item_status_object * FROM config.copy_status WHERE id = item_object.status;
307     SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
308
309     -- Fail if we couldn't find any matchpoint (requires a default)
310     IF matchpoint_id IS NULL THEN
311         result.fail_part := 'no_matchpoint';
312         result.success := FALSE;
313         done := TRUE;
314         RETURN NEXT result;
315         RETURN;
316     END IF;
317
318     SELECT INTO hold_test * FROM config.hold_matrix_matchpoint WHERE id = matchpoint_id;
319
320     IF hold_test.holdable IS FALSE THEN
321         result.fail_part := 'config.hold_matrix_test.holdable';
322         result.success := FALSE;
323         done := TRUE;
324         RETURN NEXT result;
325     END IF;
326
327     IF item_object.holdable IS FALSE THEN
328         result.fail_part := 'item.holdable';
329         result.success := FALSE;
330         done := TRUE;
331         RETURN NEXT result;
332     END IF;
333
334     IF item_status_object.holdable IS FALSE THEN
335         result.fail_part := 'status.holdable';
336         result.success := FALSE;
337         done := TRUE;
338         RETURN NEXT result;
339     END IF;
340
341     IF item_location_object.holdable IS FALSE THEN
342         result.fail_part := 'location.holdable';
343         result.success := FALSE;
344         done := TRUE;
345         RETURN NEXT result;
346     END IF;
347
348     IF hold_test.transit_range IS NOT NULL THEN
349         SELECT INTO transit_range_ou_type * FROM actor.org_unit_type WHERE id = hold_test.transit_range;
350         IF hold_test.distance_is_from_owner THEN
351             SELECT INTO transit_source ou.* FROM actor.org_unit ou JOIN asset.call_number cn ON (cn.owning_lib = ou.id) WHERE cn.id = item_object.call_number;
352         ELSE
353             SELECT INTO transit_source * FROM actor.org_unit WHERE id = item_object.circ_lib;
354         END IF;
355
356         PERFORM * FROM actor.org_unit_descendants( transit_source.id, transit_range_ou_type.depth ) WHERE id = v_pickup_ou;
357
358         IF NOT FOUND THEN
359             result.fail_part := 'transit_range';
360             result.success := FALSE;
361             done := TRUE;
362             RETURN NEXT result;
363         END IF;
364     END IF;
365
366     -- Proximity of user's home_ou to the pickup_lib to see if penalty should be ignored.
367     SELECT INTO pickup_prox prox FROM actor.org_unit_proximity WHERE from_org = user_object.home_ou AND to_org = v_pickup_ou;
368     -- Proximity of user's home_ou to the items' lib to see if penalty should be ignored.
369     IF hold_test.distance_is_from_owner THEN
370         SELECT INTO item_prox prox FROM actor.org_unit_proximity WHERE from_org = user_object.home_ou AND to_org = item_cn_object.owning_lib;
371     ELSE
372         SELECT INTO item_prox prox FROM actor.org_unit_proximity WHERE from_org = user_object.home_ou AND to_org = item_object.circ_lib;
373     END IF;
374
375     FOR standing_penalty IN
376         SELECT  DISTINCT csp.*
377           FROM  actor.usr_standing_penalty usp
378                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
379           WHERE usr = match_user
380                 AND usp.org_unit IN ( SELECT * FROM unnest(context_org_list) )
381                 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
382                 AND (csp.ignore_proximity IS NULL OR csp.ignore_proximity < item_prox
383                      OR csp.ignore_proximity < pickup_prox)
384                 AND csp.block_list LIKE '%' || hold_penalty || '%' LOOP
385
386         result.fail_part := standing_penalty.name;
387         result.success := FALSE;
388         done := TRUE;
389         RETURN NEXT result;
390     END LOOP;
391
392     IF hold_test.stop_blocked_user IS TRUE THEN
393         FOR standing_penalty IN
394             SELECT  DISTINCT csp.*
395               FROM  actor.usr_standing_penalty usp
396                     JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
397               WHERE usr = match_user
398                     AND usp.org_unit IN ( SELECT * FROM unnest(context_org_list) )
399                     AND (usp.stop_date IS NULL or usp.stop_date > NOW())
400                     AND csp.block_list LIKE '%CIRC%' LOOP
401
402             result.fail_part := standing_penalty.name;
403             result.success := FALSE;
404             done := TRUE;
405             RETURN NEXT result;
406         END LOOP;
407     END IF;
408
409     IF hold_test.max_holds IS NOT NULL AND NOT retargetting THEN
410         SELECT    INTO hold_count COUNT(*)
411           FROM    action.hold_request
412           WHERE    usr = match_user
413             AND fulfillment_time IS NULL
414             AND cancel_time IS NULL
415             AND CASE WHEN hold_test.include_frozen_holds THEN TRUE ELSE frozen IS FALSE END;
416
417         IF hold_count >= hold_test.max_holds THEN
418             result.fail_part := 'config.hold_matrix_test.max_holds';
419             result.success := FALSE;
420             done := TRUE;
421             RETURN NEXT result;
422         END IF;
423     END IF;
424
425     IF item_object.age_protect IS NOT NULL THEN
426         SELECT INTO age_protect_object * FROM config.rule_age_hold_protect WHERE id = item_object.age_protect;
427         IF hold_test.distance_is_from_owner THEN
428             SELECT INTO use_active_date value FROM actor.org_unit_ancestor_setting('circ.holds.age_protect.active_date', item_cn_object.owning_lib);
429         ELSE
430             SELECT INTO use_active_date value FROM actor.org_unit_ancestor_setting('circ.holds.age_protect.active_date', item_object.circ_lib);
431         END IF;
432         IF use_active_date = 'true' THEN
433             age_protect_date := COALESCE(item_object.active_date, NOW());
434         ELSE
435             age_protect_date := item_object.create_date;
436         END IF;
437         IF age_protect_date + age_protect_object.age > NOW() THEN
438             SELECT INTO calc_age_prox * FROM actor.org_unit_setting WHERE name = 'circ.holds.calculated_age_proximity' AND org_unit = item_object.circ_lib;
439             IF hold_test.distance_is_from_owner THEN
440                 prox_ou := item_cn_object.owning_lib;
441             ELSE
442                 prox_ou := item_object.circ_lib;
443             END IF;
444             IF calc_age_prox.id IS NOT NULL AND calc_age_prox.value = 'true' THEN
445                 SELECT INTO hold_transit_prox action.copy_calculated_proximity(
446                     v_pickup_ou,
447                     v_request_ou,
448                     prox_ou,
449                     item_object.circ_modifier,
450                     item_cn_object.owning_lib,
451                     item_location_object.owning_lib
452                 );
453             ELSE
454                 SELECT INTO hold_transit_prox prox::NUMERIC FROM actor.org_unit_proximity WHERE from_org = prox_ou AND to_org = v_pickup_ou;
455             END IF;
456
457             IF hold_transit_prox > age_protect_object.prox::NUMERIC THEN
458                 result.fail_part := 'config.rule_age_hold_protect.prox';
459                 result.success := FALSE;
460                 done := TRUE;
461                 RETURN NEXT result;
462             END IF;
463         END IF;
464     END IF;
465
466     IF NOT done THEN
467         RETURN NEXT result;
468     END IF;
469
470     RETURN;
471 END;
472 $func$ LANGUAGE plpgsql;
473
474 CREATE OR REPLACE FUNCTION action.hold_request_permit_test( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT ) RETURNS SETOF action.matrix_test_result AS $func$
475     SELECT * FROM action.hold_request_permit_test( $1, $2, $3, $4, $5, FALSE );
476 $func$ LANGUAGE SQL;
477
478 CREATE OR REPLACE FUNCTION action.hold_retarget_permit_test( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT ) RETURNS SETOF action.matrix_test_result AS $func$
479     SELECT * FROM action.hold_request_permit_test( $1, $2, $3, $4, $5, TRUE );
480 $func$ LANGUAGE SQL;
481
482 COMMIT;
483