]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/110.hold_matrix.sql
Merge branch 'master' of git+ssh://yeti.esilibrary.com/home/evergreen/evergreen-equin...
[working/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    REFERENCES config.item_type_map (code) DEFERRABLE INITIALLY DEFERRED,
45     marc_form               TEXT    REFERENCES config.item_form_map (code) DEFERRABLE INITIALLY DEFERRED,
46     marc_vr_format          TEXT    REFERENCES config.videorecording_format_map (code) DEFERRABLE INITIALLY DEFERRED,
47     juvenile_flag           BOOL,
48     ref_flag                BOOL,
49     -- "Result" Fields
50     holdable                BOOL    NOT NULL DEFAULT TRUE,                -- Hard "can't hold" flag requiring an override
51     distance_is_from_owner  BOOL    NOT NULL DEFAULT FALSE,                -- How to calculate transit_range.  True means owning lib, false means copy circ lib
52     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
53     max_holds               INT,                            -- Total hold requests must be less than this, NULL means skip (always pass)
54     include_frozen_holds    BOOL    NOT NULL DEFAULT TRUE,                -- Include frozen hold requests in the count for max_holds test
55     stop_blocked_user       BOOL    NOT NULL DEFAULT FALSE,                -- Stop users who cannot check out items from placing holds
56     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
57 );
58
59 -- Nulls don't count for a constraint match, so we have to coalesce them into something that does.
60 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_vr_format, ''), COALESCE(juvenile_flag::TEXT, ''), COALESCE(ref_flag::TEXT, '')) WHERE active;
61
62 CREATE OR REPLACE FUNCTION action.find_hold_matrix_matchpoint(pickup_ou integer, request_ou integer, match_item bigint, match_user integer, match_requestor integer)
63   RETURNS integer AS
64 $func$
65 DECLARE
66     requestor_object    actor.usr%ROWTYPE;
67     user_object         actor.usr%ROWTYPE;
68     item_object         asset.copy%ROWTYPE;
69     item_cn_object      asset.call_number%ROWTYPE;
70     rec_descriptor      metabib.rec_descriptor%ROWTYPE;
71     matchpoint          config.hold_matrix_matchpoint%ROWTYPE;
72     weights             config.hold_matrix_weights%ROWTYPE;
73     denominator         NUMERIC(6,2);
74 BEGIN
75     SELECT INTO user_object         * FROM actor.usr                WHERE id = match_user;
76     SELECT INTO requestor_object    * FROM actor.usr                WHERE id = match_requestor;
77     SELECT INTO item_object         * FROM asset.copy               WHERE id = match_item;
78     SELECT INTO item_cn_object      * FROM asset.call_number        WHERE id = item_object.call_number;
79     SELECT INTO rec_descriptor      * FROM metabib.rec_descriptor   WHERE record = item_cn_object.record;
80
81     -- The item's owner should probably be the one determining if the item is holdable
82     -- How to decide that is debatable. Decided to default to the circ library (where the item lives)
83     -- This flag will allow for setting it to the owning library (where the call number "lives")
84     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.weight_owner_not_circ' AND enabled;
85
86     -- Grab the closest set circ weight setting.
87     IF NOT FOUND THEN
88         -- Default to circ library
89         SELECT INTO weights hw.*
90           FROM config.weight_assoc wa
91                JOIN config.hold_matrix_weights hw ON (hw.id = wa.hold_weights)
92                JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) d ON (wa.org_unit = d.id)
93           WHERE active
94           ORDER BY d.distance
95           LIMIT 1;
96     ELSE
97         -- Flag is set, use owning library
98         SELECT INTO weights hw.*
99           FROM config.weight_assoc wa
100                JOIN config.hold_matrix_weights hw ON (hw.id = wa.hold_weights)
101                JOIN actor.org_unit_ancestors_distance( cn_object.owning_lib ) d ON (wa.org_unit = d.id)
102           WHERE active
103           ORDER BY d.distance
104           LIMIT 1;
105     END IF;
106
107     -- No weights? Bad admin! Defaults to handle that anyway.
108     IF weights.id IS NULL THEN
109         weights.user_home_ou    := 5.0;
110         weights.request_ou      := 5.0;
111         weights.pickup_ou       := 5.0;
112         weights.item_owning_ou  := 5.0;
113         weights.item_circ_ou    := 5.0;
114         weights.usr_grp         := 7.0;
115         weights.requestor_grp   := 8.0;
116         weights.circ_modifier   := 4.0;
117         weights.marc_type       := 3.0;
118         weights.marc_form       := 2.0;
119         weights.marc_vr_format  := 1.0;
120         weights.juvenile_flag   := 4.0;
121         weights.ref_flag        := 0.0;
122     END IF;
123
124     -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
125     -- If you break your org tree with funky parenting this may be wrong
126     -- 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
127     -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
128     WITH all_distance(distance) AS (
129             SELECT depth AS distance FROM actor.org_unit_type
130         UNION
131             SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
132         )
133     SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
134
135     -- To ATTEMPT to make this work like it used to, make it reverse the user/requestor profile ids.
136     -- This may be better implemented as part of the upgrade script?
137     -- Set usr_grp = requestor_grp, requestor_grp = 1 or something when this flag is already set
138     -- Then remove this flag, of course.
139     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.usr_not_requestor' AND enabled;
140
141     IF FOUND THEN
142         -- Note: This, to me, is REALLY hacky. I put it in anyway.
143         -- If you can't tell, this is a single call swap on two variables.
144         SELECT INTO user_object.profile, requestor_object.profile
145                     requestor_object.profile, user_object.profile;
146     END IF;
147
148     -- Select the winning matchpoint into the matchpoint variable for returning
149     SELECT INTO matchpoint m.*
150       FROM  config.hold_matrix_matchpoint m
151             /*LEFT*/ JOIN permission.grp_ancestors_distance( requestor_object.profile ) rpgad ON m.requestor_grp = rpgad.id
152             LEFT JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.usr_grp = upgad.id
153             LEFT JOIN actor.org_unit_ancestors_distance( pickup_ou ) puoua ON m.pickup_ou = puoua.id
154             LEFT JOIN actor.org_unit_ancestors_distance( request_ou ) rqoua ON m.request_ou = rqoua.id
155             LEFT JOIN actor.org_unit_ancestors_distance( item_cn_object.owning_lib ) cnoua ON m.item_owning_ou = cnoua.id
156             LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.item_circ_ou = iooua.id
157             LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou  ) uhoua ON m.user_home_ou = uhoua.id
158       WHERE m.active
159             -- Permission Groups
160          -- AND (m.requestor_grp        IS NULL OR upgad.id IS NOT NULL) -- Optional Requestor Group?
161             AND (m.usr_grp              IS NULL OR upgad.id IS NOT NULL)
162             -- Org Units
163             AND (m.pickup_ou            IS NULL OR (puoua.id IS NOT NULL AND (puoua.distance = 0 OR NOT m.strict_ou_match)))
164             AND (m.request_ou           IS NULL OR (rqoua.id IS NOT NULL AND (rqoua.distance = 0 OR NOT m.strict_ou_match)))
165             AND (m.item_owning_ou       IS NULL OR (cnoua.id IS NOT NULL AND (cnoua.distance = 0 OR NOT m.strict_ou_match)))
166             AND (m.item_circ_ou         IS NULL OR (iooua.id IS NOT NULL AND (iooua.distance = 0 OR NOT m.strict_ou_match)))
167             AND (m.user_home_ou         IS NULL OR (uhoua.id IS NOT NULL AND (uhoua.distance = 0 OR NOT m.strict_ou_match)))
168             -- Static User Checks
169             AND (m.juvenile_flag        IS NULL OR m.juvenile_flag = user_object.juvenile)
170             -- Static Item Checks
171             AND (m.circ_modifier        IS NULL OR m.circ_modifier = item_object.circ_modifier)
172             AND (m.marc_type            IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
173             AND (m.marc_form            IS NULL OR m.marc_form = rec_descriptor.item_form)
174             AND (m.marc_vr_format       IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
175             AND (m.ref_flag             IS NULL OR m.ref_flag = item_object.ref)
176       ORDER BY
177             -- Permission Groups
178             CASE WHEN rpgad.distance    IS NOT NULL THEN 2^(2*weights.requestor_grp - (rpgad.distance/denominator)) ELSE 0.0 END +
179             CASE WHEN upgad.distance    IS NOT NULL THEN 2^(2*weights.usr_grp - (upgad.distance/denominator)) ELSE 0.0 END +
180             -- Org Units
181             CASE WHEN puoua.distance    IS NOT NULL THEN 2^(2*weights.pickup_ou - (puoua.distance/denominator)) ELSE 0.0 END +
182             CASE WHEN rqoua.distance    IS NOT NULL THEN 2^(2*weights.request_ou - (rqoua.distance/denominator)) ELSE 0.0 END +
183             CASE WHEN cnoua.distance    IS NOT NULL THEN 2^(2*weights.item_owning_ou - (cnoua.distance/denominator)) ELSE 0.0 END +
184             CASE WHEN iooua.distance    IS NOT NULL THEN 2^(2*weights.item_circ_ou - (iooua.distance/denominator)) ELSE 0.0 END +
185             CASE WHEN uhoua.distance    IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
186             -- Static User Checks       -- Note: 4^x is equiv to 2^(2*x)
187             CASE WHEN m.juvenile_flag   IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
188             -- Static Item Checks
189             CASE WHEN m.circ_modifier   IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
190             CASE WHEN m.marc_type       IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
191             CASE WHEN m.marc_form       IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
192             CASE WHEN m.marc_vr_format  IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
193             CASE WHEN m.ref_flag        IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END DESC,
194             -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
195             -- This prevents "we changed the table order by updating a rule, and we started getting different results"
196             m.id;
197
198     -- Return just the ID for now
199     RETURN matchpoint.id;
200 END;
201 $func$ LANGUAGE 'plpgsql';
202
203 CREATE TYPE action.matrix_test_result AS ( success BOOL, matchpoint INT, fail_part TEXT );
204 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$
205 DECLARE
206     matchpoint_id        INT;
207     user_object        actor.usr%ROWTYPE;
208     age_protect_object    config.rule_age_hold_protect%ROWTYPE;
209     standing_penalty    config.standing_penalty%ROWTYPE;
210     transit_range_ou_type    actor.org_unit_type%ROWTYPE;
211     transit_source        actor.org_unit%ROWTYPE;
212     item_object        asset.copy%ROWTYPE;
213     ou_skip              actor.org_unit_setting%ROWTYPE;
214     result            action.matrix_test_result;
215     hold_test        config.hold_matrix_matchpoint%ROWTYPE;
216     hold_count        INT;
217     hold_transit_prox    INT;
218     frozen_hold_count    INT;
219     context_org_list    INT[];
220     done            BOOL := FALSE;
221 BEGIN
222     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
223     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( pickup_ou );
224
225     result.success := TRUE;
226
227     -- Fail if we couldn't find a user
228     IF user_object.id IS NULL THEN
229         result.fail_part := 'no_user';
230         result.success := FALSE;
231         done := TRUE;
232         RETURN NEXT result;
233         RETURN;
234     END IF;
235
236     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
237
238     -- Fail if we couldn't find a copy
239     IF item_object.id IS NULL THEN
240         result.fail_part := 'no_item';
241         result.success := FALSE;
242         done := TRUE;
243         RETURN NEXT result;
244         RETURN;
245     END IF;
246
247     SELECT INTO matchpoint_id action.find_hold_matrix_matchpoint(pickup_ou, request_ou, match_item, match_user, match_requestor);
248     result.matchpoint := matchpoint_id;
249
250     SELECT INTO ou_skip * FROM actor.org_unit_setting WHERE name = 'circ.holds.target_skip_me' AND org_unit = item_object.circ_lib;
251
252     -- Fail if the circ_lib for the item has circ.holds.target_skip_me set to true
253     IF ou_skip.id IS NOT NULL AND ou_skip.value = 'true' THEN
254         result.fail_part := 'circ.holds.target_skip_me';
255         result.success := FALSE;
256         done := TRUE;
257         RETURN NEXT result;
258         RETURN;
259     END IF;
260
261     -- Fail if user is barred
262     IF user_object.barred IS TRUE THEN
263         result.fail_part := 'actor.usr.barred';
264         result.success := FALSE;
265         done := TRUE;
266         RETURN NEXT result;
267         RETURN;
268     END IF;
269
270     -- Fail if we couldn't find any matchpoint (requires a default)
271     IF matchpoint_id IS NULL THEN
272         result.fail_part := 'no_matchpoint';
273         result.success := FALSE;
274         done := TRUE;
275         RETURN NEXT result;
276         RETURN;
277     END IF;
278
279     SELECT INTO hold_test * FROM config.hold_matrix_matchpoint WHERE id = matchpoint_id;
280
281     IF hold_test.holdable IS FALSE THEN
282         result.fail_part := 'config.hold_matrix_test.holdable';
283         result.success := FALSE;
284         done := TRUE;
285         RETURN NEXT result;
286     END IF;
287
288     IF hold_test.transit_range IS NOT NULL THEN
289         SELECT INTO transit_range_ou_type * FROM actor.org_unit_type WHERE id = hold_test.transit_range;
290         IF hold_test.distance_is_from_owner THEN
291             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;
292         ELSE
293             SELECT INTO transit_source * FROM actor.org_unit WHERE id = item_object.circ_lib;
294         END IF;
295
296         PERFORM * FROM actor.org_unit_descendants( transit_source.id, transit_range_ou_type.depth ) WHERE id = pickup_ou;
297
298         IF NOT FOUND THEN
299             result.fail_part := 'transit_range';
300             result.success := FALSE;
301             done := TRUE;
302             RETURN NEXT result;
303         END IF;
304     END IF;
305  
306     FOR standing_penalty IN
307         SELECT  DISTINCT csp.*
308           FROM  actor.usr_standing_penalty usp
309                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
310           WHERE usr = match_user
311                 AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
312                 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
313                 AND csp.block_list LIKE '%HOLD%' LOOP
314
315         result.fail_part := standing_penalty.name;
316         result.success := FALSE;
317         done := TRUE;
318         RETURN NEXT result;
319     END LOOP;
320
321     IF hold_test.stop_blocked_user IS TRUE THEN
322         FOR standing_penalty IN
323             SELECT  DISTINCT csp.*
324               FROM  actor.usr_standing_penalty usp
325                     JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
326               WHERE usr = match_user
327                     AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
328                     AND (usp.stop_date IS NULL or usp.stop_date > NOW())
329                     AND csp.block_list LIKE '%CIRC%' LOOP
330     
331             result.fail_part := standing_penalty.name;
332             result.success := FALSE;
333             done := TRUE;
334             RETURN NEXT result;
335         END LOOP;
336     END IF;
337
338     IF hold_test.max_holds IS NOT NULL AND NOT retargetting THEN
339         SELECT    INTO hold_count COUNT(*)
340           FROM    action.hold_request
341           WHERE    usr = match_user
342             AND fulfillment_time IS NULL
343             AND cancel_time IS NULL
344             AND CASE WHEN hold_test.include_frozen_holds THEN TRUE ELSE frozen IS FALSE END;
345
346         IF hold_count >= hold_test.max_holds THEN
347             result.fail_part := 'config.hold_matrix_test.max_holds';
348             result.success := FALSE;
349             done := TRUE;
350             RETURN NEXT result;
351         END IF;
352     END IF;
353
354     IF item_object.age_protect IS NOT NULL THEN
355         SELECT INTO age_protect_object * FROM config.rule_age_hold_protect WHERE id = item_object.age_protect;
356
357         IF item_object.create_date + age_protect_object.age > NOW() THEN
358             IF hold_test.distance_is_from_owner THEN
359                 SELECT INTO hold_transit_prox prox FROM actor.org_unit_proximity WHERE from_org = item_cn_object.owning_lib AND to_org = pickup_ou;
360             ELSE
361                 SELECT INTO hold_transit_prox prox FROM actor.org_unit_proximity WHERE from_org = item_object.circ_lib AND to_org = pickup_ou;
362             END IF;
363
364             IF hold_transit_prox > age_protect_object.prox THEN
365                 result.fail_part := 'config.rule_age_hold_protect.prox';
366                 result.success := FALSE;
367                 done := TRUE;
368                 RETURN NEXT result;
369             END IF;
370         END IF;
371     END IF;
372
373     IF NOT done THEN
374         RETURN NEXT result;
375     END IF;
376
377     RETURN;
378 END;
379 $func$ LANGUAGE plpgsql;
380
381 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$
382     SELECT * FROM action.hold_request_permit_test( $1, $2, $3, $4, $5, FALSE );
383 $func$ LANGUAGE SQL;
384
385 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$
386     SELECT * FROM action.hold_request_permit_test( $1, $2, $3, $4, $5, TRUE );
387 $func$ LANGUAGE SQL;
388
389 COMMIT;
390