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