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