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