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