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