3 -- NOTE: current config.item_type should get sip2_media_type and magnetic_media columns
5 -- New table needed to handle circ modifiers inside the DB. Will still require
6 -- central admin. The circ_modifier column on asset.copy will become an fkey to this table.
7 CREATE TABLE config.circ_modifier (
9 name TEXT UNIQUE NOT NULL,
10 description TEXT NOT NULL,
11 sip2_media_type TEXT NOT NULL,
12 magnetic_media BOOL NOT NULL DEFAULT TRUE,
13 avg_wait_time INTERVAL
18 INSERT INTO config.circ_modifier VALUES ( 'DVD', 'DVD', 'um ... DVDs', '001', FALSE );
19 INSERT INTO config.circ_modifier VALUES ( 'VIDEO', 'VIDEO', 'Tapes', '001', TRUE );
20 INSERT INTO config.circ_modifier VALUES ( 'BOOK', 'BOOK', 'Dead tree', '001', FALSE );
21 INSERT INTO config.circ_modifier VALUES ( 'CRAZY_ARL-ATH_SETTING', 'R2R_TAPE', 'reel2reel tape', '007', TRUE );
24 -- But, just to get us started, use this
27 UPDATE asset.copy SET circ_modifier = UPPER(circ_modifier) WHERE circ_modifier IS NOT NULL AND circ_modifier <> '';
28 UPDATE asset.copy SET circ_modifier = NULL WHERE circ_modifier = '';
30 INSERT INTO config.circ_modifier (code, name, description, sip2_media_type )
37 WHERE circ_modifier IS NOT NULL;
41 -- add an fkey pointing to the new circ mod table
42 ALTER TABLE asset.copy ADD CONSTRAINT circ_mod_fkey FOREIGN KEY (circ_modifier) REFERENCES config.circ_modifier (code) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED;
46 ** Here we define the tables that make up the circ matrix. Conceptually, this implements
47 ** the "sparse matrix" that everyone talks about, instead of using traditional rules logic.
48 ** Physically, we cut the matrix up into separate tables (almost 3rd normal form!) that handle
49 ** different portions of the matrix. This wil simplify creation of the UI (I hope), and help the
50 ** developers focus on specific parts of the matrix.
53 CREATE TABLE config.circ_matrix_matchpoint (
54 id SERIAL PRIMARY KEY,
55 active BOOL NOT NULL DEFAULT TRUE,
57 org_unit INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED, -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
58 grp INT NOT NULL REFERENCES permission.grp_tree (id) DEFERRABLE INITIALLY DEFERRED, -- Set to the top applicable group from the group tree; will need descendents and prox functions for filtering
59 circ_modifier TEXT REFERENCES config.circ_modifier (code) DEFERRABLE INITIALLY DEFERRED,
64 copy_circ_lib INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
65 copy_owning_lib INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
66 user_home_ou INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
70 usr_age_lower_bound INTERVAL,
71 usr_age_upper_bound INTERVAL,
74 circulate BOOL, -- Hard "can't circ" flag requiring an override
75 duration_rule INT REFERENCES config.rule_circ_duration (id) DEFERRABLE INITIALLY DEFERRED,
76 recurring_fine_rule INT REFERENCES config.rule_recurring_fine (id) DEFERRABLE INITIALLY DEFERRED,
77 max_fine_rule INT REFERENCES config.rule_max_fine (id) DEFERRABLE INITIALLY DEFERRED,
78 hard_due_date INT REFERENCES config.hard_due_date (id) DEFERRABLE INITIALLY DEFERRED,
79 renewals INT, -- Renewal count override
80 grace_period INTERVAL, -- Grace period override
81 script_test TEXT, -- javascript source
82 total_copy_hold_ratio FLOAT,
83 available_copy_hold_ratio FLOAT
86 -- Nulls don't count for a constraint match, so we have to coalesce them into something that does.
87 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;
89 -- Limit groups for circ counting
90 CREATE TABLE config.circ_limit_group (
91 id SERIAL PRIMARY KEY,
92 name TEXT UNIQUE NOT NULL,
97 CREATE TABLE config.circ_limit_set (
98 id SERIAL PRIMARY KEY,
99 name TEXT UNIQUE NOT NULL,
100 owning_lib INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
101 items_out INT NOT NULL, -- Total current active circulations must be less than this. 0 means skip counting (always pass)
102 depth INT NOT NULL DEFAULT 0, -- Depth count starts at
103 global BOOL NOT NULL DEFAULT FALSE, -- If enabled, include everything below depth, otherwise ancestors/descendants only
107 -- Linkage between matchpoints and limit sets
108 CREATE TABLE config.circ_matrix_limit_set_map (
109 id SERIAL PRIMARY KEY,
110 matchpoint INT NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
111 limit_set INT NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
112 fallthrough BOOL NOT NULL DEFAULT FALSE, -- If true fallthrough will grab this rule as it goes along
113 active BOOL NOT NULL DEFAULT TRUE,
114 CONSTRAINT circ_limit_set_once_per_matchpoint UNIQUE (matchpoint, limit_set)
117 -- Linkage between limit sets and circ mods
118 CREATE TABLE config.circ_limit_set_circ_mod_map (
119 id SERIAL PRIMARY KEY,
120 limit_set INT NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
121 circ_mod TEXT NOT NULL REFERENCES config.circ_modifier (code) ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
122 CONSTRAINT cm_once_per_set UNIQUE (limit_set, circ_mod)
125 -- Linkage between limit sets and copy locations
126 CREATE TABLE config.circ_limit_set_copy_loc_map (
127 id SERIAL PRIMARY KEY,
128 limit_set INT NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
129 copy_loc INT NOT NULL REFERENCES asset.copy_location (id) ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
130 CONSTRAINT cl_once_per_set UNIQUE (limit_set, copy_loc)
133 -- Linkage between limit sets and limit groups
134 CREATE TABLE config.circ_limit_set_group_map (
135 id SERIAL PRIMARY KEY,
136 limit_set INT NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
137 limit_group INT NOT NULL REFERENCES config.circ_limit_group (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
138 check_only BOOL NOT NULL DEFAULT FALSE, -- If true, don't accumulate this limit_group for storing with the circulation
139 CONSTRAINT clg_once_per_set UNIQUE (limit_set, limit_group)
142 -- Linkage between limit groups and circulations
143 CREATE TABLE action.circulation_limit_group_map (
144 circ BIGINT NOT NULL REFERENCES action.circulation (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
145 limit_group INT NOT NULL REFERENCES config.circ_limit_group (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
146 PRIMARY KEY (circ, limit_group)
149 -- Function for populating the circ/limit group mappings
150 CREATE OR REPLACE FUNCTION action.link_circ_limit_groups ( BIGINT, INT[] ) RETURNS VOID AS $func$
151 INSERT INTO action.circulation_limit_group_map(circ, limit_group) SELECT $1, id FROM config.circ_limit_group WHERE id IN (SELECT * FROM UNNEST($2));
154 CREATE TYPE action.found_circ_matrix_matchpoint AS ( success BOOL, matchpoint config.circ_matrix_matchpoint, buildrows INT[] );
156 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$
158 cn_object asset.call_number%ROWTYPE;
159 rec_descriptor metabib.rec_descriptor%ROWTYPE;
160 cur_matchpoint config.circ_matrix_matchpoint%ROWTYPE;
161 matchpoint config.circ_matrix_matchpoint%ROWTYPE;
162 weights config.circ_matrix_weights%ROWTYPE;
164 my_item_age INTERVAL;
165 denominator NUMERIC(6,2);
167 result action.found_circ_matrix_matchpoint;
170 result.success = false;
173 SELECT INTO cn_object * FROM asset.call_number WHERE id = item_object.call_number;
174 SELECT INTO rec_descriptor * FROM metabib.rec_descriptor WHERE record = cn_object.record;
176 -- Pre-generate this so we only calc it once
177 IF user_object.dob IS NOT NULL THEN
178 SELECT INTO user_age age(user_object.dob);
182 SELECT INTO my_item_age age(coalesce(item_object.active_date, now()));
184 -- Grab the closest set circ weight setting.
185 SELECT INTO weights cw.*
186 FROM config.weight_assoc wa
187 JOIN config.circ_matrix_weights cw ON (cw.id = wa.circ_weights)
188 JOIN actor.org_unit_ancestors_distance( context_ou ) d ON (wa.org_unit = d.id)
193 -- No weights? Bad admin! Defaults to handle that anyway.
194 IF weights.id IS NULL THEN
196 weights.org_unit := 10.0;
197 weights.circ_modifier := 5.0;
198 weights.marc_type := 4.0;
199 weights.marc_form := 3.0;
200 weights.marc_bib_level := 2.0;
201 weights.marc_vr_format := 2.0;
202 weights.copy_circ_lib := 8.0;
203 weights.copy_owning_lib := 8.0;
204 weights.user_home_ou := 8.0;
205 weights.ref_flag := 1.0;
206 weights.juvenile_flag := 6.0;
207 weights.is_renewal := 7.0;
208 weights.usr_age_lower_bound := 0.0;
209 weights.usr_age_upper_bound := 0.0;
210 weights.item_age := 0.0;
213 -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
214 -- If you break your org tree with funky parenting this may be wrong
215 -- 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
216 -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
217 WITH all_distance(distance) AS (
218 SELECT depth AS distance FROM actor.org_unit_type
220 SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
222 SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
224 -- Loop over all the potential matchpoints
225 FOR cur_matchpoint IN
227 FROM config.circ_matrix_matchpoint m
228 /*LEFT*/ JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.grp = upgad.id
229 /*LEFT*/ JOIN actor.org_unit_ancestors_distance( context_ou ) ctoua ON m.org_unit = ctoua.id
230 LEFT JOIN actor.org_unit_ancestors_distance( cn_object.owning_lib ) cnoua ON m.copy_owning_lib = cnoua.id
231 LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.copy_circ_lib = iooua.id
232 LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou ) uhoua ON m.user_home_ou = uhoua.id
235 -- AND (m.grp IS NULL OR upgad.id IS NOT NULL) -- Optional Permission Group?
237 -- AND (m.org_unit IS NULL OR ctoua.id IS NOT NULL) -- Optional Org Unit?
238 AND (m.copy_owning_lib IS NULL OR cnoua.id IS NOT NULL)
239 AND (m.copy_circ_lib IS NULL OR iooua.id IS NOT NULL)
240 AND (m.user_home_ou IS NULL OR uhoua.id IS NOT NULL)
242 AND (m.is_renewal IS NULL OR m.is_renewal = renewal)
243 -- Static User Checks
244 AND (m.juvenile_flag IS NULL OR m.juvenile_flag = user_object.juvenile)
245 AND (m.usr_age_lower_bound IS NULL OR (user_age IS NOT NULL AND m.usr_age_lower_bound < user_age))
246 AND (m.usr_age_upper_bound IS NULL OR (user_age IS NOT NULL AND m.usr_age_upper_bound > user_age))
247 -- Static Item Checks
248 AND (m.circ_modifier IS NULL OR m.circ_modifier = item_object.circ_modifier)
249 AND (m.marc_type IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
250 AND (m.marc_form IS NULL OR m.marc_form = rec_descriptor.item_form)
251 AND (m.marc_bib_level IS NULL OR m.marc_bib_level = rec_descriptor.bib_level)
252 AND (m.marc_vr_format IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
253 AND (m.ref_flag IS NULL OR m.ref_flag = item_object.ref)
254 AND (m.item_age IS NULL OR (my_item_age IS NOT NULL AND m.item_age > my_item_age))
257 CASE WHEN upgad.distance IS NOT NULL THEN 2^(2*weights.grp - (upgad.distance/denominator)) ELSE 0.0 END +
259 CASE WHEN ctoua.distance IS NOT NULL THEN 2^(2*weights.org_unit - (ctoua.distance/denominator)) ELSE 0.0 END +
260 CASE WHEN cnoua.distance IS NOT NULL THEN 2^(2*weights.copy_owning_lib - (cnoua.distance/denominator)) ELSE 0.0 END +
261 CASE WHEN iooua.distance IS NOT NULL THEN 2^(2*weights.copy_circ_lib - (iooua.distance/denominator)) ELSE 0.0 END +
262 CASE WHEN uhoua.distance IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
263 -- Circ Type -- Note: 4^x is equiv to 2^(2*x)
264 CASE WHEN m.is_renewal IS NOT NULL THEN 4^weights.is_renewal ELSE 0.0 END +
265 -- Static User Checks
266 CASE WHEN m.juvenile_flag IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
267 CASE WHEN m.usr_age_lower_bound IS NOT NULL THEN 4^weights.usr_age_lower_bound ELSE 0.0 END +
268 CASE WHEN m.usr_age_upper_bound IS NOT NULL THEN 4^weights.usr_age_upper_bound ELSE 0.0 END +
269 -- Static Item Checks
270 CASE WHEN m.circ_modifier IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
271 CASE WHEN m.marc_type IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
272 CASE WHEN m.marc_form IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
273 CASE WHEN m.marc_vr_format IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
274 CASE WHEN m.ref_flag IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END +
275 -- Item age has a slight adjustment to weight based on value.
276 -- This should ensure that a shorter age limit comes first when all else is equal.
277 -- NOTE: This assumes that intervals will normally be in days.
278 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,
279 -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
280 -- This prevents "we changed the table order by updating a rule, and we started getting different results"
283 -- Record the full matching row list
284 row_list := row_list || cur_matchpoint.id;
286 -- No matchpoint yet?
287 IF matchpoint.id IS NULL THEN
288 -- Take the entire matchpoint as a starting point
289 matchpoint := cur_matchpoint;
290 CONTINUE; -- No need to look at this row any more.
293 -- Incomplete matchpoint?
294 IF matchpoint.circulate IS NULL THEN
295 matchpoint.circulate := cur_matchpoint.circulate;
297 IF matchpoint.duration_rule IS NULL THEN
298 matchpoint.duration_rule := cur_matchpoint.duration_rule;
300 IF matchpoint.recurring_fine_rule IS NULL THEN
301 matchpoint.recurring_fine_rule := cur_matchpoint.recurring_fine_rule;
303 IF matchpoint.max_fine_rule IS NULL THEN
304 matchpoint.max_fine_rule := cur_matchpoint.max_fine_rule;
306 IF matchpoint.hard_due_date IS NULL THEN
307 matchpoint.hard_due_date := cur_matchpoint.hard_due_date;
309 IF matchpoint.total_copy_hold_ratio IS NULL THEN
310 matchpoint.total_copy_hold_ratio := cur_matchpoint.total_copy_hold_ratio;
312 IF matchpoint.available_copy_hold_ratio IS NULL THEN
313 matchpoint.available_copy_hold_ratio := cur_matchpoint.available_copy_hold_ratio;
315 IF matchpoint.renewals IS NULL THEN
316 matchpoint.renewals := cur_matchpoint.renewals;
318 IF matchpoint.grace_period IS NULL THEN
319 matchpoint.grace_period := cur_matchpoint.grace_period;
323 -- Check required fields
324 IF matchpoint.circulate IS NOT NULL AND
325 matchpoint.duration_rule IS NOT NULL AND
326 matchpoint.recurring_fine_rule IS NOT NULL AND
327 matchpoint.max_fine_rule IS NOT NULL THEN
328 -- All there? We have a completed match.
329 result.success := true;
332 -- Include the assembled matchpoint, even if it isn't complete
333 result.matchpoint := matchpoint;
335 -- Include (for debugging) the full list of matching rows
336 result.buildrows := row_list;
338 -- Hand the result back to caller
341 $func$ LANGUAGE plpgsql;
343 -- Helper function - For manual calling, it can be easier to pass in IDs instead of objects
344 CREATE OR REPLACE FUNCTION action.find_circ_matrix_matchpoint( context_ou INT, match_item BIGINT, match_user INT, renewal BOOL ) RETURNS SETOF action.found_circ_matrix_matchpoint AS $func$
346 item_object asset.copy%ROWTYPE;
347 user_object actor.usr%ROWTYPE;
349 SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
350 SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
352 RETURN QUERY SELECT * FROM action.find_circ_matrix_matchpoint( context_ou, item_object, user_object, renewal );
354 $func$ LANGUAGE plpgsql;
356 CREATE TYPE action.hold_stats AS (
360 total_copy_ratio FLOAT,
361 available_copy_ratio FLOAT
364 CREATE OR REPLACE FUNCTION action.copy_related_hold_stats (copy_id INT) RETURNS action.hold_stats AS $func$
366 output action.hold_stats%ROWTYPE;
369 available_count INT := 0;
370 hold_map_data RECORD;
373 output.hold_count := 0;
374 output.copy_count := 0;
375 output.available_count := 0;
377 SELECT COUNT( DISTINCT m.hold ) INTO hold_count
378 FROM action.hold_copy_map m
379 JOIN action.hold_request h ON (m.hold = h.id)
380 WHERE m.target_copy = copy_id
383 output.hold_count := hold_count;
385 IF output.hold_count > 0 THEN
387 SELECT DISTINCT m.target_copy,
389 FROM action.hold_copy_map m
390 JOIN asset.copy acp ON (m.target_copy = acp.id)
391 JOIN action.hold_request h ON (m.hold = h.id)
392 WHERE m.hold IN ( SELECT DISTINCT hold FROM action.hold_copy_map WHERE target_copy = copy_id ) AND NOT h.frozen
394 output.copy_count := output.copy_count + 1;
395 IF hold_map_data.status IN (0,7,12) THEN
396 output.available_count := output.available_count + 1;
399 output.total_copy_ratio = output.copy_count::FLOAT / output.hold_count::FLOAT;
400 output.available_copy_ratio = output.available_count::FLOAT / output.hold_count::FLOAT;
407 $func$ LANGUAGE PLPGSQL;
409 CREATE TYPE action.circ_matrix_test_result AS ( success BOOL, fail_part TEXT, buildrows INT[], matchpoint INT, circulate BOOL, duration_rule INT, recurring_fine_rule INT, max_fine_rule INT, hard_due_date INT, renewals INT, grace_period INTERVAL, limit_groups INT[] );
410 CREATE OR REPLACE FUNCTION action.item_user_circ_test( circ_ou INT, match_item BIGINT, match_user INT, renewal BOOL ) RETURNS SETOF action.circ_matrix_test_result AS $func$
412 user_object actor.usr%ROWTYPE;
413 standing_penalty config.standing_penalty%ROWTYPE;
414 item_object asset.copy%ROWTYPE;
415 item_status_object config.copy_status%ROWTYPE;
416 item_location_object asset.copy_location%ROWTYPE;
417 result action.circ_matrix_test_result;
418 circ_test action.found_circ_matrix_matchpoint;
419 circ_matchpoint config.circ_matrix_matchpoint%ROWTYPE;
420 circ_limit_set config.circ_limit_set%ROWTYPE;
421 hold_ratio action.hold_stats%ROWTYPE;
424 context_org_list INT[];
427 -- Assume success unless we hit a failure condition
428 result.success := TRUE;
430 -- Need user info to look up matchpoints
431 SELECT INTO user_object * FROM actor.usr WHERE id = match_user AND NOT deleted;
433 -- (Insta)Fail if we couldn't find the user
434 IF user_object.id IS NULL THEN
435 result.fail_part := 'no_user';
436 result.success := FALSE;
442 -- Need item info to look up matchpoints
443 SELECT INTO item_object * FROM asset.copy WHERE id = match_item AND NOT deleted;
445 -- (Insta)Fail if we couldn't find the item
446 IF item_object.id IS NULL THEN
447 result.fail_part := 'no_item';
448 result.success := FALSE;
454 SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, item_object, user_object, renewal);
456 circ_matchpoint := circ_test.matchpoint;
457 result.matchpoint := circ_matchpoint.id;
458 result.circulate := circ_matchpoint.circulate;
459 result.duration_rule := circ_matchpoint.duration_rule;
460 result.recurring_fine_rule := circ_matchpoint.recurring_fine_rule;
461 result.max_fine_rule := circ_matchpoint.max_fine_rule;
462 result.hard_due_date := circ_matchpoint.hard_due_date;
463 result.renewals := circ_matchpoint.renewals;
464 result.grace_period := circ_matchpoint.grace_period;
465 result.buildrows := circ_test.buildrows;
467 -- (Insta)Fail if we couldn't find a matchpoint
468 IF circ_test.success = false THEN
469 result.fail_part := 'no_matchpoint';
470 result.success := FALSE;
476 -- All failures before this point are non-recoverable
477 -- Below this point are possibly overridable failures
479 -- Fail if the user is barred
480 IF user_object.barred IS TRUE THEN
481 result.fail_part := 'actor.usr.barred';
482 result.success := FALSE;
487 -- Fail if the item can't circulate
488 IF item_object.circulate IS FALSE THEN
489 result.fail_part := 'asset.copy.circulate';
490 result.success := FALSE;
495 -- Fail if the item isn't in a circulateable status on a non-renewal
496 IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN
497 result.fail_part := 'asset.copy.status';
498 result.success := FALSE;
501 -- Alternately, fail if the item isn't checked out on a renewal
502 ELSIF renewal AND item_object.status <> 1 THEN
503 result.fail_part := 'asset.copy.status';
504 result.success := FALSE;
509 -- Fail if the item can't circulate because of the shelving location
510 SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
511 IF item_location_object.circulate IS FALSE THEN
512 result.fail_part := 'asset.copy_location.circulate';
513 result.success := FALSE;
518 -- Use Circ OU for penalties and such
519 SELECT INTO context_org_list ARRAY_AGG(id) FROM actor.org_unit_full_path( circ_ou );
522 penalty_type = '%RENEW%';
524 penalty_type = '%CIRC%';
527 FOR standing_penalty IN
528 SELECT DISTINCT csp.*
529 FROM actor.usr_standing_penalty usp
530 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
531 WHERE usr = match_user
532 AND usp.org_unit IN ( SELECT * FROM unnest(context_org_list) )
533 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
534 AND csp.block_list LIKE penalty_type LOOP
536 result.fail_part := standing_penalty.name;
537 result.success := FALSE;
542 -- Fail if the test is set to hard non-circulating
543 IF circ_matchpoint.circulate IS FALSE THEN
544 result.fail_part := 'config.circ_matrix_test.circulate';
545 result.success := FALSE;
550 -- Fail if the total copy-hold ratio is too low
551 IF circ_matchpoint.total_copy_hold_ratio IS NOT NULL THEN
552 SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
553 IF hold_ratio.total_copy_ratio IS NOT NULL AND hold_ratio.total_copy_ratio < circ_matchpoint.total_copy_hold_ratio THEN
554 result.fail_part := 'config.circ_matrix_test.total_copy_hold_ratio';
555 result.success := FALSE;
561 -- Fail if the available copy-hold ratio is too low
562 IF circ_matchpoint.available_copy_hold_ratio IS NOT NULL THEN
563 IF hold_ratio.hold_count IS NULL THEN
564 SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
566 IF hold_ratio.available_copy_ratio IS NOT NULL AND hold_ratio.available_copy_ratio < circ_matchpoint.available_copy_hold_ratio THEN
567 result.fail_part := 'config.circ_matrix_test.available_copy_hold_ratio';
568 result.success := FALSE;
574 -- Fail if the user has too many items out by defined limit sets
575 FOR circ_limit_set IN SELECT ccls.* FROM config.circ_limit_set ccls
576 JOIN config.circ_matrix_limit_set_map ccmlsm ON ccmlsm.limit_set = ccls.id
577 WHERE ccmlsm.active AND ( ccmlsm.matchpoint = circ_matchpoint.id OR
578 ( ccmlsm.matchpoint IN (SELECT * FROM unnest(result.buildrows)) AND ccmlsm.fallthrough )
580 IF circ_limit_set.items_out > 0 AND NOT renewal THEN
581 SELECT INTO context_org_list ARRAY_AGG(aou.id)
582 FROM actor.org_unit_full_path( circ_ou ) aou
583 JOIN actor.org_unit_type aout ON aou.ou_type = aout.id
584 WHERE aout.depth >= circ_limit_set.depth;
585 IF circ_limit_set.global THEN
586 WITH RECURSIVE descendant_depth AS (
589 FROM actor.org_unit ou
590 WHERE ou.id IN (SELECT * FROM unnest(context_org_list))
594 FROM actor.org_unit ou
595 JOIN descendant_depth ot ON (ot.id = ou.parent_ou)
596 ) SELECT INTO context_org_list ARRAY_AGG(ou.id) FROM actor.org_unit ou JOIN descendant_depth USING (id);
598 SELECT INTO items_out COUNT(DISTINCT circ.id)
599 FROM action.circulation circ
600 JOIN asset.copy copy ON (copy.id = circ.target_copy)
601 LEFT JOIN action.circulation_limit_group_map aclgm ON (circ.id = aclgm.circ)
602 WHERE circ.usr = match_user
603 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
604 AND circ.checkin_time IS NULL
605 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
606 AND (copy.circ_modifier IN (SELECT circ_mod FROM config.circ_limit_set_circ_mod_map WHERE limit_set = circ_limit_set.id)
607 OR copy.location IN (SELECT copy_loc FROM config.circ_limit_set_copy_loc_map WHERE limit_set = circ_limit_set.id)
608 OR aclgm.limit_group IN (SELECT limit_group FROM config.circ_limit_set_group_map WHERE limit_set = circ_limit_set.id)
610 IF items_out >= circ_limit_set.items_out THEN
611 result.fail_part := 'config.circ_matrix_circ_mod_test';
612 result.success := FALSE;
617 SELECT INTO result.limit_groups result.limit_groups || ARRAY_AGG(limit_group) FROM config.circ_limit_set_group_map WHERE limit_set = circ_limit_set.id AND NOT check_only;
620 -- If we passed everything, return the successful matchpoint
627 $func$ LANGUAGE plpgsql;
629 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
630 SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
633 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
634 SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
638 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
640 user_object actor.usr%ROWTYPE;
641 new_sp_row actor.usr_standing_penalty%ROWTYPE;
642 existing_sp_row actor.usr_standing_penalty%ROWTYPE;
643 collections_fines permission.grp_penalty_threshold%ROWTYPE;
644 max_fines permission.grp_penalty_threshold%ROWTYPE;
645 max_overdue permission.grp_penalty_threshold%ROWTYPE;
646 max_items_out permission.grp_penalty_threshold%ROWTYPE;
650 context_org_list INT[];
651 current_fines NUMERIC(8,2) := 0.0;
652 tmp_fines NUMERIC(8,2);
655 tmp_org actor.org_unit%ROWTYPE;
656 tmp_penalty config.standing_penalty%ROWTYPE;
659 SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
662 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
664 -- Fail if the user has a high fine balance
666 tmp_grp := user_object.profile;
668 SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
670 IF max_fines.threshold IS NULL THEN
671 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
676 IF tmp_grp IS NULL THEN
681 IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
685 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
689 IF max_fines.threshold IS NOT NULL THEN
693 FROM actor.usr_standing_penalty
694 WHERE usr = match_user
695 AND org_unit = max_fines.org_unit
696 AND (stop_date IS NULL or stop_date > NOW())
697 AND standing_penalty = 1;
699 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
701 SELECT SUM(f.balance_owed) INTO current_fines
702 FROM money.materialized_billable_xact_summary f
705 FROM booking.reservation r
706 WHERE r.usr = match_user
707 AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
708 AND xact_finish IS NULL
712 WHERE g.usr = match_user
713 AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
714 AND xact_finish IS NULL
717 FROM action.circulation circ
718 WHERE circ.usr = match_user
719 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
720 AND xact_finish IS NULL ) l USING (id);
722 IF current_fines >= max_fines.threshold THEN
723 new_sp_row.usr := match_user;
724 new_sp_row.org_unit := max_fines.org_unit;
725 new_sp_row.standing_penalty := 1;
726 RETURN NEXT new_sp_row;
730 -- Start over for max overdue
731 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
733 -- Fail if the user has too many overdue items
735 tmp_grp := user_object.profile;
738 SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
740 IF max_overdue.threshold IS NULL THEN
741 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
746 IF tmp_grp IS NULL THEN
751 IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
755 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
759 IF max_overdue.threshold IS NOT NULL THEN
763 FROM actor.usr_standing_penalty
764 WHERE usr = match_user
765 AND org_unit = max_overdue.org_unit
766 AND (stop_date IS NULL or stop_date > NOW())
767 AND standing_penalty = 2;
769 SELECT INTO items_overdue COUNT(*)
770 FROM action.circulation circ
771 JOIN actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
772 WHERE circ.usr = match_user
773 AND circ.checkin_time IS NULL
774 AND circ.due_date < NOW()
775 AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
777 IF items_overdue >= max_overdue.threshold::INT THEN
778 new_sp_row.usr := match_user;
779 new_sp_row.org_unit := max_overdue.org_unit;
780 new_sp_row.standing_penalty := 2;
781 RETURN NEXT new_sp_row;
785 -- Start over for max out
786 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
788 -- Fail if the user has too many checked out items
790 tmp_grp := user_object.profile;
792 SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
794 IF max_items_out.threshold IS NULL THEN
795 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
800 IF tmp_grp IS NULL THEN
805 IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
809 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
814 -- Fail if the user has too many items checked out
815 IF max_items_out.threshold IS NOT NULL THEN
819 FROM actor.usr_standing_penalty
820 WHERE usr = match_user
821 AND org_unit = max_items_out.org_unit
822 AND (stop_date IS NULL or stop_date > NOW())
823 AND standing_penalty = 3;
825 SELECT INTO items_out COUNT(*)
826 FROM action.circulation circ
827 JOIN actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
828 WHERE circ.usr = match_user
829 AND circ.checkin_time IS NULL
830 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL);
832 IF items_out >= max_items_out.threshold::INT THEN
833 new_sp_row.usr := match_user;
834 new_sp_row.org_unit := max_items_out.org_unit;
835 new_sp_row.standing_penalty := 3;
836 RETURN NEXT new_sp_row;
840 -- Start over for collections warning
841 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
843 -- Fail if the user has a collections-level fine balance
845 tmp_grp := user_object.profile;
847 SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
849 IF max_fines.threshold IS NULL THEN
850 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
855 IF tmp_grp IS NULL THEN
860 IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
864 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
868 IF max_fines.threshold IS NOT NULL THEN
872 FROM actor.usr_standing_penalty
873 WHERE usr = match_user
874 AND org_unit = max_fines.org_unit
875 AND (stop_date IS NULL or stop_date > NOW())
876 AND standing_penalty = 4;
878 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
880 SELECT SUM(f.balance_owed) INTO current_fines
881 FROM money.materialized_billable_xact_summary f
884 FROM booking.reservation r
885 WHERE r.usr = match_user
886 AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
887 AND r.xact_finish IS NULL
891 WHERE g.usr = match_user
892 AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
893 AND g.xact_finish IS NULL
896 FROM action.circulation circ
897 WHERE circ.usr = match_user
898 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
899 AND circ.xact_finish IS NULL ) l USING (id);
901 IF current_fines >= max_fines.threshold THEN
902 new_sp_row.usr := match_user;
903 new_sp_row.org_unit := max_fines.org_unit;
904 new_sp_row.standing_penalty := 4;
905 RETURN NEXT new_sp_row;
909 -- Start over for in collections
910 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
912 -- Remove the in-collections penalty if the user has paid down enough
913 -- This penalty is different, because this code is not responsible for creating
914 -- new in-collections penalties, only for removing them
916 tmp_grp := user_object.profile;
918 SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 30 AND org_unit = tmp_org.id;
920 IF max_fines.threshold IS NULL THEN
921 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
926 IF tmp_grp IS NULL THEN
931 IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
935 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
939 IF max_fines.threshold IS NOT NULL THEN
941 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
943 -- first, see if the user had paid down to the threshold
944 SELECT SUM(f.balance_owed) INTO current_fines
945 FROM money.materialized_billable_xact_summary f
948 FROM booking.reservation r
949 WHERE r.usr = match_user
950 AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
951 AND r.xact_finish IS NULL
955 WHERE g.usr = match_user
956 AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
957 AND g.xact_finish IS NULL
960 FROM action.circulation circ
961 WHERE circ.usr = match_user
962 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
963 AND circ.xact_finish IS NULL ) l USING (id);
965 IF current_fines IS NULL OR current_fines <= max_fines.threshold THEN
966 -- patron has paid down enough
968 SELECT INTO tmp_penalty * FROM config.standing_penalty WHERE id = 30;
970 IF tmp_penalty.org_depth IS NOT NULL THEN
972 -- since this code is not responsible for applying the penalty, it can't
973 -- guarantee the current context org will match the org at which the penalty
974 --- was applied. search up the org tree until we hit the configured penalty depth
975 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
976 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
978 WHILE tmp_depth >= tmp_penalty.org_depth LOOP
982 FROM actor.usr_standing_penalty
983 WHERE usr = match_user
984 AND org_unit = tmp_org.id
985 AND (stop_date IS NULL or stop_date > NOW())
986 AND standing_penalty = 30;
988 IF tmp_org.parent_ou IS NULL THEN
992 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
993 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
998 -- no penalty depth is defined, look for exact matches
1002 FROM actor.usr_standing_penalty
1003 WHERE usr = match_user
1004 AND org_unit = max_fines.org_unit
1005 AND (stop_date IS NULL or stop_date > NOW())
1006 AND standing_penalty = 30;
1015 $func$ LANGUAGE plpgsql;