]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/100.circ_matrix.sql
b07aceb39e183e95ccfdfa8b88a3142d8b3e582d
[Evergreen.git] / Open-ILS / src / sql / Pg / 100.circ_matrix.sql
1
2 BEGIN;
3
4 -- NOTE: current config.item_type should get sip2_media_type and magnetic_media columns
5
6 -- New table needed to handle circ modifiers inside the DB.  Will still require
7 -- central admin.  The circ_modifier column on asset.copy will become an fkey to this table.
8 CREATE TABLE config.circ_modifier (
9         code                    TEXT    PRIMARY KEY,
10         name            TEXT    UNIQUE NOT NULL,
11         description         TEXT        NOT NULL,
12         sip2_media_type TEXT    NOT NULL,
13         magnetic_media  BOOL    NOT NULL DEFAULT TRUE
14 );
15
16 /*
17 -- for instance ...
18 INSERT INTO config.circ_modifier VALUES ( 'DVD', 'DVD', 'um ... DVDs', '001', FALSE );
19 INSERT INTO config.circ_modifier VALUES ( 'VIDEO', 'VIDEO', 'Tapes', '001', TRUE );
20 INSERT INTO config.circ_modifier VALUES ( 'BOOK', 'BOOK', 'Dead tree', '001', FALSE );
21 INSERT INTO config.circ_modifier VALUES ( 'CRAZY_ARL-ATH_SETTING', 'R2R_TAPE', 'reel2reel tape', '007', TRUE );
22 */
23
24 -- But, just to get us started, use this
25 /*
26
27 UPDATE asset.copy SET circ_modifier = UPPER(circ_modifier) WHERE circ_modifier IS NOT NULL AND circ_modifier <> '';
28 UPDATE asset.copy SET circ_modifier = NULL WHERE circ_modifier = '';
29
30 INSERT INTO config.circ_modifier (code, name, description, sip2_media_type )
31     SELECT DISTINCT
32             UPPER(circ_modifier),
33             UPPER(circ_modifier),
34             LOWER(circ_modifier),
35             '001'
36       FROM  asset.copy
37       WHERE circ_modifier IS NOT NULL;
38
39 */
40
41 -- add an fkey pointing to the new circ mod table
42 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;
43
44 -- config table to hold the vr_format names
45 CREATE TABLE config.videorecording_format_map (
46         code    TEXT    PRIMARY KEY,
47         value   TEXT    NOT NULL
48 );
49
50 INSERT INTO config.videorecording_format_map VALUES ('a','Beta');
51 INSERT INTO config.videorecording_format_map VALUES ('b','VHS');
52 INSERT INTO config.videorecording_format_map VALUES ('c','U-matic');
53 INSERT INTO config.videorecording_format_map VALUES ('d','EIAJ');
54 INSERT INTO config.videorecording_format_map VALUES ('e','Type C');
55 INSERT INTO config.videorecording_format_map VALUES ('f','Quadruplex');
56 INSERT INTO config.videorecording_format_map VALUES ('g','Laserdisc');
57 INSERT INTO config.videorecording_format_map VALUES ('h','CED');
58 INSERT INTO config.videorecording_format_map VALUES ('i','Betacam');
59 INSERT INTO config.videorecording_format_map VALUES ('j','Betacam SP');
60 INSERT INTO config.videorecording_format_map VALUES ('k','Super-VHS');
61 INSERT INTO config.videorecording_format_map VALUES ('m','M-II');
62 INSERT INTO config.videorecording_format_map VALUES ('o','D-2');
63 INSERT INTO config.videorecording_format_map VALUES ('p','8 mm.');
64 INSERT INTO config.videorecording_format_map VALUES ('q','Hi-8 mm.');
65 INSERT INTO config.videorecording_format_map VALUES ('u','Unknown');
66 INSERT INTO config.videorecording_format_map VALUES ('v','DVD');
67 INSERT INTO config.videorecording_format_map VALUES ('z','Other');
68
69
70
71 /**
72  **  Here we define the tables that make up the circ matrix.  Conceptually, this implements
73  **  the "sparse matrix" that everyone talks about, instead of using traditional rules logic.
74  **  Physically, we cut the matrix up into separate tables (almost 3rd normal form!) that handle
75  **  different portions of the matrix.  This wil simplify creation of the UI (I hope), and help the
76  **  developers focus on specific parts of the matrix.
77  **/
78
79
80 --
81 --                 ****** Which ruleset and tests to use *******
82 --
83 -- * Most specific range for org_unit and grp wins.
84 --
85 -- * circ_modifier match takes precidence over marc_type match, if circ_modifier is set here
86 --
87 -- * marc_type is first checked against the circ_as_type from the copy, then the item type from the marc record
88 --
89 -- * If neither circ_modifier nor marc_type is set (both are NULLABLE) then the entry defines the default
90 --   ruleset and tests for the OU + group (like BOOK in PINES)
91 --
92
93 CREATE TABLE config.circ_matrix_matchpoint (
94         id                      SERIAL  PRIMARY KEY,
95         active                  BOOL    NOT NULL DEFAULT TRUE,
96         org_unit                INT     NOT NULL REFERENCES actor.org_unit (id),        -- Set to the top OU for the matchpoint applicability range; we can use org_unit_prox to choose the "best"
97         grp                     INT     NOT NULL REFERENCES permission.grp_tree (id),   -- Set to the top applicable group from the group tree; will need decendents and prox functions for filtering
98         circ_modifier   TEXT    REFERENCES config.circ_modifier (code),
99         marc_type               TEXT    REFERENCES config.item_type_map (code),
100         marc_form               TEXT    REFERENCES config.item_form_map (code),
101         marc_vr_format  TEXT    REFERENCES config.videorecording_format_map (code),
102         ref_flag                BOOL,
103         usr_age_lower_bound     INTERVAL,
104         usr_age_upper_bound     INTERVAL,
105         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)
106 );
107
108 INSERT INTO config.circ_matrix_matchpoint (org_unit,grp) VALUES (1,1);
109
110
111 -- Tests to determine if circ can occur for this item at this location for this patron
112 CREATE TABLE config.circ_matrix_test (
113         matchpoint                      INT     PRIMARY KEY NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE,
114         circulate                       BOOL    NOT NULL DEFAULT TRUE,  -- Hard "can't circ" flag requiring an override
115         max_items_out           INT,                            -- Total current active circulations must be less than this, NULL means skip (always pass)
116         max_overdue                     INT,                                            -- Total overdue active circulations must be less than this, NULL means skip (always pass)
117         max_fines                       NUMERIC(8,2),                           -- Total fines owed must be less than this, NULL means skip (always pass)
118         script_test                     TEXT                                    -- filename or javascript source ??
119 );
120
121 -- Tests for max items out by circ_modifier
122 CREATE TABLE config.circ_matrix_circ_mod_test (
123     id          INT     PRIMARY KEY,
124         matchpoint  INT     NOT NULL REFERENCES config.circ_matrix_matchpoint (id) ON DELETE CASCADE,
125         items_out   INT     NOT NULL,                           -- Total current active circulations must be less than this, NULL means skip (always pass)
126     circ_mod    TEXT    NOT NULL REFERENCES config.circ_modifier (code) ON DELETE CASCADE ON UPDATE CASCADE -- circ_modifier type that the max out applies to
127 );
128
129
130
131 -- How to circ, assuming tests pass
132 CREATE TABLE config.circ_matrix_ruleset (
133         matchpoint              INT     PRIMARY KEY REFERENCES config.circ_matrix_matchpoint (id),
134         duration_rule           INT     NOT NULL REFERENCES config.rule_circ_duration (id),
135         recurring_fine_rule     INT     NOT NULL REFERENCES config.rule_recuring_fine (id),
136         max_fine_rule           INT     NOT NULL REFERENCES config.rule_max_fine (id)
137 );
138
139 INSERT INTO config.circ_matrix_ruleset (matchpoint,duration_rule,recurring_fine_rule,max_fine_rule) VALUES (1,11,1,1);
140
141 CREATE OR REPLACE FUNCTION action.find_circ_matrix_matchpoint( context_ou INT, match_item BIGINT, match_user INT ) RETURNS INT AS $func$
142 DECLARE
143         current_group   permission.grp_tree%ROWTYPE;
144         user_object     actor.usr%ROWTYPE;
145         item_object     asset.copy%ROWTYPE;
146         rec_descriptor  metabib.rec_descriptor%ROWTYPE;
147         current_mp      config.circ_matrix_matchpoint%ROWTYPE;
148         matchpoint      config.circ_matrix_matchpoint%ROWTYPE;
149 BEGIN
150         SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
151         SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
152         SELECT INTO rec_descriptor r.* FROM metabib.rec_descriptor r JOIN asset.call_number c USING (record) WHERE c.id = item_object.call_number;
153         SELECT INTO current_group * FROM permission.grp_tree WHERE id = user_object.profile;
154
155         LOOP 
156                 -- for each potential matchpoint for this ou and group ...
157                 FOR current_mp IN
158                         SELECT  m.*
159                           FROM  config.circ_matrix_matchpoint m
160                                 JOIN actor.org_unit_ancestors( context_ou ) d ON (m.org_unit = d.id)
161                                 LEFT JOIN actor.org_unit_proximity p ON (p.from_org = context_ou AND p.to_org = d.id)
162                           WHERE m.grp = current_group.id AND m.active
163                           ORDER BY      CASE WHEN p.prox                IS NULL THEN 999 ELSE p.prox END,
164                                         CASE WHEN m.circ_modifier       IS NOT NULL THEN 32 ELSE 0 END +
165                                         CASE WHEN m.marc_type           IS NOT NULL THEN 16 ELSE 0 END +
166                                         CASE WHEN m.marc_form           IS NOT NULL THEN 8 ELSE 0 END +
167                                         CASE WHEN m.marc_vr_format      IS NOT NULL THEN 4 ELSE 0 END +
168                                         CASE WHEN m.ref_flag            IS NOT NULL THEN 2 ELSE 0 END +
169                                         CASE WHEN m.usr_age_lower_bound IS NOT NULL THEN 0.5 ELSE 0 END +
170                                         CASE WHEN m.usr_age_upper_bound IS NOT NULL THEN 0.5 ELSE 0 END DESC LOOP
171
172                         IF current_mp.circ_modifier IS NOT NULL THEN
173                                 CONTINUE WHEN current_mp.circ_modifier <> item_object.circ_modifier;
174                         END IF;
175
176                         IF current_mp.marc_type IS NOT NULL THEN
177                                 IF item_object.circ_as_type IS NOT NULL THEN
178                                         CONTINUE WHEN current_mp.marc_type <> item_object.circ_as_type;
179                                 ELSE
180                                         CONTINUE WHEN current_mp.marc_type <> rec_descriptor.item_type;
181                                 END IF;
182                         END IF;
183
184                         IF current_mp.marc_form IS NOT NULL THEN
185                                 CONTINUE WHEN current_mp.marc_form <> rec_descriptor.item_form;
186                         END IF;
187
188                         IF current_mp.marc_vr_format IS NOT NULL THEN
189                                 CONTINUE WHEN current_mp.marc_vr_format <> rec_descriptor.vr_format;
190                         END IF;
191
192                         IF current_mp.ref_flag IS NOT NULL THEN
193                                 CONTINUE WHEN current_mp.ref_flag <> item_object.ref;
194                         END IF;
195
196                         IF current_mp.usr_age_lower_bound IS NOT NULL THEN
197                                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_lower_bound < age(user_object.dob);
198                         END IF;
199
200                         IF current_mp.usr_age_upper_bound IS NOT NULL THEN
201                                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_upper_bound > age(user_object.dob);
202                         END IF;
203
204
205                         -- everything was undefined or matched
206                         matchpoint = current_mp;
207
208                         EXIT WHEN matchpoint.id IS NOT NULL;
209                 END LOOP;
210
211                 EXIT WHEN current_group.parent IS NULL OR matchpoint.id IS NOT NULL;
212
213                 SELECT INTO current_group * FROM permission.grp_tree WHERE id = current_group.parent;
214         END LOOP;
215
216         RETURN matchpoint.id;
217 END;
218 $func$ LANGUAGE plpgsql;
219
220
221 CREATE TYPE action.matrix_test_result AS ( success BOOL, matchpoint INT, fail_part TEXT );
222 CREATE OR REPLACE FUNCTION action.item_user_circ_test( circ_ou INT, match_item BIGINT, match_user INT, renewal BOOL ) RETURNS SETOF action.matrix_test_result AS $func$
223 DECLARE
224         matchpoint_id           INT;
225         user_object             actor.usr%ROWTYPE;
226         item_object             asset.copy%ROWTYPE;
227         item_status_object      config.copy_status%ROWTYPE;
228         item_location_object    asset.copy_location%ROWTYPE;
229         result                  action.matrix_test_result;
230         circ_test               config.circ_matrix_test%ROWTYPE;
231         out_by_circ_mod         config.circ_matrix_circ_mod_test%ROWTYPE;
232         items_out               INT;
233         items_overdue           INT;
234         current_fines           NUMERIC(8,2) := 0.0;
235         tmp_fines               NUMERIC(8,2);
236         tmp_xact                BIGINT;
237         done                    BOOL := FALSE;
238 BEGIN
239         result.success := TRUE;
240
241         -- Fail if the user is BARRED
242         SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
243
244         -- Fail if we couldn't find a set of tests
245         IF user_object.id IS NULL THEN
246                 result.fail_part := 'no_user';
247                 result.success := FALSE;
248                 done := TRUE;
249                 RETURN NEXT result;
250                 RETURN;
251         END IF;
252
253         IF user_object.barred IS TRUE THEN
254                 result.fail_part := 'actor.usr.barred';
255                 result.success := FALSE;
256                 done := TRUE;
257                 RETURN NEXT result;
258         END IF;
259
260         -- Fail if the item can't circulate
261         SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
262         IF item_object.circulate IS FALSE THEN
263                 result.fail_part := 'asset.copy.circulate';
264                 result.success := FALSE;
265                 done := TRUE;
266                 RETURN NEXT result;
267         END IF;
268
269         -- Fail if the item isn't in a circulateable status on a non-renewal
270         IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN 
271                 result.fail_part := 'asset.copy.status';
272                 result.success := FALSE;
273                 done := TRUE;
274                 RETURN NEXT result;
275         ELSIF renewal AND item_object.status <> 1 THEN
276                 result.fail_part := 'asset.copy.status';
277                 result.success := FALSE;
278                 done := TRUE;
279                 RETURN NEXT result;
280         END IF;
281
282         -- Fail if the item can't circulate because of the shelving location
283         SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
284         IF item_location_object.circulate IS FALSE THEN
285                 result.fail_part := 'asset.copy_location.circulate';
286                 result.success := FALSE;
287                 done := TRUE;
288                 RETURN NEXT result;
289         END IF;
290
291         SELECT INTO matchpoint_id action.find_circ_matrix_matchpoint(circ_ou, match_item, match_user);
292         result.matchpoint := matchpoint_id;
293
294         -- Fail if we couldn't find a set of tests
295         IF result.matchpoint IS NULL THEN
296                 result.fail_part := 'no_matchpoint';
297                 result.success := FALSE;
298                 done := TRUE;
299                 RETURN NEXT result;
300         END IF;
301
302         -- Fail if the test is set to hard non-circulating
303         IF circ_test.circulate IS FALSE THEN
304                 result.fail_part := 'config.circ_matrix_test.circulate';
305                 result.success := FALSE;
306                 done := TRUE;
307                 RETURN NEXT result;
308         END IF;
309
310         -- Fail if the user has too many items checked out
311         IF circ_test.max_items_out IS NOT NULL THEN
312         SELECT  INTO items_out COUNT(*)
313           FROM  action.circulation
314           WHERE usr = match_user
315                 AND checkin_time IS NULL
316                 AND (stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE') OR stop_fines IS NULL);
317                 IF items_out >= circ_test.max_items_out THEN
318                         result.fail_part := 'config.circ_matrix_test.max_items_out';
319                         result.success := FALSE;
320                         done := TRUE;
321                         RETURN NEXT result;
322                 END IF;
323         END IF;
324
325         -- Fail if the user has too many items with specific circ_modifiers checked out
326         FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = matchpoint_id LOOP
327                 SELECT  INTO items_out COUNT(*)
328                   FROM  action.circulation circ
329                         JOIN asset.copy cp ON (cp.id = circ.target_copy)
330                   WHERE circ.usr = match_user
331                         AND circ.checkin_time IS NULL
332                         AND (circ.stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE') OR circ.stop_fines IS NULL)
333                         AND cp.circ_modifier = out_by_circ_mod.circ_mod;
334                 IF items_out >= out_by_circ_mod.items_out THEN
335                         result.fail_part := 'config.circ_matrix_circ_mod_test';
336                         result.success := FALSE;
337                         done := TRUE;
338                         RETURN NEXT result;
339                 END IF;
340         END LOOP;
341
342         -- Fail if the user has too many overdue items
343         IF circ_test.max_overdue IS NOT NULL THEN
344                 SELECT  INTO items_overdue COUNT(*)
345                   FROM  action.circulation
346                   WHERE usr = match_user
347                         AND checkin_time IS NULL
348                         AND due_date < NOW()
349                         AND (stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE') OR stop_fines IS NULL);
350                 IF items_overdue >= circ_test.max_overdue THEN
351                         result.fail_part := 'config.circ_matrix_test.max_overdue';
352                         result.success := FALSE;
353                         done := TRUE;
354                         RETURN NEXT result;
355                 END IF;
356         END IF;
357
358         -- Fail if the user has a high fine balance
359         IF circ_test.max_fines IS NOT NULL THEN
360                 FOR tmp_xact IN SELECT id FROM money.billable_xact WHERE usr = match_usr AND xact_finish IS NULL LOOP
361                         SELECT INTO tmp_fines SUM( amount ) FROM money.billing WHERE xact = tmp_xact AND NOT voided;
362                         current_fines = current_fines + COALESCE(tmp_fines, 0.0);
363                         SELECT INTO tmp_fines SUM( amount ) FROM money.payment WHERE xact = tmp_xact AND NOT voided;
364                         current_fines = current_fines - COALESCE(tmp_fines, 0.0);
365                 END LOOP;
366
367                 IF current_fines >= circ_test.max_overdue THEN
368                         result.fail_part := 'config.circ_matrix_test.max_fines';
369                         result.success := FALSE;
370                         RETURN NEXT result;
371                         done := TRUE;
372                 END IF;
373         END IF;
374
375         -- If we passed everything, return the successful matchpoint id
376         IF NOT done THEN
377                 RETURN NEXT result;
378         END IF;
379
380         RETURN;
381 END;
382 $func$ LANGUAGE plpgsql;
383
384 CREATE OR REPLACE FUNCTION action.item_user_circ_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
385         SELECT * FROM action.item_user_circ_test( $1, $2, $3, FALSE );
386 $func$ LANGUAGE SQL;
387
388 CREATE OR REPLACE FUNCTION action.item_user_renew_test( INT, BIGINT, INT ) RETURNS SETOF action.matrix_test_result AS $func$
389         SELECT * FROM action.item_user_circ_test( $1, $2, $3, TRUE );
390 $func$ LANGUAGE SQL;
391
392
393 COMMIT;
394