]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/040.schema.asset.sql
Merge branch 'opac-tt-poc' of git+ssh://yeti.esilibrary.com/home/evergreen/evergreen...
[Evergreen.git] / Open-ILS / src / sql / Pg / 040.schema.asset.sql
1 /*
2  * Copyright (C) 2004-2008  Georgia Public Library Service
3  * Copyright (C) 2007-2008  Equinox Software, Inc.
4  * Mike Rylander <miker@esilibrary.com> 
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 DROP SCHEMA IF EXISTS asset CASCADE;
19
20 BEGIN;
21
22 CREATE SCHEMA asset;
23
24 CREATE TABLE asset.copy_location (
25         id              SERIAL  PRIMARY KEY,
26         name            TEXT    NOT NULL,
27         owning_lib      INT     NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
28         holdable        BOOL    NOT NULL DEFAULT TRUE,
29         hold_verify     BOOL    NOT NULL DEFAULT FALSE,
30         opac_visible    BOOL    NOT NULL DEFAULT TRUE,
31         circulate       BOOL    NOT NULL DEFAULT TRUE,
32         label_prefix    TEXT,
33         label_suffix    TEXT,
34         CONSTRAINT acl_name_once_per_lib UNIQUE (name, owning_lib)
35 );
36
37 CREATE TABLE asset.copy_location_order
38 (
39         id              SERIAL           PRIMARY KEY,
40         location        INT              NOT NULL
41                                              REFERENCES asset.copy_location
42                                              ON DELETE CASCADE
43                                              DEFERRABLE INITIALLY DEFERRED,
44         org             INT              NOT NULL
45                                              REFERENCES actor.org_unit
46                                              ON DELETE CASCADE
47                                              DEFERRABLE INITIALLY DEFERRED,
48         position        INT              NOT NULL DEFAULT 0,
49         CONSTRAINT acplo_once_per_org UNIQUE ( location, org )
50 );
51
52 CREATE TABLE asset.copy (
53         id              BIGSERIAL                       PRIMARY KEY,
54         circ_lib        INT                             NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
55         creator         BIGINT                          NOT NULL,
56         call_number     BIGINT                          NOT NULL,
57         editor          BIGINT                          NOT NULL,
58         create_date     TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
59         edit_date       TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
60         copy_number     INT,
61         status          INT                             NOT NULL DEFAULT 0 REFERENCES config.copy_status (id) DEFERRABLE INITIALLY DEFERRED,
62         location        INT                             NOT NULL DEFAULT 1 REFERENCES asset.copy_location (id) DEFERRABLE INITIALLY DEFERRED,
63         loan_duration   INT                             NOT NULL CHECK ( loan_duration IN (1,2,3) ),
64         fine_level      INT                             NOT NULL CHECK ( fine_level IN (1,2,3) ),
65         age_protect     INT,
66         circulate       BOOL                            NOT NULL DEFAULT TRUE,
67         deposit         BOOL                            NOT NULL DEFAULT FALSE,
68         ref             BOOL                            NOT NULL DEFAULT FALSE,
69         holdable        BOOL                            NOT NULL DEFAULT TRUE,
70         deposit_amount  NUMERIC(6,2)                    NOT NULL DEFAULT 0.00,
71         price           NUMERIC(8,2),
72         barcode         TEXT                            NOT NULL,
73         circ_modifier   TEXT,
74         circ_as_type    TEXT,
75         dummy_title     TEXT,
76         dummy_author    TEXT,
77         alert_message   TEXT,
78         opac_visible    BOOL                            NOT NULL DEFAULT TRUE,
79         deleted         BOOL                            NOT NULL DEFAULT FALSE,
80         floating                BOOL                            NOT NULL DEFAULT FALSE,
81         dummy_isbn      TEXT,
82         status_changed_time TIMESTAMP WITH TIME ZONE,
83         mint_condition      BOOL        NOT NULL DEFAULT TRUE,
84     cost    NUMERIC(8,2)
85 );
86 CREATE UNIQUE INDEX copy_barcode_key ON asset.copy (barcode) WHERE deleted = FALSE OR deleted IS FALSE;
87 CREATE INDEX cp_cn_idx ON asset.copy (call_number);
88 CREATE INDEX cp_avail_cn_idx ON asset.copy (call_number);
89 CREATE INDEX cp_creator_idx  ON asset.copy ( creator );
90 CREATE INDEX cp_editor_idx   ON asset.copy ( editor );
91 CREATE INDEX cp_create_date  ON asset.copy (create_date);
92 CREATE RULE protect_copy_delete AS ON DELETE TO asset.copy DO INSTEAD UPDATE asset.copy SET deleted = TRUE WHERE OLD.id = asset.copy.id;
93
94 CREATE TABLE asset.copy_part_map (
95     id          SERIAL  PRIMARY KEY,
96     target_copy BIGINT  NOT NULL, -- points o asset.copy
97     part        INT     NOT NULL REFERENCES biblio.monograph_part (id) ON DELETE CASCADE
98 );
99 CREATE UNIQUE INDEX copy_part_map_cp_part_idx ON asset.copy_part_map (target_copy, part);
100
101 CREATE TABLE asset.opac_visible_copies (
102   id        BIGINT primary key, -- copy id
103   record    BIGINT,
104   circ_lib  INTEGER
105 );
106 COMMENT ON TABLE asset.opac_visible_copies IS $$
107 Materialized view of copies that are visible in the OPAC, used by
108 search.query_parser_fts() to speed up OPAC visibility checks on large
109 databases.  Contents are maintained by a set of triggers.
110 $$;
111 CREATE INDEX opac_visible_copies_idx1 on asset.opac_visible_copies (record, circ_lib);
112
113 CREATE OR REPLACE FUNCTION asset.acp_status_changed()
114 RETURNS TRIGGER AS $$
115 BEGIN
116     IF NEW.status <> OLD.status THEN
117         NEW.status_changed_time := now();
118     END IF;
119     RETURN NEW;
120 END;
121 $$ LANGUAGE plpgsql;
122
123 CREATE TRIGGER acp_status_changed_trig
124     BEFORE UPDATE ON asset.copy
125     FOR EACH ROW EXECUTE PROCEDURE asset.acp_status_changed();
126
127 CREATE TABLE asset.stat_cat_entry_transparency_map (
128         id                      BIGSERIAL       PRIMARY KEY,
129         stat_cat                INT             NOT NULL, -- needs ON DELETE CASCADE
130         stat_cat_entry          INT             NOT NULL, -- needs ON DELETE CASCADE
131         owning_transparency     INT             NOT NULL, -- needs ON DELETE CASCADE
132         CONSTRAINT scte_once_per_trans UNIQUE (owning_transparency,stat_cat)
133 );
134
135 CREATE TABLE asset.stat_cat (
136         id              SERIAL  PRIMARY KEY,
137         owner           INT     NOT NULL,
138         opac_visible    BOOL    NOT NULL DEFAULT FALSE,
139         name            TEXT    NOT NULL,
140         required        BOOL    NOT NULL DEFAULT FALSE,
141         CONSTRAINT sc_once_per_owner UNIQUE (owner,name)
142 );
143
144 CREATE TABLE asset.stat_cat_entry (
145         id              SERIAL  PRIMARY KEY,
146         stat_cat        INT     NOT NULL,
147         owner           INT     NOT NULL,
148         value           TEXT    NOT NULL,
149         CONSTRAINT sce_once_per_owner UNIQUE (stat_cat,owner,value)
150 );
151
152 CREATE TABLE asset.stat_cat_entry_copy_map (
153         id              BIGSERIAL       PRIMARY KEY,
154         stat_cat        INT             NOT NULL,
155         stat_cat_entry  INT             NOT NULL,
156         owning_copy     BIGINT          NOT NULL,
157         CONSTRAINT sce_once_per_copy UNIQUE (owning_copy,stat_cat)
158 );
159 CREATE INDEX scecm_owning_copy_idx ON asset.stat_cat_entry_copy_map(owning_copy);
160
161 CREATE TABLE asset.copy_note (
162         id              BIGSERIAL                       PRIMARY KEY,
163         owning_copy     BIGINT                          NOT NULL,
164         creator         BIGINT                          NOT NULL,
165         create_date     TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
166         pub             BOOL                            NOT NULL DEFAULT FALSE,
167         title           TEXT                            NOT NULL,
168         value           TEXT                            NOT NULL
169 );
170 CREATE INDEX asset_copy_note_creator_idx ON asset.copy_note ( creator );
171 CREATE INDEX asset_copy_note_owning_copy_idx ON asset.copy_note ( owning_copy );
172
173 CREATE TABLE asset.uri (
174     id  SERIAL  PRIMARY KEY,
175     href    TEXT    NOT NULL,
176     label   TEXT,
177     use_restriction TEXT,
178     active  BOOL    NOT NULL DEFAULT TRUE
179 );
180
181 CREATE TABLE asset.call_number_class (
182     id             bigserial     PRIMARY KEY,
183     name           TEXT          NOT NULL,
184     normalizer     TEXT          NOT NULL DEFAULT 'asset.normalize_generic',
185     field          TEXT          NOT NULL DEFAULT '050ab,055ab,060ab,070ab,080ab,082ab,086ab,088ab,090,092,096,098,099'
186 );
187 COMMENT ON TABLE asset.call_number_class IS $$
188 Defines the call number normalization database functions in the "normalizer"
189 column and the tag/subfield combinations to use to lookup the call number in
190 the "field" column for a given classification scheme. Tag/subfield combinations
191 are delimited by commas.
192 $$;
193
194 CREATE OR REPLACE FUNCTION asset.label_normalizer() RETURNS TRIGGER AS $func$
195 DECLARE
196     sortkey        TEXT := '';
197 BEGIN
198     sortkey := NEW.label_sortkey;
199
200     EXECUTE 'SELECT ' || acnc.normalizer || '(' || 
201        quote_literal( NEW.label ) || ')'
202        FROM asset.call_number_class acnc
203        WHERE acnc.id = NEW.label_class
204        INTO sortkey;
205
206     NEW.label_sortkey = sortkey;
207
208     RETURN NEW;
209 END;
210 $func$ LANGUAGE PLPGSQL;
211
212 CREATE OR REPLACE FUNCTION asset.label_normalizer_generic(TEXT) RETURNS TEXT AS $func$
213     # Created after looking at the Koha C4::ClassSortRoutine::Generic module,
214     # thus could probably be considered a derived work, although nothing was
215     # directly copied - but to err on the safe side of providing attribution:
216     # Copyright (C) 2007 LibLime
217     # Copyright (C) 2011 Equinox Software, Inc (Steve Callendar)
218     # Licensed under the GPL v2 or later
219
220     use strict;
221     use warnings;
222
223     # Converts the callnumber to uppercase
224     # Strips spaces from start and end of the call number
225     # Converts anything other than letters, digits, and periods into spaces
226     # Collapses multiple spaces into a single underscore
227     my $callnum = uc(shift);
228     $callnum =~ s/^\s//g;
229     $callnum =~ s/\s$//g;
230     # NOTE: this previously used underscores, but this caused sorting issues
231     # for the "before" half of page 0 on CN browse, sorting CNs containing a
232     # decimal before "whole number" CNs
233     $callnum =~ s/[^A-Z0-9_.]/ /g;
234     $callnum =~ s/ {2,}/ /g;
235
236     return $callnum;
237 $func$ LANGUAGE PLPERLU;
238
239 CREATE OR REPLACE FUNCTION asset.label_normalizer_dewey(TEXT) RETURNS TEXT AS $func$
240     # Derived from the Koha C4::ClassSortRoutine::Dewey module
241     # Copyright (C) 2007 LibLime
242     # Licensed under the GPL v2 or later
243
244     use strict;
245     use warnings;
246
247     my $init = uc(shift);
248     $init =~ s/^\s+//;
249     $init =~ s/\s+$//;
250     $init =~ s!/!!g;
251     $init =~ s/^([\p{IsAlpha}]+)/$1 /;
252     my @tokens = split /\.|\s+/, $init;
253     my $digit_group_count = 0;
254     for (my $i = 0; $i <= $#tokens; $i++) {
255         if ($tokens[$i] =~ /^\d+$/) {
256             $digit_group_count++;
257             if (2 == $digit_group_count) {
258                 $tokens[$i] = sprintf("%-15.15s", $tokens[$i]);
259                 $tokens[$i] =~ tr/ /0/;
260             }
261         }
262     }
263     my $key = join("_", @tokens);
264     $key =~ s/[^\p{IsAlnum}_]//g;
265
266     return $key;
267
268 $func$ LANGUAGE PLPERLU;
269
270 CREATE OR REPLACE FUNCTION asset.label_normalizer_lc(TEXT) RETURNS TEXT AS $func$
271     use strict;
272     use warnings;
273
274     # Library::CallNumber::LC is currently hosted at http://code.google.com/p/library-callnumber-lc/
275     # The author hopes to upload it to CPAN some day, which would make our lives easier
276     use Library::CallNumber::LC;
277
278     my $callnum = Library::CallNumber::LC->new(shift);
279     return $callnum->normalize();
280
281 $func$ LANGUAGE PLPERLU;
282
283 INSERT INTO asset.call_number_class (name, normalizer, field) VALUES 
284     ('Generic', 'asset.label_normalizer_generic', '050ab,055ab,060ab,070ab,080ab,082ab,086ab,088ab,090,092,096,098,099'),
285     ('Dewey (DDC)', 'asset.label_normalizer_dewey', '080ab,082ab,092abef'),
286     ('Library of Congress (LC)', 'asset.label_normalizer_lc', '050ab,055ab,090abef')
287 ;
288
289 CREATE OR REPLACE FUNCTION asset.normalize_affix_sortkey () RETURNS TRIGGER AS $$
290 BEGIN
291     NEW.label_sortkey := REGEXP_REPLACE(
292         evergreen.lpad_number_substrings(
293             naco_normalize(NEW.label),
294             '0',
295             10
296         ),
297         E'\\s+',
298         '',
299         'g'
300     );
301     RETURN NEW;
302 END;
303 $$ LANGUAGE PLPGSQL;
304
305 CREATE TABLE asset.call_number_prefix (
306         id                      SERIAL   PRIMARY KEY,
307         owning_lib          INT                 NOT NULL REFERENCES actor.org_unit (id),
308         label               TEXT                NOT NULL, -- i18n
309         label_sortkey   TEXT
310 );
311 CREATE TRIGGER prefix_normalize_tgr BEFORE INSERT OR UPDATE ON asset.call_number_prefix FOR EACH ROW EXECUTE PROCEDURE asset.normalize_affix_sortkey();
312 CREATE UNIQUE INDEX asset_call_number_prefix_once_per_lib ON asset.call_number_prefix (label, owning_lib);
313 CREATE INDEX asset_call_number_prefix_sortkey_idx ON asset.call_number_prefix (label_sortkey);
314
315 CREATE TABLE asset.call_number_suffix (
316         id                      SERIAL   PRIMARY KEY,
317         owning_lib          INT                 NOT NULL REFERENCES actor.org_unit (id),
318         label               TEXT                NOT NULL, -- i18n
319         label_sortkey   TEXT
320 );
321 CREATE TRIGGER suffix_normalize_tgr BEFORE INSERT OR UPDATE ON asset.call_number_suffix FOR EACH ROW EXECUTE PROCEDURE asset.normalize_affix_sortkey();
322 CREATE UNIQUE INDEX asset_call_number_suffix_once_per_lib ON asset.call_number_suffix (label, owning_lib);
323 CREATE INDEX asset_call_number_suffix_sortkey_idx ON asset.call_number_suffix (label_sortkey);
324
325 CREATE TABLE asset.call_number (
326         id              bigserial PRIMARY KEY,
327         creator         BIGINT                          NOT NULL,
328         create_date     TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
329         editor          BIGINT                          NOT NULL,
330         edit_date       TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
331         record          bigint                          NOT NULL,
332         owning_lib      INT                                 NOT NULL,
333         label           TEXT                            NOT NULL,
334         deleted         BOOL                            NOT NULL DEFAULT FALSE,
335         prefix          INT                                 NOT NULL DEFAULT -1 REFERENCES asset.call_number_prefix(id) DEFERRABLE INITIALLY DEFERRED,
336         suffix          INT                                 NOT NULL DEFAULT -1 REFERENCES asset.call_number_suffix(id) DEFERRABLE INITIALLY DEFERRED,
337         label_class     BIGINT                          DEFAULT 1 NOT NULL
338                                                         REFERENCES asset.call_number_class(id)
339                                                         DEFERRABLE INITIALLY DEFERRED,
340         label_sortkey   TEXT
341 );
342 CREATE INDEX asset_call_number_record_idx ON asset.call_number (record);
343 CREATE INDEX asset_call_number_creator_idx ON asset.call_number (creator);
344 CREATE INDEX asset_call_number_editor_idx ON asset.call_number (editor);
345 CREATE INDEX asset_call_number_dewey_idx ON asset.call_number (public.call_number_dewey(label));
346 CREATE INDEX asset_call_number_upper_label_id_owning_lib_idx ON asset.call_number (oils_text_as_bytea(label),id,owning_lib);
347 CREATE INDEX asset_call_number_label_sortkey ON asset.call_number(oils_text_as_bytea(label_sortkey));
348 CREATE UNIQUE INDEX asset_call_number_label_once_per_lib ON asset.call_number (record, owning_lib, label, prefix, suffix) WHERE deleted = FALSE OR deleted IS FALSE;
349 CREATE INDEX asset_call_number_label_sortkey_browse ON asset.call_number(oils_text_as_bytea(label_sortkey), oils_text_as_bytea(label), id, owning_lib) WHERE deleted IS FALSE OR deleted = FALSE;
350 CREATE RULE protect_cn_delete AS ON DELETE TO asset.call_number DO INSTEAD UPDATE asset.call_number SET deleted = TRUE WHERE OLD.id = asset.call_number.id;
351 CREATE TRIGGER asset_label_sortkey_trigger
352     BEFORE UPDATE OR INSERT ON asset.call_number
353     FOR EACH ROW EXECUTE PROCEDURE asset.label_normalizer();
354
355 CREATE TABLE asset.uri_call_number_map (
356     id          BIGSERIAL   PRIMARY KEY,
357     uri         INT         NOT NULL REFERENCES asset.uri (id),
358     call_number INT         NOT NULL REFERENCES asset.call_number (id),
359     CONSTRAINT uri_cn_once UNIQUE (uri,call_number)
360 );
361 CREATE INDEX asset_uri_call_number_map_cn_idx ON asset.uri_call_number_map (call_number);
362
363 CREATE TABLE asset.call_number_note (
364         id              BIGSERIAL                       PRIMARY KEY,
365         call_number     BIGINT                          NOT NULL,
366         creator         BIGINT                          NOT NULL,
367         create_date     TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
368         pub             BOOL                            NOT NULL DEFAULT FALSE,
369         title           TEXT                            NOT NULL,
370         value           TEXT                            NOT NULL
371 );
372 CREATE INDEX asset_call_number_note_creator_idx ON asset.call_number_note ( creator );
373
374 CREATE TABLE asset.copy_template (
375         id             SERIAL   PRIMARY KEY,
376         owning_lib     INT      NOT NULL
377                                 REFERENCES actor.org_unit (id)
378                                 DEFERRABLE INITIALLY DEFERRED,
379         creator        BIGINT   NOT NULL
380                                 REFERENCES actor.usr (id)
381                                 DEFERRABLE INITIALLY DEFERRED,
382         editor         BIGINT   NOT NULL
383                                 REFERENCES actor.usr (id)
384                                 DEFERRABLE INITIALLY DEFERRED,
385         create_date    TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
386         edit_date      TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
387         name           TEXT     NOT NULL,
388         -- columns above this point are attributes of the template itself
389         -- columns after this point are attributes of the copy this template modifies/creates
390         circ_lib       INT      REFERENCES actor.org_unit (id)
391                                 DEFERRABLE INITIALLY DEFERRED,
392         status         INT      REFERENCES config.copy_status (id)
393                                 DEFERRABLE INITIALLY DEFERRED,
394         location       INT      REFERENCES asset.copy_location (id)
395                                 DEFERRABLE INITIALLY DEFERRED,
396         loan_duration  INT      CONSTRAINT valid_loan_duration CHECK (
397                                     loan_duration IS NULL OR loan_duration IN (1,2,3)),
398         fine_level     INT      CONSTRAINT valid_fine_level CHECK (
399                                     fine_level IS NULL OR loan_duration IN (1,2,3)),
400         age_protect    INT,
401         circulate      BOOL,
402         deposit        BOOL,
403         ref            BOOL,
404         holdable       BOOL,
405         deposit_amount NUMERIC(6,2),
406         price          NUMERIC(8,2),
407         circ_modifier  TEXT,
408         circ_as_type   TEXT,
409         alert_message  TEXT,
410         opac_visible   BOOL,
411         floating       BOOL,
412         mint_condition BOOL
413 );
414
415 CREATE OR REPLACE FUNCTION asset.opac_ou_record_copy_count (org INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
416 DECLARE
417     ans RECORD;
418     trans INT;
419 BEGIN
420     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 = rid;
421
422     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
423         RETURN QUERY
424         SELECT  ans.depth,
425                 ans.id,
426                 COUNT( av.id ),
427                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
428                 COUNT( av.id ),
429                 trans
430           FROM  
431                 actor.org_unit_descendants(ans.id) d
432                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
433                 JOIN asset.copy cp ON (cp.id = av.id)
434           GROUP BY 1,2,6;
435
436         IF NOT FOUND THEN
437             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
438         END IF;
439
440     END LOOP;
441
442     RETURN;
443 END;
444 $f$ LANGUAGE PLPGSQL;
445
446 CREATE OR REPLACE FUNCTION asset.opac_lasso_record_copy_count (i_lasso INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
447 DECLARE
448     ans RECORD;
449     trans INT;
450 BEGIN
451     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 = rid;
452
453     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
454         RETURN QUERY
455         SELECT  -1,
456                 ans.id,
457                 COUNT( av.id ),
458                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
459                 COUNT( av.id ),
460                 trans
461           FROM
462                 actor.org_unit_descendants(ans.id) d
463                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
464                 JOIN asset.copy cp ON (cp.id = av.id)
465           GROUP BY 1,2,6;
466
467         IF NOT FOUND THEN
468             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
469         END IF;
470
471     END LOOP;   
472                 
473     RETURN;     
474 END;            
475 $f$ LANGUAGE PLPGSQL;
476
477 CREATE OR REPLACE FUNCTION asset.staff_ou_record_copy_count (org INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
478 DECLARE         
479     ans RECORD; 
480     trans INT;
481 BEGIN           
482     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 = rid;
483
484     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
485         RETURN QUERY
486         SELECT  ans.depth,
487                 ans.id,
488                 COUNT( cp.id ),
489                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
490                 COUNT( cp.id ),
491                 trans
492           FROM
493                 actor.org_unit_descendants(ans.id) d
494                 JOIN asset.copy cp ON (cp.circ_lib = d.id AND NOT cp.deleted)
495                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number AND NOT cn.deleted)
496           GROUP BY 1,2,6;
497
498         IF NOT FOUND THEN
499             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
500         END IF;
501
502     END LOOP;
503
504     RETURN;
505 END;
506 $f$ LANGUAGE PLPGSQL;
507
508 CREATE OR REPLACE FUNCTION asset.staff_lasso_record_copy_count (i_lasso INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
509 DECLARE
510     ans RECORD;
511     trans INT;
512 BEGIN
513     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 = rid;
514
515     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
516         RETURN QUERY
517         SELECT  -1,
518                 ans.id,
519                 COUNT( cp.id ),
520                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
521                 COUNT( cp.id ),
522                 trans
523           FROM
524                 actor.org_unit_descendants(ans.id) d
525                 JOIN asset.copy cp ON (cp.circ_lib = d.id AND NOT cp.deleted)
526                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number AND NOT cn.deleted)
527           GROUP BY 1,2,6;
528
529         IF NOT FOUND THEN
530             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
531         END IF;
532
533     END LOOP;
534
535     RETURN;
536 END;
537 $f$ LANGUAGE PLPGSQL;
538
539 CREATE OR REPLACE FUNCTION asset.record_copy_count ( place INT, rid BIGINT, staff BOOL) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
540 BEGIN
541     IF staff IS TRUE THEN
542         IF place > 0 THEN
543             RETURN QUERY SELECT * FROM asset.staff_ou_record_copy_count( place, rid );
544         ELSE
545             RETURN QUERY SELECT * FROM asset.staff_lasso_record_copy_count( -place, rid );
546         END IF;
547     ELSE
548         IF place > 0 THEN
549             RETURN QUERY SELECT * FROM asset.opac_ou_record_copy_count( place, rid );
550         ELSE
551             RETURN QUERY SELECT * FROM asset.opac_lasso_record_copy_count( -place, rid );
552         END IF;
553     END IF;
554
555     RETURN;
556 END;
557 $f$ LANGUAGE PLPGSQL;
558
559 CREATE OR REPLACE FUNCTION asset.opac_ou_metarecord_copy_count (org INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
560 DECLARE
561     ans RECORD;
562     trans INT;
563 BEGIN
564     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 = rid;
565
566     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
567         RETURN QUERY
568         SELECT  ans.depth,
569                 ans.id,
570                 COUNT( av.id ),
571                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
572                 COUNT( av.id ),
573                 trans
574           FROM  
575                 actor.org_unit_descendants(ans.id) d
576                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
577                 JOIN asset.copy cp ON (cp.id = av.id)
578                 JOIN metabib.metarecord_source_map m ON (m.source = av.record)
579           GROUP BY 1,2,6;
580
581         IF NOT FOUND THEN
582             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
583         END IF;
584
585     END LOOP;
586
587     RETURN;
588 END;
589 $f$ LANGUAGE PLPGSQL;
590
591 CREATE OR REPLACE FUNCTION asset.opac_lasso_metarecord_copy_count (i_lasso INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
592 DECLARE
593     ans RECORD;
594     trans INT;
595 BEGIN
596     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 = rid;
597
598     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
599         RETURN QUERY
600         SELECT  -1,
601                 ans.id,
602                 COUNT( av.id ),
603                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
604                 COUNT( av.id ),
605                 trans
606           FROM
607                 actor.org_unit_descendants(ans.id) d
608                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
609                 JOIN asset.copy cp ON (cp.id = av.id)
610                 JOIN metabib.metarecord_source_map m ON (m.source = av.record)
611           GROUP BY 1,2,6;
612
613         IF NOT FOUND THEN
614             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
615         END IF;
616
617     END LOOP;   
618                 
619     RETURN;     
620 END;            
621 $f$ LANGUAGE PLPGSQL;
622
623 CREATE OR REPLACE FUNCTION asset.staff_ou_metarecord_copy_count (org INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
624 DECLARE         
625     ans RECORD; 
626     trans INT;
627 BEGIN
628     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 = rid;
629
630     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
631         RETURN QUERY
632         SELECT  ans.depth,
633                 ans.id,
634                 COUNT( cp.id ),
635                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
636                 COUNT( cp.id ),
637                 trans
638           FROM
639                 actor.org_unit_descendants(ans.id) d
640                 JOIN asset.copy cp ON (cp.circ_lib = d.id AND NOT cp.deleted)
641                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number AND NOT cn.deleted)
642                 JOIN metabib.metarecord_source_map m ON (m.source = cn.record)
643           GROUP BY 1,2,6;
644
645         IF NOT FOUND THEN
646             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
647         END IF;
648
649     END LOOP;
650
651     RETURN;
652 END;
653 $f$ LANGUAGE PLPGSQL;
654
655 CREATE OR REPLACE FUNCTION asset.staff_lasso_metarecord_copy_count (i_lasso INT, rid BIGINT) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
656 DECLARE
657     ans RECORD;
658     trans INT;
659 BEGIN
660     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 = rid;
661
662     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
663         RETURN QUERY
664         SELECT  -1,
665                 ans.id,
666                 COUNT( cp.id ),
667                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
668                 COUNT( cp.id ),
669                 trans
670           FROM
671                 actor.org_unit_descendants(ans.id) d
672                 JOIN asset.copy cp ON (cp.circ_lib = d.id AND NOT cp.deleted)
673                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number AND NOT cn.deleted)
674                 JOIN metabib.metarecord_source_map m ON (m.source = cn.record)
675           GROUP BY 1,2,6;
676
677         IF NOT FOUND THEN
678             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
679         END IF;
680
681     END LOOP;
682
683     RETURN;
684 END;
685 $f$ LANGUAGE PLPGSQL;
686
687 CREATE OR REPLACE FUNCTION asset.metarecord_copy_count ( place INT, rid BIGINT, staff BOOL) RETURNS TABLE (depth INT, org_unit INT, visible BIGINT, available BIGINT, unshadow BIGINT, transcendant INT) AS $f$
688 BEGIN
689     IF staff IS TRUE THEN
690         IF place > 0 THEN
691             RETURN QUERY SELECT * FROM asset.staff_ou_metarecord_copy_count( place, rid );
692         ELSE
693             RETURN QUERY SELECT * FROM asset.staff_lasso_metarecord_copy_count( -place, rid );
694         END IF;
695     ELSE
696         IF place > 0 THEN
697             RETURN QUERY SELECT * FROM asset.opac_ou_metarecord_copy_count( place, rid );
698         ELSE
699             RETURN QUERY SELECT * FROM asset.opac_lasso_metarecord_copy_count( -place, rid );
700         END IF;
701     END IF;
702
703     RETURN;
704 END;
705 $f$ LANGUAGE PLPGSQL;
706
707 CREATE OR REPLACE FUNCTION asset.autogenerate_placeholder_barcode ( ) RETURNS TRIGGER AS $f$
708 BEGIN
709         IF NEW.barcode LIKE '@@%' THEN
710                 NEW.barcode := '@@' || NEW.id;
711         END IF;
712         RETURN NEW;
713 END;
714 $f$ LANGUAGE PLPGSQL;
715
716 CREATE TRIGGER autogenerate_placeholder_barcode
717         BEFORE INSERT OR UPDATE ON asset.copy
718         FOR EACH ROW EXECUTE PROCEDURE asset.autogenerate_placeholder_barcode();
719
720 COMMIT;
721