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