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,
63 copy_circ_lib INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
64 copy_owning_lib INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
65 user_home_ou INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
69 usr_age_lower_bound INTERVAL,
70 usr_age_upper_bound INTERVAL,
72 circulate BOOL, -- Hard "can't circ" flag requiring an override
73 duration_rule INT REFERENCES config.rule_circ_duration (id) DEFERRABLE INITIALLY DEFERRED,
74 recurring_fine_rule INT REFERENCES config.rule_recurring_fine (id) DEFERRABLE INITIALLY DEFERRED,
75 max_fine_rule INT REFERENCES config.rule_max_fine (id) DEFERRABLE INITIALLY DEFERRED,
76 hard_due_date INT REFERENCES config.hard_due_date (id) DEFERRABLE INITIALLY DEFERRED,
77 renewals INT, -- Renewal count override
78 script_test TEXT, -- javascript source
79 total_copy_hold_ratio FLOAT,
80 available_copy_hold_ratio FLOAT
83 -- Nulls don't count for a constraint match, so we have to coalesce them into something that does.
84 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_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, '')) WHERE active;
86 -- Tests for max items out by circ_modifier
87 CREATE TABLE config.circ_matrix_circ_mod_test (
88 id SERIAL PRIMARY KEY,
89 matchpoint INT NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
90 items_out INT NOT NULL -- Total current active circulations must be less than this, NULL means skip (always pass)
93 CREATE TABLE config.circ_matrix_circ_mod_test_map (
94 id SERIAL PRIMARY KEY,
95 circ_mod_test INT NOT NULL REFERENCES config.circ_matrix_circ_mod_test (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
96 circ_mod TEXT NOT NULL REFERENCES config.circ_modifier (code) ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
97 CONSTRAINT cm_once_per_test UNIQUE (circ_mod_test, circ_mod)
100 CREATE TYPE action.found_circ_matrix_matchpoint AS ( success BOOL, matchpoint config.circ_matrix_matchpoint, buildrows INT[] );
102 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$
104 cn_object asset.call_number%ROWTYPE;
105 rec_descriptor metabib.rec_descriptor%ROWTYPE;
106 cur_matchpoint config.circ_matrix_matchpoint%ROWTYPE;
107 matchpoint config.circ_matrix_matchpoint%ROWTYPE;
108 weights config.circ_matrix_weights%ROWTYPE;
110 denominator NUMERIC(6,2);
112 result action.found_circ_matrix_matchpoint;
115 result.success = false;
118 SELECT INTO cn_object * FROM asset.call_number WHERE id = item_object.call_number;
119 SELECT INTO rec_descriptor * FROM metabib.rec_descriptor WHERE record = cn_object.record;
121 -- Pre-generate this so we only calc it once
122 IF user_object.dob IS NOT NULL THEN
123 SELECT INTO user_age age(user_object.dob);
126 -- Grab the closest set circ weight setting.
127 SELECT INTO weights cw.*
128 FROM config.weight_assoc wa
129 JOIN config.circ_matrix_weights cw ON (cw.id = wa.circ_weights)
130 JOIN actor.org_unit_ancestors_distance( context_ou ) d ON (wa.org_unit = d.id)
135 -- No weights? Bad admin! Defaults to handle that anyway.
136 IF weights.id IS NULL THEN
138 weights.org_unit := 10.0;
139 weights.circ_modifier := 5.0;
140 weights.marc_type := 4.0;
141 weights.marc_form := 3.0;
142 weights.marc_vr_format := 2.0;
143 weights.copy_circ_lib := 8.0;
144 weights.copy_owning_lib := 8.0;
145 weights.user_home_ou := 8.0;
146 weights.ref_flag := 1.0;
147 weights.juvenile_flag := 6.0;
148 weights.is_renewal := 7.0;
149 weights.usr_age_lower_bound := 0.0;
150 weights.usr_age_upper_bound := 0.0;
153 -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
154 -- If you break your org tree with funky parenting this may be wrong
155 -- 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
156 -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
157 WITH all_distance(distance) AS (
158 SELECT depth AS distance FROM actor.org_unit_type
160 SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
162 SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
164 -- Loop over all the potential matchpoints
165 FOR cur_matchpoint IN
167 FROM config.circ_matrix_matchpoint m
168 /*LEFT*/ JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.grp = upgad.id
169 /*LEFT*/ JOIN actor.org_unit_ancestors_distance( context_ou ) ctoua ON m.org_unit = ctoua.id
170 LEFT JOIN actor.org_unit_ancestors_distance( cn_object.owning_lib ) cnoua ON m.copy_owning_lib = cnoua.id
171 LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.copy_circ_lib = iooua.id
172 LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou ) uhoua ON m.user_home_ou = uhoua.id
175 -- AND (m.grp IS NULL OR upgad.id IS NOT NULL) -- Optional Permission Group?
177 -- AND (m.org_unit IS NULL OR ctoua.id IS NOT NULL) -- Optional Org Unit?
178 AND (m.copy_owning_lib IS NULL OR cnoua.id IS NOT NULL)
179 AND (m.copy_circ_lib IS NULL OR iooua.id IS NOT NULL)
180 AND (m.user_home_ou IS NULL OR uhoua.id IS NOT NULL)
182 AND (m.is_renewal IS NULL OR m.is_renewal = renewal)
183 -- Static User Checks
184 AND (m.juvenile_flag IS NULL OR m.juvenile_flag = user_object.juvenile)
185 AND (m.usr_age_lower_bound IS NULL OR (user_age IS NOT NULL AND m.usr_age_lower_bound < user_age))
186 AND (m.usr_age_upper_bound IS NULL OR (user_age IS NOT NULL AND m.usr_age_upper_bound > user_age))
187 -- Static Item Checks
188 AND (m.circ_modifier IS NULL OR m.circ_modifier = item_object.circ_modifier)
189 AND (m.marc_type IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
190 AND (m.marc_form IS NULL OR m.marc_form = rec_descriptor.item_form)
191 AND (m.marc_vr_format IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
192 AND (m.ref_flag IS NULL OR m.ref_flag = item_object.ref)
195 CASE WHEN upgad.distance IS NOT NULL THEN 2^(2*weights.grp - (upgad.distance/denominator)) ELSE 0.0 END +
197 CASE WHEN ctoua.distance IS NOT NULL THEN 2^(2*weights.org_unit - (ctoua.distance/denominator)) ELSE 0.0 END +
198 CASE WHEN cnoua.distance IS NOT NULL THEN 2^(2*weights.copy_owning_lib - (cnoua.distance/denominator)) ELSE 0.0 END +
199 CASE WHEN iooua.distance IS NOT NULL THEN 2^(2*weights.copy_circ_lib - (iooua.distance/denominator)) ELSE 0.0 END +
200 CASE WHEN uhoua.distance IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
201 -- Circ Type -- Note: 4^x is equiv to 2^(2*x)
202 CASE WHEN m.is_renewal IS NOT NULL THEN 4^weights.is_renewal ELSE 0.0 END +
203 -- Static User Checks
204 CASE WHEN m.juvenile_flag IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
205 CASE WHEN m.usr_age_lower_bound IS NOT NULL THEN 4^weights.usr_age_lower_bound ELSE 0.0 END +
206 CASE WHEN m.usr_age_upper_bound IS NOT NULL THEN 4^weights.usr_age_upper_bound ELSE 0.0 END +
207 -- Static Item Checks
208 CASE WHEN m.circ_modifier IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
209 CASE WHEN m.marc_type IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
210 CASE WHEN m.marc_form IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
211 CASE WHEN m.marc_vr_format IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
212 CASE WHEN m.ref_flag IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END DESC,
213 -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
214 -- This prevents "we changed the table order by updating a rule, and we started getting different results"
217 -- Record the full matching row list
218 row_list := row_list || cur_matchpoint.id;
220 -- No matchpoint yet?
221 IF matchpoint.id IS NULL THEN
222 -- Take the entire matchpoint as a starting point
223 matchpoint := cur_matchpoint;
224 CONTINUE; -- No need to look at this row any more.
227 -- Incomplete matchpoint?
228 IF matchpoint.circulate IS NULL THEN
229 matchpoint.circulate := cur_matchpoint.circulate;
231 IF matchpoint.duration_rule IS NULL THEN
232 matchpoint.duration_rule := cur_matchpoint.duration_rule;
234 IF matchpoint.recurring_fine_rule IS NULL THEN
235 matchpoint.recurring_fine_rule := cur_matchpoint.recurring_fine_rule;
237 IF matchpoint.max_fine_rule IS NULL THEN
238 matchpoint.max_fine_rule := cur_matchpoint.max_fine_rule;
240 IF matchpoint.hard_due_date IS NULL THEN
241 matchpoint.hard_due_date := cur_matchpoint.hard_due_date;
243 IF matchpoint.total_copy_hold_ratio IS NULL THEN
244 matchpoint.total_copy_hold_ratio := cur_matchpoint.total_copy_hold_ratio;
246 IF matchpoint.available_copy_hold_ratio IS NULL THEN
247 matchpoint.available_copy_hold_ratio := cur_matchpoint.available_copy_hold_ratio;
249 IF matchpoint.renewals IS NULL THEN
250 matchpoint.renewals := cur_matchpoint.renewals;
254 -- Check required fields
255 IF matchpoint.circulate IS NOT NULL AND
256 matchpoint.duration_rule IS NOT NULL AND
257 matchpoint.recurring_fine_rule IS NOT NULL AND
258 matchpoint.max_fine_rule IS NOT NULL THEN
259 -- All there? We have a completed match.
260 result.success := true;
263 -- Include the assembled matchpoint, even if it isn't complete
264 result.matchpoint := matchpoint;
266 -- Include (for debugging) the full list of matching rows
267 result.buildrows := row_list;
269 -- Hand the result back to caller
272 $func$ LANGUAGE plpgsql;
274 -- Helper function - For manual calling, it can be easier to pass in IDs instead of objects
275 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$
277 item_object asset.copy%ROWTYPE;
278 user_object actor.usr%ROWTYPE;
280 SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
281 SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
283 RETURN QUERY SELECT * FROM action.find_circ_matrix_matchpoint( context_ou, item_object, user_object, renewal );
285 $func$ LANGUAGE plpgsql;
287 CREATE TYPE action.hold_stats AS (
291 total_copy_ratio FLOAT,
292 available_copy_ratio FLOAT
295 CREATE OR REPLACE FUNCTION action.copy_related_hold_stats (copy_id INT) RETURNS action.hold_stats AS $func$
297 output action.hold_stats%ROWTYPE;
300 available_count INT := 0;
301 hold_map_data RECORD;
304 output.hold_count := 0;
305 output.copy_count := 0;
306 output.available_count := 0;
308 SELECT COUNT( DISTINCT m.hold ) INTO hold_count
309 FROM action.hold_copy_map m
310 JOIN action.hold_request h ON (m.hold = h.id)
311 WHERE m.target_copy = copy_id
314 output.hold_count := hold_count;
316 IF output.hold_count > 0 THEN
318 SELECT DISTINCT m.target_copy,
320 FROM action.hold_copy_map m
321 JOIN asset.copy acp ON (m.target_copy = acp.id)
322 JOIN action.hold_request h ON (m.hold = h.id)
323 WHERE m.hold IN ( SELECT DISTINCT hold FROM action.hold_copy_map WHERE target_copy = copy_id ) AND NOT h.frozen
325 output.copy_count := output.copy_count + 1;
326 IF hold_map_data.status IN (0,7,12) THEN
327 output.available_count := output.available_count + 1;
330 output.total_copy_ratio = output.copy_count::FLOAT / output.hold_count::FLOAT;
331 output.available_copy_ratio = output.available_count::FLOAT / output.hold_count::FLOAT;
338 $func$ LANGUAGE PLPGSQL;
340 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 );
341 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$
343 user_object actor.usr%ROWTYPE;
344 standing_penalty config.standing_penalty%ROWTYPE;
345 item_object asset.copy%ROWTYPE;
346 item_status_object config.copy_status%ROWTYPE;
347 item_location_object asset.copy_location%ROWTYPE;
348 result action.circ_matrix_test_result;
349 circ_test action.found_circ_matrix_matchpoint;
350 circ_matchpoint config.circ_matrix_matchpoint%ROWTYPE;
351 out_by_circ_mod config.circ_matrix_circ_mod_test%ROWTYPE;
352 circ_mod_map config.circ_matrix_circ_mod_test_map%ROWTYPE;
353 hold_ratio action.hold_stats%ROWTYPE;
356 context_org_list INT[];
359 -- Assume success unless we hit a failure condition
360 result.success := TRUE;
362 -- Fail if the user is BARRED
363 SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
365 -- Fail if we couldn't find the user
366 IF user_object.id IS NULL THEN
367 result.fail_part := 'no_user';
368 result.success := FALSE;
374 SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
376 -- Fail if we couldn't find the item
377 IF item_object.id IS NULL THEN
378 result.fail_part := 'no_item';
379 result.success := FALSE;
385 IF user_object.barred IS TRUE THEN
386 result.fail_part := 'actor.usr.barred';
387 result.success := FALSE;
392 -- Fail if the item can't circulate
393 IF item_object.circulate IS FALSE THEN
394 result.fail_part := 'asset.copy.circulate';
395 result.success := FALSE;
400 -- Fail if the item isn't in a circulateable status on a non-renewal
401 IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN
402 result.fail_part := 'asset.copy.status';
403 result.success := FALSE;
406 ELSIF renewal AND item_object.status <> 1 THEN
407 result.fail_part := 'asset.copy.status';
408 result.success := FALSE;
413 -- Fail if the item can't circulate because of the shelving location
414 SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
415 IF item_location_object.circulate IS FALSE THEN
416 result.fail_part := 'asset.copy_location.circulate';
417 result.success := FALSE;
422 SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, item_object, user_object, renewal);
424 circ_matchpoint := circ_test.matchpoint;
425 result.matchpoint := circ_matchpoint.id;
426 result.circulate := circ_matchpoint.circulate;
427 result.duration_rule := circ_matchpoint.duration_rule;
428 result.recurring_fine_rule := circ_matchpoint.recurring_fine_rule;
429 result.max_fine_rule := circ_matchpoint.max_fine_rule;
430 result.hard_due_date := circ_matchpoint.hard_due_date;
431 result.renewals := circ_matchpoint.renewals;
432 result.buildrows := circ_test.buildrows;
434 -- Fail if we couldn't find a matchpoint
435 IF circ_test.success = false THEN
436 result.fail_part := 'no_matchpoint';
437 result.success := FALSE;
440 RETURN; -- All tests after this point require a matchpoint. No sense in running on an incomplete or missing one.
443 -- Apparently....use the circ matchpoint org unit to determine what org units are valid.
444 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( circ_matchpoint.org_unit );
447 penalty_type = '%RENEW%';
449 penalty_type = '%CIRC%';
452 FOR standing_penalty IN
453 SELECT DISTINCT csp.*
454 FROM actor.usr_standing_penalty usp
455 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
456 WHERE usr = match_user
457 AND usp.org_unit IN ( SELECT * FROM unnest(context_org_list) )
458 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
459 AND csp.block_list LIKE penalty_type LOOP
461 result.fail_part := standing_penalty.name;
462 result.success := FALSE;
467 -- Fail if the test is set to hard non-circulating
468 IF circ_matchpoint.circulate IS FALSE THEN
469 result.fail_part := 'config.circ_matrix_test.circulate';
470 result.success := FALSE;
475 -- Fail if the total copy-hold ratio is too low
476 IF circ_matchpoint.total_copy_hold_ratio IS NOT NULL THEN
477 SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
478 IF hold_ratio.total_copy_ratio IS NOT NULL AND hold_ratio.total_copy_ratio < circ_matchpoint.total_copy_hold_ratio THEN
479 result.fail_part := 'config.circ_matrix_test.total_copy_hold_ratio';
480 result.success := FALSE;
486 -- Fail if the available copy-hold ratio is too low
487 IF circ_matchpoint.available_copy_hold_ratio IS NOT NULL THEN
488 IF hold_ratio.hold_count IS NULL THEN
489 SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
491 IF hold_ratio.available_copy_ratio IS NOT NULL AND hold_ratio.available_copy_ratio < circ_matchpoint.available_copy_hold_ratio THEN
492 result.fail_part := 'config.circ_matrix_test.available_copy_hold_ratio';
493 result.success := FALSE;
499 -- Fail if the user has too many items with specific circ_modifiers checked out
500 FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = circ_matchpoint.id LOOP
501 SELECT INTO items_out COUNT(*)
502 FROM action.circulation circ
503 JOIN asset.copy cp ON (cp.id = circ.target_copy)
504 WHERE circ.usr = match_user
505 AND circ.circ_lib IN ( SELECT * FROM unnest(context_org_list) )
506 AND circ.checkin_time IS NULL
507 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
508 AND cp.circ_modifier IN (SELECT circ_mod FROM config.circ_matrix_circ_mod_test_map WHERE circ_mod_test = out_by_circ_mod.id);
509 IF items_out >= out_by_circ_mod.items_out THEN
510 result.fail_part := 'config.circ_matrix_circ_mod_test';
511 result.success := FALSE;
517 -- If we passed everything, return the successful matchpoint id
524 $func$ LANGUAGE plpgsql;
526 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
527 SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
530 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
531 SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
535 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
537 user_object actor.usr%ROWTYPE;
538 new_sp_row actor.usr_standing_penalty%ROWTYPE;
539 existing_sp_row actor.usr_standing_penalty%ROWTYPE;
540 collections_fines permission.grp_penalty_threshold%ROWTYPE;
541 max_fines permission.grp_penalty_threshold%ROWTYPE;
542 max_overdue permission.grp_penalty_threshold%ROWTYPE;
543 max_items_out permission.grp_penalty_threshold%ROWTYPE;
547 context_org_list INT[];
548 current_fines NUMERIC(8,2) := 0.0;
549 tmp_fines NUMERIC(8,2);
552 tmp_org actor.org_unit%ROWTYPE;
553 tmp_penalty config.standing_penalty%ROWTYPE;
556 SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
559 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
561 -- Fail if the user has a high fine balance
563 tmp_grp := user_object.profile;
565 SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
567 IF max_fines.threshold IS NULL THEN
568 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
573 IF tmp_grp IS NULL THEN
578 IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
582 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
586 IF max_fines.threshold IS NOT NULL THEN
590 FROM actor.usr_standing_penalty
591 WHERE usr = match_user
592 AND org_unit = max_fines.org_unit
593 AND (stop_date IS NULL or stop_date > NOW())
594 AND standing_penalty = 1;
596 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
598 SELECT SUM(f.balance_owed) INTO current_fines
599 FROM money.materialized_billable_xact_summary f
602 FROM booking.reservation r
603 WHERE r.usr = match_user
604 AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
605 AND xact_finish IS NULL
609 WHERE g.usr = match_user
610 AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
611 AND xact_finish IS NULL
614 FROM action.circulation circ
615 WHERE circ.usr = match_user
616 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
617 AND xact_finish IS NULL ) l USING (id);
619 IF current_fines >= max_fines.threshold THEN
620 new_sp_row.usr := match_user;
621 new_sp_row.org_unit := max_fines.org_unit;
622 new_sp_row.standing_penalty := 1;
623 RETURN NEXT new_sp_row;
627 -- Start over for max overdue
628 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
630 -- Fail if the user has too many overdue items
632 tmp_grp := user_object.profile;
635 SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
637 IF max_overdue.threshold IS NULL THEN
638 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
643 IF tmp_grp IS NULL THEN
648 IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
652 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
656 IF max_overdue.threshold IS NOT NULL THEN
660 FROM actor.usr_standing_penalty
661 WHERE usr = match_user
662 AND org_unit = max_overdue.org_unit
663 AND (stop_date IS NULL or stop_date > NOW())
664 AND standing_penalty = 2;
666 SELECT INTO items_overdue COUNT(*)
667 FROM action.circulation circ
668 JOIN actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
669 WHERE circ.usr = match_user
670 AND circ.checkin_time IS NULL
671 AND circ.due_date < NOW()
672 AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
674 IF items_overdue >= max_overdue.threshold::INT THEN
675 new_sp_row.usr := match_user;
676 new_sp_row.org_unit := max_overdue.org_unit;
677 new_sp_row.standing_penalty := 2;
678 RETURN NEXT new_sp_row;
682 -- Start over for max out
683 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
685 -- Fail if the user has too many checked out items
687 tmp_grp := user_object.profile;
689 SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
691 IF max_items_out.threshold IS NULL THEN
692 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
697 IF tmp_grp IS NULL THEN
702 IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
706 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
711 -- Fail if the user has too many items checked out
712 IF max_items_out.threshold IS NOT NULL THEN
716 FROM actor.usr_standing_penalty
717 WHERE usr = match_user
718 AND org_unit = max_items_out.org_unit
719 AND (stop_date IS NULL or stop_date > NOW())
720 AND standing_penalty = 3;
722 SELECT INTO items_out COUNT(*)
723 FROM action.circulation circ
724 JOIN actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
725 WHERE circ.usr = match_user
726 AND circ.checkin_time IS NULL
727 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL);
729 IF items_out >= max_items_out.threshold::INT THEN
730 new_sp_row.usr := match_user;
731 new_sp_row.org_unit := max_items_out.org_unit;
732 new_sp_row.standing_penalty := 3;
733 RETURN NEXT new_sp_row;
737 -- Start over for collections warning
738 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
740 -- Fail if the user has a collections-level fine balance
742 tmp_grp := user_object.profile;
744 SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
746 IF max_fines.threshold IS NULL THEN
747 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
752 IF tmp_grp IS NULL THEN
757 IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
761 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
765 IF max_fines.threshold IS NOT NULL THEN
769 FROM actor.usr_standing_penalty
770 WHERE usr = match_user
771 AND org_unit = max_fines.org_unit
772 AND (stop_date IS NULL or stop_date > NOW())
773 AND standing_penalty = 4;
775 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
777 SELECT SUM(f.balance_owed) INTO current_fines
778 FROM money.materialized_billable_xact_summary f
781 FROM booking.reservation r
782 WHERE r.usr = match_user
783 AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
784 AND r.xact_finish IS NULL
788 WHERE g.usr = match_user
789 AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
790 AND g.xact_finish IS NULL
793 FROM action.circulation circ
794 WHERE circ.usr = match_user
795 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
796 AND circ.xact_finish IS NULL ) l USING (id);
798 IF current_fines >= max_fines.threshold THEN
799 new_sp_row.usr := match_user;
800 new_sp_row.org_unit := max_fines.org_unit;
801 new_sp_row.standing_penalty := 4;
802 RETURN NEXT new_sp_row;
806 -- Start over for in collections
807 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
809 -- Remove the in-collections penalty if the user has paid down enough
810 -- This penalty is different, because this code is not responsible for creating
811 -- new in-collections penalties, only for removing them
813 tmp_grp := user_object.profile;
815 SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 30 AND org_unit = tmp_org.id;
817 IF max_fines.threshold IS NULL THEN
818 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
823 IF tmp_grp IS NULL THEN
828 IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
832 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
836 IF max_fines.threshold IS NOT NULL THEN
838 SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
840 -- first, see if the user had paid down to the threshold
841 SELECT SUM(f.balance_owed) INTO current_fines
842 FROM money.materialized_billable_xact_summary f
845 FROM booking.reservation r
846 WHERE r.usr = match_user
847 AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
848 AND r.xact_finish IS NULL
852 WHERE g.usr = match_user
853 AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
854 AND g.xact_finish IS NULL
857 FROM action.circulation circ
858 WHERE circ.usr = match_user
859 AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
860 AND circ.xact_finish IS NULL ) l USING (id);
862 IF current_fines IS NULL OR current_fines <= max_fines.threshold THEN
863 -- patron has paid down enough
865 SELECT INTO tmp_penalty * FROM config.standing_penalty WHERE id = 30;
867 IF tmp_penalty.org_depth IS NOT NULL THEN
869 -- since this code is not responsible for applying the penalty, it can't
870 -- guarantee the current context org will match the org at which the penalty
871 --- was applied. search up the org tree until we hit the configured penalty depth
872 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
873 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
875 WHILE tmp_depth >= tmp_penalty.org_depth LOOP
879 FROM actor.usr_standing_penalty
880 WHERE usr = match_user
881 AND org_unit = tmp_org.id
882 AND (stop_date IS NULL or stop_date > NOW())
883 AND standing_penalty = 30;
885 IF tmp_org.parent_ou IS NULL THEN
889 SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
890 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
895 -- no penalty depth is defined, look for exact matches
899 FROM actor.usr_standing_penalty
900 WHERE usr = match_user
901 AND org_unit = max_fines.org_unit
902 AND (stop_date IS NULL or stop_date > NOW())
903 AND standing_penalty = 30;
912 $func$ LANGUAGE plpgsql;