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