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