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