]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
allow groups of circ modifiers for the max-per-circ-mod test
[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 );
127
128 CREATE TABLE config.circ_matrix_circ_mod_test_map (
129     id      SERIAL  PRIMARY KEY,
130     circ_mod_test   INT NOT NULL REFERENCES config.circ_matrix_circ_mod_test (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
131     circ_mod        TEXT    NOT NULL REFERENCES config.circ_modifier (code) ON DELETE CASCADE ON UPDATE CASCADE  DEFERRABLE INITIALLY DEFERRED,
132     CONSTRAINT cm_once_per_test UNIQUE (circ_mod_test, circ_mod)
133 );
134
135 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$
136 DECLARE
137     current_group    permission.grp_tree%ROWTYPE;
138     user_object    actor.usr%ROWTYPE;
139     item_object    asset.copy%ROWTYPE;
140     rec_descriptor    metabib.rec_descriptor%ROWTYPE;
141     current_mp    config.circ_matrix_matchpoint%ROWTYPE;
142     matchpoint    config.circ_matrix_matchpoint%ROWTYPE;
143 BEGIN
144     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
145     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
146     SELECT INTO rec_descriptor r.* FROM metabib.rec_descriptor r JOIN asset.call_number c USING (record) WHERE c.id = item_object.call_number;
147     SELECT INTO current_group * FROM permission.grp_tree WHERE id = user_object.profile;
148
149     LOOP 
150         -- for each potential matchpoint for this ou and group ...
151         FOR current_mp IN
152             SELECT    m.*
153               FROM    config.circ_matrix_matchpoint m
154                 JOIN actor.org_unit_ancestors( context_ou ) d ON (m.org_unit = d.id)
155                 LEFT JOIN actor.org_unit_proximity p ON (p.from_org = context_ou AND p.to_org = d.id)
156               WHERE    m.grp = current_group.id AND m.active
157               ORDER BY    CASE WHEN p.prox        IS NULL THEN 999 ELSE p.prox END,
158                     CASE WHEN m.is_renewal = renewal        THEN 128 ELSE 0 END +
159                     CASE WHEN m.juvenile_flag    IS NOT NULL THEN 64 ELSE 0 END +
160                     CASE WHEN m.circ_modifier    IS NOT NULL THEN 32 ELSE 0 END +
161                     CASE WHEN m.marc_type        IS NOT NULL THEN 16 ELSE 0 END +
162                     CASE WHEN m.marc_form        IS NOT NULL THEN 8 ELSE 0 END +
163                     CASE WHEN m.marc_vr_format    IS NOT NULL THEN 4 ELSE 0 END +
164                     CASE WHEN m.ref_flag        IS NOT NULL THEN 2 ELSE 0 END +
165                     CASE WHEN m.usr_age_lower_bound    IS NOT NULL THEN 0.5 ELSE 0 END +
166                     CASE WHEN m.usr_age_upper_bound    IS NOT NULL THEN 0.5 ELSE 0 END DESC LOOP
167
168             IF current_mp.circ_modifier IS NOT NULL THEN
169                 CONTINUE WHEN current_mp.circ_modifier <> item_object.circ_modifier;
170             END IF;
171
172             IF current_mp.marc_type IS NOT NULL THEN
173                 IF item_object.circ_as_type IS NOT NULL THEN
174                     CONTINUE WHEN current_mp.marc_type <> item_object.circ_as_type;
175                 ELSE
176                     CONTINUE WHEN current_mp.marc_type <> rec_descriptor.item_type;
177                 END IF;
178             END IF;
179
180             IF current_mp.marc_form IS NOT NULL THEN
181                 CONTINUE WHEN current_mp.marc_form <> rec_descriptor.item_form;
182             END IF;
183
184             IF current_mp.marc_vr_format IS NOT NULL THEN
185                 CONTINUE WHEN current_mp.marc_vr_format <> rec_descriptor.vr_format;
186             END IF;
187
188             IF current_mp.ref_flag IS NOT NULL THEN
189                 CONTINUE WHEN current_mp.ref_flag <> item_object.ref;
190             END IF;
191
192             IF current_mp.juvenile_flag IS NOT NULL THEN
193                 CONTINUE WHEN current_mp.juvenile_flag <> user_object.juvenile;
194             END IF;
195
196             IF current_mp.usr_age_lower_bound IS NOT NULL THEN
197                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_lower_bound < age(user_object.dob);
198             END IF;
199
200             IF current_mp.usr_age_upper_bound IS NOT NULL THEN
201                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_upper_bound > age(user_object.dob);
202             END IF;
203
204
205             -- everything was undefined or matched
206             matchpoint = current_mp;
207
208             EXIT WHEN matchpoint.id IS NOT NULL;
209         END LOOP;
210
211         EXIT WHEN current_group.parent IS NULL OR matchpoint.id IS NOT NULL;
212
213         SELECT INTO current_group * FROM permission.grp_tree WHERE id = current_group.parent;
214     END LOOP;
215
216     RETURN matchpoint;
217 END;
218 $func$ LANGUAGE plpgsql;
219
220
221 CREATE TYPE action.matrix_test_result AS ( success BOOL, matchpoint INT, fail_part TEXT );
222 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$
223 DECLARE
224     user_object        actor.usr%ROWTYPE;
225     standing_penalty    config.standing_penalty%ROWTYPE;
226     item_object        asset.copy%ROWTYPE;
227     item_status_object    config.copy_status%ROWTYPE;
228     item_location_object    asset.copy_location%ROWTYPE;
229     result            action.matrix_test_result;
230     circ_test        config.circ_matrix_matchpoint%ROWTYPE;
231     out_by_circ_mod        config.circ_matrix_circ_mod_test%ROWTYPE;
232     circ_mod_map        config.circ_matrix_circ_mod_test_map%ROWTYPE;
233     penalty_type         TEXT;
234     tmp_grp         INT;
235     items_out        INT;
236     context_org_list        INT[];
237     done            BOOL := FALSE;
238 BEGIN
239     result.success := TRUE;
240
241     -- Fail if the user is BARRED
242     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
243
244     -- Fail if we couldn't find a set of tests
245     IF user_object.id IS NULL THEN
246         result.fail_part := 'no_user';
247         result.success := FALSE;
248         done := TRUE;
249         RETURN NEXT result;
250         RETURN;
251     END IF;
252
253     IF user_object.barred IS TRUE THEN
254         result.fail_part := 'actor.usr.barred';
255         result.success := FALSE;
256         done := TRUE;
257         RETURN NEXT result;
258     END IF;
259
260     -- Fail if the item can't circulate
261     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
262     IF item_object.circulate IS FALSE THEN
263         result.fail_part := 'asset.copy.circulate';
264         result.success := FALSE;
265         done := TRUE;
266         RETURN NEXT result;
267     END IF;
268
269     -- Fail if the item isn't in a circulateable status on a non-renewal
270     IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN 
271         result.fail_part := 'asset.copy.status';
272         result.success := FALSE;
273         done := TRUE;
274         RETURN NEXT result;
275     ELSIF renewal AND item_object.status <> 1 THEN
276         result.fail_part := 'asset.copy.status';
277         result.success := FALSE;
278         done := TRUE;
279         RETURN NEXT result;
280     END IF;
281
282     -- Fail if the item can't circulate because of the shelving location
283     SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
284     IF item_location_object.circulate IS FALSE THEN
285         result.fail_part := 'asset.copy_location.circulate';
286         result.success := FALSE;
287         done := TRUE;
288         RETURN NEXT result;
289     END IF;
290
291     SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, match_item, match_user, renewal);
292     result.matchpoint := circ_test.id;
293
294     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( circ_test.org_unit );
295
296     -- Fail if we couldn't find a set of tests
297     IF result.matchpoint IS NULL THEN
298         result.fail_part := 'no_matchpoint';
299         result.success := FALSE;
300         done := TRUE;
301         RETURN NEXT result;
302     END IF;
303
304     -- Fail if the test is set to hard non-circulating
305     IF circ_test.circulate IS FALSE THEN
306         result.fail_part := 'config.circ_matrix_test.circulate';
307         result.success := FALSE;
308         done := TRUE;
309         RETURN NEXT result;
310     END IF;
311
312     IF renewal THEN
313         penalty_type = '%RENEW%';
314     ELSE
315         penalty_type = '%CIRC%';
316     END IF;
317
318     FOR standing_penalty IN
319         SELECT  DISTINCT csp.*
320           FROM  actor.usr_standing_penalty usp
321                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
322           WHERE usr = match_user
323                 AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
324                 AND csp.block_list LIKE penalty_type LOOP
325
326         result.fail_part := standing_penalty.name;
327         result.success := FALSE;
328         done := TRUE;
329         RETURN NEXT result;
330     END LOOP;
331
332     -- Fail if the user has too many items with specific circ_modifiers checked out
333     FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = circ_test.id LOOP
334         SELECT  INTO items_out COUNT(*)
335           FROM  action.circulation circ
336             JOIN asset.copy cp ON (cp.id = circ.target_copy)
337           WHERE circ.usr = match_user
338                AND circ_lib IN ( SELECT * FROM explode_array(context_org_list) )
339             AND circ.checkin_time IS NULL
340             AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
341             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);
342         IF items_out >= out_by_circ_mod.items_out THEN
343             result.fail_part := 'config.circ_matrix_circ_mod_test';
344             result.success := FALSE;
345             done := TRUE;
346             RETURN NEXT result;
347         END IF;
348     END LOOP;
349
350     -- If we passed everything, return the successful matchpoint id
351     IF NOT done THEN
352         RETURN NEXT result;
353     END IF;
354
355     RETURN;
356 END;
357 $func$ LANGUAGE plpgsql;
358
359 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
360     SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
361 $func$ LANGUAGE SQL;
362
363 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
364     SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
365 $func$ LANGUAGE SQL;
366
367
368 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
369 DECLARE
370     user_object         actor.usr%ROWTYPE;
371     new_sp_row          actor.usr_standing_penalty%ROWTYPE;
372     existing_sp_row     actor.usr_standing_penalty%ROWTYPE;
373     collections_fines   permission.grp_penalty_threshold%ROWTYPE;
374     max_fines           permission.grp_penalty_threshold%ROWTYPE;
375     max_overdue         permission.grp_penalty_threshold%ROWTYPE;
376     max_items_out       permission.grp_penalty_threshold%ROWTYPE;
377     tmp_grp             INT;
378     items_overdue       INT;
379     items_out           INT;
380     context_org_list    INT[];
381     current_fines        NUMERIC(8,2) := 0.0;
382     tmp_fines            NUMERIC(8,2);
383     tmp_groc            RECORD;
384     tmp_circ            RECORD;
385     tmp_org             actor.org_unit%ROWTYPE;
386 BEGIN
387     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
388
389     -- Max fines
390     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
391
392     -- Fail if the user has a high fine balance
393     LOOP
394         tmp_grp := user_object.profile;
395         LOOP
396             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
397
398             IF max_fines.threshold IS NULL THEN
399                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
400             ELSE
401                 EXIT;
402             END IF;
403
404             IF tmp_grp IS NULL THEN
405                 EXIT;
406             END IF;
407         END LOOP;
408
409         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
410             EXIT;
411         END IF;
412
413         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
414
415     END LOOP;
416
417     IF max_fines.threshold IS NOT NULL THEN
418
419         FOR existing_sp_row IN
420                 SELECT  *
421                   FROM  actor.usr_standing_penalty
422                   WHERE usr = match_user
423                         AND org_unit = max_fines.org_unit
424                         AND standing_penalty = 1
425                 LOOP
426             RETURN NEXT existing_sp_row;
427         END LOOP;
428
429         SELECT  SUM(f.balance_owed) INTO current_fines
430           FROM  money.materialized_billable_xact_summary f
431                 JOIN (
432                     SELECT  g.id
433                       FROM  money.grocery g
434                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (g.billing_location = fp.id)
435                       WHERE usr = match_user
436                             AND xact_finish IS NULL
437                                 UNION ALL
438                     SELECT  circ.id
439                       FROM  action.circulation circ
440                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (circ.circ_lib = fp.id)
441                       WHERE usr = match_user
442                             AND xact_finish IS NULL ) l USING (id);
443
444         IF current_fines >= max_fines.threshold THEN
445             new_sp_row.usr := match_user;
446             new_sp_row.org_unit := max_fines.org_unit;
447             new_sp_row.standing_penalty := 1;
448             RETURN NEXT new_sp_row;
449         END IF;
450     END IF;
451
452     -- Start over for max overdue
453     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
454
455     -- Fail if the user has too many overdue items
456     LOOP
457         tmp_grp := user_object.profile;
458         LOOP
459
460             SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
461
462             IF max_overdue.threshold IS NULL THEN
463                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
464             ELSE
465                 EXIT;
466             END IF;
467
468             IF tmp_grp IS NULL THEN
469                 EXIT;
470             END IF;
471         END LOOP;
472
473         IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
474             EXIT;
475         END IF;
476
477         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
478
479     END LOOP;
480
481     IF max_overdue.threshold IS NOT NULL THEN
482
483         FOR existing_sp_row IN
484                 SELECT  *
485                   FROM  actor.usr_standing_penalty
486                   WHERE usr = match_user
487                         AND org_unit = max_overdue.org_unit
488                         AND standing_penalty = 2
489                 LOOP
490             RETURN NEXT existing_sp_row;
491         END LOOP;
492
493         SELECT  INTO items_overdue COUNT(*)
494           FROM  action.circulation circ
495                 JOIN  actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
496           WHERE circ.usr = match_user
497             AND circ.checkin_time IS NULL
498             AND circ.due_date < NOW()
499             AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
500
501         IF items_overdue >= max_overdue.threshold::INT THEN
502             new_sp_row.usr := match_user;
503             new_sp_row.org_unit := max_overdue.org_unit;
504             new_sp_row.standing_penalty := 2;
505             RETURN NEXT new_sp_row;
506         END IF;
507     END IF;
508
509     -- Start over for max out
510     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
511
512     -- Fail if the user has too many checked out items
513     LOOP
514         tmp_grp := user_object.profile;
515         LOOP
516             SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
517
518             IF max_items_out.threshold IS NULL THEN
519                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
520             ELSE
521                 EXIT;
522             END IF;
523
524             IF tmp_grp IS NULL THEN
525                 EXIT;
526             END IF;
527         END LOOP;
528
529         IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
530             EXIT;
531         END IF;
532
533         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
534
535     END LOOP;
536
537
538     -- Fail if the user has too many items checked out
539     IF max_items_out.threshold IS NOT NULL THEN
540
541         FOR existing_sp_row IN
542                 SELECT  *
543                   FROM  actor.usr_standing_penalty
544                   WHERE usr = match_user
545                         AND org_unit = max_items_out.org_unit
546                         AND standing_penalty = 3
547                 LOOP
548             RETURN NEXT existing_sp_row;
549         END LOOP;
550
551         SELECT  INTO items_out COUNT(*)
552           FROM  action.circulation circ
553                 JOIN  actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
554           WHERE circ.usr = match_user
555                 AND circ.checkin_time IS NULL
556                 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL);
557
558            IF items_out >= max_items_out.threshold::INT THEN
559             new_sp_row.usr := match_user;
560             new_sp_row.org_unit := max_items_out.org_unit;
561             new_sp_row.standing_penalty := 3;
562             RETURN NEXT new_sp_row;
563            END IF;
564     END IF;
565
566     -- Start over for collections warning
567     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
568
569     -- Fail if the user has a collections-level fine balance
570     LOOP
571         tmp_grp := user_object.profile;
572         LOOP
573             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
574
575             IF max_fines.threshold IS NULL THEN
576                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
577             ELSE
578                 EXIT;
579             END IF;
580
581             IF tmp_grp IS NULL THEN
582                 EXIT;
583             END IF;
584         END LOOP;
585
586         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
587             EXIT;
588         END IF;
589
590         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
591
592     END LOOP;
593
594     IF max_fines.threshold IS NOT NULL THEN
595
596         FOR existing_sp_row IN
597                 SELECT  *
598                   FROM  actor.usr_standing_penalty
599                   WHERE usr = match_user
600                         AND org_unit = max_fines.org_unit
601                         AND standing_penalty = 1
602                 LOOP
603             RETURN NEXT existing_sp_row;
604         END LOOP;
605
606         SELECT  SUM(f.balance_owed) INTO current_fines
607           FROM  money.materialized_billable_xact_summary f
608                 JOIN (
609                     SELECT  g.id
610                       FROM  money.grocery g
611                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (g.billing_location = fp.id)
612                       WHERE usr = match_user
613                             AND xact_finish IS NULL
614                                 UNION ALL
615                     SELECT  circ.id
616                       FROM  action.circulation circ
617                             JOIN  actor.org_unit_full_path( max_fines.org_unit ) fp ON (circ.circ_lib = fp.id)
618                       WHERE usr = match_user
619                             AND xact_finish IS NULL ) l USING (id);
620
621         IF current_fines >= max_fines.threshold THEN
622             new_sp_row.usr := match_user;
623             new_sp_row.org_unit := max_fines.org_unit;
624             new_sp_row.standing_penalty := 1;
625             RETURN NEXT new_sp_row;
626         END IF;
627     END IF;
628
629
630     RETURN;
631 END;
632 $func$ LANGUAGE plpgsql;
633
634 COMMIT;
635