]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
LP#1117808: Stamping upgrade scripts for extend use of merge profiles
[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     copy_location        INT     REFERENCES asset.copy_location (id) DEFERRABLE INITIALLY DEFERRED,
61     marc_type            TEXT,
62     marc_form            TEXT,
63     marc_bib_level       TEXT,
64     marc_vr_format       TEXT,
65     copy_circ_lib        INT     REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
66     copy_owning_lib      INT     REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
67     user_home_ou         INT     REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
68     ref_flag             BOOL,
69     juvenile_flag        BOOL,
70     is_renewal           BOOL,
71     usr_age_lower_bound  INTERVAL,
72     usr_age_upper_bound  INTERVAL,
73     item_age             INTERVAL,
74     -- "Result" Fields
75     circulate            BOOL,   -- Hard "can't circ" flag requiring an override
76     duration_rule        INT     REFERENCES config.rule_circ_duration (id) DEFERRABLE INITIALLY DEFERRED,
77     recurring_fine_rule  INT     REFERENCES config.rule_recurring_fine (id) DEFERRABLE INITIALLY DEFERRED,
78     max_fine_rule        INT     REFERENCES config.rule_max_fine (id) DEFERRABLE INITIALLY DEFERRED,
79     hard_due_date        INT     REFERENCES config.hard_due_date (id) DEFERRABLE INITIALLY DEFERRED,
80     renewals             INT,    -- Renewal count override
81     grace_period         INTERVAL,    -- Grace period override
82     script_test          TEXT,                           -- javascript source 
83     total_copy_hold_ratio     FLOAT,
84     available_copy_hold_ratio FLOAT
85 );
86
87 -- Nulls don't count for a constraint match, so we have to coalesce them into something that does.
88 CREATE UNIQUE INDEX ccmm_once_per_paramset ON config.circ_matrix_matchpoint (org_unit, grp, COALESCE(circ_modifier, ''), COALESCE(copy_location::TEXT, ''), 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
90 -- Limit groups for circ counting
91 CREATE TABLE config.circ_limit_group (
92     id          SERIAL  PRIMARY KEY,
93     name        TEXT    UNIQUE NOT NULL,
94     description TEXT
95 );
96
97 -- Limit sets
98 CREATE TABLE config.circ_limit_set (
99     id          SERIAL  PRIMARY KEY,
100     name        TEXT    UNIQUE NOT NULL,
101     owning_lib  INT     NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
102     items_out   INT     NOT NULL, -- Total current active circulations must be less than this. 0 means skip counting (always pass)
103     depth       INT     NOT NULL DEFAULT 0, -- Depth count starts at
104     global      BOOL    NOT NULL DEFAULT FALSE, -- If enabled, include everything below depth, otherwise ancestors/descendants only
105     description TEXT
106 );
107
108 -- Linkage between matchpoints and limit sets
109 CREATE TABLE config.circ_matrix_limit_set_map (
110     id          SERIAL  PRIMARY KEY,
111     matchpoint  INT     NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
112     limit_set   INT     NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
113     fallthrough BOOL    NOT NULL DEFAULT FALSE, -- If true fallthrough will grab this rule as it goes along
114     active      BOOL    NOT NULL DEFAULT TRUE,
115     CONSTRAINT circ_limit_set_once_per_matchpoint UNIQUE (matchpoint, limit_set)
116 );
117
118 -- Linkage between limit sets and circ mods
119 CREATE TABLE config.circ_limit_set_circ_mod_map (
120     id          SERIAL  PRIMARY KEY,
121     limit_set   INT     NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
122     circ_mod    TEXT    NOT NULL REFERENCES config.circ_modifier (code) ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
123     CONSTRAINT cm_once_per_set UNIQUE (limit_set, circ_mod)
124 );
125
126 -- Linkage between limit sets and copy locations
127 CREATE TABLE config.circ_limit_set_copy_loc_map (
128     id          SERIAL  PRIMARY KEY,
129     limit_set   INT     NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
130     copy_loc    INT     NOT NULL REFERENCES asset.copy_location (id) ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
131     CONSTRAINT cl_once_per_set UNIQUE (limit_set, copy_loc)
132 );
133
134 -- Linkage between limit sets and limit groups
135 CREATE TABLE config.circ_limit_set_group_map (
136     id          SERIAL  PRIMARY KEY,
137     limit_set    INT     NOT NULL REFERENCES config.circ_limit_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
138     limit_group INT     NOT NULL REFERENCES config.circ_limit_group (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
139     check_only  BOOL    NOT NULL DEFAULT FALSE, -- If true, don't accumulate this limit_group for storing with the circulation
140     CONSTRAINT clg_once_per_set UNIQUE (limit_set, limit_group)
141 );
142
143 -- Linkage between limit groups and circulations
144 CREATE TABLE action.circulation_limit_group_map (
145     circ        BIGINT      NOT NULL REFERENCES action.circulation (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
146     limit_group INT         NOT NULL REFERENCES config.circ_limit_group (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
147     PRIMARY KEY (circ, limit_group)
148 );
149
150 -- Function for populating the circ/limit group mappings
151 CREATE OR REPLACE FUNCTION action.link_circ_limit_groups ( BIGINT, INT[] ) RETURNS VOID AS $func$
152     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));
153 $func$ LANGUAGE SQL;
154
155 CREATE TYPE action.found_circ_matrix_matchpoint AS ( success BOOL, matchpoint config.circ_matrix_matchpoint, buildrows INT[] );
156
157 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 DECLARE
159     cn_object       asset.call_number%ROWTYPE;
160     rec_descriptor  metabib.rec_descriptor%ROWTYPE;
161     cur_matchpoint  config.circ_matrix_matchpoint%ROWTYPE;
162     matchpoint      config.circ_matrix_matchpoint%ROWTYPE;
163     weights         config.circ_matrix_weights%ROWTYPE;
164     user_age        INTERVAL;
165     my_item_age     INTERVAL;
166     denominator     NUMERIC(6,2);
167     row_list        INT[];
168     result          action.found_circ_matrix_matchpoint;
169 BEGIN
170     -- Assume failure
171     result.success = false;
172
173     -- Fetch useful data
174     SELECT INTO cn_object       * FROM asset.call_number        WHERE id = item_object.call_number;
175     SELECT INTO rec_descriptor  * FROM metabib.rec_descriptor   WHERE record = cn_object.record;
176
177     -- Pre-generate this so we only calc it once
178     IF user_object.dob IS NOT NULL THEN
179         SELECT INTO user_age age(user_object.dob);
180     END IF;
181
182     -- Ditto
183     SELECT INTO my_item_age age(coalesce(item_object.active_date, now()));
184
185     -- Grab the closest set circ weight setting.
186     SELECT INTO weights cw.*
187       FROM config.weight_assoc wa
188            JOIN config.circ_matrix_weights cw ON (cw.id = wa.circ_weights)
189            JOIN actor.org_unit_ancestors_distance( context_ou ) d ON (wa.org_unit = d.id)
190       WHERE active
191       ORDER BY d.distance
192       LIMIT 1;
193
194     -- No weights? Bad admin! Defaults to handle that anyway.
195     IF weights.id IS NULL THEN
196         weights.grp                 := 11.0;
197         weights.org_unit            := 10.0;
198         weights.circ_modifier       := 5.0;
199         weights.copy_location       := 5.0;
200         weights.marc_type           := 4.0;
201         weights.marc_form           := 3.0;
202         weights.marc_bib_level      := 2.0;
203         weights.marc_vr_format      := 2.0;
204         weights.copy_circ_lib       := 8.0;
205         weights.copy_owning_lib     := 8.0;
206         weights.user_home_ou        := 8.0;
207         weights.ref_flag            := 1.0;
208         weights.juvenile_flag       := 6.0;
209         weights.is_renewal          := 7.0;
210         weights.usr_age_lower_bound := 0.0;
211         weights.usr_age_upper_bound := 0.0;
212         weights.item_age            := 0.0;
213     END IF;
214
215     -- Determine the max (expected) depth (+1) of the org tree and max depth of the permisson tree
216     -- If you break your org tree with funky parenting this may be wrong
217     -- 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
218     -- We use one denominator for all tree-based checks for when permission groups and org units have the same weighting
219     WITH all_distance(distance) AS (
220             SELECT depth AS distance FROM actor.org_unit_type
221         UNION
222             SELECT distance AS distance FROM permission.grp_ancestors_distance((SELECT id FROM permission.grp_tree WHERE parent IS NULL))
223         )
224     SELECT INTO denominator MAX(distance) + 1 FROM all_distance;
225
226     -- Loop over all the potential matchpoints
227     FOR cur_matchpoint IN
228         SELECT m.*
229           FROM  config.circ_matrix_matchpoint m
230                 /*LEFT*/ JOIN permission.grp_ancestors_distance( user_object.profile ) upgad ON m.grp = upgad.id
231                 /*LEFT*/ JOIN actor.org_unit_ancestors_distance( context_ou ) ctoua ON m.org_unit = ctoua.id
232                 LEFT JOIN actor.org_unit_ancestors_distance( cn_object.owning_lib ) cnoua ON m.copy_owning_lib = cnoua.id
233                 LEFT JOIN actor.org_unit_ancestors_distance( item_object.circ_lib ) iooua ON m.copy_circ_lib = iooua.id
234                 LEFT JOIN actor.org_unit_ancestors_distance( user_object.home_ou  ) uhoua ON m.user_home_ou = uhoua.id
235           WHERE m.active
236                 -- Permission Groups
237              -- AND (m.grp                      IS NULL OR upgad.id IS NOT NULL) -- Optional Permission Group?
238                 -- Org Units
239              -- AND (m.org_unit                 IS NULL OR ctoua.id IS NOT NULL) -- Optional Org Unit?
240                 AND (m.copy_owning_lib          IS NULL OR cnoua.id IS NOT NULL)
241                 AND (m.copy_circ_lib            IS NULL OR iooua.id IS NOT NULL)
242                 AND (m.user_home_ou             IS NULL OR uhoua.id IS NOT NULL)
243                 -- Circ Type
244                 AND (m.is_renewal               IS NULL OR m.is_renewal = renewal)
245                 -- Static User Checks
246                 AND (m.juvenile_flag            IS NULL OR m.juvenile_flag = user_object.juvenile)
247                 AND (m.usr_age_lower_bound      IS NULL OR (user_age IS NOT NULL AND m.usr_age_lower_bound < user_age))
248                 AND (m.usr_age_upper_bound      IS NULL OR (user_age IS NOT NULL AND m.usr_age_upper_bound > user_age))
249                 -- Static Item Checks
250                 AND (m.circ_modifier            IS NULL OR m.circ_modifier = item_object.circ_modifier)
251                 AND (m.copy_location            IS NULL OR m.copy_location = item_object.location)
252                 AND (m.marc_type                IS NULL OR m.marc_type = COALESCE(item_object.circ_as_type, rec_descriptor.item_type))
253                 AND (m.marc_form                IS NULL OR m.marc_form = rec_descriptor.item_form)
254                 AND (m.marc_bib_level           IS NULL OR m.marc_bib_level = rec_descriptor.bib_level)
255                 AND (m.marc_vr_format           IS NULL OR m.marc_vr_format = rec_descriptor.vr_format)
256                 AND (m.ref_flag                 IS NULL OR m.ref_flag = item_object.ref)
257                 AND (m.item_age                 IS NULL OR (my_item_age IS NOT NULL AND m.item_age > my_item_age))
258           ORDER BY
259                 -- Permission Groups
260                 CASE WHEN upgad.distance        IS NOT NULL THEN 2^(2*weights.grp - (upgad.distance/denominator)) ELSE 0.0 END +
261                 -- Org Units
262                 CASE WHEN ctoua.distance        IS NOT NULL THEN 2^(2*weights.org_unit - (ctoua.distance/denominator)) ELSE 0.0 END +
263                 CASE WHEN cnoua.distance        IS NOT NULL THEN 2^(2*weights.copy_owning_lib - (cnoua.distance/denominator)) ELSE 0.0 END +
264                 CASE WHEN iooua.distance        IS NOT NULL THEN 2^(2*weights.copy_circ_lib - (iooua.distance/denominator)) ELSE 0.0 END +
265                 CASE WHEN uhoua.distance        IS NOT NULL THEN 2^(2*weights.user_home_ou - (uhoua.distance/denominator)) ELSE 0.0 END +
266                 -- Circ Type                    -- Note: 4^x is equiv to 2^(2*x)
267                 CASE WHEN m.is_renewal          IS NOT NULL THEN 4^weights.is_renewal ELSE 0.0 END +
268                 -- Static User Checks
269                 CASE WHEN m.juvenile_flag       IS NOT NULL THEN 4^weights.juvenile_flag ELSE 0.0 END +
270                 CASE WHEN m.usr_age_lower_bound IS NOT NULL THEN 4^weights.usr_age_lower_bound ELSE 0.0 END +
271                 CASE WHEN m.usr_age_upper_bound IS NOT NULL THEN 4^weights.usr_age_upper_bound ELSE 0.0 END +
272                 -- Static Item Checks
273                 CASE WHEN m.circ_modifier       IS NOT NULL THEN 4^weights.circ_modifier ELSE 0.0 END +
274                 CASE WHEN m.copy_location       IS NOT NULL THEN 4^weights.copy_location ELSE 0.0 END +
275                 CASE WHEN m.marc_type           IS NOT NULL THEN 4^weights.marc_type ELSE 0.0 END +
276                 CASE WHEN m.marc_form           IS NOT NULL THEN 4^weights.marc_form ELSE 0.0 END +
277                 CASE WHEN m.marc_vr_format      IS NOT NULL THEN 4^weights.marc_vr_format ELSE 0.0 END +
278                 CASE WHEN m.ref_flag            IS NOT NULL THEN 4^weights.ref_flag ELSE 0.0 END +
279                 -- Item age has a slight adjustment to weight based on value.
280                 -- This should ensure that a shorter age limit comes first when all else is equal.
281                 -- NOTE: This assumes that intervals will normally be in days.
282                 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,
283                 -- Final sort on id, so that if two rules have the same sorting in the previous sort they have a defined order
284                 -- This prevents "we changed the table order by updating a rule, and we started getting different results"
285                 m.id LOOP
286
287         -- Record the full matching row list
288         row_list := row_list || cur_matchpoint.id;
289
290         -- No matchpoint yet?
291         IF matchpoint.id IS NULL THEN
292             -- Take the entire matchpoint as a starting point
293             matchpoint := cur_matchpoint;
294             CONTINUE; -- No need to look at this row any more.
295         END IF;
296
297         -- Incomplete matchpoint?
298         IF matchpoint.circulate IS NULL THEN
299             matchpoint.circulate := cur_matchpoint.circulate;
300         END IF;
301         IF matchpoint.duration_rule IS NULL THEN
302             matchpoint.duration_rule := cur_matchpoint.duration_rule;
303         END IF;
304         IF matchpoint.recurring_fine_rule IS NULL THEN
305             matchpoint.recurring_fine_rule := cur_matchpoint.recurring_fine_rule;
306         END IF;
307         IF matchpoint.max_fine_rule IS NULL THEN
308             matchpoint.max_fine_rule := cur_matchpoint.max_fine_rule;
309         END IF;
310         IF matchpoint.hard_due_date IS NULL THEN
311             matchpoint.hard_due_date := cur_matchpoint.hard_due_date;
312         END IF;
313         IF matchpoint.total_copy_hold_ratio IS NULL THEN
314             matchpoint.total_copy_hold_ratio := cur_matchpoint.total_copy_hold_ratio;
315         END IF;
316         IF matchpoint.available_copy_hold_ratio IS NULL THEN
317             matchpoint.available_copy_hold_ratio := cur_matchpoint.available_copy_hold_ratio;
318         END IF;
319         IF matchpoint.renewals IS NULL THEN
320             matchpoint.renewals := cur_matchpoint.renewals;
321         END IF;
322         IF matchpoint.grace_period IS NULL THEN
323             matchpoint.grace_period := cur_matchpoint.grace_period;
324         END IF;
325     END LOOP;
326
327     -- Check required fields
328     IF matchpoint.circulate             IS NOT NULL AND
329        matchpoint.duration_rule         IS NOT NULL AND
330        matchpoint.recurring_fine_rule   IS NOT NULL AND
331        matchpoint.max_fine_rule         IS NOT NULL THEN
332         -- All there? We have a completed match.
333         result.success := true;
334     END IF;
335
336     -- Include the assembled matchpoint, even if it isn't complete
337     result.matchpoint := matchpoint;
338
339     -- Include (for debugging) the full list of matching rows
340     result.buildrows := row_list;
341
342     -- Hand the result back to caller
343     RETURN result;
344 END;
345 $func$ LANGUAGE plpgsql;
346
347 -- Helper function - For manual calling, it can be easier to pass in IDs instead of objects
348 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$
349 DECLARE
350     item_object asset.copy%ROWTYPE;
351     user_object actor.usr%ROWTYPE;
352 BEGIN
353     SELECT INTO item_object * FROM asset.copy   WHERE id = match_item;
354     SELECT INTO user_object * FROM actor.usr    WHERE id = match_user;
355
356     RETURN QUERY SELECT * FROM action.find_circ_matrix_matchpoint( context_ou, item_object, user_object, renewal );
357 END;
358 $func$ LANGUAGE plpgsql;
359
360 CREATE TYPE action.hold_stats AS (
361     hold_count              INT,
362     copy_count              INT,
363     available_count         INT,
364     total_copy_ratio        FLOAT,
365     available_copy_ratio    FLOAT
366 );
367
368 CREATE OR REPLACE FUNCTION action.copy_related_hold_stats (copy_id BIGINT) RETURNS action.hold_stats AS $func$
369 DECLARE
370     output          action.hold_stats%ROWTYPE;
371     hold_count      INT := 0;
372     copy_count      INT := 0;
373     available_count INT := 0;
374     hold_map_data   RECORD;
375 BEGIN
376
377     output.hold_count := 0;
378     output.copy_count := 0;
379     output.available_count := 0;
380
381     SELECT  COUNT( DISTINCT m.hold ) INTO hold_count
382       FROM  action.hold_copy_map m
383             JOIN action.hold_request h ON (m.hold = h.id)
384       WHERE m.target_copy = copy_id
385             AND NOT h.frozen;
386
387     output.hold_count := hold_count;
388
389     IF output.hold_count > 0 THEN
390         FOR hold_map_data IN
391             SELECT  DISTINCT m.target_copy,
392                     acp.status
393               FROM  action.hold_copy_map m
394                     JOIN asset.copy acp ON (m.target_copy = acp.id)
395                     JOIN action.hold_request h ON (m.hold = h.id)
396               WHERE m.hold IN ( SELECT DISTINCT hold FROM action.hold_copy_map WHERE target_copy = copy_id ) AND NOT h.frozen
397         LOOP
398             output.copy_count := output.copy_count + 1;
399             IF hold_map_data.status IN (0,7,12) THEN
400                 output.available_count := output.available_count + 1;
401             END IF;
402         END LOOP;
403         output.total_copy_ratio = output.copy_count::FLOAT / output.hold_count::FLOAT;
404         output.available_copy_ratio = output.available_count::FLOAT / output.hold_count::FLOAT;
405
406     END IF;
407
408     RETURN output;
409
410 END;
411 $func$ LANGUAGE PLPGSQL;
412
413 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[] );
414 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$
415 DECLARE
416     user_object             actor.usr%ROWTYPE;
417     standing_penalty        config.standing_penalty%ROWTYPE;
418     item_object             asset.copy%ROWTYPE;
419     item_status_object      config.copy_status%ROWTYPE;
420     item_location_object    asset.copy_location%ROWTYPE;
421     result                  action.circ_matrix_test_result;
422     circ_test               action.found_circ_matrix_matchpoint;
423     circ_matchpoint         config.circ_matrix_matchpoint%ROWTYPE;
424     circ_limit_set          config.circ_limit_set%ROWTYPE;
425     hold_ratio              action.hold_stats%ROWTYPE;
426     penalty_type            TEXT;
427     items_out               INT;
428     context_org_list        INT[];
429     done                    BOOL := FALSE;
430     item_prox               INT;
431     home_prox               INT;
432 BEGIN
433     -- Assume success unless we hit a failure condition
434     result.success := TRUE;
435
436     -- Need user info to look up matchpoints
437     SELECT INTO user_object * FROM actor.usr WHERE id = match_user AND NOT deleted;
438
439     -- (Insta)Fail if we couldn't find the user
440     IF user_object.id IS NULL THEN
441         result.fail_part := 'no_user';
442         result.success := FALSE;
443         done := TRUE;
444         RETURN NEXT result;
445         RETURN;
446     END IF;
447
448     -- Need item info to look up matchpoints
449     SELECT INTO item_object * FROM asset.copy WHERE id = match_item AND NOT deleted;
450
451     -- (Insta)Fail if we couldn't find the item 
452     IF item_object.id IS NULL THEN
453         result.fail_part := 'no_item';
454         result.success := FALSE;
455         done := TRUE;
456         RETURN NEXT result;
457         RETURN;
458     END IF;
459
460     SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, item_object, user_object, renewal);
461
462     circ_matchpoint             := circ_test.matchpoint;
463     result.matchpoint           := circ_matchpoint.id;
464     result.circulate            := circ_matchpoint.circulate;
465     result.duration_rule        := circ_matchpoint.duration_rule;
466     result.recurring_fine_rule  := circ_matchpoint.recurring_fine_rule;
467     result.max_fine_rule        := circ_matchpoint.max_fine_rule;
468     result.hard_due_date        := circ_matchpoint.hard_due_date;
469     result.renewals             := circ_matchpoint.renewals;
470     result.grace_period         := circ_matchpoint.grace_period;
471     result.buildrows            := circ_test.buildrows;
472
473     -- (Insta)Fail if we couldn't find a matchpoint
474     IF circ_test.success = false THEN
475         result.fail_part := 'no_matchpoint';
476         result.success := FALSE;
477         done := TRUE;
478         RETURN NEXT result;
479         RETURN;
480     END IF;
481
482     -- All failures before this point are non-recoverable
483     -- Below this point are possibly overridable failures
484
485     -- Fail if the user is barred
486     IF user_object.barred IS TRUE THEN
487         result.fail_part := 'actor.usr.barred';
488         result.success := FALSE;
489         done := TRUE;
490         RETURN NEXT result;
491     END IF;
492
493     -- Fail if the item can't circulate
494     IF item_object.circulate IS FALSE THEN
495         result.fail_part := 'asset.copy.circulate';
496         result.success := FALSE;
497         done := TRUE;
498         RETURN NEXT result;
499     END IF;
500
501     -- Fail if the item isn't in a circulateable status on a non-renewal
502     IF NOT renewal AND item_object.status <> 8 AND item_object.status NOT IN (
503         (SELECT id FROM config.copy_status WHERE is_available) ) THEN 
504         result.fail_part := 'asset.copy.status';
505         result.success := FALSE;
506         done := TRUE;
507         RETURN NEXT result;
508     -- Alternately, fail if the item isn't checked out on a renewal
509     ELSIF renewal AND item_object.status <> 1 THEN
510         result.fail_part := 'asset.copy.status';
511         result.success := FALSE;
512         done := TRUE;
513         RETURN NEXT result;
514     END IF;
515
516     -- Fail if the item can't circulate because of the shelving location
517     SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
518     IF item_location_object.circulate IS FALSE THEN
519         result.fail_part := 'asset.copy_location.circulate';
520         result.success := FALSE;
521         done := TRUE;
522         RETURN NEXT result;
523     END IF;
524
525     -- Use Circ OU for penalties and such
526     SELECT INTO context_org_list ARRAY_AGG(id) FROM actor.org_unit_full_path( circ_ou );
527
528     -- Proximity of user's home_ou to circ_ou to see if penalties should be ignored.
529     SELECT INTO home_prox prox FROM actor.org_unit_proximity WHERE from_org = user_object.home_ou AND to_org = circ_ou;
530
531     -- Proximity of user's home_ou to item circ_lib to see if penalties should be ignored.
532     SELECT INTO item_prox prox FROM actor.org_unit_proximity WHERE from_org = user_object.home_ou AND to_org = item_object.circ_lib;
533
534     IF renewal THEN
535         penalty_type = '%RENEW%';
536     ELSE
537         penalty_type = '%CIRC%';
538     END IF;
539
540     FOR standing_penalty IN
541         SELECT  DISTINCT csp.*
542           FROM  actor.usr_standing_penalty usp
543                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
544           WHERE usr = match_user
545                 AND usp.org_unit IN ( SELECT * FROM unnest(context_org_list) )
546                 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
547                 AND (csp.ignore_proximity IS NULL
548                      OR csp.ignore_proximity < home_prox
549                      OR csp.ignore_proximity < item_prox)
550                 AND csp.block_list LIKE penalty_type LOOP
551
552         result.fail_part := standing_penalty.name;
553         result.success := FALSE;
554         done := TRUE;
555         RETURN NEXT result;
556     END LOOP;
557
558     -- Fail if the test is set to hard non-circulating
559     IF circ_matchpoint.circulate IS FALSE THEN
560         result.fail_part := 'config.circ_matrix_test.circulate';
561         result.success := FALSE;
562         done := TRUE;
563         RETURN NEXT result;
564     END IF;
565
566     -- Fail if the total copy-hold ratio is too low
567     IF circ_matchpoint.total_copy_hold_ratio IS NOT NULL THEN
568         SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
569         IF hold_ratio.total_copy_ratio IS NOT NULL AND hold_ratio.total_copy_ratio < circ_matchpoint.total_copy_hold_ratio THEN
570             result.fail_part := 'config.circ_matrix_test.total_copy_hold_ratio';
571             result.success := FALSE;
572             done := TRUE;
573             RETURN NEXT result;
574         END IF;
575     END IF;
576
577     -- Fail if the available copy-hold ratio is too low
578     IF circ_matchpoint.available_copy_hold_ratio IS NOT NULL THEN
579         IF hold_ratio.hold_count IS NULL THEN
580             SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
581         END IF;
582         IF hold_ratio.available_copy_ratio IS NOT NULL AND hold_ratio.available_copy_ratio < circ_matchpoint.available_copy_hold_ratio THEN
583             result.fail_part := 'config.circ_matrix_test.available_copy_hold_ratio';
584             result.success := FALSE;
585             done := TRUE;
586             RETURN NEXT result;
587         END IF;
588     END IF;
589
590     -- Fail if the user has too many items out by defined limit sets
591     FOR circ_limit_set IN SELECT ccls.* FROM config.circ_limit_set ccls
592       JOIN config.circ_matrix_limit_set_map ccmlsm ON ccmlsm.limit_set = ccls.id
593       WHERE ccmlsm.active AND ( ccmlsm.matchpoint = circ_matchpoint.id OR
594         ( ccmlsm.matchpoint IN (SELECT * FROM unnest(result.buildrows)) AND ccmlsm.fallthrough )
595         ) LOOP
596             IF circ_limit_set.items_out > 0 AND NOT renewal THEN
597                 SELECT INTO context_org_list ARRAY_AGG(aou.id)
598                   FROM actor.org_unit_full_path( circ_ou ) aou
599                     JOIN actor.org_unit_type aout ON aou.ou_type = aout.id
600                   WHERE aout.depth >= circ_limit_set.depth;
601                 IF circ_limit_set.global THEN
602                     WITH RECURSIVE descendant_depth AS (
603                         SELECT  ou.id,
604                             ou.parent_ou
605                         FROM  actor.org_unit ou
606                         WHERE ou.id IN (SELECT * FROM unnest(context_org_list))
607                             UNION
608                         SELECT  ou.id,
609                             ou.parent_ou
610                         FROM  actor.org_unit ou
611                             JOIN descendant_depth ot ON (ot.id = ou.parent_ou)
612                     ) SELECT INTO context_org_list ARRAY_AGG(ou.id) FROM actor.org_unit ou JOIN descendant_depth USING (id);
613                 END IF;
614                 SELECT INTO items_out COUNT(DISTINCT circ.id)
615                   FROM action.circulation circ
616                     JOIN asset.copy copy ON (copy.id = circ.target_copy)
617                     LEFT JOIN action.circulation_limit_group_map aclgm ON (circ.id = aclgm.circ)
618                   WHERE circ.usr = match_user
619                     AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
620                     AND circ.checkin_time IS NULL
621                     AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
622                     AND (copy.circ_modifier IN (SELECT circ_mod FROM config.circ_limit_set_circ_mod_map WHERE limit_set = circ_limit_set.id)
623                         OR copy.location IN (SELECT copy_loc FROM config.circ_limit_set_copy_loc_map WHERE limit_set = circ_limit_set.id)
624                         OR aclgm.limit_group IN (SELECT limit_group FROM config.circ_limit_set_group_map WHERE limit_set = circ_limit_set.id)
625                     );
626                 IF items_out >= circ_limit_set.items_out THEN
627                     result.fail_part := 'config.circ_matrix_circ_mod_test';
628                     result.success := FALSE;
629                     done := TRUE;
630                     RETURN NEXT result;
631                 END IF;
632             END IF;
633             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;
634     END LOOP;
635
636     -- If we passed everything, return the successful matchpoint
637     IF NOT done THEN
638         RETURN NEXT result;
639     END IF;
640
641     RETURN;
642 END;
643 $func$ LANGUAGE plpgsql;
644
645 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
646     SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
647 $func$ LANGUAGE SQL;
648
649 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
650     SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
651 $func$ LANGUAGE SQL;
652
653 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
654 DECLARE
655     user_object         actor.usr%ROWTYPE;
656     new_sp_row          actor.usr_standing_penalty%ROWTYPE;
657     existing_sp_row     actor.usr_standing_penalty%ROWTYPE;
658     collections_fines   permission.grp_penalty_threshold%ROWTYPE;
659     max_fines           permission.grp_penalty_threshold%ROWTYPE;
660     max_overdue         permission.grp_penalty_threshold%ROWTYPE;
661     max_items_out       permission.grp_penalty_threshold%ROWTYPE;
662     max_lost            permission.grp_penalty_threshold%ROWTYPE;
663     max_longoverdue     permission.grp_penalty_threshold%ROWTYPE;
664     tmp_grp             INT;
665     items_overdue       INT;
666     items_out           INT;
667     items_lost          INT;
668     items_longoverdue   INT;
669     context_org_list    INT[];
670     current_fines        NUMERIC(8,2) := 0.0;
671     tmp_fines            NUMERIC(8,2);
672     tmp_groc            RECORD;
673     tmp_circ            RECORD;
674     tmp_org             actor.org_unit%ROWTYPE;
675     tmp_penalty         config.standing_penalty%ROWTYPE;
676     tmp_depth           INTEGER;
677 BEGIN
678     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
679
680     -- Max fines
681     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
682
683     -- Fail if the user has a high fine balance
684     LOOP
685         tmp_grp := user_object.profile;
686         LOOP
687             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
688
689             IF max_fines.threshold IS NULL THEN
690                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
691             ELSE
692                 EXIT;
693             END IF;
694
695             IF tmp_grp IS NULL THEN
696                 EXIT;
697             END IF;
698         END LOOP;
699
700         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
701             EXIT;
702         END IF;
703
704         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
705
706     END LOOP;
707
708     IF max_fines.threshold IS NOT NULL THEN
709
710         RETURN QUERY
711             SELECT  *
712               FROM  actor.usr_standing_penalty
713               WHERE usr = match_user
714                     AND org_unit = max_fines.org_unit
715                     AND (stop_date IS NULL or stop_date > NOW())
716                     AND standing_penalty = 1;
717
718         SELECT INTO context_org_list ARRAY_AGG(id) FROM actor.org_unit_full_path( max_fines.org_unit );
719
720         SELECT  SUM(f.balance_owed) INTO current_fines
721           FROM  money.materialized_billable_xact_summary f
722                 JOIN (
723                     SELECT  r.id
724                       FROM  booking.reservation r
725                       WHERE r.usr = match_user
726                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
727                             AND xact_finish IS NULL
728                                 UNION ALL
729                     SELECT  g.id
730                       FROM  money.grocery g
731                       WHERE g.usr = match_user
732                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
733                             AND xact_finish IS NULL
734                                 UNION ALL
735                     SELECT  circ.id
736                       FROM  action.circulation circ
737                       WHERE circ.usr = match_user
738                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
739                             AND xact_finish IS NULL ) l USING (id);
740
741         IF current_fines >= max_fines.threshold THEN
742             new_sp_row.usr := match_user;
743             new_sp_row.org_unit := max_fines.org_unit;
744             new_sp_row.standing_penalty := 1;
745             RETURN NEXT new_sp_row;
746         END IF;
747     END IF;
748
749     -- Start over for max overdue
750     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
751
752     -- Fail if the user has too many overdue items
753     LOOP
754         tmp_grp := user_object.profile;
755         LOOP
756
757             SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
758
759             IF max_overdue.threshold IS NULL THEN
760                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
761             ELSE
762                 EXIT;
763             END IF;
764
765             IF tmp_grp IS NULL THEN
766                 EXIT;
767             END IF;
768         END LOOP;
769
770         IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
771             EXIT;
772         END IF;
773
774         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
775
776     END LOOP;
777
778     IF max_overdue.threshold IS NOT NULL THEN
779
780         RETURN QUERY
781             SELECT  *
782               FROM  actor.usr_standing_penalty
783               WHERE usr = match_user
784                     AND org_unit = max_overdue.org_unit
785                     AND (stop_date IS NULL or stop_date > NOW())
786                     AND standing_penalty = 2;
787
788         SELECT  INTO items_overdue COUNT(*)
789           FROM  action.circulation circ
790                 JOIN  actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
791           WHERE circ.usr = match_user
792             AND circ.checkin_time IS NULL
793             AND circ.due_date < NOW()
794             AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
795
796         IF items_overdue >= max_overdue.threshold::INT THEN
797             new_sp_row.usr := match_user;
798             new_sp_row.org_unit := max_overdue.org_unit;
799             new_sp_row.standing_penalty := 2;
800             RETURN NEXT new_sp_row;
801         END IF;
802     END IF;
803
804     -- Start over for max out
805     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
806
807     -- Fail if the user has too many checked out items
808     LOOP
809         tmp_grp := user_object.profile;
810         LOOP
811             SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
812
813             IF max_items_out.threshold IS NULL THEN
814                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
815             ELSE
816                 EXIT;
817             END IF;
818
819             IF tmp_grp IS NULL THEN
820                 EXIT;
821             END IF;
822         END LOOP;
823
824         IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
825             EXIT;
826         END IF;
827
828         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
829
830     END LOOP;
831
832
833     -- Fail if the user has too many items checked out
834     IF max_items_out.threshold IS NOT NULL THEN
835
836         RETURN QUERY
837             SELECT  *
838               FROM  actor.usr_standing_penalty
839               WHERE usr = match_user
840                     AND org_unit = max_items_out.org_unit
841                     AND (stop_date IS NULL or stop_date > NOW())
842                     AND standing_penalty = 3;
843
844         SELECT  INTO items_out COUNT(*)
845           FROM  action.circulation circ
846                 JOIN  actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
847           WHERE circ.usr = match_user
848                 AND circ.checkin_time IS NULL
849                 AND (circ.stop_fines IN (
850                     SELECT 'MAXFINES'::TEXT
851                     UNION ALL
852                     SELECT 'LONGOVERDUE'::TEXT
853                     UNION ALL
854                     SELECT 'LOST'::TEXT
855                     WHERE 'true' ILIKE
856                     (
857                         SELECT CASE
858                             WHEN (SELECT value FROM actor.org_unit_ancestor_setting('circ.tally_lost', circ.circ_lib)) ILIKE 'true' THEN 'true'
859                             ELSE 'false'
860                         END
861                     )
862                     UNION ALL
863                     SELECT 'CLAIMSRETURNED'::TEXT
864                     WHERE 'false' ILIKE
865                     (
866                         SELECT CASE
867                             WHEN (SELECT value FROM actor.org_unit_ancestor_setting('circ.do_not_tally_claims_returned', circ.circ_lib)) ILIKE 'true' THEN 'true'
868                             ELSE 'false'
869                         END
870                     )
871                     ) OR circ.stop_fines IS NULL)
872                 AND xact_finish IS NULL;
873
874            IF items_out >= max_items_out.threshold::INT THEN
875             new_sp_row.usr := match_user;
876             new_sp_row.org_unit := max_items_out.org_unit;
877             new_sp_row.standing_penalty := 3;
878             RETURN NEXT new_sp_row;
879            END IF;
880     END IF;
881
882     -- Start over for max lost
883     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
884
885     -- Fail if the user has too many lost items
886     LOOP
887         tmp_grp := user_object.profile;
888         LOOP
889
890             SELECT * INTO max_lost FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 5 AND org_unit = tmp_org.id;
891
892             IF max_lost.threshold IS NULL THEN
893                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
894             ELSE
895                 EXIT;
896             END IF;
897
898             IF tmp_grp IS NULL THEN
899                 EXIT;
900             END IF;
901         END LOOP;
902
903         IF max_lost.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
904             EXIT;
905         END IF;
906
907         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
908
909     END LOOP;
910
911     IF max_lost.threshold IS NOT NULL THEN
912
913         RETURN QUERY
914             SELECT  *
915             FROM  actor.usr_standing_penalty
916             WHERE usr = match_user
917                 AND org_unit = max_lost.org_unit
918                 AND (stop_date IS NULL or stop_date > NOW())
919                 AND standing_penalty = 5;
920
921         SELECT  INTO items_lost COUNT(*)
922         FROM  action.circulation circ
923             JOIN  actor.org_unit_full_path( max_lost.org_unit ) fp ON (circ.circ_lib = fp.id)
924         WHERE circ.usr = match_user
925             AND circ.checkin_time IS NULL
926             AND (circ.stop_fines = 'LOST')
927             AND xact_finish IS NULL;
928
929         IF items_lost >= max_lost.threshold::INT AND 0 < max_lost.threshold::INT THEN
930             new_sp_row.usr := match_user;
931             new_sp_row.org_unit := max_lost.org_unit;
932             new_sp_row.standing_penalty := 5;
933             RETURN NEXT new_sp_row;
934         END IF;
935     END IF;
936
937     -- Start over for max longoverdue
938     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
939
940     -- Fail if the user has too many longoverdue items
941     LOOP
942         tmp_grp := user_object.profile;
943         LOOP
944
945             SELECT * INTO max_longoverdue 
946                 FROM permission.grp_penalty_threshold 
947                 WHERE grp = tmp_grp AND 
948                     penalty = 35 AND 
949                     org_unit = tmp_org.id;
950
951             IF max_longoverdue.threshold IS NULL THEN
952                 SELECT parent INTO tmp_grp 
953                     FROM permission.grp_tree WHERE id = tmp_grp;
954             ELSE
955                 EXIT;
956             END IF;
957
958             IF tmp_grp IS NULL THEN
959                 EXIT;
960             END IF;
961         END LOOP;
962
963         IF max_longoverdue.threshold IS NOT NULL 
964                 OR tmp_org.parent_ou IS NULL THEN
965             EXIT;
966         END IF;
967
968         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
969
970     END LOOP;
971
972     IF max_longoverdue.threshold IS NOT NULL THEN
973
974         RETURN QUERY
975             SELECT  *
976             FROM  actor.usr_standing_penalty
977             WHERE usr = match_user
978                 AND org_unit = max_longoverdue.org_unit
979                 AND (stop_date IS NULL or stop_date > NOW())
980                 AND standing_penalty = 35;
981
982         SELECT INTO items_longoverdue COUNT(*)
983         FROM action.circulation circ
984             JOIN actor.org_unit_full_path( max_longoverdue.org_unit ) fp 
985                 ON (circ.circ_lib = fp.id)
986         WHERE circ.usr = match_user
987             AND circ.checkin_time IS NULL
988             AND (circ.stop_fines = 'LONGOVERDUE')
989             AND xact_finish IS NULL;
990
991         IF items_longoverdue >= max_longoverdue.threshold::INT 
992                 AND 0 < max_longoverdue.threshold::INT THEN
993             new_sp_row.usr := match_user;
994             new_sp_row.org_unit := max_longoverdue.org_unit;
995             new_sp_row.standing_penalty := 35;
996             RETURN NEXT new_sp_row;
997         END IF;
998     END IF;
999
1000
1001     -- Start over for collections warning
1002     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
1003
1004     -- Fail if the user has a collections-level fine balance
1005     LOOP
1006         tmp_grp := user_object.profile;
1007         LOOP
1008             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
1009
1010             IF max_fines.threshold IS NULL THEN
1011                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
1012             ELSE
1013                 EXIT;
1014             END IF;
1015
1016             IF tmp_grp IS NULL THEN
1017                 EXIT;
1018             END IF;
1019         END LOOP;
1020
1021         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
1022             EXIT;
1023         END IF;
1024
1025         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
1026
1027     END LOOP;
1028
1029     IF max_fines.threshold IS NOT NULL THEN
1030
1031         RETURN QUERY
1032             SELECT  *
1033               FROM  actor.usr_standing_penalty
1034               WHERE usr = match_user
1035                     AND org_unit = max_fines.org_unit
1036                     AND (stop_date IS NULL or stop_date > NOW())
1037                     AND standing_penalty = 4;
1038
1039         SELECT INTO context_org_list ARRAY_AGG(id) FROM actor.org_unit_full_path( max_fines.org_unit );
1040
1041         SELECT  SUM(f.balance_owed) INTO current_fines
1042           FROM  money.materialized_billable_xact_summary f
1043                 JOIN (
1044                     SELECT  r.id
1045                       FROM  booking.reservation r
1046                       WHERE r.usr = match_user
1047                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
1048                             AND r.xact_finish IS NULL
1049                                 UNION ALL
1050                     SELECT  g.id
1051                       FROM  money.grocery g
1052                       WHERE g.usr = match_user
1053                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
1054                             AND g.xact_finish IS NULL
1055                                 UNION ALL
1056                     SELECT  circ.id
1057                       FROM  action.circulation circ
1058                       WHERE circ.usr = match_user
1059                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
1060                             AND circ.xact_finish IS NULL ) l USING (id);
1061
1062         IF current_fines >= max_fines.threshold THEN
1063             new_sp_row.usr := match_user;
1064             new_sp_row.org_unit := max_fines.org_unit;
1065             new_sp_row.standing_penalty := 4;
1066             RETURN NEXT new_sp_row;
1067         END IF;
1068     END IF;
1069
1070     -- Start over for in collections
1071     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
1072
1073     -- Remove the in-collections penalty if the user has paid down enough
1074     -- This penalty is different, because this code is not responsible for creating 
1075     -- new in-collections penalties, only for removing them
1076     LOOP
1077         tmp_grp := user_object.profile;
1078         LOOP
1079             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 30 AND org_unit = tmp_org.id;
1080
1081             IF max_fines.threshold IS NULL THEN
1082                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
1083             ELSE
1084                 EXIT;
1085             END IF;
1086
1087             IF tmp_grp IS NULL THEN
1088                 EXIT;
1089             END IF;
1090         END LOOP;
1091
1092         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
1093             EXIT;
1094         END IF;
1095
1096         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
1097
1098     END LOOP;
1099
1100     IF max_fines.threshold IS NOT NULL THEN
1101
1102         SELECT INTO context_org_list ARRAY_AGG(id) FROM actor.org_unit_full_path( max_fines.org_unit );
1103
1104         -- first, see if the user had paid down to the threshold
1105         SELECT  SUM(f.balance_owed) INTO current_fines
1106           FROM  money.materialized_billable_xact_summary f
1107                 JOIN (
1108                     SELECT  r.id
1109                       FROM  booking.reservation r
1110                       WHERE r.usr = match_user
1111                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
1112                             AND r.xact_finish IS NULL
1113                                 UNION ALL
1114                     SELECT  g.id
1115                       FROM  money.grocery g
1116                       WHERE g.usr = match_user
1117                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
1118                             AND g.xact_finish IS NULL
1119                                 UNION ALL
1120                     SELECT  circ.id
1121                       FROM  action.circulation circ
1122                       WHERE circ.usr = match_user
1123                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
1124                             AND circ.xact_finish IS NULL ) l USING (id);
1125
1126         IF current_fines IS NULL OR current_fines <= max_fines.threshold THEN
1127             -- patron has paid down enough
1128
1129             SELECT INTO tmp_penalty * FROM config.standing_penalty WHERE id = 30;
1130
1131             IF tmp_penalty.org_depth IS NOT NULL THEN
1132
1133                 -- since this code is not responsible for applying the penalty, it can't 
1134                 -- guarantee the current context org will match the org at which the penalty 
1135                 --- was applied.  search up the org tree until we hit the configured penalty depth
1136                 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
1137                 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
1138
1139                 WHILE tmp_depth >= tmp_penalty.org_depth LOOP
1140
1141                     RETURN QUERY
1142                         SELECT  *
1143                           FROM  actor.usr_standing_penalty
1144                           WHERE usr = match_user
1145                                 AND org_unit = tmp_org.id
1146                                 AND (stop_date IS NULL or stop_date > NOW())
1147                                 AND standing_penalty = 30;
1148
1149                     IF tmp_org.parent_ou IS NULL THEN
1150                         EXIT;
1151                     END IF;
1152
1153                     SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
1154                     SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
1155                 END LOOP;
1156
1157             ELSE
1158
1159                 -- no penalty depth is defined, look for exact matches
1160
1161                 RETURN QUERY
1162                     SELECT  *
1163                       FROM  actor.usr_standing_penalty
1164                       WHERE usr = match_user
1165                             AND org_unit = max_fines.org_unit
1166                             AND (stop_date IS NULL or stop_date > NOW())
1167                             AND standing_penalty = 30;
1168             END IF;
1169     
1170         END IF;
1171
1172     END IF;
1173
1174     RETURN;
1175 END;
1176 $func$ LANGUAGE plpgsql;
1177
1178
1179
1180 COMMIT;
1181