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