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