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