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