]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
teach the penalty code how to create events for system penalties returned from actor...
[working/Evergreen.git] / Open-ILS / src / sql / Pg / 100.circ_matrix.sql
1
2 BEGIN;
3
4 CREATE OR REPLACE FUNCTION explode_array(anyarray) RETURNS SETOF anyelement AS $BODY$
5     SELECT ($1)[s] FROM generate_series(1, array_upper($1, 1)) AS s;
6 $BODY$
7 LANGUAGE 'sql' IMMUTABLE;
8
9 -- NOTE: current config.item_type should get sip2_media_type and magnetic_media columns
10
11 -- New table needed to handle circ modifiers inside the DB.  Will still require
12 -- central admin.  The circ_modifier column on asset.copy will become an fkey to this table.
13 CREATE TABLE config.circ_modifier (
14     code            TEXT    PRIMARY KEY,
15     name            TEXT    UNIQUE NOT NULL,
16     description        TEXT    NOT NULL,
17     sip2_media_type    TEXT    NOT NULL,
18     magnetic_media    BOOL    NOT NULL DEFAULT TRUE
19 );
20
21 /*
22 -- for instance ...
23 INSERT INTO config.circ_modifier VALUES ( 'DVD', 'DVD', 'um ... DVDs', '001', FALSE );
24 INSERT INTO config.circ_modifier VALUES ( 'VIDEO', 'VIDEO', 'Tapes', '001', TRUE );
25 INSERT INTO config.circ_modifier VALUES ( 'BOOK', 'BOOK', 'Dead tree', '001', FALSE );
26 INSERT INTO config.circ_modifier VALUES ( 'CRAZY_ARL-ATH_SETTING', 'R2R_TAPE', 'reel2reel tape', '007', TRUE );
27 */
28
29 -- But, just to get us started, use this
30 /*
31
32 UPDATE asset.copy SET circ_modifier = UPPER(circ_modifier) WHERE circ_modifier IS NOT NULL AND circ_modifier <> '';
33 UPDATE asset.copy SET circ_modifier = NULL WHERE circ_modifier = '';
34
35 INSERT INTO config.circ_modifier (code, name, description, sip2_media_type )
36     SELECT DISTINCT
37             UPPER(circ_modifier),
38             UPPER(circ_modifier),
39             LOWER(circ_modifier),
40             '001'
41       FROM  asset.copy
42       WHERE circ_modifier IS NOT NULL;
43
44 */
45
46 -- add an fkey pointing to the new circ mod table
47 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;
48
49 -- config table to hold the vr_format names
50 CREATE TABLE config.videorecording_format_map (
51     code    TEXT    PRIMARY KEY,
52     value    TEXT    NOT NULL
53 );
54
55 INSERT INTO config.videorecording_format_map VALUES ('a','Beta');
56 INSERT INTO config.videorecording_format_map VALUES ('b','VHS');
57 INSERT INTO config.videorecording_format_map VALUES ('c','U-matic');
58 INSERT INTO config.videorecording_format_map VALUES ('d','EIAJ');
59 INSERT INTO config.videorecording_format_map VALUES ('e','Type C');
60 INSERT INTO config.videorecording_format_map VALUES ('f','Quadruplex');
61 INSERT INTO config.videorecording_format_map VALUES ('g','Laserdisc');
62 INSERT INTO config.videorecording_format_map VALUES ('h','CED');
63 INSERT INTO config.videorecording_format_map VALUES ('i','Betacam');
64 INSERT INTO config.videorecording_format_map VALUES ('j','Betacam SP');
65 INSERT INTO config.videorecording_format_map VALUES ('k','Super-VHS');
66 INSERT INTO config.videorecording_format_map VALUES ('m','M-II');
67 INSERT INTO config.videorecording_format_map VALUES ('o','D-2');
68 INSERT INTO config.videorecording_format_map VALUES ('p','8 mm.');
69 INSERT INTO config.videorecording_format_map VALUES ('q','Hi-8 mm.');
70 INSERT INTO config.videorecording_format_map VALUES ('u','Unknown');
71 INSERT INTO config.videorecording_format_map VALUES ('v','DVD');
72 INSERT INTO config.videorecording_format_map VALUES ('z','Other');
73
74
75
76 /**
77  **  Here we define the tables that make up the circ matrix.  Conceptually, this implements
78  **  the "sparse matrix" that everyone talks about, instead of using traditional rules logic.
79  **  Physically, we cut the matrix up into separate tables (almost 3rd normal form!) that handle
80  **  different portions of the matrix.  This wil simplify creation of the UI (I hope), and help the
81  **  developers focus on specific parts of the matrix.
82  **/
83
84
85 --
86 --                 ****** Which ruleset and tests to use *******
87 --
88 -- * Most specific range for org_unit and grp wins.
89 --
90 -- * circ_modifier match takes precidence over marc_type match, if circ_modifier is set here
91 --
92 -- * marc_type is first checked against the circ_as_type from the copy, then the item type from the marc record
93 --
94 -- * If neither circ_modifier nor marc_type is set (both are NULLABLE) then the entry defines the default
95 --   ruleset and tests for the OU + group (like BOOK in PINES)
96 --
97
98 CREATE TABLE config.circ_matrix_matchpoint (
99     id                   SERIAL    PRIMARY KEY,
100     active               BOOL    NOT NULL DEFAULT TRUE,
101     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"
102     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
103     circ_modifier        TEXT    REFERENCES config.circ_modifier (code) DEFERRABLE INITIALLY DEFERRED,
104     marc_type            TEXT    REFERENCES config.item_type_map (code) DEFERRABLE INITIALLY DEFERRED,
105     marc_form            TEXT    REFERENCES config.item_form_map (code) DEFERRABLE INITIALLY DEFERRED,
106     marc_vr_format       TEXT    REFERENCES config.videorecording_format_map (code) DEFERRABLE INITIALLY DEFERRED,
107     ref_flag             BOOL,
108     juvenile_flag        BOOL,
109     is_renewal           BOOL,
110     usr_age_lower_bound  INTERVAL,
111     usr_age_upper_bound  INTERVAL,
112     circulate            BOOL    NOT NULL DEFAULT TRUE,    -- Hard "can't circ" flag requiring an override
113     duration_rule        INT     NOT NULL REFERENCES config.rule_circ_duration (id) DEFERRABLE INITIALLY DEFERRED,
114     recurring_fine_rule  INT     NOT NULL REFERENCES config.rule_recuring_fine (id) DEFERRABLE INITIALLY DEFERRED,
115     max_fine_rule        INT     NOT NULL REFERENCES config.rule_max_fine (id) DEFERRABLE INITIALLY DEFERRED,
116     script_test          TEXT,                           -- javascript source 
117     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)
118 );
119
120
121 -- Tests for max items out by circ_modifier
122 CREATE TABLE config.circ_matrix_circ_mod_test (
123     id          SERIAL     PRIMARY KEY,
124     matchpoint  INT     NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
125     items_out   INT     NOT NULL,                            -- Total current active circulations must be less than this, NULL means skip (always pass)
126     circ_mod    TEXT    NOT NULL REFERENCES config.circ_modifier (code) ON DELETE CASCADE ON UPDATE CASCADE  DEFERRABLE INITIALLY DEFERRED-- circ_modifier type that the max out applies to
127 );
128
129
130 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$
131 DECLARE
132     current_group    permission.grp_tree%ROWTYPE;
133     user_object    actor.usr%ROWTYPE;
134     item_object    asset.copy%ROWTYPE;
135     rec_descriptor    metabib.rec_descriptor%ROWTYPE;
136     current_mp    config.circ_matrix_matchpoint%ROWTYPE;
137     matchpoint    config.circ_matrix_matchpoint%ROWTYPE;
138 BEGIN
139     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
140     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
141     SELECT INTO rec_descriptor r.* FROM metabib.rec_descriptor r JOIN asset.call_number c USING (record) WHERE c.id = item_object.call_number;
142     SELECT INTO current_group * FROM permission.grp_tree WHERE id = user_object.profile;
143
144     LOOP 
145         -- for each potential matchpoint for this ou and group ...
146         FOR current_mp IN
147             SELECT    m.*
148               FROM    config.circ_matrix_matchpoint m
149                 JOIN actor.org_unit_ancestors( context_ou ) d ON (m.org_unit = d.id)
150                 LEFT JOIN actor.org_unit_proximity p ON (p.from_org = context_ou AND p.to_org = d.id)
151               WHERE    m.grp = current_group.id AND m.active
152               ORDER BY    CASE WHEN p.prox        IS NULL THEN 999 ELSE p.prox END,
153                     CASE WHEN m.is_renewal = renewal        THEN 128 ELSE 0 END +
154                     CASE WHEN m.juvenile_flag    IS NOT NULL THEN 64 ELSE 0 END +
155                     CASE WHEN m.circ_modifier    IS NOT NULL THEN 32 ELSE 0 END +
156                     CASE WHEN m.marc_type        IS NOT NULL THEN 16 ELSE 0 END +
157                     CASE WHEN m.marc_form        IS NOT NULL THEN 8 ELSE 0 END +
158                     CASE WHEN m.marc_vr_format    IS NOT NULL THEN 4 ELSE 0 END +
159                     CASE WHEN m.ref_flag        IS NOT NULL THEN 2 ELSE 0 END +
160                     CASE WHEN m.usr_age_lower_bound    IS NOT NULL THEN 0.5 ELSE 0 END +
161                     CASE WHEN m.usr_age_upper_bound    IS NOT NULL THEN 0.5 ELSE 0 END DESC LOOP
162
163             IF current_mp.circ_modifier IS NOT NULL THEN
164                 CONTINUE WHEN current_mp.circ_modifier <> item_object.circ_modifier;
165             END IF;
166
167             IF current_mp.marc_type IS NOT NULL THEN
168                 IF item_object.circ_as_type IS NOT NULL THEN
169                     CONTINUE WHEN current_mp.marc_type <> item_object.circ_as_type;
170                 ELSE
171                     CONTINUE WHEN current_mp.marc_type <> rec_descriptor.item_type;
172                 END IF;
173             END IF;
174
175             IF current_mp.marc_form IS NOT NULL THEN
176                 CONTINUE WHEN current_mp.marc_form <> rec_descriptor.item_form;
177             END IF;
178
179             IF current_mp.marc_vr_format IS NOT NULL THEN
180                 CONTINUE WHEN current_mp.marc_vr_format <> rec_descriptor.vr_format;
181             END IF;
182
183             IF current_mp.ref_flag IS NOT NULL THEN
184                 CONTINUE WHEN current_mp.ref_flag <> item_object.ref;
185             END IF;
186
187             IF current_mp.juvenile_flag IS NOT NULL THEN
188                 CONTINUE WHEN current_mp.juvenile_flag <> user_object.juvenile;
189             END IF;
190
191             IF current_mp.usr_age_lower_bound IS NOT NULL THEN
192                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_lower_bound < age(user_object.dob);
193             END IF;
194
195             IF current_mp.usr_age_upper_bound IS NOT NULL THEN
196                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_upper_bound > age(user_object.dob);
197             END IF;
198
199
200             -- everything was undefined or matched
201             matchpoint = current_mp;
202
203             EXIT WHEN matchpoint.id IS NOT NULL;
204         END LOOP;
205
206         EXIT WHEN current_group.parent IS NULL OR matchpoint.id IS NOT NULL;
207
208         SELECT INTO current_group * FROM permission.grp_tree WHERE id = current_group.parent;
209     END LOOP;
210
211     RETURN matchpoint;
212 END;
213 $func$ LANGUAGE plpgsql;
214
215
216 CREATE TYPE action.matrix_test_result AS ( success BOOL, matchpoint INT, fail_part TEXT );
217 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$
218 DECLARE
219     user_object        actor.usr%ROWTYPE;
220     standing_penalty    config.standing_penalty%ROWTYPE;
221     item_object        asset.copy%ROWTYPE;
222     item_status_object    config.copy_status%ROWTYPE;
223     item_location_object    asset.copy_location%ROWTYPE;
224     result            action.matrix_test_result;
225     circ_test        config.circ_matrix_matchpoint%ROWTYPE;
226     out_by_circ_mod        config.circ_matrix_circ_mod_test%ROWTYPE;
227     penalty_type         TEXT;
228     tmp_grp         INT;
229     items_out        INT;
230     context_org_list        INT[];
231     done            BOOL := FALSE;
232 BEGIN
233     result.success := TRUE;
234
235     -- Fail if the user is BARRED
236     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
237
238     -- Fail if we couldn't find a set of tests
239     IF user_object.id IS NULL THEN
240         result.fail_part := 'no_user';
241         result.success := FALSE;
242         done := TRUE;
243         RETURN NEXT result;
244         RETURN;
245     END IF;
246
247     IF user_object.barred IS TRUE THEN
248         result.fail_part := 'actor.usr.barred';
249         result.success := FALSE;
250         done := TRUE;
251         RETURN NEXT result;
252     END IF;
253
254     -- Fail if the item can't circulate
255     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
256     IF item_object.circulate IS FALSE THEN
257         result.fail_part := 'asset.copy.circulate';
258         result.success := FALSE;
259         done := TRUE;
260         RETURN NEXT result;
261     END IF;
262
263     -- Fail if the item isn't in a circulateable status on a non-renewal
264     IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN 
265         result.fail_part := 'asset.copy.status';
266         result.success := FALSE;
267         done := TRUE;
268         RETURN NEXT result;
269     ELSIF renewal AND item_object.status <> 1 THEN
270         result.fail_part := 'asset.copy.status';
271         result.success := FALSE;
272         done := TRUE;
273         RETURN NEXT result;
274     END IF;
275
276     -- Fail if the item can't circulate because of the shelving location
277     SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
278     IF item_location_object.circulate IS FALSE THEN
279         result.fail_part := 'asset.copy_location.circulate';
280         result.success := FALSE;
281         done := TRUE;
282         RETURN NEXT result;
283     END IF;
284
285     SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, match_item, match_user, renewal);
286     result.matchpoint := circ_test.id;
287
288     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( circ_test.org_unit );
289
290     -- Fail if we couldn't find a set of tests
291     IF result.matchpoint IS NULL THEN
292         result.fail_part := 'no_matchpoint';
293         result.success := FALSE;
294         done := TRUE;
295         RETURN NEXT result;
296     END IF;
297
298     -- Fail if the test is set to hard non-circulating
299     IF circ_test.circulate IS FALSE THEN
300         result.fail_part := 'config.circ_matrix_test.circulate';
301         result.success := FALSE;
302         done := TRUE;
303         RETURN NEXT result;
304     END IF;
305
306     IF renewal THEN
307         penalty_type = '%RENEW%';
308     ELSE
309         penalty_type = '%CIRC%';
310     END IF;
311
312     FOR standing_penalty IN
313         SELECT  DISTINCT csp.*
314           FROM  actor.usr_standing_penalty usp
315                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
316           WHERE usr = match_user
317                 AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
318                 AND csp.block_list LIKE penalty_type LOOP
319
320         result.fail_part := standing_penalty.name;
321         result.success := FALSE;
322         done := TRUE;
323         RETURN NEXT result;
324     END LOOP;
325
326     -- Fail if the user has too many items with specific circ_modifiers checked out
327     FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = circ_test.id LOOP
328         SELECT  INTO items_out COUNT(*)
329           FROM  action.circulation circ
330             JOIN asset.copy cp ON (cp.id = circ.target_copy)
331           WHERE circ.usr = match_user
332                AND circ_lib IN ( SELECT * FROM explode_array(context_org_list) )
333             AND circ.checkin_time IS NULL
334             AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
335             AND cp.circ_modifier = out_by_circ_mod.circ_mod;
336         IF items_out >= out_by_circ_mod.items_out THEN
337             result.fail_part := 'config.circ_matrix_circ_mod_test';
338             result.success := FALSE;
339             done := TRUE;
340             RETURN NEXT result;
341         END IF;
342     END LOOP;
343
344     -- If we passed everything, return the successful matchpoint id
345     IF NOT done THEN
346         RETURN NEXT result;
347     END IF;
348
349     RETURN;
350 END;
351 $func$ LANGUAGE plpgsql;
352
353 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
354     SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
355 $func$ LANGUAGE SQL;
356
357 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
358     SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
359 $func$ LANGUAGE SQL;
360
361
362 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
363 DECLARE
364     user_object         actor.usr%ROWTYPE;
365     new_sp_row          actor.usr_standing_penalty%ROWTYPE;
366     existing_sp_row     actor.usr_standing_penalty%ROWTYPE;
367     collections_fines   permission.grp_penalty_threshold%ROWTYPE;
368     max_fines           permission.grp_penalty_threshold%ROWTYPE;
369     max_overdue         permission.grp_penalty_threshold%ROWTYPE;
370     max_items_out       permission.grp_penalty_threshold%ROWTYPE;
371     tmp_grp             INT;
372     items_overdue       INT;
373     items_out           INT;
374     context_org_list    INT[];
375     current_fines        NUMERIC(8,2) := 0.0;
376     tmp_fines            NUMERIC(8,2);
377     tmp_groc            RECORD;
378     tmp_circ            RECORD;
379     tmp_org             actor.org_unit%ROWTYPE;
380 BEGIN
381     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
382
383     -- Max fines
384     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
385
386     -- Fail if the user has a high fine balance
387     LOOP
388         tmp_grp := user_object.profile;
389         LOOP
390             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
391
392             IF max_fines.threshold IS NULL THEN
393                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
394             ELSE
395                 EXIT;
396             END IF;
397
398             IF tmp_grp IS NULL THEN
399                 EXIT;
400             END IF;
401         END LOOP;
402
403         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
404             EXIT;
405         END IF;
406
407         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
408
409     END LOOP;
410
411     IF max_fines.threshold IS NOT NULL THEN
412
413         FOR existing_sp_row IN
414                 SELECT  *
415                   FROM  actor.usr_standing_penalty
416                   WHERE usr = match_user
417                         AND org_unit = max_fines.org_unit
418                         AND standing_penalty = 1
419                 LOOP
420             RETURN NEXT existing_sp_row;
421         END LOOP;
422
423         SELECT  SUM(f.balance_owed) INTO current_fines
424           FROM  money.materialized_billable_xact_summary f
425                 JOIN (
426                     SELECT  g.id
427                       FROM  money.grocery g
428                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (g.billing_location = fp.id)
429                       WHERE usr = match_user
430                             AND xact_finish IS NULL
431                                 UNION ALL
432                     SELECT  circ.id
433                       FROM  action.circulation circ
434                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (circ.circ_lib = fp.id)
435                       WHERE usr = match_user
436                             AND xact_finish IS NULL ) l USING (id);
437
438         IF current_fines >= max_fines.threshold THEN
439             new_sp_row.usr := match_user;
440             new_sp_row.org_unit := max_fines.org_unit;
441             new_sp_row.standing_penalty := 1;
442             RETURN NEXT new_sp_row;
443         END IF;
444     END IF;
445
446     -- Start over for max overdue
447     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
448
449     -- Fail if the user has too many overdue items
450     LOOP
451         tmp_grp := user_object.profile;
452         LOOP
453
454             SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
455
456             IF max_overdue.threshold IS NULL THEN
457                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
458             ELSE
459                 EXIT;
460             END IF;
461
462             IF tmp_grp IS NULL THEN
463                 EXIT;
464             END IF;
465         END LOOP;
466
467         IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
468             EXIT;
469         END IF;
470
471         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
472
473     END LOOP;
474
475     IF max_overdue.threshold IS NOT NULL THEN
476
477         FOR existing_sp_row IN
478                 SELECT  *
479                   FROM  actor.usr_standing_penalty
480                   WHERE usr = match_user
481                         AND org_unit = max_overdue.org_unit
482                         AND standing_penalty = 2
483                 LOOP
484             RETURN NEXT existing_sp_row;
485         END LOOP;
486
487         SELECT  INTO items_overdue COUNT(*)
488           FROM  action.circulation circ
489                 JOIN  actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
490           WHERE circ.usr = match_user
491             AND circ.checkin_time IS NULL
492             AND circ.due_date < NOW()
493             AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
494
495         IF items_overdue >= max_overdue.threshold::INT THEN
496             new_sp_row.usr := match_user;
497             new_sp_row.org_unit := max_overdue.org_unit;
498             new_sp_row.standing_penalty := 2;
499             RETURN NEXT new_sp_row;
500         END IF;
501     END IF;
502
503     -- Start over for max out
504     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
505
506     -- Fail if the user has too many checked out items
507     LOOP
508         tmp_grp := user_object.profile;
509         LOOP
510             SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
511
512             IF max_items_out.threshold IS NULL THEN
513                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
514             ELSE
515                 EXIT;
516             END IF;
517
518             IF tmp_grp IS NULL THEN
519                 EXIT;
520             END IF;
521         END LOOP;
522
523         IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
524             EXIT;
525         END IF;
526
527         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
528
529     END LOOP;
530
531
532     -- Fail if the user has too many items checked out
533     IF max_items_out.threshold IS NOT NULL THEN
534
535         FOR existing_sp_row IN
536                 SELECT  *
537                   FROM  actor.usr_standing_penalty
538                   WHERE usr = match_user
539                         AND org_unit = max_items_out.org_unit
540                         AND standing_penalty = 3
541                 LOOP
542             RETURN NEXT existing_sp_row;
543         END LOOP;
544
545         SELECT  INTO items_out COUNT(*)
546           FROM  action.circulation circ
547                 JOIN  actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
548           WHERE circ.usr = match_user
549                 AND circ.checkin_time IS NULL
550                 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL);
551
552            IF items_out >= max_items_out.threshold::INT THEN
553             new_sp_row.usr := match_user;
554             new_sp_row.org_unit := max_items_out.org_unit;
555             new_sp_row.standing_penalty := 3;
556             RETURN NEXT new_sp_row;
557            END IF;
558     END IF;
559
560     -- Start over for collections warning
561     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
562
563     -- Fail if the user has a collections-level fine balance
564     LOOP
565         tmp_grp := user_object.profile;
566         LOOP
567             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
568
569             IF max_fines.threshold IS NULL THEN
570                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
571             ELSE
572                 EXIT;
573             END IF;
574
575             IF tmp_grp IS NULL THEN
576                 EXIT;
577             END IF;
578         END LOOP;
579
580         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
581             EXIT;
582         END IF;
583
584         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
585
586     END LOOP;
587
588     IF max_fines.threshold IS NOT NULL THEN
589
590         FOR existing_sp_row IN
591                 SELECT  *
592                   FROM  actor.usr_standing_penalty
593                   WHERE usr = match_user
594                         AND org_unit = max_fines.org_unit
595                         AND standing_penalty = 1
596                 LOOP
597             RETURN NEXT existing_sp_row;
598         END LOOP;
599
600         SELECT  SUM(f.balance_owed) INTO current_fines
601           FROM  money.materialized_billable_xact_summary f
602                 JOIN (
603                     SELECT  g.id
604                       FROM  money.grocery g
605                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (g.billing_location = fp.id)
606                       WHERE usr = match_user
607                             AND xact_finish IS NULL
608                                 UNION ALL
609                     SELECT  circ.id
610                       FROM  action.circulation circ
611                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (circ.circ_lib = fp.id)
612                       WHERE usr = match_user
613                             AND xact_finish IS NULL ) l USING (id);
614
615         IF current_fines >= max_fines.threshold THEN
616             new_sp_row.usr := match_user;
617             new_sp_row.org_unit := max_fines.org_unit;
618             new_sp_row.standing_penalty := 1;
619             RETURN NEXT new_sp_row;
620         END IF;
621     END IF;
622
623
624     RETURN;
625 END;
626 $func$ LANGUAGE plpgsql;
627
628 COMMIT;
629