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