]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
Stamping upgrade scripts for LP#818740
[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_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     -- Apparently....use the circ matchpoint org unit to determine what org units are valid.
469     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( circ_matchpoint.org_unit );
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     FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = circ_matchpoint.id LOOP
526         SELECT  INTO items_out COUNT(*)
527           FROM  action.circulation circ
528             JOIN asset.copy cp ON (cp.id = circ.target_copy)
529           WHERE circ.usr = match_user
530                AND circ.circ_lib IN ( SELECT * FROM unnest(context_org_list) )
531             AND circ.checkin_time IS NULL
532             AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
533             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);
534         IF items_out >= out_by_circ_mod.items_out THEN
535             result.fail_part := 'config.circ_matrix_circ_mod_test';
536             result.success := FALSE;
537             done := TRUE;
538             RETURN NEXT result;
539         END IF;
540     END LOOP;
541
542     -- If we passed everything, return the successful matchpoint
543     IF NOT done THEN
544         RETURN NEXT result;
545     END IF;
546
547     RETURN;
548 END;
549 $func$ LANGUAGE plpgsql;
550
551 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
552     SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
553 $func$ LANGUAGE SQL;
554
555 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.circ_matrix_test_result AS $func$
556     SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
557 $func$ LANGUAGE SQL;
558
559
560 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
561 DECLARE
562     user_object         actor.usr%ROWTYPE;
563     new_sp_row          actor.usr_standing_penalty%ROWTYPE;
564     existing_sp_row     actor.usr_standing_penalty%ROWTYPE;
565     collections_fines   permission.grp_penalty_threshold%ROWTYPE;
566     max_fines           permission.grp_penalty_threshold%ROWTYPE;
567     max_overdue         permission.grp_penalty_threshold%ROWTYPE;
568     max_items_out       permission.grp_penalty_threshold%ROWTYPE;
569     tmp_grp             INT;
570     items_overdue       INT;
571     items_out           INT;
572     context_org_list    INT[];
573     current_fines        NUMERIC(8,2) := 0.0;
574     tmp_fines            NUMERIC(8,2);
575     tmp_groc            RECORD;
576     tmp_circ            RECORD;
577     tmp_org             actor.org_unit%ROWTYPE;
578     tmp_penalty         config.standing_penalty%ROWTYPE;
579     tmp_depth           INTEGER;
580 BEGIN
581     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
582
583     -- Max fines
584     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
585
586     -- Fail if the user has a high fine balance
587     LOOP
588         tmp_grp := user_object.profile;
589         LOOP
590             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
591
592             IF max_fines.threshold IS NULL THEN
593                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
594             ELSE
595                 EXIT;
596             END IF;
597
598             IF tmp_grp IS NULL THEN
599                 EXIT;
600             END IF;
601         END LOOP;
602
603         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
604             EXIT;
605         END IF;
606
607         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
608
609     END LOOP;
610
611     IF max_fines.threshold IS NOT NULL THEN
612
613         RETURN QUERY
614             SELECT  *
615               FROM  actor.usr_standing_penalty
616               WHERE usr = match_user
617                     AND org_unit = max_fines.org_unit
618                     AND (stop_date IS NULL or stop_date > NOW())
619                     AND standing_penalty = 1;
620
621         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
622
623         SELECT  SUM(f.balance_owed) INTO current_fines
624           FROM  money.materialized_billable_xact_summary f
625                 JOIN (
626                     SELECT  r.id
627                       FROM  booking.reservation r
628                       WHERE r.usr = match_user
629                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
630                             AND xact_finish IS NULL
631                                 UNION ALL
632                     SELECT  g.id
633                       FROM  money.grocery g
634                       WHERE g.usr = match_user
635                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
636                             AND xact_finish IS NULL
637                                 UNION ALL
638                     SELECT  circ.id
639                       FROM  action.circulation circ
640                       WHERE circ.usr = match_user
641                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
642                             AND xact_finish IS NULL ) l USING (id);
643
644         IF current_fines >= max_fines.threshold THEN
645             new_sp_row.usr := match_user;
646             new_sp_row.org_unit := max_fines.org_unit;
647             new_sp_row.standing_penalty := 1;
648             RETURN NEXT new_sp_row;
649         END IF;
650     END IF;
651
652     -- Start over for max overdue
653     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
654
655     -- Fail if the user has too many overdue items
656     LOOP
657         tmp_grp := user_object.profile;
658         LOOP
659
660             SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
661
662             IF max_overdue.threshold IS NULL THEN
663                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
664             ELSE
665                 EXIT;
666             END IF;
667
668             IF tmp_grp IS NULL THEN
669                 EXIT;
670             END IF;
671         END LOOP;
672
673         IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
674             EXIT;
675         END IF;
676
677         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
678
679     END LOOP;
680
681     IF max_overdue.threshold IS NOT NULL THEN
682
683         RETURN QUERY
684             SELECT  *
685               FROM  actor.usr_standing_penalty
686               WHERE usr = match_user
687                     AND org_unit = max_overdue.org_unit
688                     AND (stop_date IS NULL or stop_date > NOW())
689                     AND standing_penalty = 2;
690
691         SELECT  INTO items_overdue COUNT(*)
692           FROM  action.circulation circ
693                 JOIN  actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
694           WHERE circ.usr = match_user
695             AND circ.checkin_time IS NULL
696             AND circ.due_date < NOW()
697             AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
698
699         IF items_overdue >= max_overdue.threshold::INT THEN
700             new_sp_row.usr := match_user;
701             new_sp_row.org_unit := max_overdue.org_unit;
702             new_sp_row.standing_penalty := 2;
703             RETURN NEXT new_sp_row;
704         END IF;
705     END IF;
706
707     -- Start over for max out
708     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
709
710     -- Fail if the user has too many checked out items
711     LOOP
712         tmp_grp := user_object.profile;
713         LOOP
714             SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
715
716             IF max_items_out.threshold IS NULL THEN
717                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
718             ELSE
719                 EXIT;
720             END IF;
721
722             IF tmp_grp IS NULL THEN
723                 EXIT;
724             END IF;
725         END LOOP;
726
727         IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
728             EXIT;
729         END IF;
730
731         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
732
733     END LOOP;
734
735
736     -- Fail if the user has too many items checked out
737     IF max_items_out.threshold IS NOT NULL THEN
738
739         RETURN QUERY
740             SELECT  *
741               FROM  actor.usr_standing_penalty
742               WHERE usr = match_user
743                     AND org_unit = max_items_out.org_unit
744                     AND (stop_date IS NULL or stop_date > NOW())
745                     AND standing_penalty = 3;
746
747         SELECT  INTO items_out COUNT(*)
748           FROM  action.circulation circ
749                 JOIN  actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
750           WHERE circ.usr = match_user
751                 AND circ.checkin_time IS NULL
752                 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL);
753
754            IF items_out >= max_items_out.threshold::INT THEN
755             new_sp_row.usr := match_user;
756             new_sp_row.org_unit := max_items_out.org_unit;
757             new_sp_row.standing_penalty := 3;
758             RETURN NEXT new_sp_row;
759            END IF;
760     END IF;
761
762     -- Start over for collections warning
763     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
764
765     -- Fail if the user has a collections-level fine balance
766     LOOP
767         tmp_grp := user_object.profile;
768         LOOP
769             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
770
771             IF max_fines.threshold IS NULL THEN
772                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
773             ELSE
774                 EXIT;
775             END IF;
776
777             IF tmp_grp IS NULL THEN
778                 EXIT;
779             END IF;
780         END LOOP;
781
782         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
783             EXIT;
784         END IF;
785
786         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
787
788     END LOOP;
789
790     IF max_fines.threshold IS NOT NULL THEN
791
792         RETURN QUERY
793             SELECT  *
794               FROM  actor.usr_standing_penalty
795               WHERE usr = match_user
796                     AND org_unit = max_fines.org_unit
797                     AND (stop_date IS NULL or stop_date > NOW())
798                     AND standing_penalty = 4;
799
800         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
801
802         SELECT  SUM(f.balance_owed) INTO current_fines
803           FROM  money.materialized_billable_xact_summary f
804                 JOIN (
805                     SELECT  r.id
806                       FROM  booking.reservation r
807                       WHERE r.usr = match_user
808                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
809                             AND r.xact_finish IS NULL
810                                 UNION ALL
811                     SELECT  g.id
812                       FROM  money.grocery g
813                       WHERE g.usr = match_user
814                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
815                             AND g.xact_finish IS NULL
816                                 UNION ALL
817                     SELECT  circ.id
818                       FROM  action.circulation circ
819                       WHERE circ.usr = match_user
820                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
821                             AND circ.xact_finish IS NULL ) l USING (id);
822
823         IF current_fines >= max_fines.threshold THEN
824             new_sp_row.usr := match_user;
825             new_sp_row.org_unit := max_fines.org_unit;
826             new_sp_row.standing_penalty := 4;
827             RETURN NEXT new_sp_row;
828         END IF;
829     END IF;
830
831     -- Start over for in collections
832     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
833
834     -- Remove the in-collections penalty if the user has paid down enough
835     -- This penalty is different, because this code is not responsible for creating 
836     -- new in-collections penalties, only for removing them
837     LOOP
838         tmp_grp := user_object.profile;
839         LOOP
840             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 30 AND org_unit = tmp_org.id;
841
842             IF max_fines.threshold IS NULL THEN
843                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
844             ELSE
845                 EXIT;
846             END IF;
847
848             IF tmp_grp IS NULL THEN
849                 EXIT;
850             END IF;
851         END LOOP;
852
853         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
854             EXIT;
855         END IF;
856
857         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
858
859     END LOOP;
860
861     IF max_fines.threshold IS NOT NULL THEN
862
863         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
864
865         -- first, see if the user had paid down to the threshold
866         SELECT  SUM(f.balance_owed) INTO current_fines
867           FROM  money.materialized_billable_xact_summary f
868                 JOIN (
869                     SELECT  r.id
870                       FROM  booking.reservation r
871                       WHERE r.usr = match_user
872                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
873                             AND r.xact_finish IS NULL
874                                 UNION ALL
875                     SELECT  g.id
876                       FROM  money.grocery g
877                       WHERE g.usr = match_user
878                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
879                             AND g.xact_finish IS NULL
880                                 UNION ALL
881                     SELECT  circ.id
882                       FROM  action.circulation circ
883                       WHERE circ.usr = match_user
884                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
885                             AND circ.xact_finish IS NULL ) l USING (id);
886
887         IF current_fines IS NULL OR current_fines <= max_fines.threshold THEN
888             -- patron has paid down enough
889
890             SELECT INTO tmp_penalty * FROM config.standing_penalty WHERE id = 30;
891
892             IF tmp_penalty.org_depth IS NOT NULL THEN
893
894                 -- since this code is not responsible for applying the penalty, it can't 
895                 -- guarantee the current context org will match the org at which the penalty 
896                 --- was applied.  search up the org tree until we hit the configured penalty depth
897                 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
898                 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
899
900                 WHILE tmp_depth >= tmp_penalty.org_depth LOOP
901
902                     RETURN QUERY
903                         SELECT  *
904                           FROM  actor.usr_standing_penalty
905                           WHERE usr = match_user
906                                 AND org_unit = tmp_org.id
907                                 AND (stop_date IS NULL or stop_date > NOW())
908                                 AND standing_penalty = 30;
909
910                     IF tmp_org.parent_ou IS NULL THEN
911                         EXIT;
912                     END IF;
913
914                     SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
915                     SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
916                 END LOOP;
917
918             ELSE
919
920                 -- no penalty depth is defined, look for exact matches
921
922                 RETURN QUERY
923                     SELECT  *
924                       FROM  actor.usr_standing_penalty
925                       WHERE usr = match_user
926                             AND org_unit = max_fines.org_unit
927                             AND (stop_date IS NULL or stop_date > NOW())
928                             AND standing_penalty = 30;
929             END IF;
930     
931         END IF;
932
933     END IF;
934
935     RETURN;
936 END;
937 $func$ LANGUAGE plpgsql;
938
939 COMMIT;
940