]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
fixed perm check. also, if no count is provided, falls back to configured max
[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         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)
112 );
113
114
115 -- Tests to determine if circ can occur for this item at this location for this patron
116 CREATE TABLE config.circ_matrix_test (
117         matchpoint      INT     PRIMARY KEY NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
118         circulate       BOOL    NOT NULL DEFAULT TRUE,  -- Hard "can't circ" flag requiring an override
119         max_items_out   INT,                            -- Total current active circulations must be less than this, NULL means skip (always pass)
120         max_overdue         INT,                                        -- Total overdue active circulations must be less than this, NULL means skip (always pass)
121         max_fines       NUMERIC(8,2),                           -- Total fines owed must be less than this, NULL means skip (always pass)
122         org_unit                INT     REFERENCES actor.org_unit (id), -- Set to the top OU for the max-out applicability range
123         script_test     TEXT                                    -- filename or javascript source ??
124 );
125
126 -- Tests for max items out by circ_modifier
127 CREATE TABLE config.circ_matrix_circ_mod_test (
128         id          SERIAL     PRIMARY KEY,
129         matchpoint  INT     NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
130         items_out   INT     NOT NULL,                           -- Total current active circulations must be less than this, NULL means skip (always pass)
131         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
132 );
133
134
135 -- How to circ, assuming tests pass
136 CREATE TABLE config.circ_matrix_ruleset (
137         matchpoint              INT     PRIMARY KEY REFERENCES config.circ_matrix_matchpoint (id) DEFERRABLE INITIALLY DEFERRED,
138         duration_rule           INT     NOT NULL REFERENCES config.rule_circ_duration (id) DEFERRABLE INITIALLY DEFERRED,
139         recurring_fine_rule     INT     NOT NULL REFERENCES config.rule_recuring_fine (id) DEFERRABLE INITIALLY DEFERRED,
140         max_fine_rule           INT     NOT NULL REFERENCES config.rule_max_fine (id) DEFERRABLE INITIALLY DEFERRED
141 );
142
143 CREATE OR REPLACE FUNCTION action.find_circ_matrix_matchpoint( context_ou INT, match_item BIGINT, match_user INT, renewal BOOL ) RETURNS INT AS $func$
144 DECLARE
145         current_group   permission.grp_tree%ROWTYPE;
146         user_object     actor.usr%ROWTYPE;
147         item_object     asset.copy%ROWTYPE;
148         rec_descriptor  metabib.rec_descriptor%ROWTYPE;
149         current_mp      config.circ_matrix_matchpoint%ROWTYPE;
150         matchpoint      config.circ_matrix_matchpoint%ROWTYPE;
151 BEGIN
152         SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
153         SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
154         SELECT INTO rec_descriptor r.* FROM metabib.rec_descriptor r JOIN asset.call_number c USING (record) WHERE c.id = item_object.call_number;
155         SELECT INTO current_group * FROM permission.grp_tree WHERE id = user_object.profile;
156
157         LOOP 
158                 -- for each potential matchpoint for this ou and group ...
159                 FOR current_mp IN
160                         SELECT  m.*
161                           FROM  config.circ_matrix_matchpoint m
162                                 JOIN actor.org_unit_ancestors( context_ou ) d ON (m.org_unit = d.id)
163                                 LEFT JOIN actor.org_unit_proximity p ON (p.from_org = context_ou AND p.to_org = d.id)
164                           WHERE m.grp = current_group.id AND m.active
165                           ORDER BY      CASE WHEN p.prox                IS NULL THEN 999 ELSE p.prox END,
166                                         CASE WHEN m.is_renewal = renewal        THEN 64 ELSE 0 END +
167                                         CASE WHEN m.circ_modifier       IS NOT NULL THEN 32 ELSE 0 END +
168                                         CASE WHEN m.marc_type           IS NOT NULL THEN 16 ELSE 0 END +
169                                         CASE WHEN m.marc_form           IS NOT NULL THEN 8 ELSE 0 END +
170                                         CASE WHEN m.marc_vr_format      IS NOT NULL THEN 4 ELSE 0 END +
171                                         CASE WHEN m.ref_flag            IS NOT NULL THEN 2 ELSE 0 END +
172                                         CASE WHEN m.usr_age_lower_bound IS NOT NULL THEN 0.5 ELSE 0 END +
173                                         CASE WHEN m.usr_age_upper_bound IS NOT NULL THEN 0.5 ELSE 0 END DESC LOOP
174
175                         IF current_mp.circ_modifier IS NOT NULL THEN
176                                 CONTINUE WHEN current_mp.circ_modifier <> item_object.circ_modifier;
177                         END IF;
178
179                         IF current_mp.marc_type IS NOT NULL THEN
180                                 IF item_object.circ_as_type IS NOT NULL THEN
181                                         CONTINUE WHEN current_mp.marc_type <> item_object.circ_as_type;
182                                 ELSE
183                                         CONTINUE WHEN current_mp.marc_type <> rec_descriptor.item_type;
184                                 END IF;
185                         END IF;
186
187                         IF current_mp.marc_form IS NOT NULL THEN
188                                 CONTINUE WHEN current_mp.marc_form <> rec_descriptor.item_form;
189                         END IF;
190
191                         IF current_mp.marc_vr_format IS NOT NULL THEN
192                                 CONTINUE WHEN current_mp.marc_vr_format <> rec_descriptor.vr_format;
193                         END IF;
194
195                         IF current_mp.ref_flag IS NOT NULL THEN
196                                 CONTINUE WHEN current_mp.ref_flag <> item_object.ref;
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.id;
220 END;
221 $func$ LANGUAGE plpgsql;
222
223
224 CREATE TYPE action.matrix_test_result AS ( success BOOL, matchpoint INT, fail_part TEXT );
225 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$
226 DECLARE
227         matchpoint_id           INT;
228         user_object             actor.usr%ROWTYPE;
229         item_object             asset.copy%ROWTYPE;
230         item_status_object      config.copy_status%ROWTYPE;
231         item_location_object    asset.copy_location%ROWTYPE;
232         result                  action.matrix_test_result;
233         circ_test               config.circ_matrix_test%ROWTYPE;
234         out_by_circ_mod         config.circ_matrix_circ_mod_test%ROWTYPE;
235         items_out               INT;
236         items_overdue           INT;
237         overdue_orgs            INT[];
238         current_fines           NUMERIC(8,2) := 0.0;
239         tmp_fines               NUMERIC(8,2);
240         tmp_groc                RECORD;
241         tmp_circ                RECORD;
242         done                    BOOL := FALSE;
243 BEGIN
244         result.success := TRUE;
245
246         -- Fail if the user is BARRED
247         SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
248
249         -- Fail if we couldn't find a set of tests
250         IF user_object.id IS NULL THEN
251                 result.fail_part := 'no_user';
252                 result.success := FALSE;
253                 done := TRUE;
254                 RETURN NEXT result;
255                 RETURN;
256         END IF;
257
258         IF user_object.barred IS TRUE THEN
259                 result.fail_part := 'actor.usr.barred';
260                 result.success := FALSE;
261                 done := TRUE;
262                 RETURN NEXT result;
263         END IF;
264
265         -- Fail if the item can't circulate
266         SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
267         IF item_object.circulate IS FALSE THEN
268                 result.fail_part := 'asset.copy.circulate';
269                 result.success := FALSE;
270                 done := TRUE;
271                 RETURN NEXT result;
272         END IF;
273
274         -- Fail if the item isn't in a circulateable status on a non-renewal
275         IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN 
276                 result.fail_part := 'asset.copy.status';
277                 result.success := FALSE;
278                 done := TRUE;
279                 RETURN NEXT result;
280         ELSIF renewal AND item_object.status <> 1 THEN
281                 result.fail_part := 'asset.copy.status';
282                 result.success := FALSE;
283                 done := TRUE;
284                 RETURN NEXT result;
285         END IF;
286
287         -- Fail if the item can't circulate because of the shelving location
288         SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
289         IF item_location_object.circulate IS FALSE THEN
290                 result.fail_part := 'asset.copy_location.circulate';
291                 result.success := FALSE;
292                 done := TRUE;
293                 RETURN NEXT result;
294         END IF;
295
296         SELECT INTO matchpoint_id action.find_circ_matrix_matchpoint(circ_ou, match_item, match_user, renewal);
297         result.matchpoint := matchpoint_id;
298
299         SELECT INTO circ_test * from config.circ_matrix_test WHERE matchpoint = result.matchpoint;
300
301     IF circ_test.org_unit IS NOT NULL THEN
302         SELECT INTO overdue_orgs ARRAY_ACCUM(id) FROM actor.org_unit_descendants( circ_test.org_unit );
303     ELSE
304         SELECT INTO overdue_orgs ARRAY_ACCUM(id) FROM actor.org_unit;
305     END IF; 
306
307         -- Fail if we couldn't find a set of tests
308         IF result.matchpoint IS NULL THEN
309                 result.fail_part := 'no_matchpoint';
310                 result.success := FALSE;
311                 done := TRUE;
312                 RETURN NEXT result;
313         END IF;
314
315         -- Fail if the test is set to hard non-circulating
316         IF circ_test.circulate IS FALSE THEN
317                 result.fail_part := 'config.circ_matrix_test.circulate';
318                 result.success := FALSE;
319                 done := TRUE;
320                 RETURN NEXT result;
321         END IF;
322
323         -- Fail if the user has too many items checked out
324         IF circ_test.max_items_out IS NOT NULL THEN
325         SELECT  INTO items_out COUNT(*)
326           FROM  action.circulation
327           WHERE usr = match_user
328                 AND circ_lib IN ( SELECT * FROM explode_array(overdue_orgs) )
329                 AND checkin_time IS NULL
330                 AND (stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE') OR stop_fines IS NULL);
331                 IF items_out >= circ_test.max_items_out THEN
332                         result.fail_part := 'config.circ_matrix_test.max_items_out';
333                         result.success := FALSE;
334                         done := TRUE;
335                         RETURN NEXT result;
336                 END IF;
337         END IF;
338
339         -- Fail if the user has too many items with specific circ_modifiers checked out
340         FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = matchpoint_id LOOP
341                 SELECT  INTO items_out COUNT(*)
342                   FROM  action.circulation circ
343                         JOIN asset.copy cp ON (cp.id = circ.target_copy)
344                   WHERE circ.usr = match_user
345             AND circ_lib IN ( SELECT * FROM explode_array(overdue_orgs) )
346                         AND circ.checkin_time IS NULL
347                         AND (circ.stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE') OR circ.stop_fines IS NULL)
348                         AND cp.circ_modifier = out_by_circ_mod.circ_mod;
349                 IF items_out >= out_by_circ_mod.items_out THEN
350                         result.fail_part := 'config.circ_matrix_circ_mod_test';
351                         result.success := FALSE;
352                         done := TRUE;
353                         RETURN NEXT result;
354                 END IF;
355         END LOOP;
356
357         -- Fail if the user has too many overdue items
358         IF circ_test.max_overdue IS NOT NULL THEN
359                 SELECT  INTO items_overdue COUNT(*)
360                   FROM  action.circulation
361                   WHERE usr = match_user
362             AND circ_lib IN ( SELECT * FROM explode_array(overdue_orgs) )
363                         AND checkin_time IS NULL
364                         AND due_date < NOW()
365                         AND (stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE') OR stop_fines IS NULL);
366                 IF items_overdue >= circ_test.max_overdue THEN
367                         result.fail_part := 'config.circ_matrix_test.max_overdue';
368                         result.success := FALSE;
369                         done := TRUE;
370                         RETURN NEXT result;
371                 END IF;
372         END IF;
373
374         -- Fail if the user has a high fine balance
375         IF circ_test.max_fines IS NOT NULL THEN
376                 FOR tmp_groc IN SELECT * FROM money.grocery WHERE usr = match_usr AND xact_finish IS NULL AND billing_location IN ( SELECT * FROM explode_array(overdue_orgs) ) LOOP
377                         SELECT INTO tmp_fines SUM( amount ) FROM money.billing WHERE xact = tmp_groc.id AND NOT voided;
378                         current_fines = current_fines + COALESCE(tmp_fines, 0.0);
379                         SELECT INTO tmp_fines SUM( amount ) FROM money.payment WHERE xact = tmp_groc.id AND NOT voided;
380                         current_fines = current_fines - COALESCE(tmp_fines, 0.0);
381                 END LOOP;
382
383                 FOR tmp_circ IN SELECT * FROM action.circulation WHERE usr = match_usr AND xact_finish IS NULL AND circ_lib IN ( SELECT * FROM explode_array(overdue_orgs) ) LOOP
384                         SELECT INTO tmp_fines SUM( amount ) FROM money.billing WHERE xact = tmp_circ.id AND NOT voided;
385                         current_fines = current_fines + COALESCE(tmp_fines, 0.0);
386                         SELECT INTO tmp_fines SUM( amount ) FROM money.payment WHERE xact = tmp_circ.id AND NOT voided;
387                         current_fines = current_fines - COALESCE(tmp_fines, 0.0);
388                 END LOOP;
389
390                 IF current_fines >= circ_test.max_fines THEN
391                         result.fail_part := 'config.circ_matrix_test.max_fines';
392                         result.success := FALSE;
393                         RETURN NEXT result;
394                         done := TRUE;
395                 END IF;
396         END IF;
397
398         -- If we passed everything, return the successful matchpoint id
399         IF NOT done THEN
400                 RETURN NEXT result;
401         END IF;
402
403         RETURN;
404 END;
405 $func$ LANGUAGE plpgsql;
406
407 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
408         SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
409 $func$ LANGUAGE SQL;
410
411 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
412         SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
413 $func$ LANGUAGE SQL;
414
415
416 COMMIT;
417