]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
Copy Location Circ Limit Sets : DB and IDL
[working/Evergreen.git] / Open-ILS / src / sql / Pg / 100.circ_matrix.sql
1
2 BEGIN;
3 -- NOTE: current config.item_type should get sip2_media_type and magnetic_media columns
4
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 (
8     code            TEXT    PRIMARY KEY,
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
14 );
15
16 /*
17 -- for instance ...
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 );
22 */
23
24 -- But, just to get us started, use this
25 /*
26
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 = '';
29
30 INSERT INTO config.circ_modifier (code, name, description, sip2_media_type )
31     SELECT DISTINCT
32             UPPER(circ_modifier),
33             UPPER(circ_modifier),
34             LOWER(circ_modifier),
35             '001'
36       FROM  asset.copy
37       WHERE circ_modifier IS NOT NULL;
38
39 */
40
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;
43
44
45 /**
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.
51  **/
52
53 CREATE TABLE config.circ_matrix_matchpoint (
54     id                   SERIAL    PRIMARY KEY,
55     active               BOOL    NOT NULL DEFAULT TRUE,
56     -- Match Fields
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,
60     marc_type            TEXT,
61     marc_form            TEXT,
62     marc_bib_level       TEXT,
63     marc_vr_format       TEXT,
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,
67     ref_flag             BOOL,
68     juvenile_flag        BOOL,
69     is_renewal           BOOL,
70     usr_age_lower_bound  INTERVAL,
71     usr_age_upper_bound  INTERVAL,
72     item_age             INTERVAL,
73     -- "Result" Fields
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
84 );
85
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;
88
89 -- Limit groups for circ counting
90 CREATE TABLE config.circ_limit_group (
91     id          SERIAL  PRIMARY KEY,
92     name        TEXT    UNIQUE NOT NULL,
93     description TEXT
94 );
95
96 -- Limit sets
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
104     description TEXT
105 );
106
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)
115 );
116
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)
123 );
124
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)
131 );
132
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)
140 );
141
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)
147 );
148
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));
152 $func$ LANGUAGE SQL;
153
154 CREATE TYPE action.found_circ_matrix_matchpoint AS ( success BOOL, matchpoint config.circ_matrix_matchpoint, buildrows INT[] );
155
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$
157 DECLARE
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;
163     user_age        INTERVAL;
164     my_item_age     INTERVAL;
165     denominator     NUMERIC(6,2);
166     row_list        INT[];
167     result          action.found_circ_matrix_matchpoint;
168 BEGIN
169     -- Assume failure
170     result.success = false;
171
172     -- Fetch useful data
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;
175
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);
179     END IF;
180
181     -- Ditto
182     SELECT INTO my_item_age age(coalesce(item_object.active_date, now()));
183
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)
189       WHERE active
190       ORDER BY d.distance
191       LIMIT 1;
192
193     -- No weights? Bad admin! Defaults to handle that anyway.
194     IF weights.id IS NULL THEN
195         weights.grp                 := 11.0;
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;
211     END IF;
212
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
219         UNION
220             SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
221         )
222     SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
223
224     -- Loop over all the potential matchpoints
225     FOR cur_matchpoint IN
226         SELECT m.*
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
233           WHERE m.active
234                 -- Permission Groups
235              -- AND (m.grp                      IS NULL OR upgad.id IS NOT NULL) -- Optional Permission Group?
236                 -- Org Units
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)
241                 -- Circ Type
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))
255           ORDER BY
256                 -- Permission Groups
257                 CASE WHEN upgad.distance        IS NOT NULL THEN 2^(2*weights.grp - (upgad.distance/denominator)) ELSE 0.0 END +
258                 -- Org Units
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"
281                 m.id LOOP
282
283         -- Record the full matching row list
284         row_list := row_list || cur_matchpoint.id;
285
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.
291         END IF;
292
293         -- Incomplete matchpoint?
294         IF matchpoint.circulate IS NULL THEN
295             matchpoint.circulate := cur_matchpoint.circulate;
296         END IF;
297         IF matchpoint.duration_rule IS NULL THEN
298             matchpoint.duration_rule := cur_matchpoint.duration_rule;
299         END IF;
300         IF matchpoint.recurring_fine_rule IS NULL THEN
301             matchpoint.recurring_fine_rule := cur_matchpoint.recurring_fine_rule;
302         END IF;
303         IF matchpoint.max_fine_rule IS NULL THEN
304             matchpoint.max_fine_rule := cur_matchpoint.max_fine_rule;
305         END IF;
306         IF matchpoint.hard_due_date IS NULL THEN
307             matchpoint.hard_due_date := cur_matchpoint.hard_due_date;
308         END IF;
309         IF matchpoint.total_copy_hold_ratio IS NULL THEN
310             matchpoint.total_copy_hold_ratio := cur_matchpoint.total_copy_hold_ratio;
311         END IF;
312         IF matchpoint.available_copy_hold_ratio IS NULL THEN
313             matchpoint.available_copy_hold_ratio := cur_matchpoint.available_copy_hold_ratio;
314         END IF;
315         IF matchpoint.renewals IS NULL THEN
316             matchpoint.renewals := cur_matchpoint.renewals;
317         END IF;
318         IF matchpoint.grace_period IS NULL THEN
319             matchpoint.grace_period := cur_matchpoint.grace_period;
320         END IF;
321     END LOOP;
322
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;
330     END IF;
331
332     -- Include the assembled matchpoint, even if it isn't complete
333     result.matchpoint := matchpoint;
334
335     -- Include (for debugging) the full list of matching rows
336     result.buildrows := row_list;
337
338     -- Hand the result back to caller
339     RETURN result;
340 END;
341 $func$ LANGUAGE plpgsql;
342
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$
345 DECLARE
346     item_object asset.copy%ROWTYPE;
347     user_object actor.usr%ROWTYPE;
348 BEGIN
349     SELECT INTO item_object * FROM asset.copy   WHERE id = match_item;
350     SELECT INTO user_object * FROM actor.usr    WHERE id = match_user;
351
352     RETURN QUERY SELECT * FROM action.find_circ_matrix_matchpoint( context_ou, item_object, user_object, renewal );
353 END;
354 $func$ LANGUAGE plpgsql;
355
356 CREATE TYPE action.hold_stats AS (
357     hold_count              INT,
358     copy_count              INT,
359     available_count         INT,
360     total_copy_ratio        FLOAT,
361     available_copy_ratio    FLOAT
362 );
363
364 CREATE OR REPLACE FUNCTION action.copy_related_hold_stats (copy_id INT) RETURNS action.hold_stats AS $func$
365 DECLARE
366     output          action.hold_stats%ROWTYPE;
367     hold_count      INT := 0;
368     copy_count      INT := 0;
369     available_count INT := 0;
370     hold_map_data   RECORD;
371 BEGIN
372
373     output.hold_count := 0;
374     output.copy_count := 0;
375     output.available_count := 0;
376
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
381             AND NOT h.frozen;
382
383     output.hold_count := hold_count;
384
385     IF output.hold_count > 0 THEN
386         FOR hold_map_data IN
387             SELECT  DISTINCT m.target_copy,
388                     acp.status
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
393         LOOP
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;
397             END IF;
398         END LOOP;
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;
401
402     END IF;
403
404     RETURN output;
405
406 END;
407 $func$ LANGUAGE PLPGSQL;
408
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$
411 DECLARE
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;
422     penalty_type            TEXT;
423     items_out               INT;
424     context_org_list        INT[];
425     done                    BOOL := FALSE;
426 BEGIN
427     -- Assume success unless we hit a failure condition
428     result.success := TRUE;
429
430     -- Need user info to look up matchpoints
431     SELECT INTO user_object * FROM actor.usr WHERE id = match_user AND NOT deleted;
432
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;
437         done := TRUE;
438         RETURN NEXT result;
439         RETURN;
440     END IF;
441
442     -- Need item info to look up matchpoints
443     SELECT INTO item_object * FROM asset.copy WHERE id = match_item AND NOT deleted;
444
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;
449         done := TRUE;
450         RETURN NEXT result;
451         RETURN;
452     END IF;
453
454     SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, item_object, user_object, renewal);
455
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;
466
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;
471         done := TRUE;
472         RETURN NEXT result;
473         RETURN;
474     END IF;
475
476     -- All failures before this point are non-recoverable
477     -- Below this point are possibly overridable failures
478
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;
483         done := TRUE;
484         RETURN NEXT result;
485     END IF;
486
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;
491         done := TRUE;
492         RETURN NEXT result;
493     END IF;
494
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;
499         done := TRUE;
500         RETURN NEXT result;
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;
505         done := TRUE;
506         RETURN NEXT result;
507     END IF;
508
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;
514         done := TRUE;
515         RETURN NEXT result;
516     END IF;
517
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 );
520
521     IF renewal THEN
522         penalty_type = '%RENEW%';
523     ELSE
524         penalty_type = '%CIRC%';
525     END IF;
526
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
535
536         result.fail_part := standing_penalty.name;
537         result.success := FALSE;
538         done := TRUE;
539         RETURN NEXT result;
540     END LOOP;
541
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;
546         done := TRUE;
547         RETURN NEXT result;
548     END IF;
549
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;
556             done := TRUE;
557             RETURN NEXT result;
558         END IF;
559     END IF;
560
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);
565         END IF;
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;
569             done := TRUE;
570             RETURN NEXT result;
571         END IF;
572     END IF;
573
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 )
579         ) LOOP
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 (
587                         SELECT  ou.id,
588                             ou.parent_ou
589                         FROM  actor.org_unit ou
590                         WHERE ou.id IN (SELECT * FROM unnest(context_org_list))
591                             UNION
592                         SELECT  ou.id,
593                             ou.parent_ou
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);
597                 END IF;
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)
609                     );
610                 IF items_out >= circ_limit_set.items_out THEN
611                     result.fail_part := 'config.circ_matrix_circ_mod_test';
612                     result.success := FALSE;
613                     done := TRUE;
614                     RETURN NEXT result;
615                 END IF;
616             END IF;
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;
618     END LOOP;
619
620     -- If we passed everything, return the successful matchpoint
621     IF NOT done THEN
622         RETURN NEXT result;
623     END IF;
624
625     RETURN;
626 END;
627 $func$ LANGUAGE plpgsql;
628
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 );
631 $func$ LANGUAGE SQL;
632
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 );
635 $func$ LANGUAGE SQL;
636
637
638 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
639 DECLARE
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;
647     tmp_grp             INT;
648     items_overdue       INT;
649     items_out           INT;
650     context_org_list    INT[];
651     current_fines        NUMERIC(8,2) := 0.0;
652     tmp_fines            NUMERIC(8,2);
653     tmp_groc            RECORD;
654     tmp_circ            RECORD;
655     tmp_org             actor.org_unit%ROWTYPE;
656     tmp_penalty         config.standing_penalty%ROWTYPE;
657     tmp_depth           INTEGER;
658 BEGIN
659     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
660
661     -- Max fines
662     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
663
664     -- Fail if the user has a high fine balance
665     LOOP
666         tmp_grp := user_object.profile;
667         LOOP
668             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
669
670             IF max_fines.threshold IS NULL THEN
671                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
672             ELSE
673                 EXIT;
674             END IF;
675
676             IF tmp_grp IS NULL THEN
677                 EXIT;
678             END IF;
679         END LOOP;
680
681         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
682             EXIT;
683         END IF;
684
685         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
686
687     END LOOP;
688
689     IF max_fines.threshold IS NOT NULL THEN
690
691         RETURN QUERY
692             SELECT  *
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;
698
699         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
700
701         SELECT  SUM(f.balance_owed) INTO current_fines
702           FROM  money.materialized_billable_xact_summary f
703                 JOIN (
704                     SELECT  r.id
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
709                                 UNION ALL
710                     SELECT  g.id
711                       FROM  money.grocery g
712                       WHERE g.usr = match_user
713                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
714                             AND xact_finish IS NULL
715                                 UNION ALL
716                     SELECT  circ.id
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);
721
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;
727         END IF;
728     END IF;
729
730     -- Start over for max overdue
731     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
732
733     -- Fail if the user has too many overdue items
734     LOOP
735         tmp_grp := user_object.profile;
736         LOOP
737
738             SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
739
740             IF max_overdue.threshold IS NULL THEN
741                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
742             ELSE
743                 EXIT;
744             END IF;
745
746             IF tmp_grp IS NULL THEN
747                 EXIT;
748             END IF;
749         END LOOP;
750
751         IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
752             EXIT;
753         END IF;
754
755         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
756
757     END LOOP;
758
759     IF max_overdue.threshold IS NOT NULL THEN
760
761         RETURN QUERY
762             SELECT  *
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;
768
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);
776
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;
782         END IF;
783     END IF;
784
785     -- Start over for max out
786     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
787
788     -- Fail if the user has too many checked out items
789     LOOP
790         tmp_grp := user_object.profile;
791         LOOP
792             SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
793
794             IF max_items_out.threshold IS NULL THEN
795                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
796             ELSE
797                 EXIT;
798             END IF;
799
800             IF tmp_grp IS NULL THEN
801                 EXIT;
802             END IF;
803         END LOOP;
804
805         IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
806             EXIT;
807         END IF;
808
809         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
810
811     END LOOP;
812
813
814     -- Fail if the user has too many items checked out
815     IF max_items_out.threshold IS NOT NULL THEN
816
817         RETURN QUERY
818             SELECT  *
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;
824
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);
831
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;
837            END IF;
838     END IF;
839
840     -- Start over for collections warning
841     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
842
843     -- Fail if the user has a collections-level fine balance
844     LOOP
845         tmp_grp := user_object.profile;
846         LOOP
847             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
848
849             IF max_fines.threshold IS NULL THEN
850                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
851             ELSE
852                 EXIT;
853             END IF;
854
855             IF tmp_grp IS NULL THEN
856                 EXIT;
857             END IF;
858         END LOOP;
859
860         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
861             EXIT;
862         END IF;
863
864         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
865
866     END LOOP;
867
868     IF max_fines.threshold IS NOT NULL THEN
869
870         RETURN QUERY
871             SELECT  *
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;
877
878         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
879
880         SELECT  SUM(f.balance_owed) INTO current_fines
881           FROM  money.materialized_billable_xact_summary f
882                 JOIN (
883                     SELECT  r.id
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
888                                 UNION ALL
889                     SELECT  g.id
890                       FROM  money.grocery g
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
894                                 UNION ALL
895                     SELECT  circ.id
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);
900
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;
906         END IF;
907     END IF;
908
909     -- Start over for in collections
910     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
911
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
915     LOOP
916         tmp_grp := user_object.profile;
917         LOOP
918             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 30 AND org_unit = tmp_org.id;
919
920             IF max_fines.threshold IS NULL THEN
921                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
922             ELSE
923                 EXIT;
924             END IF;
925
926             IF tmp_grp IS NULL THEN
927                 EXIT;
928             END IF;
929         END LOOP;
930
931         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
932             EXIT;
933         END IF;
934
935         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
936
937     END LOOP;
938
939     IF max_fines.threshold IS NOT NULL THEN
940
941         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
942
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
946                 JOIN (
947                     SELECT  r.id
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
952                                 UNION ALL
953                     SELECT  g.id
954                       FROM  money.grocery g
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
958                                 UNION ALL
959                     SELECT  circ.id
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);
964
965         IF current_fines IS NULL OR current_fines <= max_fines.threshold THEN
966             -- patron has paid down enough
967
968             SELECT INTO tmp_penalty * FROM config.standing_penalty WHERE id = 30;
969
970             IF tmp_penalty.org_depth IS NOT NULL THEN
971
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;
977
978                 WHILE tmp_depth >= tmp_penalty.org_depth LOOP
979
980                     RETURN QUERY
981                         SELECT  *
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;
987
988                     IF tmp_org.parent_ou IS NULL THEN
989                         EXIT;
990                     END IF;
991
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;
994                 END LOOP;
995
996             ELSE
997
998                 -- no penalty depth is defined, look for exact matches
999
1000                 RETURN QUERY
1001                     SELECT  *
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;
1007             END IF;
1008     
1009         END IF;
1010
1011     END IF;
1012
1013     RETURN;
1014 END;
1015 $func$ LANGUAGE plpgsql;
1016
1017 COMMIT;
1018