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