]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/040.schema.asset.sql
Merge branch 'master' of git+ssh://yeti.esilibrary.com/home/evergreen/evergreen-equin...
[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     # Licensed under the GPL v2 or later
211
212     use strict;
213     use warnings;
214
215     # Converts the callnumber to uppercase
216     # Strips spaces from start and end of the call number
217     # Converts anything other than letters, digits, and periods into underscores
218     # Collapses multiple underscores into a single underscore
219     my $callnum = uc(shift);
220     $callnum =~ s/^\s//g;
221     $callnum =~ s/\s$//g;
222     $callnum =~ s/[^A-Z0-9_.]/_/g;
223     $callnum =~ s/_{2,}/_/g;
224
225     return $callnum;
226 $func$ LANGUAGE PLPERLU;
227
228 CREATE OR REPLACE FUNCTION asset.label_normalizer_dewey(TEXT) RETURNS TEXT AS $func$
229     # Derived from the Koha C4::ClassSortRoutine::Dewey module
230     # Copyright (C) 2007 LibLime
231     # Licensed under the GPL v2 or later
232
233     use strict;
234     use warnings;
235
236     my $init = uc(shift);
237     $init =~ s/^\s+//;
238     $init =~ s/\s+$//;
239     $init =~ s!/!!g;
240     $init =~ s/^([\p{IsAlpha}]+)/$1 /;
241     my @tokens = split /\.|\s+/, $init;
242     my $digit_group_count = 0;
243     for (my $i = 0; $i <= $#tokens; $i++) {
244         if ($tokens[$i] =~ /^\d+$/) {
245             $digit_group_count++;
246             if (2 == $digit_group_count) {
247                 $tokens[$i] = sprintf("%-15.15s", $tokens[$i]);
248                 $tokens[$i] =~ tr/ /0/;
249             }
250         }
251     }
252     my $key = join("_", @tokens);
253     $key =~ s/[^\p{IsAlnum}_]//g;
254
255     return $key;
256
257 $func$ LANGUAGE PLPERLU;
258
259 CREATE OR REPLACE FUNCTION asset.label_normalizer_lc(TEXT) RETURNS TEXT AS $func$
260     use strict;
261     use warnings;
262
263     # Library::CallNumber::LC is currently hosted at http://code.google.com/p/library-callnumber-lc/
264     # The author hopes to upload it to CPAN some day, which would make our lives easier
265     use Library::CallNumber::LC;
266
267     my $callnum = Library::CallNumber::LC->new(shift);
268     return $callnum->normalize();
269
270 $func$ LANGUAGE PLPERLU;
271
272 INSERT INTO asset.call_number_class (name, normalizer, field) VALUES 
273     ('Generic', 'asset.label_normalizer_generic', '050ab,055ab,060ab,070ab,080ab,082ab,086ab,088ab,090,092,096,098,099'),
274     ('Dewey (DDC)', 'asset.label_normalizer_dewey', '080ab,082ab'),
275     ('Library of Congress (LC)', 'asset.label_normalizer_lc', '050ab,055ab')
276 ;
277
278 CREATE TABLE asset.call_number (
279         id              bigserial PRIMARY KEY,
280         creator         BIGINT                          NOT NULL,
281         create_date     TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
282         editor          BIGINT                          NOT NULL,
283         edit_date       TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
284         record          bigint                          NOT NULL,
285         owning_lib      INT                             NOT NULL,
286         label           TEXT                            NOT NULL,
287         deleted         BOOL                            NOT NULL DEFAULT FALSE,
288         label_class     BIGINT                          DEFAULT 1 NOT NULL
289                                                         REFERENCES asset.call_number_class(id)
290                                                         DEFERRABLE INITIALLY DEFERRED,
291         label_sortkey   TEXT
292 );
293 CREATE INDEX asset_call_number_record_idx ON asset.call_number (record);
294 CREATE INDEX asset_call_number_creator_idx ON asset.call_number (creator);
295 CREATE INDEX asset_call_number_editor_idx ON asset.call_number (editor);
296 CREATE INDEX asset_call_number_dewey_idx ON asset.call_number (public.call_number_dewey(label));
297 CREATE INDEX asset_call_number_upper_label_id_owning_lib_idx ON asset.call_number (oils_text_as_bytea(label),id,owning_lib);
298 CREATE INDEX asset_call_number_label_sortkey ON asset.call_number(oils_text_as_bytea(label_sortkey));
299 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;
300 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;
301 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;
302 CREATE TRIGGER asset_label_sortkey_trigger
303     BEFORE UPDATE OR INSERT ON asset.call_number
304     FOR EACH ROW EXECUTE PROCEDURE asset.label_normalizer();
305
306 CREATE TABLE asset.uri_call_number_map (
307     id          BIGSERIAL   PRIMARY KEY,
308     uri         INT         NOT NULL REFERENCES asset.uri (id),
309     call_number INT         NOT NULL REFERENCES asset.call_number (id),
310     CONSTRAINT uri_cn_once UNIQUE (uri,call_number)
311 );
312 CREATE INDEX asset_uri_call_number_map_cn_idx ON asset.uri_call_number_map (call_number);
313
314 CREATE TABLE asset.call_number_note (
315         id              BIGSERIAL                       PRIMARY KEY,
316         call_number     BIGINT                          NOT NULL,
317         creator         BIGINT                          NOT NULL,
318         create_date     TIMESTAMP WITH TIME ZONE        DEFAULT NOW(),
319         pub             BOOL                            NOT NULL DEFAULT FALSE,
320         title           TEXT                            NOT NULL,
321         value           TEXT                            NOT NULL
322 );
323 CREATE INDEX asset_call_number_note_creator_idx ON asset.call_number_note ( creator );
324
325 CREATE TABLE asset.copy_template (
326         id             SERIAL   PRIMARY KEY,
327         owning_lib     INT      NOT NULL
328                                 REFERENCES actor.org_unit (id)
329                                 DEFERRABLE INITIALLY DEFERRED,
330         creator        BIGINT   NOT NULL
331                                 REFERENCES actor.usr (id)
332                                 DEFERRABLE INITIALLY DEFERRED,
333         editor         BIGINT   NOT NULL
334                                 REFERENCES actor.usr (id)
335                                 DEFERRABLE INITIALLY DEFERRED,
336         create_date    TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
337         edit_date      TIMESTAMP WITH TIME ZONE    DEFAULT NOW(),
338         name           TEXT     NOT NULL,
339         -- columns above this point are attributes of the template itself
340         -- columns after this point are attributes of the copy this template modifies/creates
341         circ_lib       INT      REFERENCES actor.org_unit (id)
342                                 DEFERRABLE INITIALLY DEFERRED,
343         status         INT      REFERENCES config.copy_status (id)
344                                 DEFERRABLE INITIALLY DEFERRED,
345         location       INT      REFERENCES asset.copy_location (id)
346                                 DEFERRABLE INITIALLY DEFERRED,
347         loan_duration  INT      CONSTRAINT valid_loan_duration CHECK (
348                                     loan_duration IS NULL OR loan_duration IN (1,2,3)),
349         fine_level     INT      CONSTRAINT valid_fine_level CHECK (
350                                     fine_level IS NULL OR loan_duration IN (1,2,3)),
351         age_protect    INT,
352         circulate      BOOL,
353         deposit        BOOL,
354         ref            BOOL,
355         holdable       BOOL,
356         deposit_amount NUMERIC(6,2),
357         price          NUMERIC(8,2),
358         circ_modifier  TEXT,
359         circ_as_type   TEXT,
360         alert_message  TEXT,
361         opac_visible   BOOL,
362         floating       BOOL,
363         mint_condition BOOL
364 );
365
366 CREATE VIEW stats.fleshed_copy AS 
367         SELECT  cp.*,
368                 CAST(cp.create_date AS DATE) AS create_date_day,
369                 CAST(cp.edit_date AS DATE) AS edit_date_day,
370                 DATE_TRUNC('hour', cp.create_date) AS create_date_hour,
371                 DATE_TRUNC('hour', cp.edit_date) AS edit_date_hour,
372                 cn.label AS call_number_label,
373                 cn.owning_lib,
374                 rd.item_lang,
375                 rd.item_type,
376                 rd.item_form
377         FROM    asset.copy cp
378                 JOIN asset.call_number cn ON (cp.call_number = cn.id)
379                 JOIN metabib.rec_descriptor rd ON (rd.record = cn.record);
380
381 CREATE VIEW stats.fleshed_call_number AS 
382         SELECT  cn.*,
383                 CAST(cn.create_date AS DATE) AS create_date_day,
384                 CAST(cn.edit_date AS DATE) AS edit_date_day,
385                 DATE_TRUNC('hour', cn.create_date) AS create_date_hour,
386                 DATE_TRUNC('hour', cn.edit_date) AS edit_date_hour,
387                 rd.item_lang,
388                 rd.item_type,
389                 rd.item_form
390         FROM    asset.call_number cn
391                 JOIN metabib.rec_descriptor rd ON (rd.record = cn.record);
392
393 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$
394 DECLARE
395     ans RECORD;
396     trans INT;
397 BEGIN
398     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;
399
400     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
401         RETURN QUERY
402         SELECT  ans.depth,
403                 ans.id,
404                 COUNT( av.id ),
405                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
406                 COUNT( av.id ),
407                 trans
408           FROM  
409                 actor.org_unit_descendants(ans.id) d
410                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
411                 JOIN asset.copy cp ON (cp.id = av.id)
412           GROUP BY 1,2,6;
413
414         IF NOT FOUND THEN
415             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
416         END IF;
417
418     END LOOP;
419
420     RETURN;
421 END;
422 $f$ LANGUAGE PLPGSQL;
423
424 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$
425 DECLARE
426     ans RECORD;
427     trans INT;
428 BEGIN
429     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;
430
431     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
432         RETURN QUERY
433         SELECT  -1,
434                 ans.id,
435                 COUNT( av.id ),
436                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
437                 COUNT( av.id ),
438                 trans
439           FROM
440                 actor.org_unit_descendants(ans.id) d
441                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
442                 JOIN asset.copy cp ON (cp.id = av.id)
443           GROUP BY 1,2,6;
444
445         IF NOT FOUND THEN
446             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
447         END IF;
448
449     END LOOP;   
450                 
451     RETURN;     
452 END;            
453 $f$ LANGUAGE PLPGSQL;
454
455 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$
456 DECLARE         
457     ans RECORD; 
458     trans INT;
459 BEGIN           
460     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;
461
462     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
463         RETURN QUERY
464         SELECT  ans.depth,
465                 ans.id,
466                 COUNT( cp.id ),
467                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
468                 COUNT( cp.id ),
469                 trans
470           FROM
471                 actor.org_unit_descendants(ans.id) d
472                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
473                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number)
474           GROUP BY 1,2,6;
475
476         IF NOT FOUND THEN
477             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
478         END IF;
479
480     END LOOP;
481
482     RETURN;
483 END;
484 $f$ LANGUAGE PLPGSQL;
485
486 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$
487 DECLARE
488     ans RECORD;
489     trans INT;
490 BEGIN
491     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;
492
493     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
494         RETURN QUERY
495         SELECT  -1,
496                 ans.id,
497                 COUNT( cp.id ),
498                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
499                 COUNT( cp.id ),
500                 trans
501           FROM
502                 actor.org_unit_descendants(ans.id) d
503                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
504                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number)
505           GROUP BY 1,2,6;
506
507         IF NOT FOUND THEN
508             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
509         END IF;
510
511     END LOOP;
512
513     RETURN;
514 END;
515 $f$ LANGUAGE PLPGSQL;
516
517 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$
518 BEGIN
519     IF staff IS TRUE THEN
520         IF place > 0 THEN
521             RETURN QUERY SELECT * FROM asset.staff_ou_record_copy_count( place, rid );
522         ELSE
523             RETURN QUERY SELECT * FROM asset.staff_lasso_record_copy_count( -place, rid );
524         END IF;
525     ELSE
526         IF place > 0 THEN
527             RETURN QUERY SELECT * FROM asset.opac_ou_record_copy_count( place, rid );
528         ELSE
529             RETURN QUERY SELECT * FROM asset.opac_lasso_record_copy_count( -place, rid );
530         END IF;
531     END IF;
532
533     RETURN;
534 END;
535 $f$ LANGUAGE PLPGSQL;
536
537 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$
538 DECLARE
539     ans RECORD;
540     trans INT;
541 BEGIN
542     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;
543
544     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
545         RETURN QUERY
546         SELECT  ans.depth,
547                 ans.id,
548                 COUNT( av.id ),
549                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
550                 COUNT( av.id ),
551                 trans
552           FROM  
553                 actor.org_unit_descendants(ans.id) d
554                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
555                 JOIN asset.copy cp ON (cp.id = av.id)
556                 JOIN metabib.metarecord_source_map m ON (m.source = av.record)
557           GROUP BY 1,2,6;
558
559         IF NOT FOUND THEN
560             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
561         END IF;
562
563     END LOOP;
564
565     RETURN;
566 END;
567 $f$ LANGUAGE PLPGSQL;
568
569 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$
570 DECLARE
571     ans RECORD;
572     trans INT;
573 BEGIN
574     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;
575
576     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
577         RETURN QUERY
578         SELECT  -1,
579                 ans.id,
580                 COUNT( av.id ),
581                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
582                 COUNT( av.id ),
583                 trans
584           FROM
585                 actor.org_unit_descendants(ans.id) d
586                 JOIN asset.opac_visible_copies av ON (av.record = rid AND av.circ_lib = d.id)
587                 JOIN asset.copy cp ON (cp.id = av.id)
588                 JOIN metabib.metarecord_source_map m ON (m.source = av.record)
589           GROUP BY 1,2,6;
590
591         IF NOT FOUND THEN
592             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
593         END IF;
594
595     END LOOP;   
596                 
597     RETURN;     
598 END;            
599 $f$ LANGUAGE PLPGSQL;
600
601 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$
602 DECLARE         
603     ans RECORD; 
604     trans INT;
605 BEGIN
606     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;
607
608     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
609         RETURN QUERY
610         SELECT  ans.depth,
611                 ans.id,
612                 COUNT( cp.id ),
613                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
614                 COUNT( cp.id ),
615                 trans
616           FROM
617                 actor.org_unit_descendants(ans.id) d
618                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
619                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number)
620                 JOIN metabib.metarecord_source_map m ON (m.source = cn.record)
621           GROUP BY 1,2,6;
622
623         IF NOT FOUND THEN
624             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
625         END IF;
626
627     END LOOP;
628
629     RETURN;
630 END;
631 $f$ LANGUAGE PLPGSQL;
632
633 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$
634 DECLARE
635     ans RECORD;
636     trans INT;
637 BEGIN
638     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;
639
640     FOR ans IN SELECT u.org_unit AS id FROM actor.org_lasso_map AS u WHERE lasso = i_lasso LOOP
641         RETURN QUERY
642         SELECT  -1,
643                 ans.id,
644                 COUNT( cp.id ),
645                 SUM( CASE WHEN cp.status IN (0,7,12) THEN 1 ELSE 0 END ),
646                 COUNT( cp.id ),
647                 trans
648           FROM
649                 actor.org_unit_descendants(ans.id) d
650                 JOIN asset.copy cp ON (cp.circ_lib = d.id)
651                 JOIN asset.call_number cn ON (cn.record = rid AND cn.id = cp.call_number)
652                 JOIN metabib.metarecord_source_map m ON (m.source = cn.record)
653           GROUP BY 1,2,6;
654
655         IF NOT FOUND THEN
656             RETURN QUERY SELECT ans.depth, ans.id, 0::BIGINT, 0::BIGINT, 0::BIGINT, trans;
657         END IF;
658
659     END LOOP;
660
661     RETURN;
662 END;
663 $f$ LANGUAGE PLPGSQL;
664
665 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$
666 BEGIN
667     IF staff IS TRUE THEN
668         IF place > 0 THEN
669             RETURN QUERY SELECT * FROM asset.staff_ou_metarecord_copy_count( place, rid );
670         ELSE
671             RETURN QUERY SELECT * FROM asset.staff_lasso_metarecord_copy_count( -place, rid );
672         END IF;
673     ELSE
674         IF place > 0 THEN
675             RETURN QUERY SELECT * FROM asset.opac_ou_metarecord_copy_count( place, rid );
676         ELSE
677             RETURN QUERY SELECT * FROM asset.opac_lasso_metarecord_copy_count( -place, rid );
678         END IF;
679     END IF;
680
681     RETURN;
682 END;
683 $f$ LANGUAGE PLPGSQL;
684
685 CREATE OR REPLACE FUNCTION asset.autogenerate_placeholder_barcode ( ) RETURNS TRIGGER AS $f$
686 BEGIN
687         IF NEW.barcode LIKE '@@%' THEN
688                 NEW.barcode := '@@' || NEW.id;
689         END IF;
690         RETURN NEW;
691 END;
692 $f$ LANGUAGE PLPGSQL;
693
694 CREATE TRIGGER autogenerate_placeholder_barcode
695         BEFORE INSERT OR UPDATE ON asset.copy
696         FOR EACH ROW EXECUTE PROCEDURE asset.autogenerate_placeholder_barcode();
697
698 COMMIT;
699