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