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