]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/1.6.1-2.0-upgrade-db.sql
Add the asset.copy(create_date) index to the 1.6.1-2.0 update script
[Evergreen.git] / Open-ILS / src / sql / Pg / 1.6.1-2.0-upgrade-db.sql
1 -- Before starting the transaction: drop some constraints that
2 -- may or may not exist.
3
4 CREATE OR REPLACE FUNCTION oils_text_as_bytea (TEXT) RETURNS BYTEA AS $_$
5     SELECT CAST(REGEXP_REPLACE(UPPER($1), $$\\$$, $$\\\\$$, 'g') AS BYTEA);
6 $_$ LANGUAGE SQL IMMUTABLE;
7
8 DROP INDEX asset.asset_call_number_upper_label_id_owning_lib_idx;
9 CREATE INDEX asset_call_number_upper_label_id_owning_lib_idx ON asset.call_number (oils_text_as_bytea(label),id,owning_lib);
10
11 \qecho Before starting the transaction: drop some constraints.
12 \qecho If a DROP fails because the constraint doesn't exist, ignore the failure.
13
14 -- ARG! VIM! '
15
16 ALTER TABLE permission.grp_perm_map        DROP CONSTRAINT grp_perm_map_perm_fkey;
17 ALTER TABLE permission.usr_perm_map        DROP CONSTRAINT usr_perm_map_perm_fkey;
18 ALTER TABLE permission.usr_object_perm_map DROP CONSTRAINT usr_object_perm_map_perm_fkey;
19 ALTER TABLE booking.resource_type          DROP CONSTRAINT brt_name_or_record_once_per_owner;
20 ALTER TABLE booking.resource_type          DROP CONSTRAINT brt_name_once_per_owner;
21
22 \qecho Beginning the transaction now
23
24 BEGIN;
25
26 UPDATE biblio.record_entry SET marc = '<record xmlns="http://www.loc.gov/MARC21/slim"/>' WHERE id = -1;
27
28 -- Highest-numbered individual upgrade script incorporated herein:
29
30 INSERT INTO config.upgrade_log (version) VALUES ('0461');
31
32 -- Push the auri serial in case it's out of date
33 SELECT SETVAL('asset.uri'::TEXT, (SELECT MAX(id) + 1 FROM asset.uri));
34
35 -- Remove some uses of the connectby() function from the tablefunc contrib module
36 CREATE OR REPLACE FUNCTION actor.org_unit_descendants( INT, INT ) RETURNS SETOF actor.org_unit AS $$
37     WITH RECURSIVE descendant_depth AS (
38         SELECT  ou.id,
39                 ou.parent_ou,
40                 out.depth
41           FROM  actor.org_unit ou
42                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
43                 JOIN anscestor_depth ad ON (ad.id = ou.id)
44           WHERE ad.depth = $2
45             UNION ALL
46         SELECT  ou.id,
47                 ou.parent_ou,
48                 out.depth
49           FROM  actor.org_unit ou
50                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
51                 JOIN descendant_depth ot ON (ot.id = ou.parent_ou)
52     ), anscestor_depth AS (
53         SELECT  ou.id,
54                 ou.parent_ou,
55                 out.depth
56           FROM  actor.org_unit ou
57                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
58           WHERE ou.id = $1
59             UNION ALL
60         SELECT  ou.id,
61                 ou.parent_ou,
62                 out.depth
63           FROM  actor.org_unit ou
64                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
65                 JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
66     ) SELECT ou.* FROM actor.org_unit ou JOIN descendant_depth USING (id);
67 $$ LANGUAGE SQL;
68
69 CREATE OR REPLACE FUNCTION actor.org_unit_descendants( INT ) RETURNS SETOF actor.org_unit AS $$
70     WITH RECURSIVE descendant_depth AS (
71         SELECT  ou.id,
72                 ou.parent_ou,
73                 out.depth
74           FROM  actor.org_unit ou
75                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
76           WHERE ou.id = $1
77             UNION ALL
78         SELECT  ou.id,
79                 ou.parent_ou,
80                 out.depth
81           FROM  actor.org_unit ou
82                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
83                 JOIN descendant_depth ot ON (ot.id = ou.parent_ou)
84     ) SELECT ou.* FROM actor.org_unit ou JOIN descendant_depth USING (id);
85 $$ LANGUAGE SQL;
86
87 CREATE OR REPLACE FUNCTION actor.org_unit_ancestors( INT ) RETURNS SETOF actor.org_unit AS $$
88     WITH RECURSIVE anscestor_depth AS (
89         SELECT  ou.id,
90                 ou.parent_ou
91           FROM  actor.org_unit ou
92           WHERE ou.id = $1
93             UNION ALL
94         SELECT  ou.id,
95                 ou.parent_ou
96           FROM  actor.org_unit ou
97                 JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
98     ) SELECT ou.* FROM actor.org_unit ou JOIN anscestor_depth USING (id);
99 $$ LANGUAGE SQL;
100
101 -- Support merge template buckets
102 INSERT INTO container.biblio_record_entry_bucket_type (code,label) VALUES ('template_merge','Template Merge Container');
103
104 -- Recreate one of the constraints that we just dropped,
105 -- under a different name:
106
107 ALTER TABLE booking.resource_type
108         ADD CONSTRAINT brt_name_and_record_once_per_owner UNIQUE(owner, name, record);
109
110 -- Now upgrade permission.perm_list.  This is fairly complicated.
111
112 -- Add ON UPDATE CASCADE to some foreign keys so that, when we renumber the
113 -- permissions, the dependents will follow and stay in sync:
114
115 ALTER TABLE permission.grp_perm_map ADD CONSTRAINT grp_perm_map_perm_fkey FOREIGN KEY (perm)
116     REFERENCES permission.perm_list (id) ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED;
117
118 ALTER TABLE permission.usr_perm_map ADD CONSTRAINT usr_perm_map_perm_fkey FOREIGN KEY (perm)
119     REFERENCES permission.perm_list (id) ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED;
120
121 ALTER TABLE permission.usr_object_perm_map ADD CONSTRAINT usr_object_perm_map_perm_fkey FOREIGN KEY (perm)
122     REFERENCES permission.perm_list (id) ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED;
123
124 UPDATE permission.perm_list
125     SET code = 'UPDATE_ORG_UNIT_SETTING.credit.payments.allow'
126     WHERE code = 'UPDATE_ORG_UNIT_SETTING.global.credit.allow';
127
128 -- The following UPDATES were originally in an individual upgrade script, but should
129 -- no longer be necessary now that the foreign key has an ON UPDATE CASCADE clause.
130 -- We retain the UPDATES here, commented out, as historical relics.
131
132 -- UPDATE permission.grp_perm_map SET perm = perm + 1000 WHERE perm NOT IN ( SELECT id FROM permission.perm_list );
133 -- UPDATE permission.usr_perm_map SET perm = perm + 1000 WHERE perm NOT IN ( SELECT id FROM permission.perm_list );
134
135 -- Spelling correction
136 UPDATE permission.perm_list SET code = 'ADMIN_RECURRING_FINE_RULE' WHERE code = 'ADMIN_RECURING_FINE_RULE';
137
138 -- Now we engage in a Great Renumbering of the permissions in permission.perm_list,
139 -- in order to clean up accumulated cruft.
140
141 -- The first step is to establish some triggers so that, when we change the id of a permission,
142 -- the associated translations are updated accordingly.
143
144 CREATE OR REPLACE FUNCTION oils_i18n_update_apply(old_ident TEXT, new_ident TEXT, hint TEXT) RETURNS VOID AS $_$
145 BEGIN
146
147     EXECUTE $$
148         UPDATE  config.i18n_core
149           SET   identity_value = $$ || quote_literal( new_ident ) || $$ 
150           WHERE fq_field LIKE '$$ || hint || $$.%' 
151                 AND identity_value = $$ || quote_literal( old_ident ) || $$;$$;
152
153     RETURN;
154
155 END;
156 $_$ LANGUAGE PLPGSQL;
157
158 CREATE OR REPLACE FUNCTION oils_i18n_id_tracking(/* hint */) RETURNS TRIGGER AS $_$
159 BEGIN
160     PERFORM oils_i18n_update_apply( OLD.id::TEXT, NEW.id::TEXT, TG_ARGV[0]::TEXT );
161     RETURN NEW;
162 END;
163 $_$ LANGUAGE PLPGSQL;
164
165 CREATE OR REPLACE FUNCTION oils_i18n_code_tracking(/* hint */) RETURNS TRIGGER AS $_$
166 BEGIN
167     PERFORM oils_i18n_update_apply( OLD.code::TEXT, NEW.code::TEXT, TG_ARGV[0]::TEXT );
168     RETURN NEW;
169 END;
170 $_$ LANGUAGE PLPGSQL;
171
172
173 CREATE TRIGGER maintain_perm_i18n_tgr
174     AFTER UPDATE ON permission.perm_list
175     FOR EACH ROW EXECUTE PROCEDURE oils_i18n_id_tracking('ppl');
176
177 -- Next, create a new table as a convenience for sloshing data back and forth,
178 -- and for recording which permission went where.  It looks just like
179 -- permission.perm_list, but with two extra columns: one for the old id, and one to
180 -- distinguish between predefined permissions and non-predefined permissions.
181
182 -- This table is, in effect, a temporary table, because we can drop it once the
183 -- upgrade is complete.  It is not technically temporary as far as PostgreSQL is
184 -- concerned, because we don't want it to disappear at the end of the session.
185 -- We keep it around so that we have a map showing the old id and the new id for
186 -- each permission.  However there is no IDL entry for it, nor is it defined
187 -- in the base sql files.
188
189 CREATE TABLE permission.temp_perm (
190         id          INT        PRIMARY KEY,
191         code        TEXT       UNIQUE,
192         description TEXT,
193         old_id      INT,
194         predefined  BOOL       NOT NULL DEFAULT TRUE
195 );
196
197 -- Populate the temp table with a definitive set of predefined permissions,
198 -- hard-coding the ids.
199
200 -- The first set of permissions is derived from the database, as loaded in a
201 -- loaded 1.6.1 database, plus a few changes previously applied in this upgrade
202 -- script.  The second set is derived from the IDL -- permissions that are referenced
203 -- in <permacrud> elements but not defined in the database.
204
205 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( -1, 'EVERYTHING',
206      '' );
207 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 1, 'OPAC_LOGIN',
208      'Allow a user to log in to the OPAC' );
209 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 2, 'STAFF_LOGIN',
210      'Allow a user to log in to the staff client' );
211 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 3, 'MR_HOLDS',
212      'Allow a user to create a metarecord holds' );
213 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 4, 'TITLE_HOLDS',
214      'Allow a user to place a hold at the title level' );
215 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 5, 'VOLUME_HOLDS',
216      'Allow a user to place a volume level hold' );
217 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 6, 'COPY_HOLDS',
218      'Allow a user to place a hold on a specific copy' );
219 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 7, 'REQUEST_HOLDS',
220      'Allow a user to create holds for another user (if true, we still check to make sure they have permission to make the type of hold they are requesting, for example, COPY_HOLDS)' );
221 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 8, 'REQUEST_HOLDS_OVERRIDE',
222      '* no longer applicable' );
223 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 9, 'VIEW_HOLD',
224      'Allow a user to view another user''s holds' );
225 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 10, 'DELETE_HOLDS',
226      '* no longer applicable' );
227 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 11, 'UPDATE_HOLD',
228      'Allow a user to update another user''s hold' );
229 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 12, 'RENEW_CIRC',
230      'Allow a user to renew items' );
231 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 13, 'VIEW_USER_FINES_SUMMARY',
232      'Allow a user to view bill details' );
233 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 14, 'VIEW_USER_TRANSACTIONS',
234      'Allow a user to see another user''s grocery or circulation transactions in the Bills Interface; duplicate of VIEW_TRANSACTION' );
235 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 15, 'UPDATE_MARC',
236      'Allow a user to edit a MARC record' );
237 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 16, 'CREATE_MARC',
238      'Allow a user to create new MARC records' );
239 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 17, 'IMPORT_MARC',
240      'Allow a user to import a MARC record via the Z39.50 interface' );
241 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 18, 'CREATE_VOLUME',
242      'Allow a user to create a volume' );
243 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 19, 'UPDATE_VOLUME',
244      'Allow a user to edit volumes - needed for merging records. This is a duplicate of VOLUME_UPDATE; user must have both permissions at appropriate level to merge records.' );
245 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 20, 'DELETE_VOLUME',
246      'Allow a user to delete a volume' );
247 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 21, 'CREATE_COPY',
248      'Allow a user to create a new copy object' );
249 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 22, 'UPDATE_COPY',
250      'Allow a user to edit a copy' );
251 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 23, 'DELETE_COPY',
252      'Allow a user to delete a copy' );
253 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 24, 'RENEW_HOLD_OVERRIDE',
254      'Allow a user to continue to renew an item even if it is required for a hold' );
255 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 25, 'CREATE_USER',
256      'Allow a user to create another user' );
257 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 26, 'UPDATE_USER',
258      'Allow a user to edit a user''s record' );
259 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 27, 'DELETE_USER',
260      'Allow a user to mark a user as deleted' );
261 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 28, 'VIEW_USER',
262      'Allow a user to view another user''s Patron Record' );
263 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 29, 'COPY_CHECKIN',
264      'Allow a user to check in a copy' );
265 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 30, 'CREATE_TRANSIT',
266      'Allow a user to place an item in transit' );
267 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 31, 'VIEW_PERMISSION',
268      'Allow a user to view user permissions within the user permissions editor' );
269 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 32, 'CHECKIN_BYPASS_HOLD_FULFILL',
270      '* no longer applicable' );
271 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 33, 'CREATE_PAYMENT',
272      'Allow a user to record payments in the Billing Interface' );
273 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 34, 'SET_CIRC_LOST',
274      'Allow a user to mark an item as ''lost''' );
275 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 35, 'SET_CIRC_MISSING',
276      'Allow a user to mark an item as ''missing''' );
277 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 36, 'SET_CIRC_CLAIMS_RETURNED',
278      'Allow a user to mark an item as ''claims returned''' );
279 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 37, 'CREATE_TRANSACTION',
280      'Allow a user to create a new billable transaction' );
281 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 38, 'VIEW_TRANSACTION',
282      'Allow a user may view another user''s transactions' );
283 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 39, 'CREATE_BILL',
284      'Allow a user to create a new bill on a transaction' );
285 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 40, 'VIEW_CONTAINER',
286      'Allow a user to view another user''s containers (buckets)' );
287 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 41, 'CREATE_CONTAINER',
288      'Allow a user to create a new container for another user' );
289 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 42, 'UPDATE_ORG_UNIT',
290      'Allow a user to change the settings for an organization unit' );
291 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 43, 'VIEW_CIRCULATIONS',
292      'Allow a user to see what another user has checked out' );
293 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 44, 'DELETE_CONTAINER',
294      'Allow a user to delete another user''s container' );
295 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 45, 'CREATE_CONTAINER_ITEM',
296      'Allow a user to create a container item for another user' );
297 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 46, 'CREATE_USER_GROUP_LINK',
298      'Allow a user to add other users to permission groups' );
299 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 47, 'REMOVE_USER_GROUP_LINK',
300      'Allow a user to remove other users from permission groups' );
301 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 48, 'VIEW_PERM_GROUPS',
302      'Allow a user to view other users'' permission groups' );
303 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 49, 'VIEW_PERMIT_CHECKOUT',
304      'Allow a user to determine whether another user can check out an item' );
305 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 50, 'UPDATE_BATCH_COPY',
306      'Allow a user to edit copies in batch' );
307 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 51, 'CREATE_PATRON_STAT_CAT',
308      'User may create a new patron statistical category' );
309 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 52, 'CREATE_COPY_STAT_CAT',
310      'User may create a copy statistical category' );
311 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 53, 'CREATE_PATRON_STAT_CAT_ENTRY',
312      'User may create an entry in a patron statistical category' );
313 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 54, 'CREATE_COPY_STAT_CAT_ENTRY',
314      'User may create an entry in a copy statistical category' );
315 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 55, 'UPDATE_PATRON_STAT_CAT',
316      'User may update a patron statistical category' );
317 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 56, 'UPDATE_COPY_STAT_CAT',
318      'User may update a copy statistical category' );
319 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 57, 'UPDATE_PATRON_STAT_CAT_ENTRY',
320      'User may update an entry in a patron statistical category' );
321 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 58, 'UPDATE_COPY_STAT_CAT_ENTRY',
322      'User may update an entry in a copy statistical category' );
323 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 59, 'CREATE_PATRON_STAT_CAT_ENTRY_MAP',
324      'User may link another user to an entry in a statistical category' );
325 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 60, 'CREATE_COPY_STAT_CAT_ENTRY_MAP',
326      'User may link a copy to an entry in a statistical category' );
327 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 61, 'DELETE_PATRON_STAT_CAT',
328      'User may delete a patron statistical category' );
329 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 62, 'DELETE_COPY_STAT_CAT',
330      'User may delete a copy statistical category' );
331 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 63, 'DELETE_PATRON_STAT_CAT_ENTRY',
332      'User may delete an entry from a patron statistical category' );
333 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 64, 'DELETE_COPY_STAT_CAT_ENTRY',
334      'User may delete an entry from a copy statistical category' );
335 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 65, 'DELETE_PATRON_STAT_CAT_ENTRY_MAP',
336      'User may delete a patron statistical category entry map' );
337 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 66, 'DELETE_COPY_STAT_CAT_ENTRY_MAP',
338      'User may delete a copy statistical category entry map' );
339 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 67, 'CREATE_NON_CAT_TYPE',
340      'Allow a user to create a new non-cataloged item type' );
341 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 68, 'UPDATE_NON_CAT_TYPE',
342      'Allow a user to update a non-cataloged item type' );
343 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 69, 'CREATE_IN_HOUSE_USE',
344      'Allow a user to create a new in-house-use ' );
345 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 70, 'COPY_CHECKOUT',
346      'Allow a user to check out a copy' );
347 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 71, 'CREATE_COPY_LOCATION',
348      'Allow a user to create a new copy location' );
349 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 72, 'UPDATE_COPY_LOCATION',
350      'Allow a user to update a copy location' );
351 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 73, 'DELETE_COPY_LOCATION',
352      'Allow a user to delete a copy location' );
353 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 74, 'CREATE_COPY_TRANSIT',
354      'Allow a user to create a transit_copy object for transiting a copy' );
355 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 75, 'COPY_TRANSIT_RECEIVE',
356      'Allow a user to close out a transit on a copy' );
357 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 76, 'VIEW_HOLD_PERMIT',
358      'Allow a user to see if another user has permission to place a hold on a given copy' );
359 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 77, 'VIEW_COPY_CHECKOUT_HISTORY',
360      'Allow a user to view which users have checked out a given copy' );
361 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 78, 'REMOTE_Z3950_QUERY',
362      'Allow a user to perform Z39.50 queries against remote servers' );
363 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 79, 'REGISTER_WORKSTATION',
364      'Allow a user to register a new workstation' );
365 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 80, 'VIEW_COPY_NOTES',
366      'Allow a user to view all notes attached to a copy' );
367 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 81, 'VIEW_VOLUME_NOTES',
368      'Allow a user to view all notes attached to a volume' );
369 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 82, 'VIEW_TITLE_NOTES',
370      'Allow a user to view all notes attached to a title' );
371 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 83, 'CREATE_COPY_NOTE',
372      'Allow a user to create a new copy note' );
373 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 84, 'CREATE_VOLUME_NOTE',
374      'Allow a user to create a new volume note' );
375 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 85, 'CREATE_TITLE_NOTE',
376      'Allow a user to create a new title note' );
377 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 86, 'DELETE_COPY_NOTE',
378      'Allow a user to delete another user''s copy notes' );
379 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 87, 'DELETE_VOLUME_NOTE',
380      'Allow a user to delete another user''s volume note' );
381 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 88, 'DELETE_TITLE_NOTE',
382      'Allow a user to delete another user''s title note' );
383 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 89, 'UPDATE_CONTAINER',
384      'Allow a user to update another user''s container' );
385 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 90, 'CREATE_MY_CONTAINER',
386      'Allow a user to create a container for themselves' );
387 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 91, 'VIEW_HOLD_NOTIFICATION',
388      'Allow a user to view notifications attached to a hold' );
389 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 92, 'CREATE_HOLD_NOTIFICATION',
390      'Allow a user to create new hold notifications' );
391 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 93, 'UPDATE_ORG_SETTING',
392      'Allow a user to update an organization unit setting' );
393 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 94, 'OFFLINE_UPLOAD',
394      'Allow a user to upload an offline script' );
395 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 95, 'OFFLINE_VIEW',
396      'Allow a user to view uploaded offline script information' );
397 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 96, 'OFFLINE_EXECUTE',
398      'Allow a user to execute an offline script batch' );
399 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 97, 'CIRC_OVERRIDE_DUE_DATE',
400      'Allow a user to change the due date on an item to any date' );
401 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 98, 'CIRC_PERMIT_OVERRIDE',
402      'Allow a user to bypass the circulation permit call for check out' );
403 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 99, 'COPY_IS_REFERENCE.override',
404      'Allow a user to override the copy_is_reference event' );
405 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 100, 'VOID_BILLING',
406      'Allow a user to void a bill' );
407 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 101, 'CIRC_CLAIMS_RETURNED.override',
408      'Allow a user to check in or check out an item that has a status of ''claims returned''' );
409 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 102, 'COPY_BAD_STATUS.override',
410      'Allow a user to check out an item in a non-circulatable status' );
411 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 103, 'COPY_ALERT_MESSAGE.override',
412      'Allow a user to check in/out an item that has an alert message' );
413 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 104, 'COPY_STATUS_LOST.override',
414      'Allow a user to remove the lost status from a copy' );
415 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 105, 'COPY_STATUS_MISSING.override',
416      'Allow a user to change the missing status on a copy' );
417 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 106, 'ABORT_TRANSIT',
418      'Allow a user to abort a copy transit if the user is at the transit destination or source' );
419 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 107, 'ABORT_REMOTE_TRANSIT',
420      'Allow a user to abort a copy transit if the user is not at the transit source or dest' );
421 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 108, 'VIEW_ZIP_DATA',
422      'Allow a user to query the ZIP code data method' );
423 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 109, 'CANCEL_HOLDS',
424      'Allow a user to cancel holds' );
425 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 110, 'CREATE_DUPLICATE_HOLDS',
426      'Allow a user to create duplicate holds (two or more holds on the same title)' );
427 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 111, 'actor.org_unit.closed_date.delete',
428      'Allow a user to remove a closed date interval for a given location' );
429 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 112, 'actor.org_unit.closed_date.update',
430      'Allow a user to update a closed date interval for a given location' );
431 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 113, 'actor.org_unit.closed_date.create',
432      'Allow a user to create a new closed date for a location' );
433 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 114, 'DELETE_NON_CAT_TYPE',
434      'Allow a user to delete a non cataloged type' );
435 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 115, 'money.collections_tracker.create',
436      'Allow a user to put someone into collections' );
437 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 116, 'money.collections_tracker.delete',
438      'Allow a user to remove someone from collections' );
439 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 117, 'BAR_PATRON',
440      'Allow a user to bar a patron' );
441 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 118, 'UNBAR_PATRON',
442      'Allow a user to un-bar a patron' );
443 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 119, 'DELETE_WORKSTATION',
444      'Allow a user to remove an existing workstation so a new one can replace it' );
445 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 120, 'group_application.user',
446      'Allow a user to add/remove users to/from the "User" group' );
447 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 121, 'group_application.user.patron',
448      'Allow a user to add/remove users to/from the "Patron" group' );
449 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 122, 'group_application.user.staff',
450      'Allow a user to add/remove users to/from the "Staff" group' );
451 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 123, 'group_application.user.staff.circ',
452      'Allow a user to add/remove users to/from the "Circulator" group' );
453 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 124, 'group_application.user.staff.cat',
454      'Allow a user to add/remove users to/from the "Cataloger" group' );
455 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 125, 'group_application.user.staff.admin.global_admin',
456      'Allow a user to add/remove users to/from the "GlobalAdmin" group' );
457 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 126, 'group_application.user.staff.admin.local_admin',
458      'Allow a user to add/remove users to/from the "LocalAdmin" group' );
459 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 127, 'group_application.user.staff.admin.lib_manager',
460      'Allow a user to add/remove users to/from the "LibraryManager" group' );
461 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 128, 'group_application.user.staff.cat.cat1',
462      'Allow a user to add/remove users to/from the "Cat1" group' );
463 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 129, 'group_application.user.staff.supercat',
464      'Allow a user to add/remove users to/from the "Supercat" group' );
465 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 130, 'group_application.user.sip_client',
466      'Allow a user to add/remove users to/from the "SIP-Client" group' );
467 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 131, 'group_application.user.vendor',
468      'Allow a user to add/remove users to/from the "Vendor" group' );
469 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 132, 'ITEM_AGE_PROTECTED.override',
470      'Allow a user to place a hold on an age-protected item' );
471 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 133, 'MAX_RENEWALS_REACHED.override',
472      'Allow a user to renew an item past the maximum renewal count' );
473 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 134, 'PATRON_EXCEEDS_CHECKOUT_COUNT.override',
474      'Allow staff to override checkout count failure' );
475 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 135, 'PATRON_EXCEEDS_OVERDUE_COUNT.override',
476      'Allow staff to override overdue count failure' );
477 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 136, 'PATRON_EXCEEDS_FINES.override',
478      'Allow staff to override fine amount checkout failure' );
479 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 137, 'CIRC_EXCEEDS_COPY_RANGE.override',
480      'Allow staff to override circulation copy range failure' );
481 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 138, 'ITEM_ON_HOLDS_SHELF.override',
482      'Allow staff to override item on holds shelf failure' );
483 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 139, 'COPY_NOT_AVAILABLE.override',
484      'Allow staff to force checkout of Missing/Lost type items' );
485 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 140, 'HOLD_EXISTS.override',
486      'Allow a user to place multiple holds on a single title' );
487 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 141, 'RUN_REPORTS',
488      'Allow a user to run reports' );
489 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 142, 'SHARE_REPORT_FOLDER',
490      'Allow a user to share report his own folders' );
491 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 143, 'VIEW_REPORT_OUTPUT',
492      'Allow a user to view report output' );
493 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 144, 'COPY_CIRC_NOT_ALLOWED.override',
494      'Allow a user to checkout an item that is marked as non-circ' );
495 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 145, 'DELETE_CONTAINER_ITEM',
496      'Allow a user to delete an item out of another user''s container' );
497 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 146, 'ASSIGN_WORK_ORG_UNIT',
498      'Allow a staff member to define where another staff member has their permissions' );
499 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 147, 'CREATE_FUNDING_SOURCE',
500      'Allow a user to create a new funding source' );
501 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 148, 'DELETE_FUNDING_SOURCE',
502      'Allow a user to delete a funding source' );
503 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 149, 'VIEW_FUNDING_SOURCE',
504      'Allow a user to view a funding source' );
505 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 150, 'UPDATE_FUNDING_SOURCE',
506      'Allow a user to update a funding source' );
507 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 151, 'CREATE_FUND',
508      'Allow a user to create a new fund' );
509 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 152, 'DELETE_FUND',
510      'Allow a user to delete a fund' );
511 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 153, 'VIEW_FUND',
512      'Allow a user to view a fund' );
513 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 154, 'UPDATE_FUND',
514      'Allow a user to update a fund' );
515 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 155, 'CREATE_FUND_ALLOCATION',
516      'Allow a user to create a new fund allocation' );
517 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 156, 'DELETE_FUND_ALLOCATION',
518      'Allow a user to delete a fund allocation' );
519 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 157, 'VIEW_FUND_ALLOCATION',
520      'Allow a user to view a fund allocation' );
521 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 158, 'UPDATE_FUND_ALLOCATION',
522      'Allow a user to update a fund allocation' );
523 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 159, 'GENERAL_ACQ',
524      'Lowest level permission required to access the ACQ interface' );
525 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 160, 'CREATE_PROVIDER',
526      'Allow a user to create a new provider' );
527 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 161, 'DELETE_PROVIDER',
528      'Allow a user to delate a provider' );
529 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 162, 'VIEW_PROVIDER',
530      'Allow a user to view a provider' );
531 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 163, 'UPDATE_PROVIDER',
532      'Allow a user to update a provider' );
533 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 164, 'ADMIN_FUNDING_SOURCE',
534      'Allow a user to create/view/update/delete a funding source' );
535 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 165, 'ADMIN_FUND',
536      '(Deprecated) Allow a user to create/view/update/delete a fund' );
537 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 166, 'MANAGE_FUNDING_SOURCE',
538      'Allow a user to view/credit/debit a funding source' );
539 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 167, 'MANAGE_FUND',
540      'Allow a user to view/credit/debit a fund' );
541 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 168, 'CREATE_PICKLIST',
542      'Allows a user to create a picklist' );
543 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 169, 'ADMIN_PROVIDER',
544      'Allow a user to create/view/update/delete a provider' );
545 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 170, 'MANAGE_PROVIDER',
546      'Allow a user to view and purchase from a provider' );
547 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 171, 'VIEW_PICKLIST',
548      'Allow a user to view another users picklist' );
549 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 172, 'DELETE_RECORD',
550      'Allow a staff member to directly remove a bibliographic record' );
551 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 173, 'ADMIN_CURRENCY_TYPE',
552      'Allow a user to create/view/update/delete a currency_type' );
553 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 174, 'MARK_BAD_DEBT',
554      'Allow a user to mark a transaction as bad (unrecoverable) debt' );
555 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 175, 'VIEW_BILLING_TYPE',
556      'Allow a user to view billing types' );
557 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 176, 'MARK_ITEM_AVAILABLE',
558      'Allow a user to mark an item status as ''available''' );
559 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 177, 'MARK_ITEM_CHECKED_OUT',
560      'Allow a user to mark an item status as ''checked out''' );
561 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 178, 'MARK_ITEM_BINDERY',
562      'Allow a user to mark an item status as ''bindery''' );
563 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 179, 'MARK_ITEM_LOST',
564      'Allow a user to mark an item status as ''lost''' );
565 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 180, 'MARK_ITEM_MISSING',
566      'Allow a user to mark an item status as ''missing''' );
567 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 181, 'MARK_ITEM_IN_PROCESS',
568      'Allow a user to mark an item status as ''in process''' );
569 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 182, 'MARK_ITEM_IN_TRANSIT',
570      'Allow a user to mark an item status as ''in transit''' );
571 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 183, 'MARK_ITEM_RESHELVING',
572      'Allow a user to mark an item status as ''reshelving''' );
573 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 184, 'MARK_ITEM_ON_HOLDS_SHELF',
574      'Allow a user to mark an item status as ''on holds shelf''' );
575 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 185, 'MARK_ITEM_ON_ORDER',
576      'Allow a user to mark an item status as ''on order''' );
577 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 186, 'MARK_ITEM_ILL',
578      'Allow a user to mark an item status as ''inter-library loan''' );
579 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 187, 'group_application.user.staff.acq',
580      'Allows a user to add/remove/edit users in the "ACQ" group' );
581 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 188, 'CREATE_PURCHASE_ORDER',
582      'Allows a user to create a purchase order' );
583 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 189, 'VIEW_PURCHASE_ORDER',
584      'Allows a user to view a purchase order' );
585 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 190, 'IMPORT_ACQ_LINEITEM_BIB_RECORD',
586      'Allows a user to import a bib record from the acq staging area (on-order record) into the ILS bib data set' );
587 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 191, 'RECEIVE_PURCHASE_ORDER',
588      'Allows a user to mark a purchase order, lineitem, or individual copy as received' );
589 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 192, 'VIEW_ORG_SETTINGS',
590      'Allows a user to view all org settings at the specified level' );
591 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 193, 'CREATE_MFHD_RECORD',
592      'Allows a user to create a new MFHD record' );
593 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 194, 'UPDATE_MFHD_RECORD',
594      'Allows a user to update an MFHD record' );
595 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 195, 'DELETE_MFHD_RECORD',
596      'Allows a user to delete an MFHD record' );
597 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 196, 'ADMIN_ACQ_FUND',
598      'Allow a user to create/view/update/delete a fund' );
599 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 197, 'group_application.user.staff.acq_admin',
600      'Allows a user to add/remove/edit users in the "Acquisitions Administrators" group' );
601 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 198, 'SET_CIRC_CLAIMS_RETURNED.override',
602      'Allows staff to override the max claims returned value for a patron' );
603 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 199, 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
604      'Allows staff to manually change a patron''s claims returned count' );
605 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 200, 'UPDATE_BILL_NOTE',
606      'Allows staff to edit the note for a bill on a transaction' );
607 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 201, 'UPDATE_PAYMENT_NOTE',
608      'Allows staff to edit the note for a payment on a transaction' );
609 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 202, 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
610      'Allows staff to manually change a patron''s claims never checkout out count' );
611 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 203, 'ADMIN_COPY_LOCATION_ORDER',
612      'Allow a user to create/view/update/delete a copy location order' );
613 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 204, 'ASSIGN_GROUP_PERM',
614      '' );
615 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 205, 'CREATE_AUDIENCE',
616      '' );
617 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 206, 'CREATE_BIB_LEVEL',
618      '' );
619 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 207, 'CREATE_CIRC_DURATION',
620      '' );
621 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 208, 'CREATE_CIRC_MOD',
622      '' );
623 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 209, 'CREATE_COPY_STATUS',
624      '' );
625 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 210, 'CREATE_HOURS_OF_OPERATION',
626      '' );
627 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 211, 'CREATE_ITEM_FORM',
628      '' );
629 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 212, 'CREATE_ITEM_TYPE',
630      '' );
631 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 213, 'CREATE_LANGUAGE',
632      '' );
633 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 214, 'CREATE_LASSO',
634      '' );
635 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 215, 'CREATE_LASSO_MAP',
636      '' );
637 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 216, 'CREATE_LIT_FORM',
638      '' );
639 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 217, 'CREATE_METABIB_FIELD',
640      '' );
641 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 218, 'CREATE_NET_ACCESS_LEVEL',
642      '' );
643 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 219, 'CREATE_ORG_ADDRESS',
644      '' );
645 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 220, 'CREATE_ORG_TYPE',
646      '' );
647 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 221, 'CREATE_ORG_UNIT',
648      '' );
649 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 222, 'CREATE_ORG_UNIT_CLOSING',
650      '' );
651 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 223, 'CREATE_PERM',
652      '' );
653 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 224, 'CREATE_RELEVANCE_ADJUSTMENT',
654      '' );
655 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 225, 'CREATE_SURVEY',
656      '' );
657 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 226, 'CREATE_VR_FORMAT',
658      '' );
659 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 227, 'CREATE_XML_TRANSFORM',
660      '' );
661 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 228, 'DELETE_AUDIENCE',
662      '' );
663 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 229, 'DELETE_BIB_LEVEL',
664      '' );
665 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 230, 'DELETE_CIRC_DURATION',
666      '' );
667 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 231, 'DELETE_CIRC_MOD',
668      '' );
669 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 232, 'DELETE_COPY_STATUS',
670      '' );
671 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 233, 'DELETE_HOURS_OF_OPERATION',
672      '' );
673 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 234, 'DELETE_ITEM_FORM',
674      '' );
675 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 235, 'DELETE_ITEM_TYPE',
676      '' );
677 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 236, 'DELETE_LANGUAGE',
678      '' );
679 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 237, 'DELETE_LASSO',
680      '' );
681 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 238, 'DELETE_LASSO_MAP',
682      '' );
683 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 239, 'DELETE_LIT_FORM',
684      '' );
685 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 240, 'DELETE_METABIB_FIELD',
686      '' );
687 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 241, 'DELETE_NET_ACCESS_LEVEL',
688      '' );
689 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 242, 'DELETE_ORG_ADDRESS',
690      '' );
691 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 243, 'DELETE_ORG_TYPE',
692      '' );
693 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 244, 'DELETE_ORG_UNIT',
694      '' );
695 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 245, 'DELETE_ORG_UNIT_CLOSING',
696      '' );
697 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 246, 'DELETE_PERM',
698      '' );
699 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 247, 'DELETE_RELEVANCE_ADJUSTMENT',
700      '' );
701 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 248, 'DELETE_SURVEY',
702      '' );
703 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 249, 'DELETE_TRANSIT',
704      '' );
705 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 250, 'DELETE_VR_FORMAT',
706      '' );
707 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 251, 'DELETE_XML_TRANSFORM',
708      '' );
709 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 252, 'REMOVE_GROUP_PERM',
710      '' );
711 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 253, 'TRANSIT_COPY',
712      '' );
713 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 254, 'UPDATE_AUDIENCE',
714      '' );
715 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 255, 'UPDATE_BIB_LEVEL',
716      '' );
717 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 256, 'UPDATE_CIRC_DURATION',
718      '' );
719 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 257, 'UPDATE_CIRC_MOD',
720      '' );
721 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 258, 'UPDATE_COPY_NOTE',
722      '' );
723 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 259, 'UPDATE_COPY_STATUS',
724      '' );
725 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 260, 'UPDATE_GROUP_PERM',
726      '' );
727 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 261, 'UPDATE_HOURS_OF_OPERATION',
728      '' );
729 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 262, 'UPDATE_ITEM_FORM',
730      '' );
731 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 263, 'UPDATE_ITEM_TYPE',
732      '' );
733 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 264, 'UPDATE_LANGUAGE',
734      '' );
735 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 265, 'UPDATE_LASSO',
736      '' );
737 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 266, 'UPDATE_LASSO_MAP',
738      '' );
739 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 267, 'UPDATE_LIT_FORM',
740      '' );
741 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 268, 'UPDATE_METABIB_FIELD',
742      '' );
743 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 269, 'UPDATE_NET_ACCESS_LEVEL',
744      '' );
745 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 270, 'UPDATE_ORG_ADDRESS',
746      '' );
747 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 271, 'UPDATE_ORG_TYPE',
748      '' );
749 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 272, 'UPDATE_ORG_UNIT_CLOSING',
750      '' );
751 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 273, 'UPDATE_PERM',
752      '' );
753 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 274, 'UPDATE_RELEVANCE_ADJUSTMENT',
754      '' );
755 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 275, 'UPDATE_SURVEY',
756      '' );
757 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 276, 'UPDATE_TRANSIT',
758      '' );
759 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 277, 'UPDATE_VOLUME_NOTE',
760      '' );
761 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 278, 'UPDATE_VR_FORMAT',
762      '' );
763 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 279, 'UPDATE_XML_TRANSFORM',
764      '' );
765 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 280, 'MERGE_BIB_RECORDS',
766      '' );
767 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 281, 'UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF',
768      '' );
769 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 282, 'CREATE_ACQ_FUNDING_SOURCE',
770      '' );
771 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 283, 'CREATE_AUTHORITY_IMPORT_IMPORT_FIELD_DEF',
772      '' );
773 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 284, 'CREATE_AUTHORITY_IMPORT_QUEUE',
774      '' );
775 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 285, 'CREATE_AUTHORITY_RECORD_NOTE',
776      '' );
777 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 286, 'CREATE_BIB_IMPORT_FIELD_DEF',
778      '' );
779 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 287, 'CREATE_BIB_IMPORT_QUEUE',
780      '' );
781 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 288, 'CREATE_LOCALE',
782      '' );
783 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 289, 'CREATE_MARC_CODE',
784      '' );
785 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 290, 'CREATE_TRANSLATION',
786      '' );
787 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 291, 'DELETE_ACQ_FUNDING_SOURCE',
788      '' );
789 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 292, 'DELETE_AUTHORITY_IMPORT_IMPORT_FIELD_DEF',
790      '' );
791 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 293, 'DELETE_AUTHORITY_IMPORT_QUEUE',
792      '' );
793 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 294, 'DELETE_AUTHORITY_RECORD_NOTE',
794      '' );
795 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 295, 'DELETE_BIB_IMPORT_IMPORT_FIELD_DEF',
796      '' );
797 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 296, 'DELETE_BIB_IMPORT_QUEUE',
798      '' );
799 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 297, 'DELETE_LOCALE',
800      '' );
801 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 298, 'DELETE_MARC_CODE',
802      '' );
803 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 299, 'DELETE_TRANSLATION',
804      '' );
805 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 300, 'UPDATE_ACQ_FUNDING_SOURCE',
806      '' );
807 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 301, 'UPDATE_AUTHORITY_IMPORT_IMPORT_FIELD_DEF',
808      '' );
809 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 302, 'UPDATE_AUTHORITY_IMPORT_QUEUE',
810      '' );
811 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 303, 'UPDATE_AUTHORITY_RECORD_NOTE',
812      '' );
813 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 304, 'UPDATE_BIB_IMPORT_IMPORT_FIELD_DEF',
814      '' );
815 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 305, 'UPDATE_BIB_IMPORT_QUEUE',
816      '' );
817 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 306, 'UPDATE_LOCALE',
818      '' );
819 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 307, 'UPDATE_MARC_CODE',
820      '' );
821 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 308, 'UPDATE_TRANSLATION',
822      '' );
823 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 309, 'VIEW_ACQ_FUNDING_SOURCE',
824      '' );
825 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 310, 'VIEW_AUTHORITY_RECORD_NOTES',
826      '' );
827 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 311, 'CREATE_IMPORT_ITEM',
828      '' );
829 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 312, 'CREATE_IMPORT_ITEM_ATTR_DEF',
830      '' );
831 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 313, 'CREATE_IMPORT_TRASH_FIELD',
832      '' );
833 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 314, 'DELETE_IMPORT_ITEM',
834      '' );
835 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 315, 'DELETE_IMPORT_ITEM_ATTR_DEF',
836      '' );
837 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 316, 'DELETE_IMPORT_TRASH_FIELD',
838      '' );
839 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 317, 'UPDATE_IMPORT_ITEM',
840      '' );
841 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 318, 'UPDATE_IMPORT_ITEM_ATTR_DEF',
842      '' );
843 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 319, 'UPDATE_IMPORT_TRASH_FIELD',
844      '' );
845 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 320, 'UPDATE_ORG_UNIT_SETTING_ALL',
846      '' );
847 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 321, 'UPDATE_ORG_UNIT_SETTING.circ.lost_materials_processing_fee',
848      '' );
849 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 322, 'UPDATE_ORG_UNIT_SETTING.cat.default_item_price',
850      '' );
851 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 323, 'UPDATE_ORG_UNIT_SETTING.auth.opac_timeout',
852      '' );
853 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 324, 'UPDATE_ORG_UNIT_SETTING.auth.staff_timeout',
854      '' );
855 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 325, 'UPDATE_ORG_UNIT_SETTING.org.bounced_emails',
856      '' );
857 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 326, 'UPDATE_ORG_UNIT_SETTING.circ.hold_expire_alert_interval',
858      '' );
859 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 327, 'UPDATE_ORG_UNIT_SETTING.circ.hold_expire_interval',
860      '' );
861 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 328, 'UPDATE_ORG_UNIT_SETTING.credit.payments.allow',
862      '' );
863 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 329, 'UPDATE_ORG_UNIT_SETTING.circ.void_overdue_on_lost',
864      '' );
865 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 330, 'UPDATE_ORG_UNIT_SETTING.circ.hold_stalling.soft',
866      '' );
867 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 331, 'UPDATE_ORG_UNIT_SETTING.circ.hold_boundary.hard',
868      '' );
869 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 332, 'UPDATE_ORG_UNIT_SETTING.circ.hold_boundary.soft',
870      '' );
871 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 333, 'UPDATE_ORG_UNIT_SETTING.opac.barcode_regex',
872      '' );
873 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 334, 'UPDATE_ORG_UNIT_SETTING.global.password_regex',
874      '' );
875 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 335, 'UPDATE_ORG_UNIT_SETTING.circ.item_checkout_history.max',
876      '' );
877 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 336, 'UPDATE_ORG_UNIT_SETTING.circ.reshelving_complete.interval',
878      '' );
879 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 337, 'UPDATE_ORG_UNIT_SETTING.circ.selfcheck.patron_login_timeout',
880      '' );
881 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 338, 'UPDATE_ORG_UNIT_SETTING.circ.selfcheck.alert_on_checkout_event',
882      '' );
883 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 339, 'UPDATE_ORG_UNIT_SETTING.circ.selfcheck.require_patron_password',
884      '' );
885 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 340, 'UPDATE_ORG_UNIT_SETTING.global.juvenile_age_threshold',
886      '' );
887 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 341, 'UPDATE_ORG_UNIT_SETTING.cat.bib.keep_on_empty',
888      '' );
889 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 342, 'UPDATE_ORG_UNIT_SETTING.cat.bib.alert_on_empty',
890      '' );
891 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 343, 'UPDATE_ORG_UNIT_SETTING.patron.password.use_phone',
892      '' );
893 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 344, 'HOLD_ITEM_CHECKED_OUT.override',
894      'Allows a user to place a hold on an item that they already have checked out' );
895 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 345, 'ADMIN_ACQ_CANCEL_CAUSE',
896      'Allow a user to create/update/delete reasons for order cancellations' );
897 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 346, 'ACQ_XFER_MANUAL_DFUND_AMOUNT',
898      'Allow a user to transfer different amounts of money out of one fund and into another' );
899 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 347, 'OVERRIDE_HOLD_HAS_LOCAL_COPY',
900      'Allow a user to override the circ.holds.hold_has_copy_at.block setting' );
901 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 348, 'UPDATE_PICKUP_LIB_FROM_TRANSIT',
902      'Allow a user to change the pickup and transit destination for a captured hold item already in transit' );
903 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 349, 'COPY_NEEDED_FOR_HOLD.override',
904      'Allow a user to force renewal of an item that could fulfill a hold request' );
905 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 350, 'MERGE_AUTH_RECORDS',
906      'Allow a user to merge authority records together' );
907 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 351, 'ALLOW_ALT_TCN',
908      'Allows staff to import a record using an alternate TCN to avoid conflicts' );
909 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 352, 'ADMIN_TRIGGER_EVENT_DEF',
910      'Allow a user to administer trigger event definitions' );
911 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 353, 'ADMIN_TRIGGER_CLEANUP',
912      'Allow a user to create, delete, and update trigger cleanup entries' );
913 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 354, 'CREATE_TRIGGER_CLEANUP',
914      'Allow a user to create trigger cleanup entries' );
915 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 355, 'DELETE_TRIGGER_CLEANUP',
916      'Allow a user to delete trigger cleanup entries' );
917 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 356, 'UPDATE_TRIGGER_CLEANUP',
918      'Allow a user to update trigger cleanup entries' );
919 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 357, 'CREATE_TRIGGER_EVENT_DEF',
920      'Allow a user to create trigger event definitions' );
921 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 358, 'DELETE_TRIGGER_EVENT_DEF',
922      'Allow a user to delete trigger event definitions' );
923 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 359, 'UPDATE_TRIGGER_EVENT_DEF',
924      'Allow a user to update trigger event definitions' );
925 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 360, 'VIEW_TRIGGER_EVENT_DEF',
926      'Allow a user to view trigger event definitions' );
927 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 361, 'ADMIN_TRIGGER_HOOK',
928      'Allow a user to create, update, and delete trigger hooks' );
929 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 362, 'CREATE_TRIGGER_HOOK',
930      'Allow a user to create trigger hooks' );
931 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 363, 'DELETE_TRIGGER_HOOK',
932      'Allow a user to delete trigger hooks' );
933 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 364, 'UPDATE_TRIGGER_HOOK',
934      'Allow a user to update trigger hooks' );
935 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 365, 'ADMIN_TRIGGER_REACTOR',
936      'Allow a user to create, update, and delete trigger reactors' );
937 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 366, 'CREATE_TRIGGER_REACTOR',
938      'Allow a user to create trigger reactors' );
939 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 367, 'DELETE_TRIGGER_REACTOR',
940      'Allow a user to delete trigger reactors' );
941 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 368, 'UPDATE_TRIGGER_REACTOR',
942      'Allow a user to update trigger reactors' );
943 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 369, 'ADMIN_TRIGGER_TEMPLATE_OUTPUT',
944      'Allow a user to delete trigger template output' );
945 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 370, 'DELETE_TRIGGER_TEMPLATE_OUTPUT',
946      'Allow a user to delete trigger template output' );
947 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 371, 'ADMIN_TRIGGER_VALIDATOR',
948      'Allow a user to create, update, and delete trigger validators' );
949 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 372, 'CREATE_TRIGGER_VALIDATOR',
950      'Allow a user to create trigger validators' );
951 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 373, 'DELETE_TRIGGER_VALIDATOR',
952      'Allow a user to delete trigger validators' );
953 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 374, 'UPDATE_TRIGGER_VALIDATOR',
954      'Allow a user to update trigger validators' );
955 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 376, 'ADMIN_BOOKING_RESOURCE',
956      'Enables the user to create/update/delete booking resources' );
957 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 377, 'ADMIN_BOOKING_RESOURCE_TYPE',
958      'Enables the user to create/update/delete booking resource types' );
959 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 378, 'ADMIN_BOOKING_RESOURCE_ATTR',
960      'Enables the user to create/update/delete booking resource attributes' );
961 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 379, 'ADMIN_BOOKING_RESOURCE_ATTR_MAP',
962      'Enables the user to create/update/delete booking resource attribute maps' );
963 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 380, 'ADMIN_BOOKING_RESOURCE_ATTR_VALUE',
964      'Enables the user to create/update/delete booking resource attribute values' );
965 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 381, 'ADMIN_BOOKING_RESERVATION',
966      'Enables the user to create/update/delete booking reservations' );
967 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 382, 'ADMIN_BOOKING_RESERVATION_ATTR_VALUE_MAP',
968      'Enables the user to create/update/delete booking reservation attribute value maps' );
969 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 383, 'RETRIEVE_RESERVATION_PULL_LIST',
970      'Allows a user to retrieve a booking reservation pull list' );
971 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 384, 'CAPTURE_RESERVATION',
972      'Allows a user to capture booking reservations' );
973 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 385, 'UPDATE_RECORD',
974      '' );
975 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 386, 'UPDATE_ORG_UNIT_SETTING.circ.block_renews_for_holds',
976      '' );
977 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 387, 'MERGE_USERS',
978      'Allows user records to be merged' );
979 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 388, 'ISSUANCE_HOLDS',
980      'Allow a user to place holds on serials issuances' );
981 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 389, 'VIEW_CREDIT_CARD_PROCESSING',
982      'View org unit settings related to credit card processing' );
983 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 390, 'ADMIN_CREDIT_CARD_PROCESSING',
984      'Update org unit settings related to credit card processing' );
985 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 391, 'ADMIN_SERIAL_CAPTION_PATTERN',
986         'Create/update/delete serial caption and pattern objects' );
987 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 392, 'ADMIN_SERIAL_SUBSCRIPTION',
988         'Create/update/delete serial subscription objects' );
989 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 393, 'ADMIN_SERIAL_DISTRIBUTION',
990         'Create/update/delete serial distribution objects' );
991 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 394, 'ADMIN_SERIAL_STREAM',
992         'Create/update/delete serial stream objects' );
993 INSERT INTO permission.temp_perm ( id, code, description ) VALUES ( 395, 'RECEIVE_SERIAL',
994         'Receive serial items' );
995
996 -- Now for the permissions from the IDL.  We don't have descriptions for them.
997
998 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 396, 'ADMIN_ACQ_CLAIM' );
999 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 397, 'ADMIN_ACQ_CLAIM_EVENT_TYPE' );
1000 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 398, 'ADMIN_ACQ_CLAIM_TYPE' );
1001 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 399, 'ADMIN_ACQ_DISTRIB_FORMULA' );
1002 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 400, 'ADMIN_ACQ_FISCAL_YEAR' );
1003 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 401, 'ADMIN_ACQ_FUND_ALLOCATION_PERCENT' );
1004 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 402, 'ADMIN_ACQ_FUND_TAG' );
1005 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 403, 'ADMIN_ACQ_LINEITEM_ALERT_TEXT' );
1006 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 404, 'ADMIN_AGE_PROTECT_RULE' );
1007 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 405, 'ADMIN_ASSET_COPY_TEMPLATE' );
1008 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 406, 'ADMIN_BOOKING_RESERVATION_ATTR_MAP' );
1009 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 407, 'ADMIN_CIRC_MATRIX_MATCHPOINT' );
1010 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 408, 'ADMIN_CIRC_MOD' );
1011 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 409, 'ADMIN_CLAIM_POLICY' );
1012 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 410, 'ADMIN_CONFIG_REMOTE_ACCOUNT' );
1013 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 411, 'ADMIN_FIELD_DOC' );
1014 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 412, 'ADMIN_GLOBAL_FLAG' );
1015 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 413, 'ADMIN_GROUP_PENALTY_THRESHOLD' );
1016 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 414, 'ADMIN_HOLD_CANCEL_CAUSE' );
1017 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 415, 'ADMIN_HOLD_MATRIX_MATCHPOINT' );
1018 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 416, 'ADMIN_IDENT_TYPE' );
1019 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 417, 'ADMIN_IMPORT_ITEM_ATTR_DEF' );
1020 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 418, 'ADMIN_INDEX_NORMALIZER' );
1021 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 419, 'ADMIN_INVOICE' );
1022 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 420, 'ADMIN_INVOICE_METHOD' );
1023 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 421, 'ADMIN_INVOICE_PAYMENT_METHOD' );
1024 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 422, 'ADMIN_LINEITEM_MARC_ATTR_DEF' );
1025 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 423, 'ADMIN_MARC_CODE' );
1026 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 424, 'ADMIN_MAX_FINE_RULE' );
1027 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 425, 'ADMIN_MERGE_PROFILE' );
1028 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 426, 'ADMIN_ORG_UNIT_SETTING_TYPE' );
1029 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 427, 'ADMIN_RECURRING_FINE_RULE' );
1030 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 428, 'ADMIN_STANDING_PENALTY' );
1031 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 429, 'ADMIN_SURVEY' );
1032 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 430, 'ADMIN_USER_REQUEST_TYPE' );
1033 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 431, 'ADMIN_USER_SETTING_GROUP' );
1034 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 432, 'ADMIN_USER_SETTING_TYPE' );
1035 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 433, 'ADMIN_Z3950_SOURCE' );
1036 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 434, 'CREATE_BIB_BTYPE' );
1037 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 435, 'CREATE_BIBLIO_FINGERPRINT' );
1038 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 436, 'CREATE_BIB_SOURCE' );
1039 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 437, 'CREATE_BILLING_TYPE' );
1040 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 438, 'CREATE_CN_BTYPE' );
1041 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 439, 'CREATE_COPY_BTYPE' );
1042 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 440, 'CREATE_INVOICE' );
1043 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 441, 'CREATE_INVOICE_ITEM_TYPE' );
1044 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 442, 'CREATE_INVOICE_METHOD' );
1045 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 443, 'CREATE_MERGE_PROFILE' );
1046 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 444, 'CREATE_METABIB_CLASS' );
1047 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 445, 'CREATE_METABIB_SEARCH_ALIAS' );
1048 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 446, 'CREATE_USER_BTYPE' );
1049 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 447, 'DELETE_BIB_BTYPE' );
1050 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 448, 'DELETE_BIBLIO_FINGERPRINT' );
1051 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 449, 'DELETE_BIB_SOURCE' );
1052 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 450, 'DELETE_BILLING_TYPE' );
1053 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 451, 'DELETE_CN_BTYPE' );
1054 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 452, 'DELETE_COPY_BTYPE' );
1055 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 453, 'DELETE_INVOICE_ITEM_TYPE' );
1056 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 454, 'DELETE_INVOICE_METHOD' );
1057 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 455, 'DELETE_MERGE_PROFILE' );
1058 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 456, 'DELETE_METABIB_CLASS' );
1059 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 457, 'DELETE_METABIB_SEARCH_ALIAS' );
1060 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 458, 'DELETE_USER_BTYPE' );
1061 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 459, 'MANAGE_CLAIM' );
1062 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 460, 'UPDATE_BIB_BTYPE' );
1063 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 461, 'UPDATE_BIBLIO_FINGERPRINT' );
1064 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 462, 'UPDATE_BIB_SOURCE' );
1065 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 463, 'UPDATE_BILLING_TYPE' );
1066 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 464, 'UPDATE_CN_BTYPE' );
1067 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 465, 'UPDATE_COPY_BTYPE' );
1068 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 466, 'UPDATE_INVOICE_ITEM_TYPE' );
1069 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 467, 'UPDATE_INVOICE_METHOD' );
1070 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 468, 'UPDATE_MERGE_PROFILE' );
1071 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 469, 'UPDATE_METABIB_CLASS' );
1072 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 470, 'UPDATE_METABIB_SEARCH_ALIAS' );
1073 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 471, 'UPDATE_USER_BTYPE' );
1074 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 472, 'user_request.create' );
1075 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 473, 'user_request.delete' );
1076 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 474, 'user_request.update' );
1077 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 475, 'user_request.view' );
1078 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 476, 'VIEW_ACQ_FUND_ALLOCATION_PERCENT' );
1079 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 477, 'VIEW_CIRC_MATRIX_MATCHPOINT' );
1080 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 478, 'VIEW_CLAIM' );
1081 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 479, 'VIEW_GROUP_PENALTY_THRESHOLD' );
1082 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 480, 'VIEW_HOLD_MATRIX_MATCHPOINT' );
1083 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 481, 'VIEW_INVOICE' );
1084 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 482, 'VIEW_MERGE_PROFILE' );
1085 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 483, 'VIEW_SERIAL_SUBSCRIPTION' );
1086 INSERT INTO permission.temp_perm ( id, code ) VALUES ( 484, 'VIEW_STANDING_PENALTY' );
1087
1088 -- For every permission in the temp_perm table that has a matching
1089 -- permission in the real table: record the original id.
1090
1091 UPDATE permission.temp_perm AS tp
1092 SET old_id =
1093         (
1094                 SELECT id
1095                 FROM permission.perm_list AS ppl
1096                 WHERE ppl.code = tp.code
1097         )
1098 WHERE code IN ( SELECT code FROM permission.perm_list );
1099
1100 -- Start juggling ids.
1101
1102 -- If any permissions have negative ids (with the special exception of -1),
1103 -- we need to move them into the positive range in order to avoid duplicate
1104 -- key problems (since we are going to use the negative range as a temporary
1105 -- staging area).
1106
1107 -- First, move any predefined permissions that have negative ids (again with
1108 -- the special exception of -1).  Temporarily give them positive ids based on
1109 -- the sequence.
1110
1111 UPDATE permission.perm_list
1112 SET id = NEXTVAL('permission.perm_list_id_seq'::regclass)
1113 WHERE id < -1
1114   AND code IN (SELECT code FROM permission.temp_perm);
1115
1116 -- Identify any non-predefined permissions whose ids are either negative
1117 -- or within the range (0-1000) reserved for predefined permissions.
1118 -- Assign them ids above 1000, based on the sequence.  Record the new
1119 -- ids in the temp_perm table.
1120
1121 INSERT INTO permission.temp_perm ( id, code, description, old_id, predefined )
1122 (
1123         SELECT NEXTVAL('permission.perm_list_id_seq'::regclass),
1124                 code, description, id, false
1125         FROM permission.perm_list
1126         WHERE  ( id < -1 OR id BETWEEN 0 AND 1000 )
1127         AND code NOT IN (SELECT code FROM permission.temp_perm)
1128 );
1129
1130 -- Now update the ids of those non-predefined permissions, using the
1131 -- values assigned in the previous step.
1132
1133 UPDATE permission.perm_list AS ppl
1134 SET id = (
1135                 SELECT id
1136                 FROM permission.temp_perm AS tp
1137                 WHERE tp.code = ppl.code
1138         )
1139 WHERE id IN ( SELECT old_id FROM permission.temp_perm WHERE NOT predefined );
1140
1141 -- Now the negative ids have been eliminated, except for -1.  Move all the
1142 -- predefined permissions temporarily into the negative range.
1143
1144 UPDATE permission.perm_list
1145 SET id = -1 - id
1146 WHERE id <> -1
1147 AND code IN ( SELECT code from permission.temp_perm WHERE predefined );
1148
1149 -- Apply the final ids to the existing predefined permissions.
1150
1151 UPDATE permission.perm_list AS ppl
1152 SET id =
1153         (
1154                 SELECT id
1155                 FROM permission.temp_perm AS tp
1156                 WHERE tp.code = ppl.code
1157         )
1158 WHERE
1159         id <> -1
1160         AND ppl.code IN
1161         (
1162                 SELECT code from permission.temp_perm
1163                 WHERE predefined
1164                 AND old_id IS NOT NULL
1165         );
1166
1167 -- If there are any predefined permissions that don't exist yet in
1168 -- permission.perm_list, insert them now.
1169
1170 INSERT INTO permission.perm_list ( id, code, description )
1171 (
1172         SELECT id, code, description
1173         FROM permission.temp_perm
1174         WHERE old_id IS NULL
1175 );
1176
1177 -- Reset the sequence to the lowest feasible value.  This may or may not
1178 -- accomplish anything, but it will do no harm.
1179
1180 SELECT SETVAL('permission.perm_list_id_seq'::TEXT, GREATEST( 
1181         (SELECT MAX(id) FROM permission.perm_list), 1000 ));
1182
1183 -- If any permission lacks a description, use the code as a description.
1184 -- It's better than nothing.
1185
1186 UPDATE permission.perm_list
1187 SET description = code
1188 WHERE description IS NULL
1189    OR description = '';
1190
1191 -- Thus endeth the Great Renumbering.
1192
1193 -- Having massaged the permissions, massage the way they are assigned, by inserting
1194 -- rows into permission.grp_perm_map.  Some of these permissions may have already
1195 -- been assigned, so we insert the rows only if they aren't already there.
1196
1197 -- for backwards compat, give everyone the permission
1198 INSERT INTO permission.grp_perm_map (grp, perm, depth, grantable)
1199     SELECT 1, id, 0, false FROM permission.perm_list AS perm
1200         WHERE code = 'HOLD_ITEM_CHECKED_OUT.override'
1201                 AND NOT EXISTS (
1202                         SELECT 1
1203                         FROM permission.grp_perm_map AS map
1204                         WHERE
1205                                 grp = 1
1206                                 AND map.perm = perm.id
1207                 );
1208
1209 -- Add trigger administration permissions to the Local System Administrator group.
1210 INSERT INTO permission.grp_perm_map (grp, perm, depth, grantable)
1211     SELECT 10, id, 1, false FROM permission.perm_list AS perm
1212     WHERE (
1213                 perm.code LIKE 'ADMIN_TRIGGER%'
1214         OR perm.code LIKE 'CREATE_TRIGGER%'
1215         OR perm.code LIKE 'DELETE_TRIGGER%'
1216         OR perm.code LIKE 'UPDATE_TRIGGER%'
1217         ) AND NOT EXISTS (
1218                 SELECT 1
1219                 FROM permission.grp_perm_map AS map
1220                 WHERE
1221                         grp = 10
1222                         AND map.perm = perm.id
1223         );
1224
1225 -- View trigger permissions are required at a consortial level for initial setup
1226 -- (as before, only if the row doesn't already exist)
1227 INSERT INTO permission.grp_perm_map (grp, perm, depth, grantable)
1228     SELECT 10, id, 0, false FROM permission.perm_list AS perm
1229         WHERE code LIKE 'VIEW_TRIGGER%'
1230                 AND NOT EXISTS (
1231                         SELECT 1
1232                         FROM permission.grp_perm_map AS map
1233                         WHERE
1234                                 grp = 10
1235                                 AND map.perm = perm.id
1236                 );
1237
1238 -- Permission for merging auth records may already be defined,
1239 -- so add it only if it isn't there.
1240 INSERT INTO permission.grp_perm_map (grp, perm, depth, grantable)
1241     SELECT 4, id, 1, false FROM permission.perm_list AS perm
1242         WHERE code = 'MERGE_AUTH_RECORDS'
1243                 AND NOT EXISTS (
1244                         SELECT 1
1245                         FROM permission.grp_perm_map AS map
1246                         WHERE
1247                                 grp = 4
1248                                 AND map.perm = perm.id
1249                 );
1250
1251 -- Create a reference table as parent to both
1252 -- config.org_unit_setting_type and config_usr_setting_type
1253
1254 CREATE TABLE config.settings_group (
1255     name    TEXT PRIMARY KEY,
1256     label   TEXT UNIQUE NOT NULL -- I18N
1257 );
1258
1259 -- org_unit setting types
1260 CREATE TABLE config.org_unit_setting_type (
1261     name            TEXT    PRIMARY KEY,
1262     label           TEXT    UNIQUE NOT NULL,
1263     grp             TEXT    REFERENCES config.settings_group (name),
1264     description     TEXT,
1265     datatype        TEXT    NOT NULL DEFAULT 'string',
1266     fm_class        TEXT,
1267     view_perm       INT,
1268     update_perm     INT,
1269     --
1270     -- define valid datatypes
1271     --
1272     CONSTRAINT coust_valid_datatype CHECK ( datatype IN
1273     ( 'bool', 'integer', 'float', 'currency', 'interval',
1274       'date', 'string', 'object', 'array', 'link' ) ),
1275     --
1276     -- fm_class is meaningful only for 'link' datatype
1277     --
1278     CONSTRAINT coust_no_empty_link CHECK
1279     ( ( datatype =  'link' AND fm_class IS NOT NULL ) OR
1280       ( datatype <> 'link' AND fm_class IS NULL ) ),
1281         CONSTRAINT view_perm_fkey FOREIGN KEY (view_perm) REFERENCES permission.perm_list (id)
1282                 ON UPDATE CASCADE
1283                 ON DELETE RESTRICT
1284                 DEFERRABLE INITIALLY DEFERRED,
1285         CONSTRAINT update_perm_fkey FOREIGN KEY (update_perm) REFERENCES permission.perm_list (id)
1286                 ON UPDATE CASCADE
1287                 DEFERRABLE INITIALLY DEFERRED
1288 );
1289
1290 CREATE TABLE config.usr_setting_type (
1291
1292     name TEXT PRIMARY KEY,
1293     opac_visible BOOL NOT NULL DEFAULT FALSE,
1294     label TEXT UNIQUE NOT NULL,
1295     description TEXT,
1296     grp             TEXT    REFERENCES config.settings_group (name),
1297     datatype TEXT NOT NULL DEFAULT 'string',
1298     fm_class TEXT,
1299
1300     --
1301     -- define valid datatypes
1302     --
1303     CONSTRAINT coust_valid_datatype CHECK ( datatype IN
1304     ( 'bool', 'integer', 'float', 'currency', 'interval',
1305         'date', 'string', 'object', 'array', 'link' ) ),
1306
1307     --
1308     -- fm_class is meaningful only for 'link' datatype
1309     --
1310     CONSTRAINT coust_no_empty_link CHECK
1311     ( ( datatype = 'link' AND fm_class IS NOT NULL ) OR
1312         ( datatype <> 'link' AND fm_class IS NULL ) )
1313
1314 );
1315
1316 --------------------------------------
1317 -- Seed data for org_unit_setting_type
1318 --------------------------------------
1319
1320 INSERT into config.org_unit_setting_type
1321 ( name, label, description, datatype ) VALUES
1322
1323 ( 'auth.opac_timeout',
1324   'OPAC Inactivity Timeout (in seconds)',
1325   null,
1326   'integer' ),
1327
1328 ( 'auth.staff_timeout',
1329   'Staff Login Inactivity Timeout (in seconds)',
1330   null,
1331   'integer' ),
1332
1333 ( 'circ.lost_materials_processing_fee',
1334   'Lost Materials Processing Fee',
1335   null,
1336   'currency' ),
1337
1338 ( 'cat.default_item_price',
1339   'Default Item Price',
1340   null,
1341   'currency' ),
1342
1343 ( 'org.bounced_emails',
1344   'Sending email address for patron notices',
1345   null,
1346   'string' ),
1347
1348 ( 'circ.hold_expire_alert_interval',
1349   'Holds: Expire Alert Interval',
1350   'Amount of time before a hold expires at which point the patron should be alerted',
1351   'interval' ),
1352
1353 ( 'circ.hold_expire_interval',
1354   'Holds: Expire Interval',
1355   'Amount of time after a hold is placed before the hold expires.  Example "100 days"',
1356   'interval' ),
1357
1358 ( 'credit.payments.allow',
1359   'Allow Credit Card Payments',
1360   'If enabled, patrons will be able to pay fines accrued at this location via credit card',
1361   'bool' ),
1362
1363 ( 'global.default_locale',
1364   'Global Default Locale',
1365   null,
1366   'string' ),
1367
1368 ( 'circ.void_overdue_on_lost',
1369   'Void overdue fines when items are marked lost',
1370   null,
1371   'bool' ),
1372
1373 ( 'circ.hold_stalling.soft',
1374   'Holds: Soft stalling interval',
1375   'How long to wait before allowing remote items to be opportunistically captured for a hold.  Example "5 days"',
1376   'interval' ),
1377
1378 ( 'circ.hold_stalling_hard',
1379   'Holds: Hard stalling interval',
1380   '',
1381   'interval' ),
1382
1383 ( 'circ.hold_boundary.hard',
1384   'Holds: Hard boundary',
1385   null,
1386   'integer' ),
1387
1388 ( 'circ.hold_boundary.soft',
1389   'Holds: Soft boundary',
1390   null,
1391   'integer' ),
1392
1393 ( 'opac.barcode_regex',
1394   'Patron barcode format',
1395   'Regular expression defining the patron barcode format',
1396   'string' ),
1397
1398 ( 'global.password_regex',
1399   'Password format',
1400   'Regular expression defining the password format',
1401   'string' ),
1402
1403 ( 'circ.item_checkout_history.max',
1404   'Maximum previous checkouts displayed',
1405   'This is the maximum number of previous circulations the staff client will display when investigating item details',
1406   'integer' ),
1407
1408 ( 'circ.reshelving_complete.interval',
1409   'Change reshelving status interval',
1410   'Amount of time to wait before changing an item from "reshelving" status to "available".  Examples: "1 day", "6 hours"',
1411   'interval' ),
1412
1413 ( 'circ.holds.default_estimated_wait_interval',
1414   'Holds: Default Estimated Wait',
1415   'When predicting the amount of time a patron will be waiting for a hold to be fulfilled, this is the default estimated length of time to assume an item will be checked out.',
1416   'interval' ),
1417
1418 ( 'circ.holds.min_estimated_wait_interval',
1419   'Holds: Minimum Estimated Wait',
1420   'When predicting the amount of time a patron will be waiting for a hold to be fulfilled, this is the minimum estimated length of time to assume an item will be checked out.',
1421   'interval' ),
1422
1423 ( 'circ.selfcheck.patron_login_timeout',
1424   'Selfcheck: Patron Login Timeout (in seconds)',
1425   'Number of seconds of inactivity before the patron is logged out of the selfcheck interface',
1426   'integer' ),
1427
1428 ( 'circ.selfcheck.alert.popup',
1429   'Selfcheck: Pop-up alert for errors',
1430   'If true, checkout/renewal errors will cause a pop-up window in addition to the on-screen message',
1431   'bool' ),
1432
1433 ( 'circ.selfcheck.require_patron_password',
1434   'Selfcheck: Require patron password',
1435   'If true, patrons will be required to enter their password in addition to their username/barcode to log into the selfcheck interface',
1436   'bool' ),
1437
1438 ( 'global.juvenile_age_threshold',
1439   'Juvenile Age Threshold',
1440   'The age at which a user is no long considered a juvenile.  For example, "18 years".',
1441   'interval' ),
1442
1443 ( 'cat.bib.keep_on_empty',
1444   'Retain empty bib records',
1445   'Retain a bib record even when all attached copies are deleted',
1446   'bool' ),
1447
1448 ( 'cat.bib.alert_on_empty',
1449   'Alert on empty bib records',
1450   'Alert staff when the last copy for a record is being deleted',
1451   'bool' ),
1452
1453 ( 'patron.password.use_phone',
1454   'Patron: password from phone #',
1455   'Use the last 4 digits of the patrons phone number as the default password when creating new users',
1456   'bool' ),
1457
1458 ( 'circ.charge_on_damaged',
1459   'Charge item price when marked damaged',
1460   'Charge item price when marked damaged',
1461   'bool' ),
1462
1463 ( 'circ.charge_lost_on_zero',
1464   'Charge lost on zero',
1465   '',
1466   'bool' ),
1467
1468 ( 'circ.damaged_item_processing_fee',
1469   'Charge processing fee for damaged items',
1470   'Charge processing fee for damaged items',
1471   'currency' ),
1472
1473 ( 'circ.void_lost_on_checkin',
1474   'Circ: Void lost item billing when returned',
1475   'Void lost item billing when returned',
1476   'bool' ),
1477
1478 ( 'circ.max_accept_return_of_lost',
1479   'Circ: Void lost max interval',
1480   'Items that have been lost this long will not result in voided billings when returned.  E.g. ''6 months''',
1481   'interval' ),
1482
1483 ( 'circ.void_lost_proc_fee_on_checkin',
1484   'Circ: Void processing fee on lost item return',
1485   'Void processing fee when lost item returned',
1486   'bool' ),
1487
1488 ( 'circ.restore_overdue_on_lost_return',
1489   'Circ: Restore overdues on lost item return',
1490   'Restore overdue fines on lost item return',
1491   'bool' ),
1492
1493 ( 'circ.lost_immediately_available',
1494   'Circ: Lost items usable on checkin',
1495   'Lost items are usable on checkin instead of going ''home'' first',
1496   'bool' ),
1497
1498 ( 'circ.holds_fifo',
1499   'Holds: FIFO',
1500   'Force holds to a more strict First-In, First-Out capture',
1501   'bool' ),
1502
1503 ( 'opac.allow_pending_address',
1504   'OPAC: Allow pending addresses',
1505   'If enabled, patrons can create and edit existing addresses.  Addresses are kept in a pending state until staff approves the changes',
1506   'bool' ),
1507
1508 ( 'ui.circ.show_billing_tab_on_bills',
1509   'Show billing tab first when bills are present',
1510   'If enabled and a patron has outstanding bills and the alert page is not required, show the billing tab by default, instead of the checkout tab, when a patron is loaded',
1511   'bool' ),
1512
1513 ( 'ui.general.idle_timeout',
1514     'GUI: Idle timeout',
1515     'If you want staff client windows to be minimized after a certain amount of system idle time, set this to the number of seconds of idle time that you want to allow before minimizing (requires staff client restart).',
1516     'integer' ),
1517
1518 ( 'ui.circ.in_house_use.entry_cap',
1519   'GUI: Record In-House Use: Maximum # of uses allowed per entry.',
1520   'The # of uses entry in the Record In-House Use interface may not exceed the value of this setting.',
1521   'integer' ),
1522
1523 ( 'ui.circ.in_house_use.entry_warn',
1524   'GUI: Record In-House Use: # of uses threshold for Are You Sure? dialog.',
1525   'In the Record In-House Use interface, a submission attempt will warn if the # of uses field exceeds the value of this setting.',
1526   'integer' ),
1527
1528 ( 'acq.default_circ_modifier',
1529   'Default circulation modifier',
1530   null,
1531   'string' ),
1532
1533 ( 'acq.tmp_barcode_prefix',
1534   'Temporary barcode prefix',
1535   null,
1536   'string' ),
1537
1538 ( 'acq.tmp_callnumber_prefix',
1539   'Temporary call number prefix',
1540   null,
1541   'string' ),
1542
1543 ( 'ui.circ.patron_summary.horizontal',
1544   'Patron circulation summary is horizontal',
1545   null,
1546   'bool' ),
1547
1548 ( 'ui.staff.require_initials',
1549   oils_i18n_gettext('ui.staff.require_initials', 'GUI: Require staff initials for entry/edit of item/patron/penalty notes/messages.', 'coust', 'label'),
1550   oils_i18n_gettext('ui.staff.require_initials', 'Appends staff initials and edit date into note content.', 'coust', 'description'),
1551   'bool' ),
1552
1553 ( 'ui.general.button_bar',
1554   'Button bar',
1555   null,
1556   'bool' ),
1557
1558 ( 'circ.hold_shelf_status_delay',
1559   'Hold Shelf Status Delay',
1560   'The purpose is to provide an interval of time after an item goes into the on-holds-shelf status before it appears to patrons that it is actually on the holds shelf.  This gives staff time to process the item before it shows as ready-for-pickup.',
1561   'interval' ),
1562
1563 ( 'circ.patron_invalid_address_apply_penalty',
1564   'Invalid patron address penalty',
1565   'When set, if a patron address is set to invalid, a penalty is applied.',
1566   'bool' ),
1567
1568 ( 'circ.checkout_fills_related_hold',
1569   'Checkout Fills Related Hold',
1570   'When a patron checks out an item and they have no holds that directly target the item, the system will attempt to find a hold for the patron that could be fulfilled by the checked out item and fulfills it',
1571   'bool'),
1572
1573 ( 'circ.selfcheck.auto_override_checkout_events',
1574   'Selfcheck override events list',
1575   'List of checkout/renewal events that the selfcheck interface should automatically override instead instead of alerting and stopping the transaction',
1576   'array' ),
1577
1578 ( 'circ.staff_client.do_not_auto_attempt_print',
1579   'Disable Automatic Print Attempt Type List',
1580   'Disable automatic print attempts from staff client interfaces for the receipt types in this list.  Possible values: "Checkout", "Bill Pay", "Hold Slip", "Transit Slip", and "Hold/Transit Slip".  This is different from the Auto-Print checkbox in the pertinent interfaces in that it disables automatic print attempts altogether, rather than encouraging silent printing by suppressing the print dialog.  The Auto-Print checkbox in these interfaces have no effect on the behavior for this setting.  In the case of the Hold, Transit, and Hold/Transit slips, this also suppresses the alert dialogs that precede the print dialog (the ones that offer Print and Do Not Print as options).',
1581   'array' ),
1582
1583 ( 'ui.patron.default_inet_access_level',
1584   'Default level of patrons'' internet access',
1585   null,
1586   'integer' ),
1587
1588 ( 'circ.max_patron_claim_return_count',
1589     'Max Patron Claims Returned Count',
1590     'When this count is exceeded, a staff override is required to mark the item as claims returned',
1591     'integer' ),
1592
1593 ( 'circ.obscure_dob',
1594     'Obscure the Date of Birth field',
1595     'When true, the Date of Birth column in patron lists will default to Not Visible, and in the Patron Summary sidebar the value will display as <Hidden> unless the field label is clicked.',
1596     'bool' ),
1597
1598 ( 'circ.auto_hide_patron_summary',
1599     'GUI: Toggle off the patron summary sidebar after first view.',
1600     'When true, the patron summary sidebar will collapse after a new patron sub-interface is selected.',
1601     'bool' ),
1602
1603 ( 'credit.processor.default',
1604     'Credit card processing: Name default credit processor',
1605     'This can be "AuthorizeNet", "PayPal" (for the Website Payment Pro API), or "PayflowPro".',
1606     'string' ),
1607
1608 ( 'credit.processor.authorizenet.enabled',
1609     'Credit card processing: AuthorizeNet enabled',
1610     '',
1611     'bool' ),
1612
1613 ( 'credit.processor.authorizenet.login',
1614     'Credit card processing: AuthorizeNet login',
1615     '',
1616     'string' ),
1617
1618 ( 'credit.processor.authorizenet.password',
1619     'Credit card processing: AuthorizeNet password',
1620     '',
1621     'string' ),
1622
1623 ( 'credit.processor.authorizenet.server',
1624     'Credit card processing: AuthorizeNet server',
1625     'Required if using a developer/test account with AuthorizeNet',
1626     'string' ),
1627
1628 ( 'credit.processor.authorizenet.testmode',
1629     'Credit card processing: AuthorizeNet test mode',
1630     '',
1631     'bool' ),
1632
1633 ( 'credit.processor.paypal.enabled',
1634     'Credit card processing: PayPal enabled',
1635     '',
1636     'bool' ),
1637 ( 'credit.processor.paypal.login',
1638     'Credit card processing: PayPal login',
1639     '',
1640     'string' ),
1641 ( 'credit.processor.paypal.password',
1642     'Credit card processing: PayPal password',
1643     '',
1644     'string' ),
1645 ( 'credit.processor.paypal.signature',
1646     'Credit card processing: PayPal signature',
1647     '',
1648     'string' ),
1649 ( 'credit.processor.paypal.testmode',
1650     'Credit card processing: PayPal test mode',
1651     '',
1652     'bool' ),
1653
1654 ( 'ui.admin.work_log.max_entries',
1655     oils_i18n_gettext('ui.admin.work_log.max_entries', 'GUI: Work Log: Maximum Actions Logged', 'coust', 'label'),
1656     oils_i18n_gettext('ui.admin.work_log.max_entries', 'Maximum entries for "Most Recent Staff Actions" section of the Work Log interface.', 'coust', 'description'),
1657   'interval' ),
1658
1659 ( 'ui.admin.patron_log.max_entries',
1660     oils_i18n_gettext('ui.admin.patron_log.max_entries', 'GUI: Work Log: Maximum Patrons Logged', 'coust', 'label'),
1661     oils_i18n_gettext('ui.admin.patron_log.max_entries', 'Maximum entries for "Most Recently Affected Patrons..." section of the Work Log interface.', 'coust', 'description'),
1662   'interval' ),
1663
1664 ( 'lib.courier_code',
1665     oils_i18n_gettext('lib.courier_code', 'Courier Code', 'coust', 'label'),
1666     oils_i18n_gettext('lib.courier_code', 'Courier Code for the library.  Available in transit slip templates as the %courier_code% macro.', 'coust', 'description'),
1667     'string'),
1668
1669 ( 'circ.block_renews_for_holds',
1670     oils_i18n_gettext('circ.block_renews_for_holds', 'Holds: Block Renewal of Items Needed for Holds', 'coust', 'label'),
1671     oils_i18n_gettext('circ.block_renews_for_holds', 'When an item could fulfill a hold, do not allow the current patron to renew', 'coust', 'description'),
1672     'bool' ),
1673
1674 ( 'circ.password_reset_request_per_user_limit',
1675     oils_i18n_gettext('circ.password_reset_request_per_user_limit', 'Circulation: Maximum concurrently active self-serve password reset requests per user', 'coust', 'label'),
1676     oils_i18n_gettext('circ.password_reset_request_per_user_limit', 'When a user has more than this number of concurrently active self-serve password reset requests for their account, prevent the user from creating any new self-serve password reset requests until the number of active requests for the user drops back below this number.', 'coust', 'description'),
1677     'string'),
1678
1679 ( 'circ.password_reset_request_time_to_live',
1680     oils_i18n_gettext('circ.password_reset_request_time_to_live', 'Circulation: Self-serve password reset request time-to-live', 'coust', 'label'),
1681     oils_i18n_gettext('circ.password_reset_request_time_to_live', 'Length of time (in seconds) a self-serve password reset request should remain active.', 'coust', 'description'),
1682     'string'),
1683
1684 ( 'circ.password_reset_request_throttle',
1685     oils_i18n_gettext('circ.password_reset_request_throttle', 'Circulation: Maximum concurrently active self-serve password reset requests', 'coust', 'label'),
1686     oils_i18n_gettext('circ.password_reset_request_throttle', 'Prevent the creation of new self-serve password reset requests until the number of active requests drops back below this number.', 'coust', 'description'),
1687     'string')
1688 ;
1689
1690 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1691         'ui.circ.suppress_checkin_popups',
1692         oils_i18n_gettext(
1693             'ui.circ.suppress_checkin_popups', 
1694             'Circ: Suppress popup-dialogs during check-in.', 
1695             'coust', 
1696             'label'),
1697         oils_i18n_gettext(
1698             'ui.circ.suppress_checkin_popups', 
1699             'Circ: Suppress popup-dialogs during check-in.', 
1700             'coust', 
1701             'description'),
1702         'bool'
1703 );
1704
1705 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1706         'format.date',
1707         oils_i18n_gettext(
1708             'format.date',
1709             'GUI: Format Dates with this pattern.', 
1710             'coust', 
1711             'label'),
1712         oils_i18n_gettext(
1713             'format.date',
1714             'GUI: Format Dates with this pattern (examples: "yyyy-MM-dd" for "2010-04-26", "MMM d, yyyy" for "Apr 26, 2010")', 
1715             'coust', 
1716             'description'),
1717         'string'
1718 ), (
1719         'format.time',
1720         oils_i18n_gettext(
1721             'format.time',
1722             'GUI: Format Times with this pattern.', 
1723             'coust', 
1724             'label'),
1725         oils_i18n_gettext(
1726             'format.time',
1727             'GUI: Format Times with this pattern (examples: "h:m:s.SSS a z" for "2:07:20.666 PM Eastern Daylight Time", "HH:mm" for "14:07")', 
1728             'coust', 
1729             'description'),
1730         'string'
1731 );
1732
1733 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1734         'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel',
1735         oils_i18n_gettext(
1736             'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel',
1737             'CAT: Delete bib if all copies are deleted via Acquisitions lineitem cancellation.', 
1738             'coust', 
1739             'label'),
1740         oils_i18n_gettext(
1741             'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel',
1742             'CAT: Delete bib if all copies are deleted via Acquisitions lineitem cancellation.', 
1743             'coust', 
1744             'description'),
1745         'bool'
1746 );
1747
1748 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1749         'url.remote_column_settings',
1750         oils_i18n_gettext(
1751             'url.remote_column_settings',
1752             'GUI: URL for remote directory containing list column settings.', 
1753             'coust', 
1754             'label'),
1755         oils_i18n_gettext(
1756             'url.remote_column_settings',
1757             'GUI: URL for remote directory containing list column settings.  The format and naming convention for the files found in this directory match those in the local settings directory for a given workstation.  An administrator could create the desired settings locally and then copy all the tree_columns_for_* files to the remote directory.', 
1758             'coust', 
1759             'description'),
1760         'string'
1761 );
1762
1763 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1764         'gui.disable_local_save_columns',
1765         oils_i18n_gettext(
1766             'gui.disable_local_save_columns',
1767             'GUI: Disable the ability to save list column configurations locally.', 
1768             'coust', 
1769             'label'),
1770         oils_i18n_gettext(
1771             'gui.disable_local_save_columns',
1772             'GUI: Disable the ability to save list column configurations locally.  If set, columns may still be manipulated, however, the changes do not persist.  Also, existing local configurations are ignored if this setting is true.', 
1773             'coust', 
1774             'description'),
1775         'bool'
1776 );
1777
1778 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1779         'circ.password_reset_request_requires_matching_email',
1780         oils_i18n_gettext(
1781             'circ.password_reset_request_requires_matching_email',
1782             'Circulation: Require matching email address for password reset requests', 
1783             'coust', 
1784             'label'),
1785         oils_i18n_gettext(
1786             'circ.password_reset_request_requires_matching_email',
1787             'Circulation: Require matching email address for password reset requests', 
1788             'coust', 
1789             'description'),
1790         'bool'
1791 );
1792
1793 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1794         'circ.holds.expired_patron_block',
1795         oils_i18n_gettext(
1796             'circ.holds.expired_patron_block',
1797             'Circulation: Block hold request if hold recipient privileges have expired', 
1798             'coust', 
1799             'label'),
1800         oils_i18n_gettext(
1801             'circ.holds.expired_patron_block',
1802             'Circulation: Block hold request if hold recipient privileges have expired', 
1803             'coust', 
1804             'description'),
1805         'bool'
1806 );
1807
1808 INSERT INTO config.org_unit_setting_type
1809     (name, label, description, datatype) VALUES (
1810         'circ.booking_reservation.default_elbow_room',
1811         oils_i18n_gettext(
1812             'circ.booking_reservation.default_elbow_room',
1813             'Booking: Elbow room',
1814             'coust',
1815             'label'
1816         ),
1817         oils_i18n_gettext(
1818             'circ.booking_reservation.default_elbow_room',
1819             'Elbow room specifies how far in the future you must make a reservation on an item if that item will have to transit to reach its pickup location.  It secondarily defines how soon a reservation on a given item must start before the check-in process will opportunistically capture it for the reservation shelf.',
1820             'coust',
1821             'label'
1822         ),
1823         'interval'
1824     );
1825
1826 -- Org_unit_setting_type(s) that need an fm_class:
1827 INSERT into config.org_unit_setting_type
1828 ( name, label, description, datatype, fm_class ) VALUES
1829 ( 'acq.default_copy_location',
1830   'Default copy location',
1831   null,
1832   'link',
1833   'acpl' );
1834
1835 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1836     'circ.holds.org_unit_target_weight',
1837     'Holds: Org Unit Target Weight',
1838     'Org Units can be organized into hold target groups based on a weight.  Potential copies from org units with the same weight are chosen at random.',
1839     'integer'
1840 );
1841
1842 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1843     'circ.holds.target_holds_by_org_unit_weight',
1844     'Holds: Use weight-based hold targeting',
1845     'Use library weight based hold targeting',
1846     'bool'
1847 );
1848
1849 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1850     'circ.holds.max_org_unit_target_loops',
1851     'Holds: Maximum library target attempts',
1852     'When this value is set and greater than 0, the system will only attempt to find a copy at each possible branch the configured number of times',
1853     'integer'
1854 );
1855
1856
1857 -- Org setting for overriding the circ lib of a precat copy
1858 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1859     'circ.pre_cat_copy_circ_lib',
1860     'Pre-cat Item Circ Lib',
1861     'Override the default circ lib of "here" with a pre-configured circ lib for pre-cat items.  The value should be the "shortname" (aka policy name) of the org unit',
1862     'string'
1863 );
1864
1865 -- Circ auto-renew interval setting
1866 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1867     'circ.checkout_auto_renew_age',
1868     'Checkout auto renew age',
1869     'When an item has been checked out for at least this amount of time, an attempt to check out the item to the patron that it is already checked out to will simply renew the circulation',
1870     'interval'
1871 );
1872
1873 -- Setting for behind the desk hold pickups
1874 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1875     'circ.holds.behind_desk_pickup_supported',
1876     'Holds: Behind Desk Pickup Supported',
1877     'If a branch supports both a public holds shelf and behind-the-desk pickups, set this value to true.  This gives the patron the option to enable behind-the-desk pickups for their holds',
1878     'bool'
1879 );
1880
1881 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
1882         'acq.holds.allow_holds_from_purchase_request',
1883         oils_i18n_gettext(
1884             'acq.holds.allow_holds_from_purchase_request', 
1885             'Allows patrons to create automatic holds from purchase requests.', 
1886             'coust', 
1887             'label'),
1888         oils_i18n_gettext(
1889             'acq.holds.allow_holds_from_purchase_request', 
1890             'Allows patrons to create automatic holds from purchase requests.', 
1891             'coust', 
1892             'description'),
1893         'bool'
1894 );
1895
1896 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
1897     'circ.holds.target_skip_me',
1898     'Skip For Hold Targeting',
1899     'When true, don''t target any copies at this org unit for holds',
1900     'bool'
1901 );
1902
1903 -- claims returned mark item missing 
1904 INSERT INTO
1905     config.org_unit_setting_type ( name, label, description, datatype )
1906     VALUES (
1907         'circ.claim_return.mark_missing',
1908         'Claim Return: Mark copy as missing', 
1909         'When a circ is marked as claims-returned, also mark the copy as missing',
1910         'bool'
1911     );
1912
1913 -- claims never checked out mark item missing 
1914 INSERT INTO
1915     config.org_unit_setting_type ( name, label, description, datatype )
1916     VALUES (
1917         'circ.claim_never_checked_out.mark_missing',
1918         'Claim Never Checked Out: Mark copy as missing', 
1919         'When a circ is marked as claims-never-checked-out, mark the copy as missing',
1920         'bool'
1921     );
1922
1923 -- mark damaged void overdue setting
1924 INSERT INTO
1925     config.org_unit_setting_type ( name, label, description, datatype )
1926     VALUES (
1927         'circ.damaged.void_ovedue',
1928         'Mark item damaged voids overdues',
1929         'When an item is marked damaged, overdue fines on the most recent circulation are voided.',
1930         'bool'
1931     );
1932
1933 -- hold cancel display limits
1934 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
1935     VALUES (
1936         'circ.holds.canceled.display_count',
1937         'Holds: Canceled holds display count',
1938         'How many canceled holds to show in patron holds interfaces',
1939         'integer'
1940     );
1941
1942 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
1943     VALUES (
1944         'circ.holds.canceled.display_age',
1945         'Holds: Canceled holds display age',
1946         'Show all canceled holds that were canceled within this amount of time',
1947         'interval'
1948     );
1949
1950 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
1951     VALUES (
1952         'circ.holds.uncancel.reset_request_time',
1953         'Holds: Reset request time on un-cancel',
1954         'When a hold is uncanceled, reset the request time to push it to the end of the queue',
1955         'bool'
1956     );
1957
1958 INSERT INTO config.org_unit_setting_type (name, label, description, datatype)
1959     VALUES (
1960         'circ.holds.default_shelf_expire_interval',
1961         'Default hold shelf expire interval',
1962         '',
1963         'interval'
1964 );
1965
1966 INSERT INTO config.org_unit_setting_type (name, label, description, datatype, fm_class)
1967     VALUES (
1968         'circ.claim_return.copy_status', 
1969         'Claim Return Copy Status', 
1970         'Claims returned copies are put into this status.  Default is to leave the copy in the Checked Out status',
1971         'link', 
1972         'ccs' 
1973     );
1974
1975 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) 
1976     VALUES ( 
1977         'circ.max_fine.cap_at_price',
1978         oils_i18n_gettext('circ.max_fine.cap_at_price', 'Circ: Cap Max Fine at Item Price', 'coust', 'label'),
1979         oils_i18n_gettext('circ.max_fine.cap_at_price', 'This prevents the system from charging more than the item price in overdue fines', 'coust', 'description'),
1980         'bool' 
1981     );
1982
1983 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype, fm_class ) 
1984     VALUES ( 
1985         'circ.holds.clear_shelf.copy_status',
1986         oils_i18n_gettext('circ.holds.clear_shelf.copy_status', 'Holds: Clear shelf copy status', 'coust', 'label'),
1987         oils_i18n_gettext('circ.holds.clear_shelf.copy_status', 'Any copies that have not been put into reshelving, in-transit, or on-holds-shelf (for a new hold) during the clear shelf process will be put into this status.  This is basically a purgatory status for copies waiting to be pulled from the shelf and processed by hand', 'coust', 'description'),
1988         'link',
1989         'ccs'
1990     );
1991
1992 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
1993     VALUES ( 
1994         'circ.selfcheck.workstation_required',
1995         oils_i18n_gettext('circ.selfcheck.workstation_required', 'Selfcheck: Workstation Required', 'coust', 'label'),
1996         oils_i18n_gettext('circ.selfcheck.workstation_required', 'All selfcheck stations must use a workstation', 'coust', 'description'),
1997         'bool'
1998     ), (
1999         'circ.selfcheck.patron_password_required',
2000         oils_i18n_gettext('circ.selfcheck.patron_password_required', 'Selfcheck: Require Patron Password', 'coust', 'label'),
2001         oils_i18n_gettext('circ.selfcheck.patron_password_required', 'Patron must log in with barcode and password at selfcheck station', 'coust', 'description'),
2002         'bool'
2003     );
2004
2005 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2006     VALUES ( 
2007         'circ.selfcheck.alert.sound',
2008         oils_i18n_gettext('circ.selfcheck.alert.sound', 'Selfcheck: Audio Alerts', 'coust', 'label'),
2009         oils_i18n_gettext('circ.selfcheck.alert.sound', 'Use audio alerts for selfcheck events', 'coust', 'description'),
2010         'bool'
2011     );
2012
2013 INSERT INTO
2014     config.org_unit_setting_type (name, label, description, datatype)
2015     VALUES (
2016         'notice.telephony.callfile_lines',
2017         'Telephony: Arbitrary line(s) to include in each notice callfile',
2018         $$
2019         This overrides lines from opensrf.xml.
2020         Line(s) must be valid for your target server and platform
2021         (e.g. Asterisk 1.4).
2022         $$,
2023         'string'
2024     );
2025
2026 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2027     VALUES ( 
2028         'circ.offline.username_allowed',
2029         oils_i18n_gettext('circ.offline.username_allowed', 'Offline: Patron Usernames Allowed', 'coust', 'label'),
2030         oils_i18n_gettext('circ.offline.username_allowed', 'During offline circulations, allow patrons to identify themselves with usernames in addition to barcode.  For this setting to work, a barcode format must also be defined', 'coust', 'description'),
2031         'bool'
2032     );
2033
2034 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2035 VALUES (
2036     'acq.fund.balance_limit.warn',
2037     oils_i18n_gettext('acq.fund.balance_limit.warn', 'Fund Spending Limit for Warning', 'coust', 'label'),
2038     oils_i18n_gettext('acq.fund.balance_limit.warn', 'When the amount remaining in the fund, including spent money and encumbrances, goes below this percentage, attempts to spend from the fund will result in a warning to the staff.', 'coust', 'descripton'),
2039     'integer'
2040 );
2041
2042 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2043 VALUES (
2044     'acq.fund.balance_limit.block',
2045     oils_i18n_gettext('acq.fund.balance_limit.block', 'Fund Spending Limit for Block', 'coust', 'label'),
2046     oils_i18n_gettext('acq.fund.balance_limit.block', 'When the amount remaining in the fund, including spent money and encumbrances, goes below this percentage, attempts to spend from the fund will be blocked.', 'coust', 'description'),
2047     'integer'
2048 );
2049
2050 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2051     VALUES (
2052         'circ.holds.hold_has_copy_at.alert',
2053         oils_i18n_gettext('circ.holds.hold_has_copy_at.alert', 'Holds: Has Local Copy Alert', 'coust', 'label'),
2054         oils_i18n_gettext('circ.holds.hold_has_copy_at.alert', 'If there is an available copy at the requesting library that could fulfill a hold during hold placement time, alert the patron', 'coust', 'description'),
2055         'bool'
2056     ),(
2057         'circ.holds.hold_has_copy_at.block',
2058         oils_i18n_gettext('circ.holds.hold_has_copy_at.block', 'Holds: Has Local Copy Block', 'coust', 'label'),
2059         oils_i18n_gettext('circ.holds.hold_has_copy_at.block', 'If there is an available copy at the requesting library that could fulfill a hold during hold placement time, do not allow the hold to be placed', 'coust', 'description'),
2060         'bool'
2061     );
2062
2063 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2064 VALUES (
2065     'auth.persistent_login_interval',
2066     oils_i18n_gettext('auth.persistent_login_interval', 'Persistent Login Duration', 'coust', 'label'),
2067     oils_i18n_gettext('auth.persistent_login_interval', 'How long a persistent login lasts.  E.g. ''2 weeks''', 'coust', 'description'),
2068     'interval'
2069 );
2070
2071 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
2072         'cat.marc_control_number_identifier',
2073         oils_i18n_gettext(
2074             'cat.marc_control_number_identifier', 
2075             'Cat: Defines the control number identifier used in 003 and 035 fields.', 
2076             'coust', 
2077             'label'),
2078         oils_i18n_gettext(
2079             'cat.marc_control_number_identifier', 
2080             'Cat: Defines the control number identifier used in 003 and 035 fields.', 
2081             'coust', 
2082             'description'),
2083         'string'
2084 );
2085
2086 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) 
2087     VALUES (
2088         'circ.selfcheck.block_checkout_on_copy_status',
2089         oils_i18n_gettext(
2090             'circ.selfcheck.block_checkout_on_copy_status',
2091             'Selfcheck: Block copy checkout status',
2092             'coust',
2093             'label'
2094         ),
2095         oils_i18n_gettext(
2096             'circ.selfcheck.block_checkout_on_copy_status',
2097             'List of copy status IDs that will block checkout even if the generic COPY_NOT_AVAILABLE event is overridden',
2098             'coust',
2099             'description'
2100         ),
2101         'array'
2102     );
2103
2104 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype, fm_class )
2105 VALUES (
2106     'serial.prev_issuance_copy_location',
2107     oils_i18n_gettext(
2108         'serial.prev_issuance_copy_location',
2109         'Serials: Previous Issuance Copy Location',
2110         'coust',
2111         'label'
2112     ),
2113     oils_i18n_gettext(
2114         'serial.prev_issuance_copy_location',
2115         'When a serial issuance is received, copies (units) of the previous issuance will be automatically moved into the configured shelving location',
2116         'coust',
2117         'descripton'
2118         ),
2119     'link',
2120     'acpl'
2121 );
2122
2123 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype, fm_class )
2124 VALUES (
2125     'cat.default_classification_scheme',
2126     oils_i18n_gettext(
2127         'cat.default_classification_scheme',
2128         'Cataloging: Default Classification Scheme',
2129         'coust',
2130         'label'
2131     ),
2132     oils_i18n_gettext(
2133         'cat.default_classification_scheme',
2134         'Defines the default classification scheme for new call numbers: 1 = Generic; 2 = Dewey; 3 = LC',
2135         'coust',
2136         'descripton'
2137         ),
2138     'link',
2139     'acnc'
2140 );
2141
2142 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
2143         'opac.org_unit_hiding.depth',
2144         oils_i18n_gettext(
2145             'opac.org_unit_hiding.depth',
2146             'OPAC: Org Unit Hiding Depth', 
2147             'coust', 
2148             'label'),
2149         oils_i18n_gettext(
2150             'opac.org_unit_hiding.depth',
2151             'This will hide certain org units in the public OPAC if the Original Location (url param "ol") for the OPAC inherits this setting.  This setting specifies an org unit depth, that together with the OPAC Original Location determines which section of the Org Hierarchy should be visible in the OPAC.  For example, a stock Evergreen installation will have a 3-tier hierarchy (Consortium/System/Branch), where System has a depth of 1 and Branch has a depth of 2.  If this setting contains a depth of 1 in such an installation, then every library in the System in which the Original Location belongs will be visible, and everything else will be hidden.  A depth of 0 will effectively make every org visible.  The embedded OPAC in the staff client ignores this setting.', 
2152             'coust', 
2153             'description'),
2154         'integer'
2155 );
2156
2157 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype )
2158     VALUES ( 
2159         'circ.holds.clear_shelf.no_capture_holds',
2160         oils_i18n_gettext('circ.holds.clear_shelf.no_capture_holds', 'Holds: Bypass hold capture during clear shelf process', 'coust', 'label'),
2161         oils_i18n_gettext('circ.holds.clear_shelf.no_capture_holds', 'During the clear shelf process, avoid capturing new holds on cleared items.', 'coust', 'description'),
2162         'bool'
2163     );
2164
2165 INSERT INTO config.org_unit_setting_type (name, label, description, datatype) VALUES (
2166     'circ.booking_reservation.stop_circ',
2167     'Disallow circulation of items when they are on booking reserve and that reserve overlaps with the checkout period',
2168     'When true, items on booking reserve during the proposed checkout period will not be allowed to circulate unless overridden with the COPY_RESERVED.override permission.',
2169     'bool'
2170 );
2171
2172 ---------------------------------
2173 -- Seed data for usr_setting_type
2174 ----------------------------------
2175
2176 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2177     VALUES ('opac.default_font', TRUE, 'OPAC Font Size', 'OPAC Font Size', 'string');
2178
2179 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2180     VALUES ('opac.default_search_depth', TRUE, 'OPAC Search Depth', 'OPAC Search Depth', 'integer');
2181
2182 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2183     VALUES ('opac.default_search_location', TRUE, 'OPAC Search Location', 'OPAC Search Location', 'integer');
2184
2185 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2186     VALUES ('opac.hits_per_page', TRUE, 'Hits per Page', 'Hits per Page', 'string');
2187
2188 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2189     VALUES ('opac.hold_notify', TRUE, 'Hold Notification Format', 'Hold Notification Format', 'string');
2190
2191 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2192     VALUES ('staff_client.catalog.record_view.default', TRUE, 'Default Record View', 'Default Record View', 'string');
2193
2194 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2195     VALUES ('staff_client.copy_editor.templates', TRUE, 'Copy Editor Template', 'Copy Editor Template', 'object');
2196
2197 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2198     VALUES ('circ.holds_behind_desk', FALSE, 'Hold is behind Circ Desk', 'Hold is behind Circ Desk', 'bool');
2199
2200 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2201     VALUES (
2202         'history.circ.retention_age',
2203         TRUE,
2204         oils_i18n_gettext('history.circ.retention_age','Historical Circulation Retention Age','cust','label'),
2205         oils_i18n_gettext('history.circ.retention_age','Historical Circulation Retention Age','cust','description'),
2206         'interval'
2207     ),(
2208         'history.circ.retention_start',
2209         FALSE,
2210         oils_i18n_gettext('history.circ.retention_start','Historical Circulation Retention Start Date','cust','label'),
2211         oils_i18n_gettext('history.circ.retention_start','Historical Circulation Retention Start Date','cust','description'),
2212         'date'
2213     );
2214
2215 INSERT INTO config.usr_setting_type (name,opac_visible,label,description,datatype)
2216     VALUES (
2217         'history.hold.retention_age',
2218         TRUE,
2219         oils_i18n_gettext('history.hold.retention_age','Historical Hold Retention Age','cust','label'),
2220         oils_i18n_gettext('history.hold.retention_age','Historical Hold Retention Age','cust','description'),
2221         'interval'
2222     ),(
2223         'history.hold.retention_start',
2224         TRUE,
2225         oils_i18n_gettext('history.hold.retention_start','Historical Hold Retention Start Date','cust','label'),
2226         oils_i18n_gettext('history.hold.retention_start','Historical Hold Retention Start Date','cust','description'),
2227         'interval'
2228     ),(
2229         'history.hold.retention_count',
2230         TRUE,
2231         oils_i18n_gettext('history.hold.retention_count','Historical Hold Retention Count','cust','label'),
2232         oils_i18n_gettext('history.hold.retention_count','Historical Hold Retention Count','cust','description'),
2233         'integer'
2234     );
2235
2236 INSERT INTO config.usr_setting_type (name, opac_visible, label, description, datatype)
2237     VALUES (
2238         'opac.default_sort',
2239         TRUE,
2240         oils_i18n_gettext(
2241             'opac.default_sort',
2242             'OPAC Default Search Sort',
2243             'cust',
2244             'label'
2245         ),
2246         oils_i18n_gettext(
2247             'opac.default_sort',
2248             'OPAC Default Search Sort',
2249             'cust',
2250             'description'
2251         ),
2252         'string'
2253     );
2254
2255 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype, fm_class ) VALUES (
2256         'circ.missing_pieces.copy_status',
2257         oils_i18n_gettext(
2258             'circ.missing_pieces.copy_status',
2259             'Circulation: Item Status for Missing Pieces',
2260             'coust',
2261             'label'),
2262         oils_i18n_gettext(
2263             'circ.missing_pieces.copy_status',
2264             'This is the Item Status to use for items that have been marked or scanned as having Missing Pieces.  In the absence of this setting, the Damaged status is used.',
2265             'coust',
2266             'description'),
2267         'link',
2268         'ccs'
2269 );
2270
2271 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
2272         'circ.do_not_tally_claims_returned',
2273         oils_i18n_gettext(
2274             'circ.do_not_tally_claims_returned',
2275             'Circulation: Do not include outstanding Claims Returned circulations in lump sum tallies in Patron Display.',
2276             'coust',
2277             'label'),
2278         oils_i18n_gettext(
2279             'circ.do_not_tally_claims_returned',
2280             'In the Patron Display interface, the number of total active circulations for a given patron is presented in the Summary sidebar and underneath the Items Out navigation button.  This setting will prevent Claims Returned circulations from counting toward these tallies.',
2281             'coust',
2282             'description'),
2283         'bool'
2284 );
2285
2286 INSERT INTO config.org_unit_setting_type (name, label, description, datatype)
2287     VALUES
2288         ('cat.label.font.size',
2289             oils_i18n_gettext('cat.label.font.size',
2290                 'Cataloging: Spine and pocket label font size', 'coust', 'label'),
2291             oils_i18n_gettext('cat.label.font.size',
2292                 'Set the default font size for spine and pocket labels', 'coust', 'description'),
2293             'integer'
2294         )
2295         ,('cat.label.font.family',
2296             oils_i18n_gettext('cat.label.font.family',
2297                 'Cataloging: Spine and pocket label font family', 'coust', 'label'),
2298             oils_i18n_gettext('cat.label.font.family',
2299                 'Set the preferred font family for spine and pocket labels. You can specify a list of fonts, separated by commas, in order of preference; the system will use the first font it finds with a matching name. For example, "Arial, Helvetica, serif".',
2300                 'coust', 'description'),
2301             'string'
2302         )
2303         ,('cat.spine.line.width',
2304             oils_i18n_gettext('cat.spine.line.width',
2305                 'Cataloging: Spine label line width', 'coust', 'label'),
2306             oils_i18n_gettext('cat.spine.line.width',
2307                 'Set the default line width for spine labels in number of characters. This specifies the boundary at which lines must be wrapped.',
2308                 'coust', 'description'),
2309             'integer'
2310         )
2311         ,('cat.spine.line.height',
2312             oils_i18n_gettext('cat.spine.line.height',
2313                 'Cataloging: Spine label maximum lines', 'coust', 'label'),
2314             oils_i18n_gettext('cat.spine.line.height',
2315                 'Set the default maximum number of lines for spine labels.',
2316                 'coust', 'description'),
2317             'integer'
2318         )
2319         ,('cat.spine.line.margin',
2320             oils_i18n_gettext('cat.spine.line.margin',
2321                 'Cataloging: Spine label left margin', 'coust', 'label'),
2322             oils_i18n_gettext('cat.spine.line.margin',
2323                 'Set the left margin for spine labels in number of characters.',
2324                 'coust', 'description'),
2325             'integer'
2326         )
2327 ;
2328
2329 INSERT INTO config.org_unit_setting_type (name, label, description, datatype)
2330     VALUES
2331         ('cat.label.font.weight',
2332             oils_i18n_gettext('cat.label.font.weight',
2333                 'Cataloging: Spine and pocket label font weight', 'coust', 'label'),
2334             oils_i18n_gettext('cat.label.font.weight',
2335                 'Set the preferred font weight for spine and pocket labels. You can specify "normal", "bold", "bolder", or "lighter".',
2336                 'coust', 'description'),
2337             'string'
2338         )
2339 ;
2340
2341 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
2342         'circ.patron_edit.clone.copy_address',
2343         oils_i18n_gettext(
2344             'circ.patron_edit.clone.copy_address',
2345             'Patron Registration: Cloned patrons get address copy',
2346             'coust',
2347             'label'
2348         ),
2349         oils_i18n_gettext(
2350             'circ.patron_edit.clone.copy_address',
2351             'In the Patron editor, copy addresses from the cloned user instead of linking directly to the address',
2352             'coust',
2353             'description'
2354         ),
2355         'bool'
2356 );
2357
2358 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype, fm_class ) VALUES (
2359         'ui.patron.default_ident_type',
2360         oils_i18n_gettext(
2361             'ui.patron.default_ident_type',
2362             'GUI: Default Ident Type for Patron Registration',
2363             'coust',
2364             'label'),
2365         oils_i18n_gettext(
2366             'ui.patron.default_ident_type',
2367             'This is the default Ident Type for new users in the patron editor.',
2368             'coust',
2369             'description'),
2370         'link',
2371         'cit'
2372 );
2373
2374 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
2375         'ui.patron.default_country',
2376         oils_i18n_gettext(
2377             'ui.patron.default_country',
2378             'GUI: Default Country for New Addresses in Patron Editor',
2379             'coust',
2380             'label'),
2381         oils_i18n_gettext(
2382             'ui.patron.default_country',
2383             'This is the default Country for new addresses in the patron editor.',
2384             'coust',
2385             'description'),
2386         'string'
2387 );
2388
2389 INSERT INTO config.org_unit_setting_type ( name, label, description, datatype ) VALUES (
2390         'ui.patron.registration.require_address',
2391         oils_i18n_gettext(
2392             'ui.patron.registration.require_address',
2393             'GUI: Require at least one address for Patron Registration',
2394             'coust',
2395             'label'),
2396         oils_i18n_gettext(
2397             'ui.patron.registration.require_address',
2398             'Enforces a requirement for having at least one address for a patron during registration.',
2399             'coust',
2400             'description'),
2401         'bool'
2402 );
2403
2404 INSERT INTO config.org_unit_setting_type (
2405     name, label, description, datatype
2406 ) VALUES
2407     ('credit.processor.payflowpro.enabled',
2408         'Credit card processing: Enable PayflowPro payments',
2409         'This is NOT the same thing as the settings labeled with just "PayPal."',
2410         'bool'
2411     ),
2412     ('credit.processor.payflowpro.login',
2413         'Credit card processing: PayflowPro login/merchant ID',
2414         'Often the same thing as the PayPal manager login',
2415         'string'
2416     ),
2417     ('credit.processor.payflowpro.password',
2418         'Credit card processing: PayflowPro password',
2419         'PayflowPro password',
2420         'string'
2421     ),
2422     ('credit.processor.payflowpro.testmode',
2423         'Credit card processing: PayflowPro test mode',
2424         'Do not really process transactions, but stay in test mode - uses pilot-payflowpro.paypal.com instead of the usual host',
2425         'bool'
2426     ),
2427     ('credit.processor.payflowpro.vendor',
2428         'Credit card processing: PayflowPro vendor',
2429         'Often the same thing as the login',
2430         'string'
2431     ),
2432     ('credit.processor.payflowpro.partner',
2433         'Credit card processing: PayflowPro partner',
2434         'Often "PayPal" or "VeriSign", sometimes others',
2435         'string'
2436     );
2437
2438 -- Patch the name of an old selfcheck setting
2439 UPDATE actor.org_unit_setting
2440     SET name = 'circ.selfcheck.alert.popup'
2441     WHERE name = 'circ.selfcheck.alert_on_checkout_event';
2442
2443 -- Rename certain existing org_unit settings, if present,
2444 -- and make sure their values are JSON
2445 UPDATE actor.org_unit_setting SET
2446     name = 'circ.holds.default_estimated_wait_interval',
2447     --
2448     -- The value column should be JSON.  The old value should be a number,
2449     -- but it may or may not be quoted.  The following CASE behaves
2450     -- differently depending on whether value is quoted.  It is simplistic,
2451     -- and will be defeated by leading or trailing white space, or various
2452     -- malformations.
2453     --
2454     value = CASE WHEN SUBSTR( value, 1, 1 ) = '"'
2455                 THEN '"' || SUBSTR( value, 2, LENGTH(value) - 2 ) || ' days"'
2456                 ELSE '"' || value || ' days"'
2457             END
2458 WHERE name = 'circ.hold_estimate_wait_interval';
2459
2460 -- Create types for existing org unit settings
2461 -- not otherwise accounted for
2462
2463 INSERT INTO config.org_unit_setting_type(
2464  name,
2465  label,
2466  description
2467 )
2468 SELECT DISTINCT
2469         name,
2470         name,
2471         'FIXME'
2472 FROM
2473         actor.org_unit_setting
2474 WHERE
2475         name NOT IN (
2476                 SELECT name
2477                 FROM config.org_unit_setting_type
2478         );
2479
2480 -- Add foreign key to org_unit_setting
2481
2482 ALTER TABLE actor.org_unit_setting
2483         ADD FOREIGN KEY (name) REFERENCES config.org_unit_setting_type (name)
2484                 DEFERRABLE INITIALLY DEFERRED;
2485
2486 -- Create types for existing user settings
2487 -- not otherwise accounted for
2488
2489 INSERT INTO config.usr_setting_type (
2490         name,
2491         label,
2492         description
2493 )
2494 SELECT DISTINCT
2495         name,
2496         name,
2497         'FIXME'
2498 FROM
2499         actor.usr_setting
2500 WHERE
2501         name NOT IN (
2502                 SELECT name
2503                 FROM config.usr_setting_type
2504         );
2505
2506 -- Add foreign key to user_setting_type
2507
2508 ALTER TABLE actor.usr_setting
2509         ADD FOREIGN KEY (name) REFERENCES config.usr_setting_type (name)
2510                 ON DELETE CASCADE ON UPDATE CASCADE
2511                 DEFERRABLE INITIALLY DEFERRED;
2512
2513 INSERT INTO actor.org_unit_setting (org_unit, name, value) VALUES
2514     (1, 'cat.spine.line.margin', 0)
2515     ,(1, 'cat.spine.line.height', 9)
2516     ,(1, 'cat.spine.line.width', 8)
2517     ,(1, 'cat.label.font.family', '"monospace"')
2518     ,(1, 'cat.label.font.size', 10)
2519     ,(1, 'cat.label.font.weight', '"normal"')
2520 ;
2521
2522 ALTER TABLE action_trigger.event_definition ADD COLUMN granularity TEXT;
2523 ALTER TABLE action_trigger.event ADD COLUMN async_output BIGINT REFERENCES action_trigger.event_output (id);
2524 ALTER TABLE action_trigger.event_definition ADD COLUMN usr_field TEXT;
2525 ALTER TABLE action_trigger.event_definition ADD COLUMN opt_in_setting TEXT REFERENCES config.usr_setting_type (name) DEFERRABLE INITIALLY DEFERRED;
2526
2527 CREATE OR REPLACE FUNCTION is_json( TEXT ) RETURNS BOOL AS $f$
2528     use JSON::XS;
2529     my $json = shift();
2530     eval { JSON::XS->new->allow_nonref->decode( $json ) };
2531     return $@ ? 0 : 1;
2532 $f$ LANGUAGE PLPERLU;
2533
2534 ALTER TABLE action_trigger.event ADD COLUMN user_data TEXT CHECK (user_data IS NULL OR is_json( user_data ));
2535
2536 INSERT INTO action_trigger.hook (key,core_type,description) VALUES (
2537     'hold_request.cancel.expire_no_target',
2538     'ahr',
2539     'A hold is cancelled because no copies were found'
2540 );
2541
2542 INSERT INTO action_trigger.hook (key,core_type,description) VALUES (
2543     'hold_request.cancel.expire_holds_shelf',
2544     'ahr',
2545     'A hold is cancelled because it was on the holds shelf too long'
2546 );
2547
2548 INSERT INTO action_trigger.hook (key,core_type,description) VALUES (
2549     'hold_request.cancel.staff',
2550     'ahr',
2551     'A hold is cancelled because it was cancelled by staff'
2552 );
2553
2554 INSERT INTO action_trigger.hook (key,core_type,description) VALUES (
2555     'hold_request.cancel.patron',
2556     'ahr',
2557     'A hold is cancelled by the patron'
2558 );
2559
2560 -- Fix typos in descriptions
2561 UPDATE action_trigger.hook SET description = 'A hold is successfully placed' WHERE key = 'hold_request.success';
2562 UPDATE action_trigger.hook SET description = 'A hold is attempted but not successfully placed' WHERE key = 'hold_request.failure';
2563
2564 -- Add a hook for renewals
2565 INSERT INTO action_trigger.hook (key,core_type,description) VALUES ('renewal','circ','Item renewed to user');
2566
2567 INSERT INTO action_trigger.validator (module,description) VALUES ('MaxPassiveDelayAge','Check that the event is not too far past the delay_field time -- requires a max_delay_age interval parameter');
2568
2569 -- Sample Pre-due Notice --
2570
2571 INSERT INTO action_trigger.event_definition (id, active, owner, name, hook, validator, reactor, delay, delay_field, group_field, template) 
2572     VALUES (6, 'f', 1, '3 Day Courtesy Notice', 'checkout.due', 'CircIsOpen', 'SendEmail', '-3 days', 'due_date', 'usr', 
2573 $$
2574 [%- USE date -%]
2575 [%- user = target.0.usr -%]
2576 To: [%- params.recipient_email || user.email %]
2577 From: [%- params.sender_email || default_sender %]
2578 Subject: Courtesy Notice
2579
2580 Dear [% user.family_name %], [% user.first_given_name %]
2581 As a reminder, the following items are due in 3 days.
2582
2583 [% FOR circ IN target %]
2584     Title: [% circ.target_copy.call_number.record.simple_record.title %] 
2585     Barcode: [% circ.target_copy.barcode %] 
2586     Due: [% date.format(helpers.format_date(circ.due_date), '%Y-%m-%d') %]
2587     Item Cost: [% helpers.get_copy_price(circ.target_copy) %]
2588     Library: [% circ.circ_lib.name %]
2589     Library Phone: [% circ.circ_lib.phone %]
2590 [% END %]
2591
2592 $$);
2593
2594 INSERT INTO action_trigger.environment (event_def, path) VALUES 
2595     (6, 'target_copy.call_number.record.simple_record'),
2596     (6, 'usr'),
2597     (6, 'circ_lib.billing_address');
2598
2599 INSERT INTO action_trigger.event_params (event_def, param, value) VALUES
2600     (6, 'max_delay_age', '"1 day"');
2601
2602 -- also add the max delay age to the default overdue notice event def
2603 INSERT INTO action_trigger.event_params (event_def, param, value) VALUES
2604     (1, 'max_delay_age', '"1 day"');
2605   
2606 INSERT INTO action_trigger.validator (module,description) VALUES ('MinPassiveTargetAge','Check that the target is old enough to be used by this event -- requires a min_target_age interval parameter, and accepts an optional target_age_field to specify what time to use for offsetting');
2607
2608 INSERT INTO action_trigger.reactor (module,description) VALUES ('ApplyPatronPenalty','Applies the configured penalty to a patron.  Required named environment variables are "user", which refers to the user object, and "context_org", which refers to the org_unit object that acts as the focus for the penalty.');
2609
2610 INSERT INTO action_trigger.hook (
2611         key,
2612         core_type,
2613         description,
2614         passive
2615     ) VALUES (
2616         'hold_request.shelf_expires_soon',
2617         'ahr',
2618         'A hold on the shelf will expire there soon.',
2619         TRUE
2620     );
2621
2622 INSERT INTO action_trigger.event_definition (
2623         id,
2624         active,
2625         owner,
2626         name,
2627         hook,
2628         validator,
2629         reactor,
2630         delay,
2631         delay_field,
2632         group_field,
2633         template
2634     ) VALUES (
2635         7,
2636         FALSE,
2637         1,
2638         'Hold Expires from Shelf Soon',
2639         'hold_request.shelf_expires_soon',
2640         'HoldIsAvailable',
2641         'SendEmail',
2642         '- 1 DAY',
2643         'shelf_expire_time',
2644         'usr',
2645 $$
2646 [%- USE date -%]
2647 [%- user = target.0.usr -%]
2648 To: [%- params.recipient_email || user.email %]
2649 From: [%- params.sender_email || default_sender %]
2650 Subject: Hold Available Notification
2651
2652 Dear [% user.family_name %], [% user.first_given_name %]
2653 You requested holds on the following item(s), which are available for
2654 pickup, but these holds will soon expire.
2655
2656 [% FOR hold IN target %]
2657     [%- data = helpers.get_copy_bib_basics(hold.current_copy.id) -%]
2658     Title: [% data.title %]
2659     Author: [% data.author %]
2660     Library: [% hold.pickup_lib.name %]
2661 [% END %]
2662 $$
2663     );
2664
2665 INSERT INTO action_trigger.environment (
2666         event_def,
2667         path
2668     ) VALUES
2669     ( 7, 'current_copy'),
2670     ( 7, 'pickup_lib.billing_address'),
2671     ( 7, 'usr');
2672
2673 INSERT INTO action_trigger.hook (
2674         key,
2675         core_type,
2676         description,
2677         passive
2678     ) VALUES (
2679         'hold_request.long_wait',
2680         'ahr',
2681         'A patron has been waiting on a hold to be fulfilled for a long time.',
2682         TRUE
2683     );
2684
2685 INSERT INTO action_trigger.event_definition (
2686         id,
2687         active,
2688         owner,
2689         name,
2690         hook,
2691         validator,
2692         reactor,
2693         delay,
2694         delay_field,
2695         group_field,
2696         template
2697     ) VALUES (
2698         9,
2699         FALSE,
2700         1,
2701         'Hold waiting for pickup for long time',
2702         'hold_request.long_wait',
2703         'NOOP_True',
2704         'SendEmail',
2705         '6 MONTHS',
2706         'request_time',
2707         'usr',
2708 $$
2709 [%- USE date -%]
2710 [%- user = target.0.usr -%]
2711 To: [%- params.recipient_email || user.email %]
2712 From: [%- params.sender_email || default_sender %]
2713 Subject: Long Wait Hold Notification
2714
2715 Dear [% user.family_name %], [% user.first_given_name %]
2716
2717 You requested hold(s) on the following item(s), but unfortunately
2718 we have not been able to fulfill your request after a considerable
2719 length of time.  If you would still like to receive these items,
2720 no action is required.
2721
2722 [% FOR hold IN target %]
2723     Title: [% hold.bib_rec.bib_record.simple_record.title %]
2724     Author: [% hold.bib_rec.bib_record.simple_record.author %]
2725 [% END %]
2726 $$
2727 );
2728
2729 INSERT INTO action_trigger.environment (
2730         event_def,
2731         path
2732     ) VALUES
2733     (9, 'pickup_lib'),
2734     (9, 'usr'),
2735     (9, 'bib_rec.bib_record.simple_record');
2736
2737 INSERT INTO action_trigger.hook (key, core_type, description, passive) 
2738     VALUES (
2739         'format.selfcheck.checkout',
2740         'circ',
2741         'Formats circ objects for self-checkout receipt',
2742         TRUE
2743     );
2744
2745 INSERT INTO action_trigger.event_definition (id, active, owner, name, hook, validator, reactor, group_field, granularity, template )
2746     VALUES (
2747         10,
2748         TRUE,
2749         1,
2750         'Self-Checkout Receipt',
2751         'format.selfcheck.checkout',
2752         'NOOP_True',
2753         'ProcessTemplate',
2754         'usr',
2755         'print-on-demand',
2756 $$
2757 [%- USE date -%]
2758 [%- SET user = target.0.usr -%]
2759 [%- SET lib = target.0.circ_lib -%]
2760 [%- SET lib_addr = target.0.circ_lib.billing_address -%]
2761 [%- SET hours = lib.hours_of_operation -%]
2762 <div>
2763     <style> li { padding: 8px; margin 5px; }</style>
2764     <div>[% date.format %]</div>
2765     <div>[% lib.name %]</div>
2766     <div>[% lib_addr.street1 %] [% lib_addr.street2 %]</div>
2767     <div>[% lib_addr.city %], [% lib_addr.state %] [% lb_addr.post_code %]</div>
2768     <div>[% lib.phone %]</div>
2769     <br/>
2770
2771     [% user.family_name %], [% user.first_given_name %]
2772     <ol>
2773     [% FOR circ IN target %]
2774         [%-
2775             SET idx = loop.count - 1;
2776             SET udata =  user_data.$idx
2777         -%]
2778         <li>
2779             <div>[% helpers.get_copy_bib_basics(circ.target_copy.id).title %]</div>
2780             <div>Barcode: [% circ.target_copy.barcode %]</div>
2781             [% IF udata.renewal_failure %]
2782                 <div style='color:red;'>Renewal Failed</div>
2783             [% ELSE %]
2784                 <div>Due Date: [% date.format(helpers.format_date(circ.due_date), '%Y-%m-%d') %]</div>
2785             [% END %]
2786         </li>
2787     [% END %]
2788     </ol>
2789     
2790     <div>
2791         Library Hours
2792         [%- BLOCK format_time; date.format(time _ ' 1/1/1000', format='%I:%M %p'); END -%]
2793         <div>
2794             Monday 
2795             [% PROCESS format_time time = hours.dow_0_open %] 
2796             [% PROCESS format_time time = hours.dow_0_close %] 
2797         </div>
2798         <div>
2799             Tuesday 
2800             [% PROCESS format_time time = hours.dow_1_open %] 
2801             [% PROCESS format_time time = hours.dow_1_close %] 
2802         </div>
2803         <div>
2804             Wednesday 
2805             [% PROCESS format_time time = hours.dow_2_open %] 
2806             [% PROCESS format_time time = hours.dow_2_close %] 
2807         </div>
2808         <div>
2809             Thursday
2810             [% PROCESS format_time time = hours.dow_3_open %] 
2811             [% PROCESS format_time time = hours.dow_3_close %] 
2812         </div>
2813         <div>
2814             Friday
2815             [% PROCESS format_time time = hours.dow_4_open %] 
2816             [% PROCESS format_time time = hours.dow_4_close %] 
2817         </div>
2818         <div>
2819             Saturday
2820             [% PROCESS format_time time = hours.dow_5_open %] 
2821             [% PROCESS format_time time = hours.dow_5_close %] 
2822         </div>
2823         <div>
2824             Sunday 
2825             [% PROCESS format_time time = hours.dow_6_open %] 
2826             [% PROCESS format_time time = hours.dow_6_close %] 
2827         </div>
2828     </div>
2829 </div>
2830 $$
2831 );
2832
2833 INSERT INTO action_trigger.environment ( event_def, path) VALUES
2834     ( 10, 'target_copy'),
2835     ( 10, 'circ_lib.billing_address'),
2836     ( 10, 'circ_lib.hours_of_operation'),
2837     ( 10, 'usr');
2838
2839 INSERT INTO action_trigger.hook (key, core_type, description, passive) 
2840     VALUES (
2841         'format.selfcheck.items_out',
2842         'circ',
2843         'Formats items out for self-checkout receipt',
2844         TRUE
2845     );
2846
2847 INSERT INTO action_trigger.event_definition (id, active, owner, name, hook, validator, reactor, group_field, granularity, template )
2848     VALUES (
2849         11,
2850         TRUE,
2851         1,
2852         'Self-Checkout Items Out Receipt',
2853         'format.selfcheck.items_out',
2854         'NOOP_True',
2855         'ProcessTemplate',
2856         'usr',
2857         'print-on-demand',
2858 $$
2859 [%- USE date -%]
2860 [%- SET user = target.0.usr -%]
2861 <div>
2862     <style> li { padding: 8px; margin 5px; }</style>
2863     <div>[% date.format %]</div>
2864     <br/>
2865
2866     [% user.family_name %], [% user.first_given_name %]
2867     <ol>
2868     [% FOR circ IN target %]
2869         <li>
2870             <div>[% helpers.get_copy_bib_basics(circ.target_copy.id).title %]</div>
2871             <div>Barcode: [% circ.target_copy.barcode %]</div>
2872             <div>Due Date: [% date.format(helpers.format_date(circ.due_date), '%Y-%m-%d') %]</div>
2873         </li>
2874     [% END %]
2875     </ol>
2876 </div>
2877 $$
2878 );
2879
2880
2881 INSERT INTO action_trigger.environment ( event_def, path) VALUES
2882     ( 11, 'target_copy'),
2883     ( 11, 'circ_lib.billing_address'),
2884     ( 11, 'circ_lib.hours_of_operation'),
2885     ( 11, 'usr');
2886
2887 INSERT INTO action_trigger.hook (key, core_type, description, passive) 
2888     VALUES (
2889         'format.selfcheck.holds',
2890         'ahr',
2891         'Formats holds for self-checkout receipt',
2892         TRUE
2893     );
2894
2895 INSERT INTO action_trigger.event_definition (id, active, owner, name, hook, validator, reactor, group_field, granularity, template )
2896     VALUES (
2897         12,
2898         TRUE,
2899         1,
2900         'Self-Checkout Holds Receipt',
2901         'format.selfcheck.holds',
2902         'NOOP_True',
2903         'ProcessTemplate',
2904         'usr',
2905         'print-on-demand',
2906 $$
2907 [%- USE date -%]
2908 [%- SET user = target.0.usr -%]
2909 <div>
2910     <style> li { padding: 8px; margin 5px; }</style>
2911     <div>[% date.format %]</div>
2912     <br/>
2913
2914     [% user.family_name %], [% user.first_given_name %]
2915     <ol>
2916     [% FOR hold IN target %]
2917         [%-
2918             SET idx = loop.count - 1;
2919             SET udata =  user_data.$idx
2920         -%]
2921         <li>
2922             <div>Title: [% hold.bib_rec.bib_record.simple_record.title %]</div>
2923             <div>Author: [% hold.bib_rec.bib_record.simple_record.author %]</div>
2924             <div>Pickup Location: [% hold.pickup_lib.name %]</div>
2925             <div>Status: 
2926                 [%- IF udata.ready -%]
2927                     Ready for pickup
2928                 [% ELSE %]
2929                     #[% udata.queue_position %] of [% udata.potential_copies %] copies.
2930                 [% END %]
2931             </div>
2932         </li>
2933     [% END %]
2934     </ol>
2935 </div>
2936 $$
2937 );
2938
2939
2940 INSERT INTO action_trigger.environment ( event_def, path) VALUES
2941     ( 12, 'bib_rec.bib_record.simple_record'),
2942     ( 12, 'pickup_lib'),
2943     ( 12, 'usr');
2944
2945 INSERT INTO action_trigger.hook (key, core_type, description, passive) 
2946     VALUES (
2947         'format.selfcheck.fines',
2948         'au',
2949         'Formats fines for self-checkout receipt',
2950         TRUE
2951     );
2952
2953 INSERT INTO action_trigger.event_definition (id, active, owner, name, hook, validator, reactor, granularity, template )
2954     VALUES (
2955         13,
2956         TRUE,
2957         1,
2958         'Self-Checkout Fines Receipt',
2959         'format.selfcheck.fines',
2960         'NOOP_True',
2961         'ProcessTemplate',
2962         'print-on-demand',
2963 $$
2964 [%- USE date -%]
2965 [%- SET user = target -%]
2966 <div>
2967     <style> li { padding: 8px; margin 5px; }</style>
2968     <div>[% date.format %]</div>
2969     <br/>
2970
2971     [% user.family_name %], [% user.first_given_name %]
2972     <ol>
2973     [% FOR xact IN user.open_billable_transactions_summary %]
2974         <li>
2975             <div>Details: 
2976                 [% IF xact.xact_type == 'circulation' %]
2977                     [%- helpers.get_copy_bib_basics(xact.circulation.target_copy).title -%]
2978                 [% ELSE %]
2979                     [%- xact.last_billing_type -%]
2980                 [% END %]
2981             </div>
2982             <div>Total Billed: [% xact.total_owed %]</div>
2983             <div>Total Paid: [% xact.total_paid %]</div>
2984             <div>Balance Owed : [% xact.balance_owed %]</div>
2985         </li>
2986     [% END %]
2987     </ol>
2988 </div>
2989 $$
2990 );
2991
2992 INSERT INTO action_trigger.environment ( event_def, path) VALUES
2993     ( 13, 'open_billable_transactions_summary.circulation' );
2994
2995 INSERT INTO action_trigger.reactor (module,description) VALUES
2996 (   'SendFile',
2997     oils_i18n_gettext(
2998         'SendFile',
2999         'Build and transfer a file to a remote server.  Required parameter "remote_host" specifying target server.  Optional parameters: remote_user, remote_password, remote_account, port, type (FTP, SFTP or SCP), and debug.',
3000         'atreact',
3001         'description'
3002     )
3003 );
3004
3005 INSERT INTO action_trigger.hook (key, core_type, description, passive) 
3006     VALUES (
3007         'format.acqli.html',
3008         'jub',
3009         'Formats lineitem worksheet for titles received',
3010         TRUE
3011     );
3012
3013 INSERT INTO action_trigger.event_definition (id, active, owner, name, hook, validator, reactor, granularity, template)
3014     VALUES (
3015         14,
3016         TRUE,
3017         1,
3018         'Lineitem Worksheet',
3019         'format.acqli.html',
3020         'NOOP_True',
3021         'ProcessTemplate',
3022         'print-on-demand',
3023 $$
3024 [%- USE date -%]
3025 [%- SET li = target; -%]
3026 <div class="wrapper">
3027     <div class="summary" style='font-size:110%; font-weight:bold;'>
3028
3029         <div>Title: [% helpers.get_li_attr("title", "", li.attributes) %]</div>
3030         <div>Author: [% helpers.get_li_attr("author", "", li.attributes) %]</div>
3031         <div class="count">Item Count: [% li.lineitem_details.size %]</div>
3032         <div class="lineid">Lineitem ID: [% li.id %]</div>
3033
3034         [% IF li.distribution_formulas.size > 0 %]
3035             [% SET forms = [] %]
3036             [% FOREACH form IN li.distribution_formulas; forms.push(form.formula.name); END %]
3037             <div>Distribution Formulas: [% forms.join(',') %]</div>
3038         [% END %]
3039
3040         [% IF li.lineitem_notes.size > 0 %]
3041             Lineitem Notes:
3042             <ul>
3043                 [%- FOR note IN li.lineitem_notes -%]
3044                     <li>
3045                     [% IF note.alert_text %]
3046                         [% note.alert_text.code -%] 
3047                         [% IF note.value -%]
3048                             : [% note.value %]
3049                         [% END %]
3050                     [% ELSE %]
3051                         [% note.value -%] 
3052                     [% END %]
3053                     </li>
3054                 [% END %]
3055             </ul>
3056         [% END %]
3057     </div>
3058     <br/>
3059     <table>
3060         <thead>
3061             <tr>
3062                 <th>Branch</th>
3063                 <th>Barcode</th>
3064                 <th>Call Number</th>
3065                 <th>Fund</th>
3066                 <th>Recd.</th>
3067                 <th>Notes</th>
3068             </tr>
3069         </thead>
3070         <tbody>
3071         [% FOREACH detail IN li.lineitem_details.sort('owning_lib') %]
3072             [% 
3073                 IF copy.eg_copy_id;
3074                     SET copy = copy.eg_copy_id;
3075                     SET cn_label = copy.call_number.label;
3076                 ELSE; 
3077                     SET copy = detail; 
3078                     SET cn_label = detail.cn_label;
3079                 END 
3080             %]
3081             <tr>
3082                 <!-- acq.lineitem_detail.id = [%- detail.id -%] -->
3083                 <td style='padding:5px;'>[% detail.owning_lib.shortname %]</td>
3084                 <td style='padding:5px;'>[% IF copy.barcode   %]<span class="barcode"  >[% detail.barcode   %]</span>[% END %]</td>
3085                 <td style='padding:5px;'>[% IF cn_label %]<span class="cn_label" >[% cn_label  %]</span>[% END %]</td>
3086                 <td style='padding:5px;'>[% IF detail.fund %]<span class="fund">[% detail.fund.code %] ([% detail.fund.year %])</span>[% END %]</td>
3087                 <td style='padding:5px;'>[% IF detail.recv_time %]<span class="recv_time">[% detail.recv_time %]</span>[% END %]</td>
3088                 <td style='padding:5px;'>[% detail.note %]</td>
3089             </tr>
3090         [% END %]
3091         </tbody>
3092     </table>
3093 </div>
3094 $$
3095 );
3096
3097
3098 INSERT INTO action_trigger.environment (event_def, path) VALUES
3099     ( 14, 'attributes' ),
3100     ( 14, 'lineitem_details' ),
3101     ( 14, 'lineitem_details.owning_lib' ),
3102     ( 14, 'lineitem_notes' )
3103 ;
3104
3105 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES (
3106         'aur.ordered',
3107         'aur', 
3108         oils_i18n_gettext(
3109             'aur.ordered',
3110             'A patron acquisition request has been marked On-Order.',
3111             'ath',
3112             'description'
3113         ), 
3114         TRUE
3115     ), (
3116         'aur.received', 
3117         'aur', 
3118         oils_i18n_gettext(
3119             'aur.received', 
3120             'A patron acquisition request has been marked Received.',
3121             'ath',
3122             'description'
3123         ),
3124         TRUE
3125     ), (
3126         'aur.cancelled',
3127         'aur',
3128         oils_i18n_gettext(
3129             'aur.cancelled',
3130             'A patron acquisition request has been marked Cancelled.',
3131             'ath',
3132             'description'
3133         ),
3134         TRUE
3135     )
3136 ;
3137
3138 INSERT INTO action_trigger.validator (module,description) VALUES (
3139         'Acq::UserRequestOrdered',
3140         oils_i18n_gettext(
3141             'Acq::UserRequestOrdered',
3142             'Tests to see if the corresponding Line Item has a state of "on-order".',
3143             'atval',
3144             'description'
3145         )
3146     ), (
3147         'Acq::UserRequestReceived',
3148         oils_i18n_gettext(
3149             'Acq::UserRequestReceived',
3150             'Tests to see if the corresponding Line Item has a state of "received".',
3151             'atval',
3152             'description'
3153         )
3154     ), (
3155         'Acq::UserRequestCancelled',
3156         oils_i18n_gettext(
3157             'Acq::UserRequestCancelled',
3158             'Tests to see if the corresponding Line Item has a state of "cancelled".',
3159             'atval',
3160             'description'
3161         )
3162     )
3163 ;
3164
3165 -- What was event_definition #15 in v1.6.1 will be recreated as #20.  This
3166 -- renumbering requires some juggling:
3167 --
3168 -- 1. Update any child rows to point to #20.  These updates will temporarily
3169 -- violate foreign key constraints, but that's okay as long as we create
3170 -- #20 before committing.
3171 --
3172 -- 2. Delete the old #15.
3173 --
3174 -- 3. Insert the new #15.
3175 --
3176 -- 4. Insert #20.
3177 --
3178 -- We could combine steps 2 and 3 into a single update, but that would create
3179 -- additional opportunities for typos, since we already have the insert from
3180 -- an upgrade script.
3181
3182 UPDATE action_trigger.environment
3183 SET event_def = 20
3184 WHERE event_def = 15;
3185
3186 UPDATE action_trigger.event
3187 SET event_def = 20
3188 WHERE event_def = 15;
3189
3190 UPDATE action_trigger.event_params
3191 SET event_def = 20
3192 WHERE event_def = 15;
3193
3194 DELETE FROM action_trigger.event_definition
3195 WHERE id = 15;
3196
3197 INSERT INTO action_trigger.event_definition (
3198         id,
3199         active,
3200         owner,
3201         name,
3202         hook,
3203         validator,
3204         reactor,
3205         template
3206     ) VALUES (
3207         15,
3208         FALSE,
3209         1,
3210         'Email Notice: Patron Acquisition Request marked On-Order.',
3211         'aur.ordered',
3212         'Acq::UserRequestOrdered',
3213         'SendEmail',
3214 $$
3215 [%- USE date -%]
3216 [%- SET li = target.lineitem; -%]
3217 [%- SET user = target.usr -%]
3218 [%- SET title = helpers.get_li_attr("title", "", li.attributes) -%]
3219 [%- SET author = helpers.get_li_attr("author", "", li.attributes) -%]
3220 [%- SET edition = helpers.get_li_attr("edition", "", li.attributes) -%]
3221 [%- SET isbn = helpers.get_li_attr("isbn", "", li.attributes) -%]
3222 [%- SET publisher = helpers.get_li_attr("publisher", "", li.attributes) -%]
3223 [%- SET pubdate = helpers.get_li_attr("pubdate", "", li.attributes) -%]
3224
3225 To: [%- params.recipient_email || user.email %]
3226 From: [%- params.sender_email || default_sender %]
3227 Subject: Acquisition Request Notification
3228
3229 Dear [% user.family_name %], [% user.first_given_name %]
3230 Our records indicate the following acquisition request has been placed on order.
3231
3232 Title: [% title %]
3233 [% IF author %]Author: [% author %][% END %]
3234 [% IF edition %]Edition: [% edition %][% END %]
3235 [% IF isbn %]ISBN: [% isbn %][% END %]
3236 [% IF publisher %]Publisher: [% publisher %][% END %]
3237 [% IF pubdate %]Publication Date: [% pubdate %][% END %]
3238 Lineitem ID: [% li.id %]
3239 $$
3240     ), (
3241         16,
3242         FALSE,
3243         1,
3244         'Email Notice: Patron Acquisition Request marked Received.',
3245         'aur.received',
3246         'Acq::UserRequestReceived',
3247         'SendEmail',
3248 $$
3249 [%- USE date -%]
3250 [%- SET li = target.lineitem; -%]
3251 [%- SET user = target.usr -%]
3252 [%- SET title = helpers.get_li_attr("title", "", li.attributes) %]
3253 [%- SET author = helpers.get_li_attr("author", "", li.attributes) %]
3254 [%- SET edition = helpers.get_li_attr("edition", "", li.attributes) %]
3255 [%- SET isbn = helpers.get_li_attr("isbn", "", li.attributes) %]
3256 [%- SET publisher = helpers.get_li_attr("publisher", "", li.attributes) -%]
3257 [%- SET pubdate = helpers.get_li_attr("pubdate", "", li.attributes) -%]
3258
3259 To: [%- params.recipient_email || user.email %]
3260 From: [%- params.sender_email || default_sender %]
3261 Subject: Acquisition Request Notification
3262
3263 Dear [% user.family_name %], [% user.first_given_name %]
3264 Our records indicate the materials for the following acquisition request have been received.
3265
3266 Title: [% title %]
3267 [% IF author %]Author: [% author %][% END %]
3268 [% IF edition %]Edition: [% edition %][% END %]
3269 [% IF isbn %]ISBN: [% isbn %][% END %]
3270 [% IF publisher %]Publisher: [% publisher %][% END %]
3271 [% IF pubdate %]Publication Date: [% pubdate %][% END %]
3272 Lineitem ID: [% li.id %]
3273 $$
3274     ), (
3275         17,
3276         FALSE,
3277         1,
3278         'Email Notice: Patron Acquisition Request marked Cancelled.',
3279         'aur.cancelled',
3280         'Acq::UserRequestCancelled',
3281         'SendEmail',
3282 $$
3283 [%- USE date -%]
3284 [%- SET li = target.lineitem; -%]
3285 [%- SET user = target.usr -%]
3286 [%- SET title = helpers.get_li_attr("title", "", li.attributes) %]
3287 [%- SET author = helpers.get_li_attr("author", "", li.attributes) %]
3288 [%- SET edition = helpers.get_li_attr("edition", "", li.attributes) %]
3289 [%- SET isbn = helpers.get_li_attr("isbn", "", li.attributes) %]
3290 [%- SET publisher = helpers.get_li_attr("publisher", "", li.attributes) -%]
3291 [%- SET pubdate = helpers.get_li_attr("pubdate", "", li.attributes) -%]
3292
3293 To: [%- params.recipient_email || user.email %]
3294 From: [%- params.sender_email || default_sender %]
3295 Subject: Acquisition Request Notification
3296
3297 Dear [% user.family_name %], [% user.first_given_name %]
3298 Our records indicate the following acquisition request has been cancelled.
3299
3300 Title: [% title %]
3301 [% IF author %]Author: [% author %][% END %]
3302 [% IF edition %]Edition: [% edition %][% END %]
3303 [% IF isbn %]ISBN: [% isbn %][% END %]
3304 [% IF publisher %]Publisher: [% publisher %][% END %]
3305 [% IF pubdate %]Publication Date: [% pubdate %][% END %]
3306 Lineitem ID: [% li.id %]
3307 $$
3308     );
3309
3310 INSERT INTO action_trigger.environment (
3311         event_def,
3312         path
3313     ) VALUES 
3314         ( 15, 'lineitem' ),
3315         ( 15, 'lineitem.attributes' ),
3316         ( 15, 'usr' ),
3317
3318         ( 16, 'lineitem' ),
3319         ( 16, 'lineitem.attributes' ),
3320         ( 16, 'usr' ),
3321
3322         ( 17, 'lineitem' ),
3323         ( 17, 'lineitem.attributes' ),
3324         ( 17, 'usr' )
3325     ;
3326
3327 INSERT INTO action_trigger.event_definition
3328 (id, active, owner, name, hook, validator, reactor, cleanup_success, cleanup_failure, delay, delay_field, group_field, template) VALUES
3329 (23, true, 1, 'PO JEDI', 'acqpo.activated', 'Acq::PurchaseOrderEDIRequired', 'GeneratePurchaseOrderJEDI', NULL, NULL, '00:05:00', NULL, NULL,
3330 $$
3331 [%- USE date -%]
3332 [%# start JEDI document 
3333   # Vendor specific kludges:
3334   # BT      - vendcode goes to NAD/BY *suffix*  w/ 91 qualifier
3335   # INGRAM  - vendcode goes to NAD/BY *segment* w/ 91 qualifier (separately)
3336   # BRODART - vendcode goes to FTX segment (lineitem level)
3337 -%]
3338 [%- 
3339 IF target.provider.edi_default.vendcode && target.provider.code == 'BRODART';
3340     xtra_ftx = target.provider.edi_default.vendcode;
3341 END;
3342 -%]
3343 [%- BLOCK big_block -%]
3344 {
3345    "recipient":"[% target.provider.san %]",
3346    "sender":"[% target.ordering_agency.mailing_address.san %]",
3347    "body": [{
3348      "ORDERS":[ "order", {
3349         "po_number":[% target.id %],
3350         "date":"[% date.format(date.now, '%Y%m%d') %]",
3351         "buyer":[
3352             [%   IF   target.provider.edi_default.vendcode && (target.provider.code == 'BT' || target.provider.name.match('(?i)^BAKER & TAYLOR'))  -%]
3353                 {"id-qualifier": 91, "id":"[% target.ordering_agency.mailing_address.san _ ' ' _ target.provider.edi_default.vendcode %]"}
3354             [%- ELSIF target.provider.edi_default.vendcode && target.provider.code == 'INGRAM' -%]
3355                 {"id":"[% target.ordering_agency.mailing_address.san %]"},
3356                 {"id-qualifier": 91, "id":"[% target.provider.edi_default.vendcode %]"}
3357             [%- ELSE -%]
3358                 {"id":"[% target.ordering_agency.mailing_address.san %]"}
3359             [%- END -%]
3360         ],
3361         "vendor":[
3362             [%- # target.provider.name (target.provider.id) -%]
3363             "[% target.provider.san %]",
3364             {"id-qualifier": 92, "id":"[% target.provider.id %]"}
3365         ],
3366         "currency":"[% target.provider.currency_type %]",
3367                 
3368         "items":[
3369         [%- FOR li IN target.lineitems %]
3370         {
3371             "line_index":"[% li.id %]",
3372             "identifiers":[   [%-# li.isbns = helpers.get_li_isbns(li.attributes) %]
3373             [% FOR isbn IN helpers.get_li_isbns(li.attributes) -%]
3374                 [% IF isbn.length == 13 -%]
3375                 {"id-qualifier":"EN","id":"[% isbn %]"},
3376                 [% ELSE -%]
3377                 {"id-qualifier":"IB","id":"[% isbn %]"},
3378                 [%- END %]
3379             [% END %]
3380                 {"id-qualifier":"IN","id":"[% li.id %]"}
3381             ],
3382             "price":[% li.estimated_unit_price || '0.00' %],
3383             "desc":[
3384                 {"BTI":"[% helpers.get_li_attr('title',     '', li.attributes) %]"},
3385                 {"BPU":"[% helpers.get_li_attr('publisher', '', li.attributes) %]"},
3386                 {"BPD":"[% helpers.get_li_attr('pubdate',   '', li.attributes) %]"},
3387                 {"BPH":"[% helpers.get_li_attr('pagination','', li.attributes) %]"}
3388             ],
3389             [%- ftx_vals = []; 
3390                 FOR note IN li.lineitem_notes; 
3391                     NEXT UNLESS note.vendor_public == 't'; 
3392                     ftx_vals.push(note.value); 
3393                 END; 
3394                 IF xtra_ftx;           ftx_vals.unshift(xtra_ftx); END; 
3395                 IF ftx_vals.size == 0; ftx_vals.unshift('');       END;  # BT needs FTX+LIN for every LI, even if it is an empty one
3396             -%]
3397
3398             "free-text":[ 
3399                 [% FOR note IN ftx_vals -%] "[% note %]"[% UNLESS loop.last %], [% END %][% END %] 
3400             ],            
3401             "quantity":[% li.lineitem_details.size %]
3402         }[% UNLESS loop.last %],[% END %]
3403         [%-# TODO: lineitem details (later) -%]
3404         [% END %]
3405         ],
3406         "line_items":[% target.lineitems.size %]
3407      }]  [%# close ORDERS array %]
3408    }]    [%# close  body  array %]
3409 }
3410 [% END %]
3411 [% tempo = PROCESS big_block; helpers.escape_json(tempo) %]
3412
3413 $$);
3414
3415 INSERT INTO action_trigger.environment (event_def, path) VALUES 
3416   (23, 'lineitems.attributes'), 
3417   (23, 'lineitems.lineitem_details'), 
3418   (23, 'lineitems.lineitem_notes'), 
3419   (23, 'ordering_agency.mailing_address'), 
3420   (23, 'provider');
3421
3422 UPDATE action_trigger.event_definition SET template = 
3423 $$
3424 [%- USE date -%]
3425 [%-
3426     # find a lineitem attribute by name and optional type
3427     BLOCK get_li_attr;
3428         FOR attr IN li.attributes;
3429             IF attr.attr_name == attr_name;
3430                 IF !attr_type OR attr_type == attr.attr_type;
3431                     attr.attr_value;
3432                     LAST;
3433                 END;
3434             END;
3435         END;
3436     END
3437 -%]
3438
3439 <h2>Purchase Order [% target.id %]</h2>
3440 <br/>
3441 date <b>[% date.format(date.now, '%Y%m%d') %]</b>
3442 <br/>
3443
3444 <style>
3445     table td { padding:5px; border:1px solid #aaa;}
3446     table { width:95%; border-collapse:collapse; }
3447     #vendor-notes { padding:5px; border:1px solid #aaa; }
3448 </style>
3449 <table id='vendor-table'>
3450   <tr>
3451     <td valign='top'>Vendor</td>
3452     <td>
3453       <div>[% target.provider.name %]</div>
3454       <div>[% target.provider.addresses.0.street1 %]</div>
3455       <div>[% target.provider.addresses.0.street2 %]</div>
3456       <div>[% target.provider.addresses.0.city %]</div>
3457       <div>[% target.provider.addresses.0.state %]</div>
3458       <div>[% target.provider.addresses.0.country %]</div>
3459       <div>[% target.provider.addresses.0.post_code %]</div>
3460     </td>
3461     <td valign='top'>Ship to / Bill to</td>
3462     <td>
3463       <div>[% target.ordering_agency.name %]</div>
3464       <div>[% target.ordering_agency.billing_address.street1 %]</div>
3465       <div>[% target.ordering_agency.billing_address.street2 %]</div>
3466       <div>[% target.ordering_agency.billing_address.city %]</div>
3467       <div>[% target.ordering_agency.billing_address.state %]</div>
3468       <div>[% target.ordering_agency.billing_address.country %]</div>
3469       <div>[% target.ordering_agency.billing_address.post_code %]</div>
3470     </td>
3471   </tr>
3472 </table>
3473
3474 <br/><br/>
3475 <fieldset id='vendor-notes'>
3476     <legend>Notes to the Vendor</legend>
3477     <ul>
3478     [% FOR note IN target.notes %]
3479         [% IF note.vendor_public == 't' %]
3480             <li>[% note.value %]</li>
3481         [% END %]
3482     [% END %]
3483     </ul>
3484 </fieldset>
3485 <br/><br/>
3486
3487 <table>
3488   <thead>
3489     <tr>
3490       <th>PO#</th>
3491       <th>ISBN or Item #</th>
3492       <th>Title</th>
3493       <th>Quantity</th>
3494       <th>Unit Price</th>
3495       <th>Line Total</th>
3496       <th>Notes</th>
3497     </tr>
3498   </thead>
3499   <tbody>
3500
3501   [% subtotal = 0 %]
3502   [% FOR li IN target.lineitems %]
3503
3504   <tr>
3505     [% count = li.lineitem_details.size %]
3506     [% price = li.estimated_unit_price %]
3507     [% litotal = (price * count) %]
3508     [% subtotal = subtotal + litotal %]
3509     [% isbn = PROCESS get_li_attr attr_name = 'isbn' %]
3510     [% ident = PROCESS get_li_attr attr_name = 'identifier' %]
3511
3512     <td>[% target.id %]</td>
3513     <td>[% isbn || ident %]</td>
3514     <td>[% PROCESS get_li_attr attr_name = 'title' %]</td>
3515     <td>[% count %]</td>
3516     <td>[% price %]</td>
3517     <td>[% litotal %]</td>
3518     <td>
3519         <ul>
3520         [% FOR note IN li.lineitem_notes %]
3521             [% IF note.vendor_public == 't' %]
3522                 <li>[% note.value %]</li>
3523             [% END %]
3524         [% END %]
3525         </ul>
3526     </td>
3527   </tr>
3528   [% END %]
3529   <tr>
3530     <td/><td/><td/><td/>
3531     <td>Subtotal</td>
3532     <td>[% subtotal %]</td>
3533   </tr>
3534   </tbody>
3535 </table>
3536
3537 <br/>
3538
3539 Total Line Item Count: [% target.lineitems.size %]
3540 $$
3541 WHERE id = 4;
3542
3543 INSERT INTO action_trigger.environment (event_def, path) VALUES 
3544     (4, 'lineitems.lineitem_notes'),
3545     (4, 'notes');
3546
3547 INSERT INTO action_trigger.environment (event_def, path) VALUES
3548     ( 14, 'lineitem_notes.alert_text' ),
3549     ( 14, 'distribution_formulas.formula' ),
3550     ( 14, 'lineitem_details.fund' ),
3551     ( 14, 'lineitem_details.eg_copy_id' ),
3552     ( 14, 'lineitem_details.eg_copy_id.call_number' )
3553 ;
3554
3555 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES (
3556         'aur.created',
3557         'aur',
3558         oils_i18n_gettext(
3559             'aur.created',
3560             'A patron has made an acquisitions request.',
3561             'ath',
3562             'description'
3563         ),
3564         TRUE
3565     ), (
3566         'aur.rejected',
3567         'aur',
3568         oils_i18n_gettext(
3569             'aur.rejected',
3570             'A patron acquisition request has been rejected.',
3571             'ath',
3572             'description'
3573         ),
3574         TRUE
3575     )
3576 ;
3577
3578 INSERT INTO action_trigger.event_definition (
3579         id,
3580         active,
3581         owner,
3582         name,
3583         hook,
3584         validator,
3585         reactor,
3586         template
3587     ) VALUES (
3588         18,
3589         FALSE,
3590         1,
3591         'Email Notice: Acquisition Request created.',
3592         'aur.created',
3593         'NOOP_True',
3594         'SendEmail',
3595 $$
3596 [%- USE date -%]
3597 [%- SET user = target.usr -%]
3598 [%- SET title = target.title -%]
3599 [%- SET author = target.author -%]
3600 [%- SET isxn = target.isxn -%]
3601 [%- SET publisher = target.publisher -%]
3602 [%- SET pubdate = target.pubdate -%]
3603
3604 To: [%- params.recipient_email || user.email %]
3605 From: [%- params.sender_email || default_sender %]
3606 Subject: Acquisition Request Notification
3607
3608 Dear [% user.family_name %], [% user.first_given_name %]
3609 Our records indicate that you have made the following acquisition request:
3610
3611 Title: [% title %]
3612 [% IF author %]Author: [% author %][% END %]
3613 [% IF edition %]Edition: [% edition %][% END %]
3614 [% IF isbn %]ISXN: [% isxn %][% END %]
3615 [% IF publisher %]Publisher: [% publisher %][% END %]
3616 [% IF pubdate %]Publication Date: [% pubdate %][% END %]
3617 $$
3618     ), (
3619         19,
3620         FALSE,
3621         1,
3622         'Email Notice: Acquisition Request Rejected.',
3623         'aur.rejected',
3624         'NOOP_True',
3625         'SendEmail',
3626 $$
3627 [%- USE date -%]
3628 [%- SET user = target.usr -%]
3629 [%- SET title = target.title -%]
3630 [%- SET author = target.author -%]
3631 [%- SET isxn = target.isxn -%]
3632 [%- SET publisher = target.publisher -%]
3633 [%- SET pubdate = target.pubdate -%]
3634 [%- SET cancel_reason = target.cancel_reason.description -%]
3635
3636 To: [%- params.recipient_email || user.email %]
3637 From: [%- params.sender_email || default_sender %]
3638 Subject: Acquisition Request Notification
3639
3640 Dear [% user.family_name %], [% user.first_given_name %]
3641 Our records indicate the following acquisition request has been rejected for this reason: [% cancel_reason %]
3642
3643 Title: [% title %]
3644 [% IF author %]Author: [% author %][% END %]
3645 [% IF edition %]Edition: [% edition %][% END %]
3646 [% IF isbn %]ISBN: [% isbn %][% END %]
3647 [% IF publisher %]Publisher: [% publisher %][% END %]
3648 [% IF pubdate %]Publication Date: [% pubdate %][% END %]
3649 $$
3650     );
3651
3652 INSERT INTO action_trigger.environment (
3653         event_def,
3654         path
3655     ) VALUES 
3656         ( 18, 'usr' ),
3657         ( 19, 'usr' ),
3658         ( 19, 'cancel_reason' )
3659     ;
3660
3661 INSERT INTO action_trigger.hook (key, core_type, description, passive)
3662     VALUES (
3663         'format.acqcle.html',
3664         'acqcle',
3665         'Formats claim events into a voucher',
3666         TRUE
3667     );
3668
3669 INSERT INTO action_trigger.event_definition (
3670         id, active, owner, name, hook, group_field,
3671         validator, reactor, granularity, template
3672     ) VALUES (
3673         21,
3674         TRUE,
3675         1,
3676         'Claim Voucher',
3677         'format.acqcle.html',
3678         'claim',
3679         'NOOP_True',
3680         'ProcessTemplate',
3681         'print-on-demand',
3682 $$
3683 [%- USE date -%]
3684 [%- SET claim = target.0.claim -%]
3685 <!-- This will need refined/prettified. -->
3686 <div class="acq-claim-voucher">
3687     <h2>Claim: [% claim.id %] ([% claim.type.code %])</h2>
3688     <h3>Against: [%- helpers.get_li_attr("title", "", claim.lineitem_detail.lineitem.attributes) -%]</h3>
3689     <ul>
3690         [% FOR event IN target %]
3691         <li>
3692             Event type: [% event.type.code %]
3693             [% IF event.type.library_initiated %](Library initiated)[% END %]
3694             <br />
3695             Event date: [% event.event_date %]<br />
3696             Order date: [% event.claim.lineitem_detail.lineitem.purchase_order.order_date %]<br />
3697             Expected receive date: [% event.claim.lineitem_detail.lineitem.expected_recv_time %]<br />
3698             Initiated by: [% event.creator.family_name %], [% event.creator.first_given_name %] [% event.creator.second_given_name %]<br />
3699             Barcode: [% event.claim.lineitem_detail.barcode %]; Fund:
3700             [% event.claim.lineitem_detail.fund.code %]
3701             ([% event.claim.lineitem_detail.fund.year %])
3702         </li>
3703         [% END %]
3704     </ul>
3705 </div>
3706 $$
3707 );
3708
3709 INSERT INTO action_trigger.environment (event_def, path) VALUES
3710     (21, 'claim'),
3711     (21, 'claim.type'),
3712     (21, 'claim.lineitem_detail'),
3713     (21, 'claim.lineitem_detail.fund'),
3714     (21, 'claim.lineitem_detail.lineitem.attributes'),
3715     (21, 'claim.lineitem_detail.lineitem.purchase_order'),
3716     (21, 'creator'),
3717     (21, 'type')
3718 ;
3719
3720 INSERT INTO action_trigger.hook (key, core_type, description, passive)
3721     VALUES (
3722         'format.acqinv.html',
3723         'acqinv',
3724         'Formats invoices into a voucher',
3725         TRUE
3726     );
3727
3728 INSERT INTO action_trigger.event_definition (
3729         id, active, owner, name, hook,
3730         validator, reactor, granularity, template
3731     ) VALUES (
3732         22,
3733         TRUE,
3734         1,
3735         'Invoice',
3736         'format.acqinv.html',
3737         'NOOP_True',
3738         'ProcessTemplate',
3739         'print-on-demand',
3740 $$
3741 [% FILTER collapse %]
3742 [%- SET invoice = target -%]
3743 <!-- This lacks totals, info about funds (for invoice entries,
3744     funds are per-LID!), and general refinement -->
3745 <div class="acq-invoice-voucher">
3746     <h1>Invoice</h1>
3747     <div>
3748         <strong>No.</strong> [% invoice.inv_ident %]
3749         [% IF invoice.inv_type %]
3750             / <strong>Type:</strong>[% invoice.inv_type %]
3751         [% END %]
3752     </div>
3753     <div>
3754         <dl>
3755             [% BLOCK ent_with_address %]
3756             <dt>[% ent_label %]: [% ent.name %] ([% ent.code %])</dt>
3757             <dd>
3758                 [% IF ent.addresses.0 %]
3759                     [% SET addr = ent.addresses.0 %]
3760                     [% addr.street1 %]<br />
3761                     [% IF addr.street2 %][% addr.street2 %]<br />[% END %]
3762                     [% addr.city %],
3763                     [% IF addr.county %] [% addr.county %], [% END %]
3764                     [% IF addr.state %] [% addr.state %] [% END %]
3765                     [% IF addr.post_code %][% addr.post_code %][% END %]<br />
3766                     [% IF addr.country %] [% addr.country %] [% END %]
3767                 [% END %]
3768                 <p>
3769                     [% IF ent.phone %] Phone: [% ent.phone %]<br />[% END %]
3770                     [% IF ent.fax_phone %] Fax: [% ent.fax_phone %]<br />[% END %]
3771                     [% IF ent.url %] URL: [% ent.url %]<br />[% END %]
3772                     [% IF ent.email %] E-mail: [% ent.email %] [% END %]
3773                 </p>
3774             </dd>
3775             [% END %]
3776             [% INCLUDE ent_with_address
3777                 ent = invoice.provider
3778                 ent_label = "Provider" %]
3779             [% INCLUDE ent_with_address
3780                 ent = invoice.shipper
3781                 ent_label = "Shipper" %]
3782             <dt>Receiver</dt>
3783             <dd>
3784                 [% invoice.receiver.name %] ([% invoice.receiver.shortname %])
3785             </dd>
3786             <dt>Received</dt>
3787             <dd>
3788                 [% helpers.format_date(invoice.recv_date) %] by
3789                 [% invoice.recv_method %]
3790             </dd>
3791             [% IF invoice.note %]
3792                 <dt>Note</dt>
3793                 <dd>
3794                     [% invoice.note %]
3795                 </dd>
3796             [% END %]
3797         </dl>
3798     </div>
3799     <ul>
3800         [% FOR entry IN invoice.entries %]
3801             <li>
3802                 [% IF entry.lineitem %]
3803                     Title: [% helpers.get_li_attr(
3804                         "title", "", entry.lineitem.attributes
3805                     ) %]<br />
3806                     Author: [% helpers.get_li_attr(
3807                         "author", "", entry.lineitem.attributes
3808                     ) %]
3809                 [% END %]
3810                 [% IF entry.purchase_order %]
3811                     (PO: [% entry.purchase_order.name %])
3812                 [% END %]<br />
3813                 Invoice item count: [% entry.inv_item_count %]
3814                 [% IF entry.phys_item_count %]
3815                     / Physical item count: [% entry.phys_item_count %]
3816                 [% END %]
3817                 <br />
3818                 [% IF entry.cost_billed %]
3819                     Cost billed: [% entry.cost_billed %]
3820                     [% IF entry.billed_per_item %](per item)[% END %]
3821                     <br />
3822                 [% END %]
3823                 [% IF entry.actual_cost %]
3824                     Actual cost: [% entry.actual_cost %]<br />
3825                 [% END %]
3826                 [% IF entry.amount_paid %]
3827                     Amount paid: [% entry.amount_paid %]<br />
3828                 [% END %]
3829                 [% IF entry.note %]Note: [% entry.note %][% END %]
3830             </li>
3831         [% END %]
3832         [% FOR item IN invoice.items %]
3833             <li>
3834                 [% IF item.inv_item_type %]
3835                     Item Type: [% item.inv_item_type %]<br />
3836                 [% END %]
3837                 [% IF item.title %]Title/Description:
3838                     [% item.title %]<br />
3839                 [% END %]
3840                 [% IF item.author %]Author: [% item.author %]<br />[% END %]
3841                 [% IF item.purchase_order %]PO: [% item.purchase_order %]<br />[% END %]
3842                 [% IF item.note %]Note: [% item.note %]<br />[% END %]
3843                 [% IF item.cost_billed %]
3844                     Cost billed: [% item.cost_billed %]<br />
3845                 [% END %]
3846                 [% IF item.actual_cost %]
3847                     Actual cost: [% item.actual_cost %]<br />
3848                 [% END %]
3849                 [% IF item.amount_paid %]
3850                     Amount paid: [% item.amount_paid %]<br />
3851                 [% END %]
3852             </li>
3853         [% END %]
3854     </ul>
3855 </div>
3856 [% END %]
3857 $$
3858 );
3859
3860 UPDATE action_trigger.event_definition SET template = $$[% FILTER collapse %]
3861 [%- SET invoice = target -%]
3862 <!-- This lacks general refinement -->
3863 <div class="acq-invoice-voucher">
3864     <h1>Invoice</h1>
3865     <div>
3866         <strong>No.</strong> [% invoice.inv_ident %]
3867         [% IF invoice.inv_type %]
3868             / <strong>Type:</strong>[% invoice.inv_type %]
3869         [% END %]
3870     </div>
3871     <div>
3872         <dl>
3873             [% BLOCK ent_with_address %]
3874             <dt>[% ent_label %]: [% ent.name %] ([% ent.code %])</dt>
3875             <dd>
3876                 [% IF ent.addresses.0 %]
3877                     [% SET addr = ent.addresses.0 %]
3878                     [% addr.street1 %]<br />
3879                     [% IF addr.street2 %][% addr.street2 %]<br />[% END %]
3880                     [% addr.city %],
3881                     [% IF addr.county %] [% addr.county %], [% END %]
3882                     [% IF addr.state %] [% addr.state %] [% END %]
3883                     [% IF addr.post_code %][% addr.post_code %][% END %]<br />
3884                     [% IF addr.country %] [% addr.country %] [% END %]
3885                 [% END %]
3886                 <p>
3887                     [% IF ent.phone %] Phone: [% ent.phone %]<br />[% END %]
3888                     [% IF ent.fax_phone %] Fax: [% ent.fax_phone %]<br />[% END %]
3889                     [% IF ent.url %] URL: [% ent.url %]<br />[% END %]
3890                     [% IF ent.email %] E-mail: [% ent.email %] [% END %]
3891                 </p>
3892             </dd>
3893             [% END %]
3894             [% INCLUDE ent_with_address
3895                 ent = invoice.provider
3896                 ent_label = "Provider" %]
3897             [% INCLUDE ent_with_address
3898                 ent = invoice.shipper
3899                 ent_label = "Shipper" %]
3900             <dt>Receiver</dt>
3901             <dd>
3902                 [% invoice.receiver.name %] ([% invoice.receiver.shortname %])
3903             </dd>
3904             <dt>Received</dt>
3905             <dd>
3906                 [% helpers.format_date(invoice.recv_date) %] by
3907                 [% invoice.recv_method %]
3908             </dd>
3909             [% IF invoice.note %]
3910                 <dt>Note</dt>
3911                 <dd>
3912                     [% invoice.note %]
3913                 </dd>
3914             [% END %]
3915         </dl>
3916     </div>
3917     <ul>
3918         [% FOR entry IN invoice.entries %]
3919             <li>
3920                 [% IF entry.lineitem %]
3921                     Title: [% helpers.get_li_attr(
3922                         "title", "", entry.lineitem.attributes
3923                     ) %]<br />
3924                     Author: [% helpers.get_li_attr(
3925                         "author", "", entry.lineitem.attributes
3926                     ) %]
3927                 [% END %]
3928                 [% IF entry.purchase_order %]
3929                     (PO: [% entry.purchase_order.name %])
3930                 [% END %]<br />
3931                 Invoice item count: [% entry.inv_item_count %]
3932                 [% IF entry.phys_item_count %]
3933                     / Physical item count: [% entry.phys_item_count %]
3934                 [% END %]
3935                 <br />
3936                 [% IF entry.cost_billed %]
3937                     Cost billed: [% entry.cost_billed %]
3938                     [% IF entry.billed_per_item %](per item)[% END %]
3939                     <br />
3940                 [% END %]
3941                 [% IF entry.actual_cost %]
3942                     Actual cost: [% entry.actual_cost %]<br />
3943                 [% END %]
3944                 [% IF entry.amount_paid %]
3945                     Amount paid: [% entry.amount_paid %]<br />
3946                 [% END %]
3947                 [% IF entry.note %]Note: [% entry.note %][% END %]
3948             </li>
3949         [% END %]
3950         [% FOR item IN invoice.items %]
3951             <li>
3952                 [% IF item.inv_item_type %]
3953                     Item Type: [% item.inv_item_type %]<br />
3954                 [% END %]
3955                 [% IF item.title %]Title/Description:
3956                     [% item.title %]<br />
3957                 [% END %]
3958                 [% IF item.author %]Author: [% item.author %]<br />[% END %]
3959                 [% IF item.purchase_order %]PO: [% item.purchase_order %]<br />[% END %]
3960                 [% IF item.note %]Note: [% item.note %]<br />[% END %]
3961                 [% IF item.cost_billed %]
3962                     Cost billed: [% item.cost_billed %]<br />
3963                 [% END %]
3964                 [% IF item.actual_cost %]
3965                     Actual cost: [% item.actual_cost %]<br />
3966                 [% END %]
3967                 [% IF item.amount_paid %]
3968                     Amount paid: [% item.amount_paid %]<br />
3969                 [% END %]
3970             </li>
3971         [% END %]
3972     </ul>
3973     <div>
3974         Amounts spent per fund:
3975         <table>
3976         [% FOR blob IN user_data %]
3977             <tr>
3978                 <th style="text-align: left;">[% blob.fund.code %] ([% blob.fund.year %]):</th>
3979                 <td>$[% blob.total %]</td>
3980             </tr>
3981         [% END %]
3982         </table>
3983     </div>
3984 </div>
3985 [% END %]$$ WHERE id = 22;
3986 INSERT INTO action_trigger.environment (event_def, path) VALUES
3987     (22, 'provider'),
3988     (22, 'provider.addresses'),
3989     (22, 'shipper'),
3990     (22, 'shipper.addresses'),
3991     (22, 'receiver'),
3992     (22, 'entries'),
3993     (22, 'entries.purchase_order'),
3994     (22, 'entries.lineitem'),
3995     (22, 'entries.lineitem.attributes'),
3996     (22, 'items')
3997 ;
3998
3999 INSERT INTO action_trigger.environment (event_def, path) VALUES 
4000   (23, 'provider.edi_default');
4001
4002 INSERT INTO action_trigger.validator (module, description) 
4003     VALUES (
4004         'Acq::PurchaseOrderEDIRequired',
4005         oils_i18n_gettext(
4006             'Acq::PurchaseOrderEDIRequired',
4007             'Purchase order is delivered via EDI',
4008             'atval',
4009             'description'
4010         )
4011     );
4012
4013 INSERT INTO action_trigger.reactor (module, description)
4014     VALUES (
4015         'GeneratePurchaseOrderJEDI',
4016         oils_i18n_gettext(
4017             'GeneratePurchaseOrderJEDI',
4018             'Creates purchase order JEDI (JSON EDI) for subsequent EDI processing',
4019             'atreact',
4020             'description'
4021         )
4022     );
4023
4024 UPDATE action_trigger.hook 
4025     SET 
4026         key = 'acqpo.activated', 
4027         passive = FALSE,
4028         description = oils_i18n_gettext(
4029             'acqpo.activated',
4030             'Purchase order was activated',
4031             'ath',
4032             'description'
4033         )
4034     WHERE key = 'format.po.jedi';
4035
4036 -- We just changed a key in action_trigger.hook.  Now redirect any
4037 -- child rows to point to the new key.  (There probably aren't any;
4038 -- this is just a precaution against possible local modifications.)
4039
4040 UPDATE action_trigger.event_definition
4041 SET hook = 'acqpo.activated'
4042 WHERE hook = 'format.po.jedi';
4043
4044 INSERT INTO action_trigger.reactor (module, description) VALUES (
4045     'AstCall', 'Possibly place a phone call with Asterisk'
4046 );
4047
4048 INSERT INTO
4049     action_trigger.event_definition (
4050         id, active, owner, name, hook, validator, reactor,
4051         cleanup_success, cleanup_failure, delay, delay_field, group_field,
4052         max_delay, granularity, usr_field, opt_in_setting, template
4053     ) VALUES (
4054         24,
4055         FALSE,
4056         1,
4057         'Telephone Overdue Notice',
4058         'checkout.due', 'NOOP_True', 'AstCall',
4059         DEFAULT, DEFAULT, '5 seconds', 'due_date', 'usr',
4060         DEFAULT, DEFAULT, DEFAULT, DEFAULT,
4061         $$
4062 [% phone = target.0.usr.day_phone | replace('[\s\-\(\)]', '') -%]
4063 [% IF phone.match('^[2-9]') %][% country = 1 %][% ELSE %][% country = '' %][% END -%]
4064 Channel: [% channel_prefix %]/[% country %][% phone %]
4065 Context: overdue-test
4066 MaxRetries: 1
4067 RetryTime: 60
4068 WaitTime: 30
4069 Extension: 10
4070 Archive: 1
4071 Set: eg_user_id=[% target.0.usr.id %]
4072 Set: items=[% target.size %]
4073 Set: titlestring=[% titles = [] %][% FOR circ IN target %][% titles.push(circ.target_copy.call_number.record.simple_record.title) %][% END %][% titles.join(". ") %]
4074 $$
4075     );
4076
4077 INSERT INTO
4078     action_trigger.environment (id, event_def, path)
4079     VALUES
4080         (DEFAULT, 24, 'target_copy.call_number.record.simple_record'),
4081         (DEFAULT, 24, 'usr')
4082     ;
4083
4084 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES (
4085         'circ.format.history.email',
4086         'circ', 
4087         oils_i18n_gettext(
4088             'circ.format.history.email',
4089             'An email has been requested for a circ history.',
4090             'ath',
4091             'description'
4092         ), 
4093         FALSE
4094     )
4095     ,(
4096         'circ.format.history.print',
4097         'circ', 
4098         oils_i18n_gettext(
4099             'circ.format.history.print',
4100             'A circ history needs to be formatted for printing.',
4101             'ath',
4102             'description'
4103         ), 
4104         FALSE
4105     )
4106     ,(
4107         'ahr.format.history.email',
4108         'ahr', 
4109         oils_i18n_gettext(
4110             'ahr.format.history.email',
4111             'An email has been requested for a hold request history.',
4112             'ath',
4113             'description'
4114         ), 
4115         FALSE
4116     )
4117     ,(
4118         'ahr.format.history.print',
4119         'ahr', 
4120         oils_i18n_gettext(
4121             'ahr.format.history.print',
4122             'A hold request history needs to be formatted for printing.',
4123             'ath',
4124             'description'
4125         ), 
4126         FALSE
4127     )
4128
4129 ;
4130
4131 INSERT INTO action_trigger.event_definition (
4132         id,
4133         active,
4134         owner,
4135         name,
4136         hook,
4137         validator,
4138         reactor,
4139         group_field,
4140         granularity,
4141         template
4142     ) VALUES (
4143         25,
4144         TRUE,
4145         1,
4146         'circ.history.email',
4147         'circ.format.history.email',
4148         'NOOP_True',
4149         'SendEmail',
4150         'usr',
4151         NULL,
4152 $$
4153 [%- USE date -%]
4154 [%- SET user = target.0.usr -%]
4155 To: [%- params.recipient_email || user.email %]
4156 From: [%- params.sender_email || default_sender %]
4157 Subject: Circulation History
4158
4159     [% FOR circ IN target %]
4160             [% helpers.get_copy_bib_basics(circ.target_copy.id).title %]
4161             Barcode: [% circ.target_copy.barcode %]
4162             Checked Out: [% date.format(helpers.format_date(circ.xact_start), '%Y-%m-%d') %]
4163             Due Date: [% date.format(helpers.format_date(circ.due_date), '%Y-%m-%d') %]
4164             Returned: [% date.format(helpers.format_date(circ.checkin_time), '%Y-%m-%d') %]
4165     [% END %]
4166 $$
4167     )
4168     ,(
4169         26,
4170         TRUE,
4171         1,
4172         'circ.history.print',
4173         'circ.format.history.print',
4174         'NOOP_True',
4175         'ProcessTemplate',
4176         'usr',
4177         'print-on-demand',
4178 $$
4179 [%- USE date -%]
4180 <div>
4181     <style> li { padding: 8px; margin 5px; }</style>
4182     <div>[% date.format %]</div>
4183     <br/>
4184
4185     [% user.family_name %], [% user.first_given_name %]
4186     <ol>
4187     [% FOR circ IN target %]
4188         <li>
4189             <div>[% helpers.get_copy_bib_basics(circ.target_copy.id).title %]</div>
4190             <div>Barcode: [% circ.target_copy.barcode %]</div>
4191             <div>Checked Out: [% date.format(helpers.format_date(circ.xact_start), '%Y-%m-%d') %]</div>
4192             <div>Due Date: [% date.format(helpers.format_date(circ.due_date), '%Y-%m-%d') %]</div>
4193             <div>Returned: [% date.format(helpers.format_date(circ.checkin_time), '%Y-%m-%d') %]</div>
4194         </li>
4195     [% END %]
4196     </ol>
4197 </div>
4198 $$
4199     )
4200     ,(
4201         27,
4202         TRUE,
4203         1,
4204         'ahr.history.email',
4205         'ahr.format.history.email',
4206         'NOOP_True',
4207         'SendEmail',
4208         'usr',
4209         NULL,
4210 $$
4211 [%- USE date -%]
4212 [%- SET user = target.0.usr -%]
4213 To: [%- params.recipient_email || user.email %]
4214 From: [%- params.sender_email || default_sender %]
4215 Subject: Hold Request History
4216
4217     [% FOR hold IN target %]
4218             [% helpers.get_copy_bib_basics(hold.current_copy.id).title %]
4219             Requested: [% date.format(helpers.format_date(hold.request_time), '%Y-%m-%d') %]
4220             [% IF hold.fulfillment_time %]Fulfilled: [% date.format(helpers.format_date(hold.fulfillment_time), '%Y-%m-%d') %][% END %]
4221     [% END %]
4222 $$
4223     )
4224     ,(
4225         28,
4226         TRUE,
4227         1,
4228         'ahr.history.print',
4229         'ahr.format.history.print',
4230         'NOOP_True',
4231         'ProcessTemplate',
4232         'usr',
4233         'print-on-demand',
4234 $$
4235 [%- USE date -%]
4236 <div>
4237     <style> li { padding: 8px; margin 5px; }</style>
4238     <div>[% date.format %]</div>
4239     <br/>
4240
4241     [% user.family_name %], [% user.first_given_name %]
4242     <ol>
4243     [% FOR hold IN target %]
4244         <li>
4245             <div>[% helpers.get_copy_bib_basics(hold.current_copy.id).title %]</div>
4246             <div>Requested: [% date.format(helpers.format_date(hold.request_time), '%Y-%m-%d') %]</div>
4247             [% IF hold.fulfillment_time %]<div>Fulfilled: [% date.format(helpers.format_date(hold.fulfillment_time), '%Y-%m-%d') %]</div>[% END %]
4248         </li>
4249     [% END %]
4250     </ol>
4251 </div>
4252 $$
4253     )
4254
4255 ;
4256
4257 INSERT INTO action_trigger.environment (
4258         event_def,
4259         path
4260     ) VALUES 
4261          ( 25, 'target_copy')
4262         ,( 25, 'usr' )
4263         ,( 26, 'target_copy' )
4264         ,( 26, 'usr' )
4265         ,( 27, 'current_copy' )
4266         ,( 27, 'usr' )
4267         ,( 28, 'current_copy' )
4268         ,( 28, 'usr' )
4269 ;
4270
4271 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES (
4272         'money.format.payment_receipt.email',
4273         'mp', 
4274         oils_i18n_gettext(
4275             'money.format.payment_receipt.email',
4276             'An email has been requested for a payment receipt.',
4277             'ath',
4278             'description'
4279         ), 
4280         FALSE
4281     )
4282     ,(
4283         'money.format.payment_receipt.print',
4284         'mp', 
4285         oils_i18n_gettext(
4286             'money.format.payment_receipt.print',
4287             'A payment receipt needs to be formatted for printing.',
4288             'ath',
4289             'description'
4290         ), 
4291         FALSE
4292     )
4293 ;
4294
4295 INSERT INTO action_trigger.event_definition (
4296         id,
4297         active,
4298         owner,
4299         name,
4300         hook,
4301         validator,
4302         reactor,
4303         group_field,
4304         granularity,
4305         template
4306     ) VALUES (
4307         29,
4308         TRUE,
4309         1,
4310         'money.payment_receipt.email',
4311         'money.format.payment_receipt.email',
4312         'NOOP_True',
4313         'SendEmail',
4314         'xact.usr',
4315         NULL,
4316 $$
4317 [%- USE date -%]
4318 [%- SET user = target.0.xact.usr -%]
4319 To: [%- params.recipient_email || user.email %]
4320 From: [%- params.sender_email || default_sender %]
4321 Subject: Payment Receipt
4322
4323 [% date.format -%]
4324 [%- SET xact_mp_hash = {} -%]
4325 [%- FOR mp IN target %][%# Template is hooked around payments, but let us make the receipt focused on transactions -%]
4326     [%- SET xact_id = mp.xact.id -%]
4327     [%- IF ! xact_mp_hash.defined( xact_id ) -%][%- xact_mp_hash.$xact_id = { 'xact' => mp.xact, 'payments' => [] } -%][%- END -%]
4328     [%- xact_mp_hash.$xact_id.payments.push(mp) -%]
4329 [%- END -%]
4330 [%- FOR xact_id IN xact_mp_hash.keys.sort -%]
4331     [%- SET xact = xact_mp_hash.$xact_id.xact %]
4332 Transaction ID: [% xact_id %]
4333     [% IF xact.circulation %][% helpers.get_copy_bib_basics(xact.circulation.target_copy).title %]
4334     [% ELSE %]Miscellaneous
4335     [% END %]
4336     Line item billings:
4337         [%- SET mb_type_hash = {} -%]
4338         [%- FOR mb IN xact.billings %][%# Group billings by their btype -%]
4339             [%- IF mb.voided == 'f' -%]
4340                 [%- SET mb_type = mb.btype.id -%]
4341                 [%- IF ! mb_type_hash.defined( mb_type ) -%][%- mb_type_hash.$mb_type = { 'sum' => 0.00, 'billings' => [] } -%][%- END -%]
4342                 [%- IF ! mb_type_hash.$mb_type.defined( 'first_ts' ) -%][%- mb_type_hash.$mb_type.first_ts = mb.billing_ts -%][%- END -%]
4343                 [%- mb_type_hash.$mb_type.last_ts = mb.billing_ts -%]
4344                 [%- mb_type_hash.$mb_type.sum = mb_type_hash.$mb_type.sum + mb.amount -%]
4345                 [%- mb_type_hash.$mb_type.billings.push( mb ) -%]
4346             [%- END -%]
4347         [%- END -%]
4348         [%- FOR mb_type IN mb_type_hash.keys.sort -%]
4349             [%- IF mb_type == 1 %][%-# Consolidated view of overdue billings -%]
4350                 $[% mb_type_hash.$mb_type.sum %] for [% mb_type_hash.$mb_type.billings.0.btype.name %] 
4351                     on [% mb_type_hash.$mb_type.first_ts %] through [% mb_type_hash.$mb_type.last_ts %]
4352             [%- ELSE -%][%# all other billings show individually %]
4353                 [% FOR mb IN mb_type_hash.$mb_type.billings %]
4354                     $[% mb.amount %] for [% mb.btype.name %] on [% mb.billing_ts %] [% mb.note %]
4355                 [% END %]
4356             [% END %]
4357         [% END %]
4358     Line item payments:
4359         [% FOR mp IN xact_mp_hash.$xact_id.payments %]
4360             Payment ID: [% mp.id %]
4361                 Paid [% mp.amount %] via [% SWITCH mp.payment_type -%]
4362                     [% CASE "cash_payment" %]cash
4363                     [% CASE "check_payment" %]check
4364                     [% CASE "credit_card_payment" %]credit card (
4365                         [%- SET cc_chunks = mp.credit_card_payment.cc_number.replace(' ','').chunk(4); -%]
4366                         [%- cc_chunks.slice(0, -1+cc_chunks.max).join.replace('\S','X') -%] 
4367                         [% cc_chunks.last -%]
4368                         exp [% mp.credit_card_payment.expire_month %]/[% mp.credit_card_payment.expire_year -%]
4369                     )
4370                     [% CASE "credit_payment" %]credit
4371                     [% CASE "forgive_payment" %]forgiveness
4372                     [% CASE "goods_payment" %]goods
4373                     [% CASE "work_payment" %]work
4374                 [%- END %] on [% mp.payment_ts %] [% mp.note %]
4375         [% END %]
4376 [% END %]
4377 $$
4378     )
4379     ,(
4380         30,
4381         TRUE,
4382         1,
4383         'money.payment_receipt.print',
4384         'money.format.payment_receipt.print',
4385         'NOOP_True',
4386         'ProcessTemplate',
4387         'xact.usr',
4388         'print-on-demand',
4389 $$
4390 [%- USE date -%][%- SET user = target.0.xact.usr -%]
4391 <div style="li { padding: 8px; margin 5px; }">
4392     <div>[% date.format %]</div><br/>
4393     <ol>
4394     [% SET xact_mp_hash = {} %]
4395     [% FOR mp IN target %][%# Template is hooked around payments, but let us make the receipt focused on transactions %]
4396         [% SET xact_id = mp.xact.id %]
4397         [% IF ! xact_mp_hash.defined( xact_id ) %][% xact_mp_hash.$xact_id = { 'xact' => mp.xact, 'payments' => [] } %][% END %]
4398         [% xact_mp_hash.$xact_id.payments.push(mp) %]
4399     [% END %]
4400     [% FOR xact_id IN xact_mp_hash.keys.sort %]
4401         [% SET xact = xact_mp_hash.$xact_id.xact %]
4402         <li>Transaction ID: [% xact_id %]
4403             [% IF xact.circulation %][% helpers.get_copy_bib_basics(xact.circulation.target_copy).title %]
4404             [% ELSE %]Miscellaneous
4405             [% END %]
4406             Line item billings:<ol>
4407                 [% SET mb_type_hash = {} %]
4408                 [% FOR mb IN xact.billings %][%# Group billings by their btype %]
4409                     [% IF mb.voided == 'f' %]
4410                         [% SET mb_type = mb.btype.id %]
4411                         [% IF ! mb_type_hash.defined( mb_type ) %][% mb_type_hash.$mb_type = { 'sum' => 0.00, 'billings' => [] } %][% END %]
4412                         [% IF ! mb_type_hash.$mb_type.defined( 'first_ts' ) %][% mb_type_hash.$mb_type.first_ts = mb.billing_ts %][% END %]
4413                         [% mb_type_hash.$mb_type.last_ts = mb.billing_ts %]
4414                         [% mb_type_hash.$mb_type.sum = mb_type_hash.$mb_type.sum + mb.amount %]
4415                         [% mb_type_hash.$mb_type.billings.push( mb ) %]
4416                     [% END %]
4417                 [% END %]
4418                 [% FOR mb_type IN mb_type_hash.keys.sort %]
4419                     <li>[% IF mb_type == 1 %][%# Consolidated view of overdue billings %]
4420                         $[% mb_type_hash.$mb_type.sum %] for [% mb_type_hash.$mb_type.billings.0.btype.name %] 
4421                             on [% mb_type_hash.$mb_type.first_ts %] through [% mb_type_hash.$mb_type.last_ts %]
4422                     [% ELSE %][%# all other billings show individually %]
4423                         [% FOR mb IN mb_type_hash.$mb_type.billings %]
4424                             $[% mb.amount %] for [% mb.btype.name %] on [% mb.billing_ts %] [% mb.note %]
4425                         [% END %]
4426                     [% END %]</li>
4427                 [% END %]
4428             </ol>
4429             Line item payments:<ol>
4430                 [% FOR mp IN xact_mp_hash.$xact_id.payments %]
4431                     <li>Payment ID: [% mp.id %]
4432                         Paid [% mp.amount %] via [% SWITCH mp.payment_type -%]
4433                             [% CASE "cash_payment" %]cash
4434                             [% CASE "check_payment" %]check
4435                             [% CASE "credit_card_payment" %]credit card (
4436                                 [%- SET cc_chunks = mp.credit_card_payment.cc_number.replace(' ','').chunk(4); -%]
4437                                 [%- cc_chunks.slice(0, -1+cc_chunks.max).join.replace('\S','X') -%] 
4438                                 [% cc_chunks.last -%]
4439                                 exp [% mp.credit_card_payment.expire_month %]/[% mp.credit_card_payment.expire_year -%]
4440                             )
4441                             [% CASE "credit_payment" %]credit
4442                             [% CASE "forgive_payment" %]forgiveness
4443                             [% CASE "goods_payment" %]goods
4444                             [% CASE "work_payment" %]work
4445                         [%- END %] on [% mp.payment_ts %] [% mp.note %]
4446                     </li>
4447                 [% END %]
4448             </ol>
4449         </li>
4450     [% END %]
4451     </ol>
4452 </div>
4453 $$
4454     )
4455 ;
4456
4457 INSERT INTO action_trigger.environment (
4458         event_def,
4459         path
4460     ) VALUES -- for fleshing mp objects
4461          ( 29, 'xact')
4462         ,( 29, 'xact.usr')
4463         ,( 29, 'xact.grocery' )
4464         ,( 29, 'xact.circulation' )
4465         ,( 29, 'xact.summary' )
4466         ,( 30, 'xact')
4467         ,( 30, 'xact.usr')
4468         ,( 30, 'xact.grocery' )
4469         ,( 30, 'xact.circulation' )
4470         ,( 30, 'xact.summary' )
4471 ;
4472
4473 INSERT INTO action_trigger.cleanup ( module, description ) VALUES (
4474     'DeleteTempBiblioBucket',
4475     oils_i18n_gettext(
4476         'DeleteTempBiblioBucket',
4477         'Deletes a cbreb object used as a target if it has a btype of "temp"',
4478         'atclean',
4479         'description'
4480     )
4481 );
4482
4483 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES (
4484         'biblio.format.record_entry.email',
4485         'cbreb', 
4486         oils_i18n_gettext(
4487             'biblio.format.record_entry.email',
4488             'An email has been requested for one or more biblio record entries.',
4489             'ath',
4490             'description'
4491         ), 
4492         FALSE
4493     )
4494     ,(
4495         'biblio.format.record_entry.print',
4496         'cbreb', 
4497         oils_i18n_gettext(
4498             'biblio.format.record_entry.print',
4499             'One or more biblio record entries need to be formatted for printing.',
4500             'ath',
4501             'description'
4502         ), 
4503         FALSE
4504     )
4505 ;
4506
4507 INSERT INTO action_trigger.event_definition (
4508         id,
4509         active,
4510         owner,
4511         name,
4512         hook,
4513         validator,
4514         reactor,
4515         cleanup_success,
4516         cleanup_failure,
4517         group_field,
4518         granularity,
4519         template
4520     ) VALUES (
4521         31,
4522         TRUE,
4523         1,
4524         'biblio.record_entry.email',
4525         'biblio.format.record_entry.email',
4526         'NOOP_True',
4527         'SendEmail',
4528         'DeleteTempBiblioBucket',
4529         'DeleteTempBiblioBucket',
4530         'owner',
4531         NULL,
4532 $$
4533 [%- USE date -%]
4534 [%- SET user = target.0.owner -%]
4535 To: [%- params.recipient_email || user.email %]
4536 From: [%- params.sender_email || default_sender %]
4537 Subject: Bibliographic Records
4538
4539     [% FOR cbreb IN target %]
4540     [% FOR cbrebi IN cbreb.items %]
4541         Bib ID# [% cbrebi.target_biblio_record_entry.id %] ISBN: [% crebi.target_biblio_record_entry.simple_record.isbn %]
4542         Title: [% cbrebi.target_biblio_record_entry.simple_record.title %]
4543         Author: [% cbrebi.target_biblio_record_entry.simple_record.author %]
4544         Publication Year: [% cbrebi.target_biblio_record_entry.simple_record.pubdate %]
4545
4546     [% END %]
4547     [% END %]
4548 $$
4549     )
4550     ,(
4551         32,
4552         TRUE,
4553         1,
4554         'biblio.record_entry.print',
4555         'biblio.format.record_entry.print',
4556         'NOOP_True',
4557         'ProcessTemplate',
4558         'DeleteTempBiblioBucket',
4559         'DeleteTempBiblioBucket',
4560         'owner',
4561         'print-on-demand',
4562 $$
4563 [%- USE date -%]
4564 <div>
4565     <style> li { padding: 8px; margin 5px; }</style>
4566     <ol>
4567     [% FOR cbreb IN target %]
4568     [% FOR cbrebi IN cbreb.items %]
4569         <li>Bib ID# [% cbrebi.target_biblio_record_entry.id %] ISBN: [% crebi.target_biblio_record_entry.simple_record.isbn %]<br />
4570             Title: [% cbrebi.target_biblio_record_entry.simple_record.title %]<br />
4571             Author: [% cbrebi.target_biblio_record_entry.simple_record.author %]<br />
4572             Publication Year: [% cbrebi.target_biblio_record_entry.simple_record.pubdate %]
4573         </li>
4574     [% END %]
4575     [% END %]
4576     </ol>
4577 </div>
4578 $$
4579     )
4580 ;
4581
4582 INSERT INTO action_trigger.environment (
4583         event_def,
4584         path
4585     ) VALUES -- for fleshing cbreb objects
4586          ( 31, 'owner' )
4587         ,( 31, 'items' )
4588         ,( 31, 'items.target_biblio_record_entry' )
4589         ,( 31, 'items.target_biblio_record_entry.simple_record' )
4590         ,( 31, 'items.target_biblio_record_entry.call_numbers' )
4591         ,( 31, 'items.target_biblio_record_entry.fixed_fields' )
4592         ,( 31, 'items.target_biblio_record_entry.notes' )
4593         ,( 31, 'items.target_biblio_record_entry.full_record_entries' )
4594         ,( 32, 'owner' )
4595         ,( 32, 'items' )
4596         ,( 32, 'items.target_biblio_record_entry' )
4597         ,( 32, 'items.target_biblio_record_entry.simple_record' )
4598         ,( 32, 'items.target_biblio_record_entry.call_numbers' )
4599         ,( 32, 'items.target_biblio_record_entry.fixed_fields' )
4600         ,( 32, 'items.target_biblio_record_entry.notes' )
4601         ,( 32, 'items.target_biblio_record_entry.full_record_entries' )
4602 ;
4603
4604 INSERT INTO action_trigger.environment (
4605         event_def,
4606         path
4607     ) VALUES -- for fleshing mp objects
4608          ( 29, 'credit_card_payment')
4609         ,( 29, 'xact.billings')
4610         ,( 29, 'xact.billings.btype')
4611         ,( 30, 'credit_card_payment')
4612         ,( 30, 'xact.billings')
4613         ,( 30, 'xact.billings.btype')
4614 ;
4615
4616 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES 
4617     (   'circ.format.missing_pieces.slip.print',
4618         'circ', 
4619         oils_i18n_gettext(
4620             'circ.format.missing_pieces.slip.print',
4621             'A missing pieces slip needs to be formatted for printing.',
4622             'ath',
4623             'description'
4624         ), 
4625         FALSE
4626     )
4627     ,(  'circ.format.missing_pieces.letter.print',
4628         'circ', 
4629         oils_i18n_gettext(
4630             'circ.format.missing_pieces.letter.print',
4631             'A missing pieces patron letter needs to be formatted for printing.',
4632             'ath',
4633             'description'
4634         ), 
4635         FALSE
4636     )
4637 ;
4638
4639 INSERT INTO action_trigger.event_definition (
4640         id,
4641         active,
4642         owner,
4643         name,
4644         hook,
4645         validator,
4646         reactor,
4647         group_field,
4648         granularity,
4649         template
4650     ) VALUES (
4651         33,
4652         TRUE,
4653         1,
4654         'circ.missing_pieces.slip.print',
4655         'circ.format.missing_pieces.slip.print',
4656         'NOOP_True',
4657         'ProcessTemplate',
4658         'usr',
4659         'print-on-demand',
4660 $$
4661 [%- USE date -%]
4662 [%- SET user = target.0.usr -%]
4663 <div style="li { padding: 8px; margin 5px; }">
4664     <div>[% date.format %]</div><br/>
4665     Missing pieces for:
4666     <ol>
4667     [% FOR circ IN target %]
4668         <li>Barcode: [% circ.target_copy.barcode %] Transaction ID: [% circ.id %] Due: [% circ.due_date.format %]<br />
4669             [% helpers.get_copy_bib_basics(circ.target_copy.id).title %]
4670         </li>
4671     [% END %]
4672     </ol>
4673 </div>
4674 $$
4675     )
4676     ,(
4677         34,
4678         TRUE,
4679         1,
4680         'circ.missing_pieces.letter.print',
4681         'circ.format.missing_pieces.letter.print',
4682         'NOOP_True',
4683         'ProcessTemplate',
4684         'usr',
4685         'print-on-demand',
4686 $$
4687 [%- USE date -%]
4688 [%- SET user = target.0.usr -%]
4689 [% date.format %]
4690 Dear [% user.prefix %] [% user.first_given_name %] [% user.family_name %],
4691
4692 We are missing pieces for the following returned items:
4693 [% FOR circ IN target %]
4694 Barcode: [% circ.target_copy.barcode %] Transaction ID: [% circ.id %] Due: [% circ.due_date.format %]
4695 [% helpers.get_copy_bib_basics(circ.target_copy.id).title %]
4696 [% END %]
4697
4698 Please return these pieces as soon as possible.
4699
4700 Thanks!
4701
4702 Library Staff
4703 $$
4704     )
4705 ;
4706
4707 INSERT INTO action_trigger.environment (
4708         event_def,
4709         path
4710     ) VALUES -- for fleshing circ objects
4711          ( 33, 'usr')
4712         ,( 33, 'target_copy')
4713         ,( 33, 'target_copy.circ_lib')
4714         ,( 33, 'target_copy.circ_lib.mailing_address')
4715         ,( 33, 'target_copy.circ_lib.billing_address')
4716         ,( 33, 'target_copy.call_number')
4717         ,( 33, 'target_copy.call_number.owning_lib')
4718         ,( 33, 'target_copy.call_number.owning_lib.mailing_address')
4719         ,( 33, 'target_copy.call_number.owning_lib.billing_address')
4720         ,( 33, 'circ_lib')
4721         ,( 33, 'circ_lib.mailing_address')
4722         ,( 33, 'circ_lib.billing_address')
4723         ,( 34, 'usr')
4724         ,( 34, 'target_copy')
4725         ,( 34, 'target_copy.circ_lib')
4726         ,( 34, 'target_copy.circ_lib.mailing_address')
4727         ,( 34, 'target_copy.circ_lib.billing_address')
4728         ,( 34, 'target_copy.call_number')
4729         ,( 34, 'target_copy.call_number.owning_lib')
4730         ,( 34, 'target_copy.call_number.owning_lib.mailing_address')
4731         ,( 34, 'target_copy.call_number.owning_lib.billing_address')
4732         ,( 34, 'circ_lib')
4733         ,( 34, 'circ_lib.mailing_address')
4734         ,( 34, 'circ_lib.billing_address')
4735 ;
4736
4737 INSERT INTO action_trigger.hook (key,core_type,description,passive) 
4738     VALUES (   
4739         'ahr.format.pull_list',
4740         'ahr', 
4741         oils_i18n_gettext(
4742             'ahr.format.pull_list',
4743             'Format holds pull list for printing',
4744             'ath',
4745             'description'
4746         ), 
4747         FALSE
4748     );
4749
4750 INSERT INTO action_trigger.event_definition (
4751         id,
4752         active,
4753         owner,
4754         name,
4755         hook,
4756         validator,
4757         reactor,
4758         group_field,
4759         granularity,
4760         template
4761     ) VALUES (
4762         35,
4763         TRUE,
4764         1,
4765         'Holds Pull List',
4766         'ahr.format.pull_list',
4767         'NOOP_True',
4768         'ProcessTemplate',
4769         'pickup_lib',
4770         'print-on-demand',
4771 $$
4772 [%- USE date -%]
4773 <style>
4774     table { border-collapse: collapse; } 
4775     td { padding: 5px; border-bottom: 1px solid #888; } 
4776     th { font-weight: bold; }
4777 </style>
4778 [% 
4779     # Sort the holds into copy-location buckets
4780     # In the main print loop, sort each bucket by callnumber before printing
4781     SET holds_list = [];
4782     SET loc_data = [];
4783     SET current_location = target.0.current_copy.location.id;
4784     FOR hold IN target;
4785         IF current_location != hold.current_copy.location.id;
4786             SET current_location = hold.current_copy.location.id;
4787             holds_list.push(loc_data);
4788             SET loc_data = [];
4789         END;
4790         SET hold_data = {
4791             'hold' => hold,
4792             'callnumber' => hold.current_copy.call_number.label
4793         };
4794         loc_data.push(hold_data);
4795     END;
4796     holds_list.push(loc_data)
4797 %]
4798 <table>
4799     <thead>
4800         <tr>
4801             <th>Title</th>
4802             <th>Author</th>
4803             <th>Shelving Location</th>
4804             <th>Call Number</th>
4805             <th>Barcode</th>
4806             <th>Patron</th>
4807         </tr>
4808     </thead>
4809     <tbody>
4810     [% FOR loc_data IN holds_list  %]
4811         [% FOR hold_data IN loc_data.sort('callnumber') %]
4812             [% 
4813                 SET hold = hold_data.hold;
4814                 SET copy_data = helpers.get_copy_bib_basics(hold.current_copy.id);
4815             %]
4816             <tr>
4817                 <td>[% copy_data.title | truncate %]</td>
4818                 <td>[% copy_data.author | truncate %]</td>
4819                 <td>[% hold.current_copy.location.name %]</td>
4820                 <td>[% hold.current_copy.call_number.label %]</td>
4821                 <td>[% hold.current_copy.barcode %]</td>
4822                 <td>[% hold.usr.card.barcode %]</td>
4823             </tr>
4824         [% END %]
4825     [% END %]
4826     <tbody>
4827 </table>
4828 $$
4829 );
4830
4831 INSERT INTO action_trigger.environment (
4832         event_def,
4833         path
4834     ) VALUES
4835         (35, 'current_copy.location'),
4836         (35, 'current_copy.call_number'),
4837         (35, 'usr.card'),
4838         (35, 'pickup_lib')
4839 ;
4840
4841 INSERT INTO action_trigger.validator (module, description) VALUES ( 
4842     'HoldIsCancelled', 
4843     oils_i18n_gettext( 
4844         'HoldIsCancelled', 
4845         'Check whether a hold request is cancelled.', 
4846         'atval', 
4847         'description' 
4848     ) 
4849 );
4850
4851 -- Create the query schema, and the tables and views therein
4852
4853 DROP SCHEMA IF EXISTS sql CASCADE;
4854 DROP SCHEMA IF EXISTS query CASCADE;
4855
4856 CREATE SCHEMA query;
4857
4858 CREATE TABLE query.datatype (
4859         id              SERIAL            PRIMARY KEY,
4860         datatype_name   TEXT              NOT NULL UNIQUE,
4861         is_numeric      BOOL              NOT NULL DEFAULT FALSE,
4862         is_composite    BOOL              NOT NULL DEFAULT FALSE,
4863         CONSTRAINT qdt_comp_not_num CHECK
4864         ( is_numeric IS FALSE OR is_composite IS FALSE )
4865 );
4866
4867 -- Define the most common datatypes in query.datatype.  Note that none of
4868 -- these stock datatypes specifies a width or precision.
4869
4870 -- Also: set the sequence for query.datatype to 1000, leaving plenty of
4871 -- room for more stock datatypes if we ever want to add them.
4872
4873 SELECT setval( 'query.datatype_id_seq', 1000 );
4874
4875 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4876   VALUES (1, 'SMALLINT', true);
4877  
4878 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4879   VALUES (2, 'INTEGER', true);
4880  
4881 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4882   VALUES (3, 'BIGINT', true);
4883  
4884 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4885   VALUES (4, 'DECIMAL', true);
4886  
4887 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4888   VALUES (5, 'NUMERIC', true);
4889  
4890 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4891   VALUES (6, 'REAL', true);
4892  
4893 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4894   VALUES (7, 'DOUBLE PRECISION', true);
4895  
4896 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4897   VALUES (8, 'SERIAL', true);
4898  
4899 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4900   VALUES (9, 'BIGSERIAL', true);
4901  
4902 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4903   VALUES (10, 'MONEY', false);
4904  
4905 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4906   VALUES (11, 'VARCHAR', false);
4907  
4908 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4909   VALUES (12, 'CHAR', false);
4910  
4911 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4912   VALUES (13, 'TEXT', false);
4913  
4914 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4915   VALUES (14, '"char"', false);
4916  
4917 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4918   VALUES (15, 'NAME', false);
4919  
4920 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4921   VALUES (16, 'BYTEA', false);
4922  
4923 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4924   VALUES (17, 'TIMESTAMP WITHOUT TIME ZONE', false);
4925  
4926 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4927   VALUES (18, 'TIMESTAMP WITH TIME ZONE', false);
4928  
4929 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4930   VALUES (19, 'DATE', false);
4931  
4932 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4933   VALUES (20, 'TIME WITHOUT TIME ZONE', false);
4934  
4935 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4936   VALUES (21, 'TIME WITH TIME ZONE', false);
4937  
4938 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4939   VALUES (22, 'INTERVAL', false);
4940  
4941 INSERT INTO query.datatype (id, datatype_name, is_numeric )
4942   VALUES (23, 'BOOLEAN', false);
4943  
4944 CREATE TABLE query.subfield (
4945         id              SERIAL            PRIMARY KEY,
4946         composite_type  INT               NOT NULL
4947                                           REFERENCES query.datatype(id)
4948                                           ON DELETE CASCADE
4949                                           DEFERRABLE INITIALLY DEFERRED,
4950         seq_no          INT               NOT NULL
4951                                           CONSTRAINT qsf_pos_seq_no
4952                                           CHECK( seq_no > 0 ),
4953         subfield_type   INT               NOT NULL
4954                                           REFERENCES query.datatype(id)
4955                                           DEFERRABLE INITIALLY DEFERRED,
4956         CONSTRAINT qsf_datatype_seq_no UNIQUE (composite_type, seq_no)
4957 );
4958
4959 CREATE TABLE query.function_sig (
4960         id              SERIAL            PRIMARY KEY,
4961         function_name   TEXT              NOT NULL,
4962         return_type     INT               REFERENCES query.datatype(id)
4963                                           DEFERRABLE INITIALLY DEFERRED,
4964         is_aggregate    BOOL              NOT NULL DEFAULT FALSE,
4965         CONSTRAINT qfd_rtn_or_aggr CHECK
4966         ( return_type IS NULL OR is_aggregate = FALSE )
4967 );
4968
4969 CREATE INDEX query_function_sig_name_idx 
4970         ON query.function_sig (function_name);
4971
4972 CREATE TABLE query.function_param_def (
4973         id              SERIAL            PRIMARY KEY,
4974         function_id     INT               NOT NULL
4975                                           REFERENCES query.function_sig( id )
4976                                           ON DELETE CASCADE
4977                                           DEFERRABLE INITIALLY DEFERRED,
4978         seq_no          INT               NOT NULL
4979                                           CONSTRAINT qfpd_pos_seq_no CHECK
4980                                           ( seq_no > 0 ),
4981         datatype        INT               NOT NULL
4982                                           REFERENCES query.datatype( id )
4983                                           DEFERRABLE INITIALLY DEFERRED,
4984         CONSTRAINT qfpd_function_param_seq UNIQUE (function_id, seq_no)
4985 );
4986
4987 CREATE TABLE  query.stored_query (
4988         id            SERIAL         PRIMARY KEY,
4989         type          TEXT           NOT NULL CONSTRAINT query_type CHECK
4990                                      ( type IN ( 'SELECT', 'UNION', 'INTERSECT', 'EXCEPT' ) ),
4991         use_all       BOOLEAN        NOT NULL DEFAULT FALSE,
4992         use_distinct  BOOLEAN        NOT NULL DEFAULT FALSE,
4993         from_clause   INT            , --REFERENCES query.from_clause
4994                                      --DEFERRABLE INITIALLY DEFERRED,
4995         where_clause  INT            , --REFERENCES query.expression
4996                                      --DEFERRABLE INITIALLY DEFERRED,
4997         having_clause INT            , --REFERENCES query.expression
4998                                      --DEFERRABLE INITIALLY DEFERRED
4999         limit_count   INT            , --REFERENCES query.expression( id )
5000                                      --DEFERRABLE INITIALLY DEFERRED,
5001         offset_count  INT            --REFERENCES query.expression( id )
5002                                      --DEFERRABLE INITIALLY DEFERRED
5003 );
5004
5005 -- (Foreign keys to be defined later after other tables are created)
5006
5007 CREATE TABLE query.query_sequence (
5008         id              SERIAL            PRIMARY KEY,
5009         parent_query    INT               NOT NULL
5010                                           REFERENCES query.stored_query
5011                                                                           ON DELETE CASCADE
5012                                                                           DEFERRABLE INITIALLY DEFERRED,
5013         seq_no          INT               NOT NULL,
5014         child_query     INT               NOT NULL
5015                                           REFERENCES query.stored_query
5016                                                                           ON DELETE CASCADE
5017                                                                           DEFERRABLE INITIALLY DEFERRED,
5018         CONSTRAINT query_query_seq UNIQUE( parent_query, seq_no )
5019 );
5020
5021 CREATE TABLE query.bind_variable (
5022         name          TEXT             PRIMARY KEY,
5023         type          TEXT             NOT NULL
5024                                            CONSTRAINT bind_variable_type CHECK
5025                                            ( type in ( 'string', 'number', 'string_list', 'number_list' )),
5026         description   TEXT             NOT NULL,
5027         default_value TEXT,            -- to be encoded in JSON
5028         label         TEXT             NOT NULL
5029 );
5030
5031 CREATE TABLE query.expression (
5032         id            SERIAL        PRIMARY KEY,
5033         type          TEXT          NOT NULL CONSTRAINT expression_type CHECK
5034                                     ( type IN (
5035                                     'xbet',    -- between
5036                                     'xbind',   -- bind variable
5037                                     'xbool',   -- boolean
5038                                     'xcase',   -- case
5039                                     'xcast',   -- cast
5040                                     'xcol',    -- column
5041                                     'xex',     -- exists
5042                                     'xfunc',   -- function
5043                                     'xin',     -- in
5044                                     'xisnull', -- is null
5045                                     'xnull',   -- null
5046                                     'xnum',    -- number
5047                                     'xop',     -- operator
5048                                     'xser',    -- series
5049                                     'xstr',    -- string
5050                                     'xsubq'    -- subquery
5051                                                                 ) ),
5052         parenthesize  BOOL          NOT NULL DEFAULT FALSE,
5053         parent_expr   INT           REFERENCES query.expression
5054                                     ON DELETE CASCADE
5055                                     DEFERRABLE INITIALLY DEFERRED,
5056         seq_no        INT           NOT NULL DEFAULT 1,
5057         literal       TEXT,
5058         table_alias   TEXT,
5059         column_name   TEXT,
5060         left_operand  INT           REFERENCES query.expression
5061                                     DEFERRABLE INITIALLY DEFERRED,
5062         operator      TEXT,
5063         right_operand INT           REFERENCES query.expression
5064                                     DEFERRABLE INITIALLY DEFERRED,
5065         function_id   INT           REFERENCES query.function_sig
5066                                     DEFERRABLE INITIALLY DEFERRED,
5067         subquery      INT           REFERENCES query.stored_query
5068                                     DEFERRABLE INITIALLY DEFERRED,
5069         cast_type     INT           REFERENCES query.datatype
5070                                     DEFERRABLE INITIALLY DEFERRED,
5071         negate        BOOL          NOT NULL DEFAULT FALSE,
5072         bind_variable TEXT          REFERENCES query.bind_variable
5073                                         DEFERRABLE INITIALLY DEFERRED
5074 );
5075
5076 CREATE UNIQUE INDEX query_expr_parent_seq
5077         ON query.expression( parent_expr, seq_no )
5078         WHERE parent_expr IS NOT NULL;
5079
5080 -- Due to some circular references, the following foreign key definitions
5081 -- had to be deferred until query.expression existed:
5082
5083 ALTER TABLE query.stored_query
5084         ADD FOREIGN KEY ( where_clause )
5085         REFERENCES query.expression( id )
5086         DEFERRABLE INITIALLY DEFERRED;
5087
5088 ALTER TABLE query.stored_query
5089         ADD FOREIGN KEY ( having_clause )
5090         REFERENCES query.expression( id )
5091         DEFERRABLE INITIALLY DEFERRED;
5092
5093 ALTER TABLE query.stored_query
5094     ADD FOREIGN KEY ( limit_count )
5095     REFERENCES query.expression( id )
5096     DEFERRABLE INITIALLY DEFERRED;
5097
5098 ALTER TABLE query.stored_query
5099     ADD FOREIGN KEY ( offset_count )
5100     REFERENCES query.expression( id )
5101     DEFERRABLE INITIALLY DEFERRED;
5102
5103 CREATE TABLE query.case_branch (
5104         id            SERIAL        PRIMARY KEY,
5105         parent_expr   INT           NOT NULL REFERENCES query.expression
5106                                     ON DELETE CASCADE
5107                                     DEFERRABLE INITIALLY DEFERRED,
5108         seq_no        INT           NOT NULL,
5109         condition     INT           REFERENCES query.expression
5110                                     DEFERRABLE INITIALLY DEFERRED,
5111         result        INT           NOT NULL REFERENCES query.expression
5112                                     DEFERRABLE INITIALLY DEFERRED,
5113         CONSTRAINT case_branch_parent_seq UNIQUE (parent_expr, seq_no)
5114 );
5115
5116 CREATE TABLE query.from_relation (
5117         id               SERIAL        PRIMARY KEY,
5118         type             TEXT          NOT NULL CONSTRAINT relation_type CHECK (
5119                                            type IN ( 'RELATION', 'SUBQUERY', 'FUNCTION' ) ),
5120         table_name       TEXT,
5121         class_name       TEXT,
5122         subquery         INT           REFERENCES query.stored_query,
5123         function_call    INT           REFERENCES query.expression,
5124         table_alias      TEXT,
5125         parent_relation  INT           REFERENCES query.from_relation
5126                                        ON DELETE CASCADE
5127                                        DEFERRABLE INITIALLY DEFERRED,
5128         seq_no           INT           NOT NULL DEFAULT 1,
5129         join_type        TEXT          CONSTRAINT good_join_type CHECK (
5130                                            join_type IS NULL OR join_type IN
5131                                            ( 'INNER', 'LEFT', 'RIGHT', 'FULL' )
5132                                        ),
5133         on_clause        INT           REFERENCES query.expression
5134                                        DEFERRABLE INITIALLY DEFERRED,
5135         CONSTRAINT join_or_core CHECK (
5136         ( parent_relation IS NULL AND join_type IS NULL
5137           AND on_clause IS NULL )
5138         OR
5139         ( parent_relation IS NOT NULL AND join_type IS NOT NULL
5140           AND on_clause IS NOT NULL )
5141         )
5142 );
5143
5144 CREATE UNIQUE INDEX from_parent_seq
5145         ON query.from_relation( parent_relation, seq_no )
5146         WHERE parent_relation IS NOT NULL;
5147
5148 -- The following foreign key had to be deferred until
5149 -- query.from_relation existed
5150
5151 ALTER TABLE query.stored_query
5152         ADD FOREIGN KEY (from_clause)
5153         REFERENCES query.from_relation
5154         DEFERRABLE INITIALLY DEFERRED;
5155
5156 CREATE TABLE query.record_column (
5157         id            SERIAL            PRIMARY KEY,
5158         from_relation INT               NOT NULL REFERENCES query.from_relation
5159                                         ON DELETE CASCADE
5160                                         DEFERRABLE INITIALLY DEFERRED,
5161         seq_no        INT               NOT NULL,
5162         column_name   TEXT              NOT NULL,
5163         column_type   INT               NOT NULL REFERENCES query.datatype
5164                                         ON DELETE CASCADE
5165                                                                         DEFERRABLE INITIALLY DEFERRED,
5166         CONSTRAINT column_sequence UNIQUE (from_relation, seq_no)
5167 );
5168
5169 CREATE TABLE query.select_item (
5170         id               SERIAL         PRIMARY KEY,
5171         stored_query     INT            NOT NULL REFERENCES query.stored_query
5172                                         ON DELETE CASCADE
5173                                         DEFERRABLE INITIALLY DEFERRED,
5174         seq_no           INT            NOT NULL,
5175         expression       INT            NOT NULL REFERENCES query.expression
5176                                         DEFERRABLE INITIALLY DEFERRED,
5177         column_alias     TEXT,
5178         grouped_by       BOOL           NOT NULL DEFAULT FALSE,
5179         CONSTRAINT select_sequence UNIQUE( stored_query, seq_no )
5180 );
5181
5182 CREATE TABLE query.order_by_item (
5183         id               SERIAL         PRIMARY KEY,
5184         stored_query     INT            NOT NULL REFERENCES query.stored_query
5185                                         ON DELETE CASCADE
5186                                         DEFERRABLE INITIALLY DEFERRED,
5187         seq_no           INT            NOT NULL,
5188         expression       INT            NOT NULL REFERENCES query.expression
5189                                         ON DELETE CASCADE
5190                                         DEFERRABLE INITIALLY DEFERRED,
5191         CONSTRAINT order_by_sequence UNIQUE( stored_query, seq_no )
5192 );
5193
5194 ------------------------------------------------------------
5195 -- Create updatable views for different kinds of expressions
5196 ------------------------------------------------------------
5197
5198 -- Create updatable view for BETWEEN expressions
5199
5200 CREATE OR REPLACE VIEW query.expr_xbet AS
5201     SELECT
5202                 id,
5203                 parenthesize,
5204                 parent_expr,
5205                 seq_no,
5206                 left_operand,
5207                 negate
5208     FROM
5209         query.expression
5210     WHERE
5211         type = 'xbet';
5212
5213 CREATE OR REPLACE RULE query_expr_xbet_insert_rule AS
5214     ON INSERT TO query.expr_xbet
5215     DO INSTEAD
5216     INSERT INTO query.expression (
5217                 id,
5218                 type,
5219                 parenthesize,
5220                 parent_expr,
5221                 seq_no,
5222                 left_operand,
5223                 negate
5224     ) VALUES (
5225         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5226         'xbet',
5227         COALESCE(NEW.parenthesize, FALSE),
5228         NEW.parent_expr,
5229         COALESCE(NEW.seq_no, 1),
5230                 NEW.left_operand,
5231                 COALESCE(NEW.negate, false)
5232     );
5233
5234 CREATE OR REPLACE RULE query_expr_xbet_update_rule AS
5235     ON UPDATE TO query.expr_xbet
5236     DO INSTEAD
5237     UPDATE query.expression SET
5238         id = NEW.id,
5239         parenthesize = NEW.parenthesize,
5240         parent_expr = NEW.parent_expr,
5241         seq_no = NEW.seq_no,
5242                 left_operand = NEW.left_operand,
5243                 negate = NEW.negate
5244     WHERE
5245         id = OLD.id;
5246
5247 CREATE OR REPLACE RULE query_expr_xbet_delete_rule AS
5248     ON DELETE TO query.expr_xbet
5249     DO INSTEAD
5250     DELETE FROM query.expression WHERE id = OLD.id;
5251
5252 -- Create updatable view for bind variable expressions
5253
5254 CREATE OR REPLACE VIEW query.expr_xbind AS
5255     SELECT
5256                 id,
5257                 parenthesize,
5258                 parent_expr,
5259                 seq_no,
5260                 bind_variable
5261     FROM
5262         query.expression
5263     WHERE
5264         type = 'xbind';
5265
5266 CREATE OR REPLACE RULE query_expr_xbind_insert_rule AS
5267     ON INSERT TO query.expr_xbind
5268     DO INSTEAD
5269     INSERT INTO query.expression (
5270                 id,
5271                 type,
5272                 parenthesize,
5273                 parent_expr,
5274                 seq_no,
5275                 bind_variable
5276     ) VALUES (
5277         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5278         'xbind',
5279         COALESCE(NEW.parenthesize, FALSE),
5280         NEW.parent_expr,
5281         COALESCE(NEW.seq_no, 1),
5282                 NEW.bind_variable
5283     );
5284
5285 CREATE OR REPLACE RULE query_expr_xbind_update_rule AS
5286     ON UPDATE TO query.expr_xbind
5287     DO INSTEAD
5288     UPDATE query.expression SET
5289         id = NEW.id,
5290         parenthesize = NEW.parenthesize,
5291         parent_expr = NEW.parent_expr,
5292         seq_no = NEW.seq_no,
5293                 bind_variable = NEW.bind_variable
5294     WHERE
5295         id = OLD.id;
5296
5297 CREATE OR REPLACE RULE query_expr_xbind_delete_rule AS
5298     ON DELETE TO query.expr_xbind
5299     DO INSTEAD
5300     DELETE FROM query.expression WHERE id = OLD.id;
5301
5302 -- Create updatable view for boolean expressions
5303
5304 CREATE OR REPLACE VIEW query.expr_xbool AS
5305     SELECT
5306                 id,
5307                 parenthesize,
5308                 parent_expr,
5309                 seq_no,
5310                 literal,
5311                 negate
5312     FROM
5313         query.expression
5314     WHERE
5315         type = 'xbool';
5316
5317 CREATE OR REPLACE RULE query_expr_xbool_insert_rule AS
5318     ON INSERT TO query.expr_xbool
5319     DO INSTEAD
5320     INSERT INTO query.expression (
5321                 id,
5322                 type,
5323                 parenthesize,
5324                 parent_expr,
5325                 seq_no,
5326                 literal,
5327                 negate
5328     ) VALUES (
5329         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5330         'xbool',
5331         COALESCE(NEW.parenthesize, FALSE),
5332         NEW.parent_expr,
5333         COALESCE(NEW.seq_no, 1),
5334         NEW.literal,
5335                 COALESCE(NEW.negate, false)
5336     );
5337
5338 CREATE OR REPLACE RULE query_expr_xbool_update_rule AS
5339     ON UPDATE TO query.expr_xbool
5340     DO INSTEAD
5341     UPDATE query.expression SET
5342         id = NEW.id,
5343         parenthesize = NEW.parenthesize,
5344         parent_expr = NEW.parent_expr,
5345         seq_no = NEW.seq_no,
5346         literal = NEW.literal,
5347                 negate = NEW.negate
5348     WHERE
5349         id = OLD.id;
5350
5351 CREATE OR REPLACE RULE query_expr_xbool_delete_rule AS
5352     ON DELETE TO query.expr_xbool
5353     DO INSTEAD
5354     DELETE FROM query.expression WHERE id = OLD.id;
5355
5356 -- Create updatable view for CASE expressions
5357
5358 CREATE OR REPLACE VIEW query.expr_xcase AS
5359     SELECT
5360                 id,
5361                 parenthesize,
5362                 parent_expr,
5363                 seq_no,
5364                 left_operand,
5365                 negate
5366     FROM
5367         query.expression
5368     WHERE
5369         type = 'xcase';
5370
5371 CREATE OR REPLACE RULE query_expr_xcase_insert_rule AS
5372     ON INSERT TO query.expr_xcase
5373     DO INSTEAD
5374     INSERT INTO query.expression (
5375                 id,
5376                 type,
5377                 parenthesize,
5378                 parent_expr,
5379                 seq_no,
5380                 left_operand,
5381                 negate
5382     ) VALUES (
5383         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5384         'xcase',
5385         COALESCE(NEW.parenthesize, FALSE),
5386         NEW.parent_expr,
5387         COALESCE(NEW.seq_no, 1),
5388                 NEW.left_operand,
5389                 COALESCE(NEW.negate, false)
5390     );
5391
5392 CREATE OR REPLACE RULE query_expr_xcase_update_rule AS
5393     ON UPDATE TO query.expr_xcase
5394     DO INSTEAD
5395     UPDATE query.expression SET
5396         id = NEW.id,
5397         parenthesize = NEW.parenthesize,
5398         parent_expr = NEW.parent_expr,
5399         seq_no = NEW.seq_no,
5400                 left_operand = NEW.left_operand,
5401                 negate = NEW.negate
5402     WHERE
5403         id = OLD.id;
5404
5405 CREATE OR REPLACE RULE query_expr_xcase_delete_rule AS
5406     ON DELETE TO query.expr_xcase
5407     DO INSTEAD
5408     DELETE FROM query.expression WHERE id = OLD.id;
5409
5410 -- Create updatable view for cast expressions
5411
5412 CREATE OR REPLACE VIEW query.expr_xcast AS
5413     SELECT
5414                 id,
5415                 parenthesize,
5416                 parent_expr,
5417                 seq_no,
5418                 left_operand,
5419                 cast_type,
5420                 negate
5421     FROM
5422         query.expression
5423     WHERE
5424         type = 'xcast';
5425
5426 CREATE OR REPLACE RULE query_expr_xcast_insert_rule AS
5427     ON INSERT TO query.expr_xcast
5428     DO INSTEAD
5429     INSERT INTO query.expression (
5430         id,
5431         type,
5432         parenthesize,
5433         parent_expr,
5434         seq_no,
5435         left_operand,
5436         cast_type,
5437         negate
5438     ) VALUES (
5439         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5440         'xcast',
5441         COALESCE(NEW.parenthesize, FALSE),
5442         NEW.parent_expr,
5443         COALESCE(NEW.seq_no, 1),
5444         NEW.left_operand,
5445         NEW.cast_type,
5446         COALESCE(NEW.negate, false)
5447     );
5448
5449 CREATE OR REPLACE RULE query_expr_xcast_update_rule AS
5450     ON UPDATE TO query.expr_xcast
5451     DO INSTEAD
5452     UPDATE query.expression SET
5453         id = NEW.id,
5454         parenthesize = NEW.parenthesize,
5455         parent_expr = NEW.parent_expr,
5456         seq_no = NEW.seq_no,
5457                 left_operand = NEW.left_operand,
5458                 cast_type = NEW.cast_type,
5459                 negate = NEW.negate
5460     WHERE
5461         id = OLD.id;
5462
5463 CREATE OR REPLACE RULE query_expr_xcast_delete_rule AS
5464     ON DELETE TO query.expr_xcast
5465     DO INSTEAD
5466     DELETE FROM query.expression WHERE id = OLD.id;
5467
5468 -- Create updatable view for column expressions
5469
5470 CREATE OR REPLACE VIEW query.expr_xcol AS
5471     SELECT
5472                 id,
5473                 parenthesize,
5474                 parent_expr,
5475                 seq_no,
5476                 table_alias,
5477                 column_name,
5478                 negate
5479     FROM
5480         query.expression
5481     WHERE
5482         type = 'xcol';
5483
5484 CREATE OR REPLACE RULE query_expr_xcol_insert_rule AS
5485     ON INSERT TO query.expr_xcol
5486     DO INSTEAD
5487     INSERT INTO query.expression (
5488                 id,
5489                 type,
5490                 parenthesize,
5491                 parent_expr,
5492                 seq_no,
5493                 table_alias,
5494                 column_name,
5495                 negate
5496     ) VALUES (
5497         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5498         'xcol',
5499         COALESCE(NEW.parenthesize, FALSE),
5500         NEW.parent_expr,
5501         COALESCE(NEW.seq_no, 1),
5502                 NEW.table_alias,
5503                 NEW.column_name,
5504                 COALESCE(NEW.negate, false)
5505     );
5506
5507 CREATE OR REPLACE RULE query_expr_xcol_update_rule AS
5508     ON UPDATE TO query.expr_xcol
5509     DO INSTEAD
5510     UPDATE query.expression SET
5511         id = NEW.id,
5512         parenthesize = NEW.parenthesize,
5513         parent_expr = NEW.parent_expr,
5514         seq_no = NEW.seq_no,
5515                 table_alias = NEW.table_alias,
5516                 column_name = NEW.column_name,
5517                 negate = NEW.negate
5518     WHERE
5519         id = OLD.id;
5520
5521 CREATE OR REPLACE RULE query_expr_xcol_delete_rule AS
5522     ON DELETE TO query.expr_xcol
5523     DO INSTEAD
5524     DELETE FROM query.expression WHERE id = OLD.id;
5525
5526 -- Create updatable view for EXISTS expressions
5527
5528 CREATE OR REPLACE VIEW query.expr_xex AS
5529     SELECT
5530                 id,
5531                 parenthesize,
5532                 parent_expr,
5533                 seq_no,
5534                 subquery,
5535                 negate
5536     FROM
5537         query.expression
5538     WHERE
5539         type = 'xex';
5540
5541 CREATE OR REPLACE RULE query_expr_xex_insert_rule AS
5542     ON INSERT TO query.expr_xex
5543     DO INSTEAD
5544     INSERT INTO query.expression (
5545                 id,
5546                 type,
5547                 parenthesize,
5548                 parent_expr,
5549                 seq_no,
5550                 subquery,
5551                 negate
5552     ) VALUES (
5553         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5554         'xex',
5555         COALESCE(NEW.parenthesize, FALSE),
5556         NEW.parent_expr,
5557         COALESCE(NEW.seq_no, 1),
5558                 NEW.subquery,
5559                 COALESCE(NEW.negate, false)
5560     );
5561
5562 CREATE OR REPLACE RULE query_expr_xex_update_rule AS
5563     ON UPDATE TO query.expr_xex
5564     DO INSTEAD
5565     UPDATE query.expression SET
5566         id = NEW.id,
5567         parenthesize = NEW.parenthesize,
5568         parent_expr = NEW.parent_expr,
5569         seq_no = NEW.seq_no,
5570                 subquery = NEW.subquery,
5571                 negate = NEW.negate
5572     WHERE
5573         id = OLD.id;
5574
5575 CREATE OR REPLACE RULE query_expr_xex_delete_rule AS
5576     ON DELETE TO query.expr_xex
5577     DO INSTEAD
5578     DELETE FROM query.expression WHERE id = OLD.id;
5579
5580 -- Create updatable view for function call expressions
5581
5582 CREATE OR REPLACE VIEW query.expr_xfunc AS
5583     SELECT
5584         id,
5585         parenthesize,
5586         parent_expr,
5587         seq_no,
5588         column_name,
5589         function_id,
5590         negate
5591     FROM
5592         query.expression
5593     WHERE
5594         type = 'xfunc';
5595
5596 CREATE OR REPLACE RULE query_expr_xfunc_insert_rule AS
5597     ON INSERT TO query.expr_xfunc
5598     DO INSTEAD
5599     INSERT INTO query.expression (
5600         id,
5601         type,
5602         parenthesize,
5603         parent_expr,
5604         seq_no,
5605         column_name,
5606         function_id,
5607         negate
5608     ) VALUES (
5609         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5610         'xfunc',
5611         COALESCE(NEW.parenthesize, FALSE),
5612         NEW.parent_expr,
5613         COALESCE(NEW.seq_no, 1),
5614         NEW.column_name,
5615         NEW.function_id,
5616         COALESCE(NEW.negate, false)
5617     );
5618
5619 CREATE OR REPLACE RULE query_expr_xfunc_update_rule AS
5620     ON UPDATE TO query.expr_xfunc
5621     DO INSTEAD
5622     UPDATE query.expression SET
5623         id = NEW.id,
5624         parenthesize = NEW.parenthesize,
5625         parent_expr = NEW.parent_expr,
5626         seq_no = NEW.seq_no,
5627         column_name = NEW.column_name,
5628         function_id = NEW.function_id,
5629         negate = NEW.negate
5630     WHERE
5631         id = OLD.id;
5632
5633 CREATE OR REPLACE RULE query_expr_xfunc_delete_rule AS
5634     ON DELETE TO query.expr_xfunc
5635     DO INSTEAD
5636     DELETE FROM query.expression WHERE id = OLD.id;
5637
5638 -- Create updatable view for IN expressions
5639
5640 CREATE OR REPLACE VIEW query.expr_xin AS
5641     SELECT
5642                 id,
5643                 parenthesize,
5644                 parent_expr,
5645                 seq_no,
5646                 left_operand,
5647                 subquery,
5648                 negate
5649     FROM
5650         query.expression
5651     WHERE
5652         type = 'xin';
5653
5654 CREATE OR REPLACE RULE query_expr_xin_insert_rule AS
5655     ON INSERT TO query.expr_xin
5656     DO INSTEAD
5657     INSERT INTO query.expression (
5658                 id,
5659                 type,
5660                 parenthesize,
5661                 parent_expr,
5662                 seq_no,
5663                 left_operand,
5664                 subquery,
5665                 negate
5666     ) VALUES (
5667         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5668         'xin',
5669         COALESCE(NEW.parenthesize, FALSE),
5670         NEW.parent_expr,
5671         COALESCE(NEW.seq_no, 1),
5672                 NEW.left_operand,
5673                 NEW.subquery,
5674                 COALESCE(NEW.negate, false)
5675     );
5676
5677 CREATE OR REPLACE RULE query_expr_xin_update_rule AS
5678     ON UPDATE TO query.expr_xin
5679     DO INSTEAD
5680     UPDATE query.expression SET
5681         id = NEW.id,
5682         parenthesize = NEW.parenthesize,
5683         parent_expr = NEW.parent_expr,
5684         seq_no = NEW.seq_no,
5685                 left_operand = NEW.left_operand,
5686                 subquery = NEW.subquery,
5687                 negate = NEW.negate
5688     WHERE
5689         id = OLD.id;
5690
5691 CREATE OR REPLACE RULE query_expr_xin_delete_rule AS
5692     ON DELETE TO query.expr_xin
5693     DO INSTEAD
5694     DELETE FROM query.expression WHERE id = OLD.id;
5695
5696 -- Create updatable view for IS NULL expressions
5697
5698 CREATE OR REPLACE VIEW query.expr_xisnull AS
5699     SELECT
5700                 id,
5701                 parenthesize,
5702                 parent_expr,
5703                 seq_no,
5704                 left_operand,
5705                 negate
5706     FROM
5707         query.expression
5708     WHERE
5709         type = 'xisnull';
5710
5711 CREATE OR REPLACE RULE query_expr_xisnull_insert_rule AS
5712     ON INSERT TO query.expr_xisnull
5713     DO INSTEAD
5714     INSERT INTO query.expression (
5715                 id,
5716                 type,
5717                 parenthesize,
5718                 parent_expr,
5719                 seq_no,
5720                 left_operand,
5721                 negate
5722     ) VALUES (
5723         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5724         'xisnull',
5725         COALESCE(NEW.parenthesize, FALSE),
5726         NEW.parent_expr,
5727         COALESCE(NEW.seq_no, 1),
5728                 NEW.left_operand,
5729                 COALESCE(NEW.negate, false)
5730     );
5731
5732 CREATE OR REPLACE RULE query_expr_xisnull_update_rule AS
5733     ON UPDATE TO query.expr_xisnull
5734     DO INSTEAD
5735     UPDATE query.expression SET
5736         id = NEW.id,
5737         parenthesize = NEW.parenthesize,
5738         parent_expr = NEW.parent_expr,
5739         seq_no = NEW.seq_no,
5740                 left_operand = NEW.left_operand,
5741                 negate = NEW.negate
5742     WHERE
5743         id = OLD.id;
5744
5745 CREATE OR REPLACE RULE query_expr_xisnull_delete_rule AS
5746     ON DELETE TO query.expr_xisnull
5747     DO INSTEAD
5748     DELETE FROM query.expression WHERE id = OLD.id;
5749
5750 -- Create updatable view for NULL expressions
5751
5752 CREATE OR REPLACE VIEW query.expr_xnull AS
5753     SELECT
5754                 id,
5755                 parenthesize,
5756                 parent_expr,
5757                 seq_no,
5758                 negate
5759     FROM
5760         query.expression
5761     WHERE
5762         type = 'xnull';
5763
5764 CREATE OR REPLACE RULE query_expr_xnull_insert_rule AS
5765     ON INSERT TO query.expr_xnull
5766     DO INSTEAD
5767     INSERT INTO query.expression (
5768                 id,
5769                 type,
5770                 parenthesize,
5771                 parent_expr,
5772                 seq_no,
5773                 negate
5774     ) VALUES (
5775         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5776         'xnull',
5777         COALESCE(NEW.parenthesize, FALSE),
5778         NEW.parent_expr,
5779         COALESCE(NEW.seq_no, 1),
5780                 COALESCE(NEW.negate, false)
5781     );
5782
5783 CREATE OR REPLACE RULE query_expr_xnull_update_rule AS
5784     ON UPDATE TO query.expr_xnull
5785     DO INSTEAD
5786     UPDATE query.expression SET
5787         id = NEW.id,
5788         parenthesize = NEW.parenthesize,
5789         parent_expr = NEW.parent_expr,
5790         seq_no = NEW.seq_no,
5791                 negate = NEW.negate
5792     WHERE
5793         id = OLD.id;
5794
5795 CREATE OR REPLACE RULE query_expr_xnull_delete_rule AS
5796     ON DELETE TO query.expr_xnull
5797     DO INSTEAD
5798     DELETE FROM query.expression WHERE id = OLD.id;
5799
5800 -- Create updatable view for numeric literal expressions
5801
5802 CREATE OR REPLACE VIEW query.expr_xnum AS
5803     SELECT
5804                 id,
5805                 parenthesize,
5806                 parent_expr,
5807                 seq_no,
5808                 literal
5809     FROM
5810         query.expression
5811     WHERE
5812         type = 'xnum';
5813
5814 CREATE OR REPLACE RULE query_expr_xnum_insert_rule AS
5815     ON INSERT TO query.expr_xnum
5816     DO INSTEAD
5817     INSERT INTO query.expression (
5818                 id,
5819                 type,
5820                 parenthesize,
5821                 parent_expr,
5822                 seq_no,
5823                 literal
5824     ) VALUES (
5825         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5826         'xnum',
5827         COALESCE(NEW.parenthesize, FALSE),
5828         NEW.parent_expr,
5829         COALESCE(NEW.seq_no, 1),
5830         NEW.literal
5831     );
5832
5833 CREATE OR REPLACE RULE query_expr_xnum_update_rule AS
5834     ON UPDATE TO query.expr_xnum
5835     DO INSTEAD
5836     UPDATE query.expression SET
5837         id = NEW.id,
5838         parenthesize = NEW.parenthesize,
5839         parent_expr = NEW.parent_expr,
5840         seq_no = NEW.seq_no,
5841         literal = NEW.literal
5842     WHERE
5843         id = OLD.id;
5844
5845 CREATE OR REPLACE RULE query_expr_xnum_delete_rule AS
5846     ON DELETE TO query.expr_xnum
5847     DO INSTEAD
5848     DELETE FROM query.expression WHERE id = OLD.id;
5849
5850 -- Create updatable view for operator expressions
5851
5852 CREATE OR REPLACE VIEW query.expr_xop AS
5853     SELECT
5854                 id,
5855                 parenthesize,
5856                 parent_expr,
5857                 seq_no,
5858                 left_operand,
5859                 operator,
5860                 right_operand,
5861                 negate
5862     FROM
5863         query.expression
5864     WHERE
5865         type = 'xop';
5866
5867 CREATE OR REPLACE RULE query_expr_xop_insert_rule AS
5868     ON INSERT TO query.expr_xop
5869     DO INSTEAD
5870     INSERT INTO query.expression (
5871                 id,
5872                 type,
5873                 parenthesize,
5874                 parent_expr,
5875                 seq_no,
5876                 left_operand,
5877                 operator,
5878                 right_operand,
5879                 negate
5880     ) VALUES (
5881         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5882         'xop',
5883         COALESCE(NEW.parenthesize, FALSE),
5884         NEW.parent_expr,
5885         COALESCE(NEW.seq_no, 1),
5886                 NEW.left_operand,
5887                 NEW.operator,
5888                 NEW.right_operand,
5889                 COALESCE(NEW.negate, false)
5890     );
5891
5892 CREATE OR REPLACE RULE query_expr_xop_update_rule AS
5893     ON UPDATE TO query.expr_xop
5894     DO INSTEAD
5895     UPDATE query.expression SET
5896         id = NEW.id,
5897         parenthesize = NEW.parenthesize,
5898         parent_expr = NEW.parent_expr,
5899         seq_no = NEW.seq_no,
5900                 left_operand = NEW.left_operand,
5901                 operator = NEW.operator,
5902                 right_operand = NEW.right_operand,
5903                 negate = NEW.negate
5904     WHERE
5905         id = OLD.id;
5906
5907 CREATE OR REPLACE RULE query_expr_xop_delete_rule AS
5908     ON DELETE TO query.expr_xop
5909     DO INSTEAD
5910     DELETE FROM query.expression WHERE id = OLD.id;
5911
5912 -- Create updatable view for series expressions
5913 -- i.e. series of expressions separated by operators
5914
5915 CREATE OR REPLACE VIEW query.expr_xser AS
5916     SELECT
5917                 id,
5918                 parenthesize,
5919                 parent_expr,
5920                 seq_no,
5921                 operator,
5922                 negate
5923     FROM
5924         query.expression
5925     WHERE
5926         type = 'xser';
5927
5928 CREATE OR REPLACE RULE query_expr_xser_insert_rule AS
5929     ON INSERT TO query.expr_xser
5930     DO INSTEAD
5931     INSERT INTO query.expression (
5932                 id,
5933                 type,
5934                 parenthesize,
5935                 parent_expr,
5936                 seq_no,
5937                 operator,
5938                 negate
5939     ) VALUES (
5940         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5941         'xser',
5942         COALESCE(NEW.parenthesize, FALSE),
5943         NEW.parent_expr,
5944         COALESCE(NEW.seq_no, 1),
5945                 NEW.operator,
5946                 COALESCE(NEW.negate, false)
5947     );
5948
5949 CREATE OR REPLACE RULE query_expr_xser_update_rule AS
5950     ON UPDATE TO query.expr_xser
5951     DO INSTEAD
5952     UPDATE query.expression SET
5953         id = NEW.id,
5954         parenthesize = NEW.parenthesize,
5955         parent_expr = NEW.parent_expr,
5956         seq_no = NEW.seq_no,
5957                 operator = NEW.operator,
5958                 negate = NEW.negate
5959     WHERE
5960         id = OLD.id;
5961
5962 CREATE OR REPLACE RULE query_expr_xser_delete_rule AS
5963     ON DELETE TO query.expr_xser
5964     DO INSTEAD
5965     DELETE FROM query.expression WHERE id = OLD.id;
5966
5967 -- Create updatable view for string literal expressions
5968
5969 CREATE OR REPLACE VIEW query.expr_xstr AS
5970     SELECT
5971         id,
5972         parenthesize,
5973         parent_expr,
5974         seq_no,
5975         literal
5976     FROM
5977         query.expression
5978     WHERE
5979         type = 'xstr';
5980
5981 CREATE OR REPLACE RULE query_expr_string_insert_rule AS
5982     ON INSERT TO query.expr_xstr
5983     DO INSTEAD
5984     INSERT INTO query.expression (
5985         id,
5986         type,
5987         parenthesize,
5988         parent_expr,
5989         seq_no,
5990         literal
5991     ) VALUES (
5992         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
5993         'xstr',
5994         COALESCE(NEW.parenthesize, FALSE),
5995         NEW.parent_expr,
5996         COALESCE(NEW.seq_no, 1),
5997         NEW.literal
5998     );
5999
6000 CREATE OR REPLACE RULE query_expr_string_update_rule AS
6001     ON UPDATE TO query.expr_xstr
6002     DO INSTEAD
6003     UPDATE query.expression SET
6004         id = NEW.id,
6005         parenthesize = NEW.parenthesize,
6006         parent_expr = NEW.parent_expr,
6007         seq_no = NEW.seq_no,
6008         literal = NEW.literal
6009     WHERE
6010         id = OLD.id;
6011
6012 CREATE OR REPLACE RULE query_expr_string_delete_rule AS
6013     ON DELETE TO query.expr_xstr
6014     DO INSTEAD
6015     DELETE FROM query.expression WHERE id = OLD.id;
6016
6017 -- Create updatable view for subquery expressions
6018
6019 CREATE OR REPLACE VIEW query.expr_xsubq AS
6020     SELECT
6021                 id,
6022                 parenthesize,
6023                 parent_expr,
6024                 seq_no,
6025                 subquery,
6026                 negate
6027     FROM
6028         query.expression
6029     WHERE
6030         type = 'xsubq';
6031
6032 CREATE OR REPLACE RULE query_expr_xsubq_insert_rule AS
6033     ON INSERT TO query.expr_xsubq
6034     DO INSTEAD
6035     INSERT INTO query.expression (
6036                 id,
6037                 type,
6038                 parenthesize,
6039                 parent_expr,
6040                 seq_no,
6041                 subquery,
6042                 negate
6043     ) VALUES (
6044         COALESCE(NEW.id, NEXTVAL('query.expression_id_seq'::REGCLASS)),
6045         'xsubq',
6046         COALESCE(NEW.parenthesize, FALSE),
6047         NEW.parent_expr,
6048         COALESCE(NEW.seq_no, 1),
6049                 NEW.subquery,
6050                 COALESCE(NEW.negate, false)
6051     );
6052
6053 CREATE OR REPLACE RULE query_expr_xsubq_update_rule AS
6054     ON UPDATE TO query.expr_xsubq
6055     DO INSTEAD
6056     UPDATE query.expression SET
6057         id = NEW.id,
6058         parenthesize = NEW.parenthesize,
6059         parent_expr = NEW.parent_expr,
6060         seq_no = NEW.seq_no,
6061                 subquery = NEW.subquery,
6062                 negate = NEW.negate
6063     WHERE
6064         id = OLD.id;
6065
6066 CREATE OR REPLACE RULE query_expr_xsubq_delete_rule AS
6067     ON DELETE TO query.expr_xsubq
6068     DO INSTEAD
6069     DELETE FROM query.expression WHERE id = OLD.id;
6070
6071 CREATE TABLE action.fieldset (
6072     id              SERIAL          PRIMARY KEY,
6073     owner           INT             NOT NULL REFERENCES actor.usr (id)
6074                                     DEFERRABLE INITIALLY DEFERRED,
6075     owning_lib      INT             NOT NULL REFERENCES actor.org_unit (id)
6076                                     DEFERRABLE INITIALLY DEFERRED,
6077     status          TEXT            NOT NULL
6078                                     CONSTRAINT valid_status CHECK ( status in
6079                                     ( 'PENDING', 'APPLIED', 'ERROR' )),
6080     creation_time   TIMESTAMPTZ     NOT NULL DEFAULT NOW(),
6081     scheduled_time  TIMESTAMPTZ,
6082     applied_time    TIMESTAMPTZ,
6083     classname       TEXT            NOT NULL, -- an IDL class name
6084     name            TEXT            NOT NULL,
6085     stored_query    INT             REFERENCES query.stored_query (id)
6086                                     DEFERRABLE INITIALLY DEFERRED,
6087     pkey_value      TEXT,
6088     CONSTRAINT lib_name_unique UNIQUE (owning_lib, name),
6089     CONSTRAINT fieldset_one_or_the_other CHECK (
6090         (stored_query IS NOT NULL AND pkey_value IS NULL) OR
6091         (pkey_value IS NOT NULL AND stored_query IS NULL)
6092     )
6093     -- the CHECK constraint means we can update the fields for a single
6094     -- row without all the extra overhead involved in a query
6095 );
6096
6097 CREATE INDEX action_fieldset_sched_time_idx ON action.fieldset( scheduled_time );
6098 CREATE INDEX action_owner_idx               ON action.fieldset( owner );
6099
6100 CREATE TABLE action.fieldset_col_val (
6101     id              SERIAL  PRIMARY KEY,
6102     fieldset        INT     NOT NULL REFERENCES action.fieldset
6103                                          ON DELETE CASCADE
6104                                          DEFERRABLE INITIALLY DEFERRED,
6105     col             TEXT    NOT NULL,  -- "field" from the idl ... the column on the table
6106     val             TEXT,              -- value for the column ... NULL means, well, NULL
6107     CONSTRAINT fieldset_col_once_per_set UNIQUE (fieldset, col)
6108 );
6109
6110 CREATE OR REPLACE FUNCTION action.apply_fieldset(
6111         fieldset_id IN INT,        -- id from action.fieldset
6112         table_name  IN TEXT,       -- table to be updated
6113         pkey_name   IN TEXT,       -- name of primary key column in that table
6114         query       IN TEXT        -- query constructed by qstore (for query-based
6115                                    --    fieldsets only; otherwise null
6116 )
6117 RETURNS TEXT AS $$
6118 DECLARE
6119         statement TEXT;
6120         fs_status TEXT;
6121         fs_pkey_value TEXT;
6122         fs_query TEXT;
6123         sep CHAR;
6124         status_code TEXT;
6125         msg TEXT;
6126         update_count INT;
6127         cv RECORD;
6128 BEGIN
6129         -- Sanity checks
6130         IF fieldset_id IS NULL THEN
6131                 RETURN 'Fieldset ID parameter is NULL';
6132         END IF;
6133         IF table_name IS NULL THEN
6134                 RETURN 'Table name parameter is NULL';
6135         END IF;
6136         IF pkey_name IS NULL THEN
6137                 RETURN 'Primary key name parameter is NULL';
6138         END IF;
6139         --
6140         statement := 'UPDATE ' || table_name || ' SET';
6141         --
6142         SELECT
6143                 status,
6144                 quote_literal( pkey_value )
6145         INTO
6146                 fs_status,
6147                 fs_pkey_value
6148         FROM
6149                 action.fieldset
6150         WHERE
6151                 id = fieldset_id;
6152         --
6153         IF fs_status IS NULL THEN
6154                 RETURN 'No fieldset found for id = ' || fieldset_id;
6155         ELSIF fs_status = 'APPLIED' THEN
6156                 RETURN 'Fieldset ' || fieldset_id || ' has already been applied';
6157         END IF;
6158         --
6159         sep := '';
6160         FOR cv IN
6161                 SELECT  col,
6162                                 val
6163                 FROM    action.fieldset_col_val
6164                 WHERE   fieldset = fieldset_id
6165         LOOP
6166                 statement := statement || sep || ' ' || cv.col
6167                                          || ' = ' || coalesce( quote_literal( cv.val ), 'NULL' );
6168                 sep := ',';
6169         END LOOP;
6170         --
6171         IF sep = '' THEN
6172                 RETURN 'Fieldset ' || fieldset_id || ' has no column values defined';
6173         END IF;
6174         --
6175         -- Add the WHERE clause.  This differs according to whether it's a
6176         -- single-row fieldset or a query-based fieldset.
6177         --
6178         IF query IS NULL        AND fs_pkey_value IS NULL THEN
6179                 RETURN 'Incomplete fieldset: neither a primary key nor a query available';
6180         ELSIF query IS NOT NULL AND fs_pkey_value IS NULL THEN
6181             fs_query := rtrim( query, ';' );
6182             statement := statement || ' WHERE ' || pkey_name || ' IN ( '
6183                          || fs_query || ' );';
6184         ELSIF query IS NULL     AND fs_pkey_value IS NOT NULL THEN
6185                 statement := statement || ' WHERE ' || pkey_name || ' = '
6186                                      || fs_pkey_value || ';';
6187         ELSE  -- both are not null
6188                 RETURN 'Ambiguous fieldset: both a primary key and a query provided';
6189         END IF;
6190         --
6191         -- Execute the update
6192         --
6193         BEGIN
6194                 EXECUTE statement;
6195                 GET DIAGNOSTICS update_count = ROW_COUNT;
6196                 --
6197                 IF UPDATE_COUNT > 0 THEN
6198                         status_code := 'APPLIED';
6199                         msg := NULL;
6200                 ELSE
6201                         status_code := 'ERROR';
6202                         msg := 'No eligible rows found for fieldset ' || fieldset_id;
6203         END IF;
6204         EXCEPTION WHEN OTHERS THEN
6205                 status_code := 'ERROR';
6206                 msg := 'Unable to apply fieldset ' || fieldset_id
6207                            || ': ' || sqlerrm;
6208         END;
6209         --
6210         -- Update fieldset status
6211         --
6212         UPDATE action.fieldset
6213         SET status       = status_code,
6214             applied_time = now()
6215         WHERE id = fieldset_id;
6216         --
6217         RETURN msg;
6218 END;
6219 $$ LANGUAGE plpgsql;
6220
6221 COMMENT ON FUNCTION action.apply_fieldset( INT, TEXT, TEXT, TEXT ) IS $$
6222 /**
6223  * Applies a specified fieldset, using a supplied table name and primary
6224  * key name.  The query parameter should be non-null only for
6225  * query-based fieldsets.
6226  *
6227  * Returns NULL if successful, or an error message if not.
6228  */
6229 $$;
6230
6231 CREATE INDEX uhr_hold_idx ON action.unfulfilled_hold_list (hold);
6232
6233 CREATE OR REPLACE VIEW action.unfulfilled_hold_loops AS
6234     SELECT  u.hold,
6235             c.circ_lib,
6236             count(*)
6237       FROM  action.unfulfilled_hold_list u
6238             JOIN asset.copy c ON (c.id = u.current_copy)
6239       GROUP BY 1,2;
6240
6241 CREATE OR REPLACE VIEW action.unfulfilled_hold_min_loop AS
6242     SELECT  hold,
6243             min(count)
6244       FROM  action.unfulfilled_hold_loops
6245       GROUP BY 1;
6246
6247 CREATE OR REPLACE VIEW action.unfulfilled_hold_innermost_loop AS
6248     SELECT  DISTINCT l.*
6249       FROM  action.unfulfilled_hold_loops l
6250             JOIN action.unfulfilled_hold_min_loop m USING (hold)
6251       WHERE l.count = m.min;
6252
6253 ALTER TABLE asset.copy
6254 ADD COLUMN dummy_isbn TEXT;
6255
6256 ALTER TABLE auditor.asset_copy_history
6257 ADD COLUMN dummy_isbn TEXT;
6258
6259 -- Add new column status_changed_date to asset.copy, with trigger to maintain it
6260 -- Add corresponding new column to auditor.asset_copy_history
6261
6262 ALTER TABLE asset.copy
6263         ADD COLUMN status_changed_time TIMESTAMPTZ;
6264
6265 ALTER TABLE auditor.asset_copy_history
6266         ADD COLUMN status_changed_time TIMESTAMPTZ;
6267
6268 CREATE OR REPLACE FUNCTION asset.acp_status_changed()
6269 RETURNS TRIGGER AS $$
6270 BEGIN
6271     IF NEW.status <> OLD.status THEN
6272         NEW.status_changed_time := now();
6273     END IF;
6274     RETURN NEW;
6275 END;
6276 $$ LANGUAGE plpgsql;
6277
6278 CREATE TRIGGER acp_status_changed_trig
6279         BEFORE UPDATE ON asset.copy
6280         FOR EACH ROW EXECUTE PROCEDURE asset.acp_status_changed();
6281
6282 ALTER TABLE asset.copy
6283 ADD COLUMN mint_condition boolean NOT NULL DEFAULT TRUE;
6284
6285 ALTER TABLE auditor.asset_copy_history
6286 ADD COLUMN mint_condition boolean NOT NULL DEFAULT TRUE;
6287
6288 ALTER TABLE asset.copy ADD COLUMN floating BOOL NOT NULL DEFAULT FALSE;
6289 ALTER TABLE auditor.asset_copy_history ADD COLUMN floating BOOL;
6290
6291 DROP INDEX IF EXISTS asset.copy_barcode_key;
6292 CREATE UNIQUE INDEX copy_barcode_key ON asset.copy (barcode) WHERE deleted = FALSE OR deleted IS FALSE;
6293
6294 -- Note: later we create a trigger a_opac_vis_mat_view_tgr
6295 -- AFTER INSERT OR UPDATE ON asset.copy
6296
6297 ALTER TABLE asset.copy ADD COLUMN cost NUMERIC(8,2);
6298 ALTER TABLE auditor.asset_copy_history ADD COLUMN cost NUMERIC(8,2);
6299
6300 -- Moke mostly parallel changes to action.circulation
6301 -- and action.aged_circulation
6302
6303 ALTER TABLE action.circulation
6304 ADD COLUMN workstation INT
6305     REFERENCES actor.workstation
6306         ON DELETE SET NULL
6307         DEFERRABLE INITIALLY DEFERRED;
6308
6309 ALTER TABLE action.aged_circulation
6310 ADD COLUMN workstation INT;
6311
6312 ALTER TABLE action.circulation
6313 ADD COLUMN parent_circ BIGINT
6314         REFERENCES action.circulation(id)
6315         DEFERRABLE INITIALLY DEFERRED;
6316
6317 CREATE UNIQUE INDEX circ_parent_idx
6318 ON action.circulation( parent_circ )
6319 WHERE parent_circ IS NOT NULL;
6320
6321 ALTER TABLE action.aged_circulation
6322 ADD COLUMN parent_circ BIGINT;
6323
6324 ALTER TABLE action.circulation
6325 ADD COLUMN checkin_workstation INT
6326         REFERENCES actor.workstation(id)
6327         ON DELETE SET NULL
6328         DEFERRABLE INITIALLY DEFERRED;
6329
6330 ALTER TABLE action.aged_circulation
6331 ADD COLUMN checkin_workstation INT;
6332
6333 ALTER TABLE action.circulation
6334 ADD COLUMN checkin_scan_time TIMESTAMPTZ;
6335
6336 ALTER TABLE action.aged_circulation
6337 ADD COLUMN checkin_scan_time TIMESTAMPTZ;
6338
6339 CREATE INDEX action_circulation_target_copy_idx
6340 ON action.circulation (target_copy);
6341
6342 CREATE INDEX action_aged_circulation_target_copy_idx
6343 ON action.aged_circulation (target_copy);
6344
6345 ALTER TABLE action.circulation
6346 DROP CONSTRAINT circulation_stop_fines_check;
6347
6348 ALTER TABLE action.circulation
6349         ADD CONSTRAINT circulation_stop_fines_check
6350         CHECK (stop_fines IN (
6351         'CHECKIN','CLAIMSRETURNED','LOST','MAXFINES','RENEW','LONGOVERDUE','CLAIMSNEVERCHECKEDOUT'));
6352
6353 -- Hard due-date functionality
6354 CREATE TABLE config.hard_due_date (
6355         id          SERIAL      PRIMARY KEY,
6356         name        TEXT        NOT NULL UNIQUE CHECK ( name ~ E'^\\w+$' ),
6357         ceiling_date    TIMESTAMPTZ NOT NULL,
6358         forceto     BOOL        NOT NULL,
6359         owner       INT         NOT NULL
6360 );
6361
6362 CREATE TABLE config.hard_due_date_values (
6363     id                  SERIAL      PRIMARY KEY,
6364     hard_due_date       INT         NOT NULL REFERENCES config.hard_due_date (id)
6365                                     DEFERRABLE INITIALLY DEFERRED,
6366     ceiling_date        TIMESTAMPTZ NOT NULL,
6367     active_date         TIMESTAMPTZ NOT NULL
6368 );
6369
6370 ALTER TABLE config.circ_matrix_matchpoint ADD COLUMN hard_due_date INT REFERENCES config.hard_due_date (id);
6371
6372 CREATE OR REPLACE FUNCTION config.update_hard_due_dates () RETURNS INT AS $func$
6373 DECLARE
6374     temp_value  config.hard_due_date_values%ROWTYPE;
6375     updated     INT := 0;
6376 BEGIN
6377     FOR temp_value IN
6378       SELECT  DISTINCT ON (hard_due_date) *
6379         FROM  config.hard_due_date_values
6380         WHERE active_date <= NOW() -- We've passed (or are at) the rollover time
6381         ORDER BY active_date DESC -- Latest (nearest to us) active time
6382    LOOP
6383         UPDATE  config.hard_due_date
6384           SET   ceiling_date = temp_value.ceiling_date
6385           WHERE id = temp_value.hard_due_date
6386                 AND ceiling_date <> temp_value.ceiling_date; -- Time is equal if we've already updated the chdd
6387
6388         IF FOUND THEN
6389             updated := updated + 1;
6390         END IF;
6391     END LOOP;
6392
6393     RETURN updated;
6394 END;
6395 $func$ LANGUAGE plpgsql;
6396
6397 -- Correct some long-standing misspellings involving variations of "recur"
6398
6399 ALTER TABLE action.circulation RENAME COLUMN recuring_fine TO recurring_fine;
6400 ALTER TABLE action.circulation RENAME COLUMN recuring_fine_rule TO recurring_fine_rule;
6401
6402 ALTER TABLE action.aged_circulation RENAME COLUMN recuring_fine TO recurring_fine;
6403 ALTER TABLE action.aged_circulation RENAME COLUMN recuring_fine_rule TO recurring_fine_rule;
6404
6405 ALTER TABLE config.rule_recuring_fine RENAME TO rule_recurring_fine;
6406 ALTER TABLE config.rule_recuring_fine_id_seq RENAME TO rule_recurring_fine_id_seq;
6407
6408 ALTER TABLE config.rule_recurring_fine RENAME COLUMN recurance_interval TO recurrence_interval;
6409
6410 -- Might as well keep the comment in sync as well
6411 COMMENT ON TABLE config.rule_recurring_fine IS $$
6412 /*
6413  * Copyright (C) 2005  Georgia Public Library Service 
6414  * Mike Rylander <mrylander@gmail.com>
6415  *
6416  * Circulation Recurring Fine rules
6417  *
6418  * Each circulation is given a recurring fine amount based on one of
6419  * these rules.  The recurrence_interval should not be any shorter
6420  * than the interval between runs of the fine_processor.pl script
6421  * (which is run from CRON), or you could miss fines.
6422  * 
6423  *
6424  * ****
6425  *
6426  * This program is free software; you can redistribute it and/or
6427  * modify it under the terms of the GNU General Public License
6428  * as published by the Free Software Foundation; either version 2
6429  * of the License, or (at your option) any later version.
6430  *
6431  * This program is distributed in the hope that it will be useful,
6432  * but WITHOUT ANY WARRANTY; without even the implied warranty of
6433  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
6434  * GNU General Public License for more details.
6435  */
6436 $$;
6437
6438 -- Extend the name change to some related views:
6439
6440 DROP VIEW IF EXISTS reporter.overdue_circs;
6441
6442 CREATE OR REPLACE VIEW reporter.overdue_circs AS
6443 SELECT  *
6444   FROM  action.circulation
6445     WHERE checkin_time is null
6446                 AND (stop_fines NOT IN ('LOST','CLAIMSRETURNED') OR stop_fines IS NULL)
6447                                 AND due_date < now();
6448
6449 DROP VIEW IF EXISTS stats.fleshed_circulation;
6450
6451 DROP VIEW IF EXISTS stats.fleshed_copy;
6452
6453 CREATE VIEW stats.fleshed_copy AS
6454         SELECT  cp.*,
6455         CAST(cp.create_date AS DATE) AS create_date_day,
6456         CAST(cp.edit_date AS DATE) AS edit_date_day,
6457         DATE_TRUNC('hour', cp.create_date) AS create_date_hour,
6458         DATE_TRUNC('hour', cp.edit_date) AS edit_date_hour,
6459                 cn.label AS call_number_label,
6460                 cn.owning_lib,
6461                 rd.item_lang,
6462                 rd.item_type,
6463                 rd.item_form
6464         FROM    asset.copy cp
6465                 JOIN asset.call_number cn ON (cp.call_number = cn.id)
6466                 JOIN metabib.rec_descriptor rd ON (rd.record = cn.record);
6467
6468 CREATE VIEW stats.fleshed_circulation AS
6469         SELECT  c.*,
6470                 CAST(c.xact_start AS DATE) AS start_date_day,
6471                 CAST(c.xact_finish AS DATE) AS finish_date_day,
6472                 DATE_TRUNC('hour', c.xact_start) AS start_date_hour,
6473                 DATE_TRUNC('hour', c.xact_finish) AS finish_date_hour,
6474                 cp.call_number_label,
6475                 cp.owning_lib,
6476                 cp.item_lang,
6477                 cp.item_type,
6478                 cp.item_form
6479         FROM    action.circulation c
6480                 JOIN stats.fleshed_copy cp ON (cp.id = c.target_copy);
6481
6482 -- Drop a view temporarily in order to alter action.all_circulation, upon
6483 -- which it is dependent.  We will recreate the view later.
6484
6485 DROP VIEW IF EXISTS extend_reporter.full_circ_count;
6486
6487 -- You would think that CREATE OR REPLACE would be enough, but in testing
6488 -- PostgreSQL complained about renaming the columns in the view. So we
6489 -- drop the view first.
6490 DROP VIEW IF EXISTS action.all_circulation;
6491
6492 CREATE OR REPLACE VIEW action.all_circulation AS
6493     SELECT  id,usr_post_code, usr_home_ou, usr_profile, usr_birth_year, copy_call_number, copy_location,
6494         copy_owning_lib, copy_circ_lib, copy_bib_record, xact_start, xact_finish, target_copy,
6495         circ_lib, circ_staff, checkin_staff, checkin_lib, renewal_remaining, due_date,
6496         stop_fines_time, checkin_time, create_time, duration, fine_interval, recurring_fine,
6497         max_fine, phone_renewal, desk_renewal, opac_renewal, duration_rule, recurring_fine_rule,
6498         max_fine_rule, stop_fines, workstation, checkin_workstation, checkin_scan_time, parent_circ
6499       FROM  action.aged_circulation
6500             UNION ALL
6501     SELECT  DISTINCT circ.id,COALESCE(a.post_code,b.post_code) AS usr_post_code, p.home_ou AS usr_home_ou, p.profile AS usr_profile, EXTRACT(YEAR FROM p.dob)::INT AS usr_birth_year,
6502         cp.call_number AS copy_call_number, cp.location AS copy_location, cn.owning_lib AS copy_owning_lib, cp.circ_lib AS copy_circ_lib,
6503         cn.record AS copy_bib_record, circ.xact_start, circ.xact_finish, circ.target_copy, circ.circ_lib, circ.circ_staff, circ.checkin_staff,
6504         circ.checkin_lib, circ.renewal_remaining, circ.due_date, circ.stop_fines_time, circ.checkin_time, circ.create_time, circ.duration,
6505         circ.fine_interval, circ.recurring_fine, circ.max_fine, circ.phone_renewal, circ.desk_renewal, circ.opac_renewal, circ.duration_rule,
6506         circ.recurring_fine_rule, circ.max_fine_rule, circ.stop_fines, circ.workstation, circ.checkin_workstation, circ.checkin_scan_time,
6507         circ.parent_circ
6508       FROM  action.circulation circ
6509         JOIN asset.copy cp ON (circ.target_copy = cp.id)
6510         JOIN asset.call_number cn ON (cp.call_number = cn.id)
6511         JOIN actor.usr p ON (circ.usr = p.id)
6512         LEFT JOIN actor.usr_address a ON (p.mailing_address = a.id)
6513         LEFT JOIN actor.usr_address b ON (p.billing_address = a.id);
6514
6515 -- Recreate the temporarily dropped view, having altered the action.all_circulation view:
6516
6517 CREATE OR REPLACE VIEW extend_reporter.full_circ_count AS
6518  SELECT cp.id, COALESCE(sum(c.circ_count), 0::bigint) + COALESCE(count(circ.id), 0::bigint) + COALESCE(count(acirc.id), 0::bigint) AS circ_count
6519    FROM asset."copy" cp
6520    LEFT JOIN extend_reporter.legacy_circ_count c USING (id)
6521    LEFT JOIN "action".circulation circ ON circ.target_copy = cp.id
6522    LEFT JOIN "action".aged_circulation acirc ON acirc.target_copy = cp.id
6523   GROUP BY cp.id;
6524
6525 CREATE UNIQUE INDEX only_one_concurrent_checkout_per_copy ON action.circulation(target_copy) WHERE checkin_time IS NULL;
6526
6527 ALTER TABLE action.circulation DROP CONSTRAINT action_circulation_target_copy_fkey;
6528
6529 -- Rebuild dependent views
6530
6531 DROP VIEW IF EXISTS action.billable_circulations;
6532
6533 CREATE OR REPLACE VIEW action.billable_circulations AS
6534     SELECT  *
6535       FROM  action.circulation
6536       WHERE xact_finish IS NULL;
6537
6538 DROP VIEW IF EXISTS action.open_circulation;
6539
6540 CREATE OR REPLACE VIEW action.open_circulation AS
6541     SELECT  *
6542       FROM  action.circulation
6543       WHERE checkin_time IS NULL
6544       ORDER BY due_date;
6545
6546 CREATE OR REPLACE FUNCTION action.age_circ_on_delete () RETURNS TRIGGER AS $$
6547 DECLARE
6548 found char := 'N';
6549 BEGIN
6550
6551     -- If there are any renewals for this circulation, don't archive or delete
6552     -- it yet.   We'll do so later, when we archive and delete the renewals.
6553
6554     SELECT 'Y' INTO found
6555     FROM action.circulation
6556     WHERE parent_circ = OLD.id
6557     LIMIT 1;
6558
6559     IF found = 'Y' THEN
6560         RETURN NULL;  -- don't delete
6561         END IF;
6562
6563     -- Archive a copy of the old row to action.aged_circulation
6564
6565     INSERT INTO action.aged_circulation
6566         (id,usr_post_code, usr_home_ou, usr_profile, usr_birth_year, copy_call_number, copy_location,
6567         copy_owning_lib, copy_circ_lib, copy_bib_record, xact_start, xact_finish, target_copy,
6568         circ_lib, circ_staff, checkin_staff, checkin_lib, renewal_remaining, due_date,
6569         stop_fines_time, checkin_time, create_time, duration, fine_interval, recurring_fine,
6570         max_fine, phone_renewal, desk_renewal, opac_renewal, duration_rule, recurring_fine_rule,
6571         max_fine_rule, stop_fines, workstation, checkin_workstation, checkin_scan_time, parent_circ)
6572       SELECT
6573         id,usr_post_code, usr_home_ou, usr_profile, usr_birth_year, copy_call_number, copy_location,
6574         copy_owning_lib, copy_circ_lib, copy_bib_record, xact_start, xact_finish, target_copy,
6575         circ_lib, circ_staff, checkin_staff, checkin_lib, renewal_remaining, due_date,
6576         stop_fines_time, checkin_time, create_time, duration, fine_interval, recurring_fine,
6577         max_fine, phone_renewal, desk_renewal, opac_renewal, duration_rule, recurring_fine_rule,
6578         max_fine_rule, stop_fines, workstation, checkin_workstation, checkin_scan_time, parent_circ
6579         FROM action.all_circulation WHERE id = OLD.id;
6580
6581     RETURN OLD;
6582 END;
6583 $$ LANGUAGE 'plpgsql';
6584
6585 UPDATE config.z3950_attr SET truncation = 1 WHERE source = 'biblios' AND name = 'title';
6586
6587 UPDATE config.z3950_attr SET truncation = 1 WHERE source = 'biblios' AND truncation = 0;
6588
6589 -- Adding circ.holds.target_skip_me OU setting logic to the pre-matchpoint tests
6590
6591 CREATE OR REPLACE FUNCTION action.find_hold_matrix_matchpoint( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT ) RETURNS INT AS $func$
6592 DECLARE
6593     current_requestor_group    permission.grp_tree%ROWTYPE;
6594     requestor_object    actor.usr%ROWTYPE;
6595     user_object        actor.usr%ROWTYPE;
6596     item_object        asset.copy%ROWTYPE;
6597     item_cn_object        asset.call_number%ROWTYPE;
6598     rec_descriptor        metabib.rec_descriptor%ROWTYPE;
6599     current_mp_weight    FLOAT;
6600     matchpoint_weight    FLOAT;
6601     tmp_weight        FLOAT;
6602     current_mp        config.hold_matrix_matchpoint%ROWTYPE;
6603     matchpoint        config.hold_matrix_matchpoint%ROWTYPE;
6604 BEGIN
6605     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
6606     SELECT INTO requestor_object * FROM actor.usr WHERE id = match_requestor;
6607     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
6608     SELECT INTO item_cn_object * FROM asset.call_number WHERE id = item_object.call_number;
6609     SELECT INTO rec_descriptor r.* FROM metabib.rec_descriptor r WHERE r.record = item_cn_object.record;
6610
6611     PERFORM * FROM config.internal_flag WHERE name = 'circ.holds.usr_not_requestor' AND enabled;
6612
6613     IF NOT FOUND THEN
6614         SELECT INTO current_requestor_group * FROM permission.grp_tree WHERE id = requestor_object.profile;
6615     ELSE
6616         SELECT INTO current_requestor_group * FROM permission.grp_tree WHERE id = user_object.profile;
6617     END IF;
6618
6619     LOOP 
6620         -- for each potential matchpoint for this ou and group ...
6621         FOR current_mp IN
6622             SELECT    m.*
6623               FROM    config.hold_matrix_matchpoint m
6624               WHERE    m.requestor_grp = current_requestor_group.id AND m.active
6625               ORDER BY    CASE WHEN m.circ_modifier    IS NOT NULL THEN 16 ELSE 0 END +
6626                     CASE WHEN m.juvenile_flag    IS NOT NULL THEN 16 ELSE 0 END +
6627                     CASE WHEN m.marc_type        IS NOT NULL THEN 8 ELSE 0 END +
6628                     CASE WHEN m.marc_form        IS NOT NULL THEN 4 ELSE 0 END +
6629                     CASE WHEN m.marc_vr_format    IS NOT NULL THEN 2 ELSE 0 END +
6630                     CASE WHEN m.ref_flag        IS NOT NULL THEN 1 ELSE 0 END DESC LOOP
6631
6632             current_mp_weight := 5.0;
6633
6634             IF current_mp.circ_modifier IS NOT NULL THEN
6635                 CONTINUE WHEN current_mp.circ_modifier <> item_object.circ_modifier OR item_object.circ_modifier IS NULL;
6636             END IF;
6637
6638             IF current_mp.marc_type IS NOT NULL THEN
6639                 IF item_object.circ_as_type IS NOT NULL THEN
6640                     CONTINUE WHEN current_mp.marc_type <> item_object.circ_as_type;
6641                 ELSE
6642                     CONTINUE WHEN current_mp.marc_type <> rec_descriptor.item_type;
6643                 END IF;
6644             END IF;
6645
6646             IF current_mp.marc_form IS NOT NULL THEN
6647                 CONTINUE WHEN current_mp.marc_form <> rec_descriptor.item_form;
6648             END IF;
6649
6650             IF current_mp.marc_vr_format IS NOT NULL THEN
6651                 CONTINUE WHEN current_mp.marc_vr_format <> rec_descriptor.vr_format;
6652             END IF;
6653
6654             IF current_mp.juvenile_flag IS NOT NULL THEN
6655                 CONTINUE WHEN current_mp.juvenile_flag <> user_object.juvenile;
6656             END IF;
6657
6658             IF current_mp.ref_flag IS NOT NULL THEN
6659                 CONTINUE WHEN current_mp.ref_flag <> item_object.ref;
6660             END IF;
6661
6662
6663             -- caclulate the rule match weight
6664             IF current_mp.item_owning_ou IS NOT NULL THEN
6665                 CONTINUE WHEN current_mp.item_owning_ou NOT IN (SELECT (actor.org_unit_ancestors(item_cn_object.owning_lib)).id);
6666                 SELECT INTO tmp_weight 1.0 / (actor.org_unit_proximity(current_mp.item_owning_ou, item_cn_object.owning_lib)::FLOAT + 1.0)::FLOAT;
6667                 current_mp_weight := current_mp_weight - tmp_weight;
6668             END IF; 
6669
6670             IF current_mp.item_circ_ou IS NOT NULL THEN
6671                 CONTINUE WHEN current_mp.item_circ_ou NOT IN (SELECT (actor.org_unit_ancestors(item_object.circ_lib)).id);
6672                 SELECT INTO tmp_weight 1.0 / (actor.org_unit_proximity(current_mp.item_circ_ou, item_object.circ_lib)::FLOAT + 1.0)::FLOAT;
6673                 current_mp_weight := current_mp_weight - tmp_weight;
6674             END IF; 
6675
6676             IF current_mp.pickup_ou IS NOT NULL THEN
6677                 CONTINUE WHEN current_mp.pickup_ou NOT IN (SELECT (actor.org_unit_ancestors(pickup_ou)).id);
6678                 SELECT INTO tmp_weight 1.0 / (actor.org_unit_proximity(current_mp.pickup_ou, pickup_ou)::FLOAT + 1.0)::FLOAT;
6679                 current_mp_weight := current_mp_weight - tmp_weight;
6680             END IF; 
6681
6682             IF current_mp.request_ou IS NOT NULL THEN
6683                 CONTINUE WHEN current_mp.request_ou NOT IN (SELECT (actor.org_unit_ancestors(request_ou)).id);
6684                 SELECT INTO tmp_weight 1.0 / (actor.org_unit_proximity(current_mp.request_ou, request_ou)::FLOAT + 1.0)::FLOAT;
6685                 current_mp_weight := current_mp_weight - tmp_weight;
6686             END IF; 
6687
6688             IF current_mp.user_home_ou IS NOT NULL THEN
6689                 CONTINUE WHEN current_mp.user_home_ou NOT IN (SELECT (actor.org_unit_ancestors(user_object.home_ou)).id);
6690                 SELECT INTO tmp_weight 1.0 / (actor.org_unit_proximity(current_mp.user_home_ou, user_object.home_ou)::FLOAT + 1.0)::FLOAT;
6691                 current_mp_weight := current_mp_weight - tmp_weight;
6692             END IF; 
6693
6694             -- set the matchpoint if we found the best one
6695             IF matchpoint_weight IS NULL OR matchpoint_weight > current_mp_weight THEN
6696                 matchpoint = current_mp;
6697                 matchpoint_weight = current_mp_weight;
6698             END IF;
6699
6700         END LOOP;
6701
6702         EXIT WHEN current_requestor_group.parent IS NULL OR matchpoint.id IS NOT NULL;
6703
6704         SELECT INTO current_requestor_group * FROM permission.grp_tree WHERE id = current_requestor_group.parent;
6705     END LOOP;
6706
6707     RETURN matchpoint.id;
6708 END;
6709 $func$ LANGUAGE plpgsql;
6710
6711 CREATE OR REPLACE FUNCTION action.hold_request_permit_test( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT, retargetting BOOL ) RETURNS SETOF action.matrix_test_result AS $func$
6712 DECLARE
6713     matchpoint_id        INT;
6714     user_object        actor.usr%ROWTYPE;
6715     age_protect_object    config.rule_age_hold_protect%ROWTYPE;
6716     standing_penalty    config.standing_penalty%ROWTYPE;
6717     transit_range_ou_type    actor.org_unit_type%ROWTYPE;
6718     transit_source        actor.org_unit%ROWTYPE;
6719     item_object        asset.copy%ROWTYPE;
6720     ou_skip              actor.org_unit_setting%ROWTYPE;
6721     result            action.matrix_test_result;
6722     hold_test        config.hold_matrix_matchpoint%ROWTYPE;
6723     hold_count        INT;
6724     hold_transit_prox    INT;
6725     frozen_hold_count    INT;
6726     context_org_list    INT[];
6727     done            BOOL := FALSE;
6728 BEGIN
6729     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
6730     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( pickup_ou );
6731
6732     result.success := TRUE;
6733
6734     -- Fail if we couldn't find a user
6735     IF user_object.id IS NULL THEN
6736         result.fail_part := 'no_user';
6737         result.success := FALSE;
6738         done := TRUE;
6739         RETURN NEXT result;
6740         RETURN;
6741     END IF;
6742
6743     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
6744
6745     -- Fail if we couldn't find a copy
6746     IF item_object.id IS NULL THEN
6747         result.fail_part := 'no_item';
6748         result.success := FALSE;
6749         done := TRUE;
6750         RETURN NEXT result;
6751         RETURN;
6752     END IF;
6753
6754     SELECT INTO matchpoint_id action.find_hold_matrix_matchpoint(pickup_ou, request_ou, match_item, match_user, match_requestor);
6755     result.matchpoint := matchpoint_id;
6756
6757     SELECT INTO ou_skip * FROM actor.org_unit_setting WHERE name = 'circ.holds.target_skip_me' AND org_unit = item_object.circ_lib;
6758
6759     -- Fail if the circ_lib for the item has circ.holds.target_skip_me set to true
6760     IF ou_skip.id IS NOT NULL AND ou_skip.value = 'true' THEN
6761         result.fail_part := 'circ.holds.target_skip_me';
6762         result.success := FALSE;
6763         done := TRUE;
6764         RETURN NEXT result;
6765         RETURN;
6766     END IF;
6767
6768     -- Fail if user is barred
6769     IF user_object.barred IS TRUE THEN
6770         result.fail_part := 'actor.usr.barred';
6771         result.success := FALSE;
6772         done := TRUE;
6773         RETURN NEXT result;
6774         RETURN;
6775     END IF;
6776
6777     -- Fail if we couldn't find any matchpoint (requires a default)
6778     IF matchpoint_id IS NULL THEN
6779         result.fail_part := 'no_matchpoint';
6780         result.success := FALSE;
6781         done := TRUE;
6782         RETURN NEXT result;
6783         RETURN;
6784     END IF;
6785
6786     SELECT INTO hold_test * FROM config.hold_matrix_matchpoint WHERE id = matchpoint_id;
6787
6788     IF hold_test.holdable IS FALSE THEN
6789         result.fail_part := 'config.hold_matrix_test.holdable';
6790         result.success := FALSE;
6791         done := TRUE;
6792         RETURN NEXT result;
6793     END IF;
6794
6795     IF hold_test.transit_range IS NOT NULL THEN
6796         SELECT INTO transit_range_ou_type * FROM actor.org_unit_type WHERE id = hold_test.transit_range;
6797         IF hold_test.distance_is_from_owner THEN
6798             SELECT INTO transit_source ou.* FROM actor.org_unit ou JOIN asset.call_number cn ON (cn.owning_lib = ou.id) WHERE cn.id = item_object.call_number;
6799         ELSE
6800             SELECT INTO transit_source * FROM actor.org_unit WHERE id = item_object.circ_lib;
6801         END IF;
6802
6803         PERFORM * FROM actor.org_unit_descendants( transit_source.id, transit_range_ou_type.depth ) WHERE id = pickup_ou;
6804
6805         IF NOT FOUND THEN
6806             result.fail_part := 'transit_range';
6807             result.success := FALSE;
6808             done := TRUE;
6809             RETURN NEXT result;
6810         END IF;
6811     END IF;
6812  
6813     IF NOT retargetting THEN
6814         FOR standing_penalty IN
6815             SELECT  DISTINCT csp.*
6816               FROM  actor.usr_standing_penalty usp
6817                     JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
6818               WHERE usr = match_user
6819                     AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
6820                     AND (usp.stop_date IS NULL or usp.stop_date > NOW())
6821                     AND csp.block_list LIKE '%HOLD%' LOOP
6822     
6823             result.fail_part := standing_penalty.name;
6824             result.success := FALSE;
6825             done := TRUE;
6826             RETURN NEXT result;
6827         END LOOP;
6828     
6829         IF hold_test.stop_blocked_user IS TRUE THEN
6830             FOR standing_penalty IN
6831                 SELECT  DISTINCT csp.*
6832                   FROM  actor.usr_standing_penalty usp
6833                         JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
6834                   WHERE usr = match_user
6835                         AND usp.org_unit IN ( SELECT * FROM explode_array(context_org_list) )
6836                         AND (usp.stop_date IS NULL or usp.stop_date > NOW())
6837                         AND csp.block_list LIKE '%CIRC%' LOOP
6838         
6839                 result.fail_part := standing_penalty.name;
6840                 result.success := FALSE;
6841                 done := TRUE;
6842                 RETURN NEXT result;
6843             END LOOP;
6844         END IF;
6845     
6846         IF hold_test.max_holds IS NOT NULL THEN
6847             SELECT    INTO hold_count COUNT(*)
6848               FROM    action.hold_request
6849               WHERE    usr = match_user
6850                 AND fulfillment_time IS NULL
6851                 AND cancel_time IS NULL
6852                 AND CASE WHEN hold_test.include_frozen_holds THEN TRUE ELSE frozen IS FALSE END;
6853     
6854             IF hold_count >= hold_test.max_holds THEN
6855                 result.fail_part := 'config.hold_matrix_test.max_holds';
6856                 result.success := FALSE;
6857                 done := TRUE;
6858                 RETURN NEXT result;
6859             END IF;
6860         END IF;
6861     END IF;
6862
6863     IF item_object.age_protect IS NOT NULL THEN
6864         SELECT INTO age_protect_object * FROM config.rule_age_hold_protect WHERE id = item_object.age_protect;
6865
6866         IF item_object.create_date + age_protect_object.age > NOW() THEN
6867             IF hold_test.distance_is_from_owner THEN
6868                 SELECT INTO hold_transit_prox prox FROM actor.org_unit_proximity WHERE from_org = item_cn_object.owning_lib AND to_org = pickup_ou;
6869             ELSE
6870                 SELECT INTO hold_transit_prox prox FROM actor.org_unit_proximity WHERE from_org = item_object.circ_lib AND to_org = pickup_ou;
6871             END IF;
6872
6873             IF hold_transit_prox > age_protect_object.prox THEN
6874                 result.fail_part := 'config.rule_age_hold_protect.prox';
6875                 result.success := FALSE;
6876                 done := TRUE;
6877                 RETURN NEXT result;
6878             END IF;
6879         END IF;
6880     END IF;
6881
6882     IF NOT done THEN
6883         RETURN NEXT result;
6884     END IF;
6885
6886     RETURN;
6887 END;
6888 $func$ LANGUAGE plpgsql;
6889
6890 CREATE OR REPLACE FUNCTION action.hold_request_permit_test( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT ) RETURNS SETOF action.matrix_test_result AS $func$
6891     SELECT * FROM action.hold_request_permit_test( $1, $2, $3, $4, $5, FALSE);
6892 $func$ LANGUAGE SQL;
6893
6894 CREATE OR REPLACE FUNCTION action.hold_retarget_permit_test( pickup_ou INT, request_ou INT, match_item BIGINT, match_user INT, match_requestor INT ) RETURNS SETOF action.matrix_test_result AS $func$
6895     SELECT * FROM action.hold_request_permit_test( $1, $2, $3, $4, $5, TRUE );
6896 $func$ LANGUAGE SQL;
6897
6898 -- New post-delete trigger to propagate deletions to parent(s)
6899
6900 CREATE OR REPLACE FUNCTION action.age_parent_circ_on_delete () RETURNS TRIGGER AS $$
6901 BEGIN
6902
6903     -- Having deleted a renewal, we can delete the original circulation (or a previous
6904     -- renewal, if that's what parent_circ is pointing to).  That deletion will trigger
6905     -- deletion of any prior parents, etc. recursively.
6906
6907     IF OLD.parent_circ IS NOT NULL THEN
6908         DELETE FROM action.circulation
6909         WHERE id = OLD.parent_circ;
6910     END IF;
6911
6912     RETURN OLD;
6913 END;
6914 $$ LANGUAGE 'plpgsql';
6915
6916 CREATE TRIGGER age_parent_circ AFTER DELETE ON action.circulation
6917 FOR EACH ROW EXECUTE PROCEDURE action.age_parent_circ_on_delete ();
6918
6919 -- This only gets inserted if there are no other id > 100 billing types
6920 INSERT INTO config.billing_type (id, name, owner) SELECT DISTINCT 101, oils_i18n_gettext(101, 'Misc', 'cbt', 'name'), 1 FROM config.billing_type_id_seq WHERE last_value < 101;
6921 SELECT SETVAL('config.billing_type_id_seq'::TEXT, 101) FROM config.billing_type_id_seq WHERE last_value < 101;
6922
6923 -- Populate xact_type column in the materialized version of billable_xact_summary
6924
6925 CREATE OR REPLACE FUNCTION money.mat_summary_create () RETURNS TRIGGER AS $$
6926 BEGIN
6927         INSERT INTO money.materialized_billable_xact_summary (id, usr, xact_start, xact_finish, total_paid, total_owed, balance_owed, xact_type)
6928                 VALUES ( NEW.id, NEW.usr, NEW.xact_start, NEW.xact_finish, 0.0, 0.0, 0.0, TG_ARGV[0]);
6929         RETURN NEW;
6930 END;
6931 $$ LANGUAGE PLPGSQL;
6932  
6933 DROP TRIGGER IF EXISTS mat_summary_create_tgr ON action.circulation;
6934 CREATE TRIGGER mat_summary_create_tgr AFTER INSERT ON action.circulation FOR EACH ROW EXECUTE PROCEDURE money.mat_summary_create ('circulation');
6935  
6936 DROP TRIGGER IF EXISTS mat_summary_create_tgr ON money.grocery;
6937 CREATE TRIGGER mat_summary_create_tgr AFTER INSERT ON money.grocery FOR EACH ROW EXECUTE PROCEDURE money.mat_summary_create ('grocery');
6938
6939 CREATE RULE money_payment_view_update AS ON UPDATE TO money.payment_view DO INSTEAD 
6940     UPDATE money.payment SET xact = NEW.xact, payment_ts = NEW.payment_ts, voided = NEW.voided, amount = NEW.amount, note = NEW.note WHERE id = NEW.id;
6941
6942 -- Generate the equivalent of compound subject entries from the existing rows
6943 -- so that we don't have to laboriously reindex them
6944
6945 --INSERT INTO config.metabib_field (field_class, name, format, xpath ) VALUES
6946 --    ( 'subject', 'complete', 'mods32', $$//mods32:mods/mods32:subject//text()$$ );
6947 --
6948 --CREATE INDEX metabib_subject_field_entry_source_idx ON metabib.subject_field_entry (source);
6949 --
6950 --INSERT INTO metabib.subject_field_entry (source, field, value)
6951 --    SELECT source, (
6952 --            SELECT id 
6953 --            FROM config.metabib_field
6954 --            WHERE field_class = 'subject' AND name = 'complete'
6955 --        ), 
6956 --        ARRAY_TO_STRING ( 
6957 --            ARRAY (
6958 --                SELECT value 
6959 --                FROM metabib.subject_field_entry msfe
6960 --                WHERE msfe.source = groupee.source
6961 --                ORDER BY source 
6962 --            ), ' ' 
6963 --        ) AS grouped
6964 --    FROM ( 
6965 --        SELECT source
6966 --        FROM metabib.subject_field_entry
6967 --        GROUP BY source
6968 --    ) AS groupee;
6969
6970 CREATE OR REPLACE FUNCTION money.materialized_summary_billing_del () RETURNS TRIGGER AS $$
6971 DECLARE
6972         prev_billing    money.billing%ROWTYPE;
6973         old_billing     money.billing%ROWTYPE;
6974 BEGIN
6975         SELECT * INTO prev_billing FROM money.billing WHERE xact = OLD.xact AND NOT voided ORDER BY billing_ts DESC LIMIT 1 OFFSET 1;
6976         SELECT * INTO old_billing FROM money.billing WHERE xact = OLD.xact AND NOT voided ORDER BY billing_ts DESC LIMIT 1;
6977
6978         IF OLD.id = old_billing.id THEN
6979                 UPDATE  money.materialized_billable_xact_summary
6980                   SET   last_billing_ts = prev_billing.billing_ts,
6981                         last_billing_note = prev_billing.note,
6982                         last_billing_type = prev_billing.billing_type
6983                   WHERE id = OLD.xact;
6984         END IF;
6985
6986         IF NOT OLD.voided THEN
6987                 UPDATE  money.materialized_billable_xact_summary
6988                   SET   total_owed = total_owed - OLD.amount,
6989                         balance_owed = balance_owed + OLD.amount
6990                   WHERE id = OLD.xact;
6991         END IF;
6992
6993         RETURN OLD;
6994 END;
6995 $$ LANGUAGE PLPGSQL;
6996
6997 -- ARG! need to rid ourselves of the broken table definition ... this mechanism is not ideal, sorry.
6998 DROP TABLE IF EXISTS config.index_normalizer CASCADE;
6999
7000 CREATE OR REPLACE FUNCTION public.naco_normalize( TEXT, TEXT ) RETURNS TEXT AS $func$
7001     use Unicode::Normalize;
7002     use Encode;
7003
7004     # When working with Unicode data, the first step is to decode it to
7005     # a byte string; after that, lowercasing is safe
7006     my $txt = lc(decode_utf8(shift));
7007     my $sf = shift;
7008
7009     $txt = NFD($txt);
7010     $txt =~ s/\pM+//go; # Remove diacritics
7011
7012     # remove non-combining diacritics
7013     # this list of characters follows the NACO normalization spec,
7014     # but a looser but more comprehensive version might be
7015     # $txt =~ s/\pLm+//go;
7016     $txt =~ tr/\x{02B9}\x{02BA}\x{02BB}\x{02BC}//d;
7017
7018     $txt =~ s/\xE6/AE/go;   # Convert ae digraph
7019     $txt =~ s/\x{153}/OE/go;# Convert oe digraph
7020     $txt =~ s/\xFE/TH/go;   # Convert Icelandic thorn
7021
7022     $txt =~ tr/\x{2070}\x{2071}\x{2072}\x{2073}\x{2074}\x{2075}\x{2076}\x{2077}\x{2078}\x{2079}\x{207A}\x{207B}/0123456789+-/;# Convert superscript numbers
7023     $txt =~ tr/\x{2080}\x{2081}\x{2082}\x{2083}\x{2084}\x{2085}\x{2086}\x{2087}\x{2088}\x{2089}\x{208A}\x{208B}/0123456889+-/;# Convert subscript numbers
7024
7025     $txt =~ tr/\x{0251}\x{03B1}\x{03B2}\x{0262}\x{03B3}/AABGG/;     # Convert Latin and Greek
7026     $txt =~ tr/\x{2113}\xF0\x{111}\!\"\(\)\-\{\}\<\>\;\:\.\?\xA1\xBF\/\\\@\*\%\=\xB1\+\xAE\xA9\x{2117}\$\xA3\x{FFE1}\xB0\^\_\~\`/LDD /; # Convert Misc
7027     $txt =~ tr/\'\[\]\|//d;                         # Remove Misc
7028
7029     if ($sf && $sf =~ /^a/o) {
7030         my $commapos = index($txt,',');
7031         if ($commapos > -1) {
7032             if ($commapos != length($txt) - 1) {
7033                 my @list = split /,/, $txt;
7034                 my $first = shift @list;
7035                 $txt = $first . ',' . join(' ', @list);
7036             } else {
7037                 $txt =~ s/,/ /go;
7038             }
7039         }
7040     } else {
7041         $txt =~ s/,/ /go;
7042     }
7043
7044     $txt =~ s/\s+/ /go; # Compress multiple spaces
7045     $txt =~ s/^\s+//o;  # Remove leading space
7046     $txt =~ s/\s+$//o;  # Remove trailing space
7047
7048     # Encoding the outgoing string is good practice, but not strictly
7049     # necessary in this case because we've stripped everything from it
7050     return encode_utf8($txt);
7051 $func$ LANGUAGE 'plperlu' STRICT IMMUTABLE;
7052
7053 -- Some handy functions, based on existing ones, to provide optional ingest normalization
7054
7055 CREATE OR REPLACE FUNCTION public.left_trunc( TEXT, INT ) RETURNS TEXT AS $func$
7056         SELECT SUBSTRING($1,$2);
7057 $func$ LANGUAGE SQL STRICT IMMUTABLE;
7058
7059 CREATE OR REPLACE FUNCTION public.right_trunc( TEXT, INT ) RETURNS TEXT AS $func$
7060         SELECT SUBSTRING($1,1,$2);
7061 $func$ LANGUAGE SQL STRICT IMMUTABLE;
7062
7063 CREATE OR REPLACE FUNCTION public.naco_normalize_keep_comma( TEXT ) RETURNS TEXT AS $func$
7064         SELECT public.naco_normalize($1,'a');
7065 $func$ LANGUAGE SQL STRICT IMMUTABLE;
7066
7067 CREATE OR REPLACE FUNCTION public.split_date_range( TEXT ) RETURNS TEXT AS $func$
7068         SELECT REGEXP_REPLACE( $1, E'(\\d{4})-(\\d{4})', E'\\1 \\2', 'g' );
7069 $func$ LANGUAGE SQL STRICT IMMUTABLE;
7070
7071 -- And ... a table in which to register them
7072
7073 CREATE TABLE config.index_normalizer (
7074         id              SERIAL  PRIMARY KEY,
7075         name            TEXT    UNIQUE NOT NULL,
7076         description     TEXT,
7077         func            TEXT    NOT NULL,
7078         param_count     INT     NOT NULL DEFAULT 0
7079 );
7080
7081 CREATE TABLE config.metabib_field_index_norm_map (
7082         id      SERIAL  PRIMARY KEY,
7083         field   INT     NOT NULL REFERENCES config.metabib_field (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
7084         norm    INT     NOT NULL REFERENCES config.index_normalizer (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
7085         params  TEXT,
7086         pos     INT     NOT NULL DEFAULT 0
7087 );
7088
7089 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7090         'NACO Normalize',
7091         'Apply NACO normalization rules to the extracted text.  See http://www.loc.gov/catdir/pcc/naco/normrule-2.html for details.',
7092         'naco_normalize',
7093         0
7094 );
7095
7096 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7097         'Normalize date range',
7098         'Split date ranges in the form of "XXXX-YYYY" into "XXXX YYYY" for proper index.',
7099         'split_date_range',
7100         1
7101 );
7102
7103 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7104         'NACO Normalize -- retain first comma',
7105         'Apply NACO normalization rules to the extracted text, retaining the first comma.  See http://www.loc.gov/catdir/pcc/naco/normrule-2.html for details.',
7106         'naco_normalize_keep_comma',
7107         0
7108 );
7109
7110 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7111         'Strip Diacritics',
7112         'Convert text to NFD form and remove non-spacing combining marks.',
7113         'remove_diacritics',
7114         0
7115 );
7116
7117 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7118         'Up-case',
7119         'Convert text upper case.',
7120         'uppercase',
7121         0
7122 );
7123
7124 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7125         'Down-case',
7126         'Convert text lower case.',
7127         'lowercase',
7128         0
7129 );
7130
7131 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7132         'Extract Dewey-like number',
7133         'Extract a string of numeric characters ther resembles a DDC number.',
7134         'call_number_dewey',
7135         0
7136 );
7137
7138 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7139         'Left truncation',
7140         'Discard the specified number of characters from the left side of the string.',
7141         'left_trunc',
7142         1
7143 );
7144
7145 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7146         'Right truncation',
7147         'Include only the specified number of characters from the left side of the string.',
7148         'right_trunc',
7149         1
7150 );
7151
7152 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
7153         'First word',
7154         'Include only the first space-separated word of a string.',
7155         'first_word',
7156         0
7157 );
7158
7159 INSERT INTO config.metabib_field_index_norm_map (field,norm)
7160         SELECT  m.id,
7161                 i.id
7162           FROM  config.metabib_field m,
7163                 config.index_normalizer i
7164           WHERE i.func IN ('naco_normalize','split_date_range');
7165
7166 CREATE OR REPLACE FUNCTION oils_tsearch2 () RETURNS TRIGGER AS $$
7167 DECLARE
7168     normalizer      RECORD;
7169     value           TEXT := '';
7170 BEGIN
7171
7172     value := NEW.value;
7173
7174     IF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
7175         FOR normalizer IN
7176             SELECT  n.func AS func,
7177                     n.param_count AS param_count,
7178                     m.params AS params
7179               FROM  config.index_normalizer n
7180                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
7181               WHERE field = NEW.field AND m.pos < 0
7182               ORDER BY m.pos LOOP
7183                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
7184                     quote_literal( value ) ||
7185                     CASE
7186                         WHEN normalizer.param_count > 0
7187                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
7188                             ELSE ''
7189                         END ||
7190                     ')' INTO value;
7191
7192         END LOOP;
7193
7194         NEW.value := value;
7195     END IF;
7196
7197     IF NEW.index_vector = ''::tsvector THEN
7198         RETURN NEW;
7199     END IF;
7200
7201     IF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
7202         FOR normalizer IN
7203             SELECT  n.func AS func,
7204                     n.param_count AS param_count,
7205                     m.params AS params
7206               FROM  config.index_normalizer n
7207                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
7208               WHERE field = NEW.field AND m.pos >= 0
7209               ORDER BY m.pos LOOP
7210                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
7211                     quote_literal( value ) ||
7212                     CASE
7213                         WHEN normalizer.param_count > 0
7214                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
7215                             ELSE ''
7216                         END ||
7217                     ')' INTO value;
7218
7219         END LOOP;
7220     END IF;
7221
7222     IF REGEXP_REPLACE(VERSION(),E'^.+?(\\d+\\.\\d+).*?$',E'\\1')::FLOAT > 8.2 THEN
7223         NEW.index_vector = to_tsvector((TG_ARGV[0])::regconfig, value);
7224     ELSE
7225         NEW.index_vector = to_tsvector(TG_ARGV[0], value);
7226     END IF;
7227
7228     RETURN NEW;
7229 END;
7230 $$ LANGUAGE PLPGSQL;
7231
7232 CREATE OR REPLACE FUNCTION oils_xpath ( TEXT, TEXT, ANYARRAY ) RETURNS TEXT[] AS 'SELECT XPATH( $1, $2::XML, $3 )::TEXT[];' LANGUAGE SQL IMMUTABLE;
7233
7234 CREATE OR REPLACE FUNCTION oils_xpath ( TEXT, TEXT ) RETURNS TEXT[] AS 'SELECT XPATH( $1, $2::XML )::TEXT[];' LANGUAGE SQL IMMUTABLE;
7235
7236 CREATE OR REPLACE FUNCTION oils_xpath_string ( TEXT, TEXT, TEXT, ANYARRAY ) RETURNS TEXT AS $func$
7237     SELECT  ARRAY_TO_STRING(
7238                 oils_xpath(
7239                     $1 ||
7240                         CASE WHEN $1 ~ $re$/[^/[]*@[^]]+$$re$ OR $1 ~ $re$text\(\)$$re$ THEN '' ELSE '//text()' END,
7241                     $2,
7242                     $4
7243                 ),
7244                 $3
7245             );
7246 $func$ LANGUAGE SQL IMMUTABLE;
7247
7248 CREATE OR REPLACE FUNCTION oils_xpath_string ( TEXT, TEXT, TEXT ) RETURNS TEXT AS $func$
7249     SELECT oils_xpath_string( $1, $2, $3, '{}'::TEXT[] );
7250 $func$ LANGUAGE SQL IMMUTABLE;
7251
7252 CREATE OR REPLACE FUNCTION oils_xpath_string ( TEXT, TEXT, ANYARRAY ) RETURNS TEXT AS $func$
7253     SELECT oils_xpath_string( $1, $2, '', $3 );
7254 $func$ LANGUAGE SQL IMMUTABLE;
7255
7256 CREATE OR REPLACE FUNCTION oils_xpath_string ( TEXT, TEXT ) RETURNS TEXT AS $func$
7257     SELECT oils_xpath_string( $1, $2, '{}'::TEXT[] );
7258 $func$ LANGUAGE SQL IMMUTABLE;
7259
7260 CREATE TYPE metabib.field_entry_template AS (
7261         field_class     TEXT,
7262         field           INT,
7263         source          BIGINT,
7264         value           TEXT
7265 );
7266
7267 CREATE OR REPLACE FUNCTION oils_xslt_process(TEXT, TEXT) RETURNS TEXT AS $func$
7268   use strict;
7269
7270   use XML::LibXSLT;
7271   use XML::LibXML;
7272
7273   my $doc = shift;
7274   my $xslt = shift;
7275
7276   # The following approach uses the older XML::LibXML 1.69 / XML::LibXSLT 1.68
7277   # methods of parsing XML documents and stylesheets, in the hopes of broader
7278   # compatibility with distributions
7279   my $parser = $_SHARED{'_xslt_process'}{parsers}{xml} || XML::LibXML->new();
7280
7281   # Cache the XML parser, if we do not already have one
7282   $_SHARED{'_xslt_process'}{parsers}{xml} = $parser
7283     unless ($_SHARED{'_xslt_process'}{parsers}{xml});
7284
7285   my $xslt_parser = $_SHARED{'_xslt_process'}{parsers}{xslt} || XML::LibXSLT->new();
7286
7287   # Cache the XSLT processor, if we do not already have one
7288   $_SHARED{'_xslt_process'}{parsers}{xslt} = $xslt_parser
7289     unless ($_SHARED{'_xslt_process'}{parsers}{xslt});
7290
7291   my $stylesheet = $_SHARED{'_xslt_process'}{stylesheets}{$xslt} ||
7292     $xslt_parser->parse_stylesheet( $parser->parse_string($xslt) );
7293
7294   $_SHARED{'_xslt_process'}{stylesheets}{$xslt} = $stylesheet
7295     unless ($_SHARED{'_xslt_process'}{stylesheets}{$xslt});
7296
7297   return $stylesheet->output_string(
7298     $stylesheet->transform(
7299       $parser->parse_string($doc)
7300     )
7301   );
7302
7303 $func$ LANGUAGE 'plperlu' STRICT IMMUTABLE;
7304
7305 -- Add two columns so that the following function will compile.
7306 -- Eventually the label column will be NOT NULL, but not yet.
7307 ALTER TABLE config.metabib_field ADD COLUMN label TEXT;
7308 ALTER TABLE config.metabib_field ADD COLUMN facet_xpath TEXT;
7309
7310 CREATE OR REPLACE FUNCTION biblio.extract_metabib_field_entry ( rid BIGINT, default_joiner TEXT ) RETURNS SETOF metabib.field_entry_template AS $func$
7311 DECLARE
7312     bib     biblio.record_entry%ROWTYPE;
7313     idx     config.metabib_field%ROWTYPE;
7314     xfrm        config.xml_transform%ROWTYPE;
7315     prev_xfrm   TEXT;
7316     transformed_xml TEXT;
7317     xml_node    TEXT;
7318     xml_node_list   TEXT[];
7319     facet_text  TEXT;
7320     raw_text    TEXT;
7321     curr_text   TEXT;
7322     joiner      TEXT := default_joiner; -- XXX will index defs supply a joiner?
7323     output_row  metabib.field_entry_template%ROWTYPE;
7324 BEGIN
7325
7326     -- Get the record
7327     SELECT INTO bib * FROM biblio.record_entry WHERE id = rid;
7328
7329     -- Loop over the indexing entries
7330     FOR idx IN SELECT * FROM config.metabib_field ORDER BY format LOOP
7331
7332         SELECT INTO xfrm * from config.xml_transform WHERE name = idx.format;
7333
7334         -- See if we can skip the XSLT ... it's expensive
7335         IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
7336             -- Can't skip the transform
7337             IF xfrm.xslt <> '---' THEN
7338                 transformed_xml := oils_xslt_process(bib.marc,xfrm.xslt);
7339             ELSE
7340                 transformed_xml := bib.marc;
7341             END IF;
7342
7343             prev_xfrm := xfrm.name;
7344         END IF;
7345
7346         xml_node_list := oils_xpath( idx.xpath, transformed_xml, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
7347
7348         raw_text := NULL;
7349         FOR xml_node IN SELECT x FROM explode_array(xml_node_list) AS x LOOP
7350             CONTINUE WHEN xml_node !~ E'^\\s*<';
7351
7352             curr_text := ARRAY_TO_STRING(
7353                 oils_xpath( '//text()',
7354                     REGEXP_REPLACE( -- This escapes all &s not followed by "amp;".  Data ise returned from oils_xpath (above) in UTF-8, not entity encoded
7355                         REGEXP_REPLACE( -- This escapes embeded <s
7356                             xml_node,
7357                             $re$(>[^<]+)(<)([^>]+<)$re$,
7358                             E'\\1&lt;\\3',
7359                             'g'
7360                         ),
7361                         '&(?!amp;)',
7362                         '&amp;',
7363                         'g'
7364                     )
7365                 ),
7366                 ' '
7367             );
7368
7369             CONTINUE WHEN curr_text IS NULL OR curr_text = '';
7370
7371             IF raw_text IS NOT NULL THEN
7372                 raw_text := raw_text || joiner;
7373             END IF;
7374
7375             raw_text := COALESCE(raw_text,'') || curr_text;
7376
7377             -- insert raw node text for faceting
7378             IF idx.facet_field THEN
7379
7380                 IF idx.facet_xpath IS NOT NULL AND idx.facet_xpath <> '' THEN
7381                     facet_text := oils_xpath_string( idx.facet_xpath, xml_node, joiner, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
7382                 ELSE
7383                     facet_text := curr_text;
7384                 END IF;
7385
7386                 output_row.field_class = idx.field_class;
7387                 output_row.field = -1 * idx.id;
7388                 output_row.source = rid;
7389                 output_row.value = BTRIM(REGEXP_REPLACE(facet_text, E'\\s+', ' ', 'g'));
7390
7391                 RETURN NEXT output_row;
7392             END IF;
7393
7394         END LOOP;
7395
7396         CONTINUE WHEN raw_text IS NULL OR raw_text = '';
7397
7398         -- insert combined node text for searching
7399         IF idx.search_field THEN
7400             output_row.field_class = idx.field_class;
7401             output_row.field = idx.id;
7402             output_row.source = rid;
7403             output_row.value = BTRIM(REGEXP_REPLACE(raw_text, E'\\s+', ' ', 'g'));
7404
7405             RETURN NEXT output_row;
7406         END IF;
7407
7408     END LOOP;
7409
7410 END;
7411 $func$ LANGUAGE PLPGSQL;
7412
7413 -- default to a space joiner
7414 CREATE OR REPLACE FUNCTION biblio.extract_metabib_field_entry ( BIGINT ) RETURNS SETOF metabib.field_entry_template AS $func$
7415         SELECT * FROM biblio.extract_metabib_field_entry($1, ' ');
7416 $func$ LANGUAGE SQL;
7417
7418 CREATE OR REPLACE FUNCTION biblio.flatten_marc ( TEXT ) RETURNS SETOF metabib.full_rec AS $func$
7419
7420 use MARC::Record;
7421 use MARC::File::XML (BinaryEncoding => 'UTF-8');
7422
7423 my $xml = shift;
7424 my $r = MARC::Record->new_from_xml( $xml );
7425
7426 return_next( { tag => 'LDR', value => $r->leader } );
7427
7428 for my $f ( $r->fields ) {
7429     if ($f->is_control_field) {
7430         return_next({ tag => $f->tag, value => $f->data });
7431     } else {
7432         for my $s ($f->subfields) {
7433             return_next({
7434                 tag      => $f->tag,
7435                 ind1     => $f->indicator(1),
7436                 ind2     => $f->indicator(2),
7437                 subfield => $s->[0],
7438                 value    => $s->[1]
7439             });
7440
7441             if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
7442                 my $trim = $f->indicator(2) || 0;
7443                 return_next({
7444                     tag      => 'tnf',
7445                     ind1     => $f->indicator(1),
7446                     ind2     => $f->indicator(2),
7447                     subfield => 'a',
7448                     value    => substr( $s->[1], $trim )
7449                 });
7450             }
7451         }
7452     }
7453 }
7454
7455 return undef;
7456
7457 $func$ LANGUAGE PLPERLU;
7458
7459 CREATE OR REPLACE FUNCTION biblio.flatten_marc ( rid BIGINT ) RETURNS SETOF metabib.full_rec AS $func$
7460 DECLARE
7461     bib biblio.record_entry%ROWTYPE;
7462     output  metabib.full_rec%ROWTYPE;
7463     field   RECORD;
7464 BEGIN
7465     SELECT INTO bib * FROM biblio.record_entry WHERE id = rid;
7466
7467     FOR field IN SELECT * FROM biblio.flatten_marc( bib.marc ) LOOP
7468         output.record := rid;
7469         output.ind1 := field.ind1;
7470         output.ind2 := field.ind2;
7471         output.tag := field.tag;
7472         output.subfield := field.subfield;
7473         IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
7474             output.value := naco_normalize(field.value, field.subfield);
7475         ELSE
7476             output.value := field.value;
7477         END IF;
7478
7479         CONTINUE WHEN output.value IS NULL;
7480
7481         RETURN NEXT output;
7482     END LOOP;
7483 END;
7484 $func$ LANGUAGE PLPGSQL;
7485
7486 -- functions to create auditor objects
7487
7488 CREATE FUNCTION auditor.create_auditor_seq     ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
7489 BEGIN
7490     EXECUTE $$
7491         CREATE SEQUENCE auditor.$$ || sch || $$_$$ || tbl || $$_pkey_seq;
7492     $$;
7493         RETURN TRUE;
7494 END;
7495 $creator$ LANGUAGE 'plpgsql';
7496
7497 CREATE FUNCTION auditor.create_auditor_history ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
7498 BEGIN
7499     EXECUTE $$
7500         CREATE TABLE auditor.$$ || sch || $$_$$ || tbl || $$_history (
7501             audit_id    BIGINT                          PRIMARY KEY,
7502             audit_time  TIMESTAMP WITH TIME ZONE        NOT NULL,
7503             audit_action        TEXT                            NOT NULL,
7504             LIKE $$ || sch || $$.$$ || tbl || $$
7505         );
7506     $$;
7507         RETURN TRUE;
7508 END;
7509 $creator$ LANGUAGE 'plpgsql';
7510
7511 CREATE FUNCTION auditor.create_auditor_func    ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
7512 BEGIN
7513     EXECUTE $$
7514         CREATE FUNCTION auditor.audit_$$ || sch || $$_$$ || tbl || $$_func ()
7515         RETURNS TRIGGER AS $func$
7516         BEGIN
7517             INSERT INTO auditor.$$ || sch || $$_$$ || tbl || $$_history
7518                 SELECT  nextval('auditor.$$ || sch || $$_$$ || tbl || $$_pkey_seq'),
7519                     now(),
7520                     SUBSTR(TG_OP,1,1),
7521                     OLD.*;
7522             RETURN NULL;
7523         END;
7524         $func$ LANGUAGE 'plpgsql';
7525     $$;
7526         RETURN TRUE;
7527 END;
7528 $creator$ LANGUAGE 'plpgsql';
7529
7530 CREATE FUNCTION auditor.create_auditor_update_trigger ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
7531 BEGIN
7532     EXECUTE $$
7533         CREATE TRIGGER audit_$$ || sch || $$_$$ || tbl || $$_update_trigger
7534             AFTER UPDATE OR DELETE ON $$ || sch || $$.$$ || tbl || $$ FOR EACH ROW
7535             EXECUTE PROCEDURE auditor.audit_$$ || sch || $$_$$ || tbl || $$_func ();
7536     $$;
7537         RETURN TRUE;
7538 END;
7539 $creator$ LANGUAGE 'plpgsql';
7540
7541 CREATE FUNCTION auditor.create_auditor_lifecycle     ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
7542 BEGIN
7543     EXECUTE $$
7544         CREATE VIEW auditor.$$ || sch || $$_$$ || tbl || $$_lifecycle AS
7545             SELECT      -1, now() as audit_time, '-' as audit_action, *
7546               FROM      $$ || sch || $$.$$ || tbl || $$
7547                 UNION ALL
7548             SELECT      *
7549               FROM      auditor.$$ || sch || $$_$$ || tbl || $$_history;
7550     $$;
7551         RETURN TRUE;
7552 END;
7553 $creator$ LANGUAGE 'plpgsql';
7554
7555 DROP FUNCTION IF EXISTS auditor.create_auditor (TEXT, TEXT);
7556
7557 -- The main event
7558
7559 CREATE FUNCTION auditor.create_auditor ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
7560 BEGIN
7561     PERFORM auditor.create_auditor_seq(sch, tbl);
7562     PERFORM auditor.create_auditor_history(sch, tbl);
7563     PERFORM auditor.create_auditor_func(sch, tbl);
7564     PERFORM auditor.create_auditor_update_trigger(sch, tbl);
7565     PERFORM auditor.create_auditor_lifecycle(sch, tbl);
7566     RETURN TRUE;
7567 END;
7568 $creator$ LANGUAGE 'plpgsql';
7569
7570 ALTER TABLE action.hold_request ADD COLUMN cut_in_line BOOL;
7571
7572 ALTER TABLE action.hold_request
7573 ADD COLUMN mint_condition boolean NOT NULL DEFAULT TRUE;
7574
7575 ALTER TABLE action.hold_request
7576 ADD COLUMN shelf_expire_time TIMESTAMPTZ;
7577
7578 ALTER TABLE action.hold_request DROP CONSTRAINT hold_request_current_copy_fkey;
7579
7580 ALTER TABLE action.hold_request DROP CONSTRAINT hold_request_hold_type_check;
7581
7582 UPDATE config.index_normalizer SET param_count = 0 WHERE func = 'split_date_range';
7583
7584 CREATE INDEX actor_usr_usrgroup_idx ON actor.usr (usrgroup);
7585
7586 -- Add claims_never_checked_out_count to actor.usr, related history
7587
7588 ALTER TABLE actor.usr ADD COLUMN
7589         claims_never_checked_out_count  INT         NOT NULL DEFAULT 0;
7590
7591 ALTER TABLE AUDITOR.actor_usr_history ADD COLUMN 
7592         claims_never_checked_out_count INT;
7593
7594 DROP VIEW IF EXISTS auditor.actor_usr_lifecycle;
7595
7596 SELECT auditor.create_auditor_lifecycle( 'actor', 'usr' );
7597
7598 -----------
7599
7600 CREATE OR REPLACE FUNCTION action.circulation_claims_returned () RETURNS TRIGGER AS $$
7601 BEGIN
7602         IF OLD.stop_fines IS NULL OR OLD.stop_fines <> NEW.stop_fines THEN
7603                 IF NEW.stop_fines = 'CLAIMSRETURNED' THEN
7604                         UPDATE actor.usr SET claims_returned_count = claims_returned_count + 1 WHERE id = NEW.usr;
7605                 END IF;
7606                 IF NEW.stop_fines = 'CLAIMSNEVERCHECKEDOUT' THEN
7607                         UPDATE actor.usr SET claims_never_checked_out_count = claims_never_checked_out_count + 1 WHERE id = NEW.usr;
7608                 END IF;
7609                 IF NEW.stop_fines = 'LOST' THEN
7610                         UPDATE asset.copy SET status = 3 WHERE id = NEW.target_copy;
7611                 END IF;
7612         END IF;
7613         RETURN NEW;
7614 END;
7615 $$ LANGUAGE 'plpgsql';
7616
7617 -- Create new table acq.fund_allocation_percent
7618 -- Populate it from acq.fund_allocation
7619 -- Convert all percentages to amounts in acq.fund_allocation
7620
7621 CREATE TABLE acq.fund_allocation_percent
7622 (
7623     id                   SERIAL            PRIMARY KEY,
7624     funding_source       INT               NOT NULL REFERENCES acq.funding_source
7625                                                DEFERRABLE INITIALLY DEFERRED,
7626     org                  INT               NOT NULL REFERENCES actor.org_unit
7627                                                DEFERRABLE INITIALLY DEFERRED,
7628     fund_code            TEXT,
7629     percent              NUMERIC           NOT NULL,
7630     allocator            INTEGER           NOT NULL REFERENCES actor.usr
7631                                                DEFERRABLE INITIALLY DEFERRED,
7632     note                 TEXT,
7633     create_time          TIMESTAMPTZ       NOT NULL DEFAULT now(),
7634     CONSTRAINT logical_key UNIQUE( funding_source, org, fund_code ),
7635     CONSTRAINT percentage_range CHECK( percent >= 0 AND percent <= 100 )
7636 );
7637
7638 -- Trigger function to validate combination of org_unit and fund_code
7639
7640 CREATE OR REPLACE FUNCTION acq.fund_alloc_percent_val()
7641 RETURNS TRIGGER AS $$
7642 --
7643 DECLARE
7644 --
7645 dummy int := 0;
7646 --
7647 BEGIN
7648     SELECT
7649         1
7650     INTO
7651         dummy
7652     FROM
7653         acq.fund
7654     WHERE
7655         org = NEW.org
7656         AND code = NEW.fund_code
7657         LIMIT 1;
7658     --
7659     IF dummy = 1 then
7660         RETURN NEW;
7661     ELSE
7662         RAISE EXCEPTION 'No fund exists for org % and code %', NEW.org, NEW.fund_code;
7663     END IF;
7664 END;
7665 $$ LANGUAGE plpgsql;
7666
7667 CREATE TRIGGER acq_fund_alloc_percent_val_trig
7668     BEFORE INSERT OR UPDATE ON acq.fund_allocation_percent
7669     FOR EACH ROW EXECUTE PROCEDURE acq.fund_alloc_percent_val();
7670
7671 CREATE OR REPLACE FUNCTION acq.fap_limit_100()
7672 RETURNS TRIGGER AS $$
7673 DECLARE
7674 --
7675 total_percent numeric;
7676 --
7677 BEGIN
7678     SELECT
7679         sum( percent )
7680     INTO
7681         total_percent
7682     FROM
7683         acq.fund_allocation_percent AS fap
7684     WHERE
7685         fap.funding_source = NEW.funding_source;
7686     --
7687     IF total_percent > 100 THEN
7688         RAISE EXCEPTION 'Total percentages exceed 100 for funding_source %',
7689             NEW.funding_source;
7690     ELSE
7691         RETURN NEW;
7692     END IF;
7693 END;
7694 $$ LANGUAGE plpgsql;
7695
7696 CREATE TRIGGER acqfap_limit_100_trig
7697     AFTER INSERT OR UPDATE ON acq.fund_allocation_percent
7698     FOR EACH ROW EXECUTE PROCEDURE acq.fap_limit_100();
7699
7700 -- Populate new table from acq.fund_allocation
7701
7702 INSERT INTO acq.fund_allocation_percent
7703 (
7704     funding_source,
7705     org,
7706     fund_code,
7707     percent,
7708     allocator,
7709     note,
7710     create_time
7711 )
7712     SELECT
7713         fa.funding_source,
7714         fund.org,
7715         fund.code,
7716         fa.percent,
7717         fa.allocator,
7718         fa.note,
7719         fa.create_time
7720     FROM
7721         acq.fund_allocation AS fa
7722             INNER JOIN acq.fund AS fund
7723                 ON ( fa.fund = fund.id )
7724     WHERE
7725         fa.percent is not null
7726     ORDER BY
7727         fund.org;
7728
7729 -- Temporary function to convert percentages to amounts in acq.fund_allocation
7730
7731 -- Algorithm to apply to each funding source:
7732
7733 -- 1. Add up the credits.
7734 -- 2. Add up the percentages.
7735 -- 3. Multiply the sum of the percentages times the sum of the credits.  Drop any
7736 --    fractional cents from the result.  This is the total amount to be allocated.
7737 -- 4. For each allocation: multiply the percentage by the total allocation.  Drop any
7738 --    fractional cents to get a preliminary amount.
7739 -- 5. Add up the preliminary amounts for all the allocations.
7740 -- 6. Subtract the results of step 5 from the result of step 3.  The difference is the
7741 --    number of residual cents (resulting from having dropped fractional cents) that
7742 --    must be distributed across the funds in order to make the total of the amounts
7743 --    match the total allocation.
7744 -- 7. Make a second pass through the allocations, in decreasing order of the fractional
7745 --    cents that were dropped from their amounts in step 4.  Add one cent to the amount
7746 --    for each successive fund, until all the residual cents have been exhausted.
7747
7748 -- Result: the sum of the individual allocations now equals the total to be allocated,
7749 -- to the penny.  The individual amounts match the percentages as closely as possible,
7750 -- given the constraint that the total must match.
7751
7752 CREATE OR REPLACE FUNCTION acq.apply_percents()
7753 RETURNS VOID AS $$
7754 declare
7755 --
7756 tot              RECORD;
7757 fund             RECORD;
7758 tot_cents        INTEGER;
7759 src              INTEGER;
7760 id               INTEGER[];
7761 curr_id          INTEGER;
7762 pennies          NUMERIC[];
7763 curr_amount      NUMERIC;
7764 i                INTEGER;
7765 total_of_floors  INTEGER;
7766 total_percent    NUMERIC;
7767 total_allocation INTEGER;
7768 residue          INTEGER;
7769 --
7770 begin
7771         RAISE NOTICE 'Applying percents';
7772         FOR tot IN
7773                 SELECT
7774                         fsrc.funding_source,
7775                         sum( fsrc.amount ) AS total
7776                 FROM
7777                         acq.funding_source_credit AS fsrc
7778                 WHERE fsrc.funding_source IN
7779                         ( SELECT DISTINCT fa.funding_source
7780                           FROM acq.fund_allocation AS fa
7781                           WHERE fa.percent IS NOT NULL )
7782                 GROUP BY
7783                         fsrc.funding_source
7784         LOOP
7785                 tot_cents = floor( tot.total * 100 );
7786                 src = tot.funding_source;
7787                 RAISE NOTICE 'Funding source % total %',
7788                         src, tot_cents;
7789                 i := 0;
7790                 total_of_floors := 0;
7791                 total_percent := 0;
7792                 --
7793                 FOR fund in
7794                         SELECT
7795                                 fa.id,
7796                                 fa.percent,
7797                                 floor( fa.percent * tot_cents / 100 ) as floor_pennies
7798                         FROM
7799                                 acq.fund_allocation AS fa
7800                         WHERE
7801                                 fa.funding_source = src
7802                                 AND fa.percent IS NOT NULL
7803                         ORDER BY
7804                                 mod( fa.percent * tot_cents / 100, 1 ),
7805                                 fa.fund,
7806                                 fa.id
7807                 LOOP
7808                         RAISE NOTICE '   %: %',
7809                                 fund.id,
7810                                 fund.floor_pennies;
7811                         i := i + 1;
7812                         id[i] = fund.id;
7813                         pennies[i] = fund.floor_pennies;
7814                         total_percent := total_percent + fund.percent;
7815                         total_of_floors := total_of_floors + pennies[i];
7816                 END LOOP;
7817                 total_allocation := floor( total_percent * tot_cents /100 );
7818                 RAISE NOTICE 'Total before distributing residue: %', total_of_floors;
7819                 residue := total_allocation - total_of_floors;
7820                 RAISE NOTICE 'Residue: %', residue;
7821                 --
7822                 -- Post the calculated amounts, revising as needed to
7823                 -- distribute the rounding error
7824                 --
7825                 WHILE i > 0 LOOP
7826                         IF residue > 0 THEN
7827                                 pennies[i] = pennies[i] + 1;
7828                                 residue := residue - 1;
7829                         END IF;
7830                         --
7831                         -- Post amount
7832                         --
7833                         curr_id     := id[i];
7834                         curr_amount := trunc( pennies[i] / 100, 2 );
7835                         --
7836                         UPDATE
7837                                 acq.fund_allocation AS fa
7838                         SET
7839                                 amount = curr_amount,
7840                                 percent = NULL
7841                         WHERE
7842                                 fa.id = curr_id;
7843                         --
7844                         RAISE NOTICE '   ID % and amount %',
7845                                 curr_id,
7846                                 curr_amount;
7847                         i = i - 1;
7848                 END LOOP;
7849         END LOOP;
7850 end;
7851 $$ LANGUAGE 'plpgsql';
7852
7853 -- Run the temporary function
7854
7855 select * from acq.apply_percents();
7856
7857 -- Drop the temporary function now that we're done with it
7858
7859 DROP FUNCTION IF EXISTS acq.apply_percents();
7860
7861 -- Eliminate acq.fund_allocation.percent, which has been moved to the acq.fund_allocation_percent table.
7862
7863 -- If the following step fails, it's probably because there are still some non-null percent values in
7864 -- acq.fund_allocation.  They should have all been converted to amounts, and then set to null, by a
7865 -- previous upgrade step based on 0049.schema.acq_funding_allocation_percent.sql.  If there are any
7866 -- non-null values, then either that step didn't run, or it didn't work, or some non-null values
7867 -- slipped in afterwards.
7868
7869 -- To convert any remaining percents to amounts: create, run, and then drop the temporary stored
7870 -- procedure acq.apply_percents() as defined above.
7871
7872 ALTER TABLE acq.fund_allocation
7873 ALTER COLUMN amount SET NOT NULL;
7874
7875 CREATE OR REPLACE VIEW acq.fund_allocation_total AS
7876     SELECT  fund,
7877             SUM(a.amount * acq.exchange_ratio(s.currency_type, f.currency_type))::NUMERIC(100,2) AS amount
7878     FROM acq.fund_allocation a
7879          JOIN acq.fund f ON (a.fund = f.id)
7880          JOIN acq.funding_source s ON (a.funding_source = s.id)
7881     GROUP BY 1;
7882
7883 CREATE OR REPLACE VIEW acq.funding_source_allocation_total AS
7884     SELECT  funding_source,
7885             SUM(a.amount)::NUMERIC(100,2) AS amount
7886     FROM  acq.fund_allocation a
7887     GROUP BY 1;
7888
7889 ALTER TABLE acq.fund_allocation
7890 DROP COLUMN percent;
7891
7892 CREATE TABLE asset.copy_location_order
7893 (
7894         id              SERIAL           PRIMARY KEY,
7895         location        INT              NOT NULL
7896                                              REFERENCES asset.copy_location
7897                                              ON DELETE CASCADE
7898                                              DEFERRABLE INITIALLY DEFERRED,
7899         org             INT              NOT NULL
7900                                              REFERENCES actor.org_unit
7901                                              ON DELETE CASCADE
7902                                              DEFERRABLE INITIALLY DEFERRED,
7903         position        INT              NOT NULL DEFAULT 0,
7904         CONSTRAINT acplo_once_per_org UNIQUE ( location, org )
7905 );
7906
7907 ALTER TABLE money.credit_card_payment ADD COLUMN cc_processor TEXT;
7908
7909 -- If you ran this before its most recent incarnation:
7910 -- delete from config.upgrade_log where version = '0328';
7911 -- alter table money.credit_card_payment drop column cc_name;
7912
7913 ALTER TABLE money.credit_card_payment ADD COLUMN cc_first_name TEXT;
7914 ALTER TABLE money.credit_card_payment ADD COLUMN cc_last_name TEXT;
7915
7916 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$
7917 DECLARE
7918     current_group    permission.grp_tree%ROWTYPE;
7919     user_object    actor.usr%ROWTYPE;
7920     item_object    asset.copy%ROWTYPE;
7921     cn_object    asset.call_number%ROWTYPE;
7922     rec_descriptor    metabib.rec_descriptor%ROWTYPE;
7923     current_mp    config.circ_matrix_matchpoint%ROWTYPE;
7924     matchpoint    config.circ_matrix_matchpoint%ROWTYPE;
7925 BEGIN
7926     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
7927     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
7928     SELECT INTO cn_object * FROM asset.call_number WHERE id = item_object.call_number;
7929     SELECT INTO rec_descriptor r.* FROM metabib.rec_descriptor r JOIN asset.call_number c USING (record) WHERE c.id = item_object.call_number;
7930     SELECT INTO current_group * FROM permission.grp_tree WHERE id = user_object.profile;
7931
7932     LOOP 
7933         -- for each potential matchpoint for this ou and group ...
7934         FOR current_mp IN
7935             SELECT  m.*
7936               FROM  config.circ_matrix_matchpoint m
7937                     JOIN actor.org_unit_ancestors( context_ou ) d ON (m.org_unit = d.id)
7938                     LEFT JOIN actor.org_unit_proximity p ON (p.from_org = context_ou AND p.to_org = d.id)
7939               WHERE m.grp = current_group.id
7940                     AND m.active
7941                     AND (m.copy_owning_lib IS NULL OR cn_object.owning_lib IN ( SELECT id FROM actor.org_unit_descendants(m.copy_owning_lib) ))
7942                     AND (m.copy_circ_lib   IS NULL OR item_object.circ_lib IN ( SELECT id FROM actor.org_unit_descendants(m.copy_circ_lib)   ))
7943               ORDER BY    CASE WHEN p.prox        IS NULL THEN 999 ELSE p.prox END,
7944                     CASE WHEN m.copy_owning_lib IS NOT NULL
7945                         THEN 256 / ( SELECT COALESCE(prox, 255) + 1 FROM actor.org_unit_proximity WHERE to_org = cn_object.owning_lib AND from_org = m.copy_owning_lib LIMIT 1 )
7946                         ELSE 0
7947                     END +
7948                     CASE WHEN m.copy_circ_lib IS NOT NULL
7949                         THEN 256 / ( SELECT COALESCE(prox, 255) + 1 FROM actor.org_unit_proximity WHERE to_org = item_object.circ_lib AND from_org = m.copy_circ_lib LIMIT 1 )
7950                         ELSE 0
7951                     END +
7952                     CASE WHEN m.is_renewal = renewal        THEN 128 ELSE 0 END +
7953                     CASE WHEN m.juvenile_flag    IS NOT NULL THEN 64 ELSE 0 END +
7954                     CASE WHEN m.circ_modifier    IS NOT NULL THEN 32 ELSE 0 END +
7955                     CASE WHEN m.marc_type        IS NOT NULL THEN 16 ELSE 0 END +
7956                     CASE WHEN m.marc_form        IS NOT NULL THEN 8 ELSE 0 END +
7957                     CASE WHEN m.marc_vr_format    IS NOT NULL THEN 4 ELSE 0 END +
7958                     CASE WHEN m.ref_flag        IS NOT NULL THEN 2 ELSE 0 END +
7959                     CASE WHEN m.usr_age_lower_bound    IS NOT NULL THEN 0.5 ELSE 0 END +
7960                     CASE WHEN m.usr_age_upper_bound    IS NOT NULL THEN 0.5 ELSE 0 END DESC LOOP
7961
7962             IF current_mp.is_renewal IS NOT NULL THEN
7963                 CONTINUE WHEN current_mp.is_renewal <> renewal;
7964             END IF;
7965
7966             IF current_mp.circ_modifier IS NOT NULL THEN
7967                 CONTINUE WHEN current_mp.circ_modifier <> item_object.circ_modifier OR item_object.circ_modifier IS NULL;
7968             END IF;
7969
7970             IF current_mp.marc_type IS NOT NULL THEN
7971                 IF item_object.circ_as_type IS NOT NULL THEN
7972                     CONTINUE WHEN current_mp.marc_type <> item_object.circ_as_type;
7973                 ELSE
7974                     CONTINUE WHEN current_mp.marc_type <> rec_descriptor.item_type;
7975                 END IF;
7976             END IF;
7977
7978             IF current_mp.marc_form IS NOT NULL THEN
7979                 CONTINUE WHEN current_mp.marc_form <> rec_descriptor.item_form;
7980             END IF;
7981
7982             IF current_mp.marc_vr_format IS NOT NULL THEN
7983                 CONTINUE WHEN current_mp.marc_vr_format <> rec_descriptor.vr_format;
7984             END IF;
7985
7986             IF current_mp.ref_flag IS NOT NULL THEN
7987                 CONTINUE WHEN current_mp.ref_flag <> item_object.ref;
7988             END IF;
7989
7990             IF current_mp.juvenile_flag IS NOT NULL THEN
7991                 CONTINUE WHEN current_mp.juvenile_flag <> user_object.juvenile;
7992             END IF;
7993
7994             IF current_mp.usr_age_lower_bound IS NOT NULL THEN
7995                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_lower_bound < age(user_object.dob);
7996             END IF;
7997
7998             IF current_mp.usr_age_upper_bound IS NOT NULL THEN
7999                 CONTINUE WHEN user_object.dob IS NULL OR current_mp.usr_age_upper_bound > age(user_object.dob);
8000             END IF;
8001
8002
8003             -- everything was undefined or matched
8004             matchpoint = current_mp;
8005
8006             EXIT WHEN matchpoint.id IS NOT NULL;
8007         END LOOP;
8008
8009         EXIT WHEN current_group.parent IS NULL OR matchpoint.id IS NOT NULL;
8010
8011         SELECT INTO current_group * FROM permission.grp_tree WHERE id = current_group.parent;
8012     END LOOP;
8013
8014     RETURN matchpoint;
8015 END;
8016 $func$ LANGUAGE plpgsql;
8017
8018 CREATE TYPE action.hold_stats AS (
8019     hold_count              INT,
8020     copy_count              INT,
8021     available_count         INT,
8022     total_copy_ratio        FLOAT,
8023     available_copy_ratio    FLOAT
8024 );
8025
8026 CREATE OR REPLACE FUNCTION action.copy_related_hold_stats (copy_id INT) RETURNS action.hold_stats AS $func$
8027 DECLARE
8028     output          action.hold_stats%ROWTYPE;
8029     hold_count      INT := 0;
8030     copy_count      INT := 0;
8031     available_count INT := 0;
8032     hold_map_data   RECORD;
8033 BEGIN
8034
8035     output.hold_count := 0;
8036     output.copy_count := 0;
8037     output.available_count := 0;
8038
8039     SELECT  COUNT( DISTINCT m.hold ) INTO hold_count
8040       FROM  action.hold_copy_map m
8041             JOIN action.hold_request h ON (m.hold = h.id)
8042       WHERE m.target_copy = copy_id
8043             AND NOT h.frozen;
8044
8045     output.hold_count := hold_count;
8046
8047     IF output.hold_count > 0 THEN
8048         FOR hold_map_data IN
8049             SELECT  DISTINCT m.target_copy,
8050                     acp.status
8051               FROM  action.hold_copy_map m
8052                     JOIN asset.copy acp ON (m.target_copy = acp.id)
8053                     JOIN action.hold_request h ON (m.hold = h.id)
8054               WHERE m.hold IN ( SELECT DISTINCT hold FROM action.hold_copy_map WHERE target_copy = copy_id ) AND NOT h.frozen
8055         LOOP
8056             output.copy_count := output.copy_count + 1;
8057             IF hold_map_data.status IN (0,7,12) THEN
8058                 output.available_count := output.available_count + 1;
8059             END IF;
8060         END LOOP;
8061         output.total_copy_ratio = output.copy_count::FLOAT / output.hold_count::FLOAT;
8062         output.available_copy_ratio = output.available_count::FLOAT / output.hold_count::FLOAT;
8063
8064     END IF;
8065
8066     RETURN output;
8067
8068 END;
8069 $func$ LANGUAGE PLPGSQL;
8070
8071 ALTER TABLE config.circ_matrix_matchpoint ADD COLUMN total_copy_hold_ratio FLOAT;
8072 ALTER TABLE config.circ_matrix_matchpoint ADD COLUMN available_copy_hold_ratio FLOAT;
8073
8074 ALTER TABLE config.circ_matrix_matchpoint DROP CONSTRAINT ep_once_per_grp_loc_mod_marc;
8075
8076 ALTER TABLE config.circ_matrix_matchpoint ADD COLUMN copy_circ_lib   INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED;
8077 ALTER TABLE config.circ_matrix_matchpoint ADD COLUMN copy_owning_lib INT REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED;
8078
8079 ALTER TABLE config.circ_matrix_matchpoint ADD CONSTRAINT ep_once_per_grp_loc_mod_marc UNIQUE (
8080     grp, org_unit, circ_modifier, marc_type, marc_form, marc_vr_format, ref_flag,
8081     juvenile_flag, usr_age_lower_bound, usr_age_upper_bound, is_renewal, copy_circ_lib,
8082     copy_owning_lib
8083 );
8084
8085 -- Return the correct fail_part when the item can't be found
8086 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$
8087 DECLARE
8088     user_object        actor.usr%ROWTYPE;
8089     standing_penalty    config.standing_penalty%ROWTYPE;
8090     item_object        asset.copy%ROWTYPE;
8091     item_status_object    config.copy_status%ROWTYPE;
8092     item_location_object    asset.copy_location%ROWTYPE;
8093     result            action.matrix_test_result;
8094     circ_test        config.circ_matrix_matchpoint%ROWTYPE;
8095     out_by_circ_mod        config.circ_matrix_circ_mod_test%ROWTYPE;
8096     circ_mod_map        config.circ_matrix_circ_mod_test_map%ROWTYPE;
8097     hold_ratio          action.hold_stats%ROWTYPE;
8098     penalty_type         TEXT;
8099     tmp_grp         INT;
8100     items_out        INT;
8101     context_org_list        INT[];
8102     done            BOOL := FALSE;
8103 BEGIN
8104     result.success := TRUE;
8105
8106     -- Fail if the user is BARRED
8107     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
8108
8109     -- Fail if we couldn't find the user 
8110     IF user_object.id IS NULL THEN
8111         result.fail_part := 'no_user';
8112         result.success := FALSE;
8113         done := TRUE;
8114         RETURN NEXT result;
8115         RETURN;
8116     END IF;
8117
8118     SELECT INTO item_object * FROM asset.copy WHERE id = match_item;
8119
8120     -- Fail if we couldn't find the item 
8121     IF item_object.id IS NULL THEN
8122         result.fail_part := 'no_item';
8123         result.success := FALSE;
8124         done := TRUE;
8125         RETURN NEXT result;
8126         RETURN;
8127     END IF;
8128
8129     SELECT INTO circ_test * FROM action.find_circ_matrix_matchpoint(circ_ou, match_item, match_user, renewal);
8130     result.matchpoint := circ_test.id;
8131
8132     -- Fail if we couldn't find a matchpoint
8133     IF result.matchpoint IS NULL THEN
8134         result.fail_part := 'no_matchpoint';
8135         result.success := FALSE;
8136         done := TRUE;
8137         RETURN NEXT result;
8138     END IF;
8139
8140     IF user_object.barred IS TRUE THEN
8141         result.fail_part := 'actor.usr.barred';
8142         result.success := FALSE;
8143         done := TRUE;
8144         RETURN NEXT result;
8145     END IF;
8146
8147     -- Fail if the item can't circulate
8148     IF item_object.circulate IS FALSE THEN
8149         result.fail_part := 'asset.copy.circulate';
8150         result.success := FALSE;
8151         done := TRUE;
8152         RETURN NEXT result;
8153     END IF;
8154
8155     -- Fail if the item isn't in a circulateable status on a non-renewal
8156     IF NOT renewal AND item_object.status NOT IN ( 0, 7, 8 ) THEN 
8157         result.fail_part := 'asset.copy.status';
8158         result.success := FALSE;
8159         done := TRUE;
8160         RETURN NEXT result;
8161     ELSIF renewal AND item_object.status <> 1 THEN
8162         result.fail_part := 'asset.copy.status';
8163         result.success := FALSE;
8164         done := TRUE;
8165         RETURN NEXT result;
8166     END IF;
8167
8168     -- Fail if the item can't circulate because of the shelving location
8169     SELECT INTO item_location_object * FROM asset.copy_location WHERE id = item_object.location;
8170     IF item_location_object.circulate IS FALSE THEN
8171         result.fail_part := 'asset.copy_location.circulate';
8172         result.success := FALSE;
8173         done := TRUE;
8174         RETURN NEXT result;
8175     END IF;
8176
8177     SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( circ_test.org_unit );
8178
8179     -- Fail if the test is set to hard non-circulating
8180     IF circ_test.circulate IS FALSE THEN
8181         result.fail_part := 'config.circ_matrix_test.circulate';
8182         result.success := FALSE;
8183         done := TRUE;
8184         RETURN NEXT result;
8185     END IF;
8186
8187     -- Fail if the total copy-hold ratio is too low
8188     IF circ_test.total_copy_hold_ratio IS NOT NULL THEN
8189         SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
8190         IF hold_ratio.total_copy_ratio IS NOT NULL AND hold_ratio.total_copy_ratio < circ_test.total_copy_hold_ratio THEN
8191             result.fail_part := 'config.circ_matrix_test.total_copy_hold_ratio';
8192             result.success := FALSE;
8193             done := TRUE;
8194             RETURN NEXT result;
8195         END IF;
8196     END IF;
8197
8198     -- Fail if the available copy-hold ratio is too low
8199     IF circ_test.available_copy_hold_ratio IS NOT NULL THEN
8200         SELECT INTO hold_ratio * FROM action.copy_related_hold_stats(match_item);
8201         IF hold_ratio.available_copy_ratio IS NOT NULL AND hold_ratio.available_copy_ratio < circ_test.available_copy_hold_ratio THEN
8202             result.fail_part := 'config.circ_matrix_test.available_copy_hold_ratio';
8203             result.success := FALSE;
8204             done := TRUE;
8205             RETURN NEXT result;
8206         END IF;
8207     END IF;
8208
8209     IF renewal THEN
8210         penalty_type = '%RENEW%';
8211     ELSE
8212         penalty_type = '%CIRC%';
8213     END IF;
8214
8215     FOR standing_penalty IN
8216         SELECT  DISTINCT csp.*
8217           FROM  actor.usr_standing_penalty usp
8218                 JOIN config.standing_penalty csp ON (csp.id = usp.standing_penalty)
8219           WHERE usr = match_user
8220                 AND usp.org_unit IN ( SELECT * FROM unnest(context_org_list) )
8221                 AND (usp.stop_date IS NULL or usp.stop_date > NOW())
8222                 AND csp.block_list LIKE penalty_type LOOP
8223
8224         result.fail_part := standing_penalty.name;
8225         result.success := FALSE;
8226         done := TRUE;
8227         RETURN NEXT result;
8228     END LOOP;
8229
8230     -- Fail if the user has too many items with specific circ_modifiers checked out
8231     FOR out_by_circ_mod IN SELECT * FROM config.circ_matrix_circ_mod_test WHERE matchpoint = circ_test.id LOOP
8232         SELECT  INTO items_out COUNT(*)
8233           FROM  action.circulation circ
8234             JOIN asset.copy cp ON (cp.id = circ.target_copy)
8235           WHERE circ.usr = match_user
8236                AND circ.circ_lib IN ( SELECT * FROM unnest(context_org_list) )
8237             AND circ.checkin_time IS NULL
8238             AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL)
8239             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);
8240         IF items_out >= out_by_circ_mod.items_out THEN
8241             result.fail_part := 'config.circ_matrix_circ_mod_test';
8242             result.success := FALSE;
8243             done := TRUE;
8244             RETURN NEXT result;
8245         END IF;
8246     END LOOP;
8247
8248     -- If we passed everything, return the successful matchpoint id
8249     IF NOT done THEN
8250         RETURN NEXT result;
8251     END IF;
8252
8253     RETURN;
8254 END;
8255 $func$ LANGUAGE plpgsql;
8256
8257 CREATE TABLE config.remote_account (
8258     id          SERIAL  PRIMARY KEY,
8259     label       TEXT    NOT NULL,
8260     host        TEXT    NOT NULL,   -- name or IP, :port optional
8261     username    TEXT,               -- optional, since we could default to $USER
8262     password    TEXT,               -- optional, since we could use SSH keys, or anonymous login.
8263     account     TEXT,               -- aka profile or FTP "account" command
8264     path        TEXT,               -- aka directory
8265     owner       INT     NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
8266     last_activity TIMESTAMP WITH TIME ZONE
8267 );
8268
8269 CREATE TABLE acq.edi_account (      -- similar tables can extend remote_account for other parts of EG
8270     provider    INT     NOT NULL REFERENCES acq.provider          (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
8271     in_dir      TEXT,   -- incoming messages dir (probably different than config.remote_account.path, the outgoing dir)
8272         vendcode    TEXT,
8273         vendacct    TEXT
8274
8275 ) INHERITS (config.remote_account);
8276
8277 ALTER TABLE acq.edi_account ADD PRIMARY KEY (id);
8278
8279 CREATE TABLE acq.claim_type (
8280         id             SERIAL           PRIMARY KEY,
8281         org_unit       INT              NOT NULL REFERENCES actor.org_unit(id)
8282                                                  DEFERRABLE INITIALLY DEFERRED,
8283         code           TEXT             NOT NULL,
8284         description    TEXT             NOT NULL,
8285         CONSTRAINT claim_type_once_per_org UNIQUE ( org_unit, code )
8286 );
8287
8288 CREATE TABLE acq.claim (
8289         id             SERIAL           PRIMARY KEY,
8290         type           INT              NOT NULL REFERENCES acq.claim_type
8291                                                  DEFERRABLE INITIALLY DEFERRED,
8292         lineitem_detail BIGINT          NOT NULL REFERENCES acq.lineitem_detail
8293                                                  DEFERRABLE INITIALLY DEFERRED
8294 );
8295
8296 CREATE TABLE acq.claim_policy (
8297         id              SERIAL       PRIMARY KEY,
8298         org_unit        INT          NOT NULL REFERENCES actor.org_unit
8299                                      DEFERRABLE INITIALLY DEFERRED,
8300         name            TEXT         NOT NULL,
8301         description     TEXT         NOT NULL,
8302         CONSTRAINT name_once_per_org UNIQUE (org_unit, name)
8303 );
8304
8305 -- Add a san column for EDI. 
8306 -- See: http://isbn.org/standards/home/isbn/us/san/san-qa.asp
8307
8308 ALTER TABLE acq.provider ADD COLUMN san INT;
8309
8310 ALTER TABLE acq.provider ALTER COLUMN san TYPE TEXT USING lpad(text(san), 7, '0');
8311
8312 -- null edi_default is OK... it has to be, since we have no values in acq.edi_account yet
8313 ALTER TABLE acq.provider ADD COLUMN edi_default INT REFERENCES acq.edi_account (id) DEFERRABLE INITIALLY DEFERRED;
8314
8315 ALTER TABLE acq.provider
8316         ADD COLUMN active BOOL NOT NULL DEFAULT TRUE;
8317
8318 ALTER TABLE acq.provider
8319         ADD COLUMN prepayment_required BOOLEAN NOT NULL DEFAULT FALSE;
8320
8321 ALTER TABLE acq.provider
8322         ADD COLUMN url TEXT;
8323
8324 ALTER TABLE acq.provider
8325         ADD COLUMN email TEXT;
8326
8327 ALTER TABLE acq.provider
8328         ADD COLUMN phone TEXT;
8329
8330 ALTER TABLE acq.provider
8331         ADD COLUMN fax_phone TEXT;
8332
8333 ALTER TABLE acq.provider
8334         ADD COLUMN default_claim_policy INT
8335                 REFERENCES acq.claim_policy
8336                 DEFERRABLE INITIALLY DEFERRED;
8337
8338 ALTER TABLE action.transit_copy
8339 ADD COLUMN prev_dest INTEGER REFERENCES actor.org_unit( id )
8340                                                          DEFERRABLE INITIALLY DEFERRED;
8341
8342 DROP SCHEMA IF EXISTS booking CASCADE;
8343
8344 CREATE SCHEMA booking;
8345
8346 CREATE TABLE booking.resource_type (
8347         id             SERIAL          PRIMARY KEY,
8348         name           TEXT            NOT NULL,
8349         fine_interval  INTERVAL,
8350         fine_amount    DECIMAL(8,2)    NOT NULL DEFAULT 0,
8351         owner          INT             NOT NULL
8352                                        REFERENCES actor.org_unit( id )
8353                                        DEFERRABLE INITIALLY DEFERRED,
8354         catalog_item   BOOLEAN         NOT NULL DEFAULT FALSE,
8355         transferable   BOOLEAN         NOT NULL DEFAULT FALSE,
8356     record         BIGINT          REFERENCES biblio.record_entry (id)
8357                                        DEFERRABLE INITIALLY DEFERRED,
8358     max_fine       NUMERIC(8,2),
8359     elbow_room     INTERVAL,
8360     CONSTRAINT brt_name_and_record_once_per_owner UNIQUE(owner, name, record)
8361 );
8362
8363 CREATE TABLE booking.resource (
8364         id             SERIAL           PRIMARY KEY,
8365         owner          INT              NOT NULL
8366                                         REFERENCES actor.org_unit(id)
8367                                         DEFERRABLE INITIALLY DEFERRED,
8368         type           INT              NOT NULL
8369                                         REFERENCES booking.resource_type(id)
8370                                         DEFERRABLE INITIALLY DEFERRED,
8371         overbook       BOOLEAN          NOT NULL DEFAULT FALSE,
8372         barcode        TEXT             NOT NULL,
8373         deposit        BOOLEAN          NOT NULL DEFAULT FALSE,
8374         deposit_amount DECIMAL(8,2)     NOT NULL DEFAULT 0.00,
8375         user_fee       DECIMAL(8,2)     NOT NULL DEFAULT 0.00,
8376         CONSTRAINT br_unique UNIQUE (owner, barcode)
8377 );
8378
8379 -- For non-catalog items: hijack barcode for name/description
8380
8381 CREATE TABLE booking.resource_attr (
8382         id              SERIAL          PRIMARY KEY,
8383         owner           INT             NOT NULL
8384                                         REFERENCES actor.org_unit(id)
8385                                         DEFERRABLE INITIALLY DEFERRED,
8386         name            TEXT            NOT NULL,
8387         resource_type   INT             NOT NULL
8388                                         REFERENCES booking.resource_type(id)
8389                                         ON DELETE CASCADE
8390                                         DEFERRABLE INITIALLY DEFERRED,
8391         required        BOOLEAN         NOT NULL DEFAULT FALSE,
8392         CONSTRAINT bra_name_once_per_type UNIQUE(resource_type, name)
8393 );
8394
8395 CREATE TABLE booking.resource_attr_value (
8396         id               SERIAL         PRIMARY KEY,
8397         owner            INT            NOT NULL
8398                                         REFERENCES actor.org_unit(id)
8399                                         DEFERRABLE INITIALLY DEFERRED,
8400         attr             INT            NOT NULL
8401                                         REFERENCES booking.resource_attr(id)
8402                                         DEFERRABLE INITIALLY DEFERRED,
8403         valid_value      TEXT           NOT NULL,
8404         CONSTRAINT brav_logical_key UNIQUE(owner, attr, valid_value)
8405 );
8406
8407 CREATE TABLE booking.resource_attr_map (
8408         id               SERIAL         PRIMARY KEY,
8409         resource         INT            NOT NULL
8410                                         REFERENCES booking.resource(id)
8411                                         ON DELETE CASCADE
8412                                         DEFERRABLE INITIALLY DEFERRED,
8413         resource_attr    INT            NOT NULL
8414                                         REFERENCES booking.resource_attr(id)
8415                                         ON DELETE CASCADE
8416                                         DEFERRABLE INITIALLY DEFERRED,
8417         value            INT            NOT NULL
8418                                         REFERENCES booking.resource_attr_value(id)
8419                                         DEFERRABLE INITIALLY DEFERRED,
8420         CONSTRAINT bram_one_value_per_attr UNIQUE(resource, resource_attr)
8421 );
8422
8423 CREATE TABLE booking.reservation (
8424         request_time     TIMESTAMPTZ   NOT NULL DEFAULT now(),
8425         start_time       TIMESTAMPTZ,
8426         end_time         TIMESTAMPTZ,
8427         capture_time     TIMESTAMPTZ,
8428         cancel_time      TIMESTAMPTZ,
8429         pickup_time      TIMESTAMPTZ,
8430         return_time      TIMESTAMPTZ,
8431         booking_interval INTERVAL,
8432         fine_interval    INTERVAL,
8433         fine_amount      DECIMAL(8,2),
8434         target_resource_type  INT       NOT NULL
8435                                         REFERENCES booking.resource_type(id)
8436                                         ON DELETE CASCADE
8437                                         DEFERRABLE INITIALLY DEFERRED,
8438         target_resource  INT            REFERENCES booking.resource(id)
8439                                         ON DELETE CASCADE
8440                                         DEFERRABLE INITIALLY DEFERRED,
8441         current_resource INT            REFERENCES booking.resource(id)
8442                                         ON DELETE CASCADE
8443                                         DEFERRABLE INITIALLY DEFERRED,
8444         request_lib      INT            NOT NULL
8445                                         REFERENCES actor.org_unit(id)
8446                                         DEFERRABLE INITIALLY DEFERRED,
8447         pickup_lib       INT            REFERENCES actor.org_unit(id)
8448                                         DEFERRABLE INITIALLY DEFERRED,
8449         capture_staff    INT            REFERENCES actor.usr(id)
8450                                         DEFERRABLE INITIALLY DEFERRED,
8451     max_fine         NUMERIC(8,2)
8452 ) INHERITS (money.billable_xact);
8453
8454 ALTER TABLE booking.reservation ADD PRIMARY KEY (id);
8455
8456 ALTER TABLE booking.reservation
8457         ADD CONSTRAINT booking_reservation_usr_fkey
8458         FOREIGN KEY (usr) REFERENCES actor.usr (id)
8459         DEFERRABLE INITIALLY DEFERRED;
8460
8461 CREATE TABLE booking.reservation_attr_value_map (
8462         id               SERIAL         PRIMARY KEY,
8463         reservation      INT            NOT NULL
8464                                         REFERENCES booking.reservation(id)
8465                                         ON DELETE CASCADE
8466                                         DEFERRABLE INITIALLY DEFERRED,
8467         attr_value       INT            NOT NULL
8468                                         REFERENCES booking.resource_attr_value(id)
8469                                         ON DELETE CASCADE
8470                                         DEFERRABLE INITIALLY DEFERRED,
8471         CONSTRAINT bravm_logical_key UNIQUE(reservation, attr_value)
8472 );
8473
8474 -- represents a circ chain summary
8475 CREATE TYPE action.circ_chain_summary AS (
8476     num_circs INTEGER,
8477     start_time TIMESTAMP WITH TIME ZONE,
8478     checkout_workstation TEXT,
8479     last_renewal_time TIMESTAMP WITH TIME ZONE, -- NULL if no renewals
8480     last_stop_fines TEXT,
8481     last_stop_fines_time TIMESTAMP WITH TIME ZONE,
8482     last_renewal_workstation TEXT, -- NULL if no renewals
8483     last_checkin_workstation TEXT,
8484     last_checkin_time TIMESTAMP WITH TIME ZONE,
8485     last_checkin_scan_time TIMESTAMP WITH TIME ZONE
8486 );
8487
8488 CREATE OR REPLACE FUNCTION action.circ_chain ( ctx_circ_id INTEGER ) RETURNS SETOF action.circulation AS $$
8489 DECLARE
8490     tmp_circ action.circulation%ROWTYPE;
8491     circ_0 action.circulation%ROWTYPE;
8492 BEGIN
8493
8494     SELECT INTO tmp_circ * FROM action.circulation WHERE id = ctx_circ_id;
8495
8496     IF tmp_circ IS NULL THEN
8497         RETURN NEXT tmp_circ;
8498     END IF;
8499     circ_0 := tmp_circ;
8500
8501     -- find the front of the chain
8502     WHILE TRUE LOOP
8503         SELECT INTO tmp_circ * FROM action.circulation WHERE id = tmp_circ.parent_circ;
8504         IF tmp_circ IS NULL THEN
8505             EXIT;
8506         END IF;
8507         circ_0 := tmp_circ;
8508     END LOOP;
8509
8510     -- now send the circs to the caller, oldest to newest
8511     tmp_circ := circ_0;
8512     WHILE TRUE LOOP
8513         IF tmp_circ IS NULL THEN
8514             EXIT;
8515         END IF;
8516         RETURN NEXT tmp_circ;
8517         SELECT INTO tmp_circ * FROM action.circulation WHERE parent_circ = tmp_circ.id;
8518     END LOOP;
8519
8520 END;
8521 $$ LANGUAGE 'plpgsql';
8522
8523 CREATE OR REPLACE FUNCTION action.summarize_circ_chain ( ctx_circ_id INTEGER ) RETURNS action.circ_chain_summary AS $$
8524
8525 DECLARE
8526
8527     -- first circ in the chain
8528     circ_0 action.circulation%ROWTYPE;
8529
8530     -- last circ in the chain
8531     circ_n action.circulation%ROWTYPE;
8532
8533     -- circ chain under construction
8534     chain action.circ_chain_summary;
8535     tmp_circ action.circulation%ROWTYPE;
8536
8537 BEGIN
8538     
8539     chain.num_circs := 0;
8540     FOR tmp_circ IN SELECT * FROM action.circ_chain(ctx_circ_id) LOOP
8541
8542         IF chain.num_circs = 0 THEN
8543             circ_0 := tmp_circ;
8544         END IF;
8545
8546         chain.num_circs := chain.num_circs + 1;
8547         circ_n := tmp_circ;
8548     END LOOP;
8549
8550     chain.start_time := circ_0.xact_start;
8551     chain.last_stop_fines := circ_n.stop_fines;
8552     chain.last_stop_fines_time := circ_n.stop_fines_time;
8553     chain.last_checkin_time := circ_n.checkin_time;
8554     chain.last_checkin_scan_time := circ_n.checkin_scan_time;
8555     SELECT INTO chain.checkout_workstation name FROM actor.workstation WHERE id = circ_0.workstation;
8556     SELECT INTO chain.last_checkin_workstation name FROM actor.workstation WHERE id = circ_n.checkin_workstation;
8557
8558     IF chain.num_circs > 1 THEN
8559         chain.last_renewal_time := circ_n.xact_start;
8560         SELECT INTO chain.last_renewal_workstation name FROM actor.workstation WHERE id = circ_n.workstation;
8561     END IF;
8562
8563     RETURN chain;
8564
8565 END;
8566 $$ LANGUAGE 'plpgsql';
8567
8568 CREATE TRIGGER mat_summary_create_tgr AFTER INSERT ON booking.reservation FOR EACH ROW EXECUTE PROCEDURE money.mat_summary_create ('reservation');
8569 CREATE TRIGGER mat_summary_change_tgr AFTER UPDATE ON booking.reservation FOR EACH ROW EXECUTE PROCEDURE money.mat_summary_update ();
8570 CREATE TRIGGER mat_summary_remove_tgr AFTER DELETE ON booking.reservation FOR EACH ROW EXECUTE PROCEDURE money.mat_summary_delete ();
8571
8572 ALTER TABLE config.standing_penalty
8573         ADD COLUMN org_depth   INTEGER;
8574
8575 CREATE OR REPLACE FUNCTION actor.calculate_system_penalties( match_user INT, context_org INT ) RETURNS SETOF actor.usr_standing_penalty AS $func$
8576 DECLARE
8577     user_object         actor.usr%ROWTYPE;
8578     new_sp_row          actor.usr_standing_penalty%ROWTYPE;
8579     existing_sp_row     actor.usr_standing_penalty%ROWTYPE;
8580     collections_fines   permission.grp_penalty_threshold%ROWTYPE;
8581     max_fines           permission.grp_penalty_threshold%ROWTYPE;
8582     max_overdue         permission.grp_penalty_threshold%ROWTYPE;
8583     max_items_out       permission.grp_penalty_threshold%ROWTYPE;
8584     tmp_grp             INT;
8585     items_overdue       INT;
8586     items_out           INT;
8587     context_org_list    INT[];
8588     current_fines        NUMERIC(8,2) := 0.0;
8589     tmp_fines            NUMERIC(8,2);
8590     tmp_groc            RECORD;
8591     tmp_circ            RECORD;
8592     tmp_org             actor.org_unit%ROWTYPE;
8593     tmp_penalty         config.standing_penalty%ROWTYPE;
8594     tmp_depth           INTEGER;
8595 BEGIN
8596     SELECT INTO user_object * FROM actor.usr WHERE id = match_user;
8597
8598     -- Max fines
8599     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
8600
8601     -- Fail if the user has a high fine balance
8602     LOOP
8603         tmp_grp := user_object.profile;
8604         LOOP
8605             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 1 AND org_unit = tmp_org.id;
8606
8607             IF max_fines.threshold IS NULL THEN
8608                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
8609             ELSE
8610                 EXIT;
8611             END IF;
8612
8613             IF tmp_grp IS NULL THEN
8614                 EXIT;
8615             END IF;
8616         END LOOP;
8617
8618         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
8619             EXIT;
8620         END IF;
8621
8622         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
8623
8624     END LOOP;
8625
8626     IF max_fines.threshold IS NOT NULL THEN
8627
8628         RETURN QUERY
8629             SELECT  *
8630               FROM  actor.usr_standing_penalty
8631               WHERE usr = match_user
8632                     AND org_unit = max_fines.org_unit
8633                     AND (stop_date IS NULL or stop_date > NOW())
8634                     AND standing_penalty = 1;
8635
8636         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
8637
8638         SELECT  SUM(f.balance_owed) INTO current_fines
8639           FROM  money.materialized_billable_xact_summary f
8640                 JOIN (
8641                     SELECT  r.id
8642                       FROM  booking.reservation r
8643                       WHERE r.usr = match_user
8644                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
8645                             AND xact_finish IS NULL
8646                                 UNION ALL
8647                     SELECT  g.id
8648                       FROM  money.grocery g
8649                       WHERE g.usr = match_user
8650                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
8651                             AND xact_finish IS NULL
8652                                 UNION ALL
8653                     SELECT  circ.id
8654                       FROM  action.circulation circ
8655                       WHERE circ.usr = match_user
8656                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
8657                             AND xact_finish IS NULL ) l USING (id);
8658
8659         IF current_fines >= max_fines.threshold THEN
8660             new_sp_row.usr := match_user;
8661             new_sp_row.org_unit := max_fines.org_unit;
8662             new_sp_row.standing_penalty := 1;
8663             RETURN NEXT new_sp_row;
8664         END IF;
8665     END IF;
8666
8667     -- Start over for max overdue
8668     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
8669
8670     -- Fail if the user has too many overdue items
8671     LOOP
8672         tmp_grp := user_object.profile;
8673         LOOP
8674
8675             SELECT * INTO max_overdue FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 2 AND org_unit = tmp_org.id;
8676
8677             IF max_overdue.threshold IS NULL THEN
8678                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
8679             ELSE
8680                 EXIT;
8681             END IF;
8682
8683             IF tmp_grp IS NULL THEN
8684                 EXIT;
8685             END IF;
8686         END LOOP;
8687
8688         IF max_overdue.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
8689             EXIT;
8690         END IF;
8691
8692         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
8693
8694     END LOOP;
8695
8696     IF max_overdue.threshold IS NOT NULL THEN
8697
8698         RETURN QUERY
8699             SELECT  *
8700               FROM  actor.usr_standing_penalty
8701               WHERE usr = match_user
8702                     AND org_unit = max_overdue.org_unit
8703                     AND (stop_date IS NULL or stop_date > NOW())
8704                     AND standing_penalty = 2;
8705
8706         SELECT  INTO items_overdue COUNT(*)
8707           FROM  action.circulation circ
8708                 JOIN  actor.org_unit_full_path( max_overdue.org_unit ) fp ON (circ.circ_lib = fp.id)
8709           WHERE circ.usr = match_user
8710             AND circ.checkin_time IS NULL
8711             AND circ.due_date < NOW()
8712             AND (circ.stop_fines = 'MAXFINES' OR circ.stop_fines IS NULL);
8713
8714         IF items_overdue >= max_overdue.threshold::INT THEN
8715             new_sp_row.usr := match_user;
8716             new_sp_row.org_unit := max_overdue.org_unit;
8717             new_sp_row.standing_penalty := 2;
8718             RETURN NEXT new_sp_row;
8719         END IF;
8720     END IF;
8721
8722     -- Start over for max out
8723     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
8724
8725     -- Fail if the user has too many checked out items
8726     LOOP
8727         tmp_grp := user_object.profile;
8728         LOOP
8729             SELECT * INTO max_items_out FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 3 AND org_unit = tmp_org.id;
8730
8731             IF max_items_out.threshold IS NULL THEN
8732                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
8733             ELSE
8734                 EXIT;
8735             END IF;
8736
8737             IF tmp_grp IS NULL THEN
8738                 EXIT;
8739             END IF;
8740         END LOOP;
8741
8742         IF max_items_out.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
8743             EXIT;
8744         END IF;
8745
8746         SELECT INTO tmp_org * FROM actor.org_unit WHERE id = tmp_org.parent_ou;
8747
8748     END LOOP;
8749
8750
8751     -- Fail if the user has too many items checked out
8752     IF max_items_out.threshold IS NOT NULL THEN
8753
8754         RETURN QUERY
8755             SELECT  *
8756               FROM  actor.usr_standing_penalty
8757               WHERE usr = match_user
8758                     AND org_unit = max_items_out.org_unit
8759                     AND (stop_date IS NULL or stop_date > NOW())
8760                     AND standing_penalty = 3;
8761
8762         SELECT  INTO items_out COUNT(*)
8763           FROM  action.circulation circ
8764                 JOIN  actor.org_unit_full_path( max_items_out.org_unit ) fp ON (circ.circ_lib = fp.id)
8765           WHERE circ.usr = match_user
8766                 AND circ.checkin_time IS NULL
8767                 AND (circ.stop_fines IN ('MAXFINES','LONGOVERDUE') OR circ.stop_fines IS NULL);
8768
8769            IF items_out >= max_items_out.threshold::INT THEN
8770             new_sp_row.usr := match_user;
8771             new_sp_row.org_unit := max_items_out.org_unit;
8772             new_sp_row.standing_penalty := 3;
8773             RETURN NEXT new_sp_row;
8774            END IF;
8775     END IF;
8776
8777     -- Start over for collections warning
8778     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
8779
8780     -- Fail if the user has a collections-level fine balance
8781     LOOP
8782         tmp_grp := user_object.profile;
8783         LOOP
8784             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 4 AND org_unit = tmp_org.id;
8785
8786             IF max_fines.threshold IS NULL THEN
8787                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
8788             ELSE
8789                 EXIT;
8790             END IF;
8791
8792             IF tmp_grp IS NULL THEN
8793                 EXIT;
8794             END IF;
8795         END LOOP;
8796
8797         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
8798             EXIT;
8799         END IF;
8800
8801         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
8802
8803     END LOOP;
8804
8805     IF max_fines.threshold IS NOT NULL THEN
8806
8807         RETURN QUERY
8808             SELECT  *
8809               FROM  actor.usr_standing_penalty
8810               WHERE usr = match_user
8811                     AND org_unit = max_fines.org_unit
8812                     AND (stop_date IS NULL or stop_date > NOW())
8813                     AND standing_penalty = 4;
8814
8815         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
8816
8817         SELECT  SUM(f.balance_owed) INTO current_fines
8818           FROM  money.materialized_billable_xact_summary f
8819                 JOIN (
8820                     SELECT  r.id
8821                       FROM  booking.reservation r
8822                       WHERE r.usr = match_user
8823                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
8824                             AND r.xact_finish IS NULL
8825                                 UNION ALL
8826                     SELECT  g.id
8827                       FROM  money.grocery g
8828                       WHERE g.usr = match_user
8829                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
8830                             AND g.xact_finish IS NULL
8831                                 UNION ALL
8832                     SELECT  circ.id
8833                       FROM  action.circulation circ
8834                       WHERE circ.usr = match_user
8835                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
8836                             AND circ.xact_finish IS NULL ) l USING (id);
8837
8838         IF current_fines >= max_fines.threshold THEN
8839             new_sp_row.usr := match_user;
8840             new_sp_row.org_unit := max_fines.org_unit;
8841             new_sp_row.standing_penalty := 4;
8842             RETURN NEXT new_sp_row;
8843         END IF;
8844     END IF;
8845
8846     -- Start over for in collections
8847     SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
8848
8849     -- Remove the in-collections penalty if the user has paid down enough
8850     -- This penalty is different, because this code is not responsible for creating 
8851     -- new in-collections penalties, only for removing them
8852     LOOP
8853         tmp_grp := user_object.profile;
8854         LOOP
8855             SELECT * INTO max_fines FROM permission.grp_penalty_threshold WHERE grp = tmp_grp AND penalty = 30 AND org_unit = tmp_org.id;
8856
8857             IF max_fines.threshold IS NULL THEN
8858                 SELECT parent INTO tmp_grp FROM permission.grp_tree WHERE id = tmp_grp;
8859             ELSE
8860                 EXIT;
8861             END IF;
8862
8863             IF tmp_grp IS NULL THEN
8864                 EXIT;
8865             END IF;
8866         END LOOP;
8867
8868         IF max_fines.threshold IS NOT NULL OR tmp_org.parent_ou IS NULL THEN
8869             EXIT;
8870         END IF;
8871
8872         SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
8873
8874     END LOOP;
8875
8876     IF max_fines.threshold IS NOT NULL THEN
8877
8878         SELECT INTO context_org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( max_fines.org_unit );
8879
8880         -- first, see if the user had paid down to the threshold
8881         SELECT  SUM(f.balance_owed) INTO current_fines
8882           FROM  money.materialized_billable_xact_summary f
8883                 JOIN (
8884                     SELECT  r.id
8885                       FROM  booking.reservation r
8886                       WHERE r.usr = match_user
8887                             AND r.pickup_lib IN (SELECT * FROM unnest(context_org_list))
8888                             AND r.xact_finish IS NULL
8889                                 UNION ALL
8890                     SELECT  g.id
8891                       FROM  money.grocery g
8892                       WHERE g.usr = match_user
8893                             AND g.billing_location IN (SELECT * FROM unnest(context_org_list))
8894                             AND g.xact_finish IS NULL
8895                                 UNION ALL
8896                     SELECT  circ.id
8897                       FROM  action.circulation circ
8898                       WHERE circ.usr = match_user
8899                             AND circ.circ_lib IN (SELECT * FROM unnest(context_org_list))
8900                             AND circ.xact_finish IS NULL ) l USING (id);
8901
8902         IF current_fines IS NULL OR current_fines <= max_fines.threshold THEN
8903             -- patron has paid down enough
8904
8905             SELECT INTO tmp_penalty * FROM config.standing_penalty WHERE id = 30;
8906
8907             IF tmp_penalty.org_depth IS NOT NULL THEN
8908
8909                 -- since this code is not responsible for applying the penalty, it can't 
8910                 -- guarantee the current context org will match the org at which the penalty 
8911                 --- was applied.  search up the org tree until we hit the configured penalty depth
8912                 SELECT INTO tmp_org * FROM actor.org_unit WHERE id = context_org;
8913                 SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
8914
8915                 WHILE tmp_depth >= tmp_penalty.org_depth LOOP
8916
8917                     RETURN QUERY
8918                         SELECT  *
8919                           FROM  actor.usr_standing_penalty
8920                           WHERE usr = match_user
8921                                 AND org_unit = tmp_org.id
8922                                 AND (stop_date IS NULL or stop_date > NOW())
8923                                 AND standing_penalty = 30;
8924
8925                     IF tmp_org.parent_ou IS NULL THEN
8926                         EXIT;
8927                     END IF;
8928
8929                     SELECT * INTO tmp_org FROM actor.org_unit WHERE id = tmp_org.parent_ou;
8930                     SELECT INTO tmp_depth depth FROM actor.org_unit_type WHERE id = tmp_org.ou_type;
8931                 END LOOP;
8932
8933             ELSE
8934
8935                 -- no penalty depth is defined, look for exact matches
8936
8937                 RETURN QUERY
8938                     SELECT  *
8939                       FROM  actor.usr_standing_penalty
8940                       WHERE usr = match_user
8941                             AND org_unit = max_fines.org_unit
8942                             AND (stop_date IS NULL or stop_date > NOW())
8943                             AND standing_penalty = 30;
8944             END IF;
8945     
8946         END IF;
8947
8948     END IF;
8949
8950     RETURN;
8951 END;
8952 $func$ LANGUAGE plpgsql;
8953
8954 -- Create a default row in acq.fiscal_calendar
8955 -- Add a column in actor.org_unit to point to it
8956
8957 INSERT INTO acq.fiscal_calendar ( id, name ) VALUES ( 1, 'Default' );
8958
8959 ALTER TABLE actor.org_unit
8960 ADD COLUMN fiscal_calendar INT NOT NULL
8961         REFERENCES acq.fiscal_calendar( id )
8962         DEFERRABLE INITIALLY DEFERRED
8963         DEFAULT 1;
8964
8965 ALTER TABLE auditor.actor_org_unit_history
8966         ADD COLUMN fiscal_calendar INT;
8967
8968 DROP VIEW IF EXISTS auditor.actor_org_unit_lifecycle;
8969
8970 SELECT auditor.create_auditor_lifecycle( 'actor', 'org_unit' );
8971
8972 ALTER TABLE acq.funding_source_credit
8973 ADD COLUMN deadline_date TIMESTAMPTZ;
8974
8975 ALTER TABLE acq.funding_source_credit
8976 ADD COLUMN effective_date TIMESTAMPTZ NOT NULL DEFAULT now();
8977
8978 INSERT INTO config.standing_penalty (id,name,label) VALUES (30,'PATRON_IN_COLLECTIONS','Patron has been referred to a collections agency');
8979
8980 CREATE TABLE acq.fund_transfer (
8981         id               SERIAL         PRIMARY KEY,
8982         src_fund         INT            NOT NULL REFERENCES acq.fund( id )
8983                                         DEFERRABLE INITIALLY DEFERRED,
8984         src_amount       NUMERIC        NOT NULL,
8985         dest_fund        INT            REFERENCES acq.fund( id )
8986                                         DEFERRABLE INITIALLY DEFERRED,
8987         dest_amount      NUMERIC,
8988         transfer_time    TIMESTAMPTZ    NOT NULL DEFAULT now(),
8989         transfer_user    INT            NOT NULL REFERENCES actor.usr( id )
8990                                         DEFERRABLE INITIALLY DEFERRED,
8991         note             TEXT,
8992     funding_source_credit INTEGER   NOT NULL
8993                                         REFERENCES acq.funding_source_credit(id)
8994                                         DEFERRABLE INITIALLY DEFERRED
8995 );
8996
8997 CREATE INDEX acqftr_usr_idx
8998 ON acq.fund_transfer( transfer_user );
8999
9000 COMMENT ON TABLE acq.fund_transfer IS $$
9001 /*
9002  * Copyright (C) 2009  Georgia Public Library Service
9003  * Scott McKellar <scott@esilibrary.com>
9004  *
9005  * Fund Transfer
9006  *
9007  * Each row represents the transfer of money from a source fund
9008  * to a destination fund.  There should be corresponding entries
9009  * in acq.fund_allocation.  The purpose of acq.fund_transfer is
9010  * to record how much money moved from which fund to which other
9011  * fund.
9012  * 
9013  * The presence of two amount fields, rather than one, reflects
9014  * the possibility that the two funds are denominated in different
9015  * currencies.  If they use the same currency type, the two
9016  * amounts should be the same.
9017  *
9018  * ****
9019  *
9020  * This program is free software; you can redistribute it and/or
9021  * modify it under the terms of the GNU General Public License
9022  * as published by the Free Software Foundation; either version 2
9023  * of the License, or (at your option) any later version.
9024  *
9025  * This program is distributed in the hope that it will be useful,
9026  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9027  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9028  * GNU General Public License for more details.
9029  */
9030 $$;
9031
9032 CREATE TABLE acq.claim_event_type (
9033         id             SERIAL           PRIMARY KEY,
9034         org_unit       INT              NOT NULL REFERENCES actor.org_unit(id)
9035                                                  DEFERRABLE INITIALLY DEFERRED,
9036         code           TEXT             NOT NULL,
9037         description    TEXT             NOT NULL,
9038         library_initiated BOOL          NOT NULL DEFAULT FALSE,
9039         CONSTRAINT event_type_once_per_org UNIQUE ( org_unit, code )
9040 );
9041
9042 CREATE TABLE acq.claim_event (
9043         id             BIGSERIAL        PRIMARY KEY,
9044         type           INT              NOT NULL REFERENCES acq.claim_event_type
9045                                                  DEFERRABLE INITIALLY DEFERRED,
9046         claim          SERIAL           NOT NULL REFERENCES acq.claim
9047                                                  DEFERRABLE INITIALLY DEFERRED,
9048         event_date     TIMESTAMPTZ      NOT NULL DEFAULT now(),
9049         creator        INT              NOT NULL REFERENCES actor.usr
9050                                                  DEFERRABLE INITIALLY DEFERRED,
9051         note           TEXT
9052 );
9053
9054 CREATE INDEX claim_event_claim_date_idx ON acq.claim_event( claim, event_date );
9055
9056 CREATE OR REPLACE FUNCTION actor.usr_purge_data(
9057         src_usr  IN INTEGER,
9058         dest_usr IN INTEGER
9059 ) RETURNS VOID AS $$
9060 DECLARE
9061         suffix TEXT;
9062         renamable_row RECORD;
9063 BEGIN
9064
9065         UPDATE actor.usr SET
9066                 active = FALSE,
9067                 card = NULL,
9068                 mailing_address = NULL,
9069                 billing_address = NULL
9070         WHERE id = src_usr;
9071
9072         -- acq.*
9073         UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
9074         UPDATE acq.lineitem SET creator = dest_usr WHERE creator = src_usr;
9075         UPDATE acq.lineitem SET editor = dest_usr WHERE editor = src_usr;
9076         UPDATE acq.lineitem SET selector = dest_usr WHERE selector = src_usr;
9077         UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
9078         UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
9079         DELETE FROM acq.lineitem_usr_attr_definition WHERE usr = src_usr;
9080
9081         -- Update with a rename to avoid collisions
9082         FOR renamable_row in
9083                 SELECT id, name
9084                 FROM   acq.picklist
9085                 WHERE  owner = src_usr
9086         LOOP
9087                 suffix := ' (' || src_usr || ')';
9088                 LOOP
9089                         BEGIN
9090                                 UPDATE  acq.picklist
9091                                 SET     owner = dest_usr, name = name || suffix
9092                                 WHERE   id = renamable_row.id;
9093                         EXCEPTION WHEN unique_violation THEN
9094                                 suffix := suffix || ' ';
9095                                 CONTINUE;
9096                         END;
9097                         EXIT;
9098                 END LOOP;
9099         END LOOP;
9100
9101         UPDATE acq.picklist SET creator = dest_usr WHERE creator = src_usr;
9102         UPDATE acq.picklist SET editor = dest_usr WHERE editor = src_usr;
9103         UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
9104         UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
9105         UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
9106         UPDATE acq.purchase_order SET creator = dest_usr WHERE creator = src_usr;
9107         UPDATE acq.purchase_order SET editor = dest_usr WHERE editor = src_usr;
9108         UPDATE acq.claim_event SET creator = dest_usr WHERE creator = src_usr;
9109
9110         -- action.*
9111         DELETE FROM action.circulation WHERE usr = src_usr;
9112         UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
9113         UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
9114         UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
9115         UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
9116         UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
9117         DELETE FROM action.hold_request WHERE usr = src_usr;
9118         UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
9119         UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
9120         DELETE FROM action.non_cataloged_circulation WHERE patron = src_usr;
9121         UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
9122         DELETE FROM action.survey_response WHERE usr = src_usr;
9123         UPDATE action.fieldset SET owner = dest_usr WHERE owner = src_usr;
9124
9125         -- actor.*
9126         DELETE FROM actor.card WHERE usr = src_usr;
9127         DELETE FROM actor.stat_cat_entry_usr_map WHERE target_usr = src_usr;
9128
9129         -- The following update is intended to avoid transient violations of a foreign
9130         -- key constraint, whereby actor.usr_address references itself.  It may not be
9131         -- necessary, but it does no harm.
9132         UPDATE actor.usr_address SET replaces = NULL
9133                 WHERE usr = src_usr AND replaces IS NOT NULL;
9134         DELETE FROM actor.usr_address WHERE usr = src_usr;
9135         DELETE FROM actor.usr_note WHERE usr = src_usr;
9136         UPDATE actor.usr_note SET creator = dest_usr WHERE creator = src_usr;
9137         DELETE FROM actor.usr_org_unit_opt_in WHERE usr = src_usr;
9138         UPDATE actor.usr_org_unit_opt_in SET staff = dest_usr WHERE staff = src_usr;
9139         DELETE FROM actor.usr_setting WHERE usr = src_usr;
9140         DELETE FROM actor.usr_standing_penalty WHERE usr = src_usr;
9141         UPDATE actor.usr_standing_penalty SET staff = dest_usr WHERE staff = src_usr;
9142
9143         -- asset.*
9144         UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
9145         UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
9146         UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
9147         UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
9148         UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
9149         UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
9150
9151         -- auditor.*
9152         DELETE FROM auditor.actor_usr_address_history WHERE id = src_usr;
9153         DELETE FROM auditor.actor_usr_history WHERE id = src_usr;
9154         UPDATE auditor.asset_call_number_history SET creator = dest_usr WHERE creator = src_usr;
9155         UPDATE auditor.asset_call_number_history SET editor  = dest_usr WHERE editor  = src_usr;
9156         UPDATE auditor.asset_copy_history SET creator = dest_usr WHERE creator = src_usr;
9157         UPDATE auditor.asset_copy_history SET editor  = dest_usr WHERE editor  = src_usr;
9158         UPDATE auditor.biblio_record_entry_history SET creator = dest_usr WHERE creator = src_usr;
9159         UPDATE auditor.biblio_record_entry_history SET editor  = dest_usr WHERE editor  = src_usr;
9160
9161         -- biblio.*
9162         UPDATE biblio.record_entry SET creator = dest_usr WHERE creator = src_usr;
9163         UPDATE biblio.record_entry SET editor = dest_usr WHERE editor = src_usr;
9164         UPDATE biblio.record_note SET creator = dest_usr WHERE creator = src_usr;
9165         UPDATE biblio.record_note SET editor = dest_usr WHERE editor = src_usr;
9166
9167         -- container.*
9168         -- Update buckets with a rename to avoid collisions
9169         FOR renamable_row in
9170                 SELECT id, name
9171                 FROM   container.biblio_record_entry_bucket
9172                 WHERE  owner = src_usr
9173         LOOP
9174                 suffix := ' (' || src_usr || ')';
9175                 LOOP
9176                         BEGIN
9177                                 UPDATE  container.biblio_record_entry_bucket
9178                                 SET     owner = dest_usr, name = name || suffix
9179                                 WHERE   id = renamable_row.id;
9180                         EXCEPTION WHEN unique_violation THEN
9181                                 suffix := suffix || ' ';
9182                                 CONTINUE;
9183                         END;
9184                         EXIT;
9185                 END LOOP;
9186         END LOOP;
9187
9188         FOR renamable_row in
9189                 SELECT id, name
9190                 FROM   container.call_number_bucket
9191                 WHERE  owner = src_usr
9192         LOOP
9193                 suffix := ' (' || src_usr || ')';
9194                 LOOP
9195                         BEGIN
9196                                 UPDATE  container.call_number_bucket
9197                                 SET     owner = dest_usr, name = name || suffix
9198                                 WHERE   id = renamable_row.id;
9199                         EXCEPTION WHEN unique_violation THEN
9200                                 suffix := suffix || ' ';
9201                                 CONTINUE;
9202                         END;
9203                         EXIT;
9204                 END LOOP;
9205         END LOOP;
9206
9207         FOR renamable_row in
9208                 SELECT id, name
9209                 FROM   container.copy_bucket
9210                 WHERE  owner = src_usr
9211         LOOP
9212                 suffix := ' (' || src_usr || ')';
9213                 LOOP
9214                         BEGIN
9215                                 UPDATE  container.copy_bucket
9216                                 SET     owner = dest_usr, name = name || suffix
9217                                 WHERE   id = renamable_row.id;
9218                         EXCEPTION WHEN unique_violation THEN
9219                                 suffix := suffix || ' ';
9220                                 CONTINUE;
9221                         END;
9222                         EXIT;
9223                 END LOOP;
9224         END LOOP;
9225
9226         FOR renamable_row in
9227                 SELECT id, name
9228                 FROM   container.user_bucket
9229                 WHERE  owner = src_usr
9230         LOOP
9231                 suffix := ' (' || src_usr || ')';
9232                 LOOP
9233                         BEGIN
9234                                 UPDATE  container.user_bucket
9235                                 SET     owner = dest_usr, name = name || suffix
9236                                 WHERE   id = renamable_row.id;
9237                         EXCEPTION WHEN unique_violation THEN
9238                                 suffix := suffix || ' ';
9239                                 CONTINUE;
9240                         END;
9241                         EXIT;
9242                 END LOOP;
9243         END LOOP;
9244
9245         DELETE FROM container.user_bucket_item WHERE target_user = src_usr;
9246
9247         -- money.*
9248         DELETE FROM money.billable_xact WHERE usr = src_usr;
9249         DELETE FROM money.collections_tracker WHERE usr = src_usr;
9250         UPDATE money.collections_tracker SET collector = dest_usr WHERE collector = src_usr;
9251
9252         -- permission.*
9253         DELETE FROM permission.usr_grp_map WHERE usr = src_usr;
9254         DELETE FROM permission.usr_object_perm_map WHERE usr = src_usr;
9255         DELETE FROM permission.usr_perm_map WHERE usr = src_usr;
9256         DELETE FROM permission.usr_work_ou_map WHERE usr = src_usr;
9257
9258         -- reporter.*
9259         -- Update with a rename to avoid collisions
9260         BEGIN
9261                 FOR renamable_row in
9262                         SELECT id, name
9263                         FROM   reporter.output_folder
9264                         WHERE  owner = src_usr
9265                 LOOP
9266                         suffix := ' (' || src_usr || ')';
9267                         LOOP
9268                                 BEGIN
9269                                         UPDATE  reporter.output_folder
9270                                         SET     owner = dest_usr, name = name || suffix
9271                                         WHERE   id = renamable_row.id;
9272                                 EXCEPTION WHEN unique_violation THEN
9273                                         suffix := suffix || ' ';
9274                                         CONTINUE;
9275                                 END;
9276                                 EXIT;
9277                         END LOOP;
9278                 END LOOP;
9279         EXCEPTION WHEN undefined_table THEN
9280                 -- do nothing
9281         END;
9282
9283         BEGIN
9284                 UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
9285         EXCEPTION WHEN undefined_table THEN
9286                 -- do nothing
9287         END;
9288
9289         -- Update with a rename to avoid collisions
9290         BEGIN
9291                 FOR renamable_row in
9292                         SELECT id, name
9293                         FROM   reporter.report_folder
9294                         WHERE  owner = src_usr
9295                 LOOP
9296                         suffix := ' (' || src_usr || ')';
9297                         LOOP
9298                                 BEGIN
9299                                         UPDATE  reporter.report_folder
9300                                         SET     owner = dest_usr, name = name || suffix
9301                                         WHERE   id = renamable_row.id;
9302                                 EXCEPTION WHEN unique_violation THEN
9303                                         suffix := suffix || ' ';
9304                                         CONTINUE;
9305                                 END;
9306                                 EXIT;
9307                         END LOOP;
9308                 END LOOP;
9309         EXCEPTION WHEN undefined_table THEN
9310                 -- do nothing
9311         END;
9312
9313         BEGIN
9314                 UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
9315         EXCEPTION WHEN undefined_table THEN
9316                 -- do nothing
9317         END;
9318
9319         BEGIN
9320                 UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
9321         EXCEPTION WHEN undefined_table THEN
9322                 -- do nothing
9323         END;
9324
9325         -- Update with a rename to avoid collisions
9326         BEGIN
9327                 FOR renamable_row in
9328                         SELECT id, name
9329                         FROM   reporter.template_folder
9330                         WHERE  owner = src_usr
9331                 LOOP
9332                         suffix := ' (' || src_usr || ')';
9333                         LOOP
9334                                 BEGIN
9335                                         UPDATE  reporter.template_folder
9336                                         SET     owner = dest_usr, name = name || suffix
9337                                         WHERE   id = renamable_row.id;
9338                                 EXCEPTION WHEN unique_violation THEN
9339                                         suffix := suffix || ' ';
9340                                         CONTINUE;
9341                                 END;
9342                                 EXIT;
9343                         END LOOP;
9344                 END LOOP;
9345         EXCEPTION WHEN undefined_table THEN
9346         -- do nothing
9347         END;
9348
9349         -- vandelay.*
9350         -- Update with a rename to avoid collisions
9351         FOR renamable_row in
9352                 SELECT id, name
9353                 FROM   vandelay.queue
9354                 WHERE  owner = src_usr
9355         LOOP
9356                 suffix := ' (' || src_usr || ')';
9357                 LOOP
9358                         BEGIN
9359                                 UPDATE  vandelay.queue
9360                                 SET     owner = dest_usr, name = name || suffix
9361                                 WHERE   id = renamable_row.id;
9362                         EXCEPTION WHEN unique_violation THEN
9363                                 suffix := suffix || ' ';
9364                                 CONTINUE;
9365                         END;
9366                         EXIT;
9367                 END LOOP;
9368         END LOOP;
9369
9370 END;
9371 $$ LANGUAGE plpgsql;
9372
9373 COMMENT ON FUNCTION actor.usr_purge_data(INT, INT) IS $$
9374 /**
9375  * Finds rows dependent on a given row in actor.usr and either deletes them
9376  * or reassigns them to a different user.
9377  */
9378 $$;
9379
9380 CREATE OR REPLACE FUNCTION actor.usr_delete(
9381         src_usr  IN INTEGER,
9382         dest_usr IN INTEGER
9383 ) RETURNS VOID AS $$
9384 DECLARE
9385         old_profile actor.usr.profile%type;
9386         old_home_ou actor.usr.home_ou%type;
9387         new_profile actor.usr.profile%type;
9388         new_home_ou actor.usr.home_ou%type;
9389         new_name    text;
9390         new_dob     actor.usr.dob%type;
9391 BEGIN
9392         SELECT
9393                 id || '-PURGED-' || now(),
9394                 profile,
9395                 home_ou,
9396                 dob
9397         INTO
9398                 new_name,
9399                 old_profile,
9400                 old_home_ou,
9401                 new_dob
9402         FROM
9403                 actor.usr
9404         WHERE
9405                 id = src_usr;
9406         --
9407         -- Quit if no such user
9408         --
9409         IF old_profile IS NULL THEN
9410                 RETURN;
9411         END IF;
9412         --
9413         perform actor.usr_purge_data( src_usr, dest_usr );
9414         --
9415         -- Find the root grp_tree and the root org_unit.  This would be simpler if we 
9416         -- could assume that there is only one root.  Theoretically, someday, maybe,
9417         -- there could be multiple roots, so we take extra trouble to get the right ones.
9418         --
9419         SELECT
9420                 id
9421         INTO
9422                 new_profile
9423         FROM
9424                 permission.grp_ancestors( old_profile )
9425         WHERE
9426                 parent is null;
9427         --
9428         SELECT
9429                 id
9430         INTO
9431                 new_home_ou
9432         FROM
9433                 actor.org_unit_ancestors( old_home_ou )
9434         WHERE
9435                 parent_ou is null;
9436         --
9437         -- Truncate date of birth
9438         --
9439         IF new_dob IS NOT NULL THEN
9440                 new_dob := date_trunc( 'year', new_dob );
9441         END IF;
9442         --
9443         UPDATE
9444                 actor.usr
9445                 SET
9446                         card = NULL,
9447                         profile = new_profile,
9448                         usrname = new_name,
9449                         email = NULL,
9450                         passwd = random()::text,
9451                         standing = DEFAULT,
9452                         ident_type = 
9453                         (
9454                                 SELECT MIN( id )
9455                                 FROM config.identification_type
9456                         ),
9457                         ident_value = NULL,
9458                         ident_type2 = NULL,
9459                         ident_value2 = NULL,
9460                         net_access_level = DEFAULT,
9461                         photo_url = NULL,
9462                         prefix = NULL,
9463                         first_given_name = new_name,
9464                         second_given_name = NULL,
9465                         family_name = new_name,
9466                         suffix = NULL,
9467                         alias = NULL,
9468                         day_phone = NULL,
9469                         evening_phone = NULL,
9470                         other_phone = NULL,
9471                         mailing_address = NULL,
9472                         billing_address = NULL,
9473                         home_ou = new_home_ou,
9474                         dob = new_dob,
9475                         active = FALSE,
9476                         master_account = DEFAULT, 
9477                         super_user = DEFAULT,
9478                         barred = FALSE,
9479                         deleted = TRUE,
9480                         juvenile = DEFAULT,
9481                         usrgroup = 0,
9482                         claims_returned_count = DEFAULT,
9483                         credit_forward_balance = DEFAULT,
9484                         last_xact_id = DEFAULT,
9485                         alert_message = NULL,
9486                         create_date = now(),
9487                         expire_date = now()
9488         WHERE
9489                 id = src_usr;
9490 END;
9491 $$ LANGUAGE plpgsql;
9492
9493 COMMENT ON FUNCTION actor.usr_delete(INT, INT) IS $$
9494 /**
9495  * Logically deletes a user.  Removes personally identifiable information,
9496  * and purges associated data in other tables.
9497  */
9498 $$;
9499
9500 -- INSERT INTO config.copy_status (id,name) VALUES (15,oils_i18n_gettext(15, 'On reservation shelf', 'ccs', 'name'));
9501
9502 ALTER TABLE acq.fund
9503 ADD COLUMN rollover BOOL NOT NULL DEFAULT FALSE;
9504
9505 ALTER TABLE acq.fund
9506         ADD COLUMN propagate BOOLEAN NOT NULL DEFAULT TRUE;
9507
9508 -- A fund can't roll over if it doesn't propagate from one year to the next
9509
9510 ALTER TABLE acq.fund
9511         ADD CONSTRAINT acq_fund_rollover_implies_propagate CHECK
9512         ( propagate OR NOT rollover );
9513
9514 ALTER TABLE acq.fund
9515         ADD COLUMN active BOOL NOT NULL DEFAULT TRUE;
9516
9517 ALTER TABLE acq.fund
9518     ADD COLUMN balance_warning_percent INT;
9519
9520 ALTER TABLE acq.fund
9521     ADD COLUMN balance_stop_percent INT;
9522
9523 CREATE VIEW acq.ordered_funding_source_credit AS
9524         SELECT
9525                 CASE WHEN deadline_date IS NULL THEN
9526                         2
9527                 ELSE
9528                         1
9529                 END AS sort_priority,
9530                 CASE WHEN deadline_date IS NULL THEN
9531                         effective_date
9532                 ELSE
9533                         deadline_date
9534                 END AS sort_date,
9535                 id,
9536                 funding_source,
9537                 amount,
9538                 note
9539         FROM
9540                 acq.funding_source_credit;
9541
9542 COMMENT ON VIEW acq.ordered_funding_source_credit IS $$
9543 /*
9544  * Copyright (C) 2009  Georgia Public Library Service
9545  * Scott McKellar <scott@gmail.com>
9546  *
9547  * The acq.ordered_funding_source_credit view is a prioritized
9548  * ordering of funding source credits.  When ordered by the first
9549  * three columns, this view defines the order in which the various
9550  * credits are to be tapped for spending, subject to the allocations
9551  * in the acq.fund_allocation table.
9552  *
9553  * The first column reflects the principle that we should spend
9554  * money with deadlines before spending money without deadlines.
9555  *
9556  * The second column reflects the principle that we should spend the
9557  * oldest money first.  For money with deadlines, that means that we
9558  * spend first from the credit with the earliest deadline.  For
9559  * money without deadlines, we spend first from the credit with the
9560  * earliest effective date.  
9561  *
9562  * The third column is a tie breaker to ensure a consistent
9563  * ordering.
9564  *
9565  * ****
9566  *
9567  * This program is free software; you can redistribute it and/or
9568  * modify it under the terms of the GNU General Public License
9569  * as published by the Free Software Foundation; either version 2
9570  * of the License, or (at your option) any later version.
9571  *
9572  * This program is distributed in the hope that it will be useful,
9573  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9574  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9575  * GNU General Public License for more details.
9576  */
9577 $$;
9578
9579 CREATE OR REPLACE VIEW money.billable_xact_summary_location_view AS
9580     SELECT  m.*, COALESCE(c.circ_lib, g.billing_location, r.pickup_lib) AS billing_location
9581       FROM  money.materialized_billable_xact_summary m
9582             LEFT JOIN action.circulation c ON (c.id = m.id)
9583             LEFT JOIN money.grocery g ON (g.id = m.id)
9584             LEFT JOIN booking.reservation r ON (r.id = m.id);
9585
9586 CREATE TABLE config.marc21_rec_type_map (
9587     code        TEXT    PRIMARY KEY,
9588     type_val    TEXT    NOT NULL,
9589     blvl_val    TEXT    NOT NULL
9590 );
9591
9592 CREATE TABLE config.marc21_ff_pos_map (
9593     id          SERIAL  PRIMARY KEY,
9594     fixed_field TEXT    NOT NULL,
9595     tag         TEXT    NOT NULL,
9596     rec_type    TEXT    NOT NULL,
9597     start_pos   INT     NOT NULL,
9598     length      INT     NOT NULL,
9599     default_val TEXT    NOT NULL DEFAULT ' '
9600 );
9601
9602 CREATE TABLE config.marc21_physical_characteristic_type_map (
9603     ptype_key   TEXT    PRIMARY KEY,
9604     label       TEXT    NOT NULL -- I18N
9605 );
9606
9607 CREATE TABLE config.marc21_physical_characteristic_subfield_map (
9608     id          SERIAL  PRIMARY KEY,
9609     ptype_key   TEXT    NOT NULL REFERENCES config.marc21_physical_characteristic_type_map (ptype_key) ON DELETE CASCADE ON UPDATE CASCADE,
9610     subfield    TEXT    NOT NULL,
9611     start_pos   INT     NOT NULL,
9612     length      INT     NOT NULL,
9613     label       TEXT    NOT NULL -- I18N
9614 );
9615
9616 CREATE TABLE config.marc21_physical_characteristic_value_map (
9617     id              SERIAL  PRIMARY KEY,
9618     value           TEXT    NOT NULL,
9619     ptype_subfield  INT     NOT NULL REFERENCES config.marc21_physical_characteristic_subfield_map (id),
9620     label           TEXT    NOT NULL -- I18N
9621 );
9622
9623 ----------------------------------
9624 -- MARC21 record structure data --
9625 ----------------------------------
9626
9627 -- Record type map
9628 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('BKS','at','acdm');
9629 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('SER','a','bsi');
9630 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('VIS','gkro','abcdmsi');
9631 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('MIX','p','cdi');
9632 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('MAP','ef','abcdmsi');
9633 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('SCO','cd','abcdmsi');
9634 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('REC','ij','abcdmsi');
9635 INSERT INTO config.marc21_rec_type_map (code, type_val, blvl_val) VALUES ('COM','m','abcdmsi');
9636
9637 ------ Physical Characteristics
9638
9639 -- Map
9640 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('a','Map');
9641 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('a','b','1','1','SMD');
9642 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Atlas');
9643 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Diagram');
9644 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Map');
9645 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Profile');
9646 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Model');
9647 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Remote-sensing image');
9648 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Section');
9649 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
9650 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('y',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'View');
9651 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9652 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('a','d','3','1','Color');
9653 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'One color');
9654 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
9655 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('a','e','4','1','Physical medium');
9656 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Paper');
9657 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Wood');
9658 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stone');
9659 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Metal');
9660 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics');
9661 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Skins');
9662 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Textile');
9663 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Plaster');
9664 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Flexible base photographic medium, positive');
9665 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Flexible base photographic medium, negative');
9666 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Non-flexible base photographic medium, positive');
9667 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Non-flexible base photographic medium, negative');
9668 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9669 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('y',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other photographic medium');
9670 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9671 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('a','f','5','1','Type of reproduction');
9672 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Facsimile');
9673 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9674 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9675 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9676 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('a','g','6','1','Production/reproduction details');
9677 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Photocopy, blueline print');
9678 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Photocopy');
9679 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Pre-production');
9680 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film');
9681 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9682 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9683 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('a','h','7','1','Positive/negative');
9684 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Positive');
9685 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Negative');
9686 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9687 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9688
9689 -- Electronic Resource
9690 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('c','Electronic Resource');
9691 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','b','1','1','SMD');
9692 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Tape Cartridge');
9693 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Chip cartridge');
9694 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Computer optical disk cartridge');
9695 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Tape cassette');
9696 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Tape reel');
9697 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic disk');
9698 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magneto-optical disk');
9699 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical disk');
9700 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Remote');
9701 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
9702 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9703 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','d','3','1','Color');
9704 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'One color');
9705 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Black-and-white');
9706 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
9707 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Gray scale');
9708 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9709 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9710 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9711 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9712 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','e','4','1','Dimensions');
9713 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 1/2 in.');
9714 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'12 in.');
9715 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'4 3/4 in. or 12 cm.');
9716 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1 1/8 x 2 3/8 in.');
9717 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 7/8 x 2 1/2 in.');
9718 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9719 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'5 1/4 in.');
9720 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9721 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('v',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 in.');
9722 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9723 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','f','5','1','Sound');
9724 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES (' ',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'No sound (Silent)');
9725 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound');
9726 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9727 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','g','6','3','Image bit depth');
9728 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('---',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9729 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('mmm',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multiple');
9730 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('nnn',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9731 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','h','9','1','File formats');
9732 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'One file format');
9733 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multiple file formats');
9734 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9735 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','i','10','1','Quality assurance target(s)');
9736 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Absent');
9737 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9738 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Present');
9739 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9740 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','j','11','1','Antecedent/Source');
9741 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'File reproduced from original');
9742 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'File reproduced from microform');
9743 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'File reproduced from electronic resource');
9744 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'File reproduced from an intermediate (not microform)');
9745 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9746 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9747 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9748 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','k','12','1','Level of compression');
9749 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Uncompressed');
9750 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Lossless');
9751 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Lossy');
9752 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9753 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9754 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('c','l','13','1','Reformatting quality');
9755 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Access');
9756 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9757 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Preservation');
9758 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Replacement');
9759 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9760
9761 -- Globe
9762 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('d','Globe');
9763 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('d','b','1','1','SMD');
9764 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Celestial globe');
9765 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Planetary or lunar globe');
9766 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Terrestrial globe');
9767 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Earth moon globe');
9768 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
9769 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9770 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('d','d','3','1','Color');
9771 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'One color');
9772 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
9773 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('d','e','4','1','Physical medium');
9774 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Paper');
9775 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Wood');
9776 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stone');
9777 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Metal');
9778 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics');
9779 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Skins');
9780 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Textile');
9781 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Plaster');
9782 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9783 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9784 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('d','f','5','1','Type of reproduction');
9785 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Facsimile');
9786 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9787 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9788 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9789
9790 -- Tactile Material
9791 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('f','Tactile Material');
9792 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('f','b','1','1','SMD');
9793 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Moon');
9794 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Braille');
9795 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Combination');
9796 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Tactile, with no writing system');
9797 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
9798 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9799 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('f','d','3','2','Class of braille writing');
9800 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Literary braille');
9801 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Format code braille');
9802 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mathematics and scientific braille');
9803 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Computer braille');
9804 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Music braille');
9805 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multiple braille types');
9806 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9807 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9808 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9809 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('f','e','4','1','Level of contraction');
9810 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Uncontracted');
9811 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Contracted');
9812 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Combination');
9813 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9814 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9815 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9816 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('f','f','6','3','Braille music format');
9817 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Bar over bar');
9818 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Bar by bar');
9819 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Line over line');
9820 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Paragraph');
9821 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Single line');
9822 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Section by section');
9823 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Line by line');
9824 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Open score');
9825 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Spanner short form scoring');
9826 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Short form scoring');
9827 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Outline');
9828 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('l',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Vertical score');
9829 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9830 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9831 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9832 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('f','g','9','1','Special physical characteristics');
9833 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Print/braille');
9834 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Jumbo or enlarged braille');
9835 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9836 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9837 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9838
9839 -- Projected Graphic
9840 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('g','Projected Graphic');
9841 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','b','1','1','SMD');
9842 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film cartridge');
9843 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Filmstrip');
9844 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film filmstrip type');
9845 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Filmstrip roll');
9846 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Slide');
9847 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Transparency');
9848 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9849 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','d','3','1','Color');
9850 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Black-and-white');
9851 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
9852 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Hand-colored');
9853 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9854 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9855 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9856 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9857 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','e','4','1','Base of emulsion');
9858 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Glass');
9859 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics');
9860 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety film');
9861 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film base, other than safety film');
9862 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed collection');
9863 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Paper');
9864 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9865 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9866 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','f','5','1','Sound on medium or separate');
9867 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound on medium');
9868 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound separate from medium');
9869 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9870 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','g','6','1','Medium for sound');
9871 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical sound track on motion picture film');
9872 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic sound track on motion picture film');
9873 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape in cartridge');
9874 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound disc');
9875 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape on reel');
9876 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape in cassette');
9877 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical and magnetic sound track on film');
9878 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videotape');
9879 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videodisc');
9880 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9881 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9882 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','h','7','1','Dimensions');
9883 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Standard 8 mm.');
9884 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Super 8 mm./single 8 mm.');
9885 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'9.5 mm.');
9886 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'16 mm.');
9887 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'28 mm.');
9888 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'35 mm.');
9889 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'70 mm.');
9890 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'2 x 2 in. (5 x 5 cm.)');
9891 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'2 1/4 x 2 1/4 in. (6 x 6 cm.)');
9892 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'4 x 5 in. (10 x 13 cm.)');
9893 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'5 x 7 in. (13 x 18 cm.)');
9894 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9895 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('v',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 x 10 in. (21 x 26 cm.)');
9896 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('w',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'9 x 9 in. (23 x 23 cm.)');
9897 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('x',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'10 x 10 in. (26 x 26 cm.)');
9898 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('y',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'7 x 7 in. (18 x 18 cm.)');
9899 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9900 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('g','i','8','1','Secondary support material');
9901 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Cardboard');
9902 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Glass');
9903 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics');
9904 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'metal');
9905 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Metal and glass');
9906 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics and glass');
9907 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed collection');
9908 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9909 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9910
9911 -- Microform
9912 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('h','Microform');
9913 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','b','1','1','SMD');
9914 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Aperture card');
9915 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microfilm cartridge');
9916 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microfilm cassette');
9917 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microfilm reel');
9918 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microfiche');
9919 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microfiche cassette');
9920 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microopaque');
9921 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
9922 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9923 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','d','3','1','Positive/negative');
9924 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Positive');
9925 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Negative');
9926 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9927 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9928 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','e','4','1','Dimensions');
9929 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 mm.');
9930 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'16 mm.');
9931 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'35 mm.');
9932 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'70mm.');
9933 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'105 mm.');
9934 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('l',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 x 5 in. (8 x 13 cm.)');
9935 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'4 x 6 in. (11 x 15 cm.)');
9936 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'6 x 9 in. (16 x 23 cm.)');
9937 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 1/4 x 7 3/8 in. (9 x 19 cm.)');
9938 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9939 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9940 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','f','5','4','Reduction ratio range/Reduction ratio');
9941 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Low (1-16x)');
9942 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Normal (16-30x)');
9943 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'High (31-60x)');
9944 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Very high (61-90x)');
9945 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Ultra (90x-)');
9946 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9947 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('v',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Reduction ratio varies');
9948 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','g','9','1','Color');
9949 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Black-and-white');
9950 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
9951 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9952 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9953 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9954 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','h','10','1','Emulsion on film');
9955 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Silver halide');
9956 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Diazo');
9957 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Vesicular');
9958 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
9959 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9960 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9961 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9962 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','i','11','1','Quality assurance target(s)');
9963 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1st gen. master');
9964 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Printing master');
9965 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Service copy');
9966 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed generation');
9967 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9968 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('h','j','12','1','Base of film');
9969 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety base, undetermined');
9970 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety base, acetate undetermined');
9971 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety base, diacetate');
9972 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('l',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Nitrate base');
9973 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed base');
9974 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
9975 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety base, polyester');
9976 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety base, mixed');
9977 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Safety base, triacetate');
9978 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
9979 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9980
9981 -- Non-projected Graphic
9982 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('k','Non-projected Graphic');
9983 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('k','b','1','1','SMD');
9984 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Collage');
9985 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Drawing');
9986 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Painting');
9987 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Photo-mechanical print');
9988 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Photonegative');
9989 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Photoprint');
9990 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Picture');
9991 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Print');
9992 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('l',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Technical drawing');
9993 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Chart');
9994 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Flash/activity card');
9995 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
9996 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
9997 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('k','d','3','1','Color');
9998 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'One color');
9999 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Black-and-white');
10000 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
10001 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Hand-colored');
10002 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
10003 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10004 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10005 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('k','e','4','1','Primary support material');
10006 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Canvas');
10007 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Bristol board');
10008 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Cardboard/illustration board');
10009 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Glass');
10010 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics');
10011 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Skins');
10012 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Textile');
10013 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Metal');
10014 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed collection');
10015 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Paper');
10016 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Plaster');
10017 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Hardboard');
10018 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Porcelain');
10019 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stone');
10020 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Wood');
10021 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10022 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10023 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('k','f','5','1','Secondary support material');
10024 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Canvas');
10025 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Bristol board');
10026 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Cardboard/illustration board');
10027 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Glass');
10028 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetics');
10029 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Skins');
10030 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Textile');
10031 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Metal');
10032 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed collection');
10033 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Paper');
10034 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Plaster');
10035 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Hardboard');
10036 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Porcelain');
10037 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stone');
10038 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Wood');
10039 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10040 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10041
10042 -- Motion Picture
10043 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('m','Motion Picture');
10044 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','b','1','1','SMD');
10045 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film cartridge');
10046 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film cassette');
10047 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Film reel');
10048 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
10049 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10050 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','d','3','1','Color');
10051 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Black-and-white');
10052 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
10053 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Hand-colored');
10054 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
10055 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10056 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10057 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','e','4','1','Motion picture presentation format');
10058 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Standard sound aperture, reduced frame');
10059 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Nonanamorphic (wide-screen)');
10060 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3D');
10061 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Anamorphic (wide-screen)');
10062 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other-wide screen format');
10063 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Standard. silent aperture, full frame');
10064 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10065 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10066 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','f','5','1','Sound on medium or separate');
10067 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound on medium');
10068 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound separate from medium');
10069 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10070 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','g','6','1','Medium for sound');
10071 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical sound track on motion picture film');
10072 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic sound track on motion picture film');
10073 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape in cartridge');
10074 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound disc');
10075 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape on reel');
10076 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape in cassette');
10077 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical and magnetic sound track on film');
10078 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videotape');
10079 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videodisc');
10080 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10081 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10082 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','h','7','1','Dimensions');
10083 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Standard 8 mm.');
10084 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Super 8 mm./single 8 mm.');
10085 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'9.5 mm.');
10086 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'16 mm.');
10087 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'28 mm.');
10088 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'35 mm.');
10089 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'70 mm.');
10090 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10091 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10092 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','i','8','1','Configuration of playback channels');
10093 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
10094 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Monaural');
10095 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10096 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multichannel, surround or quadraphonic');
10097 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stereophonic');
10098 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10099 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10100 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('m','j','9','1','Production elements');
10101 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Work print');
10102 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Trims');
10103 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Outtakes');
10104 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Rushes');
10105 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixing tracks');
10106 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Title bands/inter-title rolls');
10107 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Production rolls');
10108 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10109 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10110
10111 -- Remote-sensing Image
10112 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('r','Remote-sensing Image');
10113 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','b','1','1','SMD');
10114 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
10115 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','d','3','1','Altitude of sensor');
10116 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Surface');
10117 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Airborne');
10118 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Spaceborne');
10119 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10120 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10121 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10122 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','e','4','1','Attitude of sensor');
10123 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Low oblique');
10124 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'High oblique');
10125 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Vertical');
10126 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10127 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10128 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','f','5','1','Cloud cover');
10129 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('0',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'0-09%');
10130 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('1',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'10-19%');
10131 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('2',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'20-29%');
10132 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('3',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'30-39%');
10133 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('4',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'40-49%');
10134 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('5',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'50-59%');
10135 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('6',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'60-69%');
10136 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('7',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'70-79%');
10137 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('8',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'80-89%');
10138 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('9',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'90-100%');
10139 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10140 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10141 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','g','6','1','Platform construction type');
10142 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Balloon');
10143 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Aircraft-low altitude');
10144 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Aircraft-medium altitude');
10145 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Aircraft-high altitude');
10146 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Manned spacecraft');
10147 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unmanned spacecraft');
10148 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Land-based remote-sensing device');
10149 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Water surface-based remote-sensing device');
10150 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Submersible remote-sensing device');
10151 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10152 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10153 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10154 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','h','7','1','Platform use category');
10155 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Meteorological');
10156 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Surface observing');
10157 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Space observing');
10158 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed uses');
10159 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10160 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10161 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10162 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','i','8','1','Sensor type');
10163 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Active');
10164 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Passive');
10165 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10166 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10167 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('r','j','9','2','Data type');
10168 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('aa',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Visible light');
10169 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('da',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Near infrared');
10170 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('db',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Middle infrared');
10171 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('dc',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Far infrared');
10172 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('dd',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Thermal infrared');
10173 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('de',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Shortwave infrared (SWIR)');
10174 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('df',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Reflective infrared');
10175 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('dv',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Combinations');
10176 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('dz',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other infrared data');
10177 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('ga',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sidelooking airborne radar (SLAR)');
10178 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gb',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Synthetic aperture radar (SAR-single frequency)');
10179 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gc',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'SAR-multi-frequency (multichannel)');
10180 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gd',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'SAR-like polarization');
10181 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('ge',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'SAR-cross polarization');
10182 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gf',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Infometric SAR');
10183 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gg',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Polarmetric SAR');
10184 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gu',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Passive microwave mapping');
10185 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('gz',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other microwave data');
10186 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('ja',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Far ultraviolet');
10187 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('jb',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Middle ultraviolet');
10188 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('jc',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Near ultraviolet');
10189 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('jv',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Ultraviolet combinations');
10190 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('jz',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other ultraviolet data');
10191 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('ma',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multi-spectral, multidata');
10192 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('mb',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multi-temporal');
10193 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('mm',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Combination of various data types');
10194 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('nn',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10195 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('pa',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sonar-water depth');
10196 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('pb',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sonar-bottom topography images, sidescan');
10197 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('pc',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sonar-bottom topography, near-surface');
10198 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('pd',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sonar-bottom topography, near-bottom');
10199 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('pe',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Seismic surveys');
10200 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('pz',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other acoustical data');
10201 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('ra',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Gravity anomales (general)');
10202 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('rb',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Free-air');
10203 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('rc',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Bouger');
10204 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('rd',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Isostatic');
10205 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('sa',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic field');
10206 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('ta',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Radiometric surveys');
10207 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('uu',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10208 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('zz',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10209
10210 -- Sound Recording
10211 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('s','Sound Recording');
10212 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','b','1','1','SMD');
10213 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound disc');
10214 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Cylinder');
10215 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound cartridge');
10216 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound-track film');
10217 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Roll');
10218 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound cassette');
10219 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('t',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound-tape reel');
10220 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
10221 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('w',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Wire recording');
10222 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10223 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','d','3','1','Speed');
10224 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'16 rpm');
10225 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'33 1/3 rpm');
10226 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'45 rpm');
10227 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'78 rpm');
10228 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 rpm');
10229 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1.4 mps');
10230 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'120 rpm');
10231 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'160 rpm');
10232 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'15/16 ips');
10233 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('l',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1 7/8 ips');
10234 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 3/4 ips');
10235 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'7 1/2 ips');
10236 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'15 ips');
10237 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'30 ips');
10238 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10239 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10240 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','e','4','1','Configuration of playback channels');
10241 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Monaural');
10242 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Quadraphonic');
10243 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stereophonic');
10244 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10245 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10246 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','f','5','1','Groove width or pitch');
10247 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Microgroove/fine');
10248 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10249 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Coarse/standard');
10250 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10251 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10252 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','g','6','1','Dimensions');
10253 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 in.');
10254 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'5 in.');
10255 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'7 in.');
10256 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'10 in.');
10257 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'12 in.');
10258 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'16 in.');
10259 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'4 3/4 in. (12 cm.)');
10260 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3 7/8 x 2 1/2 in.');
10261 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10262 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'5 1/4 x 3 7/8 in.');
10263 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'2 3/4 x 4 in.');
10264 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10265 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10266 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','h','7','1','Tape width');
10267 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('l',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1/8 in.');
10268 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1/4in.');
10269 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10270 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1/2 in.');
10271 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1 in.');
10272 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10273 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10274 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','i','8','1','Tape configuration ');
10275 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Full (1) track');
10276 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Half (2) track');
10277 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Quarter (4) track');
10278 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 track');
10279 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'12 track');
10280 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'16 track');
10281 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10282 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10283 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10284 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','m','12','1','Special playback');
10285 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'NAB standard');
10286 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'CCIR standard');
10287 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Dolby-B encoded, standard Dolby');
10288 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'dbx encoded');
10289 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Digital recording');
10290 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Dolby-A encoded');
10291 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Dolby-C encoded');
10292 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'CX encoded');
10293 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10294 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10295 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10296 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('s','n','13','1','Capture and storage');
10297 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Acoustical capture, direct storage');
10298 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Direct storage, not acoustical');
10299 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Digital storage');
10300 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Analog electrical storage');
10301 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10302 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10303
10304 -- Videorecording
10305 INSERT INTO config.marc21_physical_characteristic_type_map (ptype_key, label) VALUES ('v','Videorecording');
10306 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','b','1','1','SMD');
10307 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videocartridge');
10308 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videodisc');
10309 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videocassette');
10310 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videoreel');
10311 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unspecified');
10312 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10313 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','d','3','1','Color');
10314 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Black-and-white');
10315 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multicolored');
10316 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
10317 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10318 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10319 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10320 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','e','4','1','Videorecording format');
10321 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Beta');
10322 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'VHS');
10323 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'U-matic');
10324 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'EIAJ');
10325 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Type C');
10326 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Quadruplex');
10327 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Laserdisc');
10328 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'CED');
10329 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Betacam');
10330 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('j',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Betacam SP');
10331 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Super-VHS');
10332 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'M-II');
10333 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'D-2');
10334 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 mm.');
10335 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Hi-8 mm.');
10336 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10337 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('v',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'DVD');
10338 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10339 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','f','5','1','Sound on medium or separate');
10340 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound on medium');
10341 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound separate from medium');
10342 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10343 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','g','6','1','Medium for sound');
10344 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical sound track on motion picture film');
10345 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('b',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic sound track on motion picture film');
10346 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('c',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape in cartridge');
10347 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('d',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Sound disc');
10348 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('e',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape on reel');
10349 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('f',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Magnetic audio tape in cassette');
10350 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('g',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Optical and magnetic sound track on motion picture film');
10351 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('h',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videotape');
10352 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('i',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Videodisc');
10353 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10354 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10355 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','h','7','1','Dimensions');
10356 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('a',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'8 mm.');
10357 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1/4 in.');
10358 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('o',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1/2 in.');
10359 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('p',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'1 in.');
10360 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'2 in.');
10361 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('r',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'3/4 in.');
10362 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10363 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10364 INSERT INTO config.marc21_physical_characteristic_subfield_map (ptype_key,subfield,start_pos,length,label) VALUES ('v','i','8','1','Configuration of playback channel');
10365 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('k',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Mixed');
10366 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('m',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Monaural');
10367 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('n',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Not applicable');
10368 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('q',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Multichannel, surround or quadraphonic');
10369 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('s',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Stereophonic');
10370 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('u',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Unknown');
10371 INSERT INTO config.marc21_physical_characteristic_value_map (value,ptype_subfield,label) VALUES ('z',CURRVAL('config.marc21_physical_characteristic_subfield_map_id_seq'),'Other');
10372
10373 -- Fixed Field position data -- 0-based!
10374 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Alph', '006', 'SER', 16, 1, ' ');
10375 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Alph', '008', 'SER', 33, 1, ' ');
10376 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '006', 'BKS', 5, 1, ' ');
10377 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '006', 'COM', 5, 1, ' ');
10378 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '006', 'REC', 5, 1, ' ');
10379 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '006', 'SCO', 5, 1, ' ');
10380 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '006', 'SER', 5, 1, ' ');
10381 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '006', 'VIS', 5, 1, ' ');
10382 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '008', 'BKS', 22, 1, ' ');
10383 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '008', 'COM', 22, 1, ' ');
10384 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '008', 'REC', 22, 1, ' ');
10385 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '008', 'SCO', 22, 1, ' ');
10386 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '008', 'SER', 22, 1, ' ');
10387 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Audn', '008', 'VIS', 22, 1, ' ');
10388 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'BKS', 7, 1, 'm');
10389 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'COM', 7, 1, 'm');
10390 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'MAP', 7, 1, 'm');
10391 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'MIX', 7, 1, 'c');
10392 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'REC', 7, 1, 'm');
10393 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'SCO', 7, 1, 'm');
10394 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'SER', 7, 1, 's');
10395 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('BLvl', 'ldr', 'VIS', 7, 1, 'm');
10396 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Biog', '006', 'BKS', 17, 1, ' ');
10397 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Biog', '008', 'BKS', 34, 1, ' ');
10398 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Conf', '006', 'BKS', 7, 4, ' ');
10399 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Conf', '006', 'SER', 8, 3, ' ');
10400 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Conf', '008', 'BKS', 24, 4, ' ');
10401 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Conf', '008', 'SER', 25, 3, ' ');
10402 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'BKS', 8, 1, ' ');
10403 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'COM', 8, 1, ' ');
10404 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'MAP', 8, 1, ' ');
10405 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'MIX', 8, 1, ' ');
10406 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'REC', 8, 1, ' ');
10407 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'SCO', 8, 1, ' ');
10408 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'SER', 8, 1, ' ');
10409 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctrl', 'ldr', 'VIS', 8, 1, ' ');
10410 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'BKS', 15, 3, ' ');
10411 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'COM', 15, 3, ' ');
10412 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'MAP', 15, 3, ' ');
10413 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'MIX', 15, 3, ' ');
10414 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'REC', 15, 3, ' ');
10415 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'SCO', 15, 3, ' ');
10416 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'SER', 15, 3, ' ');
10417 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ctry', '008', 'VIS', 15, 3, ' ');
10418 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'BKS', 7, 4, ' ');
10419 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'COM', 7, 4, ' ');
10420 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'MAP', 7, 4, ' ');
10421 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'MIX', 7, 4, ' ');
10422 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'REC', 7, 4, ' ');
10423 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'SCO', 7, 4, ' ');
10424 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'SER', 7, 4, ' ');
10425 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date1', '008', 'VIS', 7, 4, ' ');
10426 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'BKS', 11, 4, ' ');
10427 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'COM', 11, 4, ' ');
10428 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'MAP', 11, 4, ' ');
10429 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'MIX', 11, 4, ' ');
10430 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'REC', 11, 4, ' ');
10431 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'SCO', 11, 4, ' ');
10432 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'SER', 11, 4, '9');
10433 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Date2', '008', 'VIS', 11, 4, ' ');
10434 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'BKS', 18, 1, ' ');
10435 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'COM', 18, 1, ' ');
10436 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'MAP', 18, 1, ' ');
10437 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'MIX', 18, 1, ' ');
10438 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'REC', 18, 1, ' ');
10439 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'SCO', 18, 1, ' ');
10440 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'SER', 18, 1, ' ');
10441 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Desc', 'ldr', 'VIS', 18, 1, ' ');
10442 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'BKS', 6, 1, ' ');
10443 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'COM', 6, 1, ' ');
10444 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'MAP', 6, 1, ' ');
10445 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'MIX', 6, 1, ' ');
10446 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'REC', 6, 1, ' ');
10447 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'SCO', 6, 1, ' ');
10448 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'SER', 6, 1, 'c');
10449 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('DtSt', '008', 'VIS', 6, 1, ' ');
10450 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'BKS', 17, 1, ' ');
10451 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'COM', 17, 1, ' ');
10452 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'MAP', 17, 1, ' ');
10453 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'MIX', 17, 1, ' ');
10454 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'REC', 17, 1, ' ');
10455 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'SCO', 17, 1, ' ');
10456 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'SER', 17, 1, ' ');
10457 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('ELvl', 'ldr', 'VIS', 17, 1, ' ');
10458 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Fest', '006', 'BKS', 13, 1, '0');
10459 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Fest', '008', 'BKS', 30, 1, '0');
10460 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'BKS', 6, 1, ' ');
10461 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'MAP', 12, 1, ' ');
10462 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'MIX', 6, 1, ' ');
10463 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'REC', 6, 1, ' ');
10464 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'SCO', 6, 1, ' ');
10465 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'SER', 6, 1, ' ');
10466 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '006', 'VIS', 12, 1, ' ');
10467 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'BKS', 23, 1, ' ');
10468 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'MAP', 29, 1, ' ');
10469 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'MIX', 23, 1, ' ');
10470 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'REC', 23, 1, ' ');
10471 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'SCO', 23, 1, ' ');
10472 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'SER', 23, 1, ' ');
10473 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Form', '008', 'VIS', 29, 1, ' ');
10474 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '006', 'BKS', 11, 1, ' ');
10475 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '006', 'COM', 11, 1, ' ');
10476 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '006', 'MAP', 11, 1, ' ');
10477 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '006', 'SER', 11, 1, ' ');
10478 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '006', 'VIS', 11, 1, ' ');
10479 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '008', 'BKS', 28, 1, ' ');
10480 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '008', 'COM', 28, 1, ' ');
10481 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '008', 'MAP', 28, 1, ' ');
10482 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '008', 'SER', 28, 1, ' ');
10483 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('GPub', '008', 'VIS', 28, 1, ' ');
10484 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ills', '006', 'BKS', 1, 4, ' ');
10485 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Ills', '008', 'BKS', 18, 4, ' ');
10486 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Indx', '006', 'BKS', 14, 1, '0');
10487 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Indx', '006', 'MAP', 14, 1, '0');
10488 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Indx', '008', 'BKS', 31, 1, '0');
10489 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Indx', '008', 'MAP', 31, 1, '0');
10490 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'BKS', 35, 3, ' ');
10491 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'COM', 35, 3, ' ');
10492 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'MAP', 35, 3, ' ');
10493 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'MIX', 35, 3, ' ');
10494 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'REC', 35, 3, ' ');
10495 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'SCO', 35, 3, ' ');
10496 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'SER', 35, 3, ' ');
10497 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Lang', '008', 'VIS', 35, 3, ' ');
10498 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('LitF', '006', 'BKS', 16, 1, '0');
10499 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('LitF', '008', 'BKS', 33, 1, '0');
10500 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'BKS', 38, 1, ' ');
10501 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'COM', 38, 1, ' ');
10502 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'MAP', 38, 1, ' ');
10503 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'MIX', 38, 1, ' ');
10504 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'REC', 38, 1, ' ');
10505 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'SCO', 38, 1, ' ');
10506 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'SER', 38, 1, ' ');
10507 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('MRec', '008', 'VIS', 38, 1, ' ');
10508 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('S/L', '006', 'SER', 17, 1, '0');
10509 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('S/L', '008', 'SER', 34, 1, '0');
10510 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('TMat', '006', 'VIS', 16, 1, ' ');
10511 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('TMat', '008', 'VIS', 33, 1, ' ');
10512 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'BKS', 6, 1, 'a');
10513 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'COM', 6, 1, 'm');
10514 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'MAP', 6, 1, 'e');
10515 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'MIX', 6, 1, 'p');
10516 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'REC', 6, 1, 'i');
10517 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'SCO', 6, 1, 'c');
10518 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'SER', 6, 1, 'a');
10519 INSERT INTO config.marc21_ff_pos_map (fixed_field, tag, rec_type,start_pos, length, default_val) VALUES ('Type', 'ldr', 'VIS', 6, 1, 'g');
10520
10521 CREATE OR REPLACE FUNCTION biblio.marc21_record_type( rid BIGINT ) RETURNS config.marc21_rec_type_map AS $func$
10522 DECLARE
10523         ldr         RECORD;
10524         tval        TEXT;
10525         tval_rec    RECORD;
10526         bval        TEXT;
10527         bval_rec    RECORD;
10528     retval      config.marc21_rec_type_map%ROWTYPE;
10529 BEGIN
10530     SELECT * INTO ldr FROM metabib.full_rec WHERE record = rid AND tag = 'LDR' LIMIT 1;
10531
10532     IF ldr.id IS NULL THEN
10533         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
10534         RETURN retval;
10535     END IF;
10536
10537     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
10538     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
10539
10540
10541     tval := SUBSTRING( ldr.value, tval_rec.start_pos + 1, tval_rec.length );
10542     bval := SUBSTRING( ldr.value, bval_rec.start_pos + 1, bval_rec.length );
10543
10544     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr.value;
10545
10546     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
10547
10548
10549     IF retval.code IS NULL THEN
10550         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
10551     END IF;
10552
10553     RETURN retval;
10554 END;
10555 $func$ LANGUAGE PLPGSQL;
10556
10557 CREATE OR REPLACE FUNCTION biblio.marc21_extract_fixed_field( rid BIGINT, ff TEXT ) RETURNS TEXT AS $func$
10558 DECLARE
10559     rtype       TEXT;
10560     ff_pos      RECORD;
10561     tag_data    RECORD;
10562     val         TEXT;
10563 BEGIN
10564     rtype := (biblio.marc21_record_type( rid )).code;
10565     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
10566         FOR tag_data IN SELECT * FROM metabib.full_rec WHERE tag = UPPER(ff_pos.tag) AND record = rid LOOP
10567             val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
10568             RETURN val;
10569         END LOOP;
10570         val := REPEAT( ff_pos.default_val, ff_pos.length );
10571         RETURN val;
10572     END LOOP;
10573
10574     RETURN NULL;
10575 END;
10576 $func$ LANGUAGE PLPGSQL;
10577
10578 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
10579 CREATE OR REPLACE FUNCTION biblio.marc21_physical_characteristics( rid BIGINT ) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
10580 DECLARE
10581     rowid   INT := 0;
10582     _007    RECORD;
10583     ptype   config.marc21_physical_characteristic_type_map%ROWTYPE;
10584     psf     config.marc21_physical_characteristic_subfield_map%ROWTYPE;
10585     pval    config.marc21_physical_characteristic_value_map%ROWTYPE;
10586     retval  biblio.marc21_physical_characteristics%ROWTYPE;
10587 BEGIN
10588
10589     SELECT * INTO _007 FROM metabib.full_rec WHERE record = rid AND tag = '007' LIMIT 1;
10590
10591     IF _007.id IS NOT NULL THEN
10592         SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007.value, 1, 1 );
10593
10594         IF ptype.ptype_key IS NOT NULL THEN
10595             FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
10596                 SELECT * INTO pval FROM config.marc21_physical_characteristic_value_map WHERE ptype_subfield = psf.id AND value = SUBSTRING( _007.value, psf.start_pos + 1, psf.length );
10597
10598                 IF pval.id IS NOT NULL THEN
10599                     rowid := rowid + 1;
10600                     retval.id := rowid;
10601                     retval.record := rid;
10602                     retval.ptype := ptype.ptype_key;
10603                     retval.subfield := psf.id;
10604                     retval.value := pval.id;
10605                     RETURN NEXT retval;
10606                 END IF;
10607
10608             END LOOP;
10609         END IF;
10610     END IF;
10611
10612     RETURN;
10613 END;
10614 $func$ LANGUAGE PLPGSQL;
10615
10616 DROP VIEW IF EXISTS money.open_usr_circulation_summary;
10617 DROP VIEW IF EXISTS money.open_usr_summary;
10618 DROP VIEW IF EXISTS money.open_billable_xact_summary;
10619
10620 -- The view should supply defaults for numeric (amount) columns
10621 CREATE OR REPLACE VIEW money.billable_xact_summary AS
10622     SELECT  xact.id,
10623         xact.usr,
10624         xact.xact_start,
10625         xact.xact_finish,
10626         COALESCE(credit.amount, 0.0::numeric) AS total_paid,
10627         credit.payment_ts AS last_payment_ts,
10628         credit.note AS last_payment_note,
10629         credit.payment_type AS last_payment_type,
10630         COALESCE(debit.amount, 0.0::numeric) AS total_owed,
10631         debit.billing_ts AS last_billing_ts,
10632         debit.note AS last_billing_note,
10633         debit.billing_type AS last_billing_type,
10634         COALESCE(debit.amount, 0.0::numeric) - COALESCE(credit.amount, 0.0::numeric) AS balance_owed,
10635         p.relname AS xact_type
10636       FROM  money.billable_xact xact
10637         JOIN pg_class p ON xact.tableoid = p.oid
10638         LEFT JOIN (
10639             SELECT  billing.xact,
10640                 sum(billing.amount) AS amount,
10641                 max(billing.billing_ts) AS billing_ts,
10642                 last(billing.note) AS note,
10643                 last(billing.billing_type) AS billing_type
10644               FROM  money.billing
10645               WHERE billing.voided IS FALSE
10646               GROUP BY billing.xact
10647             ) debit ON xact.id = debit.xact
10648         LEFT JOIN (
10649             SELECT  payment_view.xact,
10650                 sum(payment_view.amount) AS amount,
10651                 max(payment_view.payment_ts) AS payment_ts,
10652                 last(payment_view.note) AS note,
10653                 last(payment_view.payment_type) AS payment_type
10654               FROM  money.payment_view
10655               WHERE payment_view.voided IS FALSE
10656               GROUP BY payment_view.xact
10657             ) credit ON xact.id = credit.xact
10658       ORDER BY debit.billing_ts, credit.payment_ts;
10659
10660 CREATE OR REPLACE VIEW money.open_billable_xact_summary AS 
10661     SELECT * FROM money.billable_xact_summary_location_view
10662     WHERE xact_finish IS NULL;
10663
10664 CREATE OR REPLACE VIEW money.open_usr_circulation_summary AS
10665     SELECT 
10666         usr,
10667         SUM(total_paid) AS total_paid,
10668         SUM(total_owed) AS total_owed,
10669         SUM(balance_owed) AS balance_owed
10670     FROM  money.materialized_billable_xact_summary
10671     WHERE xact_type = 'circulation' AND xact_finish IS NULL
10672     GROUP BY usr;
10673
10674 CREATE OR REPLACE VIEW money.usr_summary AS
10675     SELECT 
10676         usr, 
10677         sum(total_paid) AS total_paid, 
10678         sum(total_owed) AS total_owed, 
10679         sum(balance_owed) AS balance_owed
10680     FROM money.materialized_billable_xact_summary
10681     GROUP BY usr;
10682
10683 CREATE OR REPLACE VIEW money.open_usr_summary AS
10684     SELECT 
10685         usr, 
10686         sum(total_paid) AS total_paid, 
10687         sum(total_owed) AS total_owed, 
10688         sum(balance_owed) AS balance_owed
10689     FROM money.materialized_billable_xact_summary
10690     WHERE xact_finish IS NULL
10691     GROUP BY usr;
10692
10693 -- CREATE RULE protect_mfhd_delete AS ON DELETE TO serial.record_entry DO INSTEAD UPDATE serial.record_entry SET deleted = true WHERE old.id = serial.record_entry.id;
10694
10695 CREATE TABLE config.biblio_fingerprint (
10696         id                      SERIAL  PRIMARY KEY,
10697         name            TEXT    NOT NULL, 
10698         xpath           TEXT    NOT NULL,
10699     first_word  BOOL    NOT NULL DEFAULT FALSE,
10700         format          TEXT    NOT NULL DEFAULT 'marcxml'
10701 );
10702
10703 INSERT INTO config.biblio_fingerprint (name, xpath, format)
10704     VALUES (
10705         'Title',
10706         '//marc:datafield[@tag="700"]/marc:subfield[@code="t"]|' ||
10707             '//marc:datafield[@tag="240"]/marc:subfield[@code="a"]|' ||
10708             '//marc:datafield[@tag="242"]/marc:subfield[@code="a"]|' ||
10709             '//marc:datafield[@tag="246"]/marc:subfield[@code="a"]|' ||
10710             '//marc:datafield[@tag="245"]/marc:subfield[@code="a"]',
10711         'marcxml'
10712     );
10713
10714 INSERT INTO config.biblio_fingerprint (name, xpath, format, first_word)
10715     VALUES (
10716         'Author',
10717         '//marc:datafield[@tag="700" and ./*[@code="t"]]/marc:subfield[@code="a"]|'
10718             '//marc:datafield[@tag="100"]/marc:subfield[@code="a"]|'
10719             '//marc:datafield[@tag="110"]/marc:subfield[@code="a"]|'
10720             '//marc:datafield[@tag="111"]/marc:subfield[@code="a"]|'
10721             '//marc:datafield[@tag="260"]/marc:subfield[@code="b"]',
10722         'marcxml',
10723         TRUE
10724     );
10725
10726 CREATE OR REPLACE FUNCTION biblio.extract_quality ( marc TEXT, best_lang TEXT, best_type TEXT ) RETURNS INT AS $func$
10727 DECLARE
10728     qual        INT;
10729     ldr         TEXT;
10730     tval        TEXT;
10731     tval_rec    RECORD;
10732     bval        TEXT;
10733     bval_rec    RECORD;
10734     type_map    RECORD;
10735     ff_pos      RECORD;
10736     ff_tag_data TEXT;
10737 BEGIN
10738
10739     IF marc IS NULL OR marc = '' THEN
10740         RETURN NULL;
10741     END IF;
10742
10743     -- First, the count of tags
10744     qual := ARRAY_UPPER(oils_xpath('*[local-name()="datafield"]', marc), 1);
10745
10746     -- now go through a bunch of pain to get the record type
10747     IF best_type IS NOT NULL THEN
10748         ldr := (oils_xpath('//*[local-name()="leader"]/text()', marc))[1];
10749
10750         IF ldr IS NOT NULL THEN
10751             SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
10752             SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
10753
10754
10755             tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
10756             bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
10757
10758             -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
10759
10760             SELECT * INTO type_map FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
10761
10762             IF type_map.code IS NOT NULL THEN
10763                 IF best_type = type_map.code THEN
10764                     qual := qual + qual / 2;
10765                 END IF;
10766
10767                 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = 'Lang' AND rec_type = type_map.code ORDER BY tag DESC LOOP
10768                     ff_tag_data := SUBSTRING((oils_xpath('//*[@tag="' || ff_pos.tag || '"]/text()',marc))[1], ff_pos.start_pos + 1, ff_pos.length);
10769                     IF ff_tag_data = best_lang THEN
10770                             qual := qual + 100;
10771                     END IF;
10772                 END LOOP;
10773             END IF;
10774         END IF;
10775     END IF;
10776
10777     -- Now look for some quality metrics
10778     -- DCL record?
10779     IF ARRAY_UPPER(oils_xpath('//*[@tag="040"]/*[@code="a" and contains(.,"DLC")]', marc), 1) = 1 THEN
10780         qual := qual + 10;
10781     END IF;
10782
10783     -- From OCLC?
10784     IF (oils_xpath('//*[@tag="003"]/text()', marc))[1] ~* E'oclo?c' THEN
10785         qual := qual + 10;
10786     END IF;
10787
10788     RETURN qual;
10789
10790 END;
10791 $func$ LANGUAGE PLPGSQL;
10792
10793 CREATE OR REPLACE FUNCTION biblio.extract_fingerprint ( marc text ) RETURNS TEXT AS $func$
10794 DECLARE
10795     idx     config.biblio_fingerprint%ROWTYPE;
10796     xfrm        config.xml_transform%ROWTYPE;
10797     prev_xfrm   TEXT;
10798     transformed_xml TEXT;
10799     xml_node    TEXT;
10800     xml_node_list   TEXT[];
10801     raw_text    TEXT;
10802     output_text TEXT := '';
10803 BEGIN
10804
10805     IF marc IS NULL OR marc = '' THEN
10806         RETURN NULL;
10807     END IF;
10808
10809     -- Loop over the indexing entries
10810     FOR idx IN SELECT * FROM config.biblio_fingerprint ORDER BY format, id LOOP
10811
10812         SELECT INTO xfrm * from config.xml_transform WHERE name = idx.format;
10813
10814         -- See if we can skip the XSLT ... it's expensive
10815         IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
10816             -- Can't skip the transform
10817             IF xfrm.xslt <> '---' THEN
10818                 transformed_xml := oils_xslt_process(marc,xfrm.xslt);
10819             ELSE
10820                 transformed_xml := marc;
10821             END IF;
10822
10823             prev_xfrm := xfrm.name;
10824         END IF;
10825
10826         raw_text := COALESCE(
10827             naco_normalize(
10828                 ARRAY_TO_STRING(
10829                     oils_xpath(
10830                         '//text()',
10831                         (oils_xpath(
10832                             idx.xpath,
10833                             transformed_xml,
10834                             ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]
10835                         ))[1]
10836                     ),
10837                     ''
10838                 )
10839             ),
10840             ''
10841         );
10842
10843         raw_text := REGEXP_REPLACE(raw_text, E'\\[.+?\\]', E'');
10844         raw_text := REGEXP_REPLACE(raw_text, E'\\mthe\\M|\\man?d?d\\M', E'', 'g'); -- arg! the pain!
10845
10846         IF idx.first_word IS TRUE THEN
10847             raw_text := REGEXP_REPLACE(raw_text, E'^(\\w+).*?$', E'\\1');
10848         END IF;
10849
10850         output_text := output_text || REGEXP_REPLACE(raw_text, E'\\s+', '', 'g');
10851
10852     END LOOP;
10853
10854     RETURN output_text;
10855
10856 END;
10857 $func$ LANGUAGE PLPGSQL;
10858
10859 -- BEFORE UPDATE OR INSERT trigger for biblio.record_entry
10860 CREATE OR REPLACE FUNCTION biblio.fingerprint_trigger () RETURNS TRIGGER AS $func$
10861 BEGIN
10862
10863     -- For TG_ARGV, first param is language (like 'eng'), second is record type (like 'BKS')
10864
10865     IF NEW.deleted IS TRUE THEN -- we don't much care, then, do we?
10866         RETURN NEW;
10867     END IF;
10868
10869     NEW.fingerprint := biblio.extract_fingerprint(NEW.marc);
10870     NEW.quality := biblio.extract_quality(NEW.marc, TG_ARGV[0], TG_ARGV[1]);
10871
10872     RETURN NEW;
10873
10874 END;
10875 $func$ LANGUAGE PLPGSQL;
10876
10877 CREATE TABLE config.internal_flag (
10878     name    TEXT    PRIMARY KEY,
10879     value   TEXT,
10880     enabled BOOL    NOT NULL DEFAULT FALSE
10881 );
10882 INSERT INTO config.internal_flag (name) VALUES ('ingest.metarecord_mapping.skip_on_insert');
10883 INSERT INTO config.internal_flag (name) VALUES ('ingest.reingest.force_on_same_marc');
10884 INSERT INTO config.internal_flag (name) VALUES ('ingest.reingest.skip_located_uri');
10885 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_located_uri');
10886 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_metabib_full_rec');
10887 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_metabib_rec_descriptor');
10888 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_metabib_field_entry');
10889 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_authority_linking');
10890 INSERT INTO config.internal_flag (name) VALUES ('ingest.metarecord_mapping.skip_on_update');
10891 INSERT INTO config.internal_flag (name) VALUES ('ingest.assume_inserts_only');
10892
10893 CREATE TABLE authority.bib_linking (
10894     id          BIGSERIAL   PRIMARY KEY,
10895     bib         BIGINT      NOT NULL REFERENCES biblio.record_entry (id),
10896     authority   BIGINT      NOT NULL REFERENCES authority.record_entry (id)
10897 );
10898 CREATE INDEX authority_bl_bib_idx ON authority.bib_linking ( bib );
10899 CREATE UNIQUE INDEX authority_bl_bib_authority_once_idx ON authority.bib_linking ( authority, bib );
10900
10901 CREATE OR REPLACE FUNCTION public.remove_paren_substring( TEXT ) RETURNS TEXT AS $func$
10902     SELECT regexp_replace($1, $$\([^)]+\)$$, '', 'g');
10903 $func$ LANGUAGE SQL STRICT IMMUTABLE;
10904
10905 CREATE OR REPLACE FUNCTION biblio.map_authority_linking (bibid BIGINT, marc TEXT) RETURNS BIGINT AS $func$
10906     DELETE FROM authority.bib_linking WHERE bib = $1;
10907     INSERT INTO authority.bib_linking (bib, authority)
10908         SELECT  y.bib,
10909                 y.authority
10910           FROM (    SELECT  DISTINCT $1 AS bib,
10911                             BTRIM(remove_paren_substring(txt))::BIGINT AS authority
10912                       FROM  explode_array(oils_xpath('//*[@code="0"]/text()',$2)) x(txt)
10913                       WHERE BTRIM(remove_paren_substring(txt)) ~ $re$^\d+$$re$
10914                 ) y JOIN authority.record_entry r ON r.id = y.authority;
10915     SELECT $1;
10916 $func$ LANGUAGE SQL;
10917
10918 CREATE OR REPLACE FUNCTION metabib.reingest_metabib_rec_descriptor( bib_id BIGINT ) RETURNS VOID AS $func$
10919 BEGIN
10920     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
10921     IF NOT FOUND THEN
10922         DELETE FROM metabib.rec_descriptor WHERE record = bib_id;
10923     END IF;
10924     INSERT INTO metabib.rec_descriptor (record, item_type, item_form, bib_level, control_type, enc_level, audience, lit_form, type_mat, cat_form, pub_status, item_lang, vr_format, date1, date2)
10925         SELECT  bib_id,
10926                 biblio.marc21_extract_fixed_field( bib_id, 'Type' ),
10927                 biblio.marc21_extract_fixed_field( bib_id, 'Form' ),
10928                 biblio.marc21_extract_fixed_field( bib_id, 'BLvl' ),
10929                 biblio.marc21_extract_fixed_field( bib_id, 'Ctrl' ),
10930                 biblio.marc21_extract_fixed_field( bib_id, 'ELvl' ),
10931                 biblio.marc21_extract_fixed_field( bib_id, 'Audn' ),
10932                 biblio.marc21_extract_fixed_field( bib_id, 'LitF' ),
10933                 biblio.marc21_extract_fixed_field( bib_id, 'TMat' ),
10934                 biblio.marc21_extract_fixed_field( bib_id, 'Desc' ),
10935                 biblio.marc21_extract_fixed_field( bib_id, 'DtSt' ),
10936                 biblio.marc21_extract_fixed_field( bib_id, 'Lang' ),
10937                 (   SELECT  v.value
10938                       FROM  biblio.marc21_physical_characteristics( bib_id) p
10939                             JOIN config.marc21_physical_characteristic_subfield_map s ON (s.id = p.subfield)
10940                             JOIN config.marc21_physical_characteristic_value_map v ON (v.id = p.value)
10941                       WHERE p.ptype = 'v' AND s.subfield = 'e'    ),
10942                 LPAD(NULLIF(REGEXP_REPLACE(NULLIF(biblio.marc21_extract_fixed_field( bib_id, 'Date1'), ''), E'\\D', '0', 'g')::INT,0)::TEXT,4,'0'),
10943                 LPAD(NULLIF(REGEXP_REPLACE(NULLIF(biblio.marc21_extract_fixed_field( bib_id, 'Date2'), ''), E'\\D', '9', 'g')::INT,9999)::TEXT,4,'0');
10944
10945     RETURN;
10946 END;
10947 $func$ LANGUAGE PLPGSQL;
10948
10949 CREATE TABLE config.metabib_class (
10950     name    TEXT    PRIMARY KEY,
10951     label   TEXT    NOT NULL UNIQUE
10952 );
10953
10954 INSERT INTO config.metabib_class ( name, label ) VALUES ( 'keyword', oils_i18n_gettext('keyword', 'Keyword', 'cmc', 'label') );
10955 INSERT INTO config.metabib_class ( name, label ) VALUES ( 'title', oils_i18n_gettext('title', 'Title', 'cmc', 'label') );
10956 INSERT INTO config.metabib_class ( name, label ) VALUES ( 'author', oils_i18n_gettext('author', 'Author', 'cmc', 'label') );
10957 INSERT INTO config.metabib_class ( name, label ) VALUES ( 'subject', oils_i18n_gettext('subject', 'Subject', 'cmc', 'label') );
10958 INSERT INTO config.metabib_class ( name, label ) VALUES ( 'series', oils_i18n_gettext('series', 'Series', 'cmc', 'label') );
10959
10960 CREATE TABLE metabib.facet_entry (
10961         id              BIGSERIAL       PRIMARY KEY,
10962         source          BIGINT          NOT NULL,
10963         field           INT             NOT NULL,
10964         value           TEXT            NOT NULL
10965 );
10966
10967 CREATE OR REPLACE FUNCTION metabib.reingest_metabib_field_entries( bib_id BIGINT ) RETURNS VOID AS $func$
10968 DECLARE
10969     fclass          RECORD;
10970     ind_data        metabib.field_entry_template%ROWTYPE;
10971 BEGIN
10972     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
10973     IF NOT FOUND THEN
10974         FOR fclass IN SELECT * FROM config.metabib_class LOOP
10975             -- RAISE NOTICE 'Emptying out %', fclass.name;
10976             EXECUTE $$DELETE FROM metabib.$$ || fclass.name || $$_field_entry WHERE source = $$ || bib_id;
10977         END LOOP;
10978         DELETE FROM metabib.facet_entry WHERE source = bib_id;
10979     END IF;
10980
10981     FOR ind_data IN SELECT * FROM biblio.extract_metabib_field_entry( bib_id ) LOOP
10982         IF ind_data.field < 0 THEN
10983             ind_data.field = -1 * ind_data.field;
10984             INSERT INTO metabib.facet_entry (field, source, value)
10985                 VALUES (ind_data.field, ind_data.source, ind_data.value);
10986         ELSE
10987             EXECUTE $$
10988                 INSERT INTO metabib.$$ || ind_data.field_class || $$_field_entry (field, source, value)
10989                     VALUES ($$ ||
10990                         quote_literal(ind_data.field) || $$, $$ ||
10991                         quote_literal(ind_data.source) || $$, $$ ||
10992                         quote_literal(ind_data.value) ||
10993                     $$);$$;
10994         END IF;
10995
10996     END LOOP;
10997
10998     RETURN;
10999 END;
11000 $func$ LANGUAGE PLPGSQL;
11001
11002 CREATE OR REPLACE FUNCTION biblio.extract_located_uris( bib_id BIGINT, marcxml TEXT, editor_id INT ) RETURNS VOID AS $func$
11003 DECLARE
11004     uris            TEXT[];
11005     uri_xml         TEXT;
11006     uri_label       TEXT;
11007     uri_href        TEXT;
11008     uri_use         TEXT;
11009     uri_owner       TEXT;
11010     uri_owner_id    INT;
11011     uri_id          INT;
11012     uri_cn_id       INT;
11013     uri_map_id      INT;
11014 BEGIN
11015
11016     uris := oils_xpath('//*[@tag="856" and (@ind1="4" or @ind1="1") and (@ind2="0" or @ind2="1")]',marcxml);
11017     IF ARRAY_UPPER(uris,1) > 0 THEN
11018         FOR i IN 1 .. ARRAY_UPPER(uris, 1) LOOP
11019             -- First we pull info out of the 856
11020             uri_xml     := uris[i];
11021
11022             uri_href    := (oils_xpath('//*[@code="u"]/text()',uri_xml))[1];
11023             CONTINUE WHEN uri_href IS NULL;
11024
11025             uri_label   := (oils_xpath('//*[@code="y"]/text()|//*[@code="3"]/text()|//*[@code="u"]/text()',uri_xml))[1];
11026             CONTINUE WHEN uri_label IS NULL;
11027
11028             uri_owner   := (oils_xpath('//*[@code="9"]/text()|//*[@code="w"]/text()|//*[@code="n"]/text()',uri_xml))[1];
11029             CONTINUE WHEN uri_owner IS NULL;
11030
11031             uri_use     := (oils_xpath('//*[@code="z"]/text()|//*[@code="2"]/text()|//*[@code="n"]/text()|//*[@code="u"]/text()',uri_xml))[1];
11032
11033             uri_owner := REGEXP_REPLACE(uri_owner, $re$^.*?\((\w+)\).*$$re$, E'\\1');
11034
11035             SELECT id INTO uri_owner_id FROM actor.org_unit WHERE shortname = uri_owner;
11036             CONTINUE WHEN NOT FOUND;
11037
11038             -- now we look for a matching uri
11039             SELECT id INTO uri_id FROM asset.uri WHERE label = uri_label AND href = uri_href AND use_restriction = uri_use AND active;
11040             IF NOT FOUND THEN -- create one
11041                 INSERT INTO asset.uri (label, href, use_restriction) VALUES (uri_label, uri_href, uri_use);
11042                 SELECT id INTO uri_id FROM asset.uri WHERE label = uri_label AND href = uri_href AND use_restriction = uri_use AND active;
11043             END IF;
11044
11045             -- we need a call number to link through
11046             SELECT id INTO uri_cn_id FROM asset.call_number WHERE owning_lib = uri_owner_id AND record = bib_id AND label = '##URI##' AND NOT deleted;
11047             IF NOT FOUND THEN
11048                 INSERT INTO asset.call_number (owning_lib, record, create_date, edit_date, creator, editor, label)
11049                     VALUES (uri_owner_id, bib_id, 'now', 'now', editor_id, editor_id, '##URI##');
11050                 SELECT id INTO uri_cn_id FROM asset.call_number WHERE owning_lib = uri_owner_id AND record = bib_id AND label = '##URI##' AND NOT deleted;
11051             END IF;
11052
11053             -- now, link them if they're not already
11054             SELECT id INTO uri_map_id FROM asset.uri_call_number_map WHERE call_number = uri_cn_id AND uri = uri_id;
11055             IF NOT FOUND THEN
11056                 INSERT INTO asset.uri_call_number_map (call_number, uri) VALUES (uri_cn_id, uri_id);
11057             END IF;
11058
11059         END LOOP;
11060     END IF;
11061
11062     RETURN;
11063 END;
11064 $func$ LANGUAGE PLPGSQL;
11065
11066 CREATE OR REPLACE FUNCTION metabib.remap_metarecord_for_bib( bib_id BIGINT, fp TEXT ) RETURNS BIGINT AS $func$
11067 DECLARE
11068     source_count    INT;
11069     old_mr          BIGINT;
11070     tmp_mr          metabib.metarecord%ROWTYPE;
11071     deleted_mrs     BIGINT[];
11072 BEGIN
11073
11074     DELETE FROM metabib.metarecord_source_map WHERE source = bib_id; -- Rid ourselves of the search-estimate-killing linkage
11075
11076     FOR tmp_mr IN SELECT  m.* FROM  metabib.metarecord m JOIN metabib.metarecord_source_map s ON (s.metarecord = m.id) WHERE s.source = bib_id LOOP
11077
11078         IF old_mr IS NULL AND fp = tmp_mr.fingerprint THEN -- Find the first fingerprint-matching
11079             old_mr := tmp_mr.id;
11080         ELSE
11081             SELECT COUNT(*) INTO source_count FROM metabib.metarecord_source_map WHERE metarecord = tmp_mr.id;
11082             IF source_count = 0 THEN -- No other records
11083                 deleted_mrs := ARRAY_APPEND(deleted_mrs, tmp_mr.id);
11084                 DELETE FROM metabib.metarecord WHERE id = tmp_mr.id;
11085             END IF;
11086         END IF;
11087
11088     END LOOP;
11089
11090     IF old_mr IS NULL THEN -- we found no suitable, preexisting MR based on old source maps
11091         SELECT id INTO old_mr FROM metabib.metarecord WHERE fingerprint = fp; -- is there one for our current fingerprint?
11092         IF old_mr IS NULL THEN -- nope, create one and grab its id
11093             INSERT INTO metabib.metarecord ( fingerprint, master_record ) VALUES ( fp, bib_id );
11094             SELECT id INTO old_mr FROM metabib.metarecord WHERE fingerprint = fp;
11095         ELSE -- indeed there is. update it with a null cache and recalcualated master record
11096             UPDATE  metabib.metarecord
11097               SET   mods = NULL,
11098                     master_record = ( SELECT id FROM biblio.record_entry WHERE fingerprint = fp ORDER BY quality DESC LIMIT 1)
11099               WHERE id = old_mr;
11100         END IF;
11101     ELSE -- there was one we already attached to, update its mods cache and master_record
11102         UPDATE  metabib.metarecord
11103           SET   mods = NULL,
11104                 master_record = ( SELECT id FROM biblio.record_entry WHERE fingerprint = fp ORDER BY quality DESC LIMIT 1)
11105           WHERE id = old_mr;
11106     END IF;
11107
11108     INSERT INTO metabib.metarecord_source_map (metarecord, source) VALUES (old_mr, bib_id); -- new source mapping
11109
11110     IF ARRAY_UPPER(deleted_mrs,1) > 0 THEN
11111         UPDATE action.hold_request SET target = old_mr WHERE target IN ( SELECT explode_array(deleted_mrs) ) AND hold_type = 'M'; -- if we had to delete any MRs above, make sure their holds are moved
11112     END IF;
11113
11114     RETURN old_mr;
11115
11116 END;
11117 $func$ LANGUAGE PLPGSQL;
11118
11119 CREATE OR REPLACE FUNCTION metabib.reingest_metabib_full_rec( bib_id BIGINT ) RETURNS VOID AS $func$
11120 BEGIN
11121     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
11122     IF NOT FOUND THEN
11123         DELETE FROM metabib.real_full_rec WHERE record = bib_id;
11124     END IF;
11125     INSERT INTO metabib.real_full_rec (record, tag, ind1, ind2, subfield, value)
11126         SELECT record, tag, ind1, ind2, subfield, value FROM biblio.flatten_marc( bib_id );
11127
11128     RETURN;
11129 END;
11130 $func$ LANGUAGE PLPGSQL;
11131
11132 -- AFTER UPDATE OR INSERT trigger for biblio.record_entry
11133 CREATE OR REPLACE FUNCTION biblio.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
11134 BEGIN
11135
11136     IF NEW.deleted IS TRUE THEN -- If this bib is deleted
11137         DELETE FROM metabib.metarecord_source_map WHERE source = NEW.id; -- Rid ourselves of the search-estimate-killing linkage
11138         DELETE FROM authority.bib_linking WHERE bib = NEW.id; -- Avoid updating fields in bibs that are no longer visible
11139         RETURN NEW; -- and we're done
11140     END IF;
11141
11142     IF TG_OP = 'UPDATE' THEN -- re-ingest?
11143         PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
11144
11145         IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
11146             RETURN NEW;
11147         END IF;
11148     END IF;
11149
11150     -- Record authority linking
11151     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_linking' AND enabled;
11152     IF NOT FOUND THEN
11153         PERFORM biblio.map_authority_linking( NEW.id, NEW.marc );
11154     END IF;
11155
11156     -- Flatten and insert the mfr data
11157     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_metabib_full_rec' AND enabled;
11158     IF NOT FOUND THEN
11159         PERFORM metabib.reingest_metabib_full_rec(NEW.id);
11160         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_metabib_rec_descriptor' AND enabled;
11161         IF NOT FOUND THEN
11162             PERFORM metabib.reingest_metabib_rec_descriptor(NEW.id);
11163         END IF;
11164     END IF;
11165
11166     -- Gather and insert the field entry data
11167     PERFORM metabib.reingest_metabib_field_entries(NEW.id);
11168
11169     -- Located URI magic
11170     IF TG_OP = 'INSERT' THEN
11171         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_located_uri' AND enabled;
11172         IF NOT FOUND THEN
11173             PERFORM biblio.extract_located_uris( NEW.id, NEW.marc, NEW.editor );
11174         END IF;
11175     ELSE
11176         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_located_uri' AND enabled;
11177         IF NOT FOUND THEN
11178             PERFORM biblio.extract_located_uris( NEW.id, NEW.marc, NEW.editor );
11179         END IF;
11180     END IF;
11181
11182     -- (re)map metarecord-bib linking
11183     IF TG_OP = 'INSERT' THEN -- if not deleted and performing an insert, check for the flag
11184         PERFORM * FROM config.internal_flag WHERE name = 'ingest.metarecord_mapping.skip_on_insert' AND enabled;
11185         IF NOT FOUND THEN
11186             PERFORM metabib.remap_metarecord_for_bib( NEW.id, NEW.fingerprint );
11187         END IF;
11188     ELSE -- we're doing an update, and we're not deleted, remap
11189         PERFORM * FROM config.internal_flag WHERE name = 'ingest.metarecord_mapping.skip_on_update' AND enabled;
11190         IF NOT FOUND THEN
11191             PERFORM metabib.remap_metarecord_for_bib( NEW.id, NEW.fingerprint );
11192         END IF;
11193     END IF;
11194
11195     RETURN NEW;
11196 END;
11197 $func$ LANGUAGE PLPGSQL;
11198
11199 CREATE TRIGGER fingerprint_tgr BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.fingerprint_trigger ('eng','BKS');
11200 CREATE TRIGGER aaa_indexing_ingest_or_delete AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.indexing_ingest_or_delete ();
11201
11202 DROP TRIGGER IF EXISTS zzz_update_materialized_simple_rec_delete_tgr ON biblio.record_entry;
11203
11204 CREATE OR REPLACE FUNCTION oils_xpath_table ( key TEXT, document_field TEXT, relation_name TEXT, xpaths TEXT, criteria TEXT ) RETURNS SETOF RECORD AS $func$
11205 DECLARE
11206     xpath_list  TEXT[];
11207     select_list TEXT[];
11208     where_list  TEXT[];
11209     q           TEXT;
11210     out_record  RECORD;
11211     empty_test  RECORD;
11212 BEGIN
11213     xpath_list := STRING_TO_ARRAY( xpaths, '|' );
11214  
11215     select_list := ARRAY_APPEND( select_list, key || '::INT AS key' );
11216  
11217     FOR i IN 1 .. ARRAY_UPPER(xpath_list,1) LOOP
11218         IF xpath_list[i] = 'null()' THEN
11219             select_list := ARRAY_APPEND( select_list, 'NULL::TEXT AS c_' || i );
11220         ELSE
11221             select_list := ARRAY_APPEND(
11222                 select_list,
11223                 $sel$
11224                 EXPLODE_ARRAY(
11225                     COALESCE(
11226                         NULLIF(
11227                             oils_xpath(
11228                                 $sel$ ||
11229                                     quote_literal(
11230                                         CASE
11231                                             WHEN xpath_list[i] ~ $re$/[^/[]*@[^/]+$$re$ OR xpath_list[i] ~ $re$text\(\)$$re$ THEN xpath_list[i]
11232                                             ELSE xpath_list[i] || '//text()'
11233                                         END
11234                                     ) ||
11235                                 $sel$,
11236                                 $sel$ || document_field || $sel$
11237                             ),
11238                            '{}'::TEXT[]
11239                         ),
11240                         '{NULL}'::TEXT[]
11241                     )
11242                 ) AS c_$sel$ || i
11243             );
11244             where_list := ARRAY_APPEND(
11245                 where_list,
11246                 'c_' || i || ' IS NOT NULL'
11247             );
11248         END IF;
11249     END LOOP;
11250  
11251     q := $q$
11252 SELECT * FROM (
11253     SELECT $q$ || ARRAY_TO_STRING( select_list, ', ' ) || $q$ FROM $q$ || relation_name || $q$ WHERE ($q$ || criteria || $q$)
11254 )x WHERE $q$ || ARRAY_TO_STRING( where_list, ' AND ' );
11255     -- RAISE NOTICE 'query: %', q;
11256  
11257     FOR out_record IN EXECUTE q LOOP
11258         RETURN NEXT out_record;
11259     END LOOP;
11260  
11261     RETURN;
11262 END;
11263 $func$ LANGUAGE PLPGSQL IMMUTABLE;
11264
11265 CREATE OR REPLACE FUNCTION vandelay.ingest_items ( import_id BIGINT, attr_def_id BIGINT ) RETURNS SETOF vandelay.import_item AS $$
11266 DECLARE
11267
11268     owning_lib      TEXT;
11269     circ_lib        TEXT;
11270     call_number     TEXT;
11271     copy_number     TEXT;
11272     status          TEXT;
11273     location        TEXT;
11274     circulate       TEXT;
11275     deposit         TEXT;
11276     deposit_amount  TEXT;
11277     ref             TEXT;
11278     holdable        TEXT;
11279     price           TEXT;
11280     barcode         TEXT;
11281     circ_modifier   TEXT;
11282     circ_as_type    TEXT;
11283     alert_message   TEXT;
11284     opac_visible    TEXT;
11285     pub_note        TEXT;
11286     priv_note       TEXT;
11287
11288     attr_def        RECORD;
11289     tmp_attr_set    RECORD;
11290     attr_set        vandelay.import_item%ROWTYPE;
11291
11292     xpath           TEXT;
11293
11294 BEGIN
11295
11296     SELECT * INTO attr_def FROM vandelay.import_item_attr_definition WHERE id = attr_def_id;
11297
11298     IF FOUND THEN
11299
11300         attr_set.definition := attr_def.id; 
11301     
11302         -- Build the combined XPath
11303     
11304         owning_lib :=
11305             CASE
11306                 WHEN attr_def.owning_lib IS NULL THEN 'null()'
11307                 WHEN LENGTH( attr_def.owning_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.owning_lib || '"]'
11308                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.owning_lib
11309             END;
11310     
11311         circ_lib :=
11312             CASE
11313                 WHEN attr_def.circ_lib IS NULL THEN 'null()'
11314                 WHEN LENGTH( attr_def.circ_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_lib || '"]'
11315                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_lib
11316             END;
11317     
11318         call_number :=
11319             CASE
11320                 WHEN attr_def.call_number IS NULL THEN 'null()'
11321                 WHEN LENGTH( attr_def.call_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.call_number || '"]'
11322                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.call_number
11323             END;
11324     
11325         copy_number :=
11326             CASE
11327                 WHEN attr_def.copy_number IS NULL THEN 'null()'
11328                 WHEN LENGTH( attr_def.copy_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.copy_number || '"]'
11329                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.copy_number
11330             END;
11331     
11332         status :=
11333             CASE
11334                 WHEN attr_def.status IS NULL THEN 'null()'
11335                 WHEN LENGTH( attr_def.status ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.status || '"]'
11336                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.status
11337             END;
11338     
11339         location :=
11340             CASE
11341                 WHEN attr_def.location IS NULL THEN 'null()'
11342                 WHEN LENGTH( attr_def.location ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.location || '"]'
11343                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.location
11344             END;
11345     
11346         circulate :=
11347             CASE
11348                 WHEN attr_def.circulate IS NULL THEN 'null()'
11349                 WHEN LENGTH( attr_def.circulate ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circulate || '"]'
11350                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circulate
11351             END;
11352     
11353         deposit :=
11354             CASE
11355                 WHEN attr_def.deposit IS NULL THEN 'null()'
11356                 WHEN LENGTH( attr_def.deposit ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit || '"]'
11357                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit
11358             END;
11359     
11360         deposit_amount :=
11361             CASE
11362                 WHEN attr_def.deposit_amount IS NULL THEN 'null()'
11363                 WHEN LENGTH( attr_def.deposit_amount ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit_amount || '"]'
11364                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit_amount
11365             END;
11366     
11367         ref :=
11368             CASE
11369                 WHEN attr_def.ref IS NULL THEN 'null()'
11370                 WHEN LENGTH( attr_def.ref ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.ref || '"]'
11371                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.ref
11372             END;
11373     
11374         holdable :=
11375             CASE
11376                 WHEN attr_def.holdable IS NULL THEN 'null()'
11377                 WHEN LENGTH( attr_def.holdable ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.holdable || '"]'
11378                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.holdable
11379             END;
11380     
11381         price :=
11382             CASE
11383                 WHEN attr_def.price IS NULL THEN 'null()'
11384                 WHEN LENGTH( attr_def.price ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.price || '"]'
11385                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.price
11386             END;
11387     
11388         barcode :=
11389             CASE
11390                 WHEN attr_def.barcode IS NULL THEN 'null()'
11391                 WHEN LENGTH( attr_def.barcode ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.barcode || '"]'
11392                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.barcode
11393             END;
11394     
11395         circ_modifier :=
11396             CASE
11397                 WHEN attr_def.circ_modifier IS NULL THEN 'null()'
11398                 WHEN LENGTH( attr_def.circ_modifier ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_modifier || '"]'
11399                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_modifier
11400             END;
11401     
11402         circ_as_type :=
11403             CASE
11404                 WHEN attr_def.circ_as_type IS NULL THEN 'null()'
11405                 WHEN LENGTH( attr_def.circ_as_type ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_as_type || '"]'
11406                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_as_type
11407             END;
11408     
11409         alert_message :=
11410             CASE
11411                 WHEN attr_def.alert_message IS NULL THEN 'null()'
11412                 WHEN LENGTH( attr_def.alert_message ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.alert_message || '"]'
11413                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.alert_message
11414             END;
11415     
11416         opac_visible :=
11417             CASE
11418                 WHEN attr_def.opac_visible IS NULL THEN 'null()'
11419                 WHEN LENGTH( attr_def.opac_visible ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.opac_visible || '"]'
11420                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.opac_visible
11421             END;
11422
11423         pub_note :=
11424             CASE
11425                 WHEN attr_def.pub_note IS NULL THEN 'null()'
11426                 WHEN LENGTH( attr_def.pub_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.pub_note || '"]'
11427                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.pub_note
11428             END;
11429         priv_note :=
11430             CASE
11431                 WHEN attr_def.priv_note IS NULL THEN 'null()'
11432                 WHEN LENGTH( attr_def.priv_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.priv_note || '"]'
11433                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.priv_note
11434             END;
11435     
11436     
11437         xpath := 
11438             owning_lib      || '|' || 
11439             circ_lib        || '|' || 
11440             call_number     || '|' || 
11441             copy_number     || '|' || 
11442             status          || '|' || 
11443             location        || '|' || 
11444             circulate       || '|' || 
11445             deposit         || '|' || 
11446             deposit_amount  || '|' || 
11447             ref             || '|' || 
11448             holdable        || '|' || 
11449             price           || '|' || 
11450             barcode         || '|' || 
11451             circ_modifier   || '|' || 
11452             circ_as_type    || '|' || 
11453             alert_message   || '|' || 
11454             pub_note        || '|' || 
11455             priv_note       || '|' || 
11456             opac_visible;
11457
11458         -- RAISE NOTICE 'XPath: %', xpath;
11459         
11460         FOR tmp_attr_set IN
11461                 SELECT  *
11462                   FROM  oils_xpath_table( 'id', 'marc', 'vandelay.queued_bib_record', xpath, 'id = ' || import_id )
11463                             AS t( id INT, ol TEXT, clib TEXT, cn TEXT, cnum TEXT, cs TEXT, cl TEXT, circ TEXT,
11464                                   dep TEXT, dep_amount TEXT, r TEXT, hold TEXT, pr TEXT, bc TEXT, circ_mod TEXT,
11465                                   circ_as TEXT, amessage TEXT, note TEXT, pnote TEXT, opac_vis TEXT )
11466         LOOP
11467     
11468             tmp_attr_set.pr = REGEXP_REPLACE(tmp_attr_set.pr, E'[^0-9\\.]', '', 'g');
11469             tmp_attr_set.dep_amount = REGEXP_REPLACE(tmp_attr_set.dep_amount, E'[^0-9\\.]', '', 'g');
11470
11471             tmp_attr_set.pr := NULLIF( tmp_attr_set.pr, '' );
11472             tmp_attr_set.dep_amount := NULLIF( tmp_attr_set.dep_amount, '' );
11473     
11474             SELECT id INTO attr_set.owning_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.ol); -- INT
11475             SELECT id INTO attr_set.circ_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.clib); -- INT
11476             SELECT id INTO attr_set.status FROM config.copy_status WHERE LOWER(name) = LOWER(tmp_attr_set.cs); -- INT
11477     
11478             SELECT  id INTO attr_set.location
11479               FROM  asset.copy_location
11480               WHERE LOWER(name) = LOWER(tmp_attr_set.cl)
11481                     AND asset.copy_location.owning_lib = COALESCE(attr_set.owning_lib, attr_set.circ_lib); -- INT
11482     
11483             attr_set.circulate      :=
11484                 LOWER( SUBSTRING( tmp_attr_set.circ, 1, 1)) IN ('t','y','1')
11485                 OR LOWER(tmp_attr_set.circ) = 'circulating'; -- BOOL
11486
11487             attr_set.deposit        :=
11488                 LOWER( SUBSTRING( tmp_attr_set.dep, 1, 1 ) ) IN ('t','y','1')
11489                 OR LOWER(tmp_attr_set.dep) = 'deposit'; -- BOOL
11490
11491             attr_set.holdable       :=
11492                 LOWER( SUBSTRING( tmp_attr_set.hold, 1, 1 ) ) IN ('t','y','1')
11493                 OR LOWER(tmp_attr_set.hold) = 'holdable'; -- BOOL
11494
11495             attr_set.opac_visible   :=
11496                 LOWER( SUBSTRING( tmp_attr_set.opac_vis, 1, 1 ) ) IN ('t','y','1')
11497                 OR LOWER(tmp_attr_set.opac_vis) = 'visible'; -- BOOL
11498
11499             attr_set.ref            :=
11500                 LOWER( SUBSTRING( tmp_attr_set.r, 1, 1 ) ) IN ('t','y','1')
11501                 OR LOWER(tmp_attr_set.r) = 'reference'; -- BOOL
11502     
11503             attr_set.copy_number    := tmp_attr_set.cnum::INT; -- INT,
11504             attr_set.deposit_amount := tmp_attr_set.dep_amount::NUMERIC(6,2); -- NUMERIC(6,2),
11505             attr_set.price          := tmp_attr_set.pr::NUMERIC(8,2); -- NUMERIC(8,2),
11506     
11507             attr_set.call_number    := tmp_attr_set.cn; -- TEXT
11508             attr_set.barcode        := tmp_attr_set.bc; -- TEXT,
11509             attr_set.circ_modifier  := tmp_attr_set.circ_mod; -- TEXT,
11510             attr_set.circ_as_type   := tmp_attr_set.circ_as; -- TEXT,
11511             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
11512             attr_set.pub_note       := tmp_attr_set.note; -- TEXT,
11513             attr_set.priv_note      := tmp_attr_set.pnote; -- TEXT,
11514             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
11515     
11516             RETURN NEXT attr_set;
11517     
11518         END LOOP;
11519     
11520     END IF;
11521
11522     RETURN;
11523
11524 END;
11525 $$ LANGUAGE PLPGSQL;
11526
11527 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_items ( ) RETURNS TRIGGER AS $func$
11528 DECLARE
11529     attr_def    BIGINT;
11530     item_data   vandelay.import_item%ROWTYPE;
11531 BEGIN
11532
11533     SELECT item_attr_def INTO attr_def FROM vandelay.bib_queue WHERE id = NEW.queue;
11534
11535     FOR item_data IN SELECT * FROM vandelay.ingest_items( NEW.id::BIGINT, attr_def ) LOOP
11536         INSERT INTO vandelay.import_item (
11537             record,
11538             definition,
11539             owning_lib,
11540             circ_lib,
11541             call_number,
11542             copy_number,
11543             status,
11544             location,
11545             circulate,
11546             deposit,
11547             deposit_amount,
11548             ref,
11549             holdable,
11550             price,
11551             barcode,
11552             circ_modifier,
11553             circ_as_type,
11554             alert_message,
11555             pub_note,
11556             priv_note,
11557             opac_visible
11558         ) VALUES (
11559             NEW.id,
11560             item_data.definition,
11561             item_data.owning_lib,
11562             item_data.circ_lib,
11563             item_data.call_number,
11564             item_data.copy_number,
11565             item_data.status,
11566             item_data.location,
11567             item_data.circulate,
11568             item_data.deposit,
11569             item_data.deposit_amount,
11570             item_data.ref,
11571             item_data.holdable,
11572             item_data.price,
11573             item_data.barcode,
11574             item_data.circ_modifier,
11575             item_data.circ_as_type,
11576             item_data.alert_message,
11577             item_data.pub_note,
11578             item_data.priv_note,
11579             item_data.opac_visible
11580         );
11581     END LOOP;
11582
11583     RETURN NULL;
11584 END;
11585 $func$ LANGUAGE PLPGSQL;
11586
11587 CREATE OR REPLACE FUNCTION acq.create_acq_seq     ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
11588 BEGIN
11589     EXECUTE $$
11590         CREATE SEQUENCE acq.$$ || sch || $$_$$ || tbl || $$_pkey_seq;
11591     $$;
11592         RETURN TRUE;
11593 END;
11594 $creator$ LANGUAGE 'plpgsql';
11595
11596 CREATE OR REPLACE FUNCTION acq.create_acq_history ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
11597 BEGIN
11598     EXECUTE $$
11599         CREATE TABLE acq.$$ || sch || $$_$$ || tbl || $$_history (
11600             audit_id    BIGINT                          PRIMARY KEY,
11601             audit_time  TIMESTAMP WITH TIME ZONE        NOT NULL,
11602             audit_action        TEXT                            NOT NULL,
11603             LIKE $$ || sch || $$.$$ || tbl || $$
11604         );
11605     $$;
11606         RETURN TRUE;
11607 END;
11608 $creator$ LANGUAGE 'plpgsql';
11609
11610 CREATE OR REPLACE FUNCTION acq.create_acq_func    ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
11611 BEGIN
11612     EXECUTE $$
11613         CREATE OR REPLACE FUNCTION acq.audit_$$ || sch || $$_$$ || tbl || $$_func ()
11614         RETURNS TRIGGER AS $func$
11615         BEGIN
11616             INSERT INTO acq.$$ || sch || $$_$$ || tbl || $$_history
11617                 SELECT  nextval('acq.$$ || sch || $$_$$ || tbl || $$_pkey_seq'),
11618                     now(),
11619                     SUBSTR(TG_OP,1,1),
11620                     OLD.*;
11621             RETURN NULL;
11622         END;
11623         $func$ LANGUAGE 'plpgsql';
11624     $$;
11625         RETURN TRUE;
11626 END;
11627 $creator$ LANGUAGE 'plpgsql';
11628
11629 CREATE OR REPLACE FUNCTION acq.create_acq_update_trigger ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
11630 BEGIN
11631     EXECUTE $$
11632         CREATE TRIGGER audit_$$ || sch || $$_$$ || tbl || $$_update_trigger
11633             AFTER UPDATE OR DELETE ON $$ || sch || $$.$$ || tbl || $$ FOR EACH ROW
11634             EXECUTE PROCEDURE acq.audit_$$ || sch || $$_$$ || tbl || $$_func ();
11635     $$;
11636         RETURN TRUE;
11637 END;
11638 $creator$ LANGUAGE 'plpgsql';
11639
11640 CREATE OR REPLACE FUNCTION acq.create_acq_lifecycle     ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
11641 BEGIN
11642     EXECUTE $$
11643         CREATE OR REPLACE VIEW acq.$$ || sch || $$_$$ || tbl || $$_lifecycle AS
11644             SELECT      -1, now() as audit_time, '-' as audit_action, *
11645               FROM      $$ || sch || $$.$$ || tbl || $$
11646                 UNION ALL
11647             SELECT      *
11648               FROM      acq.$$ || sch || $$_$$ || tbl || $$_history;
11649     $$;
11650         RETURN TRUE;
11651 END;
11652 $creator$ LANGUAGE 'plpgsql';
11653
11654 -- The main event
11655
11656 CREATE OR REPLACE FUNCTION acq.create_acq_auditor ( sch TEXT, tbl TEXT ) RETURNS BOOL AS $creator$
11657 BEGIN
11658     PERFORM acq.create_acq_seq(sch, tbl);
11659     PERFORM acq.create_acq_history(sch, tbl);
11660     PERFORM acq.create_acq_func(sch, tbl);
11661     PERFORM acq.create_acq_update_trigger(sch, tbl);
11662     PERFORM acq.create_acq_lifecycle(sch, tbl);
11663     RETURN TRUE;
11664 END;
11665 $creator$ LANGUAGE 'plpgsql';
11666
11667 ALTER TABLE acq.lineitem DROP COLUMN item_count;
11668
11669 CREATE OR REPLACE VIEW acq.fund_debit_total AS
11670     SELECT  fund.id AS fund,
11671             fund_debit.encumbrance AS encumbrance,
11672             SUM( COALESCE( fund_debit.amount, 0 ) ) AS amount
11673       FROM acq.fund AS fund
11674                         LEFT JOIN acq.fund_debit AS fund_debit
11675                                 ON ( fund.id = fund_debit.fund )
11676       GROUP BY 1,2;
11677
11678 CREATE TABLE acq.debit_attribution (
11679         id                     INT         NOT NULL PRIMARY KEY,
11680         fund_debit             INT         NOT NULL
11681                                            REFERENCES acq.fund_debit
11682                                            DEFERRABLE INITIALLY DEFERRED,
11683     debit_amount           NUMERIC     NOT NULL,
11684         funding_source_credit  INT         REFERENCES acq.funding_source_credit
11685                                            DEFERRABLE INITIALLY DEFERRED,
11686     credit_amount          NUMERIC
11687 );
11688
11689 CREATE INDEX acq_attribution_debit_idx
11690         ON acq.debit_attribution( fund_debit );
11691
11692 CREATE INDEX acq_attribution_credit_idx
11693         ON acq.debit_attribution( funding_source_credit );
11694
11695 CREATE OR REPLACE FUNCTION acq.attribute_debits() RETURNS VOID AS $$
11696 /*
11697 Function to attribute expenditures and encumbrances to funding source credits,
11698 and thereby to funding sources.
11699
11700 Read the debits in chonological order, attributing each one to one or
11701 more funding source credits.  Constraints:
11702
11703 1. Don't attribute more to a credit than the amount of the credit.
11704
11705 2. For a given fund, don't attribute more to a funding source than the
11706 source has allocated to that fund.
11707
11708 3. Attribute debits to credits with deadlines before attributing them to
11709 credits without deadlines.  Otherwise attribute to the earliest credits
11710 first, based on the deadline date when present, or on the effective date
11711 when there is no deadline.  Use funding_source_credit.id as a tie-breaker.
11712 This ordering is defined by an ORDER BY clause on the view
11713 acq.ordered_funding_source_credit.
11714
11715 Start by truncating the table acq.debit_attribution.  Then insert a row
11716 into that table for each attribution.  If a debit cannot be fully
11717 attributed, insert a row for the unattributable balance, with the 
11718 funding_source_credit and credit_amount columns NULL.
11719 */
11720 DECLARE
11721         curr_fund_source_bal RECORD;
11722         seqno                INT;     -- sequence num for credits applicable to a fund
11723         fund_credit          RECORD;  -- current row in temp t_fund_credit table
11724         fc                   RECORD;  -- used for loading t_fund_credit table
11725         sc                   RECORD;  -- used for loading t_fund_credit table
11726         --
11727         -- Used exclusively in the main loop:
11728         --
11729         deb                 RECORD;   -- current row from acq.fund_debit table
11730         curr_credit_bal     RECORD;   -- current row from temp t_credit table
11731         debit_balance       NUMERIC;  -- amount left to attribute for current debit
11732         conv_debit_balance  NUMERIC;  -- debit balance in currency of the fund
11733         attr_amount         NUMERIC;  -- amount being attributed, in currency of debit
11734         conv_attr_amount    NUMERIC;  -- amount being attributed, in currency of source
11735         conv_cred_balance   NUMERIC;  -- credit_balance in the currency of the fund
11736         conv_alloc_balance  NUMERIC;  -- allocated balance in the currency of the fund
11737         attrib_count        INT;      -- populates id of acq.debit_attribution
11738 BEGIN
11739         --
11740         -- Load a temporary table.  For each combination of fund and funding source,
11741         -- load an entry with the total amount allocated to that fund by that source.
11742         -- This sum may reflect transfers as well as original allocations.  We will
11743         -- reduce this balance whenever we attribute debits to it.
11744         --
11745         CREATE TEMP TABLE t_fund_source_bal
11746         ON COMMIT DROP AS
11747                 SELECT
11748                         fund AS fund,
11749                         funding_source AS source,
11750                         sum( amount ) AS balance
11751                 FROM
11752                         acq.fund_allocation
11753                 GROUP BY
11754                         fund,
11755                         funding_source
11756                 HAVING
11757                         sum( amount ) > 0;
11758         --
11759         CREATE INDEX t_fund_source_bal_idx
11760                 ON t_fund_source_bal( fund, source );
11761         -------------------------------------------------------------------------------
11762         --
11763         -- Load another temporary table.  For each fund, load zero or more
11764         -- funding source credits from which that fund can get money.
11765         --
11766         CREATE TEMP TABLE t_fund_credit (
11767                 fund        INT,
11768                 seq         INT,
11769                 credit      INT
11770         ) ON COMMIT DROP;
11771         --
11772         FOR fc IN
11773                 SELECT DISTINCT fund
11774                 FROM acq.fund_allocation
11775                 ORDER BY fund
11776         LOOP                  -- Loop over the funds
11777                 seqno := 1;
11778                 FOR sc IN
11779                         SELECT
11780                                 ofsc.id
11781                         FROM
11782                                 acq.ordered_funding_source_credit AS ofsc
11783                         WHERE
11784                                 ofsc.funding_source IN
11785                                 (
11786                                         SELECT funding_source
11787                                         FROM acq.fund_allocation
11788                                         WHERE fund = fc.fund
11789                                 )
11790                 ORDER BY
11791                     ofsc.sort_priority,
11792                     ofsc.sort_date,
11793                     ofsc.id
11794                 LOOP                        -- Add each credit to the list
11795                         INSERT INTO t_fund_credit (
11796                                 fund,
11797                                 seq,
11798                                 credit
11799                         ) VALUES (
11800                                 fc.fund,
11801                                 seqno,
11802                                 sc.id
11803                         );
11804                         --RAISE NOTICE 'Fund % credit %', fc.fund, sc.id;
11805                         seqno := seqno + 1;
11806                 END LOOP;     -- Loop over credits for a given fund
11807         END LOOP;         -- Loop over funds
11808         --
11809         CREATE INDEX t_fund_credit_idx
11810                 ON t_fund_credit( fund, seq );
11811         -------------------------------------------------------------------------------
11812         --
11813         -- Load yet another temporary table.  This one is a list of funding source
11814         -- credits, with their balances.  We shall reduce those balances as we
11815         -- attribute debits to them.
11816         --
11817         CREATE TEMP TABLE t_credit
11818         ON COMMIT DROP AS
11819         SELECT
11820             fsc.id AS credit,
11821             fsc.funding_source AS source,
11822             fsc.amount AS balance,
11823             fs.currency_type AS currency_type
11824         FROM
11825             acq.funding_source_credit AS fsc,
11826             acq.funding_source fs
11827         WHERE
11828             fsc.funding_source = fs.id
11829                         AND fsc.amount > 0;
11830         --
11831         CREATE INDEX t_credit_idx
11832                 ON t_credit( credit );
11833         --
11834         -------------------------------------------------------------------------------
11835         --
11836         -- Now that we have loaded the lookup tables: loop through the debits,
11837         -- attributing each one to one or more funding source credits.
11838         -- 
11839         truncate table acq.debit_attribution;
11840         --
11841         attrib_count := 0;
11842         FOR deb in
11843                 SELECT
11844                         fd.id,
11845                         fd.fund,
11846                         fd.amount,
11847                         f.currency_type,
11848                         fd.encumbrance
11849                 FROM
11850                         acq.fund_debit fd,
11851                         acq.fund f
11852                 WHERE
11853                         fd.fund = f.id
11854                 ORDER BY
11855                         fd.id
11856         LOOP
11857                 --RAISE NOTICE 'Debit %, fund %', deb.id, deb.fund;
11858                 --
11859                 debit_balance := deb.amount;
11860                 --
11861                 -- Loop over the funding source credits that are eligible
11862                 -- to pay for this debit
11863                 --
11864                 FOR fund_credit IN
11865                         SELECT
11866                                 credit
11867                         FROM
11868                                 t_fund_credit
11869                         WHERE
11870                                 fund = deb.fund
11871                         ORDER BY
11872                                 seq
11873                 LOOP
11874                         --RAISE NOTICE '   Examining credit %', fund_credit.credit;
11875                         --
11876                         -- Look up the balance for this credit.  If it's zero, then
11877                         -- it's not useful, so treat it as if you didn't find it.
11878                         -- (Actually there shouldn't be any zero balances in the table,
11879                         -- but we check just to make sure.)
11880                         --
11881                         SELECT *
11882                         INTO curr_credit_bal
11883                         FROM t_credit
11884                         WHERE
11885                                 credit = fund_credit.credit
11886                                 AND balance > 0;
11887                         --
11888                         IF curr_credit_bal IS NULL THEN
11889                                 --
11890                                 -- This credit is exhausted; try the next one.
11891                                 --
11892                                 CONTINUE;
11893                         END IF;
11894                         --
11895                         --
11896                         -- At this point we have an applicable credit with some money left.
11897                         -- Now see if the relevant funding_source has any money left.
11898                         --
11899                         -- Look up the balance of the allocation for this combination of
11900                         -- fund and source.  If you find such an entry, but it has a zero
11901                         -- balance, then it's not useful, so treat it as unfound.
11902                         -- (Actually there shouldn't be any zero balances in the table,
11903                         -- but we check just to make sure.)
11904                         --
11905                         SELECT *
11906                         INTO curr_fund_source_bal
11907                         FROM t_fund_source_bal
11908                         WHERE
11909                                 fund = deb.fund
11910                                 AND source = curr_credit_bal.source
11911                                 AND balance > 0;
11912                         --
11913                         IF curr_fund_source_bal IS NULL THEN
11914                                 --
11915                                 -- This fund/source doesn't exist or is already exhausted,
11916                                 -- so we can't use this credit.  Go on to the next one.
11917                                 --
11918                                 CONTINUE;
11919                         END IF;
11920                         --
11921                         -- Convert the available balances to the currency of the fund
11922                         --
11923                         conv_alloc_balance := curr_fund_source_bal.balance * acq.exchange_ratio(
11924                                 curr_credit_bal.currency_type, deb.currency_type );
11925                         conv_cred_balance := curr_credit_bal.balance * acq.exchange_ratio(
11926                                 curr_credit_bal.currency_type, deb.currency_type );
11927                         --
11928                         -- Determine how much we can attribute to this credit: the minimum
11929                         -- of the debit amount, the fund/source balance, and the
11930                         -- credit balance
11931                         --
11932                         --RAISE NOTICE '   deb bal %', debit_balance;
11933                         --RAISE NOTICE '      source % balance %', curr_credit_bal.source, conv_alloc_balance;
11934                         --RAISE NOTICE '      credit % balance %', curr_credit_bal.credit, conv_cred_balance;
11935                         --
11936                         conv_attr_amount := NULL;
11937                         attr_amount := debit_balance;
11938                         --
11939                         IF attr_amount > conv_alloc_balance THEN
11940                                 attr_amount := conv_alloc_balance;
11941                                 conv_attr_amount := curr_fund_source_bal.balance;
11942                         END IF;
11943                         IF attr_amount > conv_cred_balance THEN
11944                                 attr_amount := conv_cred_balance;
11945                                 conv_attr_amount := curr_credit_bal.balance;
11946                         END IF;
11947                         --
11948                         -- If we're attributing all of one of the balances, then that's how
11949                         -- much we will deduct from the balances, and we already captured
11950                         -- that amount above.  Otherwise we must convert the amount of the
11951                         -- attribution from the currency of the fund back to the currency of
11952                         -- the funding source.
11953                         --
11954                         IF conv_attr_amount IS NULL THEN
11955                                 conv_attr_amount := attr_amount * acq.exchange_ratio(
11956                                         deb.currency_type, curr_credit_bal.currency_type );
11957                         END IF;
11958                         --
11959                         -- Insert a row to record the attribution
11960                         --
11961                         attrib_count := attrib_count + 1;
11962                         INSERT INTO acq.debit_attribution (
11963                                 id,
11964                                 fund_debit,
11965                                 debit_amount,
11966                                 funding_source_credit,
11967                                 credit_amount
11968                         ) VALUES (
11969                                 attrib_count,
11970                                 deb.id,
11971                                 attr_amount,
11972                                 curr_credit_bal.credit,
11973                                 conv_attr_amount
11974                         );
11975                         --
11976                         -- Subtract the attributed amount from the various balances
11977                         --
11978                         debit_balance := debit_balance - attr_amount;
11979                         curr_fund_source_bal.balance := curr_fund_source_bal.balance - conv_attr_amount;
11980                         --
11981                         IF curr_fund_source_bal.balance <= 0 THEN
11982                                 --
11983                                 -- This allocation is exhausted.  Delete it so
11984                                 -- that we don't waste time looking at it again.
11985                                 --
11986                                 DELETE FROM t_fund_source_bal
11987                                 WHERE
11988                                         fund = curr_fund_source_bal.fund
11989                                         AND source = curr_fund_source_bal.source;
11990                         ELSE
11991                                 UPDATE t_fund_source_bal
11992                                 SET balance = balance - conv_attr_amount
11993                                 WHERE
11994                                         fund = curr_fund_source_bal.fund
11995                                         AND source = curr_fund_source_bal.source;
11996                         END IF;
11997                         --
11998                         IF curr_credit_bal.balance <= 0 THEN
11999                                 --
12000                                 -- This funding source credit is exhausted.  Delete it
12001                                 -- so that we don't waste time looking at it again.
12002                                 --
12003                                 --DELETE FROM t_credit
12004                                 --WHERE
12005                                 --      credit = curr_credit_bal.credit;
12006                                 --
12007                                 DELETE FROM t_fund_credit
12008                                 WHERE
12009                                         credit = curr_credit_bal.credit;
12010                         ELSE
12011                                 UPDATE t_credit
12012                                 SET balance = curr_credit_bal.balance
12013                                 WHERE
12014                                         credit = curr_credit_bal.credit;
12015                         END IF;
12016                         --
12017                         -- Are we done with this debit yet?
12018                         --
12019                         IF debit_balance <= 0 THEN
12020                                 EXIT;       -- We've fully attributed this debit; stop looking at credits.
12021                         END IF;
12022                 END LOOP;       -- End loop over credits
12023                 --
12024                 IF debit_balance <> 0 THEN
12025                         --
12026                         -- We weren't able to attribute this debit, or at least not
12027                         -- all of it.  Insert a row for the unattributed balance.
12028                         --
12029                         attrib_count := attrib_count + 1;
12030                         INSERT INTO acq.debit_attribution (
12031                                 id,
12032                                 fund_debit,
12033                                 debit_amount,
12034                                 funding_source_credit,
12035                                 credit_amount
12036                         ) VALUES (
12037                                 attrib_count,
12038                                 deb.id,
12039                                 debit_balance,
12040                                 NULL,
12041                                 NULL
12042                         );
12043                 END IF;
12044         END LOOP;   -- End of loop over debits
12045 END;
12046 $$ LANGUAGE 'plpgsql';
12047
12048 CREATE OR REPLACE FUNCTION extract_marc_field ( TEXT, BIGINT, TEXT, TEXT ) RETURNS TEXT AS $$
12049 DECLARE
12050     query TEXT;
12051     output TEXT;
12052 BEGIN
12053     query := $q$
12054         SELECT  regexp_replace(
12055                     oils_xpath_string(
12056                         $q$ || quote_literal($3) || $q$,
12057                         marc,
12058                         ' '
12059                     ),
12060                     $q$ || quote_literal($4) || $q$,
12061                     '',
12062                     'g')
12063           FROM  $q$ || $1 || $q$
12064           WHERE id = $q$ || $2;
12065
12066     EXECUTE query INTO output;
12067
12068     -- RAISE NOTICE 'query: %, output; %', query, output;
12069
12070     RETURN output;
12071 END;
12072 $$ LANGUAGE PLPGSQL IMMUTABLE;
12073
12074 CREATE OR REPLACE FUNCTION extract_marc_field ( TEXT, BIGINT, TEXT ) RETURNS TEXT AS $$
12075     SELECT extract_marc_field($1,$2,$3,'');
12076 $$ LANGUAGE SQL IMMUTABLE;
12077
12078 CREATE OR REPLACE FUNCTION asset.merge_record_assets( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
12079 DECLARE
12080     moved_objects INT := 0;
12081     source_cn     asset.call_number%ROWTYPE;
12082     target_cn     asset.call_number%ROWTYPE;
12083     metarec       metabib.metarecord%ROWTYPE;
12084     hold          action.hold_request%ROWTYPE;
12085     ser_rec       serial.record_entry%ROWTYPE;
12086     uri_count     INT := 0;
12087     counter       INT := 0;
12088     uri_datafield TEXT;
12089     uri_text      TEXT := '';
12090 BEGIN
12091
12092     -- move any 856 entries on records that have at least one MARC-mapped URI entry
12093     SELECT  INTO uri_count COUNT(*)
12094       FROM  asset.uri_call_number_map m
12095             JOIN asset.call_number cn ON (m.call_number = cn.id)
12096       WHERE cn.record = source_record;
12097
12098     IF uri_count > 0 THEN
12099
12100         SELECT  COUNT(*) INTO counter
12101           FROM  oils_xpath_table(
12102                     'id',
12103                     'marc',
12104                     'biblio.record_entry',
12105                     '//*[@tag="856"]',
12106                     'id=' || source_record
12107                 ) as t(i int,c text);
12108
12109         FOR i IN 1 .. counter LOOP
12110             SELECT  '<datafield xmlns="http://www.loc.gov/MARC21/slim"' ||
12111                         ' tag="856"' || 
12112                         ' ind1="' || FIRST(ind1) || '"'  || 
12113                         ' ind2="' || FIRST(ind2) || '">' || 
12114                         array_to_string(
12115                             array_accum(
12116                                 '<subfield code="' || subfield || '">' ||
12117                                 regexp_replace(
12118                                     regexp_replace(
12119                                         regexp_replace(data,'&','&amp;','g'),
12120                                         '>', '&gt;', 'g'
12121                                     ),
12122                                     '<', '&lt;', 'g'
12123                                 ) || '</subfield>'
12124                             ), ''
12125                         ) || '</datafield>' INTO uri_datafield
12126               FROM  oils_xpath_table(
12127                         'id',
12128                         'marc',
12129                         'biblio.record_entry',
12130                         '//*[@tag="856"][position()=' || i || ']/@ind1|' || 
12131                         '//*[@tag="856"][position()=' || i || ']/@ind2|' || 
12132                         '//*[@tag="856"][position()=' || i || ']/*/@code|' ||
12133                         '//*[@tag="856"][position()=' || i || ']/*[@code]',
12134                         'id=' || source_record
12135                     ) as t(id int,ind1 text, ind2 text,subfield text,data text);
12136
12137             uri_text := uri_text || uri_datafield;
12138         END LOOP;
12139
12140         IF uri_text <> '' THEN
12141             UPDATE  biblio.record_entry
12142               SET   marc = regexp_replace(marc,'(</[^>]*record>)', uri_text || E'\\1')
12143               WHERE id = target_record;
12144         END IF;
12145
12146     END IF;
12147
12148     -- Find and move metarecords to the target record
12149     SELECT  INTO metarec *
12150       FROM  metabib.metarecord
12151       WHERE master_record = source_record;
12152
12153     IF FOUND THEN
12154         UPDATE  metabib.metarecord
12155           SET   master_record = target_record,
12156             mods = NULL
12157           WHERE id = metarec.id;
12158
12159         moved_objects := moved_objects + 1;
12160     END IF;
12161
12162     -- Find call numbers attached to the source ...
12163     FOR source_cn IN SELECT * FROM asset.call_number WHERE record = source_record LOOP
12164
12165         SELECT  INTO target_cn *
12166           FROM  asset.call_number
12167           WHERE label = source_cn.label
12168             AND owning_lib = source_cn.owning_lib
12169             AND record = target_record;
12170
12171         -- ... and if there's a conflicting one on the target ...
12172         IF FOUND THEN
12173
12174             -- ... move the copies to that, and ...
12175             UPDATE  asset.copy
12176               SET   call_number = target_cn.id
12177               WHERE call_number = source_cn.id;
12178
12179             -- ... move V holds to the move-target call number
12180             FOR hold IN SELECT * FROM action.hold_request WHERE target = source_cn.id AND hold_type = 'V' LOOP
12181
12182                 UPDATE  action.hold_request
12183                   SET   target = target_cn.id
12184                   WHERE id = hold.id;
12185
12186                 moved_objects := moved_objects + 1;
12187             END LOOP;
12188
12189         -- ... if not ...
12190         ELSE
12191             -- ... just move the call number to the target record
12192             UPDATE  asset.call_number
12193               SET   record = target_record
12194               WHERE id = source_cn.id;
12195         END IF;
12196
12197         moved_objects := moved_objects + 1;
12198     END LOOP;
12199
12200     -- Find T holds targeting the source record ...
12201     FOR hold IN SELECT * FROM action.hold_request WHERE target = source_record AND hold_type = 'T' LOOP
12202
12203         -- ... and move them to the target record
12204         UPDATE  action.hold_request
12205           SET   target = target_record
12206           WHERE id = hold.id;
12207
12208         moved_objects := moved_objects + 1;
12209     END LOOP;
12210
12211     -- Find serial records targeting the source record ...
12212     FOR ser_rec IN SELECT * FROM serial.record_entry WHERE record = source_record LOOP
12213         -- ... and move them to the target record
12214         UPDATE  serial.record_entry
12215           SET   record = target_record
12216           WHERE id = ser_rec.id;
12217
12218         moved_objects := moved_objects + 1;
12219     END LOOP;
12220
12221     -- Finally, "delete" the source record
12222     DELETE FROM biblio.record_entry WHERE id = source_record;
12223
12224     -- That's all, folks!
12225     RETURN moved_objects;
12226 END;
12227 $func$ LANGUAGE plpgsql;
12228
12229 CREATE OR REPLACE FUNCTION acq.transfer_fund(
12230         old_fund   IN INT,
12231         old_amount IN NUMERIC,     -- in currency of old fund
12232         new_fund   IN INT,
12233         new_amount IN NUMERIC,     -- in currency of new fund
12234         user_id    IN INT,
12235         xfer_note  IN TEXT         -- to be recorded in acq.fund_transfer
12236         -- ,funding_source_in IN INT  -- if user wants to specify a funding source (see notes)
12237 ) RETURNS VOID AS $$
12238 /* -------------------------------------------------------------------------------
12239
12240 Function to transfer money from one fund to another.
12241
12242 A transfer is represented as a pair of entries in acq.fund_allocation, with a
12243 negative amount for the old (losing) fund and a positive amount for the new
12244 (gaining) fund.  In some cases there may be more than one such pair of entries
12245 in order to pull the money from different funding sources, or more specifically
12246 from different funding source credits.  For each such pair there is also an
12247 entry in acq.fund_transfer.
12248
12249 Since funding_source is a non-nullable column in acq.fund_allocation, we must
12250 choose a funding source for the transferred money to come from.  This choice
12251 must meet two constraints, so far as possible:
12252
12253 1. The amount transferred from a given funding source must not exceed the
12254 amount allocated to the old fund by the funding source.  To that end we
12255 compare the amount being transferred to the amount allocated.
12256
12257 2. We shouldn't transfer money that has already been spent or encumbered, as
12258 defined by the funding attribution process.  We attribute expenses to the
12259 oldest funding source credits first.  In order to avoid transferring that
12260 attributed money, we reverse the priority, transferring from the newest funding
12261 source credits first.  There can be no guarantee that this approach will
12262 avoid overcommitting a fund, but no other approach can do any better.
12263
12264 In this context the age of a funding source credit is defined by the
12265 deadline_date for credits with deadline_dates, and by the effective_date for
12266 credits without deadline_dates, with the proviso that credits with deadline_dates
12267 are all considered "older" than those without.
12268
12269 ----------
12270
12271 In the signature for this function, there is one last parameter commented out,
12272 named "funding_source_in".  Correspondingly, the WHERE clause for the query
12273 driving the main loop has an OR clause commented out, which references the
12274 funding_source_in parameter.
12275
12276 If these lines are uncommented, this function will allow the user optionally to
12277 restrict a fund transfer to a specified funding source.  If the source
12278 parameter is left NULL, then there will be no such restriction.
12279
12280 ------------------------------------------------------------------------------- */ 
12281 DECLARE
12282         same_currency      BOOLEAN;
12283         currency_ratio     NUMERIC;
12284         old_fund_currency  TEXT;
12285         old_remaining      NUMERIC;  -- in currency of old fund
12286         new_fund_currency  TEXT;
12287         new_fund_active    BOOLEAN;
12288         new_remaining      NUMERIC;  -- in currency of new fund
12289         curr_old_amt       NUMERIC;  -- in currency of old fund
12290         curr_new_amt       NUMERIC;  -- in currency of new fund
12291         source_addition    NUMERIC;  -- in currency of funding source
12292         source_deduction   NUMERIC;  -- in currency of funding source
12293         orig_allocated_amt NUMERIC;  -- in currency of funding source
12294         allocated_amt      NUMERIC;  -- in currency of fund
12295         source             RECORD;
12296 BEGIN
12297         --
12298         -- Sanity checks
12299         --
12300         IF old_fund IS NULL THEN
12301                 RAISE EXCEPTION 'acq.transfer_fund: old fund id is NULL';
12302         END IF;
12303         --
12304         IF old_amount IS NULL THEN
12305                 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer is NULL';
12306         END IF;
12307         --
12308         -- The new fund and its amount must be both NULL or both not NULL.
12309         --
12310         IF new_fund IS NOT NULL AND new_amount IS NULL THEN
12311                 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer to receiving fund is NULL';
12312         END IF;
12313         --
12314         IF new_fund IS NULL AND new_amount IS NOT NULL THEN
12315                 RAISE EXCEPTION 'acq.transfer_fund: receiving fund is NULL, its amount is not NULL';
12316         END IF;
12317         --
12318         IF user_id IS NULL THEN
12319                 RAISE EXCEPTION 'acq.transfer_fund: user id is NULL';
12320         END IF;
12321         --
12322         -- Initialize the amounts to be transferred, each denominated
12323         -- in the currency of its respective fund.  They will be
12324         -- reduced on each iteration of the loop.
12325         --
12326         old_remaining := old_amount;
12327         new_remaining := new_amount;
12328         --
12329         -- RAISE NOTICE 'Transferring % in fund % to % in fund %',
12330         --      old_amount, old_fund, new_amount, new_fund;
12331         --
12332         -- Get the currency types of the old and new funds.
12333         --
12334         SELECT
12335                 currency_type
12336         INTO
12337                 old_fund_currency
12338         FROM
12339                 acq.fund
12340         WHERE
12341                 id = old_fund;
12342         --
12343         IF old_fund_currency IS NULL THEN
12344                 RAISE EXCEPTION 'acq.transfer_fund: old fund id % is not defined', old_fund;
12345         END IF;
12346         --
12347         IF new_fund IS NOT NULL THEN
12348                 SELECT
12349                         currency_type,
12350                         active
12351                 INTO
12352                         new_fund_currency,
12353                         new_fund_active
12354                 FROM
12355                         acq.fund
12356                 WHERE
12357                         id = new_fund;
12358                 --
12359                 IF new_fund_currency IS NULL THEN
12360                         RAISE EXCEPTION 'acq.transfer_fund: new fund id % is not defined', new_fund;
12361                 ELSIF NOT new_fund_active THEN
12362                         --
12363                         -- No point in putting money into a fund from whence you can't spend it
12364                         --
12365                         RAISE EXCEPTION 'acq.transfer_fund: new fund id % is inactive', new_fund;
12366                 END IF;
12367                 --
12368                 IF new_amount = old_amount THEN
12369                         same_currency := true;
12370                         currency_ratio := 1;
12371                 ELSE
12372                         --
12373                         -- We'll have to translate currency between funds.  We presume that
12374                         -- the calling code has already applied an appropriate exchange rate,
12375                         -- so we'll apply the same conversion to each sub-transfer.
12376                         --
12377                         same_currency := false;
12378                         currency_ratio := new_amount / old_amount;
12379                 END IF;
12380         END IF;
12381         --
12382         -- Identify the funding source(s) from which we want to transfer the money.
12383         -- The principle is that we want to transfer the newest money first, because
12384         -- we spend the oldest money first.  The priority for spending is defined
12385         -- by a sort of the view acq.ordered_funding_source_credit.
12386         --
12387         FOR source in
12388                 SELECT
12389                         ofsc.id,
12390                         ofsc.funding_source,
12391                         ofsc.amount,
12392                         ofsc.amount * acq.exchange_ratio( fs.currency_type, old_fund_currency )
12393                                 AS converted_amt,
12394                         fs.currency_type
12395                 FROM
12396                         acq.ordered_funding_source_credit AS ofsc,
12397                         acq.funding_source fs
12398                 WHERE
12399                         ofsc.funding_source = fs.id
12400                         and ofsc.funding_source IN
12401                         (
12402                                 SELECT funding_source
12403                                 FROM acq.fund_allocation
12404                                 WHERE fund = old_fund
12405                         )
12406                         -- and
12407                         -- (
12408                         --      ofsc.funding_source = funding_source_in
12409                         --      OR funding_source_in IS NULL
12410                         -- )
12411                 ORDER BY
12412                         ofsc.sort_priority desc,
12413                         ofsc.sort_date desc,
12414                         ofsc.id desc
12415         LOOP
12416                 --
12417                 -- Determine how much money the old fund got from this funding source,
12418                 -- denominated in the currency types of the source and of the fund.
12419                 -- This result may reflect transfers from previous iterations.
12420                 --
12421                 SELECT
12422                         COALESCE( sum( amount ), 0 ),
12423                         COALESCE( sum( amount )
12424                                 * acq.exchange_ratio( source.currency_type, old_fund_currency ), 0 )
12425                 INTO
12426                         orig_allocated_amt,     -- in currency of the source
12427                         allocated_amt           -- in currency of the old fund
12428                 FROM
12429                         acq.fund_allocation
12430                 WHERE
12431                         fund = old_fund
12432                         and funding_source = source.funding_source;
12433                 --      
12434                 -- Determine how much to transfer from this credit, in the currency
12435                 -- of the fund.   Begin with the amount remaining to be attributed:
12436                 --
12437                 curr_old_amt := old_remaining;
12438                 --
12439                 -- Can't attribute more than was allocated from the fund:
12440                 --
12441                 IF curr_old_amt > allocated_amt THEN
12442                         curr_old_amt := allocated_amt;
12443                 END IF;
12444                 --
12445                 -- Can't attribute more than the amount of the current credit:
12446                 --
12447                 IF curr_old_amt > source.converted_amt THEN
12448                         curr_old_amt := source.converted_amt;
12449                 END IF;
12450                 --
12451                 curr_old_amt := trunc( curr_old_amt, 2 );
12452                 --
12453                 old_remaining := old_remaining - curr_old_amt;
12454                 --
12455                 -- Determine the amount to be deducted, if any,
12456                 -- from the old allocation.
12457                 --
12458                 IF old_remaining > 0 THEN
12459                         --
12460                         -- In this case we're using the whole allocation, so use that
12461                         -- amount directly instead of applying a currency translation
12462                         -- and thereby inviting round-off errors.
12463                         --
12464                         source_deduction := - orig_allocated_amt;
12465                 ELSE 
12466                         source_deduction := trunc(
12467                                 ( - curr_old_amt ) *
12468                                         acq.exchange_ratio( old_fund_currency, source.currency_type ),
12469                                 2 );
12470                 END IF;
12471                 --
12472                 IF source_deduction <> 0 THEN
12473                         --
12474                         -- Insert negative allocation for old fund in fund_allocation,
12475                         -- converted into the currency of the funding source
12476                         --
12477                         INSERT INTO acq.fund_allocation (
12478                                 funding_source,
12479                                 fund,
12480                                 amount,
12481                                 allocator,
12482                                 note
12483                         ) VALUES (
12484                                 source.funding_source,
12485                                 old_fund,
12486                                 source_deduction,
12487                                 user_id,
12488                                 'Transfer to fund ' || new_fund
12489                         );
12490                 END IF;
12491                 --
12492                 IF new_fund IS NOT NULL THEN
12493                         --
12494                         -- Determine how much to add to the new fund, in
12495                         -- its currency, and how much remains to be added:
12496                         --
12497                         IF same_currency THEN
12498                                 curr_new_amt := curr_old_amt;
12499                         ELSE
12500                                 IF old_remaining = 0 THEN
12501                                         --
12502                                         -- This is the last iteration, so nothing should be left
12503                                         --
12504                                         curr_new_amt := new_remaining;
12505                                         new_remaining := 0;
12506                                 ELSE
12507                                         curr_new_amt := trunc( curr_old_amt * currency_ratio, 2 );
12508                                         new_remaining := new_remaining - curr_new_amt;
12509                                 END IF;
12510                         END IF;
12511                         --
12512                         -- Determine how much to add, if any,
12513                         -- to the new fund's allocation.
12514                         --
12515                         IF old_remaining > 0 THEN
12516                                 --
12517                                 -- In this case we're using the whole allocation, so use that amount
12518                                 -- amount directly instead of applying a currency translation and
12519                                 -- thereby inviting round-off errors.
12520                                 --
12521                                 source_addition := orig_allocated_amt;
12522                         ELSIF source.currency_type = old_fund_currency THEN
12523                                 --
12524                                 -- In this case we don't need a round trip currency translation,
12525                                 -- thereby inviting round-off errors:
12526                                 --
12527                                 source_addition := curr_old_amt;
12528                         ELSE 
12529                                 source_addition := trunc(
12530                                         curr_new_amt *
12531                                                 acq.exchange_ratio( new_fund_currency, source.currency_type ),
12532                                         2 );
12533                         END IF;
12534                         --
12535                         IF source_addition <> 0 THEN
12536                                 --
12537                                 -- Insert positive allocation for new fund in fund_allocation,
12538                                 -- converted to the currency of the founding source
12539                                 --
12540                                 INSERT INTO acq.fund_allocation (
12541                                         funding_source,
12542                                         fund,
12543                                         amount,
12544                                         allocator,
12545                                         note
12546                                 ) VALUES (
12547                                         source.funding_source,
12548                                         new_fund,
12549                                         source_addition,
12550                                         user_id,
12551                                         'Transfer from fund ' || old_fund
12552                                 );
12553                         END IF;
12554                 END IF;
12555                 --
12556                 IF trunc( curr_old_amt, 2 ) <> 0
12557                 OR trunc( curr_new_amt, 2 ) <> 0 THEN
12558                         --
12559                         -- Insert row in fund_transfer, using amounts in the currency of the funds
12560                         --
12561                         INSERT INTO acq.fund_transfer (
12562                                 src_fund,
12563                                 src_amount,
12564                                 dest_fund,
12565                                 dest_amount,
12566                                 transfer_user,
12567                                 note,
12568                                 funding_source_credit
12569                         ) VALUES (
12570                                 old_fund,
12571                                 trunc( curr_old_amt, 2 ),
12572                                 new_fund,
12573                                 trunc( curr_new_amt, 2 ),
12574                                 user_id,
12575                                 xfer_note,
12576                                 source.id
12577                         );
12578                 END IF;
12579                 --
12580                 if old_remaining <= 0 THEN
12581                         EXIT;                   -- Nothing more to be transferred
12582                 END IF;
12583         END LOOP;
12584 END;
12585 $$ LANGUAGE plpgsql;
12586
12587 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_unit(
12588         old_year INTEGER,
12589         user_id INTEGER,
12590         org_unit_id INTEGER
12591 ) RETURNS VOID AS $$
12592 DECLARE
12593 --
12594 new_id      INT;
12595 old_fund    RECORD;
12596 org_found   BOOLEAN;
12597 --
12598 BEGIN
12599         --
12600         -- Sanity checks
12601         --
12602         IF old_year IS NULL THEN
12603                 RAISE EXCEPTION 'Input year argument is NULL';
12604         ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
12605                 RAISE EXCEPTION 'Input year is out of range';
12606         END IF;
12607         --
12608         IF user_id IS NULL THEN
12609                 RAISE EXCEPTION 'Input user id argument is NULL';
12610         END IF;
12611         --
12612         IF org_unit_id IS NULL THEN
12613                 RAISE EXCEPTION 'Org unit id argument is NULL';
12614         ELSE
12615                 SELECT TRUE INTO org_found
12616                 FROM actor.org_unit
12617                 WHERE id = org_unit_id;
12618                 --
12619                 IF org_found IS NULL THEN
12620                         RAISE EXCEPTION 'Org unit id is invalid';
12621                 END IF;
12622         END IF;
12623         --
12624         -- Loop over the applicable funds
12625         --
12626         FOR old_fund in SELECT * FROM acq.fund
12627         WHERE
12628                 year = old_year
12629                 AND propagate
12630                 AND org = org_unit_id
12631         LOOP
12632                 BEGIN
12633                         INSERT INTO acq.fund (
12634                                 org,
12635                                 name,
12636                                 year,
12637                                 currency_type,
12638                                 code,
12639                                 rollover,
12640                                 propagate,
12641                                 balance_warning_percent,
12642                                 balance_stop_percent
12643                         ) VALUES (
12644                                 old_fund.org,
12645                                 old_fund.name,
12646                                 old_year + 1,
12647                                 old_fund.currency_type,
12648                                 old_fund.code,
12649                                 old_fund.rollover,
12650                                 true,
12651                                 old_fund.balance_warning_percent,
12652                                 old_fund.balance_stop_percent
12653                         )
12654                         RETURNING id INTO new_id;
12655                 EXCEPTION
12656                         WHEN unique_violation THEN
12657                                 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
12658                                 CONTINUE;
12659                 END;
12660                 --RAISE NOTICE 'Propagating fund % to fund %',
12661                 --      old_fund.code, new_id;
12662         END LOOP;
12663 END;
12664 $$ LANGUAGE plpgsql;
12665
12666 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_tree(
12667         old_year INTEGER,
12668         user_id INTEGER,
12669         org_unit_id INTEGER
12670 ) RETURNS VOID AS $$
12671 DECLARE
12672 --
12673 new_id      INT;
12674 old_fund    RECORD;
12675 org_found   BOOLEAN;
12676 --
12677 BEGIN
12678         --
12679         -- Sanity checks
12680         --
12681         IF old_year IS NULL THEN
12682                 RAISE EXCEPTION 'Input year argument is NULL';
12683         ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
12684                 RAISE EXCEPTION 'Input year is out of range';
12685         END IF;
12686         --
12687         IF user_id IS NULL THEN
12688                 RAISE EXCEPTION 'Input user id argument is NULL';
12689         END IF;
12690         --
12691         IF org_unit_id IS NULL THEN
12692                 RAISE EXCEPTION 'Org unit id argument is NULL';
12693         ELSE
12694                 SELECT TRUE INTO org_found
12695                 FROM actor.org_unit
12696                 WHERE id = org_unit_id;
12697                 --
12698                 IF org_found IS NULL THEN
12699                         RAISE EXCEPTION 'Org unit id is invalid';
12700                 END IF;
12701         END IF;
12702         --
12703         -- Loop over the applicable funds
12704         --
12705         FOR old_fund in SELECT * FROM acq.fund
12706         WHERE
12707                 year = old_year
12708                 AND propagate
12709                 AND org in (
12710                         SELECT id FROM actor.org_unit_descendants( org_unit_id )
12711                 )
12712         LOOP
12713                 BEGIN
12714                         INSERT INTO acq.fund (
12715                                 org,
12716                                 name,
12717                                 year,
12718                                 currency_type,
12719                                 code,
12720                                 rollover,
12721                                 propagate,
12722                                 balance_warning_percent,
12723                                 balance_stop_percent
12724                         ) VALUES (
12725                                 old_fund.org,
12726                                 old_fund.name,
12727                                 old_year + 1,
12728                                 old_fund.currency_type,
12729                                 old_fund.code,
12730                                 old_fund.rollover,
12731                                 true,
12732                                 old_fund.balance_warning_percent,
12733                                 old_fund.balance_stop_percent
12734                         )
12735                         RETURNING id INTO new_id;
12736                 EXCEPTION
12737                         WHEN unique_violation THEN
12738                                 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
12739                                 CONTINUE;
12740                 END;
12741                 --RAISE NOTICE 'Propagating fund % to fund %',
12742                 --      old_fund.code, new_id;
12743         END LOOP;
12744 END;
12745 $$ LANGUAGE plpgsql;
12746
12747 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_unit(
12748         old_year INTEGER,
12749         user_id INTEGER,
12750         org_unit_id INTEGER
12751 ) RETURNS VOID AS $$
12752 DECLARE
12753 --
12754 new_fund    INT;
12755 new_year    INT := old_year + 1;
12756 org_found   BOOL;
12757 xfer_amount NUMERIC;
12758 roll_fund   RECORD;
12759 deb         RECORD;
12760 detail      RECORD;
12761 --
12762 BEGIN
12763         --
12764         -- Sanity checks
12765         --
12766         IF old_year IS NULL THEN
12767                 RAISE EXCEPTION 'Input year argument is NULL';
12768     ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
12769         RAISE EXCEPTION 'Input year is out of range';
12770         END IF;
12771         --
12772         IF user_id IS NULL THEN
12773                 RAISE EXCEPTION 'Input user id argument is NULL';
12774         END IF;
12775         --
12776         IF org_unit_id IS NULL THEN
12777                 RAISE EXCEPTION 'Org unit id argument is NULL';
12778         ELSE
12779                 --
12780                 -- Validate the org unit
12781                 --
12782                 SELECT TRUE
12783                 INTO org_found
12784                 FROM actor.org_unit
12785                 WHERE id = org_unit_id;
12786                 --
12787                 IF org_found IS NULL THEN
12788                         RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
12789                 END IF;
12790         END IF;
12791         --
12792         -- Loop over the propagable funds to identify the details
12793         -- from the old fund plus the id of the new one, if it exists.
12794         --
12795         FOR roll_fund in
12796         SELECT
12797             oldf.id AS old_fund,
12798             oldf.org,
12799             oldf.name,
12800             oldf.currency_type,
12801             oldf.code,
12802                 oldf.rollover,
12803             newf.id AS new_fund_id
12804         FROM
12805         acq.fund AS oldf
12806         LEFT JOIN acq.fund AS newf
12807                 ON ( oldf.code = newf.code )
12808         WHERE
12809                     oldf.org = org_unit_id
12810                 and oldf.year = old_year
12811                 and oldf.propagate
12812         and newf.year = new_year
12813         LOOP
12814                 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
12815                 --
12816                 IF roll_fund.new_fund_id IS NULL THEN
12817                         --
12818                         -- The old fund hasn't been propagated yet.  Propagate it now.
12819                         --
12820                         INSERT INTO acq.fund (
12821                                 org,
12822                                 name,
12823                                 year,
12824                                 currency_type,
12825                                 code,
12826                                 rollover,
12827                                 propagate,
12828                                 balance_warning_percent,
12829                                 balance_stop_percent
12830                         ) VALUES (
12831                                 roll_fund.org,
12832                                 roll_fund.name,
12833                                 new_year,
12834                                 roll_fund.currency_type,
12835                                 roll_fund.code,
12836                                 true,
12837                                 true,
12838                                 roll_fund.balance_warning_percent,
12839                                 roll_fund.balance_stop_percent
12840                         )
12841                         RETURNING id INTO new_fund;
12842                 ELSE
12843                         new_fund = roll_fund.new_fund_id;
12844                 END IF;
12845                 --
12846                 -- Determine the amount to transfer
12847                 --
12848                 SELECT amount
12849                 INTO xfer_amount
12850                 FROM acq.fund_spent_balance
12851                 WHERE fund = roll_fund.old_fund;
12852                 --
12853                 IF xfer_amount <> 0 THEN
12854                         IF roll_fund.rollover THEN
12855                                 --
12856                                 -- Transfer balance from old fund to new
12857                                 --
12858                                 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
12859                                 --
12860                                 PERFORM acq.transfer_fund(
12861                                         roll_fund.old_fund,
12862                                         xfer_amount,
12863                                         new_fund,
12864                                         xfer_amount,
12865                                         user_id,
12866                                         'Rollover'
12867                                 );
12868                         ELSE
12869                                 --
12870                                 -- Transfer balance from old fund to the void
12871                                 --
12872                                 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
12873                                 --
12874                                 PERFORM acq.transfer_fund(
12875                                         roll_fund.old_fund,
12876                                         xfer_amount,
12877                                         NULL,
12878                                         NULL,
12879                                         user_id,
12880                                         'Rollover'
12881                                 );
12882                         END IF;
12883                 END IF;
12884                 --
12885                 IF roll_fund.rollover THEN
12886                         --
12887                         -- Move any lineitems from the old fund to the new one
12888                         -- where the associated debit is an encumbrance.
12889                         --
12890                         -- Any other tables tying expenditure details to funds should
12891                         -- receive similar treatment.  At this writing there are none.
12892                         --
12893                         UPDATE acq.lineitem_detail
12894                         SET fund = new_fund
12895                         WHERE
12896                         fund = roll_fund.old_fund -- this condition may be redundant
12897                         AND fund_debit in
12898                         (
12899                                 SELECT id
12900                                 FROM acq.fund_debit
12901                                 WHERE
12902                                 fund = roll_fund.old_fund
12903                                 AND encumbrance
12904                         );
12905                         --
12906                         -- Move encumbrance debits from the old fund to the new fund
12907                         --
12908                         UPDATE acq.fund_debit
12909                         SET fund = new_fund
12910                         wHERE
12911                                 fund = roll_fund.old_fund
12912                                 AND encumbrance;
12913                 END IF;
12914                 --
12915                 -- Mark old fund as inactive, now that we've closed it
12916                 --
12917                 UPDATE acq.fund
12918                 SET active = FALSE
12919                 WHERE id = roll_fund.old_fund;
12920         END LOOP;
12921 END;
12922 $$ LANGUAGE plpgsql;
12923
12924 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_tree(
12925         old_year INTEGER,
12926         user_id INTEGER,
12927         org_unit_id INTEGER
12928 ) RETURNS VOID AS $$
12929 DECLARE
12930 --
12931 new_fund    INT;
12932 new_year    INT := old_year + 1;
12933 org_found   BOOL;
12934 xfer_amount NUMERIC;
12935 roll_fund   RECORD;
12936 deb         RECORD;
12937 detail      RECORD;
12938 --
12939 BEGIN
12940         --
12941         -- Sanity checks
12942         --
12943         IF old_year IS NULL THEN
12944                 RAISE EXCEPTION 'Input year argument is NULL';
12945     ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
12946         RAISE EXCEPTION 'Input year is out of range';
12947         END IF;
12948         --
12949         IF user_id IS NULL THEN
12950                 RAISE EXCEPTION 'Input user id argument is NULL';
12951         END IF;
12952         --
12953         IF org_unit_id IS NULL THEN
12954                 RAISE EXCEPTION 'Org unit id argument is NULL';
12955         ELSE
12956                 --
12957                 -- Validate the org unit
12958                 --
12959                 SELECT TRUE
12960                 INTO org_found
12961                 FROM actor.org_unit
12962                 WHERE id = org_unit_id;
12963                 --
12964                 IF org_found IS NULL THEN
12965                         RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
12966                 END IF;
12967         END IF;
12968         --
12969         -- Loop over the propagable funds to identify the details
12970         -- from the old fund plus the id of the new one, if it exists.
12971         --
12972         FOR roll_fund in
12973         SELECT
12974             oldf.id AS old_fund,
12975             oldf.org,
12976             oldf.name,
12977             oldf.currency_type,
12978             oldf.code,
12979                 oldf.rollover,
12980             newf.id AS new_fund_id
12981         FROM
12982         acq.fund AS oldf
12983         LEFT JOIN acq.fund AS newf
12984                 ON ( oldf.code = newf.code )
12985         WHERE
12986                     oldf.year = old_year
12987                 AND oldf.propagate
12988         AND newf.year = new_year
12989                 AND oldf.org in (
12990                         SELECT id FROM actor.org_unit_descendants( org_unit_id )
12991                 )
12992         LOOP
12993                 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
12994                 --
12995                 IF roll_fund.new_fund_id IS NULL THEN
12996                         --
12997                         -- The old fund hasn't been propagated yet.  Propagate it now.
12998                         --
12999                         INSERT INTO acq.fund (
13000                                 org,
13001                                 name,
13002                                 year,
13003                                 currency_type,
13004                                 code,
13005                                 rollover,
13006                                 propagate,
13007                                 balance_warning_percent,
13008                                 balance_stop_percent
13009                         ) VALUES (
13010                                 roll_fund.org,
13011                                 roll_fund.name,
13012                                 new_year,
13013                                 roll_fund.currency_type,
13014                                 roll_fund.code,
13015                                 true,
13016                                 true,
13017                                 roll_fund.balance_warning_percent,
13018                                 roll_fund.balance_stop_percent
13019                         )
13020                         RETURNING id INTO new_fund;
13021                 ELSE
13022                         new_fund = roll_fund.new_fund_id;
13023                 END IF;
13024                 --
13025                 -- Determine the amount to transfer
13026                 --
13027                 SELECT amount
13028                 INTO xfer_amount
13029                 FROM acq.fund_spent_balance
13030                 WHERE fund = roll_fund.old_fund;
13031                 --
13032                 IF xfer_amount <> 0 THEN
13033                         IF roll_fund.rollover THEN
13034                                 --
13035                                 -- Transfer balance from old fund to new
13036                                 --
13037                                 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
13038                                 --
13039                                 PERFORM acq.transfer_fund(
13040                                         roll_fund.old_fund,
13041                                         xfer_amount,
13042                                         new_fund,
13043                                         xfer_amount,
13044                                         user_id,
13045                                         'Rollover'
13046                                 );
13047                         ELSE
13048                                 --
13049                                 -- Transfer balance from old fund to the void
13050                                 --
13051                                 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
13052                                 --
13053                                 PERFORM acq.transfer_fund(
13054                                         roll_fund.old_fund,
13055                                         xfer_amount,
13056                                         NULL,
13057                                         NULL,
13058                                         user_id,
13059                                         'Rollover'
13060                                 );
13061                         END IF;
13062                 END IF;
13063                 --
13064                 IF roll_fund.rollover THEN
13065                         --
13066                         -- Move any lineitems from the old fund to the new one
13067                         -- where the associated debit is an encumbrance.
13068                         --
13069                         -- Any other tables tying expenditure details to funds should
13070                         -- receive similar treatment.  At this writing there are none.
13071                         --
13072                         UPDATE acq.lineitem_detail
13073                         SET fund = new_fund
13074                         WHERE
13075                         fund = roll_fund.old_fund -- this condition may be redundant
13076                         AND fund_debit in
13077                         (
13078                                 SELECT id
13079                                 FROM acq.fund_debit
13080                                 WHERE
13081                                 fund = roll_fund.old_fund
13082                                 AND encumbrance
13083                         );
13084                         --
13085                         -- Move encumbrance debits from the old fund to the new fund
13086                         --
13087                         UPDATE acq.fund_debit
13088                         SET fund = new_fund
13089                         wHERE
13090                                 fund = roll_fund.old_fund
13091                                 AND encumbrance;
13092                 END IF;
13093                 --
13094                 -- Mark old fund as inactive, now that we've closed it
13095                 --
13096                 UPDATE acq.fund
13097                 SET active = FALSE
13098                 WHERE id = roll_fund.old_fund;
13099         END LOOP;
13100 END;
13101 $$ LANGUAGE plpgsql;
13102
13103 CREATE OR REPLACE FUNCTION public.remove_commas( TEXT ) RETURNS TEXT AS $$
13104     SELECT regexp_replace($1, ',', '', 'g');
13105 $$ LANGUAGE SQL STRICT IMMUTABLE;
13106
13107 CREATE OR REPLACE FUNCTION public.remove_whitespace( TEXT ) RETURNS TEXT AS $$
13108     SELECT regexp_replace(normalize_space($1), E'\\s+', '', 'g');
13109 $$ LANGUAGE SQL STRICT IMMUTABLE;
13110
13111 CREATE TABLE acq.distribution_formula_application (
13112     id BIGSERIAL PRIMARY KEY,
13113     creator INT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED,
13114     create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
13115     formula INT NOT NULL
13116         REFERENCES acq.distribution_formula(id) DEFERRABLE INITIALLY DEFERRED,
13117     lineitem INT NOT NULL
13118         REFERENCES acq.lineitem( id )
13119                 ON DELETE CASCADE
13120                 DEFERRABLE INITIALLY DEFERRED
13121 );
13122
13123 CREATE INDEX acqdfa_df_idx
13124     ON acq.distribution_formula_application(formula);
13125 CREATE INDEX acqdfa_li_idx
13126     ON acq.distribution_formula_application(lineitem);
13127 CREATE INDEX acqdfa_creator_idx
13128     ON acq.distribution_formula_application(creator);
13129
13130 CREATE TABLE acq.user_request_type (
13131     id      SERIAL  PRIMARY KEY,
13132     label   TEXT    NOT NULL UNIQUE -- i18n-ize
13133 );
13134
13135 INSERT INTO acq.user_request_type (id,label) VALUES (1, oils_i18n_gettext('1', 'Books', 'aurt', 'label'));
13136 INSERT INTO acq.user_request_type (id,label) VALUES (2, oils_i18n_gettext('2', 'Journal/Magazine & Newspaper Articles', 'aurt', 'label'));
13137 INSERT INTO acq.user_request_type (id,label) VALUES (3, oils_i18n_gettext('3', 'Audiobooks', 'aurt', 'label'));
13138 INSERT INTO acq.user_request_type (id,label) VALUES (4, oils_i18n_gettext('4', 'Music', 'aurt', 'label'));
13139 INSERT INTO acq.user_request_type (id,label) VALUES (5, oils_i18n_gettext('5', 'DVDs', 'aurt', 'label'));
13140
13141 SELECT SETVAL('acq.user_request_type_id_seq'::TEXT, 6);
13142
13143 CREATE TABLE acq.cancel_reason (
13144         id            SERIAL            PRIMARY KEY,
13145         org_unit      INTEGER           NOT NULL REFERENCES actor.org_unit( id )
13146                                         DEFERRABLE INITIALLY DEFERRED,
13147         label         TEXT              NOT NULL,
13148         description   TEXT              NOT NULL,
13149         keep_debits   BOOL              NOT NULL DEFAULT FALSE,
13150         CONSTRAINT acq_cancel_reason_one_per_org_unit UNIQUE( org_unit, label )
13151 );
13152
13153 -- Reserve ids 1-999 for stock reasons
13154 -- Reserve ids 1000-1999 for EDI reasons
13155 -- 2000+ are available for staff to create
13156
13157 SELECT SETVAL('acq.cancel_reason_id_seq'::TEXT, 2000);
13158
13159 CREATE TABLE acq.user_request (
13160     id                  SERIAL  PRIMARY KEY,
13161     usr                 INT     NOT NULL REFERENCES actor.usr (id), -- requesting user
13162     hold                BOOL    NOT NULL DEFAULT TRUE,
13163
13164     pickup_lib          INT     NOT NULL REFERENCES actor.org_unit (id), -- pickup lib
13165     holdable_formats    TEXT,           -- nullable, for use in hold creation
13166     phone_notify        TEXT,
13167     email_notify        BOOL    NOT NULL DEFAULT TRUE,
13168     lineitem            INT     REFERENCES acq.lineitem (id) ON DELETE CASCADE,
13169     eg_bib              BIGINT  REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
13170     request_date        TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- when they requested it
13171     need_before         TIMESTAMPTZ,    -- don't create holds after this
13172     max_fee             TEXT,
13173
13174     request_type        INT     NOT NULL REFERENCES acq.user_request_type (id), 
13175     isxn                TEXT,
13176     title               TEXT,
13177     volume              TEXT,
13178     author              TEXT,
13179     article_title       TEXT,
13180     article_pages       TEXT,
13181     publisher           TEXT,
13182     location            TEXT,
13183     pubdate             TEXT,
13184     mentioned           TEXT,
13185     other_info          TEXT,
13186         cancel_reason       INT              REFERENCES acq.cancel_reason( id )
13187                                              DEFERRABLE INITIALLY DEFERRED
13188 );
13189
13190 CREATE TABLE acq.lineitem_alert_text (
13191         id               SERIAL         PRIMARY KEY,
13192         code             TEXT           NOT NULL,
13193         description      TEXT,
13194         owning_lib       INT            NOT NULL
13195                                         REFERENCES actor.org_unit(id)
13196                                         DEFERRABLE INITIALLY DEFERRED,
13197         CONSTRAINT alert_one_code_per_org UNIQUE (code, owning_lib)
13198 );
13199
13200 ALTER TABLE acq.lineitem_note
13201         ADD COLUMN alert_text    INT     REFERENCES acq.lineitem_alert_text(id)
13202                                          DEFERRABLE INITIALLY DEFERRED;
13203
13204 -- add ON DELETE CASCADE clause
13205
13206 ALTER TABLE acq.lineitem_note
13207         DROP CONSTRAINT lineitem_note_lineitem_fkey;
13208
13209 ALTER TABLE acq.lineitem_note
13210         ADD FOREIGN KEY (lineitem) REFERENCES acq.lineitem( id )
13211                 ON DELETE CASCADE
13212                 DEFERRABLE INITIALLY DEFERRED;
13213
13214 ALTER TABLE acq.lineitem_note
13215         ADD COLUMN vendor_public BOOLEAN NOT NULL DEFAULT FALSE;
13216
13217 CREATE TABLE acq.invoice_method (
13218     code    TEXT    PRIMARY KEY,
13219     name    TEXT    NOT NULL -- i18n-ize
13220 );
13221 INSERT INTO acq.invoice_method (code,name) VALUES ('EDI',oils_i18n_gettext('EDI', 'EDI', 'acqim', 'name'));
13222 INSERT INTO acq.invoice_method (code,name) VALUES ('PPR',oils_i18n_gettext('PPR', 'Paper', 'acqit', 'name'));
13223
13224 CREATE TABLE acq.invoice_payment_method (
13225         code      TEXT     PRIMARY KEY,
13226         name      TEXT     NOT NULL
13227 );
13228
13229 CREATE TABLE acq.invoice (
13230     id             SERIAL      PRIMARY KEY,
13231     receiver       INT         NOT NULL REFERENCES actor.org_unit (id),
13232     provider       INT         NOT NULL REFERENCES acq.provider (id),
13233     shipper        INT         NOT NULL REFERENCES acq.provider (id),
13234     recv_date      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
13235     recv_method    TEXT        NOT NULL REFERENCES acq.invoice_method (code) DEFAULT 'EDI',
13236     inv_type       TEXT,       -- A "type" field is desired, but no idea what goes here
13237     inv_ident      TEXT        NOT NULL, -- vendor-supplied invoice id/number
13238         payment_auth   TEXT,
13239         payment_method TEXT        REFERENCES acq.invoice_payment_method (code)
13240                                    DEFERRABLE INITIALLY DEFERRED,
13241         note           TEXT,
13242     complete       BOOL        NOT NULL DEFAULT FALSE,
13243     CONSTRAINT inv_ident_once_per_provider UNIQUE(provider, inv_ident)
13244 );
13245
13246 CREATE TABLE acq.invoice_entry (
13247     id              SERIAL      PRIMARY KEY,
13248     invoice         INT         NOT NULL REFERENCES acq.invoice (id) ON DELETE CASCADE,
13249     purchase_order  INT         REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
13250     lineitem        INT         REFERENCES acq.lineitem (id) ON UPDATE CASCADE ON DELETE SET NULL,
13251     inv_item_count  INT         NOT NULL, -- How many acqlids did they say they sent
13252     phys_item_count INT, -- and how many did staff count
13253     note            TEXT,
13254     billed_per_item BOOL,
13255     cost_billed     NUMERIC(8,2),
13256     actual_cost     NUMERIC(8,2),
13257         amount_paid     NUMERIC (8,2)
13258 );
13259
13260 CREATE TABLE acq.invoice_item_type (
13261     code    TEXT    PRIMARY KEY,
13262     name    TEXT    NOT NULL, -- i18n-ize
13263         prorate BOOL    NOT NULL DEFAULT FALSE
13264 );
13265
13266 INSERT INTO acq.invoice_item_type (code,name) VALUES ('TAX',oils_i18n_gettext('TAX', 'Tax', 'aiit', 'name'));
13267 INSERT INTO acq.invoice_item_type (code,name) VALUES ('PRO',oils_i18n_gettext('PRO', 'Processing Fee', 'aiit', 'name'));
13268 INSERT INTO acq.invoice_item_type (code,name) VALUES ('SHP',oils_i18n_gettext('SHP', 'Shipping Charge', 'aiit', 'name'));
13269 INSERT INTO acq.invoice_item_type (code,name) VALUES ('HND',oils_i18n_gettext('HND', 'Handling Charge', 'aiit', 'name'));
13270 INSERT INTO acq.invoice_item_type (code,name) VALUES ('ITM',oils_i18n_gettext('ITM', 'Non-library Item', 'aiit', 'name'));
13271 INSERT INTO acq.invoice_item_type (code,name) VALUES ('SUB',oils_i18n_gettext('SUB', 'Serial Subscription', 'aiit', 'name'));
13272
13273 CREATE TABLE acq.po_item (
13274         id              SERIAL      PRIMARY KEY,
13275         purchase_order  INT         REFERENCES acq.purchase_order (id)
13276                                     ON UPDATE CASCADE ON DELETE SET NULL
13277                                     DEFERRABLE INITIALLY DEFERRED,
13278         fund_debit      INT         REFERENCES acq.fund_debit (id)
13279                                     DEFERRABLE INITIALLY DEFERRED,
13280         inv_item_type   TEXT        NOT NULL
13281                                     REFERENCES acq.invoice_item_type (code)
13282                                     DEFERRABLE INITIALLY DEFERRED,
13283         title           TEXT,
13284         author          TEXT,
13285         note            TEXT,
13286         estimated_cost  NUMERIC(8,2),
13287         fund            INT         REFERENCES acq.fund (id)
13288                                     DEFERRABLE INITIALLY DEFERRED,
13289         target          BIGINT
13290 );
13291
13292 CREATE TABLE acq.invoice_item ( -- for invoice-only debits: taxes/fees/non-bib items/etc
13293     id              SERIAL      PRIMARY KEY,
13294     invoice         INT         NOT NULL REFERENCES acq.invoice (id) ON UPDATE CASCADE ON DELETE CASCADE,
13295     purchase_order  INT         REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
13296     fund_debit      INT         REFERENCES acq.fund_debit (id),
13297     inv_item_type   TEXT        NOT NULL REFERENCES acq.invoice_item_type (code),
13298     title           TEXT,
13299     author          TEXT,
13300     note            TEXT,
13301     cost_billed     NUMERIC(8,2),
13302     actual_cost     NUMERIC(8,2),
13303     fund            INT         REFERENCES acq.fund (id)
13304                                 DEFERRABLE INITIALLY DEFERRED,
13305     amount_paid     NUMERIC (8,2),
13306     po_item         INT         REFERENCES acq.po_item (id)
13307                                 DEFERRABLE INITIALLY DEFERRED,
13308     target          BIGINT
13309 );
13310
13311 CREATE TABLE acq.edi_message (
13312     id               SERIAL          PRIMARY KEY,
13313     account          INTEGER         REFERENCES acq.edi_account(id)
13314                                      DEFERRABLE INITIALLY DEFERRED,
13315     remote_file      TEXT,
13316     create_time      TIMESTAMPTZ     NOT NULL DEFAULT now(),
13317     translate_time   TIMESTAMPTZ,
13318     process_time     TIMESTAMPTZ,
13319     error_time       TIMESTAMPTZ,
13320     status           TEXT            NOT NULL DEFAULT 'new'
13321                                      CONSTRAINT status_value CHECK
13322                                      ( status IN (
13323                                         'new',          -- needs to be translated
13324                                         'translated',   -- needs to be processed
13325                                         'trans_error',  -- error in translation step
13326                                         'processed',    -- needs to have remote_file deleted
13327                                         'proc_error',   -- error in processing step
13328                                         'delete_error', -- error in deletion
13329                                         'retry',        -- need to retry
13330                                         'complete'      -- done
13331                                      )),
13332     edi              TEXT,
13333     jedi             TEXT,
13334     error            TEXT,
13335     purchase_order   INT             REFERENCES acq.purchase_order
13336                                      DEFERRABLE INITIALLY DEFERRED,
13337     message_type     TEXT            NOT NULL CONSTRAINT valid_message_type
13338                                      CHECK ( message_type IN (
13339                                         'ORDERS',
13340                                         'ORDRSP',
13341                                         'INVOIC',
13342                                         'OSTENQ',
13343                                         'OSTRPT'
13344                                      ))
13345 );
13346
13347 ALTER TABLE actor.org_address ADD COLUMN san TEXT;
13348
13349 ALTER TABLE acq.provider_address
13350         ADD COLUMN fax_phone TEXT;
13351
13352 ALTER TABLE acq.provider_contact_address
13353         ADD COLUMN fax_phone TEXT;
13354
13355 CREATE TABLE acq.provider_note (
13356     id      SERIAL              PRIMARY KEY,
13357     provider    INT             NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
13358     creator     INT             NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
13359     editor      INT             NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
13360     create_time TIMESTAMP WITH TIME ZONE    NOT NULL DEFAULT NOW(),
13361     edit_time   TIMESTAMP WITH TIME ZONE    NOT NULL DEFAULT NOW(),
13362     value       TEXT            NOT NULL
13363 );
13364 CREATE INDEX acq_pro_note_pro_idx      ON acq.provider_note ( provider );
13365 CREATE INDEX acq_pro_note_creator_idx  ON acq.provider_note ( creator );
13366 CREATE INDEX acq_pro_note_editor_idx   ON acq.provider_note ( editor );
13367
13368 -- For each fund: the total allocation from all sources, in the
13369 -- currency of the fund (or 0 if there are no allocations)
13370
13371 CREATE VIEW acq.all_fund_allocation_total AS
13372 SELECT
13373     f.id AS fund,
13374     COALESCE( SUM( a.amount * acq.exchange_ratio(
13375         s.currency_type, f.currency_type))::numeric(100,2), 0 )
13376     AS amount
13377 FROM
13378     acq.fund f
13379         LEFT JOIN acq.fund_allocation a
13380             ON a.fund = f.id
13381         LEFT JOIN acq.funding_source s
13382             ON a.funding_source = s.id
13383 GROUP BY
13384     f.id;
13385
13386 -- For every fund: the total encumbrances (or 0 if none),
13387 -- in the currency of the fund.
13388
13389 CREATE VIEW acq.all_fund_encumbrance_total AS
13390 SELECT
13391         f.id AS fund,
13392         COALESCE( encumb.amount, 0 ) AS amount
13393 FROM
13394         acq.fund AS f
13395                 LEFT JOIN (
13396                         SELECT
13397                                 fund,
13398                                 sum( amount ) AS amount
13399                         FROM
13400                                 acq.fund_debit
13401                         WHERE
13402                                 encumbrance
13403                         GROUP BY fund
13404                 ) AS encumb
13405                         ON f.id = encumb.fund;
13406
13407 -- For every fund: the total spent (or 0 if none),
13408 -- in the currency of the fund.
13409
13410 CREATE VIEW acq.all_fund_spent_total AS
13411 SELECT
13412     f.id AS fund,
13413     COALESCE( spent.amount, 0 ) AS amount
13414 FROM
13415     acq.fund AS f
13416         LEFT JOIN (
13417             SELECT
13418                 fund,
13419                 sum( amount ) AS amount
13420             FROM
13421                 acq.fund_debit
13422             WHERE
13423                 NOT encumbrance
13424             GROUP BY fund
13425         ) AS spent
13426             ON f.id = spent.fund;
13427
13428 -- For each fund: the amount not yet spent, in the currency
13429 -- of the fund.  May include encumbrances.
13430
13431 CREATE VIEW acq.all_fund_spent_balance AS
13432 SELECT
13433         c.fund,
13434         c.amount - d.amount AS amount
13435 FROM acq.all_fund_allocation_total c
13436     LEFT JOIN acq.all_fund_spent_total d USING (fund);
13437
13438 -- For each fund: the amount neither spent nor encumbered,
13439 -- in the currency of the fund
13440
13441 CREATE VIEW acq.all_fund_combined_balance AS
13442 SELECT
13443      a.fund,
13444      a.amount - COALESCE( c.amount, 0 ) AS amount
13445 FROM
13446      acq.all_fund_allocation_total a
13447         LEFT OUTER JOIN (
13448             SELECT
13449                 fund,
13450                 SUM( amount ) AS amount
13451             FROM
13452                 acq.fund_debit
13453             GROUP BY
13454                 fund
13455         ) AS c USING ( fund );
13456
13457 CREATE OR REPLACE FUNCTION actor.usr_merge( src_usr INT, dest_usr INT, del_addrs BOOLEAN, del_cards BOOLEAN, deactivate_cards BOOLEAN ) RETURNS VOID AS $$
13458 DECLARE
13459         suffix TEXT;
13460         bucket_row RECORD;
13461         picklist_row RECORD;
13462         queue_row RECORD;
13463         folder_row RECORD;
13464 BEGIN
13465
13466     -- do some initial cleanup 
13467     UPDATE actor.usr SET card = NULL WHERE id = src_usr;
13468     UPDATE actor.usr SET mailing_address = NULL WHERE id = src_usr;
13469     UPDATE actor.usr SET billing_address = NULL WHERE id = src_usr;
13470
13471     -- actor.*
13472     IF del_cards THEN
13473         DELETE FROM actor.card where usr = src_usr;
13474     ELSE
13475         IF deactivate_cards THEN
13476             UPDATE actor.card SET active = 'f' WHERE usr = src_usr;
13477         END IF;
13478         UPDATE actor.card SET usr = dest_usr WHERE usr = src_usr;
13479     END IF;
13480
13481
13482     IF del_addrs THEN
13483         DELETE FROM actor.usr_address WHERE usr = src_usr;
13484     ELSE
13485         UPDATE actor.usr_address SET usr = dest_usr WHERE usr = src_usr;
13486     END IF;
13487
13488     UPDATE actor.usr_note SET usr = dest_usr WHERE usr = src_usr;
13489     -- dupes are technically OK in actor.usr_standing_penalty, should manually delete them...
13490     UPDATE actor.usr_standing_penalty SET usr = dest_usr WHERE usr = src_usr;
13491     PERFORM actor.usr_merge_rows('actor.usr_org_unit_opt_in', 'usr', src_usr, dest_usr);
13492     PERFORM actor.usr_merge_rows('actor.usr_setting', 'usr', src_usr, dest_usr);
13493
13494     -- permission.*
13495     PERFORM actor.usr_merge_rows('permission.usr_perm_map', 'usr', src_usr, dest_usr);
13496     PERFORM actor.usr_merge_rows('permission.usr_object_perm_map', 'usr', src_usr, dest_usr);
13497     PERFORM actor.usr_merge_rows('permission.usr_grp_map', 'usr', src_usr, dest_usr);
13498     PERFORM actor.usr_merge_rows('permission.usr_work_ou_map', 'usr', src_usr, dest_usr);
13499
13500
13501     -- container.*
13502         
13503         -- For each *_bucket table: transfer every bucket belonging to src_usr
13504         -- into the custody of dest_usr.
13505         --
13506         -- In order to avoid colliding with an existing bucket owned by
13507         -- the destination user, append the source user's id (in parenthesese)
13508         -- to the name.  If you still get a collision, add successive
13509         -- spaces to the name and keep trying until you succeed.
13510         --
13511         FOR bucket_row in
13512                 SELECT id, name
13513                 FROM   container.biblio_record_entry_bucket
13514                 WHERE  owner = src_usr
13515         LOOP
13516                 suffix := ' (' || src_usr || ')';
13517                 LOOP
13518                         BEGIN
13519                                 UPDATE  container.biblio_record_entry_bucket
13520                                 SET     owner = dest_usr, name = name || suffix
13521                                 WHERE   id = bucket_row.id;
13522                         EXCEPTION WHEN unique_violation THEN
13523                                 suffix := suffix || ' ';
13524                                 CONTINUE;
13525                         END;
13526                         EXIT;
13527                 END LOOP;
13528         END LOOP;
13529
13530         FOR bucket_row in
13531                 SELECT id, name
13532                 FROM   container.call_number_bucket
13533                 WHERE  owner = src_usr
13534         LOOP
13535                 suffix := ' (' || src_usr || ')';
13536                 LOOP
13537                         BEGIN
13538                                 UPDATE  container.call_number_bucket
13539                                 SET     owner = dest_usr, name = name || suffix
13540                                 WHERE   id = bucket_row.id;
13541                         EXCEPTION WHEN unique_violation THEN
13542                                 suffix := suffix || ' ';
13543                                 CONTINUE;
13544                         END;
13545                         EXIT;
13546                 END LOOP;
13547         END LOOP;
13548
13549         FOR bucket_row in
13550                 SELECT id, name
13551                 FROM   container.copy_bucket
13552                 WHERE  owner = src_usr
13553         LOOP
13554                 suffix := ' (' || src_usr || ')';
13555                 LOOP
13556                         BEGIN
13557                                 UPDATE  container.copy_bucket
13558                                 SET     owner = dest_usr, name = name || suffix
13559                                 WHERE   id = bucket_row.id;
13560                         EXCEPTION WHEN unique_violation THEN
13561                                 suffix := suffix || ' ';
13562                                 CONTINUE;
13563                         END;
13564                         EXIT;
13565                 END LOOP;
13566         END LOOP;
13567
13568         FOR bucket_row in
13569                 SELECT id, name
13570                 FROM   container.user_bucket
13571                 WHERE  owner = src_usr
13572         LOOP
13573                 suffix := ' (' || src_usr || ')';
13574                 LOOP
13575                         BEGIN
13576                                 UPDATE  container.user_bucket
13577                                 SET     owner = dest_usr, name = name || suffix
13578                                 WHERE   id = bucket_row.id;
13579                         EXCEPTION WHEN unique_violation THEN
13580                                 suffix := suffix || ' ';
13581                                 CONTINUE;
13582                         END;
13583                         EXIT;
13584                 END LOOP;
13585         END LOOP;
13586
13587         UPDATE container.user_bucket_item SET target_user = dest_usr WHERE target_user = src_usr;
13588
13589     -- vandelay.*
13590         -- transfer queues the same way we transfer buckets (see above)
13591         FOR queue_row in
13592                 SELECT id, name
13593                 FROM   vandelay.queue
13594                 WHERE  owner = src_usr
13595         LOOP
13596                 suffix := ' (' || src_usr || ')';
13597                 LOOP
13598                         BEGIN
13599                                 UPDATE  vandelay.queue
13600                                 SET     owner = dest_usr, name = name || suffix
13601                                 WHERE   id = queue_row.id;
13602                         EXCEPTION WHEN unique_violation THEN
13603                                 suffix := suffix || ' ';
13604                                 CONTINUE;
13605                         END;
13606                         EXIT;
13607                 END LOOP;
13608         END LOOP;
13609
13610     -- money.*
13611     PERFORM actor.usr_merge_rows('money.collections_tracker', 'usr', src_usr, dest_usr);
13612     PERFORM actor.usr_merge_rows('money.collections_tracker', 'collector', src_usr, dest_usr);
13613     UPDATE money.billable_xact SET usr = dest_usr WHERE usr = src_usr;
13614     UPDATE money.billing SET voider = dest_usr WHERE voider = src_usr;
13615     UPDATE money.bnm_payment SET accepting_usr = dest_usr WHERE accepting_usr = src_usr;
13616
13617     -- action.*
13618     UPDATE action.circulation SET usr = dest_usr WHERE usr = src_usr;
13619     UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
13620     UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
13621
13622     UPDATE action.hold_request SET usr = dest_usr WHERE usr = src_usr;
13623     UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
13624     UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
13625     UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
13626
13627     UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
13628     UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
13629     UPDATE action.non_cataloged_circulation SET patron = dest_usr WHERE patron = src_usr;
13630     UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
13631     UPDATE action.survey_response SET usr = dest_usr WHERE usr = src_usr;
13632
13633     -- acq.*
13634     UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
13635         UPDATE acq.fund_transfer SET transfer_user = dest_usr WHERE transfer_user = src_usr;
13636
13637         -- transfer picklists the same way we transfer buckets (see above)
13638         FOR picklist_row in
13639                 SELECT id, name
13640                 FROM   acq.picklist
13641                 WHERE  owner = src_usr
13642         LOOP
13643                 suffix := ' (' || src_usr || ')';
13644                 LOOP
13645                         BEGIN
13646                                 UPDATE  acq.picklist
13647                                 SET     owner = dest_usr, name = name || suffix
13648                                 WHERE   id = picklist_row.id;
13649                         EXCEPTION WHEN unique_violation THEN
13650                                 suffix := suffix || ' ';
13651                                 CONTINUE;
13652                         END;
13653                         EXIT;
13654                 END LOOP;
13655         END LOOP;
13656
13657     UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
13658     UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
13659     UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
13660     UPDATE acq.provider_note SET creator = dest_usr WHERE creator = src_usr;
13661     UPDATE acq.provider_note SET editor = dest_usr WHERE editor = src_usr;
13662     UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
13663     UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
13664     UPDATE acq.lineitem_usr_attr_definition SET usr = dest_usr WHERE usr = src_usr;
13665
13666     -- asset.*
13667     UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
13668     UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
13669     UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
13670     UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
13671     UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
13672     UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
13673
13674     -- serial.*
13675     UPDATE serial.record_entry SET creator = dest_usr WHERE creator = src_usr;
13676     UPDATE serial.record_entry SET editor = dest_usr WHERE editor = src_usr;
13677
13678     -- reporter.*
13679     -- It's not uncommon to define the reporter schema in a replica 
13680     -- DB only, so don't assume these tables exist in the write DB.
13681     BEGIN
13682         UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
13683     EXCEPTION WHEN undefined_table THEN
13684         -- do nothing
13685     END;
13686     BEGIN
13687         UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
13688     EXCEPTION WHEN undefined_table THEN
13689         -- do nothing
13690     END;
13691     BEGIN
13692         UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
13693     EXCEPTION WHEN undefined_table THEN
13694         -- do nothing
13695     END;
13696     BEGIN
13697                 -- transfer folders the same way we transfer buckets (see above)
13698                 FOR folder_row in
13699                         SELECT id, name
13700                         FROM   reporter.template_folder
13701                         WHERE  owner = src_usr
13702                 LOOP
13703                         suffix := ' (' || src_usr || ')';
13704                         LOOP
13705                                 BEGIN
13706                                         UPDATE  reporter.template_folder
13707                                         SET     owner = dest_usr, name = name || suffix
13708                                         WHERE   id = folder_row.id;
13709                                 EXCEPTION WHEN unique_violation THEN
13710                                         suffix := suffix || ' ';
13711                                         CONTINUE;
13712                                 END;
13713                                 EXIT;
13714                         END LOOP;
13715                 END LOOP;
13716     EXCEPTION WHEN undefined_table THEN
13717         -- do nothing
13718     END;
13719     BEGIN
13720                 -- transfer folders the same way we transfer buckets (see above)
13721                 FOR folder_row in
13722                         SELECT id, name
13723                         FROM   reporter.report_folder
13724                         WHERE  owner = src_usr
13725                 LOOP
13726                         suffix := ' (' || src_usr || ')';
13727                         LOOP
13728                                 BEGIN
13729                                         UPDATE  reporter.report_folder
13730                                         SET     owner = dest_usr, name = name || suffix
13731                                         WHERE   id = folder_row.id;
13732                                 EXCEPTION WHEN unique_violation THEN
13733                                         suffix := suffix || ' ';
13734                                         CONTINUE;
13735                                 END;
13736                                 EXIT;
13737                         END LOOP;
13738                 END LOOP;
13739     EXCEPTION WHEN undefined_table THEN
13740         -- do nothing
13741     END;
13742     BEGIN
13743                 -- transfer folders the same way we transfer buckets (see above)
13744                 FOR folder_row in
13745                         SELECT id, name
13746                         FROM   reporter.output_folder
13747                         WHERE  owner = src_usr
13748                 LOOP
13749                         suffix := ' (' || src_usr || ')';
13750                         LOOP
13751                                 BEGIN
13752                                         UPDATE  reporter.output_folder
13753                                         SET     owner = dest_usr, name = name || suffix
13754                                         WHERE   id = folder_row.id;
13755                                 EXCEPTION WHEN unique_violation THEN
13756                                         suffix := suffix || ' ';
13757                                         CONTINUE;
13758                                 END;
13759                                 EXIT;
13760                         END LOOP;
13761                 END LOOP;
13762     EXCEPTION WHEN undefined_table THEN
13763         -- do nothing
13764     END;
13765
13766     -- Finally, delete the source user
13767     DELETE FROM actor.usr WHERE id = src_usr;
13768
13769 END;
13770 $$ LANGUAGE plpgsql;
13771
13772 -- The "add" trigger functions should protect against existing NULLed values, just in case
13773 CREATE OR REPLACE FUNCTION money.materialized_summary_billing_add () RETURNS TRIGGER AS $$
13774 BEGIN
13775     IF NOT NEW.voided THEN
13776         UPDATE  money.materialized_billable_xact_summary
13777           SET   total_owed = COALESCE(total_owed, 0.0::numeric) + NEW.amount,
13778             last_billing_ts = NEW.billing_ts,
13779             last_billing_note = NEW.note,
13780             last_billing_type = NEW.billing_type,
13781             balance_owed = balance_owed + NEW.amount
13782           WHERE id = NEW.xact;
13783     END IF;
13784
13785     RETURN NEW;
13786 END;
13787 $$ LANGUAGE PLPGSQL;
13788
13789 CREATE OR REPLACE FUNCTION money.materialized_summary_payment_add () RETURNS TRIGGER AS $$
13790 BEGIN
13791     IF NOT NEW.voided THEN
13792         UPDATE  money.materialized_billable_xact_summary
13793           SET   total_paid = COALESCE(total_paid, 0.0::numeric) + NEW.amount,
13794             last_payment_ts = NEW.payment_ts,
13795             last_payment_note = NEW.note,
13796             last_payment_type = TG_ARGV[0],
13797             balance_owed = balance_owed - NEW.amount
13798           WHERE id = NEW.xact;
13799     END IF;
13800
13801     RETURN NEW;
13802 END;
13803 $$ LANGUAGE PLPGSQL;
13804
13805 -- Refresh the mat view with the corrected underlying view
13806 TRUNCATE money.materialized_billable_xact_summary;
13807 INSERT INTO money.materialized_billable_xact_summary SELECT * FROM money.billable_xact_summary;
13808
13809 -- Now redefine the view as a window onto the materialized view
13810 CREATE OR REPLACE VIEW money.billable_xact_summary AS
13811     SELECT * FROM money.materialized_billable_xact_summary;
13812
13813 CREATE OR REPLACE FUNCTION permission.usr_has_perm_at_nd(
13814     user_id    IN INTEGER,
13815     perm_code  IN TEXT
13816 )
13817 RETURNS SETOF INTEGER AS $$
13818 --
13819 -- Return a set of all the org units for which a given user has a given
13820 -- permission, granted directly (not through inheritance from a parent
13821 -- org unit).
13822 --
13823 -- The permissions apply to a minimum depth of the org unit hierarchy,
13824 -- for the org unit(s) to which the user is assigned.  (They also apply
13825 -- to the subordinates of those org units, but we don't report the
13826 -- subordinates here.)
13827 --
13828 -- For purposes of this function, the permission.usr_work_ou_map table
13829 -- defines which users belong to which org units.  I.e. we ignore the
13830 -- home_ou column of actor.usr.
13831 --
13832 -- The result set may contain duplicates, which should be eliminated
13833 -- by a DISTINCT clause.
13834 --
13835 DECLARE
13836     b_super       BOOLEAN;
13837     n_perm        INTEGER;
13838     n_min_depth   INTEGER;
13839     n_work_ou     INTEGER;
13840     n_curr_ou     INTEGER;
13841     n_depth       INTEGER;
13842     n_curr_depth  INTEGER;
13843 BEGIN
13844     --
13845     -- Check for superuser
13846     --
13847     SELECT INTO b_super
13848         super_user
13849     FROM
13850         actor.usr
13851     WHERE
13852         id = user_id;
13853     --
13854     IF NOT FOUND THEN
13855         return;             -- No user?  No permissions.
13856     ELSIF b_super THEN
13857         --
13858         -- Super user has all permissions everywhere
13859         --
13860         FOR n_work_ou IN
13861             SELECT
13862                 id
13863             FROM
13864                 actor.org_unit
13865             WHERE
13866                 parent_ou IS NULL
13867         LOOP
13868             RETURN NEXT n_work_ou;
13869         END LOOP;
13870         RETURN;
13871     END IF;
13872     --
13873     -- Translate the permission name
13874     -- to a numeric permission id
13875     --
13876     SELECT INTO n_perm
13877         id
13878     FROM
13879         permission.perm_list
13880     WHERE
13881         code = perm_code;
13882     --
13883     IF NOT FOUND THEN
13884         RETURN;               -- No such permission
13885     END IF;
13886     --
13887     -- Find the highest-level org unit (i.e. the minimum depth)
13888     -- to which the permission is applied for this user
13889     --
13890     -- This query is modified from the one in permission.usr_perms().
13891     --
13892     SELECT INTO n_min_depth
13893         min( depth )
13894     FROM    (
13895         SELECT depth
13896           FROM permission.usr_perm_map upm
13897          WHERE upm.usr = user_id
13898            AND (upm.perm = n_perm OR upm.perm = -1)
13899                     UNION
13900         SELECT  gpm.depth
13901           FROM  permission.grp_perm_map gpm
13902           WHERE (gpm.perm = n_perm OR gpm.perm = -1)
13903             AND gpm.grp IN (
13904                SELECT   (permission.grp_ancestors(
13905                     (SELECT profile FROM actor.usr WHERE id = user_id)
13906                 )).id
13907             )
13908                     UNION
13909         SELECT  p.depth
13910           FROM  permission.grp_perm_map p
13911           WHERE (p.perm = n_perm OR p.perm = -1)
13912             AND p.grp IN (
13913                 SELECT (permission.grp_ancestors(m.grp)).id
13914                 FROM   permission.usr_grp_map m
13915                 WHERE  m.usr = user_id
13916             )
13917     ) AS x;
13918     --
13919     IF NOT FOUND THEN
13920         RETURN;                -- No such permission for this user
13921     END IF;
13922     --
13923     -- Identify the org units to which the user is assigned.  Note that
13924     -- we pay no attention to the home_ou column in actor.usr.
13925     --
13926     FOR n_work_ou IN
13927         SELECT
13928             work_ou
13929         FROM
13930             permission.usr_work_ou_map
13931         WHERE
13932             usr = user_id
13933     LOOP            -- For each org unit to which the user is assigned
13934         --
13935         -- Determine the level of the org unit by a lookup in actor.org_unit_type.
13936         -- We take it on faith that this depth agrees with the actual hierarchy
13937         -- defined in actor.org_unit.
13938         --
13939         SELECT INTO n_depth
13940             type.depth
13941         FROM
13942             actor.org_unit_type type
13943                 INNER JOIN actor.org_unit ou
13944                     ON ( ou.ou_type = type.id )
13945         WHERE
13946             ou.id = n_work_ou;
13947         --
13948         IF NOT FOUND THEN
13949             CONTINUE;        -- Maybe raise exception?
13950         END IF;
13951         --
13952         -- Compare the depth of the work org unit to the
13953         -- minimum depth, and branch accordingly
13954         --
13955         IF n_depth = n_min_depth THEN
13956             --
13957             -- The org unit is at the right depth, so return it.
13958             --
13959             RETURN NEXT n_work_ou;
13960         ELSIF n_depth > n_min_depth THEN
13961             --
13962             -- Traverse the org unit tree toward the root,
13963             -- until you reach the minimum depth determined above
13964             --
13965             n_curr_depth := n_depth;
13966             n_curr_ou := n_work_ou;
13967             WHILE n_curr_depth > n_min_depth LOOP
13968                 SELECT INTO n_curr_ou
13969                     parent_ou
13970                 FROM
13971                     actor.org_unit
13972                 WHERE
13973                     id = n_curr_ou;
13974                 --
13975                 IF FOUND THEN
13976                     n_curr_depth := n_curr_depth - 1;
13977                 ELSE
13978                     --
13979                     -- This can happen only if the hierarchy defined in
13980                     -- actor.org_unit is corrupted, or out of sync with
13981                     -- the depths defined in actor.org_unit_type.
13982                     -- Maybe we should raise an exception here, instead
13983                     -- of silently ignoring the problem.
13984                     --
13985                     n_curr_ou = NULL;
13986                     EXIT;
13987                 END IF;
13988             END LOOP;
13989             --
13990             IF n_curr_ou IS NOT NULL THEN
13991                 RETURN NEXT n_curr_ou;
13992             END IF;
13993         ELSE
13994             --
13995             -- The permission applies only at a depth greater than the work org unit.
13996             -- Use connectby() to find all dependent org units at the specified depth.
13997             --
13998             FOR n_curr_ou IN
13999                 SELECT ou::INTEGER
14000                 FROM connectby(
14001                         'actor.org_unit',         -- table name
14002                         'id',                     -- key column
14003                         'parent_ou',              -- recursive foreign key
14004                         n_work_ou::TEXT,          -- id of starting point
14005                         (n_min_depth - n_depth)   -- max depth to search, relative
14006                     )                             --   to starting point
14007                     AS t(
14008                         ou text,            -- dependent org unit
14009                         parent_ou text,     -- (ignore)
14010                         level int           -- depth relative to starting point
14011                     )
14012                 WHERE
14013                     level = n_min_depth - n_depth
14014             LOOP
14015                 RETURN NEXT n_curr_ou;
14016             END LOOP;
14017         END IF;
14018         --
14019     END LOOP;
14020     --
14021     RETURN;
14022     --
14023 END;
14024 $$ LANGUAGE 'plpgsql';
14025
14026 ALTER TABLE acq.purchase_order
14027         ADD COLUMN cancel_reason INT
14028                 REFERENCES acq.cancel_reason( id )
14029             DEFERRABLE INITIALLY DEFERRED,
14030         ADD COLUMN prepayment_required BOOLEAN NOT NULL DEFAULT FALSE;
14031
14032 -- Build the history table and lifecycle view
14033 -- for acq.purchase_order
14034
14035 SELECT acq.create_acq_auditor ( 'acq', 'purchase_order' );
14036
14037 CREATE INDEX acq_po_hist_id_idx            ON acq.acq_purchase_order_history( id );
14038
14039 ALTER TABLE acq.lineitem
14040         ADD COLUMN cancel_reason INT
14041                 REFERENCES acq.cancel_reason( id )
14042             DEFERRABLE INITIALLY DEFERRED,
14043         ADD COLUMN estimated_unit_price NUMERIC,
14044         ADD COLUMN claim_policy INT
14045                 REFERENCES acq.claim_policy
14046                 DEFERRABLE INITIALLY DEFERRED,
14047         ALTER COLUMN eg_bib_id SET DATA TYPE bigint;
14048
14049 -- Build the history table and lifecycle view
14050 -- for acq.lineitem
14051
14052 SELECT acq.create_acq_auditor ( 'acq', 'lineitem' );
14053 CREATE INDEX acq_lineitem_hist_id_idx            ON acq.acq_lineitem_history( id );
14054
14055 ALTER TABLE acq.lineitem_detail
14056         ADD COLUMN cancel_reason        INT REFERENCES acq.cancel_reason( id )
14057                                             DEFERRABLE INITIALLY DEFERRED;
14058
14059 ALTER TABLE acq.lineitem_detail
14060         DROP CONSTRAINT lineitem_detail_lineitem_fkey;
14061
14062 ALTER TABLE acq.lineitem_detail
14063         ADD FOREIGN KEY (lineitem) REFERENCES acq.lineitem( id )
14064                 ON DELETE CASCADE
14065                 DEFERRABLE INITIALLY DEFERRED;
14066
14067 ALTER TABLE acq.lineitem_detail DROP CONSTRAINT lineitem_detail_eg_copy_id_fkey;
14068
14069 INSERT INTO acq.cancel_reason ( id, org_unit, label, description ) VALUES (
14070         1, 1, 'invalid_isbn', oils_i18n_gettext( 1, 'ISBN is unrecognizable', 'acqcr', 'label' ));
14071
14072 INSERT INTO acq.cancel_reason ( id, org_unit, label, description ) VALUES (
14073         2, 1, 'postpone', oils_i18n_gettext( 2, 'Title has been postponed', 'acqcr', 'label' ));
14074
14075 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
14076
14077     use MARC::Record;
14078     use MARC::File::XML (BinaryEncoding => 'UTF-8');
14079     use strict;
14080
14081     my $target_xml = shift;
14082     my $source_xml = shift;
14083     my $field_spec = shift;
14084     my $force_add = shift || 0;
14085
14086     my $target_r = MARC::Record->new_from_xml( $target_xml );
14087     my $source_r = MARC::Record->new_from_xml( $source_xml );
14088
14089     return $target_xml unless ($target_r && $source_r);
14090
14091     my @field_list = split(',', $field_spec);
14092
14093     my %fields;
14094     for my $f (@field_list) {
14095         $f =~ s/^\s*//; $f =~ s/\s*$//;
14096         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
14097             my $field = $1;
14098             $field =~ s/\s+//;
14099             my $sf = $2;
14100             $sf =~ s/\s+//;
14101             my $match = $3;
14102             $match =~ s/^\s*//; $match =~ s/\s*$//;
14103             $fields{$field} = { sf => [ split('', $sf) ] };
14104             if ($match) {
14105                 my ($msf,$mre) = split('~', $match);
14106                 if (length($msf) > 0 and length($mre) > 0) {
14107                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
14108                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
14109                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
14110                 }
14111             }
14112         }
14113     }
14114
14115     for my $f ( keys %fields) {
14116         if ( @{$fields{$f}{sf}} ) {
14117             for my $from_field ($source_r->field( $f )) {
14118                 my @tos = $target_r->field( $f );
14119                 if (!@tos) {
14120                     next if (exists($fields{$f}{match}) and !$force_add);
14121                     my @new_fields = map { $_->clone } $source_r->field( $f );
14122                     $target_r->insert_fields_ordered( @new_fields );
14123                 } else {
14124                     for my $to_field (@tos) {
14125                         if (exists($fields{$f}{match})) {
14126                             next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
14127                         }
14128                         my @new_sf = map { ($_ => $from_field->subfield($_)) } @{$fields{$f}{sf}};
14129                         $to_field->add_subfields( @new_sf );
14130                     }
14131                 }
14132             }
14133         } else {
14134             my @new_fields = map { $_->clone } $source_r->field( $f );
14135             $target_r->insert_fields_ordered( @new_fields );
14136         }
14137     }
14138
14139     $target_xml = $target_r->as_xml_record;
14140     $target_xml =~ s/^<\?.+?\?>$//mo;
14141     $target_xml =~ s/\n//sgo;
14142     $target_xml =~ s/>\s+</></sgo;
14143
14144     return $target_xml;
14145
14146 $_$ LANGUAGE PLPERLU;
14147
14148 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
14149     SELECT vandelay.add_field( $1, $2, $3, 0 );
14150 $_$ LANGUAGE SQL;
14151
14152 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
14153
14154     use MARC::Record;
14155     use MARC::File::XML (BinaryEncoding => 'UTF-8');
14156     use strict;
14157
14158     my $xml = shift;
14159     my $r = MARC::Record->new_from_xml( $xml );
14160
14161     return $xml unless ($r);
14162
14163     my $field_spec = shift;
14164     my @field_list = split(',', $field_spec);
14165
14166     my %fields;
14167     for my $f (@field_list) {
14168         $f =~ s/^\s*//; $f =~ s/\s*$//;
14169         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
14170             my $field = $1;
14171             $field =~ s/\s+//;
14172             my $sf = $2;
14173             $sf =~ s/\s+//;
14174             my $match = $3;
14175             $match =~ s/^\s*//; $match =~ s/\s*$//;
14176             $fields{$field} = { sf => [ split('', $sf) ] };
14177             if ($match) {
14178                 my ($msf,$mre) = split('~', $match);
14179                 if (length($msf) > 0 and length($mre) > 0) {
14180                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
14181                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
14182                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
14183                 }
14184             }
14185         }
14186     }
14187
14188     for my $f ( keys %fields) {
14189         for my $to_field ($r->field( $f )) {
14190             if (exists($fields{$f}{match})) {
14191                 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
14192             }
14193
14194             if ( @{$fields{$f}{sf}} ) {
14195                 $to_field->delete_subfield(code => $fields{$f}{sf});
14196             } else {
14197                 $r->delete_field( $to_field );
14198             }
14199         }
14200     }
14201
14202     $xml = $r->as_xml_record;
14203     $xml =~ s/^<\?.+?\?>$//mo;
14204     $xml =~ s/\n//sgo;
14205     $xml =~ s/>\s+</></sgo;
14206
14207     return $xml;
14208
14209 $_$ LANGUAGE PLPERLU;
14210
14211 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
14212 DECLARE
14213     xml_output TEXT;
14214 BEGIN
14215     xml_output := vandelay.strip_field( target_xml, field);
14216
14217     IF xml_output <> target_xml  AND field ~ E'~' THEN
14218         -- we removed something, and there was a regexp restriction in the field definition, so proceed
14219         xml_output := vandelay.add_field( xml_output, source_xml, field, 1 );
14220     ELSIF field !~ E'~' THEN
14221         -- No regexp restriction, add the field
14222         xml_output := vandelay.add_field( xml_output, source_xml, field, 0 );
14223     END IF;
14224
14225     RETURN xml_output;
14226 END;
14227 $_$ LANGUAGE PLPGSQL;
14228
14229 CREATE OR REPLACE FUNCTION vandelay.preserve_field ( incumbent_xml TEXT, incoming_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
14230     SELECT vandelay.add_field( vandelay.strip_field( $2, $3), $1, $3 );
14231 $_$ LANGUAGE SQL;
14232
14233 CREATE VIEW action.unfulfilled_hold_max_loop AS
14234         SELECT  hold,
14235                 max(count) AS max
14236         FROM    action.unfulfilled_hold_loops
14237         GROUP BY 1;
14238
14239 ALTER TABLE acq.lineitem_attr
14240         DROP CONSTRAINT lineitem_attr_lineitem_fkey;
14241
14242 ALTER TABLE acq.lineitem_attr
14243         ADD FOREIGN KEY (lineitem) REFERENCES acq.lineitem( id )
14244                 ON DELETE CASCADE
14245                 DEFERRABLE INITIALLY DEFERRED;
14246
14247 ALTER TABLE acq.po_note
14248         ADD COLUMN vendor_public BOOLEAN NOT NULL DEFAULT FALSE;
14249
14250 CREATE TABLE vandelay.merge_profile (
14251     id              BIGSERIAL   PRIMARY KEY,
14252     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
14253     name            TEXT        NOT NULL,
14254     add_spec        TEXT,
14255     replace_spec    TEXT,
14256     strip_spec      TEXT,
14257     preserve_spec   TEXT,
14258     CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
14259     CONSTRAINT add_replace_strip_or_preserve CHECK ((preserve_spec IS NOT NULL OR replace_spec IS NOT NULL) OR (preserve_spec IS NULL AND replace_spec IS NULL))
14260 );
14261
14262 CREATE OR REPLACE FUNCTION vandelay.match_bib_record ( ) RETURNS TRIGGER AS $func$
14263 DECLARE
14264     attr        RECORD;
14265     attr_def    RECORD;
14266     eg_rec      RECORD;
14267     id_value    TEXT;
14268     exact_id    BIGINT;
14269 BEGIN
14270
14271     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
14272
14273     SELECT * INTO attr_def FROM vandelay.bib_attr_definition WHERE xpath = '//*[@tag="901"]/*[@code="c"]' ORDER BY id LIMIT 1;
14274
14275     IF attr_def IS NOT NULL AND attr_def.id IS NOT NULL THEN
14276         id_value := extract_marc_field('vandelay.queued_bib_record', NEW.id, attr_def.xpath, attr_def.remove);
14277
14278         IF id_value IS NOT NULL AND id_value <> '' AND id_value ~ $r$^\d+$$r$ THEN
14279             SELECT id INTO exact_id FROM biblio.record_entry WHERE id = id_value::BIGINT AND NOT deleted;
14280             SELECT * INTO attr FROM vandelay.queued_bib_record_attr WHERE record = NEW.id and field = attr_def.id LIMIT 1;
14281             IF exact_id IS NOT NULL THEN
14282                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, exact_id);
14283             END IF;
14284         END IF;
14285     END IF;
14286
14287     IF exact_id IS NULL THEN
14288         FOR attr IN SELECT a.* FROM vandelay.queued_bib_record_attr a JOIN vandelay.bib_attr_definition d ON (d.id = a.field) WHERE record = NEW.id AND d.ident IS TRUE LOOP
14289
14290             -- All numbers? check for an id match
14291             IF (attr.attr_value ~ $r$^\d+$$r$) THEN
14292                 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE id = attr.attr_value::BIGINT AND deleted IS FALSE LOOP
14293                     INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
14294                 END LOOP;
14295             END IF;
14296
14297             -- Looks like an ISBN? check for an isbn match
14298             IF (attr.attr_value ~* $r$^[0-9x]+$$r$ AND character_length(attr.attr_value) IN (10,13)) THEN
14299                 FOR eg_rec IN EXECUTE $$SELECT * FROM metabib.full_rec fr WHERE fr.value LIKE LOWER('$$ || attr.attr_value || $$%') AND fr.tag = '020' AND fr.subfield = 'a'$$ LOOP
14300                     PERFORM id FROM biblio.record_entry WHERE id = eg_rec.record AND deleted IS FALSE;
14301                     IF FOUND THEN
14302                         INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('isbn', attr.id, NEW.id, eg_rec.record);
14303                     END IF;
14304                 END LOOP;
14305
14306                 -- subcheck for isbn-as-tcn
14307                 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = 'i' || attr.attr_value AND deleted IS FALSE LOOP
14308                     INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
14309                 END LOOP;
14310             END IF;
14311
14312             -- check for an OCLC tcn_value match
14313             IF (attr.attr_value ~ $r$^o\d+$$r$) THEN
14314                 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = regexp_replace(attr.attr_value,'^o','ocm') AND deleted IS FALSE LOOP
14315                     INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
14316                 END LOOP;
14317             END IF;
14318
14319             -- check for a direct tcn_value match
14320             FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = attr.attr_value AND deleted IS FALSE LOOP
14321                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
14322             END LOOP;
14323
14324             -- check for a direct item barcode match
14325             FOR eg_rec IN
14326                     SELECT  DISTINCT b.*
14327                       FROM  biblio.record_entry b
14328                             JOIN asset.call_number cn ON (cn.record = b.id)
14329                             JOIN asset.copy cp ON (cp.call_number = cn.id)
14330                       WHERE cp.barcode = attr.attr_value AND cp.deleted IS FALSE
14331             LOOP
14332                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
14333             END LOOP;
14334
14335         END LOOP;
14336     END IF;
14337
14338     RETURN NULL;
14339 END;
14340 $func$ LANGUAGE PLPGSQL;
14341
14342 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_xml TEXT, source_xml TEXT, add_rule TEXT, replace_preserve_rule TEXT, strip_rule TEXT ) RETURNS TEXT AS $_$
14343     SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
14344 $_$ LANGUAGE SQL;
14345
14346 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
14347 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
14348 DECLARE
14349     output              vandelay.compile_profile%ROWTYPE;
14350     profile             vandelay.merge_profile%ROWTYPE;
14351     profile_tmpl        TEXT;
14352     profile_tmpl_owner  TEXT;
14353     add_rule            TEXT := '';
14354     strip_rule          TEXT := '';
14355     replace_rule        TEXT := '';
14356     preserve_rule       TEXT := '';
14357
14358 BEGIN
14359
14360     profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
14361     profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
14362
14363     IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
14364         SELECT  p.* INTO profile
14365           FROM  vandelay.merge_profile p
14366                 JOIN actor.org_unit u ON (u.id = p.owner)
14367           WHERE p.name = profile_tmpl
14368                 AND u.shortname = profile_tmpl_owner;
14369
14370         IF profile.id IS NOT NULL THEN
14371             add_rule := COALESCE(profile.add_spec,'');
14372             strip_rule := COALESCE(profile.strip_spec,'');
14373             replace_rule := COALESCE(profile.replace_spec,'');
14374             preserve_rule := COALESCE(profile.preserve_spec,'');
14375         END IF;
14376     END IF;
14377
14378     add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
14379     strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
14380     replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
14381     preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
14382
14383     output.add_rule := BTRIM(add_rule,',');
14384     output.replace_rule := BTRIM(replace_rule,',');
14385     output.strip_rule := BTRIM(strip_rule,',');
14386     output.preserve_rule := BTRIM(preserve_rule,',');
14387
14388     RETURN output;
14389 END;
14390 $_$ LANGUAGE PLPGSQL;
14391
14392 -- Template-based marc munging functions
14393 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
14394 DECLARE
14395     merge_profile   vandelay.merge_profile%ROWTYPE;
14396     dyn_profile     vandelay.compile_profile%ROWTYPE;
14397     editor_string   TEXT;
14398     editor_id       INT;
14399     source_marc     TEXT;
14400     target_marc     TEXT;
14401     eg_marc         TEXT;
14402     replace_rule    TEXT;
14403     match_count     INT;
14404 BEGIN
14405
14406     SELECT  b.marc INTO eg_marc
14407       FROM  biblio.record_entry b
14408       WHERE b.id = eg_id
14409       LIMIT 1;
14410
14411     IF eg_marc IS NULL OR v_marc IS NULL THEN
14412         -- RAISE NOTICE 'no marc for template or bib record';
14413         RETURN FALSE;
14414     END IF;
14415
14416     dyn_profile := vandelay.compile_profile( v_marc );
14417
14418     IF merge_profile_id IS NOT NULL THEN
14419         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
14420         IF FOUND THEN
14421             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
14422             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
14423             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
14424             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
14425         END IF;
14426     END IF;
14427
14428     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
14429         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
14430         RETURN FALSE;
14431     END IF;
14432
14433     IF dyn_profile.replace_rule <> '' THEN
14434         source_marc = v_marc;
14435         target_marc = eg_marc;
14436         replace_rule = dyn_profile.replace_rule;
14437     ELSE
14438         source_marc = eg_marc;
14439         target_marc = v_marc;
14440         replace_rule = dyn_profile.preserve_rule;
14441     END IF;
14442
14443     UPDATE  biblio.record_entry
14444       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
14445       WHERE id = eg_id;
14446
14447     IF NOT FOUND THEN
14448         -- RAISE NOTICE 'update of biblio.record_entry failed';
14449         RETURN FALSE;
14450     END IF;
14451
14452     RETURN TRUE;
14453
14454 END;
14455 $$ LANGUAGE PLPGSQL;
14456
14457 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
14458     SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
14459 $$ LANGUAGE SQL;
14460
14461 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
14462 DECLARE
14463     merge_profile   vandelay.merge_profile%ROWTYPE;
14464     dyn_profile     vandelay.compile_profile%ROWTYPE;
14465     editor_string   TEXT;
14466     editor_id       INT;
14467     source_marc     TEXT;
14468     target_marc     TEXT;
14469     eg_marc         TEXT;
14470     v_marc          TEXT;
14471     replace_rule    TEXT;
14472     match_count     INT;
14473 BEGIN
14474
14475     SELECT  q.marc INTO v_marc
14476       FROM  vandelay.queued_record q
14477             JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
14478       LIMIT 1;
14479
14480     IF v_marc IS NULL THEN
14481         -- RAISE NOTICE 'no marc for vandelay or bib record';
14482         RETURN FALSE;
14483     END IF;
14484
14485     IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
14486         UPDATE  vandelay.queued_bib_record
14487           SET   imported_as = eg_id,
14488                 import_time = NOW()
14489           WHERE id = import_id;
14490
14491         editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
14492
14493         IF editor_string IS NOT NULL AND editor_string <> '' THEN
14494             SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
14495
14496             IF editor_id IS NULL THEN
14497                 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
14498             END IF;
14499
14500             IF editor_id IS NOT NULL THEN
14501                 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
14502             END IF;
14503         END IF;
14504
14505         RETURN TRUE;
14506     END IF;
14507
14508     -- RAISE NOTICE 'update of biblio.record_entry failed';
14509
14510     RETURN FALSE;
14511
14512 END;
14513 $$ LANGUAGE PLPGSQL;
14514
14515 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
14516 DECLARE
14517     eg_id           BIGINT;
14518     match_count     INT;
14519     match_attr      vandelay.bib_attr_definition%ROWTYPE;
14520 BEGIN
14521
14522     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
14523
14524     IF FOUND THEN
14525         -- RAISE NOTICE 'already imported, cannot auto-overlay'
14526         RETURN FALSE;
14527     END IF;
14528
14529     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
14530
14531     IF match_count <> 1 THEN
14532         -- RAISE NOTICE 'not an exact match';
14533         RETURN FALSE;
14534     END IF;
14535
14536     SELECT  d.* INTO match_attr
14537       FROM  vandelay.bib_attr_definition d
14538             JOIN vandelay.queued_bib_record_attr a ON (a.field = d.id)
14539             JOIN vandelay.bib_match m ON (m.matched_attr = a.id)
14540       WHERE m.queued_record = import_id;
14541
14542     IF NOT (match_attr.xpath ~ '@tag="901"' AND match_attr.xpath ~ '@code="c"') THEN
14543         -- RAISE NOTICE 'not a 901c match: %', match_attr.xpath;
14544         RETURN FALSE;
14545     END IF;
14546
14547     SELECT  m.eg_record INTO eg_id
14548       FROM  vandelay.bib_match m
14549       WHERE m.queued_record = import_id
14550       LIMIT 1;
14551
14552     IF eg_id IS NULL THEN
14553         RETURN FALSE;
14554     END IF;
14555
14556     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
14557 END;
14558 $$ LANGUAGE PLPGSQL;
14559
14560 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
14561 DECLARE
14562     queued_record   vandelay.queued_bib_record%ROWTYPE;
14563 BEGIN
14564
14565     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
14566
14567         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
14568             RETURN NEXT queued_record.id;
14569         END IF;
14570
14571     END LOOP;
14572
14573     RETURN;
14574
14575 END;
14576 $$ LANGUAGE PLPGSQL;
14577
14578 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
14579     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
14580 $$ LANGUAGE SQL;
14581
14582 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
14583 DECLARE
14584     merge_profile   vandelay.merge_profile%ROWTYPE;
14585     dyn_profile     vandelay.compile_profile%ROWTYPE;
14586     source_marc     TEXT;
14587     target_marc     TEXT;
14588     eg_marc         TEXT;
14589     v_marc          TEXT;
14590     replace_rule    TEXT;
14591     match_count     INT;
14592 BEGIN
14593
14594     SELECT  b.marc INTO eg_marc
14595       FROM  authority.record_entry b
14596             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
14597       LIMIT 1;
14598
14599     SELECT  q.marc INTO v_marc
14600       FROM  vandelay.queued_record q
14601             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
14602       LIMIT 1;
14603
14604     IF eg_marc IS NULL OR v_marc IS NULL THEN
14605         -- RAISE NOTICE 'no marc for vandelay or authority record';
14606         RETURN FALSE;
14607     END IF;
14608
14609     dyn_profile := vandelay.compile_profile( v_marc );
14610
14611     IF merge_profile_id IS NOT NULL THEN
14612         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
14613         IF FOUND THEN
14614             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
14615             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
14616             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
14617             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
14618         END IF;
14619     END IF;
14620
14621     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
14622         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
14623         RETURN FALSE;
14624     END IF;
14625
14626     IF dyn_profile.replace_rule <> '' THEN
14627         source_marc = v_marc;
14628         target_marc = eg_marc;
14629         replace_rule = dyn_profile.replace_rule;
14630     ELSE
14631         source_marc = eg_marc;
14632         target_marc = v_marc;
14633         replace_rule = dyn_profile.preserve_rule;
14634     END IF;
14635
14636     UPDATE  authority.record_entry
14637       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
14638       WHERE id = eg_id;
14639
14640     IF FOUND THEN
14641         UPDATE  vandelay.queued_authority_record
14642           SET   imported_as = eg_id,
14643                 import_time = NOW()
14644           WHERE id = import_id;
14645         RETURN TRUE;
14646     END IF;
14647
14648     -- RAISE NOTICE 'update of authority.record_entry failed';
14649
14650     RETURN FALSE;
14651
14652 END;
14653 $$ LANGUAGE PLPGSQL;
14654
14655 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
14656 DECLARE
14657     eg_id           BIGINT;
14658     match_count     INT;
14659 BEGIN
14660     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
14661
14662     IF match_count <> 1 THEN
14663         -- RAISE NOTICE 'not an exact match';
14664         RETURN FALSE;
14665     END IF;
14666
14667     SELECT  m.eg_record INTO eg_id
14668       FROM  vandelay.authority_match m
14669       WHERE m.queued_record = import_id
14670       LIMIT 1;
14671
14672     IF eg_id IS NULL THEN
14673         RETURN FALSE;
14674     END IF;
14675
14676     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
14677 END;
14678 $$ LANGUAGE PLPGSQL;
14679
14680 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
14681 DECLARE
14682     queued_record   vandelay.queued_authority_record%ROWTYPE;
14683 BEGIN
14684
14685     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
14686
14687         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
14688             RETURN NEXT queued_record.id;
14689         END IF;
14690
14691     END LOOP;
14692
14693     RETURN;
14694
14695 END;
14696 $$ LANGUAGE PLPGSQL;
14697
14698 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
14699     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
14700 $$ LANGUAGE SQL;
14701
14702 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
14703 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
14704 DECLARE
14705     eg_tcn          TEXT;
14706     eg_tcn_source   TEXT;
14707     output          vandelay.tcn_data%ROWTYPE;
14708 BEGIN
14709
14710     -- 001/003
14711     eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
14712     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14713
14714         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
14715         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
14716             eg_tcn_source := 'System Local';
14717         END IF;
14718
14719         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14720
14721         IF NOT FOUND THEN
14722             output.used := FALSE;
14723         ELSE
14724             output.used := TRUE;
14725         END IF;
14726
14727         output.tcn := eg_tcn;
14728         output.tcn_source := eg_tcn_source;
14729         RETURN NEXT output;
14730
14731     END IF;
14732
14733     -- 901 ab
14734     eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
14735     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14736
14737         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
14738         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
14739             eg_tcn_source := 'System Local';
14740         END IF;
14741
14742         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14743
14744         IF NOT FOUND THEN
14745             output.used := FALSE;
14746         ELSE
14747             output.used := TRUE;
14748         END IF;
14749
14750         output.tcn := eg_tcn;
14751         output.tcn_source := eg_tcn_source;
14752         RETURN NEXT output;
14753
14754     END IF;
14755
14756     -- 039 ab
14757     eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
14758     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14759
14760         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
14761         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
14762             eg_tcn_source := 'System Local';
14763         END IF;
14764
14765         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14766
14767         IF NOT FOUND THEN
14768             output.used := FALSE;
14769         ELSE
14770             output.used := TRUE;
14771         END IF;
14772
14773         output.tcn := eg_tcn;
14774         output.tcn_source := eg_tcn_source;
14775         RETURN NEXT output;
14776
14777     END IF;
14778
14779     -- 020 a
14780     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
14781     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14782
14783         eg_tcn_source := 'ISBN';
14784
14785         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14786
14787         IF NOT FOUND THEN
14788             output.used := FALSE;
14789         ELSE
14790             output.used := TRUE;
14791         END IF;
14792
14793         output.tcn := eg_tcn;
14794         output.tcn_source := eg_tcn_source;
14795         RETURN NEXT output;
14796
14797     END IF;
14798
14799     -- 022 a
14800     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
14801     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14802
14803         eg_tcn_source := 'ISSN';
14804
14805         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14806
14807         IF NOT FOUND THEN
14808             output.used := FALSE;
14809         ELSE
14810             output.used := TRUE;
14811         END IF;
14812
14813         output.tcn := eg_tcn;
14814         output.tcn_source := eg_tcn_source;
14815         RETURN NEXT output;
14816
14817     END IF;
14818
14819     -- 010 a
14820     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
14821     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14822
14823         eg_tcn_source := 'LCCN';
14824
14825         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14826
14827         IF NOT FOUND THEN
14828             output.used := FALSE;
14829         ELSE
14830             output.used := TRUE;
14831         END IF;
14832
14833         output.tcn := eg_tcn;
14834         output.tcn_source := eg_tcn_source;
14835         RETURN NEXT output;
14836
14837     END IF;
14838
14839     -- 035 a
14840     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
14841     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
14842
14843         eg_tcn_source := 'System Legacy';
14844
14845         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
14846
14847         IF NOT FOUND THEN
14848             output.used := FALSE;
14849         ELSE
14850             output.used := TRUE;
14851         END IF;
14852
14853         output.tcn := eg_tcn;
14854         output.tcn_source := eg_tcn_source;
14855         RETURN NEXT output;
14856
14857     END IF;
14858
14859     RETURN;
14860 END;
14861 $_$ LANGUAGE PLPGSQL;
14862
14863 CREATE INDEX claim_lid_idx ON acq.claim( lineitem_detail );
14864
14865 CREATE OR REPLACE RULE protect_bib_rec_delete AS ON DELETE TO biblio.record_entry DO INSTEAD (UPDATE biblio.record_entry SET deleted = TRUE WHERE OLD.id = biblio.record_entry.id; DELETE FROM metabib.metarecord_source_map WHERE source = OLD.id);
14866
14867 CREATE INDEX metabib_title_field_entry_value_idx ON metabib.title_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
14868 CREATE INDEX metabib_author_field_entry_value_idx ON metabib.author_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
14869 CREATE INDEX metabib_subject_field_entry_value_idx ON metabib.subject_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
14870 CREATE INDEX metabib_keyword_field_entry_value_idx ON metabib.keyword_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
14871 CREATE INDEX metabib_series_field_entry_value_idx ON metabib.series_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
14872
14873 CREATE INDEX metabib_author_field_entry_source_idx ON metabib.author_field_entry (source);
14874 CREATE INDEX metabib_keyword_field_entry_source_idx ON metabib.keyword_field_entry (source);
14875 CREATE INDEX metabib_title_field_entry_source_idx ON metabib.title_field_entry (source);
14876 CREATE INDEX metabib_series_field_entry_source_idx ON metabib.series_field_entry (source);
14877
14878 ALTER TABLE metabib.series_field_entry
14879         ADD CONSTRAINT metabib_series_field_entry_source_pkey FOREIGN KEY (source)
14880                 REFERENCES biblio.record_entry (id)
14881                 ON DELETE CASCADE
14882                 DEFERRABLE INITIALLY DEFERRED;
14883
14884 ALTER TABLE metabib.series_field_entry
14885         ADD CONSTRAINT metabib_series_field_entry_field_pkey FOREIGN KEY (field)
14886                 REFERENCES config.metabib_field (id)
14887                 ON DELETE CASCADE
14888                 DEFERRABLE INITIALLY DEFERRED;
14889
14890 CREATE TABLE acq.claim_policy_action (
14891         id              SERIAL       PRIMARY KEY,
14892         claim_policy    INT          NOT NULL REFERENCES acq.claim_policy
14893                                  ON DELETE CASCADE
14894                                      DEFERRABLE INITIALLY DEFERRED,
14895         action_interval INTERVAL     NOT NULL,
14896         action          INT          NOT NULL REFERENCES acq.claim_event_type
14897                                      DEFERRABLE INITIALLY DEFERRED,
14898         CONSTRAINT action_sequence UNIQUE (claim_policy, action_interval)
14899 );
14900
14901 CREATE OR REPLACE FUNCTION public.ingest_acq_marc ( ) RETURNS TRIGGER AS $function$
14902 DECLARE
14903     value       TEXT; 
14904     atype       TEXT; 
14905     prov        INT;
14906     pos         INT;
14907     adef        RECORD;
14908     xpath_string    TEXT;
14909 BEGIN
14910     FOR adef IN SELECT *,tableoid FROM acq.lineitem_attr_definition LOOP
14911     
14912         SELECT relname::TEXT INTO atype FROM pg_class WHERE oid = adef.tableoid;
14913       
14914         IF (atype NOT IN ('lineitem_usr_attr_definition','lineitem_local_attr_definition')) THEN
14915             IF (atype = 'lineitem_provider_attr_definition') THEN
14916                 SELECT provider INTO prov FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
14917                 CONTINUE WHEN NEW.provider IS NULL OR prov <> NEW.provider;
14918             END IF;
14919             
14920             IF (atype = 'lineitem_provider_attr_definition') THEN
14921                 SELECT xpath INTO xpath_string FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
14922             ELSIF (atype = 'lineitem_marc_attr_definition') THEN
14923                 SELECT xpath INTO xpath_string FROM acq.lineitem_marc_attr_definition WHERE id = adef.id;
14924             ELSIF (atype = 'lineitem_generated_attr_definition') THEN
14925                 SELECT xpath INTO xpath_string FROM acq.lineitem_generated_attr_definition WHERE id = adef.id;
14926             END IF;
14927       
14928             xpath_string := REGEXP_REPLACE(xpath_string,$re$//?text\(\)$$re$,'');
14929
14930             IF (adef.code = 'title' OR adef.code = 'author') THEN
14931                 -- title and author should not be split
14932                 -- FIXME: once oils_xpath can grok XPATH 2.0 functions, we can use
14933                 -- string-join in the xpath and remove this special case
14934                 SELECT extract_acq_marc_field(id, xpath_string, adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
14935                 IF (value IS NOT NULL AND value <> '') THEN
14936                     INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
14937                         VALUES (NEW.id, adef.id, atype, adef.code, value);
14938                 END IF;
14939             ELSE
14940                 pos := 1;
14941
14942                 LOOP
14943                     SELECT extract_acq_marc_field(id, xpath_string || '[' || pos || ']', adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
14944       
14945                     IF (value IS NOT NULL AND value <> '') THEN
14946                         INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
14947                             VALUES (NEW.id, adef.id, atype, adef.code, value);
14948                     ELSE
14949                         EXIT;
14950                     END IF;
14951
14952                     pos := pos + 1;
14953                 END LOOP;
14954             END IF;
14955
14956         END IF;
14957
14958     END LOOP;
14959
14960     RETURN NULL;
14961 END;
14962 $function$ LANGUAGE PLPGSQL;
14963
14964 UPDATE config.metabib_field SET label = name;
14965 ALTER TABLE config.metabib_field ALTER COLUMN label SET NOT NULL;
14966
14967 ALTER TABLE config.metabib_field ADD CONSTRAINT metabib_field_field_class_fkey
14968          FOREIGN KEY (field_class) REFERENCES config.metabib_class (name);
14969
14970 ALTER TABLE config.metabib_field DROP CONSTRAINT metabib_field_field_class_check;
14971
14972 ALTER TABLE config.metabib_field ADD CONSTRAINT metabib_field_format_fkey FOREIGN KEY (format) REFERENCES config.xml_transform (name);
14973
14974 CREATE TABLE config.metabib_search_alias (
14975     alias       TEXT    PRIMARY KEY,
14976     field_class TEXT    NOT NULL REFERENCES config.metabib_class (name),
14977     field       INT     REFERENCES config.metabib_field (id)
14978 );
14979
14980 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('kw','keyword');
14981 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('eg.keyword','keyword');
14982 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.publisher','keyword');
14983 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.identifier','keyword');
14984 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('bib.subjecttitle','keyword');
14985 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('bib.genre','keyword');
14986 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('bib.edition','keyword');
14987 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('srw.serverchoice','keyword');
14988
14989 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('au','author');
14990 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('name','author');
14991 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('creator','author');
14992 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('eg.author','author');
14993 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('eg.name','author');
14994 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.creator','author');
14995 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.contributor','author');
14996 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('bib.name','author');
14997 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.namepersonal','author',8);
14998 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.namepersonalfamily','author',8);
14999 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.namepersonalgiven','author',8);
15000 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.namecorporate','author',7);
15001 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.nameconference','author',9);
15002
15003 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('ti','title');
15004 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('eg.title','title');
15005 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.title','title');
15006 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.titleabbreviated','title',2);
15007 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.titleuniform','title',5);
15008 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.titletranslated','title',3);
15009 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.titlealternative','title',4);
15010 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.title','title',2);
15011
15012 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('su','subject');
15013 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('eg.subject','subject');
15014 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.subject','subject');
15015 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.subjectplace','subject',11);
15016 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.subjectname','subject',12);
15017 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.subjectoccupation','subject',16);
15018
15019 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('se','series');
15020 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('eg.series','series');
15021 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('bib.titleseries','series',1);
15022
15023 UPDATE config.metabib_field SET facet_field=TRUE WHERE id = 1;
15024 UPDATE config.metabib_field SET xpath=$$//mods32:mods/mods32:name[@type='corporate' and mods32:role/mods32:roleTerm[text()='creator']]$$, facet_field=TRUE, facet_xpath=$$*[local-name()='namePart']$$ WHERE id = 7;
15025 UPDATE config.metabib_field SET xpath=$$//mods32:mods/mods32:name[@type='personal' and mods32:role/mods32:roleTerm[text()='creator']]$$, facet_field=TRUE, facet_xpath=$$*[local-name()='namePart']$$ WHERE id = 8;
15026 UPDATE config.metabib_field SET xpath=$$//mods32:mods/mods32:name[@type='conference' and mods32:role/mods32:roleTerm[text()='creator']]$$, facet_field=TRUE, facet_xpath=$$*[local-name()='namePart']$$ WHERE id = 9;
15027 UPDATE config.metabib_field SET xpath=$$//mods32:mods/mods32:name[@type='personal' and not(mods32:role)]$$, facet_field=TRUE, facet_xpath=$$*[local-name()='namePart']$$ WHERE id = 10;
15028
15029 UPDATE config.metabib_field SET facet_field=TRUE WHERE id = 11;
15030 UPDATE config.metabib_field SET facet_field=TRUE , facet_xpath=$$*[local-name()='namePart']$$ WHERE id = 12;
15031 UPDATE config.metabib_field SET facet_field=TRUE WHERE id = 13;
15032 UPDATE config.metabib_field SET facet_field=TRUE WHERE id = 14;
15033
15034 CREATE INDEX metabib_rec_descriptor_item_type_idx ON metabib.rec_descriptor (item_type);
15035 CREATE INDEX metabib_rec_descriptor_item_form_idx ON metabib.rec_descriptor (item_form);
15036 CREATE INDEX metabib_rec_descriptor_bib_level_idx ON metabib.rec_descriptor (bib_level);
15037 CREATE INDEX metabib_rec_descriptor_control_type_idx ON metabib.rec_descriptor (control_type);
15038 CREATE INDEX metabib_rec_descriptor_char_encoding_idx ON metabib.rec_descriptor (char_encoding);
15039 CREATE INDEX metabib_rec_descriptor_enc_level_idx ON metabib.rec_descriptor (enc_level);
15040 CREATE INDEX metabib_rec_descriptor_audience_idx ON metabib.rec_descriptor (audience);
15041 CREATE INDEX metabib_rec_descriptor_lit_form_idx ON metabib.rec_descriptor (lit_form);
15042 CREATE INDEX metabib_rec_descriptor_cat_form_idx ON metabib.rec_descriptor (cat_form);
15043 CREATE INDEX metabib_rec_descriptor_pub_status_idx ON metabib.rec_descriptor (pub_status);
15044 CREATE INDEX metabib_rec_descriptor_item_lang_idx ON metabib.rec_descriptor (item_lang);
15045 CREATE INDEX metabib_rec_descriptor_vr_format_idx ON metabib.rec_descriptor (vr_format);
15046 CREATE INDEX metabib_rec_descriptor_date1_idx ON metabib.rec_descriptor (date1);
15047 CREATE INDEX metabib_rec_descriptor_dates_idx ON metabib.rec_descriptor (date1,date2);
15048
15049 CREATE TABLE asset.opac_visible_copies (
15050   id        BIGINT primary key, -- copy id
15051   record    BIGINT,
15052   circ_lib  INTEGER
15053 );
15054 COMMENT ON TABLE asset.opac_visible_copies IS $$
15055 Materialized view of copies that are visible in the OPAC, used by
15056 search.query_parser_fts() to speed up OPAC visibility checks on large
15057 databases.  Contents are maintained by a set of triggers.
15058 $$;
15059 CREATE INDEX opac_visible_copies_idx1 on asset.opac_visible_copies (record, circ_lib);
15060
15061 CREATE OR REPLACE FUNCTION search.query_parser_fts (
15062
15063     param_search_ou INT,
15064     param_depth     INT,
15065     param_query     TEXT,
15066     param_statuses  INT[],
15067     param_locations INT[],
15068     param_offset    INT,
15069     param_check     INT,
15070     param_limit     INT,
15071     metarecord      BOOL,
15072     staff           BOOL
15073  
15074 ) RETURNS SETOF search.search_result AS $func$
15075 DECLARE
15076
15077     current_res         search.search_result%ROWTYPE;
15078     search_org_list     INT[];
15079
15080     check_limit         INT;
15081     core_limit          INT;
15082     core_offset         INT;
15083     tmp_int             INT;
15084
15085     core_result         RECORD;
15086     core_cursor         REFCURSOR;
15087     core_rel_query      TEXT;
15088
15089     total_count         INT := 0;
15090     check_count         INT := 0;
15091     deleted_count       INT := 0;
15092     visible_count       INT := 0;
15093     excluded_count      INT := 0;
15094
15095 BEGIN
15096
15097     check_limit := COALESCE( param_check, 1000 );
15098     core_limit  := COALESCE( param_limit, 25000 );
15099     core_offset := COALESCE( param_offset, 0 );
15100
15101     -- core_skip_chk := COALESCE( param_skip_chk, 1 );
15102
15103     IF param_search_ou > 0 THEN
15104         IF param_depth IS NOT NULL THEN
15105             SELECT array_accum(distinct id) INTO search_org_list FROM actor.org_unit_descendants( param_search_ou, param_depth );
15106         ELSE
15107             SELECT array_accum(distinct id) INTO search_org_list FROM actor.org_unit_descendants( param_search_ou );
15108         END IF;
15109     ELSIF param_search_ou < 0 THEN
15110         SELECT array_accum(distinct org_unit) INTO search_org_list FROM actor.org_lasso_map WHERE lasso = -param_search_ou;
15111     ELSIF param_search_ou = 0 THEN
15112         -- reserved for user lassos (ou_buckets/type='lasso') with ID passed in depth ... hack? sure.
15113     END IF;
15114
15115     OPEN core_cursor FOR EXECUTE param_query;
15116
15117     LOOP
15118
15119         FETCH core_cursor INTO core_result;
15120         EXIT WHEN NOT FOUND;
15121         EXIT WHEN total_count >= core_limit;
15122
15123         total_count := total_count + 1;
15124
15125         CONTINUE WHEN total_count NOT BETWEEN  core_offset + 1 AND check_limit + core_offset;
15126
15127         check_count := check_count + 1;
15128
15129         PERFORM 1 FROM biblio.record_entry b WHERE NOT b.deleted AND b.id IN ( SELECT * FROM search.explode_array( core_result.records ) );
15130         IF NOT FOUND THEN
15131             -- RAISE NOTICE ' % were all deleted ... ', core_result.records;
15132             deleted_count := deleted_count + 1;
15133             CONTINUE;
15134         END IF;
15135
15136         PERFORM 1
15137           FROM  biblio.record_entry b
15138                 JOIN config.bib_source s ON (b.source = s.id)
15139           WHERE s.transcendant
15140                 AND b.id IN ( SELECT * FROM search.explode_array( core_result.records ) );
15141
15142         IF FOUND THEN
15143             -- RAISE NOTICE ' % were all transcendant ... ', core_result.records;
15144             visible_count := visible_count + 1;
15145
15146             current_res.id = core_result.id;
15147             current_res.rel = core_result.rel;
15148
15149             tmp_int := 1;
15150             IF metarecord THEN
15151                 SELECT COUNT(DISTINCT s.source) INTO tmp_int FROM metabib.metarecord_source_map s WHERE s.metarecord = core_result.id;
15152             END IF;
15153
15154             IF tmp_int = 1 THEN
15155                 current_res.record = core_result.records[1];
15156             ELSE
15157                 current_res.record = NULL;
15158             END IF;
15159
15160             RETURN NEXT current_res;
15161
15162             CONTINUE;
15163         END IF;
15164
15165         PERFORM 1
15166           FROM  asset.call_number cn
15167                 JOIN asset.uri_call_number_map map ON (map.call_number = cn.id)
15168                 JOIN asset.uri uri ON (map.uri = uri.id)
15169           WHERE NOT cn.deleted
15170                 AND cn.label = '##URI##'
15171                 AND uri.active
15172                 AND ( param_locations IS NULL OR array_upper(param_locations, 1) IS NULL )
15173                 AND cn.record IN ( SELECT * FROM search.explode_array( core_result.records ) )
15174                 AND cn.owning_lib IN ( SELECT * FROM search.explode_array( search_org_list ) )
15175           LIMIT 1;
15176
15177         IF FOUND THEN
15178             -- RAISE NOTICE ' % have at least one URI ... ', core_result.records;
15179             visible_count := visible_count + 1;
15180
15181             current_res.id = core_result.id;
15182             current_res.rel = core_result.rel;
15183
15184             tmp_int := 1;
15185             IF metarecord THEN
15186                 SELECT COUNT(DISTINCT s.source) INTO tmp_int FROM metabib.metarecord_source_map s WHERE s.metarecord = core_result.id;
15187             END IF;
15188
15189             IF tmp_int = 1 THEN
15190                 current_res.record = core_result.records[1];
15191             ELSE
15192                 current_res.record = NULL;
15193             END IF;
15194
15195             RETURN NEXT current_res;
15196
15197             CONTINUE;
15198         END IF;
15199
15200         IF param_statuses IS NOT NULL AND array_upper(param_statuses, 1) > 0 THEN
15201
15202             PERFORM 1
15203               FROM  asset.call_number cn
15204                     JOIN asset.copy cp ON (cp.call_number = cn.id)
15205               WHERE NOT cn.deleted
15206                     AND NOT cp.deleted
15207                     AND cp.status IN ( SELECT * FROM search.explode_array( param_statuses ) )
15208                     AND cn.record IN ( SELECT * FROM search.explode_array( core_result.records ) )
15209                     AND cp.circ_lib IN ( SELECT * FROM search.explode_array( search_org_list ) )
15210               LIMIT 1;
15211
15212             IF NOT FOUND THEN
15213                 -- RAISE NOTICE ' % were all status-excluded ... ', core_result.records;
15214                 excluded_count := excluded_count + 1;
15215                 CONTINUE;
15216             END IF;
15217
15218         END IF;
15219
15220         IF param_locations IS NOT NULL AND array_upper(param_locations, 1) > 0 THEN
15221
15222             PERFORM 1
15223               FROM  asset.call_number cn
15224                     JOIN asset.copy cp ON (cp.call_number = cn.id)
15225               WHERE NOT cn.deleted
15226                     AND NOT cp.deleted
15227                     AND cp.location IN ( SELECT * FROM search.explode_array( param_locations ) )
15228                     AND cn.record IN ( SELECT * FROM search.explode_array( core_result.records ) )
15229                     AND cp.circ_lib IN ( SELECT * FROM search.explode_array( search_org_list ) )
15230               LIMIT 1;
15231
15232             IF NOT FOUND THEN
15233                 -- RAISE NOTICE ' % were all copy_location-excluded ... ', core_result.records;
15234                 excluded_count := excluded_count + 1;
15235                 CONTINUE;
15236             END IF;
15237
15238         END IF;
15239
15240         IF staff IS NULL OR NOT staff THEN
15241
15242             PERFORM 1
15243               FROM  asset.opac_visible_copies
15244               WHERE circ_lib IN ( SELECT * FROM search.explode_array( search_org_list ) )
15245                     AND record IN ( SELECT * FROM search.explode_array( core_result.records ) )
15246               LIMIT 1;
15247
15248             IF NOT FOUND THEN
15249                 -- RAISE NOTICE ' % were all visibility-excluded ... ', core_result.records;
15250                 excluded_count := excluded_count + 1;
15251                 CONTINUE;
15252             END IF;
15253
15254         ELSE
15255
15256             PERFORM 1
15257               FROM  asset.call_number cn
15258                     JOIN asset.copy cp ON (cp.call_number = cn.id)
15259                     JOIN actor.org_unit a ON (cp.circ_lib = a.id)
15260               WHERE NOT cn.deleted
15261                     AND NOT cp.deleted
15262                     AND cp.circ_lib IN ( SELECT * FROM search.explode_array( search_org_list ) )
15263                     AND cn.record IN ( SELECT * FROM search.explode_array( core_result.records ) )
15264               LIMIT 1;
15265
15266             IF NOT FOUND THEN
15267
15268                 PERFORM 1
15269                   FROM  asset.call_number cn
15270                   WHERE cn.record IN ( SELECT * FROM search.explode_array( core_result.records ) )
15271                   LIMIT 1;
15272
15273                 IF FOUND THEN
15274                     -- RAISE NOTICE ' % were all visibility-excluded ... ', core_result.records;
15275                     excluded_count := excluded_count + 1;
15276                     CONTINUE;
15277                 END IF;
15278
15279             END IF;
15280
15281         END IF;
15282
15283         visible_count := visible_count + 1;
15284
15285         current_res.id = core_result.id;
15286         current_res.rel = core_result.rel;
15287
15288         tmp_int := 1;
15289         IF metarecord THEN
15290             SELECT COUNT(DISTINCT s.source) INTO tmp_int FROM metabib.metarecord_source_map s WHERE s.metarecord = core_result.id;
15291         END IF;
15292
15293         IF tmp_int = 1 THEN
15294             current_res.record = core_result.records[1];
15295         ELSE
15296             current_res.record = NULL;
15297         END IF;
15298
15299         RETURN NEXT current_res;
15300
15301         IF visible_count % 1000 = 0 THEN
15302             -- RAISE NOTICE ' % visible so far ... ', visible_count;
15303         END IF;
15304
15305     END LOOP;
15306
15307     current_res.id = NULL;
15308     current_res.rel = NULL;
15309     current_res.record = NULL;
15310     current_res.total = total_count;
15311     current_res.checked = check_count;
15312     current_res.deleted = deleted_count;
15313     current_res.visible = visible_count;
15314     current_res.excluded = excluded_count;
15315
15316     CLOSE core_cursor;
15317
15318     RETURN NEXT current_res;
15319
15320 END;
15321 $func$ LANGUAGE PLPGSQL;
15322
15323 ALTER TABLE biblio.record_entry ADD COLUMN owner INT;
15324 ALTER TABLE biblio.record_entry
15325          ADD CONSTRAINT biblio_record_entry_owner_fkey FOREIGN KEY (owner)
15326          REFERENCES actor.org_unit (id)
15327          DEFERRABLE INITIALLY DEFERRED;
15328
15329 ALTER TABLE biblio.record_entry ADD COLUMN share_depth INT;
15330
15331 ALTER TABLE auditor.biblio_record_entry_history ADD COLUMN owner INT;
15332 ALTER TABLE auditor.biblio_record_entry_history ADD COLUMN share_depth INT;
15333
15334 DROP VIEW auditor.biblio_record_entry_lifecycle;
15335
15336 SELECT auditor.create_auditor_lifecycle( 'biblio', 'record_entry' );
15337
15338 CREATE OR REPLACE FUNCTION public.first_word ( TEXT ) RETURNS TEXT AS $$
15339         SELECT COALESCE(SUBSTRING( $1 FROM $_$^\S+$_$), '');
15340 $$ LANGUAGE SQL STRICT IMMUTABLE;
15341
15342 CREATE OR REPLACE FUNCTION public.normalize_space( TEXT ) RETURNS TEXT AS $$
15343     SELECT regexp_replace(regexp_replace(regexp_replace($1, E'\\n', ' ', 'g'), E'(?:^\\s+)|(\\s+$)', '', 'g'), E'\\s+', ' ', 'g');
15344 $$ LANGUAGE SQL STRICT IMMUTABLE;
15345
15346 CREATE OR REPLACE FUNCTION public.lowercase( TEXT ) RETURNS TEXT AS $$
15347     return lc(shift);
15348 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
15349
15350 CREATE OR REPLACE FUNCTION public.uppercase( TEXT ) RETURNS TEXT AS $$
15351     return uc(shift);
15352 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
15353
15354 CREATE OR REPLACE FUNCTION public.remove_diacritics( TEXT ) RETURNS TEXT AS $$
15355     use Unicode::Normalize;
15356
15357     my $x = NFD(shift);
15358     $x =~ s/\pM+//go;
15359     return $x;
15360
15361 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
15362
15363 CREATE OR REPLACE FUNCTION public.entityize( TEXT ) RETURNS TEXT AS $$
15364     use Unicode::Normalize;
15365
15366     my $x = NFC(shift);
15367     $x =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
15368     return $x;
15369
15370 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
15371
15372 CREATE OR REPLACE FUNCTION actor.org_unit_ancestor_setting( setting_name TEXT, org_id INT ) RETURNS SETOF actor.org_unit_setting AS $$
15373 DECLARE
15374     setting RECORD;
15375     cur_org INT;
15376 BEGIN
15377     cur_org := org_id;
15378     LOOP
15379         SELECT INTO setting * FROM actor.org_unit_setting WHERE org_unit = cur_org AND name = setting_name;
15380         IF FOUND THEN
15381             RETURN NEXT setting;
15382         END IF;
15383         SELECT INTO cur_org parent_ou FROM actor.org_unit WHERE id = cur_org;
15384         EXIT WHEN cur_org IS NULL;
15385     END LOOP;
15386     RETURN;
15387 END;
15388 $$ LANGUAGE plpgsql STABLE;
15389
15390 CREATE OR REPLACE FUNCTION acq.extract_holding_attr_table (lineitem int, tag text) RETURNS SETOF acq.flat_lineitem_holding_subfield AS $$
15391 DECLARE
15392     counter INT;
15393     lida    acq.flat_lineitem_holding_subfield%ROWTYPE;
15394 BEGIN
15395
15396     SELECT  COUNT(*) INTO counter
15397       FROM  oils_xpath_table(
15398                 'id',
15399                 'marc',
15400                 'acq.lineitem',
15401                 '//*[@tag="' || tag || '"]',
15402                 'id=' || lineitem
15403             ) as t(i int,c text);
15404
15405     FOR i IN 1 .. counter LOOP
15406         FOR lida IN
15407             SELECT  *
15408               FROM  (   SELECT  id,i,t,v
15409                           FROM  oils_xpath_table(
15410                                     'id',
15411                                     'marc',
15412                                     'acq.lineitem',
15413                                     '//*[@tag="' || tag || '"][position()=' || i || ']/*/@code|' ||
15414                                         '//*[@tag="' || tag || '"][position()=' || i || ']/*[@code]',
15415                                     'id=' || lineitem
15416                                 ) as t(id int,t text,v text)
15417                     )x
15418         LOOP
15419             RETURN NEXT lida;
15420         END LOOP;
15421     END LOOP;
15422
15423     RETURN;
15424 END;
15425 $$ LANGUAGE PLPGSQL;
15426
15427 CREATE OR REPLACE FUNCTION oils_i18n_xlate ( keytable TEXT, keyclass TEXT, keycol TEXT, identcol TEXT, keyvalue TEXT, raw_locale TEXT ) RETURNS TEXT AS $func$
15428 DECLARE
15429     locale      TEXT := REGEXP_REPLACE( REGEXP_REPLACE( raw_locale, E'[;, ].+$', '' ), E'_', '-', 'g' );
15430     language    TEXT := REGEXP_REPLACE( locale, E'-.+$', '' );
15431     result      config.i18n_core%ROWTYPE;
15432     fallback    TEXT;
15433     keyfield    TEXT := keyclass || '.' || keycol;
15434 BEGIN
15435
15436     -- Try the full locale
15437     SELECT  * INTO result
15438       FROM  config.i18n_core
15439       WHERE fq_field = keyfield
15440             AND identity_value = keyvalue
15441             AND translation = locale;
15442
15443     -- Try just the language
15444     IF NOT FOUND THEN
15445         SELECT  * INTO result
15446           FROM  config.i18n_core
15447           WHERE fq_field = keyfield
15448                 AND identity_value = keyvalue
15449                 AND translation = language;
15450     END IF;
15451
15452     -- Fall back to the string we passed in in the first place
15453     IF NOT FOUND THEN
15454     EXECUTE
15455             'SELECT ' ||
15456                 keycol ||
15457             ' FROM ' || keytable ||
15458             ' WHERE ' || identcol || ' = ' || quote_literal(keyvalue)
15459                 INTO fallback;
15460         RETURN fallback;
15461     END IF;
15462
15463     RETURN result.string;
15464 END;
15465 $func$ LANGUAGE PLPGSQL STABLE;
15466
15467 SELECT auditor.create_auditor ( 'acq', 'invoice' );
15468
15469 SELECT auditor.create_auditor ( 'acq', 'invoice_item' );
15470
15471 SELECT auditor.create_auditor ( 'acq', 'invoice_entry' );
15472
15473 INSERT INTO acq.cancel_reason ( id, org_unit, label, description, keep_debits ) VALUES (
15474     3, 1, 'delivered_but_lost',
15475     oils_i18n_gettext( 2, 'Delivered but not received; presumed lost', 'acqcr', 'label' ), TRUE );
15476
15477 CREATE TABLE config.global_flag (
15478     label   TEXT    NOT NULL
15479 ) INHERITS (config.internal_flag);
15480 ALTER TABLE config.global_flag ADD PRIMARY KEY (name);
15481
15482 INSERT INTO config.global_flag (name, label, enabled)
15483     VALUES (
15484         'cat.bib.use_id_for_tcn',
15485         oils_i18n_gettext(
15486             'cat.bib.use_id_for_tcn',
15487             'Cat: Use Internal ID for TCN Value',
15488             'cgf', 
15489             'label'
15490         ),
15491         TRUE
15492     );
15493
15494 -- resolves performance issue noted by EG Indiana
15495
15496 CREATE INDEX scecm_owning_copy_idx ON asset.stat_cat_entry_copy_map(owning_copy);
15497
15498 INSERT INTO config.metabib_class ( name, label ) VALUES ( 'identifier', oils_i18n_gettext('identifier', 'Identifier', 'cmc', 'name') );
15499
15500 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15501     (17, 'identifier', 'accession', oils_i18n_gettext(17, 'Accession Number', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="001"]/text()$$, TRUE );
15502 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15503     (18, 'identifier', 'isbn', oils_i18n_gettext(18, 'ISBN', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="020"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15504 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15505     (19, 'identifier', 'issn', oils_i18n_gettext(19, 'ISSN', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="022"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15506 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15507     (20, 'identifier', 'upc', oils_i18n_gettext(20, 'UPC', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="024" and ind1="1"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15508 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15509     (21, 'identifier', 'ismn', oils_i18n_gettext(21, 'ISMN', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="024" and ind1="2"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15510 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15511     (22, 'identifier', 'ean', oils_i18n_gettext(22, 'EAN', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="024" and ind1="3"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15512 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15513     (23, 'identifier', 'isrc', oils_i18n_gettext(23, 'ISRC', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="024" and ind1="0"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15514 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15515     (24, 'identifier', 'sici', oils_i18n_gettext(24, 'SICI', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="024" and ind1="4"]/marcxml:subfield[code="a" or code="z"]/text()$$, TRUE );
15516 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field ) VALUES
15517     (25, 'identifier', 'bibcn', oils_i18n_gettext(25, 'Local Free-Text Call Number', 'cmf', 'label'), 'marcxml', $$//marcxml:datafield[tag="099"]//text()$$, TRUE );
15518
15519 SELECT SETVAL('config.metabib_field_id_seq'::TEXT, (SELECT MAX(id) FROM config.metabib_field), TRUE);
15520  
15521
15522 DELETE FROM config.metabib_search_alias WHERE alias = 'dc.identifier';
15523
15524 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('id','identifier');
15525 INSERT INTO config.metabib_search_alias (alias,field_class) VALUES ('dc.identifier','identifier');
15526 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('eg.isbn','identifier', 18);
15527 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('eg.issn','identifier', 19);
15528 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('eg.upc','identifier', 20);
15529 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('eg.callnumber','identifier', 25);
15530
15531 CREATE TABLE metabib.identifier_field_entry (
15532         id              BIGSERIAL       PRIMARY KEY,
15533         source          BIGINT          NOT NULL,
15534         field           INT             NOT NULL,
15535         value           TEXT            NOT NULL,
15536         index_vector    tsvector        NOT NULL
15537 );
15538 CREATE TRIGGER metabib_identifier_field_entry_fti_trigger
15539         BEFORE UPDATE OR INSERT ON metabib.identifier_field_entry
15540         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('keyword');
15541
15542 CREATE INDEX metabib_identifier_field_entry_index_vector_idx ON metabib.identifier_field_entry USING GIST (index_vector);
15543 CREATE INDEX metabib_identifier_field_entry_value_idx ON metabib.identifier_field_entry
15544     (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
15545 CREATE INDEX metabib_identifier_field_entry_source_idx ON metabib.identifier_field_entry (source);
15546
15547 ALTER TABLE metabib.identifier_field_entry ADD CONSTRAINT metabib_identifier_field_entry_source_pkey
15548     FOREIGN KEY (source) REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED;
15549 ALTER TABLE metabib.identifier_field_entry ADD CONSTRAINT metabib_identifier_field_entry_field_pkey
15550     FOREIGN KEY (field) REFERENCES config.metabib_field (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED;
15551
15552 CREATE OR REPLACE FUNCTION public.translate_isbn1013( TEXT ) RETURNS TEXT AS $func$
15553     use Business::ISBN;
15554     use strict;
15555     use warnings;
15556
15557     # For each ISBN found in a single string containing a set of ISBNs:
15558     #   * Normalize an incoming ISBN to have the correct checksum and no hyphens
15559     #   * Convert an incoming ISBN10 or ISBN13 to its counterpart and return
15560
15561     my $input = shift;
15562     my $output = '';
15563
15564     foreach my $word (split(/\s/, $input)) {
15565         my $isbn = Business::ISBN->new($word);
15566
15567         # First check the checksum; if it is not valid, fix it and add the original
15568         # bad-checksum ISBN to the output
15569         if ($isbn && $isbn->is_valid_checksum() == Business::ISBN::BAD_CHECKSUM) {
15570             $output .= $isbn->isbn() . " ";
15571             $isbn->fix_checksum();
15572         }
15573
15574         # If we now have a valid ISBN, convert it to its counterpart ISBN10/ISBN13
15575         # and add the normalized original ISBN to the output
15576         if ($isbn && $isbn->is_valid()) {
15577             my $isbn_xlated = ($isbn->type eq "ISBN13") ? $isbn->as_isbn10 : $isbn->as_isbn13;
15578             $output .= $isbn->isbn . " ";
15579
15580             # If we successfully converted the ISBN to its counterpart, add the
15581             # converted ISBN to the output as well
15582             $output .= ($isbn_xlated->isbn . " ") if ($isbn_xlated);
15583         }
15584     }
15585     return $output if $output;
15586
15587     # If there were no valid ISBNs, just return the raw input
15588     return $input;
15589 $func$ LANGUAGE PLPERLU;
15590
15591 COMMENT ON FUNCTION public.translate_isbn1013(TEXT) IS $$
15592 /*
15593  * Copyright (C) 2010 Merrimack Valley Library Consortium
15594  * Jason Stephenson <jstephenson@mvlc.org>
15595  * Copyright (C) 2010 Laurentian University
15596  * Dan Scott <dscott@laurentian.ca>
15597  *
15598  * The translate_isbn1013 function takes an input ISBN and returns the
15599  * following in a single space-delimited string if the input ISBN is valid:
15600  *   - The normalized input ISBN (hyphens stripped)
15601  *   - The normalized input ISBN with a fixed checksum if the checksum was bad
15602  *   - The ISBN converted to its ISBN10 or ISBN13 counterpart, if possible
15603  */
15604 $$;
15605
15606 UPDATE config.metabib_field SET facet_field = FALSE WHERE id BETWEEN 17 AND 25;
15607 UPDATE config.metabib_field SET xpath = REPLACE(xpath,'marcxml','marc') WHERE id BETWEEN 17 AND 25;
15608 UPDATE config.metabib_field SET xpath = REPLACE(xpath,'tag','@tag') WHERE id BETWEEN 17 AND 25;
15609 UPDATE config.metabib_field SET xpath = REPLACE(xpath,'code','@code') WHERE id BETWEEN 17 AND 25;
15610 UPDATE config.metabib_field SET xpath = REPLACE(xpath,'"',E'\'') WHERE id BETWEEN 17 AND 25;
15611 UPDATE config.metabib_field SET xpath = REPLACE(xpath,'/text()','') WHERE id BETWEEN 17 AND 24;
15612
15613 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
15614         'ISBN 10/13 conversion',
15615         'Translate ISBN10 to ISBN13, and vice versa, for indexing purposes.',
15616         'translate_isbn1013',
15617         0
15618 );
15619
15620 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
15621         'Replace',
15622         'Replace all occurences of first parameter in the string with the second parameter.',
15623         'replace',
15624         2
15625 );
15626
15627 INSERT INTO config.metabib_field_index_norm_map (field,norm,pos)
15628     SELECT  m.id, i.id, 1
15629       FROM  config.metabib_field m,
15630             config.index_normalizer i
15631       WHERE i.func IN ('first_word')
15632             AND m.id IN (18);
15633
15634 INSERT INTO config.metabib_field_index_norm_map (field,norm,pos)
15635     SELECT  m.id, i.id, 2
15636       FROM  config.metabib_field m,
15637             config.index_normalizer i
15638       WHERE i.func IN ('translate_isbn1013')
15639             AND m.id IN (18);
15640
15641 INSERT INTO config.metabib_field_index_norm_map (field,norm,params)
15642     SELECT  m.id, i.id, $$['-','']$$
15643       FROM  config.metabib_field m,
15644             config.index_normalizer i
15645       WHERE i.func IN ('replace')
15646             AND m.id IN (19);
15647
15648 INSERT INTO config.metabib_field_index_norm_map (field,norm,params)
15649     SELECT  m.id, i.id, $$[' ','']$$
15650       FROM  config.metabib_field m,
15651             config.index_normalizer i
15652       WHERE i.func IN ('replace')
15653             AND m.id IN (19);
15654
15655 DELETE FROM config.metabib_field_index_norm_map WHERE norm IN (1,2) and field > 16;
15656
15657 UPDATE  config.metabib_field_index_norm_map
15658   SET   params = REPLACE(params,E'\'','"')
15659   WHERE params IS NOT NULL AND params <> '';
15660
15661 DROP TRIGGER IF EXISTS metabib_identifier_field_entry_fti_trigger ON metabib.identifier_field_entry;
15662
15663 CREATE TEXT SEARCH CONFIGURATION identifier ( COPY = title );
15664
15665 ALTER TABLE config.circ_modifier
15666         ADD COLUMN avg_wait_time INTERVAL;
15667
15668 --CREATE TABLE actor.usr_password_reset (
15669 --  id SERIAL PRIMARY KEY,
15670 --  uuid TEXT NOT NULL, 
15671 --  usr BIGINT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED, 
15672 --  request_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), 
15673 --  has_been_reset BOOL NOT NULL DEFAULT false
15674 --);
15675 --COMMENT ON TABLE actor.usr_password_reset IS $$
15676 --/*
15677 -- * Copyright (C) 2010 Laurentian University
15678 -- * Dan Scott <dscott@laurentian.ca>
15679 -- *
15680 -- * Self-serve password reset requests
15681 -- *
15682 -- * ****
15683 -- *
15684 -- * This program is free software; you can redistribute it and/or
15685 -- * modify it under the terms of the GNU General Public License
15686 -- * as published by the Free Software Foundation; either version 2
15687 -- * of the License, or (at your option) any later version.
15688 -- *
15689 -- * This program is distributed in the hope that it will be useful,
15690 -- * but WITHOUT ANY WARRANTY; without even the implied warranty of
15691 -- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15692 -- * GNU General Public License for more details.
15693 -- */
15694 --$$;
15695 --CREATE UNIQUE INDEX actor_usr_password_reset_uuid_idx ON actor.usr_password_reset (uuid);
15696 --CREATE INDEX actor_usr_password_reset_usr_idx ON actor.usr_password_reset (usr);
15697 --CREATE INDEX actor_usr_password_reset_request_time_idx ON actor.usr_password_reset (request_time);
15698 --CREATE INDEX actor_usr_password_reset_has_been_reset_idx ON actor.usr_password_reset (has_been_reset);
15699
15700 -- Use the identifier search class tsconfig
15701 DROP TRIGGER IF EXISTS metabib_identifier_field_entry_fti_trigger ON metabib.identifier_field_entry;
15702 CREATE TRIGGER metabib_identifier_field_entry_fti_trigger
15703     BEFORE INSERT OR UPDATE ON metabib.identifier_field_entry
15704     FOR EACH ROW
15705     EXECUTE PROCEDURE public.oils_tsearch2('identifier');
15706
15707 INSERT INTO config.global_flag (name,label,enabled)
15708     VALUES ('history.circ.retention_age',oils_i18n_gettext('history.circ.retention_age', 'Historical Circulation Retention Age', 'cgf', 'label'), TRUE);
15709 INSERT INTO config.global_flag (name,label,enabled)
15710     VALUES ('history.circ.retention_count',oils_i18n_gettext('history.circ.retention_count', 'Historical Circulations per Copy', 'cgf', 'label'), TRUE);
15711
15712 -- turn a JSON scalar into an SQL TEXT value
15713 CREATE OR REPLACE FUNCTION oils_json_to_text( TEXT ) RETURNS TEXT AS $f$
15714     use JSON::XS;                    
15715     my $json = shift();
15716     my $txt;
15717     eval { $txt = JSON::XS->new->allow_nonref->decode( $json ) };   
15718     return undef if ($@);
15719     return $txt
15720 $f$ LANGUAGE PLPERLU;
15721
15722 -- Return the list of circ chain heads in xact_start order that the user has chosen to "retain"
15723 CREATE OR REPLACE FUNCTION action.usr_visible_circs (usr_id INT) RETURNS SETOF action.circulation AS $func$
15724 DECLARE
15725     c               action.circulation%ROWTYPE;
15726     view_age        INTERVAL;
15727     usr_view_age    actor.usr_setting%ROWTYPE;
15728     usr_view_start  actor.usr_setting%ROWTYPE;
15729 BEGIN
15730     SELECT * INTO usr_view_age FROM actor.usr_setting WHERE usr = usr_id AND name = 'history.circ.retention_age';
15731     SELECT * INTO usr_view_start FROM actor.usr_setting WHERE usr = usr_id AND name = 'history.circ.retention_start';
15732
15733     IF usr_view_age.value IS NOT NULL AND usr_view_start.value IS NOT NULL THEN
15734         -- User opted in and supplied a retention age
15735         IF oils_json_to_text(usr_view_age.value)::INTERVAL > AGE(NOW(), oils_json_to_text(usr_view_start.value)::TIMESTAMPTZ) THEN
15736             view_age := AGE(NOW(), oils_json_to_text(usr_view_start.value)::TIMESTAMPTZ);
15737         ELSE
15738             view_age := oils_json_to_text(usr_view_age.value)::INTERVAL;
15739         END IF;
15740     ELSIF usr_view_start.value IS NOT NULL THEN
15741         -- User opted in
15742         view_age := AGE(NOW(), oils_json_to_text(usr_view_start.value)::TIMESTAMPTZ);
15743     ELSE
15744         -- User did not opt in
15745         RETURN;
15746     END IF;
15747
15748     FOR c IN
15749         SELECT  *
15750           FROM  action.circulation
15751           WHERE usr = usr_id
15752                 AND parent_circ IS NULL
15753                 AND xact_start > NOW() - view_age
15754           ORDER BY xact_start
15755     LOOP
15756         RETURN NEXT c;
15757     END LOOP;
15758
15759     RETURN;
15760 END;
15761 $func$ LANGUAGE PLPGSQL;
15762
15763 CREATE OR REPLACE FUNCTION action.purge_circulations () RETURNS INT AS $func$
15764 DECLARE
15765     usr_keep_age    actor.usr_setting%ROWTYPE;
15766     usr_keep_start  actor.usr_setting%ROWTYPE;
15767     org_keep_age    INTERVAL;
15768     org_keep_count  INT;
15769
15770     keep_age        INTERVAL;
15771
15772     target_acp      RECORD;
15773     circ_chain_head action.circulation%ROWTYPE;
15774     circ_chain_tail action.circulation%ROWTYPE;
15775
15776     purge_position  INT;
15777     count_purged    INT;
15778 BEGIN
15779
15780     count_purged := 0;
15781
15782     SELECT value::INTERVAL INTO org_keep_age FROM config.global_flag WHERE name = 'history.circ.retention_age' AND enabled;
15783
15784     SELECT value::INT INTO org_keep_count FROM config.global_flag WHERE name = 'history.circ.retention_count' AND enabled;
15785     IF org_keep_count IS NULL THEN
15786         RETURN count_purged; -- Gimme a count to keep, or I keep them all, forever
15787     END IF;
15788
15789     -- First, find copies with more than keep_count non-renewal circs
15790     FOR target_acp IN
15791         SELECT  target_copy,
15792                 COUNT(*) AS total_real_circs
15793           FROM  action.circulation
15794           WHERE parent_circ IS NULL
15795                 AND xact_finish IS NOT NULL
15796           GROUP BY target_copy
15797           HAVING COUNT(*) > org_keep_count
15798     LOOP
15799         purge_position := 0;
15800         -- And, for those, select circs that are finished and older than keep_age
15801         FOR circ_chain_head IN
15802             SELECT  *
15803               FROM  action.circulation
15804               WHERE target_copy = target_acp.target_copy
15805                     AND parent_circ IS NULL
15806               ORDER BY xact_start
15807         LOOP
15808
15809             -- Stop once we've purged enough circs to hit org_keep_count
15810             EXIT WHEN target_acp.total_real_circs - purge_position <= org_keep_count;
15811
15812             SELECT * INTO circ_chain_tail FROM action.circ_chain(circ_chain_head.id) ORDER BY xact_start DESC LIMIT 1;
15813             EXIT WHEN circ_chain_tail.xact_finish IS NULL;
15814
15815             -- Now get the user settings, if any, to block purging if the user wants to keep more circs
15816             usr_keep_age.value := NULL;
15817             SELECT * INTO usr_keep_age FROM actor.usr_setting WHERE usr = circ_chain_head.usr AND name = 'history.circ.retention_age';
15818
15819             usr_keep_start.value := NULL;
15820             SELECT * INTO usr_keep_start FROM actor.usr_setting WHERE usr = circ_chain_head.usr AND name = 'history.circ.retention_start';
15821
15822             IF usr_keep_age.value IS NOT NULL AND usr_keep_start.value IS NOT NULL THEN
15823                 IF oils_json_to_text(usr_keep_age.value)::INTERVAL > AGE(NOW(), oils_json_to_text(usr_keep_start.value)::TIMESTAMPTZ) THEN
15824                     keep_age := AGE(NOW(), oils_json_to_text(usr_keep_start.value)::TIMESTAMPTZ);
15825                 ELSE
15826                     keep_age := oils_json_to_text(usr_keep_age.value)::INTERVAL;
15827                 END IF;
15828             ELSIF usr_keep_start.value IS NOT NULL THEN
15829                 keep_age := AGE(NOW(), oils_json_to_text(usr_keep_start.value)::TIMESTAMPTZ);
15830             ELSE
15831                 keep_age := COALESCE( org_keep_age::INTERVAL, '2000 years'::INTERVAL );
15832             END IF;
15833
15834             EXIT WHEN AGE(NOW(), circ_chain_tail.xact_finish) < keep_age;
15835
15836             -- We've passed the purging tests, purge the circ chain starting at the end
15837             DELETE FROM action.circulation WHERE id = circ_chain_tail.id;
15838             WHILE circ_chain_tail.parent_circ IS NOT NULL LOOP
15839                 SELECT * INTO circ_chain_tail FROM action.circulation WHERE id = circ_chain_tail.parent_circ;
15840                 DELETE FROM action.circulation WHERE id = circ_chain_tail.id;
15841             END LOOP;
15842
15843             count_purged := count_purged + 1;
15844             purge_position := purge_position + 1;
15845
15846         END LOOP;
15847     END LOOP;
15848 END;
15849 $func$ LANGUAGE PLPGSQL;
15850
15851 CREATE OR REPLACE FUNCTION action.usr_visible_holds (usr_id INT) RETURNS SETOF action.hold_request AS $func$
15852 DECLARE
15853     h               action.hold_request%ROWTYPE;
15854     view_age        INTERVAL;
15855     view_count      INT;
15856     usr_view_count  actor.usr_setting%ROWTYPE;
15857     usr_view_age    actor.usr_setting%ROWTYPE;
15858     usr_view_start  actor.usr_setting%ROWTYPE;
15859 BEGIN
15860     SELECT * INTO usr_view_count FROM actor.usr_setting WHERE usr = usr_id AND name = 'history.hold.retention_count';
15861     SELECT * INTO usr_view_age FROM actor.usr_setting WHERE usr = usr_id AND name = 'history.hold.retention_age';
15862     SELECT * INTO usr_view_start FROM actor.usr_setting WHERE usr = usr_id AND name = 'history.hold.retention_start';
15863
15864     FOR h IN
15865         SELECT  *
15866           FROM  action.hold_request
15867           WHERE usr = usr_id
15868                 AND fulfillment_time IS NULL
15869                 AND cancel_time IS NULL
15870           ORDER BY request_time DESC
15871     LOOP
15872         RETURN NEXT h;
15873     END LOOP;
15874
15875     IF usr_view_start.value IS NULL THEN
15876         RETURN;
15877     END IF;
15878
15879     IF usr_view_age.value IS NOT NULL THEN
15880         -- User opted in and supplied a retention age
15881         IF oils_json_to_string(usr_view_age.value)::INTERVAL > AGE(NOW(), oils_json_to_string(usr_view_start.value)::TIMESTAMPTZ) THEN
15882             view_age := AGE(NOW(), oils_json_to_string(usr_view_start.value)::TIMESTAMPTZ);
15883         ELSE
15884             view_age := oils_json_to_string(usr_view_age.value)::INTERVAL;
15885         END IF;
15886     ELSE
15887         -- User opted in
15888         view_age := AGE(NOW(), oils_json_to_string(usr_view_start.value)::TIMESTAMPTZ);
15889     END IF;
15890
15891     IF usr_view_count.value IS NOT NULL THEN
15892         view_count := oils_json_to_text(usr_view_count.value)::INT;
15893     ELSE
15894         view_count := 1000;
15895     END IF;
15896
15897     -- show some fulfilled/canceled holds
15898     FOR h IN
15899         SELECT  *
15900           FROM  action.hold_request
15901           WHERE usr = usr_id
15902                 AND ( fulfillment_time IS NOT NULL OR cancel_time IS NOT NULL )
15903                 AND request_time > NOW() - view_age
15904           ORDER BY request_time DESC
15905           LIMIT view_count
15906     LOOP
15907         RETURN NEXT h;
15908     END LOOP;
15909
15910     RETURN;
15911 END;
15912 $func$ LANGUAGE PLPGSQL;
15913
15914 DROP TABLE IF EXISTS serial.bib_summary CASCADE;
15915
15916 DROP TABLE IF EXISTS serial.index_summary CASCADE;
15917
15918 DROP TABLE IF EXISTS serial.sup_summary CASCADE;
15919
15920 DROP TABLE IF EXISTS serial.issuance CASCADE;
15921
15922 DROP TABLE IF EXISTS serial.binding_unit CASCADE;
15923
15924 DROP TABLE IF EXISTS serial.subscription CASCADE;
15925
15926 CREATE TABLE asset.copy_template (
15927         id             SERIAL   PRIMARY KEY,
15928         owning_lib     INT      NOT NULL
15929                                 REFERENCES actor.org_unit (id)
15930                                 DEFERRABLE INITIALLY DEFERRED,
15931         creator        BIGINT   NOT NULL
15932                                 REFERENCES actor.usr (id)
15933                                 DEFERRABLE INITIALLY DEFERRED,
15934         editor         BIGINT   NOT NULL
15935                                 REFERENCES actor.usr (id)
15936                                 DEFERRABLE INITIALLY DEFERRED,
15937         create_date    TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
15938         edit_date      TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
15939         name           TEXT     NOT NULL,
15940         -- columns above this point are attributes of the template itself
15941         -- columns after this point are attributes of the copy this template modifies/creates
15942         circ_lib       INT      REFERENCES actor.org_unit (id)
15943                                 DEFERRABLE INITIALLY DEFERRED,
15944         status         INT      REFERENCES config.copy_status (id)
15945                                 DEFERRABLE INITIALLY DEFERRED,
15946         location       INT      REFERENCES asset.copy_location (id)
15947                                 DEFERRABLE INITIALLY DEFERRED,
15948         loan_duration  INT      CONSTRAINT valid_loan_duration CHECK (
15949                                     loan_duration IS NULL OR loan_duration IN (1,2,3)),
15950         fine_level     INT      CONSTRAINT valid_fine_level CHECK (
15951                                     fine_level IS NULL OR loan_duration IN (1,2,3)),
15952         age_protect    INT,
15953         circulate      BOOL,
15954         deposit        BOOL,
15955         ref            BOOL,
15956         holdable       BOOL,
15957         deposit_amount NUMERIC(6,2),
15958         price          NUMERIC(8,2),
15959         circ_modifier  TEXT,
15960         circ_as_type   TEXT,
15961         alert_message  TEXT,
15962         opac_visible   BOOL,
15963         floating       BOOL,
15964         mint_condition BOOL
15965 );
15966
15967 CREATE TABLE serial.subscription (
15968         id                     SERIAL       PRIMARY KEY,
15969         owning_lib             INT          NOT NULL DEFAULT 1
15970                                             REFERENCES actor.org_unit (id)
15971                                             ON DELETE SET NULL
15972                                             DEFERRABLE INITIALLY DEFERRED,
15973         start_date             TIMESTAMP WITH TIME ZONE     NOT NULL,
15974         end_date               TIMESTAMP WITH TIME ZONE,    -- interpret NULL as current subscription
15975         record_entry           BIGINT       REFERENCES biblio.record_entry (id)
15976                                             ON DELETE SET NULL
15977                                             DEFERRABLE INITIALLY DEFERRED,
15978         expected_date_offset   INTERVAL
15979         -- acquisitions/business-side tables link to here
15980 );
15981 CREATE INDEX serial_subscription_record_idx ON serial.subscription (record_entry);
15982 CREATE INDEX serial_subscription_owner_idx ON serial.subscription (owning_lib);
15983
15984 --at least one distribution per org_unit holding issues
15985 CREATE TABLE serial.distribution (
15986         id                    SERIAL  PRIMARY KEY,
15987         record_entry          BIGINT  REFERENCES serial.record_entry (id)
15988                                       ON DELETE SET NULL
15989                                       DEFERRABLE INITIALLY DEFERRED,
15990         summary_method        TEXT    CONSTRAINT sdist_summary_method_check CHECK (
15991                                           summary_method IS NULL
15992                                           OR summary_method IN ( 'add_to_sre',
15993                                           'merge_with_sre', 'use_sre_only',
15994                                           'use_sdist_only')),
15995         subscription          INT     NOT NULL
15996                                       REFERENCES serial.subscription (id)
15997                                                                   ON DELETE CASCADE
15998                                                                   DEFERRABLE INITIALLY DEFERRED,
15999         holding_lib           INT     NOT NULL
16000                                       REFERENCES actor.org_unit (id)
16001                                                                   DEFERRABLE INITIALLY DEFERRED,
16002         label                 TEXT    NOT NULL,
16003         receive_call_number   BIGINT  REFERENCES asset.call_number (id)
16004                                       DEFERRABLE INITIALLY DEFERRED,
16005         receive_unit_template INT     REFERENCES asset.copy_template (id)
16006                                       DEFERRABLE INITIALLY DEFERRED,
16007         bind_call_number      BIGINT  REFERENCES asset.call_number (id)
16008                                       DEFERRABLE INITIALLY DEFERRED,
16009         bind_unit_template    INT     REFERENCES asset.copy_template (id)
16010                                       DEFERRABLE INITIALLY DEFERRED,
16011         unit_label_prefix     TEXT,
16012         unit_label_suffix     TEXT
16013 );
16014 CREATE INDEX serial_distribution_sub_idx ON serial.distribution (subscription);
16015 CREATE INDEX serial_distribution_holding_lib_idx ON serial.distribution (holding_lib);
16016
16017 CREATE UNIQUE INDEX one_dist_per_sre_idx ON serial.distribution (record_entry);
16018
16019 CREATE TABLE serial.stream (
16020         id              SERIAL  PRIMARY KEY,
16021         distribution    INT     NOT NULL
16022                                 REFERENCES serial.distribution (id)
16023                                 ON DELETE CASCADE
16024                                 DEFERRABLE INITIALLY DEFERRED,
16025         routing_label   TEXT
16026 );
16027 CREATE INDEX serial_stream_dist_idx ON serial.stream (distribution);
16028
16029 CREATE UNIQUE INDEX label_once_per_dist
16030         ON serial.stream (distribution, routing_label)
16031         WHERE routing_label IS NOT NULL;
16032
16033 CREATE TABLE serial.routing_list_user (
16034         id             SERIAL       PRIMARY KEY,
16035         stream         INT          NOT NULL
16036                                     REFERENCES serial.stream
16037                                     ON DELETE CASCADE
16038                                     DEFERRABLE INITIALLY DEFERRED,
16039         pos            INT          NOT NULL DEFAULT 1,
16040         reader         INT          REFERENCES actor.usr
16041                                     ON DELETE CASCADE
16042                                     DEFERRABLE INITIALLY DEFERRED,
16043         department     TEXT,
16044         note           TEXT,
16045         CONSTRAINT one_pos_per_routing_list UNIQUE ( stream, pos ),
16046         CONSTRAINT reader_or_dept CHECK
16047         (
16048             -- Recipient is a person or a department, but not both
16049                 (reader IS NOT NULL AND department IS NULL) OR
16050                 (reader IS NULL AND department IS NOT NULL)
16051         )
16052 );
16053 CREATE INDEX serial_routing_list_user_stream_idx ON serial.routing_list_user (stream);
16054 CREATE INDEX serial_routing_list_user_reader_idx ON serial.routing_list_user (reader);
16055
16056 CREATE TABLE serial.caption_and_pattern (
16057         id           SERIAL       PRIMARY KEY,
16058         subscription INT          NOT NULL REFERENCES serial.subscription (id)
16059                                   ON DELETE CASCADE
16060                                   DEFERRABLE INITIALLY DEFERRED,
16061         type         TEXT         NOT NULL
16062                                   CONSTRAINT cap_type CHECK ( type in
16063                                   ( 'basic', 'supplement', 'index' )),
16064         create_date  TIMESTAMPTZ  NOT NULL DEFAULT now(),
16065         start_date   TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
16066         end_date     TIMESTAMP WITH TIME ZONE,
16067         active       BOOL         NOT NULL DEFAULT FALSE,
16068         pattern_code TEXT         NOT NULL,       -- must contain JSON
16069         enum_1       TEXT,
16070         enum_2       TEXT,
16071         enum_3       TEXT,
16072         enum_4       TEXT,
16073         enum_5       TEXT,
16074         enum_6       TEXT,
16075         chron_1      TEXT,
16076         chron_2      TEXT,
16077         chron_3      TEXT,
16078         chron_4      TEXT,
16079         chron_5      TEXT
16080 );
16081 CREATE INDEX serial_caption_and_pattern_sub_idx ON serial.caption_and_pattern (subscription);
16082
16083 CREATE TABLE serial.issuance (
16084         id              SERIAL    PRIMARY KEY,
16085         creator         INT       NOT NULL
16086                                   REFERENCES actor.usr (id)
16087                                                           DEFERRABLE INITIALLY DEFERRED,
16088         editor          INT       NOT NULL
16089                                   REFERENCES actor.usr (id)
16090                                   DEFERRABLE INITIALLY DEFERRED,
16091         create_date     TIMESTAMP WITH TIME ZONE        NOT NULL DEFAULT now(),
16092         edit_date       TIMESTAMP WITH TIME ZONE        NOT NULL DEFAULT now(),
16093         subscription    INT       NOT NULL
16094                                   REFERENCES serial.subscription (id)
16095                                   ON DELETE CASCADE
16096                                   DEFERRABLE INITIALLY DEFERRED,
16097         label           TEXT,
16098         date_published  TIMESTAMP WITH TIME ZONE,
16099         caption_and_pattern  INT  REFERENCES serial.caption_and_pattern (id)
16100                               DEFERRABLE INITIALLY DEFERRED,
16101         holding_code    TEXT,
16102         holding_type    TEXT      CONSTRAINT valid_holding_type CHECK
16103                                   (
16104                                       holding_type IS NULL
16105                                       OR holding_type IN ('basic','supplement','index')
16106                                   ),
16107         holding_link_id INT
16108         -- TODO: add columns for separate enumeration/chronology values
16109 );
16110 CREATE INDEX serial_issuance_sub_idx ON serial.issuance (subscription);
16111 CREATE INDEX serial_issuance_caption_and_pattern_idx ON serial.issuance (caption_and_pattern);
16112 CREATE INDEX serial_issuance_date_published_idx ON serial.issuance (date_published);
16113
16114 CREATE TABLE serial.unit (
16115         label           TEXT,
16116         label_sort_key  TEXT,
16117         contents        TEXT    NOT NULL
16118 ) INHERITS (asset.copy);
16119 CREATE UNIQUE INDEX unit_barcode_key ON serial.unit (barcode) WHERE deleted = FALSE OR deleted IS FALSE;
16120 CREATE INDEX unit_cn_idx ON serial.unit (call_number);
16121 CREATE INDEX unit_avail_cn_idx ON serial.unit (call_number);
16122 CREATE INDEX unit_creator_idx  ON serial.unit ( creator );
16123 CREATE INDEX unit_editor_idx   ON serial.unit ( editor );
16124
16125 ALTER TABLE serial.unit ADD PRIMARY KEY (id);
16126
16127 ALTER TABLE serial.unit ADD CONSTRAINT serial_unit_call_number_fkey FOREIGN KEY (call_number) REFERENCES asset.call_number (id) DEFERRABLE INITIALLY DEFERRED;
16128
16129 ALTER TABLE serial.unit ADD CONSTRAINT serial_unit_creator_fkey FOREIGN KEY (creator) REFERENCES actor.usr (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED;
16130
16131 ALTER TABLE serial.unit ADD CONSTRAINT serial_unit_editor_fkey FOREIGN KEY (editor) REFERENCES actor.usr (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED;
16132
16133 CREATE TABLE serial.item (
16134         id              SERIAL  PRIMARY KEY,
16135         creator         INT     NOT NULL
16136                                 REFERENCES actor.usr (id)
16137                                 DEFERRABLE INITIALLY DEFERRED,
16138         editor          INT     NOT NULL
16139                                 REFERENCES actor.usr (id)
16140                                 DEFERRABLE INITIALLY DEFERRED,
16141         create_date     TIMESTAMP WITH TIME ZONE        NOT NULL DEFAULT now(),
16142         edit_date       TIMESTAMP WITH TIME ZONE        NOT NULL DEFAULT now(),
16143         issuance        INT     NOT NULL
16144                                 REFERENCES serial.issuance (id)
16145                                 ON DELETE CASCADE
16146                                 DEFERRABLE INITIALLY DEFERRED,
16147         stream          INT     NOT NULL
16148                                 REFERENCES serial.stream (id)
16149                                 ON DELETE CASCADE
16150                                 DEFERRABLE INITIALLY DEFERRED,
16151         unit            INT     REFERENCES serial.unit (id)
16152                                 ON DELETE SET NULL
16153                                 DEFERRABLE INITIALLY DEFERRED,
16154         uri             INT     REFERENCES asset.uri (id)
16155                                 ON DELETE SET NULL
16156                                 DEFERRABLE INITIALLY DEFERRED,
16157         date_expected   TIMESTAMP WITH TIME ZONE,
16158         date_received   TIMESTAMP WITH TIME ZONE,
16159         status          TEXT    CONSTRAINT valid_status CHECK (
16160                                status IN ( 'Bindery', 'Bound', 'Claimed', 'Discarded',
16161                                'Expected', 'Not Held', 'Not Published', 'Received'))
16162                             DEFAULT 'Expected',
16163         shadowed        BOOL    NOT NULL DEFAULT FALSE
16164 );
16165 CREATE INDEX serial_item_stream_idx ON serial.item (stream);
16166 CREATE INDEX serial_item_issuance_idx ON serial.item (issuance);
16167 CREATE INDEX serial_item_unit_idx ON serial.item (unit);
16168 CREATE INDEX serial_item_uri_idx ON serial.item (uri);
16169 CREATE INDEX serial_item_date_received_idx ON serial.item (date_received);
16170 CREATE INDEX serial_item_status_idx ON serial.item (status);
16171
16172 CREATE TABLE serial.item_note (
16173         id          SERIAL  PRIMARY KEY,
16174         item        INT     NOT NULL
16175                             REFERENCES serial.item (id)
16176                             ON DELETE CASCADE
16177                             DEFERRABLE INITIALLY DEFERRED,
16178         creator     INT     NOT NULL
16179                             REFERENCES actor.usr (id)
16180                             DEFERRABLE INITIALLY DEFERRED,
16181         create_date TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
16182         pub         BOOL    NOT NULL    DEFAULT FALSE,
16183         title       TEXT    NOT NULL,
16184         value       TEXT    NOT NULL
16185 );
16186 CREATE INDEX serial_item_note_item_idx ON serial.item_note (item);
16187
16188 CREATE TABLE serial.basic_summary (
16189         id                  SERIAL  PRIMARY KEY,
16190         distribution        INT     NOT NULL
16191                                     REFERENCES serial.distribution (id)
16192                                     ON DELETE CASCADE
16193                                     DEFERRABLE INITIALLY DEFERRED,
16194         generated_coverage  TEXT    NOT NULL,
16195         textual_holdings    TEXT,
16196         show_generated      BOOL    NOT NULL DEFAULT TRUE
16197 );
16198 CREATE INDEX serial_basic_summary_dist_idx ON serial.basic_summary (distribution);
16199
16200 CREATE TABLE serial.supplement_summary (
16201         id                  SERIAL  PRIMARY KEY,
16202         distribution        INT     NOT NULL
16203                                     REFERENCES serial.distribution (id)
16204                                     ON DELETE CASCADE
16205                                     DEFERRABLE INITIALLY DEFERRED,
16206         generated_coverage  TEXT    NOT NULL,
16207         textual_holdings    TEXT,
16208         show_generated      BOOL    NOT NULL DEFAULT TRUE
16209 );
16210 CREATE INDEX serial_supplement_summary_dist_idx ON serial.supplement_summary (distribution);
16211
16212 CREATE TABLE serial.index_summary (
16213         id                  SERIAL  PRIMARY KEY,
16214         distribution        INT     NOT NULL
16215                                     REFERENCES serial.distribution (id)
16216                                     ON DELETE CASCADE
16217                                     DEFERRABLE INITIALLY DEFERRED,
16218         generated_coverage  TEXT    NOT NULL,
16219         textual_holdings    TEXT,
16220         show_generated      BOOL    NOT NULL DEFAULT TRUE
16221 );
16222 CREATE INDEX serial_index_summary_dist_idx ON serial.index_summary (distribution);
16223
16224 -- DELETE FROM action_trigger.environment WHERE event_def IN (29,30); DELETE FROM action_trigger.event where event_def IN (29,30); DELETE FROM action_trigger.event_definition WHERE id IN (29,30); DELETE FROM action_trigger.hook WHERE key IN ('money.format.payment_receipt.email','money.format.payment_receipt.print'); DELETE FROM config.upgrade_log WHERE version = '0289'; -- from testing, this sql will remove these events, etc.
16225
16226 DROP INDEX IF EXISTS authority.authority_record_unique_tcn;
16227 CREATE UNIQUE INDEX authority_record_unique_tcn ON authority.record_entry (arn_source,arn_value) WHERE deleted = FALSE OR deleted IS FALSE;
16228
16229 DROP INDEX IF EXISTS asset.asset_call_number_label_once_per_lib;
16230 CREATE UNIQUE INDEX asset_call_number_label_once_per_lib ON asset.call_number (record, owning_lib, label) WHERE deleted = FALSE OR deleted IS FALSE;
16231
16232 DROP INDEX IF EXISTS biblio.biblio_record_unique_tcn;
16233 CREATE UNIQUE INDEX biblio_record_unique_tcn ON biblio.record_entry (tcn_value) WHERE deleted = FALSE OR deleted IS FALSE;
16234
16235 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_val INTERVAL )
16236 RETURNS INTEGER AS $$
16237 BEGIN
16238         RETURN EXTRACT( EPOCH FROM interval_val );
16239 END;
16240 $$ LANGUAGE plpgsql;
16241
16242 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_string TEXT )
16243 RETURNS INTEGER AS $$
16244 BEGIN
16245         RETURN config.interval_to_seconds( interval_string::INTERVAL );
16246 END;
16247 $$ LANGUAGE plpgsql;
16248
16249 INSERT INTO container.biblio_record_entry_bucket_type( code, label ) VALUES (
16250     'temp',
16251     oils_i18n_gettext(
16252         'temp',
16253         'Temporary bucket which gets deleted after use.',
16254         'cbrebt',
16255         'label'
16256     )
16257 );
16258
16259 -- DELETE FROM action_trigger.environment WHERE event_def IN (31,32); DELETE FROM action_trigger.event where event_def IN (31,32); DELETE FROM action_trigger.event_definition WHERE id IN (31,32); DELETE FROM action_trigger.hook WHERE key IN ('biblio.format.record_entry.email','biblio.format.record_entry.print'); DELETE FROM action_trigger.cleanup WHERE module = 'DeleteTempBiblioBucket'; DELETE FROM container.biblio_record_entry_bucket_item WHERE bucket IN (SELECT id FROM container.biblio_record_entry_bucket WHERE btype = 'temp'); DELETE FROM container.biblio_record_entry_bucket WHERE btype = 'temp'; DELETE FROM container.biblio_record_entry_bucket_type WHERE code = 'temp'; DELETE FROM config.upgrade_log WHERE version = '0294'; -- from testing, this sql will remove these events, etc.
16260
16261 CREATE OR REPLACE FUNCTION biblio.check_marcxml_well_formed () RETURNS TRIGGER AS $func$
16262 BEGIN
16263
16264     IF xml_is_well_formed(NEW.marc) THEN
16265         RETURN NEW;
16266     ELSE
16267         RAISE EXCEPTION 'Attempted to % MARCXML that is not well formed', TG_OP;
16268     END IF;
16269     
16270 END;
16271 $func$ LANGUAGE PLPGSQL;
16272
16273 CREATE TRIGGER a_marcxml_is_well_formed BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.check_marcxml_well_formed();
16274
16275 CREATE TRIGGER a_marcxml_is_well_formed BEFORE INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.check_marcxml_well_formed();
16276
16277 ALTER TABLE serial.record_entry
16278         ALTER COLUMN marc DROP NOT NULL;
16279
16280 insert INTO CONFIG.xml_transform(name, namespace_uri, prefix, xslt)
16281 VALUES ('marc21expand880', 'http://www.loc.gov/MARC21/slim', 'marc', $$<?xml version="1.0" encoding="UTF-8"?>
16282 <xsl:stylesheet
16283     xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
16284     xmlns:marc="http://www.loc.gov/MARC21/slim"
16285     version="1.0">
16286 <!--
16287 Copyright (C) 2010  Equinox Software, Inc.
16288 Galen Charlton <gmc@esilibrary.cOM.
16289
16290 This program is free software; you can redistribute it and/or
16291 modify it under the terms of the GNU General Public License
16292 as published by the Free Software Foundation; either version 2
16293 of the License, or (at your option) any later version.
16294
16295 This program is distributed in the hope that it will be useful,
16296 but WITHOUT ANY WARRANTY; without even the implied warranty of
16297 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16298 GNU General Public License for more details.
16299
16300 marc21_expand_880.xsl - stylesheet used during indexing to
16301                         map alternative graphical representations
16302                         of MARC fields stored in 880 fields
16303                         to the corresponding tag name and value.
16304
16305 For example, if a MARC record for a Chinese book has
16306
16307 245.00 $6 880-01 $a Ba shi san nian duan pian xiao shuo xuan
16308 880.00 $6 245-01/$1 $a八十三年短篇小說選
16309
16310 this stylesheet will transform it to the equivalent of
16311
16312 245.00 $6 880-01 $a Ba shi san nian duan pian xiao shuo xuan
16313 245.00 $6 245-01/$1 $a八十三年短篇小說選
16314
16315 -->
16316     <xsl:output encoding="UTF-8" indent="yes" method="xml"/>
16317
16318     <xsl:template match="@*|node()">
16319         <xsl:copy>
16320             <xsl:apply-templates select="@*|node()"/>
16321         </xsl:copy>
16322     </xsl:template>
16323
16324     <xsl:template match="//marc:datafield[@tag='880']">
16325         <xsl:if test="./marc:subfield[@code='6'] and string-length(./marc:subfield[@code='6']) &gt;= 6">
16326             <marc:datafield>
16327                 <xsl:attribute name="tag">
16328                     <xsl:value-of select="substring(./marc:subfield[@code='6'], 1, 3)" />
16329                 </xsl:attribute>
16330                 <xsl:attribute name="ind1">
16331                     <xsl:value-of select="@ind1" />
16332                 </xsl:attribute>
16333                 <xsl:attribute name="ind2">
16334                     <xsl:value-of select="@ind2" />
16335                 </xsl:attribute>
16336                 <xsl:apply-templates />
16337             </marc:datafield>
16338         </xsl:if>
16339     </xsl:template>
16340     
16341 </xsl:stylesheet>$$);
16342
16343 -- fix broken prefix and namespace URI for the
16344 -- mods32 transform found in some databases
16345 -- that started out at version 1.2 or earlier
16346 UPDATE config.xml_transform
16347 SET namespace_uri = 'http://www.loc.gov/mods/v3'
16348 WHERE name = 'mods32'
16349 AND namespace_uri = 'http://www.loc.gov/mods/'
16350 AND xslt LIKE '%xmlns="http://www.loc.gov/mods/v3"%';
16351
16352 UPDATE config.xml_transform
16353 SET prefix = 'mods32'
16354 WHERE name = 'mods32'
16355 AND prefix = 'mods'
16356 AND EXISTS (SELECT xpath FROM config.metabib_field WHERE xpath ~ 'mods32:');
16357
16358 -- Splitting the ingest trigger up into little bits
16359
16360 CREATE TEMPORARY TABLE eg_0301_check_if_has_contents (
16361     flag INTEGER PRIMARY KEY
16362 ) ON COMMIT DROP;
16363 INSERT INTO eg_0301_check_if_has_contents VALUES (1);
16364
16365 -- cause failure if either of the tables we want to drop have rows
16366 INSERT INTO eg_0301_check_if_has_contents SELECT 1 FROM asset.copy_transparency LIMIT 1;
16367 INSERT INTO eg_0301_check_if_has_contents SELECT 1 FROM asset.copy_transparency_map LIMIT 1;
16368
16369 DROP TABLE IF EXISTS asset.copy_transparency_map;
16370 DROP TABLE IF EXISTS asset.copy_transparency;
16371
16372 UPDATE config.metabib_field SET facet_xpath = '//' || facet_xpath WHERE facet_xpath IS NOT NULL;
16373
16374 -- We won't necessarily use all of these, but they are here for completeness.
16375 -- Source is the EDI spec 1229 codelist, eg: http://www.stylusstudio.com/edifact/D04B/1229.htm
16376 -- Values are the EDI code value + 1000
16377
16378 INSERT INTO acq.cancel_reason (keep_debits, id, org_unit, label, description) VALUES 
16379 ('t',(  1+1000), 1, 'Added',     'The information is to be or has been added.'),
16380 ('f',(  2+1000), 1, 'Deleted',   'The information is to be or has been deleted.'),
16381 ('t',(  3+1000), 1, 'Changed',   'The information is to be or has been changed.'),
16382 ('t',(  4+1000), 1, 'No action',                  'This line item is not affected by the actual message.'),
16383 ('t',(  5+1000), 1, 'Accepted without amendment', 'This line item is entirely accepted by the seller.'),
16384 ('t',(  6+1000), 1, 'Accepted with amendment',    'This line item is accepted but amended by the seller.'),
16385 ('f',(  7+1000), 1, 'Not accepted',               'This line item is not accepted by the seller.'),
16386 ('t',(  8+1000), 1, 'Schedule only', 'Code specifying that the message is a schedule only.'),
16387 ('t',(  9+1000), 1, 'Amendments',    'Code specifying that amendments are requested/notified.'),
16388 ('f',( 10+1000), 1, 'Not found',   'This line item is not found in the referenced message.'),
16389 ('t',( 11+1000), 1, 'Not amended', 'This line is not amended by the buyer.'),
16390 ('t',( 12+1000), 1, 'Line item numbers changed', 'Code specifying that the line item numbers have changed.'),
16391 ('t',( 13+1000), 1, 'Buyer has deducted amount', 'Buyer has deducted amount from payment.'),
16392 ('t',( 14+1000), 1, 'Buyer claims against invoice', 'Buyer has a claim against an outstanding invoice.'),
16393 ('t',( 15+1000), 1, 'Charge back by seller', 'Factor has been requested to charge back the outstanding item.'),
16394 ('t',( 16+1000), 1, 'Seller will issue credit note', 'Seller agrees to issue a credit note.'),
16395 ('t',( 17+1000), 1, 'Terms changed for new terms', 'New settlement terms have been agreed.'),
16396 ('t',( 18+1000), 1, 'Abide outcome of negotiations', 'Factor agrees to abide by the outcome of negotiations between seller and buyer.'),
16397 ('t',( 19+1000), 1, 'Seller rejects dispute', 'Seller does not accept validity of dispute.'),
16398 ('t',( 20+1000), 1, 'Settlement', 'The reported situation is settled.'),
16399 ('t',( 21+1000), 1, 'No delivery', 'Code indicating that no delivery will be required.'),
16400 ('t',( 22+1000), 1, 'Call-off delivery', 'A request for delivery of a particular quantity of goods to be delivered on a particular date (or within a particular period).'),
16401 ('t',( 23+1000), 1, 'Proposed amendment', 'A code used to indicate an amendment suggested by the sender.'),
16402 ('t',( 24+1000), 1, 'Accepted with amendment, no confirmation required', 'Accepted with changes which require no confirmation.'),
16403 ('t',( 25+1000), 1, 'Equipment provisionally repaired', 'The equipment or component has been provisionally repaired.'),
16404 ('t',( 26+1000), 1, 'Included', 'Code indicating that the entity is included.'),
16405 ('t',( 27+1000), 1, 'Verified documents for coverage', 'Upon receipt and verification of documents we shall cover you when due as per your instructions.'),
16406 ('t',( 28+1000), 1, 'Verified documents for debit',    'Upon receipt and verification of documents we shall authorize you to debit our account with you when due.'),
16407 ('t',( 29+1000), 1, 'Authenticated advice for coverage',      'On receipt of your authenticated advice we shall cover you when due as per your instructions.'),
16408 ('t',( 30+1000), 1, 'Authenticated advice for authorization', 'On receipt of your authenticated advice we shall authorize you to debit our account with you when due.'),
16409 ('t',( 31+1000), 1, 'Authenticated advice for credit',        'On receipt of your authenticated advice we shall credit your account with us when due.'),
16410 ('t',( 32+1000), 1, 'Credit advice requested for direct debit',           'A credit advice is requested for the direct debit.'),
16411 ('t',( 33+1000), 1, 'Credit advice and acknowledgement for direct debit', 'A credit advice and acknowledgement are requested for the direct debit.'),
16412 ('t',( 34+1000), 1, 'Inquiry',     'Request for information.'),
16413 ('t',( 35+1000), 1, 'Checked',     'Checked.'),
16414 ('t',( 36+1000), 1, 'Not checked', 'Not checked.'),
16415 ('f',( 37+1000), 1, 'Cancelled',   'Discontinued.'),
16416 ('t',( 38+1000), 1, 'Replaced',    'Provide a replacement.'),
16417 ('t',( 39+1000), 1, 'New',         'Not existing before.'),
16418 ('t',( 40+1000), 1, 'Agreed',      'Consent.'),
16419 ('t',( 41+1000), 1, 'Proposed',    'Put forward for consideration.'),
16420 ('t',( 42+1000), 1, 'Already delivered', 'Delivery has taken place.'),
16421 ('t',( 43+1000), 1, 'Additional subordinate structures will follow', 'Additional subordinate structures will follow the current hierarchy level.'),
16422 ('t',( 44+1000), 1, 'Additional subordinate structures will not follow', 'No additional subordinate structures will follow the current hierarchy level.'),
16423 ('t',( 45+1000), 1, 'Result opposed',         'A notification that the result is opposed.'),
16424 ('t',( 46+1000), 1, 'Auction held',           'A notification that an auction was held.'),
16425 ('t',( 47+1000), 1, 'Legal action pursued',   'A notification that legal action has been pursued.'),
16426 ('t',( 48+1000), 1, 'Meeting held',           'A notification that a meeting was held.'),
16427 ('t',( 49+1000), 1, 'Result set aside',       'A notification that the result has been set aside.'),
16428 ('t',( 50+1000), 1, 'Result disputed',        'A notification that the result has been disputed.'),
16429 ('t',( 51+1000), 1, 'Countersued',            'A notification that a countersuit has been filed.'),
16430 ('t',( 52+1000), 1, 'Pending',                'A notification that an action is awaiting settlement.'),
16431 ('f',( 53+1000), 1, 'Court action dismissed', 'A notification that a court action will no longer be heard.'),
16432 ('t',( 54+1000), 1, 'Referred item, accepted', 'The item being referred to has been accepted.'),
16433 ('f',( 55+1000), 1, 'Referred item, rejected', 'The item being referred to has been rejected.'),
16434 ('t',( 56+1000), 1, 'Debit advice statement line',  'Notification that the statement line is a debit advice.'),
16435 ('t',( 57+1000), 1, 'Credit advice statement line', 'Notification that the statement line is a credit advice.'),
16436 ('t',( 58+1000), 1, 'Grouped credit advices',       'Notification that the credit advices are grouped.'),
16437 ('t',( 59+1000), 1, 'Grouped debit advices',        'Notification that the debit advices are grouped.'),
16438 ('t',( 60+1000), 1, 'Registered', 'The name is registered.'),
16439 ('f',( 61+1000), 1, 'Payment denied', 'The payment has been denied.'),
16440 ('t',( 62+1000), 1, 'Approved as amended', 'Approved with modifications.'),
16441 ('t',( 63+1000), 1, 'Approved as submitted', 'The request has been approved as submitted.'),
16442 ('f',( 64+1000), 1, 'Cancelled, no activity', 'Cancelled due to the lack of activity.'),
16443 ('t',( 65+1000), 1, 'Under investigation', 'Investigation is being done.'),
16444 ('t',( 66+1000), 1, 'Initial claim received', 'Notification that the initial claim was received.'),
16445 ('f',( 67+1000), 1, 'Not in process', 'Not in process.'),
16446 ('f',( 68+1000), 1, 'Rejected, duplicate', 'Rejected because it is a duplicate.'),
16447 ('f',( 69+1000), 1, 'Rejected, resubmit with corrections', 'Rejected but may be resubmitted when corrected.'),
16448 ('t',( 70+1000), 1, 'Pending, incomplete', 'Pending because of incomplete information.'),
16449 ('t',( 71+1000), 1, 'Under field office investigation', 'Investigation by the field is being done.'),
16450 ('t',( 72+1000), 1, 'Pending, awaiting additional material', 'Pending awaiting receipt of additional material.'),
16451 ('t',( 73+1000), 1, 'Pending, awaiting review', 'Pending while awaiting review.'),
16452 ('t',( 74+1000), 1, 'Reopened', 'Opened again.'),
16453 ('t',( 75+1000), 1, 'Processed by primary, forwarded to additional payer(s)',   'This request has been processed by the primary payer and sent to additional payer(s).'),
16454 ('t',( 76+1000), 1, 'Processed by secondary, forwarded to additional payer(s)', 'This request has been processed by the secondary payer and sent to additional payer(s).'),
16455 ('t',( 77+1000), 1, 'Processed by tertiary, forwarded to additional payer(s)',  'This request has been processed by the tertiary payer and sent to additional payer(s).'),
16456 ('t',( 78+1000), 1, 'Previous payment decision reversed', 'A previous payment decision has been reversed.'),
16457 ('t',( 79+1000), 1, 'Not our claim, forwarded to another payer(s)', 'A request does not belong to this payer but has been forwarded to another payer(s).'),
16458 ('t',( 80+1000), 1, 'Transferred to correct insurance carrier', 'The request has been transferred to the correct insurance carrier for processing.'),
16459 ('t',( 81+1000), 1, 'Not paid, predetermination pricing only', 'Payment has not been made and the enclosed response is predetermination pricing only.'),
16460 ('t',( 82+1000), 1, 'Documentation claim', 'The claim is for documentation purposes only, no payment required.'),
16461 ('t',( 83+1000), 1, 'Reviewed', 'Assessed.'),
16462 ('f',( 84+1000), 1, 'Repriced', 'This price was changed.'),
16463 ('t',( 85+1000), 1, 'Audited', 'An official examination has occurred.'),
16464 ('t',( 86+1000), 1, 'Conditionally paid', 'Payment has been conditionally made.'),
16465 ('t',( 87+1000), 1, 'On appeal', 'Reconsideration of the decision has been applied for.'),
16466 ('t',( 88+1000), 1, 'Closed', 'Shut.'),
16467 ('t',( 89+1000), 1, 'Reaudited', 'A subsequent official examination has occurred.'),
16468 ('t',( 90+1000), 1, 'Reissued', 'Issued again.'),
16469 ('t',( 91+1000), 1, 'Closed after reopening', 'Reopened and then closed.'),
16470 ('t',( 92+1000), 1, 'Redetermined', 'Determined again or differently.'),
16471 ('t',( 93+1000), 1, 'Processed as primary',   'Processed as the first.'),
16472 ('t',( 94+1000), 1, 'Processed as secondary', 'Processed as the second.'),
16473 ('t',( 95+1000), 1, 'Processed as tertiary',  'Processed as the third.'),
16474 ('t',( 96+1000), 1, 'Correction of error', 'A correction to information previously communicated which contained an error.'),
16475 ('t',( 97+1000), 1, 'Single credit item of a group', 'Notification that the credit item is a single credit item of a group of credit items.'),
16476 ('t',( 98+1000), 1, 'Single debit item of a group',  'Notification that the debit item is a single debit item of a group of debit items.'),
16477 ('t',( 99+1000), 1, 'Interim response', 'The response is an interim one.'),
16478 ('t',(100+1000), 1, 'Final response',   'The response is an final one.'),
16479 ('t',(101+1000), 1, 'Debit advice requested', 'A debit advice is requested for the transaction.'),
16480 ('t',(102+1000), 1, 'Transaction not impacted', 'Advice that the transaction is not impacted.'),
16481 ('t',(103+1000), 1, 'Patient to be notified',                    'The action to take is to notify the patient.'),
16482 ('t',(104+1000), 1, 'Healthcare provider to be notified',        'The action to take is to notify the healthcare provider.'),
16483 ('t',(105+1000), 1, 'Usual general practitioner to be notified', 'The action to take is to notify the usual general practitioner.'),
16484 ('t',(106+1000), 1, 'Advice without details', 'An advice without details is requested or notified.'),
16485 ('t',(107+1000), 1, 'Advice with details', 'An advice with details is requested or notified.'),
16486 ('t',(108+1000), 1, 'Amendment requested', 'An amendment is requested.'),
16487 ('t',(109+1000), 1, 'For information', 'Included for information only.'),
16488 ('f',(110+1000), 1, 'Withdraw', 'A code indicating discontinuance or retraction.'),
16489 ('t',(111+1000), 1, 'Delivery date change', 'The action / notiification is a change of the delivery date.'),
16490 ('f',(112+1000), 1, 'Quantity change',      'The action / notification is a change of quantity.'),
16491 ('t',(113+1000), 1, 'Resale and claim', 'The identified items have been sold by the distributor to the end customer, and compensation for the loss of inventory value is claimed.'),
16492 ('t',(114+1000), 1, 'Resale',           'The identified items have been sold by the distributor to the end customer.'),
16493 ('t',(115+1000), 1, 'Prior addition', 'This existing line item becomes available at an earlier date.');
16494
16495 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath, facet_field, search_field ) VALUES
16496     (26, 'identifier', 'arcn', oils_i18n_gettext(26, 'Authority record control number', 'cmf', 'label'), 'marcxml', $$//marc:subfield[@code='0']$$, TRUE, FALSE );
16497  
16498 SELECT SETVAL('config.metabib_field_id_seq'::TEXT, (SELECT MAX(id) FROM config.metabib_field), TRUE);
16499  
16500 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
16501         'Remove Parenthesized Substring',
16502         'Remove any parenthesized substrings from the extracted text, such as the agency code preceding authority record control numbers in subfield 0.',
16503         'remove_paren_substring',
16504         0
16505 );
16506
16507 INSERT INTO config.index_normalizer (name, description, func, param_count) VALUES (
16508         'Trim Surrounding Space',
16509         'Trim leading and trailing spaces from extracted text.',
16510         'btrim',
16511         0
16512 );
16513
16514 INSERT INTO config.metabib_field_index_norm_map (field,norm,pos)
16515     SELECT  m.id,
16516             i.id,
16517             -2
16518       FROM  config.metabib_field m,
16519             config.index_normalizer i
16520       WHERE i.func IN ('remove_paren_substring')
16521             AND m.id IN (26);
16522
16523 INSERT INTO config.metabib_field_index_norm_map (field,norm,pos)
16524     SELECT  m.id,
16525             i.id,
16526             -1
16527       FROM  config.metabib_field m,
16528             config.index_normalizer i
16529       WHERE i.func IN ('btrim')
16530             AND m.id IN (26);
16531
16532 -- Function that takes, and returns, marcxml and compiles an embedded ruleset for you, and they applys it
16533 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
16534 DECLARE
16535     dyn_profile     vandelay.compile_profile%ROWTYPE;
16536     replace_rule    TEXT;
16537     tmp_marc        TEXT;
16538     trgt_marc        TEXT;
16539     tmpl_marc        TEXT;
16540     match_count     INT;
16541 BEGIN
16542
16543     IF target_marc IS NULL OR template_marc IS NULL THEN
16544         -- RAISE NOTICE 'no marc for target or template record';
16545         RETURN NULL;
16546     END IF;
16547
16548     dyn_profile := vandelay.compile_profile( template_marc );
16549
16550     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
16551         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
16552         RETURN NULL;
16553     END IF;
16554
16555     IF dyn_profile.replace_rule <> '' THEN
16556         trgt_marc = target_marc;
16557         tmpl_marc = template_marc;
16558         replace_rule = dyn_profile.replace_rule;
16559     ELSE
16560         tmp_marc = target_marc;
16561         trgt_marc = template_marc;
16562         tmpl_marc = tmp_marc;
16563         replace_rule = dyn_profile.preserve_rule;
16564     END IF;
16565
16566     RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
16567
16568 END;
16569 $$ LANGUAGE PLPGSQL;
16570
16571 -- Function to generate an ephemeral overlay template from an authority record
16572 CREATE OR REPLACE FUNCTION authority.generate_overlay_template ( TEXT, BIGINT ) RETURNS TEXT AS $func$
16573
16574     use MARC::Record;
16575     use MARC::File::XML (BinaryEncoding => 'UTF-8');
16576
16577     my $xml = shift;
16578     my $r = MARC::Record->new_from_xml( $xml );
16579
16580     return undef unless ($r);
16581
16582     my $id = shift() || $r->subfield( '901' => 'c' );
16583     $id =~ s/^\s*(?:\([^)]+\))?\s*(.+)\s*?$/$1/;
16584     return undef unless ($id); # We need an ID!
16585
16586     my $tmpl = MARC::Record->new();
16587
16588     my @rule_fields;
16589     for my $field ( $r->field( '1..' ) ) { # Get main entry fields from the authority record
16590
16591         my $tag = $field->tag;
16592         my $i1 = $field->indicator(1);
16593         my $i2 = $field->indicator(2);
16594         my $sf = join '', map { $_->[0] } $field->subfields;
16595         my @data = map { @$_ } $field->subfields;
16596
16597         my @replace_them;
16598
16599         # Map the authority field to bib fields it can control.
16600         if ($tag >= 100 and $tag <= 111) {       # names
16601             @replace_them = map { $tag + $_ } (0, 300, 500, 600, 700);
16602         } elsif ($tag eq '130') {                # uniform title
16603             @replace_them = qw/130 240 440 730 830/;
16604         } elsif ($tag >= 150 and $tag <= 155) {  # subjects
16605             @replace_them = ($tag + 500);
16606         } elsif ($tag >= 180 and $tag <= 185) {  # floating subdivisions
16607             @replace_them = qw/100 400 600 700 800 110 410 610 710 810 111 411 611 711 811 130 240 440 730 830 650 651 655/;
16608         } else {
16609             next;
16610         }
16611
16612         # Dummy up the bib-side data
16613         $tmpl->append_fields(
16614             map {
16615                 MARC::Field->new( $_, $i1, $i2, @data )
16616             } @replace_them
16617         );
16618
16619         # Construct some 'replace' rules
16620         push @rule_fields, map { $_ . $sf . '[0~\)' .$id . '$]' } @replace_them;
16621     }
16622
16623     # Insert the replace rules into the template
16624     $tmpl->append_fields(
16625         MARC::Field->new( '905' => ' ' => ' ' => 'r' => join(',', @rule_fields ) )
16626     );
16627
16628     $xml = $tmpl->as_xml_record;
16629     $xml =~ s/^<\?.+?\?>$//mo;
16630     $xml =~ s/\n//sgo;
16631     $xml =~ s/>\s+</></sgo;
16632
16633     return $xml;
16634
16635 $func$ LANGUAGE PLPERLU;
16636
16637 CREATE OR REPLACE FUNCTION authority.generate_overlay_template ( BIGINT ) RETURNS TEXT AS $func$
16638     SELECT authority.generate_overlay_template( marc, id ) FROM authority.record_entry WHERE id = $1;
16639 $func$ LANGUAGE SQL;
16640
16641 CREATE OR REPLACE FUNCTION authority.generate_overlay_template ( TEXT ) RETURNS TEXT AS $func$
16642     SELECT authority.generate_overlay_template( $1, NULL );
16643 $func$ LANGUAGE SQL;
16644
16645 DELETE FROM config.metabib_field_index_norm_map WHERE field = 26;
16646 DELETE FROM config.metabib_field WHERE id = 26;
16647
16648 -- Making this a global_flag (UI accessible) instead of an internal_flag
16649 INSERT INTO config.global_flag (name, label) -- defaults to enabled=FALSE
16650     VALUES (
16651         'ingest.disable_authority_linking',
16652         oils_i18n_gettext(
16653             'ingest.disable_authority_linking',
16654             'Authority Automation: Disable bib-authority link tracking',
16655             'cgf', 
16656             'label'
16657         )
16658     );
16659 UPDATE config.global_flag SET enabled = (SELECT enabled FROM ONLY config.internal_flag WHERE name = 'ingest.disable_authority_linking');
16660 DELETE FROM config.internal_flag WHERE name = 'ingest.disable_authority_linking';
16661
16662 INSERT INTO config.global_flag (name, label) -- defaults to enabled=FALSE
16663     VALUES (
16664         'ingest.disable_authority_auto_update',
16665         oils_i18n_gettext(
16666             'ingest.disable_authority_auto_update',
16667             'Authority Automation: Disable automatic authority updating (requires link tracking)',
16668             'cgf', 
16669             'label'
16670         )
16671     );
16672
16673 -- Enable automated ingest of authority records; just insert the row into
16674 -- authority.record_entry and authority.full_rec will automatically be populated
16675
16676 CREATE OR REPLACE FUNCTION authority.propagate_changes (aid BIGINT, bid BIGINT) RETURNS BIGINT AS $func$
16677     UPDATE  biblio.record_entry
16678       SET   marc = vandelay.merge_record_xml( marc, authority.generate_overlay_template( $1 ) )
16679       WHERE id = $2;
16680     SELECT $1;
16681 $func$ LANGUAGE SQL;
16682
16683 CREATE OR REPLACE FUNCTION authority.propagate_changes (aid BIGINT) RETURNS SETOF BIGINT AS $func$
16684     SELECT authority.propagate_changes( authority, bib ) FROM authority.bib_linking WHERE authority = $1;
16685 $func$ LANGUAGE SQL;
16686
16687 CREATE OR REPLACE FUNCTION authority.flatten_marc ( TEXT ) RETURNS SETOF authority.full_rec AS $func$
16688
16689 use MARC::Record;
16690 use MARC::File::XML (BinaryEncoding => 'UTF-8');
16691
16692 my $xml = shift;
16693 my $r = MARC::Record->new_from_xml( $xml );
16694
16695 return_next( { tag => 'LDR', value => $r->leader } );
16696
16697 for my $f ( $r->fields ) {
16698     if ($f->is_control_field) {
16699         return_next({ tag => $f->tag, value => $f->data });
16700     } else {
16701         for my $s ($f->subfields) {
16702             return_next({
16703                 tag      => $f->tag,
16704                 ind1     => $f->indicator(1),
16705                 ind2     => $f->indicator(2),
16706                 subfield => $s->[0],
16707                 value    => $s->[1]
16708             });
16709
16710         }
16711     }
16712 }
16713
16714 return undef;
16715
16716 $func$ LANGUAGE PLPERLU;
16717
16718 CREATE OR REPLACE FUNCTION authority.flatten_marc ( rid BIGINT ) RETURNS SETOF authority.full_rec AS $func$
16719 DECLARE
16720     auth    authority.record_entry%ROWTYPE;
16721     output    authority.full_rec%ROWTYPE;
16722     field    RECORD;
16723 BEGIN
16724     SELECT INTO auth * FROM authority.record_entry WHERE id = rid;
16725
16726     FOR field IN SELECT * FROM authority.flatten_marc( auth.marc ) LOOP
16727         output.record := rid;
16728         output.ind1 := field.ind1;
16729         output.ind2 := field.ind2;
16730         output.tag := field.tag;
16731         output.subfield := field.subfield;
16732         IF field.subfield IS NOT NULL THEN
16733             output.value := naco_normalize(field.value, field.subfield);
16734         ELSE
16735             output.value := field.value;
16736         END IF;
16737
16738         CONTINUE WHEN output.value IS NULL;
16739
16740         RETURN NEXT output;
16741     END LOOP;
16742 END;
16743 $func$ LANGUAGE PLPGSQL;
16744
16745 -- authority.rec_descriptor appears to be unused currently
16746 CREATE OR REPLACE FUNCTION authority.reingest_authority_rec_descriptor( auth_id BIGINT ) RETURNS VOID AS $func$
16747 BEGIN
16748     DELETE FROM authority.rec_descriptor WHERE record = auth_id;
16749 --    INSERT INTO authority.rec_descriptor (record, record_status, char_encoding)
16750 --        SELECT  auth_id, ;
16751
16752     RETURN;
16753 END;
16754 $func$ LANGUAGE PLPGSQL;
16755
16756 CREATE OR REPLACE FUNCTION authority.reingest_authority_full_rec( auth_id BIGINT ) RETURNS VOID AS $func$
16757 BEGIN
16758     DELETE FROM authority.full_rec WHERE record = auth_id;
16759     INSERT INTO authority.full_rec (record, tag, ind1, ind2, subfield, value)
16760         SELECT record, tag, ind1, ind2, subfield, value FROM authority.flatten_marc( auth_id );
16761
16762     RETURN;
16763 END;
16764 $func$ LANGUAGE PLPGSQL;
16765
16766 -- AFTER UPDATE OR INSERT trigger for authority.record_entry
16767 CREATE OR REPLACE FUNCTION authority.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
16768 BEGIN
16769
16770     IF NEW.deleted IS TRUE THEN -- If this authority is deleted
16771         DELETE FROM authority.bib_linking WHERE authority = NEW.id; -- Avoid updating fields in bibs that are no longer visible
16772         DELETE FROM authority.full_rec WHERE record = NEW.id; -- Avoid validating fields against deleted authority records
16773           -- Should remove matching $0 from controlled fields at the same time?
16774         RETURN NEW; -- and we're done
16775     END IF;
16776
16777     IF TG_OP = 'UPDATE' THEN -- re-ingest?
16778         PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
16779
16780         IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
16781             RETURN NEW;
16782         END IF;
16783     END IF;
16784
16785     -- Flatten and insert the afr data
16786     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_full_rec' AND enabled;
16787     IF NOT FOUND THEN
16788         PERFORM authority.reingest_authority_full_rec(NEW.id);
16789 -- authority.rec_descriptor is not currently used
16790 --        PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_rec_descriptor' AND enabled;
16791 --        IF NOT FOUND THEN
16792 --            PERFORM authority.reingest_authority_rec_descriptor(NEW.id);
16793 --        END IF;
16794     END IF;
16795
16796     RETURN NEW;
16797 END;
16798 $func$ LANGUAGE PLPGSQL;
16799
16800 CREATE TRIGGER aaa_auth_ingest_or_delete AFTER INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE authority.indexing_ingest_or_delete ();
16801
16802 -- Some records manage to get XML namespace declarations into each element,
16803 -- like <datafield xmlns:marc="http://www.loc.gov/MARC21/slim"
16804 -- This broke the old maintain_901(), so we'll make the regex more robust
16805
16806 CREATE OR REPLACE FUNCTION maintain_901 () RETURNS TRIGGER AS $func$
16807 BEGIN
16808     -- Remove any existing 901 fields before we insert the authoritative one
16809     NEW.marc := REGEXP_REPLACE(NEW.marc, E'<datafield\s*[^<>]*?\s*tag="901".+?</datafield>', '', 'g');
16810     IF TG_TABLE_SCHEMA = 'biblio' THEN
16811         NEW.marc := REGEXP_REPLACE(
16812             NEW.marc,
16813             E'(</(?:[^:]*?:)?record>)',
16814             E'<datafield tag="901" ind1=" " ind2=" ">' ||
16815                 '<subfield code="a">' || NEW.tcn_value || E'</subfield>' ||
16816                 '<subfield code="b">' || NEW.tcn_source || E'</subfield>' ||
16817                 '<subfield code="c">' || NEW.id || E'</subfield>' ||
16818                 '<subfield code="t">' || TG_TABLE_SCHEMA || E'</subfield>' ||
16819                 CASE WHEN NEW.owner IS NOT NULL THEN '<subfield code="o">' || NEW.owner || E'</subfield>' ELSE '' END ||
16820                 CASE WHEN NEW.share_depth IS NOT NULL THEN '<subfield code="d">' || NEW.share_depth || E'</subfield>' ELSE '' END ||
16821              E'</datafield>\\1'
16822         );
16823     ELSIF TG_TABLE_SCHEMA = 'authority' THEN
16824         NEW.marc := REGEXP_REPLACE(
16825             NEW.marc,
16826             E'(</(?:[^:]*?:)?record>)',
16827             E'<datafield tag="901" ind1=" " ind2=" ">' ||
16828                 '<subfield code="c">' || NEW.id || E'</subfield>' ||
16829                 '<subfield code="t">' || TG_TABLE_SCHEMA || E'</subfield>' ||
16830              E'</datafield>\\1'
16831         );
16832     ELSIF TG_TABLE_SCHEMA = 'serial' THEN
16833         NEW.marc := REGEXP_REPLACE(
16834             NEW.marc,
16835             E'(</(?:[^:]*?:)?record>)',
16836             E'<datafield tag="901" ind1=" " ind2=" ">' ||
16837                 '<subfield code="c">' || NEW.id || E'</subfield>' ||
16838                 '<subfield code="t">' || TG_TABLE_SCHEMA || E'</subfield>' ||
16839                 '<subfield code="o">' || NEW.owning_lib || E'</subfield>' ||
16840                 CASE WHEN NEW.record IS NOT NULL THEN '<subfield code="r">' || NEW.record || E'</subfield>' ELSE '' END ||
16841              E'</datafield>\\1'
16842         );
16843     ELSE
16844         NEW.marc := REGEXP_REPLACE(
16845             NEW.marc,
16846             E'(</(?:[^:]*?:)?record>)',
16847             E'<datafield tag="901" ind1=" " ind2=" ">' ||
16848                 '<subfield code="c">' || NEW.id || E'</subfield>' ||
16849                 '<subfield code="t">' || TG_TABLE_SCHEMA || E'</subfield>' ||
16850              E'</datafield>\\1'
16851         );
16852     END IF;
16853
16854     RETURN NEW;
16855 END;
16856 $func$ LANGUAGE PLPGSQL;
16857
16858 CREATE TRIGGER b_maintain_901 BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE maintain_901();
16859 CREATE TRIGGER b_maintain_901 BEFORE INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE maintain_901();
16860 CREATE TRIGGER b_maintain_901 BEFORE INSERT OR UPDATE ON serial.record_entry FOR EACH ROW EXECUTE PROCEDURE maintain_901();
16861  
16862 -- In booking, elbow room defines:
16863 --  a) how far in the future you must make a reservation on a given item if
16864 --      that item will have to transit somewhere to fulfill the reservation.
16865 --  b) how soon a reservation must be starting for the reserved item to
16866 --      be op-captured by the checkin interface.
16867
16868 -- We don't want to clobber any default_elbow room at any level:
16869
16870 CREATE OR REPLACE FUNCTION pg_temp.default_elbow() RETURNS INTEGER AS $$
16871 DECLARE
16872     existing    actor.org_unit_setting%ROWTYPE;
16873 BEGIN
16874     SELECT INTO existing id FROM actor.org_unit_setting WHERE name = 'circ.booking_reservation.default_elbow_room';
16875     IF NOT FOUND THEN
16876         INSERT INTO actor.org_unit_setting (org_unit, name, value) VALUES (
16877             (SELECT id FROM actor.org_unit WHERE parent_ou IS NULL),
16878             'circ.booking_reservation.default_elbow_room',
16879             '"1 day"'
16880         );
16881         RETURN 1;
16882     END IF;
16883     RETURN 0;
16884 END;
16885 $$ LANGUAGE plpgsql;
16886
16887 SELECT pg_temp.default_elbow();
16888
16889 DROP FUNCTION IF EXISTS action.usr_visible_circ_copies( INTEGER );
16890
16891 -- returns the distinct set of target copy IDs from a user's visible circulation history
16892 CREATE OR REPLACE FUNCTION action.usr_visible_circ_copies( INTEGER ) RETURNS SETOF BIGINT AS $$
16893     SELECT DISTINCT(target_copy) FROM action.usr_visible_circs($1)
16894 $$ LANGUAGE SQL;
16895
16896 ALTER TABLE action.in_house_use DROP CONSTRAINT in_house_use_item_fkey;
16897 ALTER TABLE action.transit_copy DROP CONSTRAINT transit_copy_target_copy_fkey;
16898 ALTER TABLE action.hold_transit_copy DROP CONSTRAINT ahtc_tc_fkey;
16899 ALTER TABLE action.hold_copy_map DROP CONSTRAINT hold_copy_map_target_copy_fkey;
16900
16901 ALTER TABLE asset.stat_cat_entry_copy_map DROP CONSTRAINT a_sc_oc_fkey;
16902
16903 ALTER TABLE authority.record_entry ADD COLUMN owner INT;
16904 ALTER TABLE serial.record_entry ADD COLUMN owner INT;
16905
16906 INSERT INTO config.global_flag (name, label, enabled)
16907     VALUES (
16908         'cat.maintain_control_numbers',
16909         oils_i18n_gettext(
16910             'cat.maintain_control_numbers',
16911             'Cat: Maintain 001/003/035 according to the MARC21 specification',
16912             'cgf', 
16913             'label'
16914         ),
16915         TRUE
16916     );
16917
16918 INSERT INTO config.global_flag (name, label, enabled)
16919     VALUES (
16920         'circ.holds.empty_issuance_ok',
16921         oils_i18n_gettext(
16922             'circ.holds.empty_issuance_ok',
16923             'Holds: Allow holds on empty issuances',
16924             'cgf',
16925             'label'
16926         ),
16927         TRUE
16928     );
16929
16930 INSERT INTO config.global_flag (name, label, enabled)
16931     VALUES (
16932         'circ.holds.usr_not_requestor',
16933         oils_i18n_gettext(
16934             'circ.holds.usr_not_requestor',
16935             'Holds: When testing hold matrix matchpoints, use the profile group of the receiving user instead of that of the requestor (affects staff-placed holds)',
16936             'cgf',
16937             'label'
16938         ),
16939         TRUE
16940     );
16941
16942 CREATE OR REPLACE FUNCTION maintain_control_numbers() RETURNS TRIGGER AS $func$
16943 use strict;
16944 use MARC::Record;
16945 use MARC::File::XML (BinaryEncoding => 'UTF-8');
16946 use Encode;
16947 use Unicode::Normalize;
16948
16949 my $record = MARC::Record->new_from_xml($_TD->{new}{marc});
16950 my $schema = $_TD->{table_schema};
16951 my $rec_id = $_TD->{new}{id};
16952
16953 # Short-circuit if maintaining control numbers per MARC21 spec is not enabled
16954 my $enable = spi_exec_query("SELECT enabled FROM config.global_flag WHERE name = 'cat.maintain_control_numbers'");
16955 if (!($enable->{processed}) or $enable->{rows}[0]->{enabled} eq 'f') {
16956     return;
16957 }
16958
16959 # Get the control number identifier from an OU setting based on $_TD->{new}{owner}
16960 my $ou_cni = 'EVRGRN';
16961
16962 my $owner;
16963 if ($schema eq 'serial') {
16964     $owner = $_TD->{new}{owning_lib};
16965 } else {
16966     # are.owner and bre.owner can be null, so fall back to the consortial setting
16967     $owner = $_TD->{new}{owner} || 1;
16968 }
16969
16970 my $ous_rv = spi_exec_query("SELECT value FROM actor.org_unit_ancestor_setting('cat.marc_control_number_identifier', $owner)");
16971 if ($ous_rv->{processed}) {
16972     $ou_cni = $ous_rv->{rows}[0]->{value};
16973     $ou_cni =~ s/"//g; # Stupid VIM syntax highlighting"
16974 } else {
16975     # Fall back to the shortname of the OU if there was no OU setting
16976     $ous_rv = spi_exec_query("SELECT shortname FROM actor.org_unit WHERE id = $owner");
16977     if ($ous_rv->{processed}) {
16978         $ou_cni = $ous_rv->{rows}[0]->{shortname};
16979     }
16980 }
16981
16982 my ($create, $munge) = (0, 0);
16983
16984 my @scns = $record->field('035');
16985
16986 foreach my $id_field ('001', '003') {
16987     my $spec_value;
16988     my @controls = $record->field($id_field);
16989
16990     if ($id_field eq '001') {
16991         $spec_value = $rec_id;
16992     } else {
16993         $spec_value = $ou_cni;
16994     }
16995
16996     # Create the 001/003 if none exist
16997     if (scalar(@controls) == 1) {
16998         # Only one field; check to see if we need to munge it
16999         unless (grep $_->data() eq $spec_value, @controls) {
17000             $munge = 1;
17001         }
17002     } else {
17003         # Delete the other fields, as with more than 1 001/003 we do not know which 003/001 to match
17004         foreach my $control (@controls) {
17005             unless ($control->data() eq $spec_value) {
17006                 $record->delete_field($control);
17007             }
17008         }
17009         $record->insert_fields_ordered(MARC::Field->new($id_field, $spec_value));
17010         $create = 1;
17011     }
17012 }
17013
17014 # Now, if we need to munge the 001, we will first push the existing 001/003
17015 # into the 035; but if the record did not have one (and one only) 001 and 003
17016 # to begin with, skip this process
17017 if ($munge and not $create) {
17018     my $scn = "(" . $record->field('003')->data() . ")" . $record->field('001')->data();
17019
17020     # Do not create duplicate 035 fields
17021     unless (grep $_->subfield('a') eq $scn, @scns) {
17022         $record->insert_fields_ordered(MARC::Field->new('035', '', '', 'a' => $scn));
17023     }
17024 }
17025
17026 # Set the 001/003 and update the MARC
17027 if ($create or $munge) {
17028     $record->field('001')->data($rec_id);
17029     $record->field('003')->data($ou_cni);
17030
17031     my $xml = $record->as_xml_record();
17032     $xml =~ s/\n//sgo;
17033     $xml =~ s/^<\?xml.+\?\s*>//go;
17034     $xml =~ s/>\s+</></go;
17035     $xml =~ s/\p{Cc}//go;
17036
17037     # Embed a version of OpenILS::Application::AppUtils->entityize()
17038     # to avoid having to set PERL5LIB for PostgreSQL as well
17039
17040     # If we are going to convert non-ASCII characters to XML entities,
17041     # we had better be dealing with a UTF8 string to begin with
17042     $xml = decode_utf8($xml);
17043
17044     $xml = NFC($xml);
17045
17046     # Convert raw ampersands to entities
17047     $xml =~ s/&(?!\S+;)/&amp;/gso;
17048
17049     # Convert Unicode characters to entities
17050     $xml =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
17051
17052     $xml =~ s/[\x00-\x1f]//go;
17053     $_TD->{new}{marc} = $xml;
17054
17055     return "MODIFY";
17056 }
17057
17058 CREATE OR REPLACE FUNCTION maintain_control_numbers() RETURNS TRIGGER AS $func$
17059 use strict;
17060 use MARC::Record;
17061 use MARC::File::XML (BinaryEncoding => 'UTF-8');
17062 use Encode;
17063 use Unicode::Normalize;
17064
17065 my $record = MARC::Record->new_from_xml($_TD->{new}{marc});
17066 my $schema = $_TD->{table_schema};
17067 my $rec_id = $_TD->{new}{id};
17068
17069 # Short-circuit if maintaining control numbers per MARC21 spec is not enabled
17070 my $enable = spi_exec_query("SELECT enabled FROM config.global_flag WHERE name = 'cat.maintain_control_numbers'");
17071 if (!($enable->{processed}) or $enable->{rows}[0]->{enabled} eq 'f') {
17072     return;
17073 }
17074
17075 # Get the control number identifier from an OU setting based on $_TD->{new}{owner}
17076 my $ou_cni = 'EVRGRN';
17077
17078 my $owner;
17079 if ($schema eq 'serial') {
17080     $owner = $_TD->{new}{owning_lib};
17081 } else {
17082     # are.owner and bre.owner can be null, so fall back to the consortial setting
17083     $owner = $_TD->{new}{owner} || 1;
17084 }
17085
17086 my $ous_rv = spi_exec_query("SELECT value FROM actor.org_unit_ancestor_setting('cat.marc_control_number_identifier', $owner)");
17087 if ($ous_rv->{processed}) {
17088     $ou_cni = $ous_rv->{rows}[0]->{value};
17089     $ou_cni =~ s/"//g; # Stupid VIM syntax highlighting"
17090 } else {
17091     # Fall back to the shortname of the OU if there was no OU setting
17092     $ous_rv = spi_exec_query("SELECT shortname FROM actor.org_unit WHERE id = $owner");
17093     if ($ous_rv->{processed}) {
17094         $ou_cni = $ous_rv->{rows}[0]->{shortname};
17095     }
17096 }
17097
17098 my ($create, $munge) = (0, 0);
17099
17100 my @scns = $record->field('035');
17101
17102 foreach my $id_field ('001', '003') {
17103     my $spec_value;
17104     my @controls = $record->field($id_field);
17105
17106     if ($id_field eq '001') {
17107         $spec_value = $rec_id;
17108     } else {
17109         $spec_value = $ou_cni;
17110     }
17111
17112     # Create the 001/003 if none exist
17113     if (scalar(@controls) == 1) {
17114         # Only one field; check to see if we need to munge it
17115         unless (grep $_->data() eq $spec_value, @controls) {
17116             $munge = 1;
17117         }
17118     } else {
17119         # Delete the other fields, as with more than 1 001/003 we do not know which 003/001 to match
17120         foreach my $control (@controls) {
17121             unless ($control->data() eq $spec_value) {
17122                 $record->delete_field($control);
17123             }
17124         }
17125         $record->insert_fields_ordered(MARC::Field->new($id_field, $spec_value));
17126         $create = 1;
17127     }
17128 }
17129
17130 # Now, if we need to munge the 001, we will first push the existing 001/003
17131 # into the 035; but if the record did not have one (and one only) 001 and 003
17132 # to begin with, skip this process
17133 if ($munge and not $create) {
17134     my $scn = "(" . $record->field('003')->data() . ")" . $record->field('001')->data();
17135
17136     # Do not create duplicate 035 fields
17137     unless (grep $_->subfield('a') eq $scn, @scns) {
17138         $record->insert_fields_ordered(MARC::Field->new('035', '', '', 'a' => $scn));
17139     }
17140 }
17141
17142 # Set the 001/003 and update the MARC
17143 if ($create or $munge) {
17144     $record->field('001')->data($rec_id);
17145     $record->field('003')->data($ou_cni);
17146
17147     my $xml = $record->as_xml_record();
17148     $xml =~ s/\n//sgo;
17149     $xml =~ s/^<\?xml.+\?\s*>//go;
17150     $xml =~ s/>\s+</></go;
17151     $xml =~ s/\p{Cc}//go;
17152
17153     # Embed a version of OpenILS::Application::AppUtils->entityize()
17154     # to avoid having to set PERL5LIB for PostgreSQL as well
17155
17156     # If we are going to convert non-ASCII characters to XML entities,
17157     # we had better be dealing with a UTF8 string to begin with
17158     $xml = decode_utf8($xml);
17159
17160     $xml = NFC($xml);
17161
17162     # Convert raw ampersands to entities
17163     $xml =~ s/&(?!\S+;)/&amp;/gso;
17164
17165     # Convert Unicode characters to entities
17166     $xml =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
17167
17168     $xml =~ s/[\x00-\x1f]//go;
17169     $_TD->{new}{marc} = $xml;
17170
17171     return "MODIFY";
17172 }
17173
17174 return;
17175 $func$ LANGUAGE PLPERLU;
17176
17177 CREATE TRIGGER c_maintain_control_numbers BEFORE INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE maintain_control_numbers();
17178 CREATE TRIGGER c_maintain_control_numbers BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE maintain_control_numbers();
17179 CREATE TRIGGER c_maintain_control_numbers BEFORE INSERT OR UPDATE ON serial.record_entry FOR EACH ROW EXECUTE PROCEDURE maintain_control_numbers();
17180
17181 INSERT INTO metabib.facet_entry (source, field, value)
17182     SELECT source, field, value FROM (
17183         SELECT * FROM metabib.author_field_entry
17184             UNION ALL
17185         SELECT * FROM metabib.keyword_field_entry
17186             UNION ALL
17187         SELECT * FROM metabib.identifier_field_entry
17188             UNION ALL
17189         SELECT * FROM metabib.title_field_entry
17190             UNION ALL
17191         SELECT * FROM metabib.subject_field_entry
17192             UNION ALL
17193         SELECT * FROM metabib.series_field_entry
17194         )x
17195     WHERE x.index_vector = '';
17196         
17197 DELETE FROM metabib.author_field_entry WHERE index_vector = '';
17198 DELETE FROM metabib.keyword_field_entry WHERE index_vector = '';
17199 DELETE FROM metabib.identifier_field_entry WHERE index_vector = '';
17200 DELETE FROM metabib.title_field_entry WHERE index_vector = '';
17201 DELETE FROM metabib.subject_field_entry WHERE index_vector = '';
17202 DELETE FROM metabib.series_field_entry WHERE index_vector = '';
17203
17204 CREATE INDEX metabib_facet_entry_field_idx ON metabib.facet_entry (field);
17205 CREATE INDEX metabib_facet_entry_value_idx ON metabib.facet_entry (SUBSTRING(value,1,1024));
17206 CREATE INDEX metabib_facet_entry_source_idx ON metabib.facet_entry (source);
17207
17208 -- copy OPAC visibility materialized view
17209 CREATE OR REPLACE FUNCTION asset.refresh_opac_visible_copies_mat_view () RETURNS VOID AS $$
17210
17211     TRUNCATE TABLE asset.opac_visible_copies;
17212
17213     INSERT INTO asset.opac_visible_copies (id, circ_lib, record)
17214     SELECT  cp.id, cp.circ_lib, cn.record
17215     FROM  asset.copy cp
17216         JOIN asset.call_number cn ON (cn.id = cp.call_number)
17217         JOIN actor.org_unit a ON (cp.circ_lib = a.id)
17218         JOIN asset.copy_location cl ON (cp.location = cl.id)
17219         JOIN config.copy_status cs ON (cp.status = cs.id)
17220         JOIN biblio.record_entry b ON (cn.record = b.id)
17221     WHERE NOT cp.deleted
17222         AND NOT cn.deleted
17223         AND NOT b.deleted
17224         AND cs.opac_visible
17225         AND cl.opac_visible
17226         AND cp.opac_visible
17227         AND a.opac_visible;
17228
17229 $$ LANGUAGE SQL;
17230 COMMENT ON FUNCTION asset.refresh_opac_visible_copies_mat_view() IS $$
17231 Rebuild the copy OPAC visibility cache.  Useful during migrations.
17232 $$;
17233
17234 -- and actually populate the table
17235 SELECT asset.refresh_opac_visible_copies_mat_view();
17236
17237 CREATE OR REPLACE FUNCTION asset.cache_copy_visibility () RETURNS TRIGGER as $func$
17238 DECLARE
17239     add_query       TEXT;
17240     remove_query    TEXT;
17241     do_add          BOOLEAN := false;
17242     do_remove       BOOLEAN := false;
17243 BEGIN
17244     add_query := $$
17245             INSERT INTO asset.opac_visible_copies (id, circ_lib, record)
17246                 SELECT  cp.id, cp.circ_lib, cn.record
17247                   FROM  asset.copy cp
17248                         JOIN asset.call_number cn ON (cn.id = cp.call_number)
17249                         JOIN actor.org_unit a ON (cp.circ_lib = a.id)
17250                         JOIN asset.copy_location cl ON (cp.location = cl.id)
17251                         JOIN config.copy_status cs ON (cp.status = cs.id)
17252                         JOIN biblio.record_entry b ON (cn.record = b.id)
17253                   WHERE NOT cp.deleted
17254                         AND NOT cn.deleted
17255                         AND NOT b.deleted
17256                         AND cs.opac_visible
17257                         AND cl.opac_visible
17258                         AND cp.opac_visible
17259                         AND a.opac_visible
17260     $$;
17261  
17262     remove_query := $$ DELETE FROM asset.opac_visible_copies WHERE id IN ( SELECT id FROM asset.copy WHERE $$;
17263
17264     IF TG_OP = 'INSERT' THEN
17265
17266         IF TG_TABLE_NAME IN ('copy', 'unit') THEN
17267             add_query := add_query || 'AND cp.id = ' || NEW.id || ';';
17268             EXECUTE add_query;
17269         END IF;
17270
17271         RETURN NEW;
17272
17273     END IF;
17274
17275     -- handle items first, since with circulation activity
17276     -- their statuses change frequently
17277     IF TG_TABLE_NAME IN ('copy', 'unit') THEN
17278
17279         IF OLD.location    <> NEW.location OR
17280            OLD.call_number <> NEW.call_number OR
17281            OLD.status      <> NEW.status OR
17282            OLD.circ_lib    <> NEW.circ_lib THEN
17283             -- any of these could change visibility, but
17284             -- we'll save some queries and not try to calculate
17285             -- the change directly
17286             do_remove := true;
17287             do_add := true;
17288         ELSE
17289
17290             IF OLD.deleted <> NEW.deleted THEN
17291                 IF NEW.deleted THEN
17292                     do_remove := true;
17293                 ELSE
17294                     do_add := true;
17295                 END IF;
17296             END IF;
17297
17298             IF OLD.opac_visible <> NEW.opac_visible THEN
17299                 IF OLD.opac_visible THEN
17300                     do_remove := true;
17301                 ELSIF NOT do_remove THEN -- handle edge case where deleted item
17302                                         -- is also marked opac_visible
17303                     do_add := true;
17304                 END IF;
17305             END IF;
17306
17307         END IF;
17308
17309         IF do_remove THEN
17310             DELETE FROM asset.opac_visible_copies WHERE id = NEW.id;
17311         END IF;
17312         IF do_add THEN
17313             add_query := add_query || 'AND cp.id = ' || NEW.id || ';';
17314             EXECUTE add_query;
17315         END IF;
17316
17317         RETURN NEW;
17318
17319     END IF;
17320
17321     IF TG_TABLE_NAME IN ('call_number', 'record_entry') THEN -- these have a 'deleted' column
17322  
17323         IF OLD.deleted AND NEW.deleted THEN -- do nothing
17324
17325             RETURN NEW;
17326  
17327         ELSIF NEW.deleted THEN -- remove rows
17328  
17329             IF TG_TABLE_NAME = 'call_number' THEN
17330                 DELETE FROM asset.opac_visible_copies WHERE id IN (SELECT id FROM asset.copy WHERE call_number = NEW.id);
17331             ELSIF TG_TABLE_NAME = 'record_entry' THEN
17332                 DELETE FROM asset.opac_visible_copies WHERE record = NEW.id;
17333             END IF;
17334  
17335             RETURN NEW;
17336  
17337         ELSIF OLD.deleted THEN -- add rows
17338  
17339             IF TG_TABLE_NAME IN ('copy','unit') THEN
17340                 add_query := add_query || 'AND cp.id = ' || NEW.id || ';';
17341             ELSIF TG_TABLE_NAME = 'call_number' THEN
17342                 add_query := add_query || 'AND cp.call_number = ' || NEW.id || ';';
17343             ELSIF TG_TABLE_NAME = 'record_entry' THEN
17344                 add_query := add_query || 'AND cn.record = ' || NEW.id || ';';
17345             END IF;
17346  
17347             EXECUTE add_query;
17348             RETURN NEW;
17349  
17350         END IF;
17351  
17352     END IF;
17353
17354     IF TG_TABLE_NAME = 'call_number' THEN
17355
17356         IF OLD.record <> NEW.record THEN
17357             -- call number is linked to different bib
17358             remove_query := remove_query || 'call_number = ' || NEW.id || ');';
17359             EXECUTE remove_query;
17360             add_query := add_query || 'AND cp.call_number = ' || NEW.id || ';';
17361             EXECUTE add_query;
17362         END IF;
17363
17364         RETURN NEW;
17365
17366     END IF;
17367
17368     IF TG_TABLE_NAME IN ('record_entry') THEN
17369         RETURN NEW; -- don't have 'opac_visible'
17370     END IF;
17371
17372     -- actor.org_unit, asset.copy_location, asset.copy_status
17373     IF NEW.opac_visible = OLD.opac_visible THEN -- do nothing
17374
17375         RETURN NEW;
17376
17377     ELSIF NEW.opac_visible THEN -- add rows
17378
17379         IF TG_TABLE_NAME = 'org_unit' THEN
17380             add_query := add_query || 'AND cp.circ_lib = ' || NEW.id || ';';
17381         ELSIF TG_TABLE_NAME = 'copy_location' THEN
17382             add_query := add_query || 'AND cp.location = ' || NEW.id || ';';
17383         ELSIF TG_TABLE_NAME = 'copy_status' THEN
17384             add_query := add_query || 'AND cp.status = ' || NEW.id || ';';
17385         END IF;
17386  
17387         EXECUTE add_query;
17388  
17389     ELSE -- delete rows
17390
17391         IF TG_TABLE_NAME = 'org_unit' THEN
17392             remove_query := 'DELETE FROM asset.opac_visible_copies WHERE circ_lib = ' || NEW.id || ';';
17393         ELSIF TG_TABLE_NAME = 'copy_location' THEN
17394             remove_query := remove_query || 'location = ' || NEW.id || ');';
17395         ELSIF TG_TABLE_NAME = 'copy_status' THEN
17396             remove_query := remove_query || 'status = ' || NEW.id || ');';
17397         END IF;
17398  
17399         EXECUTE remove_query;
17400  
17401     END IF;
17402  
17403     RETURN NEW;
17404 END;
17405 $func$ LANGUAGE PLPGSQL;
17406 COMMENT ON FUNCTION asset.cache_copy_visibility() IS $$
17407 Trigger function to update the copy OPAC visiblity cache.
17408 $$;
17409 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17410 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON asset.copy FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17411 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON asset.call_number FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17412 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON asset.copy_location FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17413 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON serial.unit FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17414 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON config.copy_status FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17415 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON actor.org_unit FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
17416
17417 -- must create this rule explicitly; it is not inherited from asset.copy
17418 CREATE RULE protect_serial_unit_delete AS ON DELETE TO serial.unit DO INSTEAD UPDATE serial.unit SET deleted = TRUE WHERE OLD.id = serial.unit.id;
17419
17420 CREATE RULE protect_authority_rec_delete AS ON DELETE TO authority.record_entry DO INSTEAD (UPDATE authority.record_entry SET deleted = TRUE WHERE OLD.id = authority.record_entry.id);
17421
17422 CREATE OR REPLACE FUNCTION authority.merge_records ( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
17423 DECLARE
17424     moved_objects INT := 0;
17425     bib_id        INT := 0;
17426     bib_rec       biblio.record_entry%ROWTYPE;
17427     auth_link     authority.bib_linking%ROWTYPE;
17428     ingest_same   boolean;
17429 BEGIN
17430
17431     -- 1. Update all bib records with the ID from target_record in their $0
17432     FOR bib_rec IN SELECT bre.* FROM biblio.record_entry bre
17433       INNER JOIN authority.bib_linking abl ON abl.bib = bre.id
17434       WHERE abl.authority = source_record LOOP
17435
17436         UPDATE biblio.record_entry
17437           SET marc = REGEXP_REPLACE(marc,
17438             E'(<subfield\\s+code="0"\\s*>[^<]*?\\))' || source_record || '<',
17439             E'\\1' || target_record || '<', 'g')
17440           WHERE id = bib_rec.id;
17441
17442           moved_objects := moved_objects + 1;
17443     END LOOP;
17444
17445     -- 2. Grab the current value of reingest on same MARC flag
17446     SELECT enabled INTO ingest_same
17447       FROM config.internal_flag
17448       WHERE name = 'ingest.reingest.force_on_same_marc'
17449     ;
17450
17451     -- 3. Temporarily set reingest on same to TRUE
17452     UPDATE config.internal_flag
17453       SET enabled = TRUE
17454       WHERE name = 'ingest.reingest.force_on_same_marc'
17455     ;
17456
17457     -- 4. Make a harmless update to target_record to trigger auto-update
17458     --    in linked bibliographic records
17459     UPDATE authority.record_entry
17460       SET DELETED = FALSE
17461       WHERE id = source_record;
17462
17463     -- 5. "Delete" source_record
17464     DELETE FROM authority.record_entry
17465       WHERE id = source_record;
17466
17467     -- 6. Set "reingest on same MARC" flag back to initial value
17468     UPDATE config.internal_flag
17469       SET enabled = ingest_same
17470       WHERE name = 'ingest.reingest.force_on_same_marc'
17471     ;
17472
17473     RETURN moved_objects;
17474 END;
17475 $func$ LANGUAGE plpgsql;
17476
17477 -- serial.record_entry already had an owner column spelled "owning_lib"
17478 -- Adjust the table and affected functions accordingly
17479
17480 ALTER TABLE serial.record_entry DROP COLUMN owner;
17481
17482 CREATE TABLE actor.usr_saved_search (
17483     id              SERIAL          PRIMARY KEY,
17484         owner           INT             NOT NULL REFERENCES actor.usr (id)
17485                                         ON DELETE CASCADE
17486                                         DEFERRABLE INITIALLY DEFERRED,
17487         name            TEXT            NOT NULL,
17488         create_date     TIMESTAMPTZ     NOT NULL DEFAULT now(),
17489         query_text      TEXT            NOT NULL,
17490         query_type      TEXT            NOT NULL
17491                                         CONSTRAINT valid_query_text CHECK (
17492                                         query_type IN ( 'URL' )) DEFAULT 'URL',
17493                                         -- we may add other types someday
17494         target          TEXT            NOT NULL
17495                                         CONSTRAINT valid_target CHECK (
17496                                         target IN ( 'record', 'metarecord', 'callnumber' )),
17497         CONSTRAINT name_once_per_user UNIQUE (owner, name)
17498 );
17499
17500 -- Apply Dan Wells' changes to the serial schema, from the
17501 -- seials-integration branch
17502
17503 CREATE TABLE serial.subscription_note (
17504         id           SERIAL PRIMARY KEY,
17505         subscription INT    NOT NULL
17506                             REFERENCES serial.subscription (id)
17507                             ON DELETE CASCADE
17508                             DEFERRABLE INITIALLY DEFERRED,
17509         creator      INT    NOT NULL
17510                             REFERENCES actor.usr (id)
17511                             DEFERRABLE INITIALLY DEFERRED,
17512         create_date  TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
17513         pub          BOOL   NOT NULL DEFAULT FALSE,
17514         title        TEXT   NOT NULL,
17515         value        TEXT   NOT NULL
17516 );
17517 CREATE INDEX serial_subscription_note_sub_idx ON serial.subscription_note (subscription);
17518
17519 CREATE TABLE serial.distribution_note (
17520         id           SERIAL PRIMARY KEY,
17521         distribution INT    NOT NULL
17522                             REFERENCES serial.distribution (id)
17523                             ON DELETE CASCADE
17524                             DEFERRABLE INITIALLY DEFERRED,
17525         creator      INT    NOT NULL
17526                             REFERENCES actor.usr (id)
17527                             DEFERRABLE INITIALLY DEFERRED,
17528         create_date  TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
17529         pub          BOOL   NOT NULL DEFAULT FALSE,
17530         title        TEXT   NOT NULL,
17531         value        TEXT   NOT NULL
17532 );
17533 CREATE INDEX serial_distribution_note_dist_idx ON serial.distribution_note (distribution);
17534
17535 ------- Begin surgery on serial.unit
17536
17537 ALTER TABLE serial.unit
17538         DROP COLUMN label;
17539
17540 ALTER TABLE serial.unit
17541         RENAME COLUMN label_sort_key TO sort_key;
17542
17543 ALTER TABLE serial.unit
17544         RENAME COLUMN contents TO detailed_contents;
17545
17546 ALTER TABLE serial.unit
17547         ADD COLUMN summary_contents TEXT;
17548
17549 UPDATE serial.unit
17550 SET summary_contents = detailed_contents;
17551
17552 ALTER TABLE serial.unit
17553         ALTER column summary_contents SET NOT NULL;
17554
17555 ------- End surgery on serial.unit
17556
17557 -- DELETE FROM config.upgrade_log WHERE version = 'temp'; DELETE FROM action_trigger.event WHERE event_def IN (33,34); DELETE FROM action_trigger.environment WHERE event_def IN (33,34); DELETE FROM action_trigger.event_definition WHERE id IN (33,34); DELETE FROM action_trigger.hook WHERE key IN ( 'circ.format.missing_pieces.slip.print', 'circ.format.missing_pieces.letter.print' );
17558
17559 -- Now rebuild the constraints dropped via cascade.
17560 -- ALTER TABLE acq.provider    ADD CONSTRAINT provider_edi_default_fkey FOREIGN KEY (edi_default) REFERENCES acq.edi_account (id) DEFERRABLE INITIALLY DEFERRED;
17561 DROP INDEX IF EXISTS money.money_mat_summary_id_idx;
17562 ALTER TABLE money.materialized_billable_xact_summary ADD PRIMARY KEY (id);
17563
17564 -- ALTER TABLE staging.billing_address_stage ADD PRIMARY KEY (row_id);
17565
17566 DELETE FROM config.metabib_field_index_norm_map
17567     WHERE norm IN (
17568         SELECT id 
17569             FROM config.index_normalizer
17570             WHERE func IN ('first_word', 'naco_normalize', 'split_date_range')
17571     )
17572     AND field = 18
17573 ;
17574
17575 -- We won't necessarily use all of these, but they are here for completeness.
17576 -- Source is the EDI spec 6063 codelist, eg: http://www.stylusstudio.com/edifact/D04B/6063.htm
17577 -- Values are the EDI code value + 1200
17578
17579 INSERT INTO acq.cancel_reason (org_unit, keep_debits, id, label, description) VALUES 
17580 (1, 't', 1201, 'Discrete quantity', 'Individually separated and distinct quantity.'),
17581 (1, 't', 1202, 'Charge', 'Quantity relevant for charge.'),
17582 (1, 't', 1203, 'Cumulative quantity', 'Quantity accumulated.'),
17583 (1, 't', 1204, 'Interest for overdrawn account', 'Interest for overdrawing the account.'),
17584 (1, 't', 1205, 'Active ingredient dose per unit', 'The dosage of active ingredient per unit.'),
17585 (1, 't', 1206, 'Auditor', 'The number of entities that audit accounts.'),
17586 (1, 't', 1207, 'Branch locations, leased', 'The number of branch locations being leased by an entity.'),
17587 (1, 't', 1208, 'Inventory quantity at supplier''s subject to inspection by', 'customer Quantity of goods which the customer requires the supplier to have in inventory and which may be inspected by the customer if desired.'),
17588 (1, 't', 1209, 'Branch locations, owned', 'The number of branch locations owned by an entity.'),
17589 (1, 't', 1210, 'Judgements registered', 'The number of judgements registered against an entity.'),
17590 (1, 't', 1211, 'Split quantity', 'Part of the whole quantity.'),
17591 (1, 't', 1212, 'Despatch quantity', 'Quantity despatched by the seller.'),
17592 (1, 't', 1213, 'Liens registered', 'The number of liens registered against an entity.'),
17593 (1, 't', 1214, 'Livestock', 'The number of animals kept for use or profit.'),
17594 (1, 't', 1215, 'Insufficient funds returned cheques', 'The number of cheques returned due to insufficient funds.'),
17595 (1, 't', 1216, 'Stolen cheques', 'The number of stolen cheques.'),
17596 (1, 't', 1217, 'Quantity on hand', 'The total quantity of a product on hand at a location. This includes as well units awaiting return to manufacturer, units unavailable due to inspection procedures and undamaged stock available for despatch, resale or use.'),
17597 (1, 't', 1218, 'Previous quantity', 'Quantity previously referenced.'),
17598 (1, 't', 1219, 'Paid-in security shares', 'The number of security shares issued and for which full payment has been made.'),
17599 (1, 't', 1220, 'Unusable quantity', 'Quantity not usable.'),
17600 (1, 't', 1221, 'Ordered quantity', '[6024] The quantity which has been ordered.'),
17601 (1, 't', 1222, 'Quantity at 100%', 'Equivalent quantity at 100% purity.'),
17602 (1, 't', 1223, 'Active ingredient', 'Quantity at 100% active agent content.'),
17603 (1, 't', 1224, 'Inventory quantity at supplier''s not subject to inspection', 'by customer Quantity of goods which the customer requires the supplier to have in inventory but which will not be checked by the customer.'),
17604 (1, 't', 1225, 'Retail sales', 'Quantity of retail point of sale activity.'),
17605 (1, 't', 1226, 'Promotion quantity', 'A quantity associated with a promotional event.'),
17606 (1, 't', 1227, 'On hold for shipment', 'Article received which cannot be shipped in its present form.'),
17607 (1, 't', 1228, 'Military sales quantity', 'Quantity of goods or services sold to a military organization.'),
17608 (1, 't', 1229, 'On premises sales',  'Sale of product in restaurants or bars.'),
17609 (1, 't', 1230, 'Off premises sales', 'Sale of product directly to a store.'),
17610 (1, 't', 1231, 'Estimated annual volume', 'Volume estimated for a year.'),
17611 (1, 't', 1232, 'Minimum delivery batch', 'Minimum quantity of goods delivered at one time.'),
17612 (1, 't', 1233, 'Maximum delivery batch', 'Maximum quantity of goods delivered at one time.'),
17613 (1, 't', 1234, 'Pipes', 'The number of tubes used to convey a substance.'),
17614 (1, 't', 1235, 'Price break from', 'The minimum quantity of a quantity range for a specified (unit) price.'),
17615 (1, 't', 1236, 'Price break to', 'Maximum quantity to which the price break applies.'),
17616 (1, 't', 1237, 'Poultry', 'The number of domestic fowl.'),
17617 (1, 't', 1238, 'Secured charges registered', 'The number of secured charges registered against an entity.'),
17618 (1, 't', 1239, 'Total properties owned', 'The total number of properties owned by an entity.'),
17619 (1, 't', 1240, 'Normal delivery', 'Quantity normally delivered by the seller.'),
17620 (1, 't', 1241, 'Sales quantity not included in the replenishment', 'calculation Sales which will not be included in the calculation of replenishment requirements.'),
17621 (1, 't', 1242, 'Maximum supply quantity, supplier endorsed', 'Maximum supply quantity endorsed by a supplier.'),
17622 (1, 't', 1243, 'Buyer', 'The number of buyers.'),
17623 (1, 't', 1244, 'Debenture bond', 'The number of fixed-interest bonds of an entity backed by general credit rather than specified assets.'),
17624 (1, 't', 1245, 'Debentures filed against directors', 'The number of notices of indebtedness filed against an entity''s directors.'),
17625 (1, 't', 1246, 'Pieces delivered', 'Number of pieces actually received at the final destination.'),
17626 (1, 't', 1247, 'Invoiced quantity', 'The quantity as per invoice.'),
17627 (1, 't', 1248, 'Received quantity', 'The quantity which has been received.'),
17628 (1, 't', 1249, 'Chargeable distance', '[6110] The distance between two points for which a specific tariff applies.'),
17629 (1, 't', 1250, 'Disposition undetermined quantity', 'Product quantity that has not yet had its disposition determined.'),
17630 (1, 't', 1251, 'Inventory category transfer', 'Inventory that has been moved from one inventory category to another.'),
17631 (1, 't', 1252, 'Quantity per pack', 'Quantity for each pack.'),
17632 (1, 't', 1253, 'Minimum order quantity', 'Minimum quantity of goods for an order.'),
17633 (1, 't', 1254, 'Maximum order quantity', 'Maximum quantity of goods for an order.'),
17634 (1, 't', 1255, 'Total sales', 'The summation of total quantity sales.'),
17635 (1, 't', 1256, 'Wholesaler to wholesaler sales', 'Sale of product to other wholesalers by a wholesaler.'),
17636 (1, 't', 1257, 'In transit quantity', 'A quantity that is en route.'),
17637 (1, 't', 1258, 'Quantity withdrawn', 'Quantity withdrawn from a location.'),
17638 (1, 't', 1259, 'Numbers of consumer units in the traded unit', 'Number of units for consumer sales in a unit for trading.'),
17639 (1, 't', 1260, 'Current inventory quantity available for shipment', 'Current inventory quantity available for shipment.'),
17640 (1, 't', 1261, 'Return quantity', 'Quantity of goods returned.'),
17641 (1, 't', 1262, 'Sorted quantity', 'The quantity that is sorted.'),
17642 (1, 'f', 1263, 'Sorted quantity rejected', 'The sorted quantity that is rejected.'),
17643 (1, 't', 1264, 'Scrap quantity', 'Remainder of the total quantity after split deliveries.'),
17644 (1, 'f', 1265, 'Destroyed quantity', 'Quantity of goods destroyed.'),
17645 (1, 't', 1266, 'Committed quantity', 'Quantity a party is committed to.'),
17646 (1, 't', 1267, 'Estimated reading quantity', 'The value that is estimated to be the reading of a measuring device (e.g. meter).'),
17647 (1, 't', 1268, 'End quantity', 'The quantity recorded at the end of an agreement or period.'),
17648 (1, 't', 1269, 'Start quantity', 'The quantity recorded at the start of an agreement or period.'),
17649 (1, 't', 1270, 'Cumulative quantity received', 'Cumulative quantity of all deliveries of this article received by the buyer.'),
17650 (1, 't', 1271, 'Cumulative quantity ordered', 'Cumulative quantity of all deliveries, outstanding and scheduled orders.'),
17651 (1, 't', 1272, 'Cumulative quantity received end of prior year', 'Cumulative quantity of all deliveries of the product received by the buyer till end of prior year.'),
17652 (1, 't', 1273, 'Outstanding quantity', 'Difference between quantity ordered and quantity received.'),
17653 (1, 't', 1274, 'Latest cumulative quantity', 'Cumulative quantity after complete delivery of all scheduled quantities of the product.'),
17654 (1, 't', 1275, 'Previous highest cumulative quantity', 'Cumulative quantity after complete delivery of all scheduled quantities of the product from a prior schedule period.'),
17655 (1, 't', 1276, 'Adjusted corrector reading', 'A corrector reading after it has been adjusted.'),
17656 (1, 't', 1277, 'Work days', 'Number of work days, e.g. per respective period.'),
17657 (1, 't', 1278, 'Cumulative quantity scheduled', 'Adding the quantity actually scheduled to previous cumulative quantity.'),
17658 (1, 't', 1279, 'Previous cumulative quantity', 'Cumulative quantity prior the actual order.'),
17659 (1, 't', 1280, 'Unadjusted corrector reading', 'A corrector reading before it has been adjusted.'),
17660 (1, 't', 1281, 'Extra unplanned delivery', 'Non scheduled additional quantity.'),
17661 (1, 't', 1282, 'Quantity requirement for sample inspection', 'Required quantity for sample inspection.'),
17662 (1, 't', 1283, 'Backorder quantity', 'The quantity of goods that is on back-order.'),
17663 (1, 't', 1284, 'Urgent delivery quantity', 'Quantity for urgent delivery.'),
17664 (1, 'f', 1285, 'Previous order quantity to be cancelled', 'Quantity ordered previously to be cancelled.'),
17665 (1, 't', 1286, 'Normal reading quantity', 'The value recorded or read from a measuring device (e.g. meter) in the normal conditions.'),
17666 (1, 't', 1287, 'Customer reading quantity', 'The value recorded or read from a measuring device (e.g. meter) by the customer.'),
17667 (1, 't', 1288, 'Information reading quantity', 'The value recorded or read from a measuring device (e.g. meter) for information purposes.'),
17668 (1, 't', 1289, 'Quality control held', 'Quantity of goods held pending completion of a quality control assessment.'),
17669 (1, 't', 1290, 'As is quantity', 'Quantity as it is in the existing circumstances.'),
17670 (1, 't', 1291, 'Open quantity', 'Quantity remaining after partial delivery.'),
17671 (1, 't', 1292, 'Final delivery quantity', 'Quantity of final delivery to a respective order.'),
17672 (1, 't', 1293, 'Subsequent delivery quantity', 'Quantity delivered to a respective order after it''s final delivery.'),
17673 (1, 't', 1294, 'Substitutional quantity', 'Quantity delivered replacing previous deliveries.'),
17674 (1, 't', 1295, 'Redelivery after post processing', 'Quantity redelivered after post processing.'),
17675 (1, 'f', 1296, 'Quality control failed', 'Quantity of goods which have failed quality control.'),
17676 (1, 't', 1297, 'Minimum inventory', 'Minimum stock quantity on which replenishment is based.'),
17677 (1, 't', 1298, 'Maximum inventory', 'Maximum stock quantity on which replenishment is based.'),
17678 (1, 't', 1299, 'Estimated quantity', 'Quantity estimated.'),
17679 (1, 't', 1300, 'Chargeable weight', 'The weight on which charges are based.'),
17680 (1, 't', 1301, 'Chargeable gross weight', 'The gross weight on which charges are based.'),
17681 (1, 't', 1302, 'Chargeable tare weight', 'The tare weight on which charges are based.'),
17682 (1, 't', 1303, 'Chargeable number of axles', 'The number of axles on which charges are based.'),
17683 (1, 't', 1304, 'Chargeable number of containers', 'The number of containers on which charges are based.'),
17684 (1, 't', 1305, 'Chargeable number of rail wagons', 'The number of rail wagons on which charges are based.'),
17685 (1, 't', 1306, 'Chargeable number of packages', 'The number of packages on which charges are based.'),
17686 (1, 't', 1307, 'Chargeable number of units', 'The number of units on which charges are based.'),
17687 (1, 't', 1308, 'Chargeable period', 'The period of time on which charges are based.'),
17688 (1, 't', 1309, 'Chargeable volume', 'The volume on which charges are based.'),
17689 (1, 't', 1310, 'Chargeable cubic measurements', 'The cubic measurements on which charges are based.'),
17690 (1, 't', 1311, 'Chargeable surface', 'The surface area on which charges are based.'),
17691 (1, 't', 1312, 'Chargeable length', 'The length on which charges are based.'),
17692 (1, 't', 1313, 'Quantity to be delivered', 'The quantity to be delivered.'),
17693 (1, 't', 1314, 'Number of passengers', 'Total number of passengers on the conveyance.'),
17694 (1, 't', 1315, 'Number of crew', 'Total number of crew members on the conveyance.'),
17695 (1, 't', 1316, 'Number of transport documents', 'Total number of air waybills, bills of lading, etc. being reported for a specific conveyance.'),
17696 (1, 't', 1317, 'Quantity landed', 'Quantity of goods actually arrived.'),
17697 (1, 't', 1318, 'Quantity manifested', 'Quantity of goods contracted for delivery by the carrier.'),
17698 (1, 't', 1319, 'Short shipped', 'Indication that part of the consignment was not shipped.'),
17699 (1, 't', 1320, 'Split shipment', 'Indication that the consignment has been split into two or more shipments.'),
17700 (1, 't', 1321, 'Over shipped', 'The quantity of goods shipped that exceeds the quantity contracted.'),
17701 (1, 't', 1322, 'Short-landed goods', 'If quantity of goods actually landed is less than the quantity which appears in the documentation. This quantity is the difference between these quantities.'),
17702 (1, 't', 1323, 'Surplus goods', 'If quantity of goods actually landed is more than the quantity which appears in the documentation. This quantity is the difference between these quantities.'),
17703 (1, 'f', 1324, 'Damaged goods', 'Quantity of goods which have deteriorated in transport such that they cannot be used for the purpose for which they were originally intended.'),
17704 (1, 'f', 1325, 'Pilferage goods', 'Quantity of goods stolen during transport.'),
17705 (1, 'f', 1326, 'Lost goods', 'Quantity of goods that disappeared in transport.'),
17706 (1, 't', 1327, 'Report difference', 'The quantity concerning the same transaction differs between two documents/messages and the source of this difference is a typing error.'),
17707 (1, 't', 1328, 'Quantity loaded', 'Quantity of goods loaded onto a means of transport.'),
17708 (1, 't', 1329, 'Units per unit price', 'Number of units per unit price.'),
17709 (1, 't', 1330, 'Allowance', 'Quantity relevant for allowance.'),
17710 (1, 't', 1331, 'Delivery quantity', 'Quantity required by buyer to be delivered.'),
17711 (1, 't', 1332, 'Cumulative quantity, preceding period, planned', 'Cumulative quantity originally planned for the preceding period.'),
17712 (1, 't', 1333, 'Cumulative quantity, preceding period, reached', 'Cumulative quantity reached in the preceding period.'),
17713 (1, 't', 1334, 'Cumulative quantity, actual planned',            'Cumulative quantity planned for now.'),
17714 (1, 't', 1335, 'Period quantity, planned', 'Quantity planned for this period.'),
17715 (1, 't', 1336, 'Period quantity, reached', 'Quantity reached during this period.'),
17716 (1, 't', 1337, 'Cumulative quantity, preceding period, estimated', 'Estimated cumulative quantity reached in the preceding period.'),
17717 (1, 't', 1338, 'Cumulative quantity, actual estimated',            'Estimated cumulative quantity reached now.'),
17718 (1, 't', 1339, 'Cumulative quantity, preceding period, measured', 'Surveyed cumulative quantity reached in the preceding period.'),
17719 (1, 't', 1340, 'Cumulative quantity, actual measured', 'Surveyed cumulative quantity reached now.'),
17720 (1, 't', 1341, 'Period quantity, measured',            'Surveyed quantity reached during this period.'),
17721 (1, 't', 1342, 'Total quantity, planned', 'Total quantity planned.'),
17722 (1, 't', 1343, 'Quantity, remaining', 'Quantity remaining.'),
17723 (1, 't', 1344, 'Tolerance', 'Plus or minus tolerance expressed as a monetary amount.'),
17724 (1, 't', 1345, 'Actual stock',          'The stock on hand, undamaged, and available for despatch, sale or use.'),
17725 (1, 't', 1346, 'Model or target stock', 'The stock quantity required or planned to have on hand, undamaged and available for use.'),
17726 (1, 't', 1347, 'Direct shipment quantity', 'Quantity to be shipped directly to a customer from a manufacturing site.'),
17727 (1, 't', 1348, 'Amortization total quantity',     'Indication of final quantity for amortization.'),
17728 (1, 't', 1349, 'Amortization order quantity',     'Indication of actual share of the order quantity for amortization.'),
17729 (1, 't', 1350, 'Amortization cumulated quantity', 'Indication of actual cumulated quantity of previous and actual amortization order quantity.'),
17730 (1, 't', 1351, 'Quantity advised',  'Quantity advised by supplier or shipper, in contrast to quantity actually received.'),
17731 (1, 't', 1352, 'Consignment stock', 'Quantity of goods with an external customer which is still the property of the supplier. Payment for these goods is only made to the supplier when the ownership has been transferred between the trading partners.'),
17732 (1, 't', 1353, 'Statistical sales quantity', 'Quantity of goods sold in a specified period.'),
17733 (1, 't', 1354, 'Sales quantity planned',     'Quantity of goods required to meet future demands. - Market intelligence quantity.'),
17734 (1, 't', 1355, 'Replenishment quantity',     'Quantity required to maintain the requisite on-hand stock of goods.'),
17735 (1, 't', 1356, 'Inventory movement quantity', 'To specify the quantity of an inventory movement.'),
17736 (1, 't', 1357, 'Opening stock balance quantity', 'To specify the quantity of an opening stock balance.'),
17737 (1, 't', 1358, 'Closing stock balance quantity', 'To specify the quantity of a closing stock balance.'),
17738 (1, 't', 1359, 'Number of stops', 'Number of times a means of transport stops before arriving at destination.'),
17739 (1, 't', 1360, 'Minimum production batch', 'The quantity specified is the minimum output from a single production run.'),
17740 (1, 't', 1361, 'Dimensional sample quantity', 'The quantity defined is a sample for the purpose of validating dimensions.'),
17741 (1, 't', 1362, 'Functional sample quantity', 'The quantity defined is a sample for the purpose of validating function and performance.'),
17742 (1, 't', 1363, 'Pre-production quantity', 'Quantity of the referenced item required prior to full production.'),
17743 (1, 't', 1364, 'Delivery batch', 'Quantity of the referenced item which constitutes a standard batch for deliver purposes.'),
17744 (1, 't', 1365, 'Delivery batch multiple', 'The multiples in which delivery batches can be supplied.'),
17745 (1, 't', 1366, 'All time buy',             'The total quantity of the referenced covering all future needs. Further orders of the referenced item are not expected.'),
17746 (1, 't', 1367, 'Total delivery quantity',  'The total quantity required by the buyer to be delivered.'),
17747 (1, 't', 1368, 'Single delivery quantity', 'The quantity required by the buyer to be delivered in a single shipment.'),
17748 (1, 't', 1369, 'Supplied quantity',  'Quantity of the referenced item actually shipped.'),
17749 (1, 't', 1370, 'Allocated quantity', 'Quantity of the referenced item allocated from available stock for delivery.'),
17750 (1, 't', 1371, 'Maximum stackability', 'The number of pallets/handling units which can be safely stacked one on top of another.'),
17751 (1, 't', 1372, 'Amortisation quantity', 'The quantity of the referenced item which has a cost for tooling amortisation included in the item price.'),
17752 (1, 't', 1373, 'Previously amortised quantity', 'The cumulative quantity of the referenced item which had a cost for tooling amortisation included in the item price.'),
17753 (1, 't', 1374, 'Total amortisation quantity', 'The total quantity of the referenced item which has a cost for tooling amortisation included in the item price.'),
17754 (1, 't', 1375, 'Number of moulds', 'The number of pressing moulds contained within a single piece of the referenced tooling.'),
17755 (1, 't', 1376, 'Concurrent item output of tooling', 'The number of related items which can be produced simultaneously with a single piece of the referenced tooling.'),
17756 (1, 't', 1377, 'Periodic capacity of tooling', 'Maximum production output of the referenced tool over a period of time.'),
17757 (1, 't', 1378, 'Lifetime capacity of tooling', 'Maximum production output of the referenced tool over its productive lifetime.'),
17758 (1, 't', 1379, 'Number of deliveries per despatch period', 'The number of deliveries normally expected to be despatched within each despatch period.'),
17759 (1, 't', 1380, 'Provided quantity', 'The quantity of a referenced component supplied by the buyer for manufacturing of an ordered item.'),
17760 (1, 't', 1381, 'Maximum production batch', 'The quantity specified is the maximum output from a single production run.'),
17761 (1, 'f', 1382, 'Cancelled quantity', 'Quantity of the referenced item which has previously been ordered and is now cancelled.'),
17762 (1, 't', 1383, 'No delivery requirement in this instruction', 'This delivery instruction does not contain any delivery requirements.'),
17763 (1, 't', 1384, 'Quantity of material in ordered time', 'Quantity of the referenced material within the ordered time.'),
17764 (1, 'f', 1385, 'Rejected quantity', 'The quantity of received goods rejected for quantity reasons.'),
17765 (1, 't', 1386, 'Cumulative quantity scheduled up to accumulation start date', 'The cumulative quantity scheduled up to the accumulation start date.'),
17766 (1, 't', 1387, 'Quantity scheduled', 'The quantity scheduled for delivery.'),
17767 (1, 't', 1388, 'Number of identical handling units', 'Number of identical handling units in terms of type and contents.'),
17768 (1, 't', 1389, 'Number of packages in handling unit', 'The number of packages contained in one handling unit.'),
17769 (1, 't', 1390, 'Despatch note quantity', 'The item quantity specified on the despatch note.'),
17770 (1, 't', 1391, 'Adjustment to inventory quantity', 'An adjustment to inventory quantity.'),
17771 (1, 't', 1392, 'Free goods quantity',    'Quantity of goods which are free of charge.'),
17772 (1, 't', 1393, 'Free quantity included', 'Quantity included to which no charge is applicable.'),
17773 (1, 't', 1394, 'Received and accepted',  'Quantity which has been received and accepted at a given location.'),
17774 (1, 'f', 1395, 'Received, not accepted, to be returned',  'Quantity which has been received but not accepted at a given location and which will consequently be returned to the relevant party.'),
17775 (1, 'f', 1396, 'Received, not accepted, to be destroyed', 'Quantity which has been received but not accepted at a given location and which will consequently be destroyed.'),
17776 (1, 't', 1397, 'Reordering level', 'Quantity at which an order may be triggered to replenish.'),
17777 (1, 't', 1399, 'Inventory withdrawal quantity', 'Quantity which has been withdrawn from inventory since the last inventory report.'),
17778 (1, 't', 1400, 'Free quantity not included', 'Free quantity not included in ordered quantity.'),
17779 (1, 't', 1401, 'Recommended overhaul and repair quantity', 'To indicate the recommended quantity of an article required to support overhaul and repair activities.'),
17780 (1, 't', 1402, 'Quantity per next higher assembly', 'To indicate the quantity required for the next higher assembly.'),
17781 (1, 't', 1403, 'Quantity per unit of issue', 'Provides the standard quantity of an article in which one unit can be issued.'),
17782 (1, 't', 1404, 'Cumulative scrap quantity',  'Provides the cumulative quantity of an item which has been identified as scrapped.'),
17783 (1, 't', 1405, 'Publication turn size', 'The quantity of magazines or newspapers grouped together with the spine facing alternate directions in a bundle.'),
17784 (1, 't', 1406, 'Recommended maintenance quantity', 'Recommended quantity of an article which is required to meet an agreed level of maintenance.'),
17785 (1, 't', 1407, 'Labour hours', 'Number of labour hours.'),
17786 (1, 't', 1408, 'Quantity requirement for maintenance and repair of', 'equipment Quantity of the material needed to maintain and repair equipment.'),
17787 (1, 't', 1409, 'Additional replenishment demand quantity', 'Incremental needs over and above normal replenishment calculations, but not intended to permanently change the model parameters.'),
17788 (1, 't', 1410, 'Returned by consumer quantity', 'Quantity returned by a consumer.'),
17789 (1, 't', 1411, 'Replenishment override quantity', 'Quantity to override the normal replenishment model calculations, but not intended to permanently change the model parameters.'),
17790 (1, 't', 1412, 'Quantity sold, net', 'Net quantity sold which includes returns of saleable inventory and other adjustments.'),
17791 (1, 't', 1413, 'Transferred out quantity',   'Quantity which was transferred out of this location.'),
17792 (1, 't', 1414, 'Transferred in quantity',    'Quantity which was transferred into this location.'),
17793 (1, 't', 1415, 'Unsaleable quantity',        'Quantity of inventory received which cannot be sold in its present condition.'),
17794 (1, 't', 1416, 'Consumer reserved quantity', 'Quantity reserved for consumer delivery or pickup and not yet withdrawn from inventory.'),
17795 (1, 't', 1417, 'Out of inventory quantity',  'Quantity of inventory which was requested but was not available.'),
17796 (1, 't', 1418, 'Quantity returned, defective or damaged', 'Quantity returned in a damaged or defective condition.'),
17797 (1, 't', 1419, 'Taxable quantity',           'Quantity subject to taxation.'),
17798 (1, 't', 1420, 'Meter reading', 'The numeric value of measure units counted by a meter.'),
17799 (1, 't', 1421, 'Maximum requestable quantity', 'The maximum quantity which may be requested.'),
17800 (1, 't', 1422, 'Minimum requestable quantity', 'The minimum quantity which may be requested.'),
17801 (1, 't', 1423, 'Daily average quantity', 'The quantity for a defined period divided by the number of days of the period.'),
17802 (1, 't', 1424, 'Budgeted hours',     'The number of budgeted hours.'),
17803 (1, 't', 1425, 'Actual hours',       'The number of actual hours.'),
17804 (1, 't', 1426, 'Earned value hours', 'The number of earned value hours.'),
17805 (1, 't', 1427, 'Estimated hours',    'The number of estimated hours.'),
17806 (1, 't', 1428, 'Level resource task quantity', 'Quantity of a resource that is level for the duration of the task.'),
17807 (1, 't', 1429, 'Available resource task quantity', 'Quantity of a resource available to complete a task.'),
17808 (1, 't', 1430, 'Work time units',   'Quantity of work units of time.'),
17809 (1, 't', 1431, 'Daily work shifts', 'Quantity of work shifts per day.'),
17810 (1, 't', 1432, 'Work time units per shift', 'Work units of time per work shift.'),
17811 (1, 't', 1433, 'Work calendar units',       'Work calendar units of time.'),
17812 (1, 't', 1434, 'Elapsed duration',   'Quantity representing the elapsed duration.'),
17813 (1, 't', 1435, 'Remaining duration', 'Quantity representing the remaining duration.'),
17814 (1, 't', 1436, 'Original duration',  'Quantity representing the original duration.'),
17815 (1, 't', 1437, 'Current duration',   'Quantity representing the current duration.'),
17816 (1, 't', 1438, 'Total float time',   'Quantity representing the total float time.'),
17817 (1, 't', 1439, 'Free float time',    'Quantity representing the free float time.'),
17818 (1, 't', 1440, 'Lag time',           'Quantity representing lag time.'),
17819 (1, 't', 1441, 'Lead time',          'Quantity representing lead time.'),
17820 (1, 't', 1442, 'Number of months', 'The number of months.'),
17821 (1, 't', 1443, 'Reserved quantity customer direct delivery sales', 'Quantity of products reserved for sales delivered direct to the customer.'),
17822 (1, 't', 1444, 'Reserved quantity retail sales', 'Quantity of products reserved for retail sales.'),
17823 (1, 't', 1445, 'Consolidated discount inventory', 'A quantity of inventory supplied at consolidated discount terms.'),
17824 (1, 't', 1446, 'Returns replacement quantity',    'A quantity of goods issued as a replacement for a returned quantity.'),
17825 (1, 't', 1447, 'Additional promotion sales forecast quantity', 'A forecast of additional quantity which will be sold during a period of promotional activity.'),
17826 (1, 't', 1448, 'Reserved quantity', 'Quantity reserved for specific purposes.'),
17827 (1, 't', 1449, 'Quantity displayed not available for sale', 'Quantity displayed within a retail outlet but not available for sale.'),
17828 (1, 't', 1450, 'Inventory discrepancy', 'The difference recorded between theoretical and physical inventory.'),
17829 (1, 't', 1451, 'Incremental order quantity', 'The incremental quantity by which ordering is carried out.'),
17830 (1, 't', 1452, 'Quantity requiring manipulation before despatch', 'A quantity of goods which needs manipulation before despatch.'),
17831 (1, 't', 1453, 'Quantity in quarantine',              'A quantity of goods which are held in a restricted area for quarantine purposes.'),
17832 (1, 't', 1454, 'Quantity withheld by owner of goods', 'A quantity of goods which has been withheld by the owner of the goods.'),
17833 (1, 't', 1455, 'Quantity not available for despatch', 'A quantity of goods not available for despatch.'),
17834 (1, 't', 1456, 'Quantity awaiting delivery', 'Quantity of goods which are awaiting delivery.'),
17835 (1, 't', 1457, 'Quantity in physical inventory',      'A quantity of goods held in physical inventory.'),
17836 (1, 't', 1458, 'Quantity held by logistic service provider', 'Quantity of goods under the control of a logistic service provider.'),
17837 (1, 't', 1459, 'Optimal quantity', 'The optimal quantity for a given purpose.'),
17838 (1, 't', 1460, 'Delivery quantity balance', 'The difference between the scheduled quantity and the quantity delivered to the consignee at a given date.'),
17839 (1, 't', 1461, 'Cumulative quantity shipped', 'Cumulative quantity of all shipments.'),
17840 (1, 't', 1462, 'Quantity suspended', 'The quantity of something which is suspended.'),
17841 (1, 't', 1463, 'Control quantity', 'The quantity designated for control purposes.'),
17842 (1, 't', 1464, 'Equipment quantity', 'A count of a quantity of equipment.'),
17843 (1, 't', 1465, 'Factor', 'Number by which the measured unit has to be multiplied to calculate the units used.'),
17844 (1, 't', 1466, 'Unsold quantity held by wholesaler', 'Unsold quantity held by the wholesaler.'),
17845 (1, 't', 1467, 'Quantity held by delivery vehicle', 'Quantity of goods held by the delivery vehicle.'),
17846 (1, 't', 1468, 'Quantity held by retail outlet', 'Quantity held by the retail outlet.'),
17847 (1, 'f', 1469, 'Rejected return quantity', 'A quantity for return which has been rejected.'),
17848 (1, 't', 1470, 'Accounts', 'The number of accounts.'),
17849 (1, 't', 1471, 'Accounts placed for collection', 'The number of accounts placed for collection.'),
17850 (1, 't', 1472, 'Activity codes', 'The number of activity codes.'),
17851 (1, 't', 1473, 'Agents', 'The number of agents.'),
17852 (1, 't', 1474, 'Airline attendants', 'The number of airline attendants.'),
17853 (1, 't', 1475, 'Authorised shares',  'The number of shares authorised for issue.'),
17854 (1, 't', 1476, 'Employee average',   'The average number of employees.'),
17855 (1, 't', 1477, 'Branch locations',   'The number of branch locations.'),
17856 (1, 't', 1478, 'Capital changes',    'The number of capital changes made.'),
17857 (1, 't', 1479, 'Clerks', 'The number of clerks.'),
17858 (1, 't', 1480, 'Companies in same activity', 'The number of companies doing business in the same activity category.'),
17859 (1, 't', 1481, 'Companies included in consolidated financial statement', 'The number of companies included in a consolidated financial statement.'),
17860 (1, 't', 1482, 'Cooperative shares', 'The number of cooperative shares.'),
17861 (1, 't', 1483, 'Creditors',   'The number of creditors.'),
17862 (1, 't', 1484, 'Departments', 'The number of departments.'),
17863 (1, 't', 1485, 'Design employees', 'The number of employees involved in the design process.'),
17864 (1, 't', 1486, 'Physicians', 'The number of medical doctors.'),
17865 (1, 't', 1487, 'Domestic affiliated companies', 'The number of affiliated companies located within the country.'),
17866 (1, 't', 1488, 'Drivers', 'The number of drivers.'),
17867 (1, 't', 1489, 'Employed at location',     'The number of employees at the specified location.'),
17868 (1, 't', 1490, 'Employed by this company', 'The number of employees at the specified company.'),
17869 (1, 't', 1491, 'Total employees',    'The total number of employees.'),
17870 (1, 't', 1492, 'Employees shared',   'The number of employees shared among entities.'),
17871 (1, 't', 1493, 'Engineers',          'The number of engineers.'),
17872 (1, 't', 1494, 'Estimated accounts', 'The estimated number of accounts.'),
17873 (1, 't', 1495, 'Estimated employees at location', 'The estimated number of employees at the specified location.'),
17874 (1, 't', 1496, 'Estimated total employees',       'The total estimated number of employees.'),
17875 (1, 't', 1497, 'Executives', 'The number of executives.'),
17876 (1, 't', 1498, 'Agricultural workers',   'The number of agricultural workers.'),
17877 (1, 't', 1499, 'Financial institutions', 'The number of financial institutions.'),
17878 (1, 't', 1500, 'Floors occupied', 'The number of floors occupied.'),
17879 (1, 't', 1501, 'Foreign related entities', 'The number of related entities located outside the country.'),
17880 (1, 't', 1502, 'Group employees',    'The number of employees within the group.'),
17881 (1, 't', 1503, 'Indirect employees', 'The number of employees not associated with direct production.'),
17882 (1, 't', 1504, 'Installers',    'The number of employees involved with the installation process.'),
17883 (1, 't', 1505, 'Invoices',      'The number of invoices.'),
17884 (1, 't', 1506, 'Issued shares', 'The number of shares actually issued.'),
17885 (1, 't', 1507, 'Labourers',     'The number of labourers.'),
17886 (1, 't', 1508, 'Manufactured units', 'The number of units manufactured.'),
17887 (1, 't', 1509, 'Maximum number of employees', 'The maximum number of people employed.'),
17888 (1, 't', 1510, 'Maximum number of employees at location', 'The maximum number of people employed at a location.'),
17889 (1, 't', 1511, 'Members in group', 'The number of members within a group.'),
17890 (1, 't', 1512, 'Minimum number of employees at location', 'The minimum number of people employed at a location.'),
17891 (1, 't', 1513, 'Minimum number of employees', 'The minimum number of people employed.'),
17892 (1, 't', 1514, 'Non-union employees', 'The number of employees not belonging to a labour union.'),
17893 (1, 't', 1515, 'Floors', 'The number of floors in a building.'),
17894 (1, 't', 1516, 'Nurses', 'The number of nurses.'),
17895 (1, 't', 1517, 'Office workers', 'The number of workers in an office.'),
17896 (1, 't', 1518, 'Other employees', 'The number of employees otherwise categorised.'),
17897 (1, 't', 1519, 'Part time employees', 'The number of employees working on a part time basis.'),
17898 (1, 't', 1520, 'Accounts payable average overdue days', 'The average number of days accounts payable are overdue.'),
17899 (1, 't', 1521, 'Pilots', 'The number of pilots.'),
17900 (1, 't', 1522, 'Plant workers', 'The number of workers within a plant.'),
17901 (1, 't', 1523, 'Previous number of accounts', 'The number of accounts which preceded the current count.'),
17902 (1, 't', 1524, 'Previous number of branch locations', 'The number of branch locations which preceded the current count.'),
17903 (1, 't', 1525, 'Principals included as employees', 'The number of principals which are included in the count of employees.'),
17904 (1, 't', 1526, 'Protested bills', 'The number of bills which are protested.'),
17905 (1, 't', 1527, 'Registered brands distributed', 'The number of registered brands which are being distributed.'),
17906 (1, 't', 1528, 'Registered brands manufactured', 'The number of registered brands which are being manufactured.'),
17907 (1, 't', 1529, 'Related business entities', 'The number of related business entities.'),
17908 (1, 't', 1530, 'Relatives employed', 'The number of relatives which are counted as employees.'),
17909 (1, 't', 1531, 'Rooms',        'The number of rooms.'),
17910 (1, 't', 1532, 'Salespersons', 'The number of salespersons.'),
17911 (1, 't', 1533, 'Seats',        'The number of seats.'),
17912 (1, 't', 1534, 'Shareholders', 'The number of shareholders.'),
17913 (1, 't', 1535, 'Shares of common stock', 'The number of shares of common stock.'),
17914 (1, 't', 1536, 'Shares of preferred stock', 'The number of shares of preferred stock.'),
17915 (1, 't', 1537, 'Silent partners', 'The number of silent partners.'),
17916 (1, 't', 1538, 'Subcontractors',  'The number of subcontractors.'),
17917 (1, 't', 1539, 'Subsidiaries',    'The number of subsidiaries.'),
17918 (1, 't', 1540, 'Law suits',       'The number of law suits.'),
17919 (1, 't', 1541, 'Suppliers',       'The number of suppliers.'),
17920 (1, 't', 1542, 'Teachers',        'The number of teachers.'),
17921 (1, 't', 1543, 'Technicians',     'The number of technicians.'),
17922 (1, 't', 1544, 'Trainees',        'The number of trainees.'),
17923 (1, 't', 1545, 'Union employees', 'The number of employees who are members of a labour union.'),
17924 (1, 't', 1546, 'Number of units', 'The quantity of units.'),
17925 (1, 't', 1547, 'Warehouse employees', 'The number of employees who work in a warehouse setting.'),
17926 (1, 't', 1548, 'Shareholders holding remainder of shares', 'Number of shareholders owning the remainder of shares.'),
17927 (1, 't', 1549, 'Payment orders filed', 'Number of payment orders filed.'),
17928 (1, 't', 1550, 'Uncovered cheques', 'Number of uncovered cheques.'),
17929 (1, 't', 1551, 'Auctions', 'Number of auctions.'),
17930 (1, 't', 1552, 'Units produced', 'The number of units produced.'),
17931 (1, 't', 1553, 'Added employees', 'Number of employees that were added to the workforce.'),
17932 (1, 't', 1554, 'Number of added locations', 'Number of locations that were added.'),
17933 (1, 't', 1555, 'Total number of foreign subsidiaries not included in', 'financial statement The total number of foreign subsidiaries not included in the financial statement.'),
17934 (1, 't', 1556, 'Number of closed locations', 'Number of locations that were closed.'),
17935 (1, 't', 1557, 'Counter clerks', 'The number of clerks that work behind a flat-topped fitment.'),
17936 (1, 't', 1558, 'Payment experiences in the last 3 months', 'The number of payment experiences received for an entity over the last 3 months.'),
17937 (1, 't', 1559, 'Payment experiences in the last 12 months', 'The number of payment experiences received for an entity over the last 12 months.'),
17938 (1, 't', 1560, 'Total number of subsidiaries not included in the financial', 'statement The total number of subsidiaries not included in the financial statement.'),
17939 (1, 't', 1561, 'Paid-in common shares', 'The number of paid-in common shares.'),
17940 (1, 't', 1562, 'Total number of domestic subsidiaries not included in', 'financial statement The total number of domestic subsidiaries not included in the financial statement.'),
17941 (1, 't', 1563, 'Total number of foreign subsidiaries included in financial statement', 'The total number of foreign subsidiaries included in the financial statement.'),
17942 (1, 't', 1564, 'Total number of domestic subsidiaries included in financial statement', 'The total number of domestic subsidiaries included in the financial statement.'),
17943 (1, 't', 1565, 'Total transactions', 'The total number of transactions.'),
17944 (1, 't', 1566, 'Paid-in preferred shares', 'The number of paid-in preferred shares.'),
17945 (1, 't', 1567, 'Employees', 'Code specifying the quantity of persons working for a company, whose services are used for pay.'),
17946 (1, 't', 1568, 'Active ingredient dose per unit, dispensed', 'The dosage of active ingredient per dispensed unit.'),
17947 (1, 't', 1569, 'Budget', 'Budget quantity.'),
17948 (1, 't', 1570, 'Budget, cumulative to date', 'Budget quantity, cumulative to date.'),
17949 (1, 't', 1571, 'Actual units', 'The number of actual units.'),
17950 (1, 't', 1572, 'Actual units, cumulative to date', 'The number of cumulative to date actual units.'),
17951 (1, 't', 1573, 'Earned value', 'Earned value quantity.'),
17952 (1, 't', 1574, 'Earned value, cumulative to date', 'Earned value quantity accumulated to date.'),
17953 (1, 't', 1575, 'At completion quantity, estimated', 'The estimated quantity when a project is complete.'),
17954 (1, 't', 1576, 'To complete quantity, estimated', 'The estimated quantity required to complete a project.'),
17955 (1, 't', 1577, 'Adjusted units', 'The number of adjusted units.'),
17956 (1, 't', 1578, 'Number of limited partnership shares', 'Number of shares held in a limited partnership.'),
17957 (1, 't', 1579, 'National business failure incidences', 'Number of firms in a country that discontinued with a loss to creditors.'),
17958 (1, 't', 1580, 'Industry business failure incidences', 'Number of firms in a specific industry that discontinued with a loss to creditors.'),
17959 (1, 't', 1581, 'Business class failure incidences', 'Number of firms in a specific class that discontinued with a loss to creditors.'),
17960 (1, 't', 1582, 'Mechanics', 'Number of mechanics.'),
17961 (1, 't', 1583, 'Messengers', 'Number of messengers.'),
17962 (1, 't', 1584, 'Primary managers', 'Number of primary managers.'),
17963 (1, 't', 1585, 'Secretaries', 'Number of secretaries.'),
17964 (1, 't', 1586, 'Detrimental legal filings', 'Number of detrimental legal filings.'),
17965 (1, 't', 1587, 'Branch office locations, estimated', 'Estimated number of branch office locations.'),
17966 (1, 't', 1588, 'Previous number of employees', 'The number of employees for a previous period.'),
17967 (1, 't', 1589, 'Asset seizers', 'Number of entities that seize assets of another entity.'),
17968 (1, 't', 1590, 'Out-turned quantity', 'The quantity discharged.'),
17969 (1, 't', 1591, 'Material on-board quantity, prior to loading', 'The material in vessel tanks, void spaces, and pipelines prior to loading.'),
17970 (1, 't', 1592, 'Supplier estimated previous meter reading', 'Previous meter reading estimated by the supplier.'),
17971 (1, 't', 1593, 'Supplier estimated latest meter reading',   'Latest meter reading estimated by the supplier.'),
17972 (1, 't', 1594, 'Customer estimated previous meter reading', 'Previous meter reading estimated by the customer.'),
17973 (1, 't', 1595, 'Customer estimated latest meter reading',   'Latest meter reading estimated by the customer.'),
17974 (1, 't', 1596, 'Supplier previous meter reading',           'Previous meter reading done by the supplier.'),
17975 (1, 't', 1597, 'Supplier latest meter reading',             'Latest meter reading recorded by the supplier.'),
17976 (1, 't', 1598, 'Maximum number of purchase orders allowed', 'Maximum number of purchase orders that are allowed.'),
17977 (1, 't', 1599, 'File size before compression', 'The size of a file before compression.'),
17978 (1, 't', 1600, 'File size after compression', 'The size of a file after compression.'),
17979 (1, 't', 1601, 'Securities shares', 'Number of shares of securities.'),
17980 (1, 't', 1602, 'Patients',         'Number of patients.'),
17981 (1, 't', 1603, 'Completed projects', 'Number of completed projects.'),
17982 (1, 't', 1604, 'Promoters',        'Number of entities who finance or organize an event or a production.'),
17983 (1, 't', 1605, 'Administrators',   'Number of administrators.'),
17984 (1, 't', 1606, 'Supervisors',      'Number of supervisors.'),
17985 (1, 't', 1607, 'Professionals',    'Number of professionals.'),
17986 (1, 't', 1608, 'Debt collectors',  'Number of debt collectors.'),
17987 (1, 't', 1609, 'Inspectors',       'Number of individuals who perform inspections.'),
17988 (1, 't', 1610, 'Operators',        'Number of operators.'),
17989 (1, 't', 1611, 'Trainers',         'Number of trainers.'),
17990 (1, 't', 1612, 'Active accounts',  'Number of accounts in a current or active status.'),
17991 (1, 't', 1613, 'Trademarks used',  'Number of trademarks used.'),
17992 (1, 't', 1614, 'Machines',         'Number of machines.'),
17993 (1, 't', 1615, 'Fuel pumps',       'Number of fuel pumps.'),
17994 (1, 't', 1616, 'Tables available', 'Number of tables available for use.'),
17995 (1, 't', 1617, 'Directors',        'Number of directors.'),
17996 (1, 't', 1618, 'Freelance debt collectors', 'Number of debt collectors who work on a freelance basis.'),
17997 (1, 't', 1619, 'Freelance salespersons',    'Number of salespersons who work on a freelance basis.'),
17998 (1, 't', 1620, 'Travelling employees',      'Number of travelling employees.'),
17999 (1, 't', 1621, 'Foremen', 'Number of workers with limited supervisory responsibilities.'),
18000 (1, 't', 1622, 'Production workers', 'Number of employees engaged in production.'),
18001 (1, 't', 1623, 'Employees not including owners', 'Number of employees excluding business owners.'),
18002 (1, 't', 1624, 'Beds', 'Number of beds.'),
18003 (1, 't', 1625, 'Resting quantity', 'A quantity of product that is at rest before it can be used.'),
18004 (1, 't', 1626, 'Production requirements', 'Quantity needed to meet production requirements.'),
18005 (1, 't', 1627, 'Corrected quantity', 'The quantity has been corrected.'),
18006 (1, 't', 1628, 'Operating divisions', 'Number of divisions operating.'),
18007 (1, 't', 1629, 'Quantitative incentive scheme base', 'Quantity constituting the base for the quantitative incentive scheme.'),
18008 (1, 't', 1630, 'Petitions filed', 'Number of petitions that have been filed.'),
18009 (1, 't', 1631, 'Bankruptcy petitions filed', 'Number of bankruptcy petitions that have been filed.'),
18010 (1, 't', 1632, 'Projects in process', 'Number of projects in process.'),
18011 (1, 't', 1633, 'Changes in capital structure', 'Number of modifications made to the capital structure of an entity.'),
18012 (1, 't', 1634, 'Detrimental legal filings against directors', 'The number of legal filings that are of a detrimental nature that have been filed against the directors.'),
18013 (1, 't', 1635, 'Number of failed businesses of directors', 'The number of failed businesses with which the directors have been associated.'),
18014 (1, 't', 1636, 'Professor', 'The number of professors.'),
18015 (1, 't', 1637, 'Seller',    'The number of sellers.'),
18016 (1, 't', 1638, 'Skilled worker', 'The number of skilled workers.'),
18017 (1, 't', 1639, 'Trademark represented', 'The number of trademarks represented.'),
18018 (1, 't', 1640, 'Number of quantitative incentive scheme units', 'Number of units allocated to a quantitative incentive scheme.'),
18019 (1, 't', 1641, 'Quantity in manufacturing process', 'Quantity currently in the manufacturing process.'),
18020 (1, 't', 1642, 'Number of units in the width of a layer', 'Number of units which make up the width of a layer.'),
18021 (1, 't', 1643, 'Number of units in the depth of a layer', 'Number of units which make up the depth of a layer.'),
18022 (1, 't', 1644, 'Return to warehouse', 'A quantity of products sent back to the warehouse.'),
18023 (1, 't', 1645, 'Return to the manufacturer', 'A quantity of products sent back from the manufacturer.'),
18024 (1, 't', 1646, 'Delta quantity', 'An increment or decrement to a quantity.'),
18025 (1, 't', 1647, 'Quantity moved between outlets', 'A quantity of products moved between outlets.'),
18026 (1, 't', 1648, 'Pre-paid invoice annual consumption, estimated', 'The estimated annual consumption used for a prepayment invoice.'),
18027 (1, 't', 1649, 'Total quoted quantity', 'The sum of quoted quantities.'),
18028 (1, 't', 1650, 'Requests pertaining to entity in last 12 months', 'Number of requests received in last 12 months pertaining to the entity.'),
18029 (1, 't', 1651, 'Total inquiry matches', 'Number of instances which correspond with the inquiry.'),
18030 (1, 't', 1652, 'En route to warehouse quantity',   'A quantity of products that is en route to a warehouse.'),
18031 (1, 't', 1653, 'En route from warehouse quantity', 'A quantity of products that is en route from a warehouse.'),
18032 (1, 't', 1654, 'Quantity ordered but not yet allocated from stock', 'A quantity of products which has been ordered but which has not yet been allocated from stock.'),
18033 (1, 't', 1655, 'Not yet ordered quantity', 'The quantity which has not yet been ordered.'),
18034 (1, 't', 1656, 'Net reserve power', 'The reserve power available for the net.'),
18035 (1, 't', 1657, 'Maximum number of units per shelf', 'Maximum number of units of a product that can be placed on a shelf.'),
18036 (1, 't', 1658, 'Stowaway', 'Number of stowaway(s) on a conveyance.'),
18037 (1, 't', 1659, 'Tug', 'The number of tugboat(s).'),
18038 (1, 't', 1660, 'Maximum quantity capability of the package', 'Maximum quantity of a product that can be contained in a package.'),
18039 (1, 't', 1661, 'Calculated', 'The calculated quantity.'),
18040 (1, 't', 1662, 'Monthly volume, estimated', 'Volume estimated for a month.'),
18041 (1, 't', 1663, 'Total number of persons', 'Quantity representing the total number of persons.'),
18042 (1, 't', 1664, 'Tariff Quantity', 'Quantity of the goods in the unit as required by Customs for duty/tax/fee assessment. These quantities may also be used for other fiscal or statistical purposes.'),
18043 (1, 't', 1665, 'Deducted tariff quantity',   'Quantity deducted from tariff quantity to reckon duty/tax/fee assessment bases.'),
18044 (1, 't', 1666, 'Advised but not arrived',    'Goods are advised by the consignor or supplier, but have not yet arrived at the destination.'),
18045 (1, 't', 1667, 'Received but not available', 'Goods have been received in the arrival area but are not yet available.'),
18046 (1, 't', 1668, 'Goods blocked for transshipment process', 'Goods are physically present, but can not be ordered because they are scheduled for a transshipment process.'),
18047 (1, 't', 1669, 'Goods blocked for cross docking process', 'Goods are physically present, but can not be ordered because they are scheduled for a cross docking process.'),
18048 (1, 't', 1670, 'Chargeable number of trailers', 'The number of trailers on which charges are based.'),
18049 (1, 't', 1671, 'Number of packages for a set', 'Number of packages used to pack the individual items in a grouping of merchandise that is sold together as a single trade item.'),
18050 (1, 't', 1672, 'Number of items in a set', 'The number of individual items in a grouping of merchandise that is sold together as a single trade item.'),
18051 (1, 't', 1673, 'Order sizing factor', 'A trade item specification other than gross, net weight, or volume for a trade item or a transaction, used for order sizing and pricing purposes.'),
18052 (1, 't', 1674, 'Number of different next lower level trade items', 'Value indicates the number of differrent next lower level trade items contained in a complex trade item.'),
18053 (1, 't', 1675, 'Agreed maximum buying quantity', 'The agreed maximum quantity of the trade item that may be purchased.'),
18054 (1, 't', 1676, 'Agreed minimum buying quantity', 'The agreed minimum quantity of the trade item that may be purchased.'),
18055 (1, 't', 1677, 'Free quantity of next lower level trade item', 'The numeric quantity of free items in a combination pack. The unit of measure used for the free quantity of the next lower level must be the same as the unit of measure of the Net Content of the Child Trade Item.'),
18056 (1, 't', 1678, 'Marine Diesel Oil bunkers on board, on arrival',     'Number of Marine Diesel Oil (MDO) bunkers on board when the vessel arrives in the port.'),
18057 (1, 't', 1679, 'Marine Diesel Oil bunkers, loaded',                  'Number of Marine Diesel Oil (MDO) bunkers taken on in the port.'),
18058 (1, 't', 1680, 'Intermediate Fuel Oil bunkers on board, on arrival', 'Number of Intermediate Fuel Oil (IFO) bunkers on board when the vessel arrives in the port.'),
18059 (1, 't', 1681, 'Intermediate Fuel Oil bunkers, loaded',              'Number of Intermediate Fuel Oil (IFO) bunkers taken on in the port.'),
18060 (1, 't', 1682, 'Bunker C bunkers on board, on arrival',              'Number of Bunker C, or Number 6 fuel oil bunkers on board when the vessel arrives in the port.'),
18061 (1, 't', 1683, 'Bunker C bunkers, loaded', 'Number of Bunker C, or Number 6 fuel oil bunkers, taken on in the port.'),
18062 (1, 't', 1684, 'Number of individual units within the smallest packaging', 'unit Total number of individual units contained within the smallest unit of packaging.'),
18063 (1, 't', 1685, 'Percentage of constituent element', 'The part of a product or material that is composed of the constituent element, as a percentage.'),
18064 (1, 't', 1686, 'Quantity to be decremented (LPCO)', 'Quantity to be decremented from the allowable quantity on a License, Permit, Certificate, or Other document (LPCO).'),
18065 (1, 't', 1687, 'Regulated commodity count', 'The number of regulated items.'),
18066 (1, 't', 1688, 'Number of passengers, embarking', 'The number of passengers going aboard a conveyance.'),
18067 (1, 't', 1689, 'Number of passengers, disembarking', 'The number of passengers disembarking the conveyance.'),
18068 (1, 't', 1690, 'Constituent element or component quantity', 'The specific quantity of the identified constituent element.')
18069 ;
18070 -- ZZZ, 'Mutually defined', 'As agreed by the trading partners.'),
18071
18072 CREATE TABLE acq.serial_claim (
18073     id     SERIAL           PRIMARY KEY,
18074     type   INT              NOT NULL REFERENCES acq.claim_type
18075                                      DEFERRABLE INITIALLY DEFERRED,
18076     item    BIGINT          NOT NULL REFERENCES serial.item
18077                                      DEFERRABLE INITIALLY DEFERRED
18078 );
18079
18080 CREATE INDEX serial_claim_lid_idx ON acq.serial_claim( item );
18081
18082 CREATE TABLE acq.serial_claim_event (
18083     id             BIGSERIAL        PRIMARY KEY,
18084     type           INT              NOT NULL REFERENCES acq.claim_event_type
18085                                              DEFERRABLE INITIALLY DEFERRED,
18086     claim          SERIAL           NOT NULL REFERENCES acq.serial_claim
18087                                              DEFERRABLE INITIALLY DEFERRED,
18088     event_date     TIMESTAMPTZ      NOT NULL DEFAULT now(),
18089     creator        INT              NOT NULL REFERENCES actor.usr
18090                                              DEFERRABLE INITIALLY DEFERRED,
18091     note           TEXT
18092 );
18093
18094 CREATE INDEX serial_claim_event_claim_date_idx ON acq.serial_claim_event( claim, event_date );
18095
18096 ALTER TABLE asset.stat_cat ADD COLUMN required BOOL NOT NULL DEFAULT FALSE;
18097
18098 -- now what about the auditor.*_lifecycle views??
18099
18100 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath ) VALUES
18101     (26, 'identifier', 'tcn', oils_i18n_gettext(26, 'Title Control Number', 'cmf', 'label'), 'marcxml', $$//marc:datafield[@tag='901']/marc:subfield[@code='a']$$ );
18102 INSERT INTO config.metabib_field ( id, field_class, name, label, format, xpath ) VALUES
18103     (27, 'identifier', 'bibid', oils_i18n_gettext(27, 'Internal ID', 'cmf', 'label'), 'marcxml', $$//marc:datafield[@tag='901']/marc:subfield[@code='c']$$ );
18104 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('eg.tcn','identifier', 26);
18105 INSERT INTO config.metabib_search_alias (alias,field_class,field) VALUES ('eg.bibid','identifier', 27);
18106
18107 CREATE TABLE asset.call_number_class (
18108     id             bigserial     PRIMARY KEY,
18109     name           TEXT          NOT NULL,
18110     normalizer     TEXT          NOT NULL DEFAULT 'asset.normalize_generic',
18111     field          TEXT          NOT NULL DEFAULT '050ab,055ab,060ab,070ab,080ab,082ab,086ab,088ab,090,092,096,098,099'
18112 );
18113
18114 COMMENT ON TABLE asset.call_number_class IS $$
18115 Defines the call number normalization database functions in the "normalizer"
18116 column and the tag/subfield combinations to use to lookup the call number in
18117 the "field" column for a given classification scheme. Tag/subfield combinations
18118 are delimited by commas.
18119 $$;
18120
18121 INSERT INTO asset.call_number_class (name, normalizer) VALUES 
18122     ('Generic', 'asset.label_normalizer_generic'),
18123     ('Dewey (DDC)', 'asset.label_normalizer_dewey'),
18124     ('Library of Congress (LC)', 'asset.label_normalizer_lc')
18125 ;
18126
18127 -- Generic fields
18128 UPDATE asset.call_number_class
18129     SET field = '050ab,055ab,060ab,070ab,080ab,082ab,086ab,088ab,090,092,096,098,099'
18130     WHERE id = 1
18131 ;
18132
18133 -- Dewey fields
18134 UPDATE asset.call_number_class
18135     SET field = '080ab,082ab'
18136     WHERE id = 2
18137 ;
18138
18139 -- LC fields
18140 UPDATE asset.call_number_class
18141     SET field = '050ab,055ab'
18142     WHERE id = 3
18143 ;
18144  
18145 ALTER TABLE asset.call_number
18146         ADD COLUMN label_class BIGINT DEFAULT 1 NOT NULL
18147                 REFERENCES asset.call_number_class(id)
18148                 DEFERRABLE INITIALLY DEFERRED;
18149
18150 ALTER TABLE asset.call_number
18151         ADD COLUMN label_sortkey TEXT;
18152
18153 CREATE INDEX asset_call_number_label_sortkey
18154         ON asset.call_number(oils_text_as_bytea(label_sortkey));
18155
18156 ALTER TABLE auditor.asset_call_number_history
18157         ADD COLUMN label_class BIGINT;
18158
18159 ALTER TABLE auditor.asset_call_number_history
18160         ADD COLUMN label_sortkey TEXT;
18161
18162 -- Pick up the new columns in dependent views
18163
18164 DROP VIEW auditor.asset_call_number_lifecycle;
18165
18166 SELECT auditor.create_auditor_lifecycle( 'asset', 'call_number' );
18167
18168 DROP VIEW auditor.asset_call_number_lifecycle;
18169
18170 SELECT auditor.create_auditor_lifecycle( 'asset', 'call_number' );
18171
18172 DROP VIEW IF EXISTS stats.fleshed_call_number;
18173
18174 CREATE VIEW stats.fleshed_call_number AS
18175         SELECT  cn.*,
18176             CAST(cn.create_date AS DATE) AS create_date_day,
18177         CAST(cn.edit_date AS DATE) AS edit_date_day,
18178         DATE_TRUNC('hour', cn.create_date) AS create_date_hour,
18179         DATE_TRUNC('hour', cn.edit_date) AS edit_date_hour,
18180             rd.item_lang,
18181                 rd.item_type,
18182                 rd.item_form
18183         FROM    asset.call_number cn
18184                 JOIN metabib.rec_descriptor rd ON (rd.record = cn.record);
18185
18186 CREATE OR REPLACE FUNCTION asset.label_normalizer() RETURNS TRIGGER AS $func$
18187 DECLARE
18188     sortkey        TEXT := '';
18189 BEGIN
18190     sortkey := NEW.label_sortkey;
18191
18192     EXECUTE 'SELECT ' || acnc.normalizer || '(' || 
18193        quote_literal( NEW.label ) || ')'
18194        FROM asset.call_number_class acnc
18195        WHERE acnc.id = NEW.label_class
18196        INTO sortkey;
18197
18198     NEW.label_sortkey = sortkey;
18199
18200     RETURN NEW;
18201 END;
18202 $func$ LANGUAGE PLPGSQL;
18203
18204 CREATE OR REPLACE FUNCTION asset.label_normalizer_generic(TEXT) RETURNS TEXT AS $func$
18205     # Created after looking at the Koha C4::ClassSortRoutine::Generic module,
18206     # thus could probably be considered a derived work, although nothing was
18207     # directly copied - but to err on the safe side of providing attribution:
18208     # Copyright (C) 2007 LibLime
18209     # Licensed under the GPL v2 or later
18210
18211     use strict;
18212     use warnings;
18213
18214     # Converts the callnumber to uppercase
18215     # Strips spaces from start and end of the call number
18216     # Converts anything other than letters, digits, and periods into underscores
18217     # Collapses multiple underscores into a single underscore
18218     my $callnum = uc(shift);
18219     $callnum =~ s/^\s//g;
18220     $callnum =~ s/\s$//g;
18221     $callnum =~ s/[^A-Z0-9_.]/_/g;
18222     $callnum =~ s/_{2,}/_/g;
18223
18224     return $callnum;
18225 $func$ LANGUAGE PLPERLU;
18226
18227 CREATE OR REPLACE FUNCTION asset.label_normalizer_dewey(TEXT) RETURNS TEXT AS $func$
18228     # Derived from the Koha C4::ClassSortRoutine::Dewey module
18229     # Copyright (C) 2007 LibLime
18230     # Licensed under the GPL v2 or later
18231
18232     use strict;
18233     use warnings;
18234
18235     my $init = uc(shift);
18236     $init =~ s/^\s+//;
18237     $init =~ s/\s+$//;
18238     $init =~ s!/!!g;
18239     $init =~ s/^([\p{IsAlpha}]+)/$1 /;
18240     my @tokens = split /\.|\s+/, $init;
18241     my $digit_group_count = 0;
18242     for (my $i = 0; $i <= $#tokens; $i++) {
18243         if ($tokens[$i] =~ /^\d+$/) {
18244             $digit_group_count++;
18245             if (2 == $digit_group_count) {
18246                 $tokens[$i] = sprintf("%-15.15s", $tokens[$i]);
18247                 $tokens[$i] =~ tr/ /0/;
18248             }
18249         }
18250     }
18251     my $key = join("_", @tokens);
18252     $key =~ s/[^\p{IsAlnum}_]//g;
18253
18254     return $key;
18255
18256 $func$ LANGUAGE PLPERLU;
18257
18258 CREATE OR REPLACE FUNCTION asset.label_normalizer_lc(TEXT) RETURNS TEXT AS $func$
18259     use strict;
18260     use warnings;
18261
18262     # Library::CallNumber::LC is currently hosted at http://code.google.com/p/library-callnumber-lc/
18263     # The author hopes to upload it to CPAN some day, which would make our lives easier
18264     use Library::CallNumber::LC;
18265
18266     my $callnum = Library::CallNumber::LC->new(shift);
18267     return $callnum->normalize();
18268
18269 $func$ LANGUAGE PLPERLU;
18270
18271 CREATE OR REPLACE FUNCTION asset.opac_ou_record_copy_count (org INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18272 DECLARE
18273     ans RECORD;
18274     trans INT;
18275 BEGIN
18276     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18277
18278     FOR ans IN SELECT u.id, t.depth FROM actor.org_unit_ancestors(org) AS u JOIN actor.org_unit_type t ON (u.ou_type = t.id) LOOP
18279         RETURN QUERY
18280         SELECT  ans.depth,
18281                 ans.id,
18282                 COUNT( av.id ),
18283                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18284                 COUNT( av.id ),
18285                 trans
18286           FROM
18287                 actor.org_unit_descendants(ans.id) d
18288                 JOIN asset.opac_visible_copies av ON (av.record = record AND av.circ_lib = d.id)
18289                 JOIN asset.copy cp ON (cp.id = av.id)
18290           GROUP BY 1,2,6;
18291
18292         IF NOT FOUND THEN
18293             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18294         END IF;
18295
18296     END LOOP;
18297
18298     RETURN;
18299 END;
18300 $f$ LANGUAGE PLPGSQL;
18301
18302 CREATE OR REPLACE FUNCTION asset.opac_lasso_record_copy_count (i_lasso INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18303 DECLARE
18304     ans RECORD;
18305     trans INT;
18306 BEGIN
18307     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18308
18309     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
18310         RETURN QUERY
18311         SELECT  -1,
18312                 ans.id,
18313                 COUNT( av.id ),
18314                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18315                 COUNT( av.id ),
18316                 trans
18317           FROM
18318                 actor.org_unit_descendants(ans.id) d
18319                 JOIN asset.opac_visible_copies av ON (av.record = record AND av.circ_lib = d.id)
18320                 JOIN asset.copy cp ON (cp.id = av.id)
18321           GROUP BY 1,2,6;
18322
18323         IF NOT FOUND THEN
18324             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18325         END IF;
18326
18327     END LOOP;
18328
18329     RETURN;
18330 END;
18331 $f$ LANGUAGE PLPGSQL;
18332
18333 CREATE OR REPLACE FUNCTION asset.staff_ou_record_copy_count (org INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18334 DECLARE
18335     ans RECORD;
18336     trans INT;
18337 BEGIN
18338     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18339
18340     FOR ans IN SELECT u.id, t.depth FROM actor.org_unit_ancestors(org) AS u JOIN actor.org_unit_type t ON (u.ou_type = t.id) LOOP
18341         RETURN QUERY
18342         SELECT  ans.depth,
18343                 ans.id,
18344                 COUNT( cp.id ),
18345                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18346                 COUNT( cp.id ),
18347                 trans
18348           FROM
18349                 actor.org_unit_descendants(ans.id) d
18350                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
18351                 JOIN asset.call_number cn ON (cn.record = record AND cn.id = cp.call_number)
18352           GROUP BY 1,2,6;
18353
18354         IF NOT FOUND THEN
18355             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18356         END IF;
18357
18358     END LOOP;
18359
18360     RETURN;
18361 END;
18362 $f$ LANGUAGE PLPGSQL;
18363
18364 CREATE OR REPLACE FUNCTION asset.staff_lasso_record_copy_count (i_lasso INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18365 DECLARE
18366     ans RECORD;
18367     trans INT;
18368 BEGIN
18369     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18370
18371     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
18372         RETURN QUERY
18373         SELECT  -1,
18374                 ans.id,
18375                 COUNT( cp.id ),
18376                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18377                 COUNT( cp.id ),
18378                 trans
18379           FROM
18380                 actor.org_unit_descendants(ans.id) d
18381                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
18382                 JOIN asset.call_number cn ON (cn.record = record AND cn.id = cp.call_number)
18383           GROUP BY 1,2,6;
18384
18385         IF NOT FOUND THEN
18386             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18387         END IF;
18388
18389     END LOOP;
18390
18391     RETURN;
18392 END;
18393 $f$ LANGUAGE PLPGSQL;
18394
18395 CREATE OR REPLACE FUNCTION asset.record_copy_count ( place INT, record BIGINT, staff BOOL) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18396 BEGIN
18397     IF staff IS TRUE THEN
18398         IF place > 0 THEN
18399             RETURN QUERY SELECT * FROM asset.staff_ou_record_copy_count( place, record );
18400         ELSE
18401             RETURN QUERY SELECT * FROM asset.staff_lasso_record_copy_count( -place, record );
18402         END IF;
18403     ELSE
18404         IF place > 0 THEN
18405             RETURN QUERY SELECT * FROM asset.opac_ou_record_copy_count( place, record );
18406         ELSE
18407             RETURN QUERY SELECT * FROM asset.opac_lasso_record_copy_count( -place, record );
18408         END IF;
18409     END IF;
18410
18411     RETURN;
18412 END;
18413 $f$ LANGUAGE PLPGSQL;
18414
18415 CREATE OR REPLACE FUNCTION asset.opac_ou_metarecord_copy_count (org INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18416 DECLARE
18417     ans RECORD;
18418     trans INT;
18419 BEGIN
18420     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18421
18422     FOR ans IN SELECT u.id, t.depth FROM actor.org_unit_ancestors(org) AS u JOIN actor.org_unit_type t ON (u.ou_type = t.id) LOOP
18423         RETURN QUERY
18424         SELECT  ans.depth,
18425                 ans.id,
18426                 COUNT( av.id ),
18427                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18428                 COUNT( av.id ),
18429                 trans
18430           FROM
18431                 actor.org_unit_descendants(ans.id) d
18432                 JOIN asset.opac_visible_copies av ON (av.record = record AND av.circ_lib = d.id)
18433                 JOIN asset.copy cp ON (cp.id = av.id)
18434                 JOIN metabib.metarecord_source_map m ON (m.source = av.record)
18435           GROUP BY 1,2,6;
18436
18437         IF NOT FOUND THEN
18438             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18439         END IF;
18440
18441     END LOOP;
18442
18443     RETURN;
18444 END;
18445 $f$ LANGUAGE PLPGSQL;
18446
18447 CREATE OR REPLACE FUNCTION asset.opac_lasso_metarecord_copy_count (i_lasso INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18448 DECLARE
18449     ans RECORD;
18450     trans INT;
18451 BEGIN
18452     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18453
18454     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
18455         RETURN QUERY
18456         SELECT  -1,
18457                 ans.id,
18458                 COUNT( av.id ),
18459                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18460                 COUNT( av.id ),
18461                 trans
18462           FROM
18463                 actor.org_unit_descendants(ans.id) d
18464                 JOIN asset.opac_visible_copies av ON (av.record = record AND av.circ_lib = d.id)
18465                 JOIN asset.copy cp ON (cp.id = av.id)
18466                 JOIN metabib.metarecord_source_map m ON (m.source = av.record)
18467           GROUP BY 1,2,6;
18468
18469         IF NOT FOUND THEN
18470             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18471         END IF;
18472
18473     END LOOP;
18474
18475     RETURN;
18476 END;
18477 $f$ LANGUAGE PLPGSQL;
18478
18479 CREATE OR REPLACE FUNCTION asset.staff_ou_metarecord_copy_count (org INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18480 DECLARE
18481     ans RECORD;
18482     trans INT;
18483 BEGIN
18484     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18485
18486     FOR ans IN SELECT u.id, t.depth FROM actor.org_unit_ancestors(org) AS u JOIN actor.org_unit_type t ON (u.ou_type = t.id) LOOP
18487         RETURN QUERY
18488         SELECT  ans.depth,
18489                 ans.id,
18490                 COUNT( cp.id ),
18491                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18492                 COUNT( cp.id ),
18493                 trans
18494           FROM
18495                 actor.org_unit_descendants(ans.id) d
18496                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
18497                 JOIN asset.call_number cn ON (cn.record = record AND cn.id = cp.call_number)
18498                 JOIN metabib.metarecord_source_map m ON (m.source = cn.record)
18499           GROUP BY 1,2,6;
18500
18501         IF NOT FOUND THEN
18502             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18503         END IF;
18504
18505     END LOOP;
18506
18507     RETURN;
18508 END;
18509 $f$ LANGUAGE PLPGSQL;
18510
18511 CREATE OR REPLACE FUNCTION asset.staff_lasso_metarecord_copy_count (i_lasso INT, record BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18512 DECLARE
18513     ans RECORD;
18514     trans INT;
18515 BEGIN
18516     SELECT 1 INTO trans FROM biblio.record_entry b JOIN config.bib_source src ON (b.source = src.id) WHERE src.transcendant AND b.id = record;
18517
18518     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
18519         RETURN QUERY
18520         SELECT  -1,
18521                 ans.id,
18522                 COUNT( cp.id ),
18523                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
18524                 COUNT( cp.id ),
18525                 trans
18526           FROM
18527                 actor.org_unit_descendants(ans.id) d
18528                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
18529                 JOIN asset.call_number cn ON (cn.record = record AND cn.id = cp.call_number)
18530                 JOIN metabib.metarecord_source_map m ON (m.source = cn.record)
18531           GROUP BY 1,2,6;
18532
18533         IF NOT FOUND THEN
18534             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
18535         END IF;
18536
18537     END LOOP;
18538
18539     RETURN;
18540 END;
18541 $f$ LANGUAGE PLPGSQL;
18542
18543 CREATE OR REPLACE FUNCTION asset.metarecord_copy_count ( place INT, record BIGINT, staff BOOL) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
18544 BEGIN
18545     IF staff IS TRUE THEN
18546         IF place > 0 THEN
18547             RETURN QUERY SELECT * FROM asset.staff_ou_metarecord_copy_count( place, record );
18548         ELSE
18549             RETURN QUERY SELECT * FROM asset.staff_lasso_metarecord_copy_count( -place, record );
18550         END IF;
18551     ELSE
18552         IF place > 0 THEN
18553             RETURN QUERY SELECT * FROM asset.opac_ou_metarecord_copy_count( place, record );
18554         ELSE
18555             RETURN QUERY SELECT * FROM asset.opac_lasso_metarecord_copy_count( -place, record );
18556         END IF;
18557     END IF;
18558
18559     RETURN;
18560 END;
18561 $f$ LANGUAGE PLPGSQL;
18562
18563 -- No transaction is required
18564
18565 -- Triggers on the vandelay.queued_*_record tables delete entries from
18566 -- the associated vandelay.queued_*_record_attr tables based on the record's
18567 -- ID; create an index on that column to avoid sequential scans for each
18568 -- queued record that is deleted
18569 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
18570 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
18571
18572 -- Avoid sequential scans for queue retrieval operations by providing an
18573 -- index on the queue column
18574 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
18575 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
18576
18577 -- Start picking up call number label prefixes and suffixes
18578 -- from asset.copy_location
18579 ALTER TABLE asset.copy_location ADD COLUMN label_prefix TEXT;
18580 ALTER TABLE asset.copy_location ADD COLUMN label_suffix TEXT;
18581
18582 DROP VIEW auditor.asset_copy_lifecycle;
18583
18584 SELECT auditor.create_auditor_lifecycle( 'asset', 'copy' );
18585
18586 ALTER TABLE reporter.report RENAME COLUMN recurance TO recurrence;
18587
18588 -- Let's not break existing reports
18589 UPDATE reporter.template SET data = REGEXP_REPLACE(data, E'^(.*)recuring(.*)$', E'\\1recurring\\2') WHERE data LIKE '%recuring%';
18590 UPDATE reporter.template SET data = REGEXP_REPLACE(data, E'^(.*)recurance(.*)$', E'\\1recurrence\\2') WHERE data LIKE '%recurance%';
18591
18592 -- Need to recreate this view with DISTINCT calls to ARRAY_ACCUM, thus avoiding duplicated ISBN and ISSN values
18593 CREATE OR REPLACE VIEW reporter.old_super_simple_record AS
18594 SELECT  r.id,
18595     r.fingerprint,
18596     r.quality,
18597     r.tcn_source,
18598     r.tcn_value,
18599     FIRST(title.value) AS title,
18600     FIRST(author.value) AS author,
18601     ARRAY_TO_STRING(ARRAY_ACCUM( DISTINCT publisher.value), ', ') AS publisher,
18602     ARRAY_TO_STRING(ARRAY_ACCUM( DISTINCT SUBSTRING(pubdate.value FROM $$\d+$$) ), ', ') AS pubdate,
18603     ARRAY_ACCUM( DISTINCT SUBSTRING(isbn.value FROM $$^\S+$$) ) AS isbn,
18604     ARRAY_ACCUM( DISTINCT SUBSTRING(issn.value FROM $$^\S+$$) ) AS issn
18605   FROM  biblio.record_entry r
18606     LEFT JOIN metabib.full_rec title ON (r.id = title.record AND title.tag = '245' AND title.subfield = 'a')
18607     LEFT JOIN metabib.full_rec author ON (r.id = author.record AND author.tag IN ('100','110','111') AND author.subfield = 'a')
18608     LEFT JOIN metabib.full_rec publisher ON (r.id = publisher.record AND publisher.tag = '260' AND publisher.subfield = 'b')
18609     LEFT JOIN metabib.full_rec pubdate ON (r.id = pubdate.record AND pubdate.tag = '260' AND pubdate.subfield = 'c')
18610     LEFT JOIN metabib.full_rec isbn ON (r.id = isbn.record AND isbn.tag IN ('024', '020') AND isbn.subfield IN ('a','z'))
18611     LEFT JOIN metabib.full_rec issn ON (r.id = issn.record AND issn.tag = '022' AND issn.subfield = 'a')
18612   GROUP BY 1,2,3,4,5;
18613
18614 -- Correct the ISSN array definition for reporter.simple_record
18615
18616 CREATE OR REPLACE VIEW reporter.simple_record AS
18617 SELECT  r.id,
18618         s.metarecord,
18619         r.fingerprint,
18620         r.quality,
18621         r.tcn_source,
18622         r.tcn_value,
18623         title.value AS title,
18624         uniform_title.value AS uniform_title,
18625         author.value AS author,
18626         publisher.value AS publisher,
18627         SUBSTRING(pubdate.value FROM $$\d+$$) AS pubdate,
18628         series_title.value AS series_title,
18629         series_statement.value AS series_statement,
18630         summary.value AS summary,
18631         ARRAY_ACCUM( SUBSTRING(isbn.value FROM $$^\S+$$) ) AS isbn,
18632         ARRAY_ACCUM( REGEXP_REPLACE(issn.value, E'^\\S*(\\d{4})[-\\s](\\d{3,4}x?)', E'\\1 \\2') ) AS issn,
18633         ARRAY((SELECT DISTINCT value FROM metabib.full_rec WHERE tag = '650' AND subfield = 'a' AND record = r.id)) AS topic_subject,
18634         ARRAY((SELECT DISTINCT value FROM metabib.full_rec WHERE tag = '651' AND subfield = 'a' AND record = r.id)) AS geographic_subject,
18635         ARRAY((SELECT DISTINCT value FROM metabib.full_rec WHERE tag = '655' AND subfield = 'a' AND record = r.id)) AS genre,
18636         ARRAY((SELECT DISTINCT value FROM metabib.full_rec WHERE tag = '600' AND subfield = 'a' AND record = r.id)) AS name_subject,
18637         ARRAY((SELECT DISTINCT value FROM metabib.full_rec WHERE tag = '610' AND subfield = 'a' AND record = r.id)) AS corporate_subject,
18638         ARRAY((SELECT value FROM metabib.full_rec WHERE tag = '856' AND subfield IN ('3','y','u') AND record = r.id ORDER BY CASE WHEN subfield IN ('3','y') THEN 0 ELSE 1 END)) AS external_uri
18639   FROM  biblio.record_entry r
18640         JOIN metabib.metarecord_source_map s ON (s.source = r.id)
18641         LEFT JOIN metabib.full_rec uniform_title ON (r.id = uniform_title.record AND uniform_title.tag = '240' AND uniform_title.subfield = 'a')
18642         LEFT JOIN metabib.full_rec title ON (r.id = title.record AND title.tag = '245' AND title.subfield = 'a')
18643         LEFT JOIN metabib.full_rec author ON (r.id = author.record AND author.tag = '100' AND author.subfield = 'a')
18644         LEFT JOIN metabib.full_rec publisher ON (r.id = publisher.record AND publisher.tag = '260' AND publisher.subfield = 'b')
18645         LEFT JOIN metabib.full_rec pubdate ON (r.id = pubdate.record AND pubdate.tag = '260' AND pubdate.subfield = 'c')
18646         LEFT JOIN metabib.full_rec isbn ON (r.id = isbn.record AND isbn.tag IN ('024', '020') AND isbn.subfield IN ('a','z'))
18647         LEFT JOIN metabib.full_rec issn ON (r.id = issn.record AND issn.tag = '022' AND issn.subfield = 'a')
18648         LEFT JOIN metabib.full_rec series_title ON (r.id = series_title.record AND series_title.tag IN ('830','440') AND series_title.subfield = 'a')
18649         LEFT JOIN metabib.full_rec series_statement ON (r.id = series_statement.record AND series_statement.tag = '490' AND series_statement.subfield = 'a')
18650         LEFT JOIN metabib.full_rec summary ON (r.id = summary.record AND summary.tag = '520' AND summary.subfield = 'a')
18651   GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14;
18652
18653 CREATE OR REPLACE FUNCTION reporter.disable_materialized_simple_record_trigger () RETURNS VOID AS $$
18654     DROP TRIGGER IF EXISTS zzz_update_materialized_simple_record_tgr ON metabib.real_full_rec;
18655 $$ LANGUAGE SQL;
18656
18657 CREATE OR REPLACE FUNCTION reporter.simple_rec_trigger () RETURNS TRIGGER AS $func$
18658 BEGIN
18659     IF TG_OP = 'DELETE' THEN
18660         PERFORM reporter.simple_rec_delete(NEW.id);
18661     ELSE
18662         PERFORM reporter.simple_rec_update(NEW.id);
18663     END IF;
18664
18665     RETURN NEW;
18666 END;
18667 $func$ LANGUAGE PLPGSQL;
18668
18669 CREATE TRIGGER bbb_simple_rec_trigger AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE reporter.simple_rec_trigger ();
18670
18671 ALTER TABLE extend_reporter.legacy_circ_count DROP CONSTRAINT legacy_circ_count_id_fkey;
18672
18673 CREATE INDEX asset_copy_note_owning_copy_idx ON asset.copy_note ( owning_copy );
18674
18675 UPDATE config.org_unit_setting_type
18676     SET view_perm = (SELECT id FROM permission.perm_list
18677         WHERE code = 'VIEW_CREDIT_CARD_PROCESSING' LIMIT 1)
18678     WHERE name LIKE 'credit.processor%' AND view_perm IS NULL;
18679
18680 UPDATE config.org_unit_setting_type
18681     SET update_perm = (SELECT id FROM permission.perm_list
18682         WHERE code = 'ADMIN_CREDIT_CARD_PROCESSING' LIMIT 1)
18683     WHERE name LIKE 'credit.processor%' AND update_perm IS NULL;
18684
18685 INSERT INTO config.org_unit_setting_type (name, label, description, datatype)
18686     VALUES (
18687         'opac.fully_compressed_serial_holdings',
18688         'OPAC: Use fully compressed serial holdings',
18689         'Show fully compressed serial holdings for all libraries at and below
18690         the current context unit',
18691         'bool'
18692     );
18693
18694 CREATE OR REPLACE FUNCTION authority.normalize_heading( TEXT ) RETURNS TEXT AS $func$
18695     use strict;
18696     use warnings;
18697
18698     use utf8;
18699     use MARC::Record;
18700     use MARC::File::XML (BinaryEncoding => 'UTF8');
18701     use UUID::Tiny ':std';
18702
18703     my $xml = shift() or return undef;
18704
18705     my $r;
18706
18707     # Prevent errors in XML parsing from blowing out ungracefully
18708     eval {
18709         $r = MARC::Record->new_from_xml( $xml );
18710         1;
18711     } or do {
18712        return 'BAD_MARCXML_' . create_uuid_as_string(UUID_MD5, $xml);
18713     };
18714
18715     if (!$r) {
18716        return 'BAD_MARCXML_' . create_uuid_as_string(UUID_MD5, $xml);
18717     }
18718
18719     # From http://www.loc.gov/standards/sourcelist/subject.html
18720     my $thes_code_map = {
18721         a => 'lcsh',
18722         b => 'lcshac',
18723         c => 'mesh',
18724         d => 'nal',
18725         k => 'cash',
18726         n => 'notapplicable',
18727         r => 'aat',
18728         s => 'sears',
18729         v => 'rvm',
18730     };
18731
18732     # Default to "No attempt to code" if the leader is horribly broken
18733     my $fixed_field = $r->field('008');
18734     my $thes_char = '|';
18735     if ($fixed_field) {
18736         $thes_char = substr($fixed_field->data(), 11, 1) || '|';
18737     }
18738
18739     my $thes_code = 'UNDEFINED';
18740
18741     if ($thes_char eq 'z') {
18742         # Grab the 040 $f per http://www.loc.gov/marc/authority/ad040.html
18743         $thes_code = $r->subfield('040', 'f') || 'UNDEFINED';
18744     } elsif ($thes_code_map->{$thes_char}) {
18745         $thes_code = $thes_code_map->{$thes_char};
18746     }
18747
18748     my $auth_txt = '';
18749     my $head = $r->field('1..');
18750     if ($head) {
18751         # Concatenate all of these subfields together, prefixed by their code
18752         # to prevent collisions along the lines of "Fiction, North Carolina"
18753         foreach my $sf ($head->subfields()) {
18754             $auth_txt .= '‡' . $sf->[0] . ' ' . $sf->[1];
18755         }
18756     }
18757
18758     # Perhaps better to parameterize the spi and pass as a parameter
18759     $auth_txt =~ s/'//go;
18760
18761     if ($auth_txt) {
18762         my $result = spi_exec_query("SELECT public.naco_normalize('$auth_txt') AS norm_text");
18763         my $norm_txt = $result->{rows}[0]->{norm_text};
18764         return $head->tag() . "_" . $thes_code . " " . $norm_txt;
18765     }
18766
18767     return 'NOHEADING_' . $thes_code . ' ' . create_uuid_as_string(UUID_MD5, $xml);
18768 $func$ LANGUAGE 'plperlu' IMMUTABLE;
18769
18770 COMMENT ON FUNCTION authority.normalize_heading( TEXT ) IS $$
18771 /**
18772 * Extract the authority heading, thesaurus, and NACO-normalized values
18773 * from an authority record. The primary purpose is to build a unique
18774 * index to defend against duplicated authority records from the same
18775 * thesaurus.
18776 */
18777 $$;
18778
18779 DROP INDEX authority.authority_record_unique_tcn;
18780 ALTER TABLE authority.record_entry DROP COLUMN arn_value;
18781 ALTER TABLE authority.record_entry DROP COLUMN arn_source;
18782
18783 ALTER TABLE acq.provider_contact
18784         ALTER COLUMN name SET NOT NULL;
18785
18786 ALTER TABLE actor.stat_cat
18787         ADD COLUMN usr_summary BOOL NOT NULL DEFAULT FALSE;
18788
18789 -- Recreate some foreign keys that were somehow dropped, probably
18790 -- by some kind of cascade from an inherited table:
18791
18792 ALTER TABLE action.reservation_transit_copy
18793         ADD CONSTRAINT artc_tc_fkey FOREIGN KEY (target_copy)
18794                 REFERENCES booking.resource(id)
18795                 ON DELETE CASCADE
18796                 DEFERRABLE INITIALLY DEFERRED,
18797         ADD CONSTRAINT reservation_transit_copy_reservation_fkey FOREIGN KEY (reservation)
18798                 REFERENCES booking.reservation(id)
18799                 ON DELETE SET NULL
18800                 DEFERRABLE INITIALLY DEFERRED;
18801
18802 CREATE INDEX user_bucket_item_target_user_idx
18803         ON container.user_bucket_item ( target_user );
18804
18805 CREATE INDEX m_c_t_collector_idx
18806         ON money.collections_tracker ( collector );
18807
18808 CREATE INDEX aud_actor_usr_address_hist_id_idx
18809         ON auditor.actor_usr_address_history ( id );
18810
18811 CREATE INDEX aud_actor_usr_hist_id_idx
18812         ON auditor.actor_usr_history ( id );
18813
18814 CREATE INDEX aud_asset_cn_hist_creator_idx
18815         ON auditor.asset_call_number_history ( creator );
18816
18817 CREATE INDEX aud_asset_cn_hist_editor_idx
18818         ON auditor.asset_call_number_history ( editor );
18819
18820 CREATE INDEX aud_asset_cp_hist_creator_idx
18821         ON auditor.asset_copy_history ( creator );
18822
18823 CREATE INDEX aud_asset_cp_hist_editor_idx
18824         ON auditor.asset_copy_history ( editor );
18825
18826 CREATE INDEX aud_bib_rec_entry_hist_creator_idx
18827         ON auditor.biblio_record_entry_history ( creator );
18828
18829 CREATE INDEX aud_bib_rec_entry_hist_editor_idx
18830         ON auditor.biblio_record_entry_history ( editor );
18831
18832 CREATE TABLE action.hold_request_note (
18833
18834     id     BIGSERIAL PRIMARY KEY,
18835     hold   BIGINT    NOT NULL REFERENCES action.hold_request (id)
18836                               ON DELETE CASCADE
18837                               DEFERRABLE INITIALLY DEFERRED,
18838     title  TEXT      NOT NULL,
18839     body   TEXT      NOT NULL,
18840     slip   BOOL      NOT NULL DEFAULT FALSE,
18841     pub    BOOL      NOT NULL DEFAULT FALSE,
18842     staff  BOOL      NOT NULL DEFAULT FALSE  -- created by staff
18843
18844 );
18845 CREATE INDEX ahrn_hold_idx ON action.hold_request_note (hold);
18846
18847 -- Tweak a constraint to add a CASCADE
18848
18849 ALTER TABLE action.hold_notification DROP CONSTRAINT hold_notification_hold_fkey;
18850
18851 ALTER TABLE action.hold_notification
18852         ADD CONSTRAINT hold_notification_hold_fkey
18853                 FOREIGN KEY (hold) REFERENCES action.hold_request (id)
18854                 ON DELETE CASCADE
18855                 DEFERRABLE INITIALLY DEFERRED;
18856
18857 CREATE TRIGGER asset_label_sortkey_trigger
18858     BEFORE UPDATE OR INSERT ON asset.call_number
18859     FOR EACH ROW EXECUTE PROCEDURE asset.label_normalizer();
18860
18861 CREATE OR REPLACE FUNCTION container.clear_all_expired_circ_history_items( )
18862 RETURNS VOID AS $$
18863 --
18864 -- Delete expired circulation bucket items for all users that have
18865 -- a setting for patron.max_reading_list_interval.
18866 --
18867 DECLARE
18868     today        TIMESTAMP WITH TIME ZONE;
18869     threshold    TIMESTAMP WITH TIME ZONE;
18870         usr_setting  RECORD;
18871 BEGIN
18872         SELECT date_trunc( 'day', now() ) INTO today;
18873         --
18874         FOR usr_setting in
18875                 SELECT
18876                         usr,
18877                         value
18878                 FROM
18879                         actor.usr_setting
18880                 WHERE
18881                         name = 'patron.max_reading_list_interval'
18882         LOOP
18883                 --
18884                 -- Make sure the setting is a valid interval
18885                 --
18886                 BEGIN
18887                         threshold := today - CAST( translate( usr_setting.value, '"', '' ) AS INTERVAL );
18888                 EXCEPTION
18889                         WHEN OTHERS THEN
18890                                 RAISE NOTICE 'Invalid setting patron.max_reading_list_interval for user %: ''%''',
18891                                         usr_setting.usr, usr_setting.value;
18892                                 CONTINUE;
18893                 END;
18894                 --
18895                 --RAISE NOTICE 'User % threshold %', usr_setting.usr, threshold;
18896                 --
18897         DELETE FROM container.copy_bucket_item
18898         WHERE
18899                 bucket IN
18900                 (
18901                     SELECT
18902                         id
18903                     FROM
18904                         container.copy_bucket
18905                     WHERE
18906                         owner = usr_setting.usr
18907                         AND btype = 'circ_history'
18908                 )
18909                 AND create_time < threshold;
18910         END LOOP;
18911         --
18912 END;
18913 $$ LANGUAGE plpgsql;
18914
18915 COMMENT ON FUNCTION container.clear_all_expired_circ_history_items( ) IS $$
18916 /*
18917  * Delete expired circulation bucket items for all users that have
18918  * a setting for patron.max_reading_list_interval.
18919 */
18920 $$;
18921
18922 CREATE OR REPLACE FUNCTION container.clear_expired_circ_history_items( 
18923          ac_usr IN INTEGER
18924 ) RETURNS VOID AS $$
18925 --
18926 -- Delete old circulation bucket items for a specified user.
18927 -- "Old" means older than the interval specified by a
18928 -- user-level setting, if it is so specified.
18929 --
18930 DECLARE
18931     threshold TIMESTAMP WITH TIME ZONE;
18932 BEGIN
18933         -- Sanity check
18934         IF ac_usr IS NULL THEN
18935                 RETURN;
18936         END IF;
18937         -- Determine the threshold date that defines "old".  Subtract the
18938         -- interval from the system date, then truncate to midnight.
18939         SELECT
18940                 date_trunc( 
18941                         'day',
18942                         now() - CAST( translate( value, '"', '' ) AS INTERVAL )
18943                 )
18944         INTO
18945                 threshold
18946         FROM
18947                 actor.usr_setting
18948         WHERE
18949                 usr = ac_usr
18950                 AND name = 'patron.max_reading_list_interval';
18951         --
18952         IF threshold is null THEN
18953                 -- No interval defined; don't delete anything
18954                 -- RAISE NOTICE 'No interval defined for user %', ac_usr;
18955                 return;
18956         END IF;
18957         --
18958         -- RAISE NOTICE 'Date threshold: %', threshold;
18959         --
18960         -- Threshold found; do the delete
18961         delete from container.copy_bucket_item
18962         where
18963                 bucket in
18964                 (
18965                         select
18966                                 id
18967                         from
18968                                 container.copy_bucket
18969                         where
18970                                 owner = ac_usr
18971                                 and btype = 'circ_history'
18972                 )
18973                 and create_time < threshold;
18974         --
18975         RETURN;
18976 END;
18977 $$ LANGUAGE plpgsql;
18978
18979 COMMENT ON FUNCTION container.clear_expired_circ_history_items( INTEGER ) IS $$
18980 /*
18981  * Delete old circulation bucket items for a specified user.
18982  * "Old" means older than the interval specified by a
18983  * user-level setting, if it is so specified.
18984 */
18985 $$;
18986
18987 CREATE OR REPLACE VIEW reporter.hold_request_record AS
18988 SELECT  id,
18989     target,
18990     hold_type,
18991     CASE
18992         WHEN hold_type = 'T'
18993             THEN target
18994         WHEN hold_type = 'I'
18995             THEN (SELECT ssub.record_entry FROM serial.subscription ssub JOIN serial.issuance si ON (si.subscription = ssub.id) WHERE si.id = ahr.target)
18996         WHEN hold_type = 'V'
18997             THEN (SELECT cn.record FROM asset.call_number cn WHERE cn.id = ahr.target)
18998         WHEN hold_type IN ('C','R','F')
18999             THEN (SELECT cn.record FROM asset.call_number cn JOIN asset.copy cp ON (cn.id = cp.call_number) WHERE cp.id = ahr.target)
19000         WHEN hold_type = 'M'
19001             THEN (SELECT mr.master_record FROM metabib.metarecord mr WHERE mr.id = ahr.target)
19002     END AS bib_record
19003   FROM  action.hold_request ahr;
19004
19005 UPDATE  metabib.rec_descriptor
19006   SET   date1=LPAD(NULLIF(REGEXP_REPLACE(NULLIF(date1, ''), E'\\D', '0', 'g')::INT,0)::TEXT,4,'0'),
19007         date2=LPAD(NULLIF(REGEXP_REPLACE(NULLIF(date2, ''), E'\\D', '9', 'g')::INT,9999)::TEXT,4,'0');
19008
19009 -- Change some ints to bigints:
19010
19011 ALTER TABLE container.biblio_record_entry_bucket_item
19012         ALTER COLUMN target_biblio_record_entry SET DATA TYPE bigint;
19013
19014 ALTER TABLE vandelay.queued_bib_record
19015         ALTER COLUMN imported_as SET DATA TYPE bigint;
19016
19017 ALTER TABLE action.hold_copy_map
19018         ALTER COLUMN id SET DATA TYPE bigint;
19019
19020 -- Make due times get pushed to 23:59:59 on insert OR update
19021 DROP TRIGGER IF EXISTS push_due_date_tgr ON action.circulation;
19022 CREATE TRIGGER push_due_date_tgr BEFORE INSERT OR UPDATE ON action.circulation FOR EACH ROW EXECUTE PROCEDURE action.push_circ_due_time();
19023
19024 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove )
19025 SELECT 'upc', 'UPC', '//*[@tag="024" and @ind1="1"]/*[@code="a"]', $r$(?:-|\s.+$)$r$
19026 WHERE NOT EXISTS (
19027     SELECT 1 FROM acq.lineitem_marc_attr_definition WHERE code = 'upc'
19028 );  
19029
19030 COMMIT;
19031
19032 -- Some operations go outside of the transaction, because they may
19033 -- legitimately fail.
19034
19035 \qecho ALTERs of auditor.action_hold_request_history will fail if the table
19036 \qecho doesn't exist; ignore those errors if they occur.
19037
19038 ALTER TABLE auditor.action_hold_request_history ADD COLUMN cut_in_line BOOL;
19039
19040 ALTER TABLE auditor.action_hold_request_history
19041 ADD COLUMN mint_condition boolean NOT NULL DEFAULT TRUE;
19042
19043 ALTER TABLE auditor.action_hold_request_history
19044 ADD COLUMN shelf_expire_time TIMESTAMPTZ;
19045
19046 \qecho Outside of the transaction: adding indexes that may or may not exist.
19047 \qecho If any of these CREATE INDEX statements fails because the index already
19048 \qecho exists, ignore the failure.
19049
19050 CREATE INDEX acq_picklist_owner_idx   ON acq.picklist ( owner );
19051 CREATE INDEX acq_picklist_creator_idx ON acq.picklist ( creator );
19052 CREATE INDEX acq_picklist_editor_idx  ON acq.picklist ( editor );
19053 CREATE INDEX acq_po_note_creator_idx  ON acq.po_note ( creator );
19054 CREATE INDEX acq_po_note_editor_idx   ON acq.po_note ( editor );
19055 CREATE INDEX fund_alloc_allocator_idx ON acq.fund_allocation ( allocator );
19056 CREATE INDEX li_creator_idx   ON acq.lineitem ( creator );
19057 CREATE INDEX li_editor_idx    ON acq.lineitem ( editor );
19058 CREATE INDEX li_selector_idx  ON acq.lineitem ( selector );
19059 CREATE INDEX li_note_creator_idx  ON acq.lineitem_note ( creator );
19060 CREATE INDEX li_note_editor_idx   ON acq.lineitem_note ( editor );
19061 CREATE INDEX li_usr_attr_def_usr_idx  ON acq.lineitem_usr_attr_definition ( usr );
19062 CREATE INDEX po_editor_idx   ON acq.purchase_order ( editor );
19063 CREATE INDEX po_creator_idx  ON acq.purchase_order ( creator );
19064 CREATE INDEX acq_po_org_name_order_date_idx ON acq.purchase_order( ordering_agency, name, order_date );
19065 CREATE INDEX action_in_house_use_staff_idx  ON action.in_house_use ( staff );
19066 CREATE INDEX action_non_cat_circ_patron_idx ON action.non_cataloged_circulation ( patron );
19067 CREATE INDEX action_non_cat_circ_staff_idx  ON action.non_cataloged_circulation ( staff );
19068 CREATE INDEX action_survey_response_usr_idx ON action.survey_response ( usr );
19069 CREATE INDEX ahn_notify_staff_idx           ON action.hold_notification ( notify_staff );
19070 CREATE INDEX circ_all_usr_idx               ON action.circulation ( usr );
19071 CREATE INDEX circ_circ_staff_idx            ON action.circulation ( circ_staff );
19072 CREATE INDEX circ_checkin_staff_idx         ON action.circulation ( checkin_staff );
19073 CREATE INDEX hold_request_fulfillment_staff_idx ON action.hold_request ( fulfillment_staff );
19074 CREATE INDEX hold_request_requestor_idx     ON action.hold_request ( requestor );
19075 CREATE INDEX non_cat_in_house_use_staff_idx ON action.non_cat_in_house_use ( staff );
19076 CREATE INDEX actor_usr_note_creator_idx     ON actor.usr_note ( creator );
19077 CREATE INDEX actor_usr_standing_penalty_staff_idx ON actor.usr_standing_penalty ( staff );
19078 CREATE INDEX usr_org_unit_opt_in_staff_idx  ON actor.usr_org_unit_opt_in ( staff );
19079 CREATE INDEX asset_call_number_note_creator_idx ON asset.call_number_note ( creator );
19080 CREATE INDEX asset_copy_note_creator_idx    ON asset.copy_note ( creator );
19081 CREATE INDEX cp_creator_idx                 ON asset.copy ( creator );
19082 CREATE INDEX cp_editor_idx                  ON asset.copy ( editor );
19083
19084 CREATE INDEX actor_card_barcode_lower_idx ON actor.card (lower(barcode));
19085
19086 DROP INDEX IF EXISTS authority.unique_by_heading_and_thesaurus;
19087
19088 \qecho If the following CREATE INDEX fails, It will be necessary to do some
19089 \qecho data cleanup as described in the comments.
19090
19091 CREATE UNIQUE INDEX unique_by_heading_and_thesaurus
19092     ON authority.record_entry (authority.normalize_heading(marc))
19093         WHERE deleted IS FALSE or deleted = FALSE;
19094
19095 -- If the unique index fails, uncomment the following to create
19096 -- a regular index that will help find the duplicates in a hurry:
19097 --CREATE INDEX by_heading_and_thesaurus
19098 --    ON authority.record_entry (authority.normalize_heading(marc))
19099 --    WHERE deleted IS FALSE or deleted = FALSE
19100 --;
19101
19102 -- Then find the duplicates like so to get an idea of how much
19103 -- pain you're looking at to clean things up:
19104 --SELECT id, authority.normalize_heading(marc)
19105 --    FROM authority.record_entry
19106 --    WHERE authority.normalize_heading(marc) IN (
19107 --        SELECT authority.normalize_heading(marc)
19108 --        FROM authority.record_entry
19109 --        GROUP BY authority.normalize_heading(marc)
19110 --        HAVING COUNT(*) > 1
19111 --    )
19112 --;
19113
19114 -- Once you have removed the duplicates and the CREATE UNIQUE INDEX
19115 -- statement succeeds, drop the temporary index to avoid unnecessary
19116 -- duplication:
19117 -- DROP INDEX authority.by_heading_and_thesaurus;
19118
19119 -- 0448.data.trigger.circ.staff_age_to_lost.sql
19120
19121 INSERT INTO action_trigger.hook (key,core_type,description,passive) VALUES 
19122     (   'circ.staff_age_to_lost',
19123         'circ', 
19124         oils_i18n_gettext(
19125             'circ.staff_age_to_lost',
19126             'An overdue circulation should be aged to a Lost status.',
19127             'ath',
19128             'description'
19129         ), 
19130         TRUE
19131     )
19132 ;
19133
19134 INSERT INTO action_trigger.event_definition (
19135         id,
19136         active,
19137         owner,
19138         name,
19139         hook,
19140         validator,
19141         reactor,
19142         delay_field
19143     ) VALUES (
19144         36,
19145         FALSE,
19146         1,
19147         'circ.staff_age_to_lost',
19148         'circ.staff_age_to_lost',
19149         'CircIsOverdue',
19150         'MarkItemLost',
19151         'due_date'
19152     )
19153 ;
19154
19155 -- Speed up item-age browse axis (new books feed)
19156 CREATE INDEX cp_create_date  ON asset.copy (create_date);
19157
19158 \qecho Upgrade script completed.
19159 \qecho But wait, there's more: please run reingest-1.6-2.0.pl
19160 \qecho in order to create an SQL script to run to partially reindex 
19161 \qecho the bib records; this is required to make the new facet
19162 \qecho sidebar in OPAC search results work and to upgrade the keyword 
19163 \qecho indexes to use the revised NACO normalization routine.