]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/upgrade/0562.schema.copy_active_date.sql
Break up expensive queries, match index to quals
[working/Evergreen.git] / Open-ILS / src / sql / Pg / upgrade / 0562.schema.copy_active_date.sql
1 -- Evergreen DB patch 0562.schema.copy_active_date.sql
2 --
3 -- Active Date
4
5 BEGIN;
6
7 -- check whether patch can be applied
8 SELECT evergreen.upgrade_deps_block_check('0562', :eg_version);
9
10 ALTER TABLE asset.copy
11     ADD COLUMN active_date TIMESTAMP WITH TIME ZONE;
12
13 ALTER TABLE auditor.asset_copy_history
14     ADD COLUMN active_date TIMESTAMP WITH TIME ZONE;
15
16 ALTER TABLE auditor.serial_unit_history
17     ADD COLUMN active_date TIMESTAMP WITH TIME ZONE;
18
19 ALTER TABLE config.copy_status
20     ADD COLUMN copy_active BOOL NOT NULL DEFAULT FALSE;
21
22 ALTER TABLE config.circ_matrix_weights
23     ADD COLUMN item_age NUMERIC(6,2) NOT NULL DEFAULT 0.0;
24
25 ALTER TABLE config.hold_matrix_weights
26     ADD COLUMN item_age NUMERIC(6,2) NOT NULL DEFAULT 0.0;
27
28 -- The two defaults above were to stop erroring on NOT NULL
29 -- Remove them here
30 ALTER TABLE config.circ_matrix_weights
31     ALTER COLUMN item_age DROP DEFAULT;
32
33 ALTER TABLE config.hold_matrix_weights
34     ALTER COLUMN item_age DROP DEFAULT;
35
36 ALTER TABLE config.circ_matrix_matchpoint
37     ADD COLUMN item_age INTERVAL;
38
39 ALTER TABLE config.hold_matrix_matchpoint
40     ADD COLUMN item_age INTERVAL;
41
42 CREATE OR REPLACE FUNCTION asset.acp_status_changed()
43 RETURNS TRIGGER AS $$
44 BEGIN
45     IF NEW.status <> OLD.status THEN
46         NEW.status_changed_time := now();
47         IF NEW.active_date IS NULL AND NEW.status IN (SELECT id FROM config.copy_status WHERE copy_active = true) THEN
48             NEW.active_date := now();
49         END IF;
50     END IF;
51     RETURN NEW;
52 END;
53 $$ LANGUAGE plpgsql;
54
55 CREATE OR REPLACE FUNCTION asset.acp_created()
56 RETURNS TRIGGER AS $$
57 BEGIN
58     IF NEW.active_date IS NULL AND NEW.status IN (SELECT id FROM config.copy_status WHERE copy_active = true) THEN
59         NEW.active_date := now();
60     END IF;
61     IF NEW.status_changed_time IS NULL THEN
62         NEW.status_changed_time := now();
63     END IF;
64     RETURN NEW;
65 END;
66 $$ LANGUAGE plpgsql;
67
68 CREATE TRIGGER acp_created_trig
69     BEFORE INSERT ON asset.copy
70     FOR EACH ROW EXECUTE PROCEDURE asset.acp_created();
71
72 CREATE TRIGGER sunit_created_trig
73     BEFORE INSERT ON serial.unit
74     FOR EACH ROW EXECUTE PROCEDURE asset.acp_created();
75
76 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$
77 DECLARE
78     matchpoint_id        INT;
79     user_object        actor.usr%ROWTYPE;
80     age_protect_object    config.rule_age_hold_protect%ROWTYPE;
81     standing_penalty    config.standing_penalty%ROWTYPE;
82     transit_range_ou_type    actor.org_unit_type%ROWTYPE;
83     transit_source        actor.org_unit%ROWTYPE;
84     item_object        asset.copy%ROWTYPE;
85     item_cn_object     asset.call_number%ROWTYPE;
86     ou_skip              actor.org_unit_setting%ROWTYPE;
87     result            action.matrix_test_result;
88     hold_test        config.hold_matrix_matchpoint%ROWTYPE;
89     use_active_date   TEXT;
90     age_protect_date  TIMESTAMP WITH TIME ZONE;
91     hold_count        INT;
92     hold_transit_prox    INT;
93     frozen_hold_count    INT;
94     context_org_list    INT[];
95     done            BOOL := FALSE;
96 BEGIN
97     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
98     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( pickup_ou );
99
100     result.success := TRUE;
101
102     -- Fail if we couldn't find a user
103     IF user_object.id IS NULL THEN
104         result.fail_part := 'no_user';
105         result.success := FALSE;
106         done := TRUE;
107         RETURN NEXT result;
108         RETURN;
109     END IF;
110
111     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
112
113     -- Fail if we couldn't find a copy
114     IF item_object.id IS NULL THEN
115         result.fail_part := 'no_item';
116         result.success := FALSE;
117         done := TRUE;
118         RETURN NEXT result;
119         RETURN;
120     END IF;
121
122     SELECT INTO matchpoint_id action.find_hold_matrix_matchpoint(pickup_ou, request_ou, match_item, match_user, match_requestor);
123     result.matchpoint := matchpoint_id;
124
125     SELECT INTO ou_skip * FROM actor.org_unit_setting WHERE name = 'circ.holds.target_skip_me' AND org_unit = item_object.circ_lib;
126
127     -- Fail if the circ_lib for the item has circ.holds.target_skip_me set to true
128     IF ou_skip.id IS NOT NULL AND ou_skip.value = 'true' THEN
129         result.fail_part := 'circ.holds.target_skip_me';
130         result.success := FALSE;
131         done := TRUE;
132         RETURN NEXT result;
133         RETURN;
134     END IF;
135
136     -- Fail if user is barred
137     IF user_object.barred IS TRUE THEN
138         result.fail_part := 'actor.usr.barred';
139         result.success := FALSE;
140         done := TRUE;
141         RETURN NEXT result;
142         RETURN;
143     END IF;
144
145     -- Fail if we couldn't find any matchpoint (requires a default)
146     IF matchpoint_id IS NULL THEN
147         result.fail_part := 'no_matchpoint';
148         result.success := FALSE;
149         done := TRUE;
150         RETURN NEXT result;
151         RETURN;
152     END IF;
153
154     SELECT INTO hold_test * FROM config.hold_matrix_matchpoint WHERE id = matchpoint_id;
155
156     IF hold_test.holdable IS FALSE THEN
157         result.fail_part := 'config.hold_matrix_test.holdable';
158         result.success := FALSE;
159         done := TRUE;
160         RETURN NEXT result;
161     END IF;
162
163     IF hold_test.transit_range IS NOT NULL THEN
164         SELECT INTO transit_range_ou_type * FROM actor.org_unit_type WHERE id = hold_test.transit_range;
165         IF hold_test.distance_is_from_owner THEN
166             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;
167         ELSE
168             SELECT INTO transit_source * FROM actor.org_unit WHERE id = item_object.circ_lib;
169         END IF;
170
171         PERFORM * FROM actor.org_unit_descendants( transit_source.id, transit_range_ou_type.depth ) WHERE id = pickup_ou;
172
173         IF NOT FOUND THEN
174             result.fail_part := 'transit_range';
175             result.success := FALSE;
176             done := TRUE;
177             RETURN NEXT result;
178         END IF;
179     END IF;
180  
181     FOR standing_penalty IN
182         SELECT  DISTINCT csp.*
183           FROM  actor.usr_standing_penalty usp
184                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
185           WHERE usr = match_user
186                 AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
187                 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
188                 AND csp.block_list LIKE '%HOLD%' LOOP
189
190         result.fail_part := standing_penalty.name;
191         result.success := FALSE;
192         done := TRUE;
193         RETURN NEXT result;
194     END LOOP;
195
196     IF hold_test.stop_blocked_user IS TRUE THEN
197         FOR standing_penalty IN
198             SELECT  DISTINCT csp.*
199               FROM  actor.usr_standing_penalty usp
200                     JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
201               WHERE usr = match_user
202                     AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
203                     AND (usp.stop_date IS NULL or usp.stop_date > NOW())
204                     AND csp.block_list LIKE '%CIRC%' LOOP
205     
206             result.fail_part := standing_penalty.name;
207             result.success := FALSE;
208             done := TRUE;
209             RETURN NEXT result;
210         END LOOP;
211     END IF;
212
213     IF hold_test.max_holds IS NOT NULL AND NOT retargetting THEN
214         SELECT    INTO hold_count COUNT(*)
215           FROM    action.hold_request
216           WHERE    usr = match_user
217             AND fulfillment_time IS NULL
218             AND cancel_time IS NULL
219             AND CASE WHEN hold_test.include_frozen_holds THEN TRUE ELSE frozen IS FALSE END;
220
221         IF hold_count >= hold_test.max_holds THEN
222             result.fail_part := 'config.hold_matrix_test.max_holds';
223             result.success := FALSE;
224             done := TRUE;
225             RETURN NEXT result;
226         END IF;
227     END IF;
228
229     IF item_object.age_protect IS NOT NULL THEN
230         SELECT INTO age_protect_object * FROM config.rule_age_hold_protect WHERE id = item_object.age_protect;
231         IF hold_test.distance_is_from_owner THEN
232             SELECT INTO use_active_date value FROM actor.org_unit_ancestor_setting('circ.holds.age_protect.active_date', item_cn_object.owning_lib);
233         ELSE
234             SELECT INTO use_active_date value FROM actor.org_unit_ancestor_setting('circ.holds.age_protect.active_date', item_object.circ_lib);
235         END IF;
236         IF use_active_date = 'true' THEN
237             age_protect_date := COALESCE(item_object.active_date, NOW());
238         ELSE
239             age_protect_date := item_object.create_date;
240         END IF;
241         IF age_protect_date + age_protect_object.age > NOW() THEN
242             IF hold_test.distance_is_from_owner THEN
243                 SELECT INTO item_cn_object * FROM asset.call_number WHERE id = item_object.call_number;
244                 SELECT INTO hold_transit_prox prox FROM actor.org_unit_proximity WHERE from_org = item_cn_object.owning_lib AND to_org = pickup_ou;
245             ELSE
246                 SELECT INTO hold_transit_prox prox FROM actor.org_unit_proximity WHERE from_org = item_object.circ_lib AND to_org = pickup_ou;
247             END IF;
248
249             IF hold_transit_prox > age_protect_object.prox THEN
250                 result.fail_part := 'config.rule_age_hold_protect.prox';
251                 result.success := FALSE;
252                 done := TRUE;
253                 RETURN NEXT result;
254             END IF;
255         END IF;
256     END IF;
257
258     IF NOT done THEN
259         RETURN NEXT result;
260     END IF;
261
262     RETURN;
263 END;
264 $func$ LANGUAGE plpgsql;
265
266 CREATE OR REPLACE FUNCTION action.find_circ_matrix_matchpoint( context_ou INT, item_object asset.copy, user_object actor.usr, renewal BOOL ) RETURNS action.found_circ_matrix_matchpoint AS $func$
267 DECLARE
268     cn_object       asset.call_number%ROWTYPE;
269     rec_descriptor  metabib.rec_descriptor%ROWTYPE;
270     cur_matchpoint  config.circ_matrix_matchpoint%ROWTYPE;
271     matchpoint      config.circ_matrix_matchpoint%ROWTYPE;
272     weights         config.circ_matrix_weights%ROWTYPE;
273     user_age        INTERVAL;
274     my_item_age     INTERVAL;
275     denominator     NUMERIC(6,2);
276     row_list        INT[];
277     result          action.found_circ_matrix_matchpoint;
278 BEGIN
279     -- Assume failure
280     result.success = false;
281
282     -- Fetch useful data
283     SELECT INTO cn_object       * FROM asset.call_number        WHERE id = item_object.call_number;
284     SELECT INTO rec_descriptor  * FROM metabib.rec_descriptor   WHERE record = cn_object.record;
285
286     -- Pre-generate this so we only calc it once
287     IF user_object.dob IS NOT NULL THEN
288         SELECT INTO user_age age(user_object.dob);
289     END IF;
290
291     -- Ditto
292     SELECT INTO my_item_age age(coalesce(item_object.active_date, now()));
293
294     -- Grab the closest set circ weight setting.
295     SELECT INTO weights cw.*
296       FROM config.weight_assoc wa
297            JOIN config.circ_matrix_weights cw ON (cw.id = wa.circ_weights)
298            JOIN actor.org_unit_ancestors_distance( context_ou ) d ON (wa.org_unit = d.id)
299       WHERE active
300       ORDER BY d.distance
301       LIMIT 1;
302
303     -- No weights? Bad admin! Defaults to handle that anyway.
304     IF weights.id IS NULL THEN
305         weights.grp                 := 11.0;
306         weights.org_unit            := 10.0;
307         weights.circ_modifier       := 5.0;
308         weights.marc_type           := 4.0;
309         weights.marc_form           := 3.0;
310         weights.marc_bib_level      := 2.0;
311         weights.marc_vr_format      := 2.0;
312         weights.copy_circ_lib       := 8.0;
313         weights.copy_owning_lib     := 8.0;
314         weights.user_home_ou        := 8.0;
315         weights.ref_flag            := 1.0;
316         weights.juvenile_flag       := 6.0;
317         weights.is_renewal          := 7.0;
318         weights.usr_age_lower_bound := 0.0;
319         weights.usr_age_upper_bound := 0.0;
320         weights.item_age            := 0.0;
321     END IF;
322
323     -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
324     -- If you break your org tree with funky parenting this may be wrong
325     -- Note: This CTE is duplicated in the find_hold_matrix_matchpoint function, and it may be a good idea to split it off to a function
326     -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
327     WITH all_distance(distance) AS (
328             SELECT depth AS distance FROM actor.org_unit_type
329         UNION
330             SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
331         )
332     SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
333
334     -- Loop over all the potential matchpoints
335     FOR cur_matchpoint IN
336         SELECT m.*
337           FROM  config.circ_matrix_matchpoint m
338                 /*LEFT*/ JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.grp = upgad.id
339                 /*LEFT*/ JOIN actor.org_unit_ancestors_distance( context_ou ) ctoua ON m.org_unit = ctoua.id
340                 LEFT JOIN actor.org_unit_ancestors_distance( cn_object.owning_lib ) cnoua ON m.copy_owning_lib = cnoua.id
341                 LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.copy_circ_lib = iooua.id
342                 LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou  ) uhoua ON m.user_home_ou = uhoua.id
343           WHERE m.active
344                 -- Permission Groups
345              -- AND (m.grp                      IS NULL OR upgad.id IS NOT NULL) -- Optional Permission Group?
346                 -- Org Units
347              -- AND (m.org_unit                 IS NULL OR ctoua.id IS NOT NULL) -- Optional Org Unit?
348                 AND (m.copy_owning_lib          IS NULL OR cnoua.id IS NOT NULL)
349                 AND (m.copy_circ_lib            IS NULL OR iooua.id IS NOT NULL)
350                 AND (m.user_home_ou             IS NULL OR uhoua.id IS NOT NULL)
351                 -- Circ Type
352                 AND (m.is_renewal               IS NULL OR m.is_renewal = renewal)
353                 -- Static User Checks
354                 AND (m.juvenile_flag            IS NULL OR m.juvenile_flag = user_object.juvenile)
355                 AND (m.usr_age_lower_bound      IS NULL OR (user_age IS NOT NULL AND m.usr_age_lower_bound < user_age))
356                 AND (m.usr_age_upper_bound      IS NULL OR (user_age IS NOT NULL AND m.usr_age_upper_bound > user_age))
357                 -- Static Item Checks
358                 AND (m.circ_modifier            IS NULL OR m.circ_modifier = item_object.circ_modifier)
359                 AND (m.marc_type                IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
360                 AND (m.marc_form                IS NULL OR m.marc_form = rec_descriptor.item_form)
361                 AND (m.marc_bib_level           IS NULL OR m.marc_bib_level = rec_descriptor.bib_level)
362                 AND (m.marc_vr_format           IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
363                 AND (m.ref_flag                 IS NULL OR m.ref_flag = item_object.ref)
364                 AND (m.item_age                 IS NULL OR (my_item_age IS NOT NULL AND m.item_age > my_item_age))
365           ORDER BY
366                 -- Permission Groups
367                 CASE WHEN upgad.distance        IS NOT NULL THEN 2^(2*weights.grp - (upgad.distance/denominator)) ELSE 0.0 END +
368                 -- Org Units
369                 CASE WHEN ctoua.distance        IS NOT NULL THEN 2^(2*weights.org_unit - (ctoua.distance/denominator)) ELSE 0.0 END +
370                 CASE WHEN cnoua.distance        IS NOT NULL THEN 2^(2*weights.copy_owning_lib - (cnoua.distance/denominator)) ELSE 0.0 END +
371                 CASE WHEN iooua.distance        IS NOT NULL THEN 2^(2*weights.copy_circ_lib - (iooua.distance/denominator)) ELSE 0.0 END +
372                 CASE WHEN uhoua.distance        IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
373                 -- Circ Type                    -- Note: 4^x is equiv to 2^(2*x)
374                 CASE WHEN m.is_renewal          IS NOT NULL THEN 4^weights.is_renewal ELSE 0.0 END +
375                 -- Static User Checks
376                 CASE WHEN m.juvenile_flag       IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
377                 CASE WHEN m.usr_age_lower_bound IS NOT NULL THEN 4^weights.usr_age_lower_bound ELSE 0.0 END +
378                 CASE WHEN m.usr_age_upper_bound IS NOT NULL THEN 4^weights.usr_age_upper_bound ELSE 0.0 END +
379                 -- Static Item Checks
380                 CASE WHEN m.circ_modifier       IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
381                 CASE WHEN m.marc_type           IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
382                 CASE WHEN m.marc_form           IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
383                 CASE WHEN m.marc_vr_format      IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
384                 CASE WHEN m.ref_flag            IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END +
385                 -- Item age has a slight adjustment to weight based on value.
386                 -- This should ensure that a shorter age limit comes first when all else is equal.
387                 -- NOTE: This assumes that intervals will normally be in days.
388                 CASE WHEN m.item_age            IS NOT NULL THEN 4^weights.item_age - 1 + 86400/EXTRACT(EPOCH FROM m.item_age) ELSE 0.0 END DESC,
389                 -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
390                 -- This prevents "we changed the table order by updating a rule, and we started getting different results"
391                 m.id LOOP
392
393         -- Record the full matching row list
394         row_list := row_list || cur_matchpoint.id;
395
396         -- No matchpoint yet?
397         IF matchpoint.id IS NULL THEN
398             -- Take the entire matchpoint as a starting point
399             matchpoint := cur_matchpoint;
400             CONTINUE; -- No need to look at this row any more.
401         END IF;
402
403         -- Incomplete matchpoint?
404         IF matchpoint.circulate IS NULL THEN
405             matchpoint.circulate := cur_matchpoint.circulate;
406         END IF;
407         IF matchpoint.duration_rule IS NULL THEN
408             matchpoint.duration_rule := cur_matchpoint.duration_rule;
409         END IF;
410         IF matchpoint.recurring_fine_rule IS NULL THEN
411             matchpoint.recurring_fine_rule := cur_matchpoint.recurring_fine_rule;
412         END IF;
413         IF matchpoint.max_fine_rule IS NULL THEN
414             matchpoint.max_fine_rule := cur_matchpoint.max_fine_rule;
415         END IF;
416         IF matchpoint.hard_due_date IS NULL THEN
417             matchpoint.hard_due_date := cur_matchpoint.hard_due_date;
418         END IF;
419         IF matchpoint.total_copy_hold_ratio IS NULL THEN
420             matchpoint.total_copy_hold_ratio := cur_matchpoint.total_copy_hold_ratio;
421         END IF;
422         IF matchpoint.available_copy_hold_ratio IS NULL THEN
423             matchpoint.available_copy_hold_ratio := cur_matchpoint.available_copy_hold_ratio;
424         END IF;
425         IF matchpoint.renewals IS NULL THEN
426             matchpoint.renewals := cur_matchpoint.renewals;
427         END IF;
428         IF matchpoint.grace_period IS NULL THEN
429             matchpoint.grace_period := cur_matchpoint.grace_period;
430         END IF;
431     END LOOP;
432
433     -- Check required fields
434     IF matchpoint.circulate             IS NOT NULL AND
435        matchpoint.duration_rule         IS NOT NULL AND
436        matchpoint.recurring_fine_rule   IS NOT NULL AND
437        matchpoint.max_fine_rule         IS NOT NULL THEN
438         -- All there? We have a completed match.
439         result.success := true;
440     END IF;
441
442     -- Include the assembled matchpoint, even if it isn't complete
443     result.matchpoint := matchpoint;
444
445     -- Include (for debugging) the full list of matching rows
446     result.buildrows := row_list;
447
448     -- Hand the result back to caller
449     RETURN result;
450 END;
451 $func$ LANGUAGE plpgsql;
452
453 CREATE OR REPLACE FUNCTION action.find_hold_matrix_matchpoint(pickup_ou integer, request_ou integer, match_item bigint, match_user integer, match_requestor integer)
454   RETURNS integer AS
455 $func$
456 DECLARE
457     requestor_object    actor.usr%ROWTYPE;
458     user_object         actor.usr%ROWTYPE;
459     item_object         asset.copy%ROWTYPE;
460     item_cn_object      asset.call_number%ROWTYPE;
461     my_item_age         INTERVAL;
462     rec_descriptor      metabib.rec_descriptor%ROWTYPE;
463     matchpoint          config.hold_matrix_matchpoint%ROWTYPE;
464     weights             config.hold_matrix_weights%ROWTYPE;
465     denominator         NUMERIC(6,2);
466 BEGIN
467     SELECT INTO user_object         * FROM actor.usr                WHERE id = match_user;
468     SELECT INTO requestor_object    * FROM actor.usr                WHERE id = match_requestor;
469     SELECT INTO item_object         * FROM asset.copy               WHERE id = match_item;
470     SELECT INTO item_cn_object      * FROM asset.call_number        WHERE id = item_object.call_number;
471     SELECT INTO rec_descriptor      * FROM metabib.rec_descriptor   WHERE record = item_cn_object.record;
472
473     SELECT INTO my_item_age age(coalesce(item_object.active_date, now()));
474
475     -- The item's owner should probably be the one determining if the item is holdable
476     -- How to decide that is debatable. Decided to default to the circ library (where the item lives)
477     -- This flag will allow for setting it to the owning library (where the call number "lives")
478     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.weight_owner_not_circ' AND enabled;
479
480     -- Grab the closest set circ weight setting.
481     IF NOT FOUND THEN
482         -- Default to circ library
483         SELECT INTO weights hw.*
484           FROM config.weight_assoc wa
485                JOIN config.hold_matrix_weights hw ON (hw.id = wa.hold_weights)
486                JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) d ON (wa.org_unit = d.id)
487           WHERE active
488           ORDER BY d.distance
489           LIMIT 1;
490     ELSE
491         -- Flag is set, use owning library
492         SELECT INTO weights hw.*
493           FROM config.weight_assoc wa
494                JOIN config.hold_matrix_weights hw ON (hw.id = wa.hold_weights)
495                JOIN actor.org_unit_ancestors_distance( item_cn_object.owning_lib ) d ON (wa.org_unit = d.id)
496           WHERE active
497           ORDER BY d.distance
498           LIMIT 1;
499     END IF;
500
501     -- No weights? Bad admin! Defaults to handle that anyway.
502     IF weights.id IS NULL THEN
503         weights.user_home_ou    := 5.0;
504         weights.request_ou      := 5.0;
505         weights.pickup_ou       := 5.0;
506         weights.item_owning_ou  := 5.0;
507         weights.item_circ_ou    := 5.0;
508         weights.usr_grp         := 7.0;
509         weights.requestor_grp   := 8.0;
510         weights.circ_modifier   := 4.0;
511         weights.marc_type       := 3.0;
512         weights.marc_form       := 2.0;
513         weights.marc_bib_level  := 1.0;
514         weights.marc_vr_format  := 1.0;
515         weights.juvenile_flag   := 4.0;
516         weights.ref_flag        := 0.0;
517         weights.item_age        := 0.0;
518     END IF;
519
520     -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
521     -- If you break your org tree with funky parenting this may be wrong
522     -- 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
523     -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
524     WITH all_distance(distance) AS (
525             SELECT depth AS distance FROM actor.org_unit_type
526         UNION
527             SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
528         )
529     SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
530
531     -- To ATTEMPT to make this work like it used to, make it reverse the user/requestor profile ids.
532     -- This may be better implemented as part of the upgrade script?
533     -- Set usr_grp = requestor_grp, requestor_grp = 1 or something when this flag is already set
534     -- Then remove this flag, of course.
535     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.usr_not_requestor' AND enabled;
536
537     IF FOUND THEN
538         -- Note: This, to me, is REALLY hacky. I put it in anyway.
539         -- If you can't tell, this is a single call swap on two variables.
540         SELECT INTO user_object.profile, requestor_object.profile
541                     requestor_object.profile, user_object.profile;
542     END IF;
543
544     -- Select the winning matchpoint into the matchpoint variable for returning
545     SELECT INTO matchpoint m.*
546       FROM  config.hold_matrix_matchpoint m
547             /*LEFT*/ JOIN permission.grp_ancestors_distance( requestor_object.profile ) rpgad ON m.requestor_grp = rpgad.id
548             LEFT JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.usr_grp = upgad.id
549             LEFT JOIN actor.org_unit_ancestors_distance( pickup_ou ) puoua ON m.pickup_ou = puoua.id
550             LEFT JOIN actor.org_unit_ancestors_distance( request_ou ) rqoua ON m.request_ou = rqoua.id
551             LEFT JOIN actor.org_unit_ancestors_distance( item_cn_object.owning_lib ) cnoua ON m.item_owning_ou = cnoua.id
552             LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.item_circ_ou = iooua.id
553             LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou  ) uhoua ON m.user_home_ou = uhoua.id
554       WHERE m.active
555             -- Permission Groups
556          -- AND (m.requestor_grp        IS NULL OR upgad.id IS NOT NULL) -- Optional Requestor Group?
557             AND (m.usr_grp              IS NULL OR upgad.id IS NOT NULL)
558             -- Org Units
559             AND (m.pickup_ou            IS NULL OR (puoua.id IS NOT NULL AND (puoua.distance = 0 OR NOT m.strict_ou_match)))
560             AND (m.request_ou           IS NULL OR (rqoua.id IS NOT NULL AND (rqoua.distance = 0 OR NOT m.strict_ou_match)))
561             AND (m.item_owning_ou       IS NULL OR (cnoua.id IS NOT NULL AND (cnoua.distance = 0 OR NOT m.strict_ou_match)))
562             AND (m.item_circ_ou         IS NULL OR (iooua.id IS NOT NULL AND (iooua.distance = 0 OR NOT m.strict_ou_match)))
563             AND (m.user_home_ou         IS NULL OR (uhoua.id IS NOT NULL AND (uhoua.distance = 0 OR NOT m.strict_ou_match)))
564             -- Static User Checks
565             AND (m.juvenile_flag        IS NULL OR m.juvenile_flag = user_object.juvenile)
566             -- Static Item Checks
567             AND (m.circ_modifier        IS NULL OR m.circ_modifier = item_object.circ_modifier)
568             AND (m.marc_type            IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
569             AND (m.marc_form            IS NULL OR m.marc_form = rec_descriptor.item_form)
570             AND (m.marc_bib_level       IS NULL OR m.marc_bib_level = rec_descriptor.bib_level)
571             AND (m.marc_vr_format       IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
572             AND (m.ref_flag             IS NULL OR m.ref_flag = item_object.ref)
573             AND (m.item_age             IS NULL OR (my_item_age IS NOT NULL AND m.item_age > my_item_age))
574       ORDER BY
575             -- Permission Groups
576             CASE WHEN rpgad.distance    IS NOT NULL THEN 2^(2*weights.requestor_grp - (rpgad.distance/denominator)) ELSE 0.0 END +
577             CASE WHEN upgad.distance    IS NOT NULL THEN 2^(2*weights.usr_grp - (upgad.distance/denominator)) ELSE 0.0 END +
578             -- Org Units
579             CASE WHEN puoua.distance    IS NOT NULL THEN 2^(2*weights.pickup_ou - (puoua.distance/denominator)) ELSE 0.0 END +
580             CASE WHEN rqoua.distance    IS NOT NULL THEN 2^(2*weights.request_ou - (rqoua.distance/denominator)) ELSE 0.0 END +
581             CASE WHEN cnoua.distance    IS NOT NULL THEN 2^(2*weights.item_owning_ou - (cnoua.distance/denominator)) ELSE 0.0 END +
582             CASE WHEN iooua.distance    IS NOT NULL THEN 2^(2*weights.item_circ_ou - (iooua.distance/denominator)) ELSE 0.0 END +
583             CASE WHEN uhoua.distance    IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
584             -- Static User Checks       -- Note: 4^x is equiv to 2^(2*x)
585             CASE WHEN m.juvenile_flag   IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
586             -- Static Item Checks
587             CASE WHEN m.circ_modifier   IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
588             CASE WHEN m.marc_type       IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
589             CASE WHEN m.marc_form       IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
590             CASE WHEN m.marc_vr_format  IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
591             CASE WHEN m.ref_flag        IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END +
592             -- Item age has a slight adjustment to weight based on value.
593             -- This should ensure that a shorter age limit comes first when all else is equal.
594             -- NOTE: This assumes that intervals will normally be in days.
595             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,
596             -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
597             -- This prevents "we changed the table order by updating a rule, and we started getting different results"
598             m.id;
599
600     -- Return just the ID for now
601     RETURN matchpoint.id;
602 END;
603 $func$ LANGUAGE 'plpgsql';
604
605 DROP INDEX IF EXISTS config.ccmm_once_per_paramset;
606
607 DROP INDEX IF EXISTS config.chmm_once_per_paramset;
608
609 CREATE UNIQUE INDEX ccmm_once_per_paramset ON config.circ_matrix_matchpoint (org_unit, grp, COALESCE(circ_modifier, ''), COALESCE(marc_type, ''), COALESCE(marc_form, ''), COALESCE(marc_bib_level,''), COALESCE(marc_vr_format, ''), COALESCE(copy_circ_lib::TEXT, ''), COALESCE(copy_owning_lib::TEXT, ''), COALESCE(user_home_ou::TEXT, ''), COALESCE(ref_flag::TEXT, ''), COALESCE(juvenile_flag::TEXT, ''), COALESCE(is_renewal::TEXT, ''), COALESCE(usr_age_lower_bound::TEXT, ''), COALESCE(usr_age_upper_bound::TEXT, ''), COALESCE(item_age::TEXT, '')) WHERE active;
610
611 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;
612
613 UPDATE config.copy_status SET copy_active = true WHERE id IN (0, 1, 7, 8, 10, 12, 15);
614
615 INSERT into config.org_unit_setting_type
616 ( name, label, description, datatype ) VALUES
617 ( 'circ.holds.age_protect.active_date', 'Holds: Use Active Date for Age Protection', 'When calculating age protection rules use the active date instead of the creation date.', 'bool');
618
619 -- Assume create date when item is in status we would update active date for anyway
620 UPDATE asset.copy SET active_date = create_date WHERE status IN (SELECT id FROM config.copy_status WHERE copy_active = true);
621
622 -- Assume create date for any item with circs
623 UPDATE asset.copy SET active_date = create_date WHERE id IN (SELECT id FROM extend_reporter.full_circ_count WHERE circ_count > 0);
624
625 -- Assume create date for status change time while we are at it. Because being created WAS a change in status.
626 UPDATE asset.copy SET status_changed_time = create_date WHERE status_changed_time IS NULL;
627
628 COMMIT;