2 * Copyright (C) 2009 Georgia Public Library Service
3 * Scott McKellar <scott@esilibrary.com>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
16 DROP SCHEMA IF EXISTS acq CASCADE;
26 CREATE TABLE acq.currency_type (
27 code TEXT PRIMARY KEY,
31 CREATE TABLE acq.exchange_rate (
32 id SERIAL PRIMARY KEY,
33 from_currency TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
34 to_currency TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
35 ratio NUMERIC NOT NULL,
36 CONSTRAINT exchange_rate_from_to_once UNIQUE (from_currency,to_currency)
39 CREATE TABLE acq.claim_policy (
40 id SERIAL PRIMARY KEY,
41 org_unit INT NOT NULL REFERENCES actor.org_unit
42 DEFERRABLE INITIALLY DEFERRED,
44 description TEXT NOT NULL,
45 CONSTRAINT name_once_per_org UNIQUE (org_unit, name)
48 CREATE TABLE acq.claim_event_type (
49 id SERIAL PRIMARY KEY,
50 org_unit INT NOT NULL REFERENCES actor.org_unit(id)
51 DEFERRABLE INITIALLY DEFERRED,
53 description TEXT NOT NULL,
54 library_initiated BOOL NOT NULL DEFAULT FALSE,
55 CONSTRAINT event_type_once_per_org UNIQUE ( org_unit, code )
58 CREATE TABLE acq.claim_policy_action (
59 id SERIAL PRIMARY KEY,
60 claim_policy INT NOT NULL REFERENCES acq.claim_policy
62 DEFERRABLE INITIALLY DEFERRED,
63 action_interval INTERVAL NOT NULL,
64 action INT NOT NULL REFERENCES acq.claim_event_type
65 DEFERRABLE INITIALLY DEFERRED,
66 CONSTRAINT action_sequence UNIQUE (claim_policy, action_interval)
69 CREATE TABLE acq.provider (
70 id SERIAL PRIMARY KEY,
72 owner INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
73 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
77 edi_default INT, -- REFERENCES acq.edi_account (id) DEFERRABLE INITIALLY DEFERRED
78 active BOOL NOT NULL DEFAULT TRUE,
79 prepayment_required BOOL NOT NULL DEFAULT FALSE,
84 default_copy_count INT NOT NULL DEFAULT 0,
85 default_claim_policy INT REFERENCES acq.claim_policy
86 DEFERRABLE INITIALLY DEFERRED,
87 primary_contact INT, -- REFERENCE acq.provider_contact(id) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED
88 CONSTRAINT provider_name_once_per_owner UNIQUE (name,owner),
89 CONSTRAINT code_once_per_owner UNIQUE (code, owner)
92 CREATE TABLE acq.provider_holding_subfield_map (
93 id SERIAL PRIMARY KEY,
94 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
95 name TEXT NOT NULL, -- barcode, price, etc
96 subfield TEXT NOT NULL,
97 CONSTRAINT name_once_per_provider UNIQUE (provider,name)
100 CREATE TABLE acq.provider_address (
101 id SERIAL PRIMARY KEY,
102 valid BOOL NOT NULL DEFAULT TRUE,
104 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
105 street1 TEXT NOT NULL,
110 country TEXT NOT NULL,
111 post_code TEXT NOT NULL,
115 CREATE TABLE acq.provider_contact (
116 id SERIAL PRIMARY KEY,
117 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
119 role TEXT, -- free-form.. e.g. "our sales guy"
124 CREATE TABLE acq.provider_contact_address (
125 id SERIAL PRIMARY KEY,
126 valid BOOL NOT NULL DEFAULT TRUE,
128 contact INT NOT NULL REFERENCES acq.provider_contact (id) DEFERRABLE INITIALLY DEFERRED,
129 street1 TEXT NOT NULL,
134 country TEXT NOT NULL,
135 post_code TEXT NOT NULL,
139 CREATE TABLE acq.provider_note (
140 id SERIAL PRIMARY KEY,
141 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
142 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
143 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
144 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
145 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
148 CREATE INDEX acq_pro_note_pro_idx ON acq.provider_note ( provider );
149 CREATE INDEX acq_pro_note_creator_idx ON acq.provider_note ( creator );
150 CREATE INDEX acq_pro_note_editor_idx ON acq.provider_note ( editor );
153 CREATE TABLE acq.funding_source (
154 id SERIAL PRIMARY KEY,
156 owner INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
157 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
159 active BOOL NOT NULL DEFAULT TRUE,
160 CONSTRAINT funding_source_code_once_per_owner UNIQUE (code,owner),
161 CONSTRAINT funding_source_name_once_per_owner UNIQUE (name,owner)
164 CREATE TABLE acq.funding_source_credit (
165 id SERIAL PRIMARY KEY,
166 funding_source INT NOT NULL REFERENCES acq.funding_source (id) DEFERRABLE INITIALLY DEFERRED,
167 amount NUMERIC NOT NULL,
169 deadline_date TIMESTAMPTZ,
170 effective_date TIMESTAMPTZ NOT NULL default now()
173 CREATE VIEW acq.ordered_funding_source_credit AS
175 CASE WHEN deadline_date IS NULL THEN
179 END AS sort_priority,
180 CASE WHEN deadline_date IS NULL THEN
190 acq.funding_source_credit;
192 COMMENT ON VIEW acq.ordered_funding_source_credit IS $$
193 The acq.ordered_funding_source_credit view is a prioritized
194 ordering of funding source credits. When ordered by the first
195 three columns, this view defines the order in which the various
196 credits are to be tapped for spending, subject to the allocations
197 in the acq.fund_allocation table.
199 The first column reflects the principle that we should spend
200 money with deadlines before spending money without deadlines.
202 The second column reflects the principle that we should spend the
203 oldest money first. For money with deadlines, that means that we
204 spend first from the credit with the earliest deadline. For
205 money without deadlines, we spend first from the credit with the
206 earliest effective date.
208 The third column is a tie breaker to ensure a consistent
212 CREATE TABLE acq.fund (
213 id SERIAL PRIMARY KEY,
214 org INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
216 year INT NOT NULL DEFAULT EXTRACT( YEAR FROM NOW() ),
217 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
219 rollover BOOL NOT NULL DEFAULT FALSE,
220 propagate BOOL NOT NULL DEFAULT TRUE,
221 active BOOL NOT NULL DEFAULT TRUE,
222 balance_warning_percent INT,
223 balance_stop_percent INT,
224 CONSTRAINT name_once_per_org_year UNIQUE (org,name,year),
225 CONSTRAINT code_once_per_org_year UNIQUE (org, code, year),
226 CONSTRAINT acq_fund_rollover_implies_propagate CHECK ( propagate OR NOT rollover )
229 CREATE TABLE acq.fund_debit (
230 id SERIAL PRIMARY KEY,
231 fund INT NOT NULL REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
232 origin_amount NUMERIC NOT NULL, -- pre-exchange-rate amount
233 origin_currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
234 amount NUMERIC NOT NULL,
235 encumbrance BOOL NOT NULL DEFAULT TRUE,
236 debit_type TEXT NOT NULL,
237 xfer_destination INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
238 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
241 CREATE TABLE acq.fund_allocation (
242 id SERIAL PRIMARY KEY,
243 funding_source INT NOT NULL REFERENCES acq.funding_source (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
244 fund INT NOT NULL REFERENCES acq.fund (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
245 amount NUMERIC NOT NULL,
246 allocator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
248 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
250 CREATE INDEX fund_alloc_allocator_idx ON acq.fund_allocation ( allocator );
252 CREATE TABLE acq.fund_allocation_percent
254 id SERIAL PRIMARY KEY,
255 funding_source INT NOT NULL REFERENCES acq.funding_source
256 DEFERRABLE INITIALLY DEFERRED,
257 org INT NOT NULL REFERENCES actor.org_unit
258 DEFERRABLE INITIALLY DEFERRED,
260 percent NUMERIC NOT NULL,
261 allocator INTEGER NOT NULL REFERENCES actor.usr
262 DEFERRABLE INITIALLY DEFERRED,
264 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
265 CONSTRAINT logical_key UNIQUE( funding_source, org, fund_code ),
266 CONSTRAINT percentage_range CHECK( percent >= 0 AND percent <= 100 )
269 -- Trigger function to validate combination of org_unit and fund_code
271 CREATE OR REPLACE FUNCTION acq.fund_alloc_percent_val()
272 RETURNS TRIGGER AS $$
287 AND code = NEW.fund_code
293 RAISE EXCEPTION 'No fund exists for org % and code %', NEW.org, NEW.fund_code;
298 CREATE TRIGGER acq_fund_alloc_percent_val_trig
299 BEFORE INSERT OR UPDATE ON acq.fund_allocation_percent
300 FOR EACH ROW EXECUTE PROCEDURE acq.fund_alloc_percent_val();
302 -- To do: trigger to verify that percentages don't add up to more than 100
304 CREATE OR REPLACE FUNCTION acq.fap_limit_100()
305 RETURNS TRIGGER AS $$
308 total_percent numeric;
316 acq.fund_allocation_percent AS fap
318 fap.funding_source = NEW.funding_source;
320 IF total_percent > 100 THEN
321 RAISE EXCEPTION 'Total percentages exceed 100 for funding_source %',
329 CREATE TRIGGER acqfap_limit_100_trig
330 AFTER INSERT OR UPDATE ON acq.fund_allocation_percent
331 FOR EACH ROW EXECUTE PROCEDURE acq.fap_limit_100();
333 CREATE TABLE acq.picklist (
334 id SERIAL PRIMARY KEY,
335 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
336 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
337 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
338 org_unit INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
340 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
341 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
342 CONSTRAINT name_once_per_owner UNIQUE (name,owner)
344 CREATE INDEX acq_picklist_owner_idx ON acq.picklist ( owner );
345 CREATE INDEX acq_picklist_creator_idx ON acq.picklist ( creator );
346 CREATE INDEX acq_picklist_editor_idx ON acq.picklist ( editor );
348 CREATE TABLE acq.cancel_reason (
349 id SERIAL PRIMARY KEY,
350 org_unit INTEGER NOT NULL REFERENCES actor.org_unit( id )
351 DEFERRABLE INITIALLY DEFERRED,
353 description TEXT NOT NULL,
354 keep_debits BOOL NOT NULL DEFAULT FALSE,
355 CONSTRAINT acq_cancel_reason_one_per_org_unit UNIQUE( org_unit, label )
358 -- Reserve ids 1-999 for stock reasons
359 -- Reserve ids 1000-1999 for EDI reasons
360 -- 2000+ are available for staff to create
362 SELECT SETVAL('acq.cancel_reason_id_seq'::TEXT, 2000);
364 DROP TRIGGER IF EXISTS acq_no_deleted_reserved_cancel_reasons ON acq.cancel_reason;
366 CREATE TRIGGER acq_no_deleted_reserved_cancel_reasons BEFORE DELETE ON acq.cancel_reason
367 FOR EACH ROW EXECUTE PROCEDURE evergreen.protect_reserved_rows_from_delete(2000);
369 CREATE TABLE acq.purchase_order (
370 id SERIAL PRIMARY KEY,
371 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
372 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
373 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
374 ordering_agency INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
375 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
376 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
377 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
378 state TEXT NOT NULL DEFAULT 'new',
379 order_date TIMESTAMP WITH TIME ZONE,
381 cancel_reason INT REFERENCES acq.cancel_reason( id )
382 DEFERRABLE INITIALLY DEFERRED,
383 prepayment_required BOOLEAN NOT NULL DEFAULT FALSE,
384 CONSTRAINT valid_po_state CHECK (state IN ('new','pending','on-order','received','cancelled'))
386 CREATE INDEX po_owner_idx ON acq.purchase_order (owner);
387 CREATE INDEX po_provider_idx ON acq.purchase_order (provider);
388 CREATE INDEX po_state_idx ON acq.purchase_order (state);
389 CREATE INDEX po_creator_idx ON acq.purchase_order ( creator );
390 CREATE INDEX po_editor_idx ON acq.purchase_order ( editor );
391 CREATE INDEX acq_po_org_name_order_date_idx ON acq.purchase_order( ordering_agency, name, order_date );
393 -- The name should default to the id, as text. We can't reference a column
394 -- in a DEFAULT clause, so we use a trigger:
396 CREATE OR REPLACE FUNCTION acq.purchase_order_name_default () RETURNS TRIGGER
399 IF NEW.name IS NULL THEN
400 NEW.name := NEW.id::TEXT;
407 CREATE TRIGGER po_name_default_trg
408 BEFORE INSERT OR UPDATE ON acq.purchase_order
409 FOR EACH ROW EXECUTE PROCEDURE acq.purchase_order_name_default ();
411 -- The order name should be unique for a given ordering agency on a given order date
412 -- (truncated to midnight), but only where the order_date is not NULL. Conceptually
413 -- this rule requires a check constraint with a subquery. However you can't have a
414 -- subquery in a CHECK constraint, so we fake it with a trigger.
416 CREATE OR REPLACE FUNCTION acq.po_org_name_date_unique () RETURNS TRIGGER
422 -- If order_date is not null, then make sure we don't have a collision
423 -- on order_date (truncated to day), org, and name
425 IF NEW.order_date IS NULL THEN
429 -- In the WHERE clause, we compare the order_dates without regard to time of day.
430 -- We use a pair of inequalities instead of comparing truncated dates so that the
431 -- query can do an indexed range scan.
433 SELECT 1 INTO collision
434 FROM acq.purchase_order
436 ordering_agency = NEW.ordering_agency
438 AND order_date >= date_trunc( 'day', NEW.order_date )
439 AND order_date < date_trunc( 'day', NEW.order_date ) + '1 day'::INTERVAL
442 IF collision IS NULL THEN
443 -- okay, no collision
446 -- collision; nip it in the bud
447 RAISE EXCEPTION 'Colliding purchase orders: ordering_agency %, date %, name ''%''',
448 NEW.ordering_agency, NEW.order_date, NEW.name;
453 CREATE TRIGGER po_org_name_date_unique_trg
454 BEFORE INSERT OR UPDATE ON acq.purchase_order
455 FOR EACH ROW EXECUTE PROCEDURE acq.po_org_name_date_unique ();
457 CREATE TABLE acq.po_note (
458 id SERIAL PRIMARY KEY,
459 purchase_order INT NOT NULL REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
460 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
461 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
462 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
463 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
465 vendor_public BOOLEAN NOT NULL DEFAULT FALSE
467 CREATE INDEX po_note_po_idx ON acq.po_note (purchase_order);
468 CREATE INDEX acq_po_note_creator_idx ON acq.po_note ( creator );
469 CREATE INDEX acq_po_note_editor_idx ON acq.po_note ( editor );
471 CREATE TABLE acq.lineitem (
472 id BIGSERIAL PRIMARY KEY,
473 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
474 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
475 selector INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
476 provider INT REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
477 purchase_order INT REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
478 picklist INT REFERENCES acq.picklist (id) DEFERRABLE INITIALLY DEFERRED,
479 expected_recv_time TIMESTAMP WITH TIME ZONE,
480 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
481 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
483 eg_bib_id BIGINT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
485 state TEXT NOT NULL DEFAULT 'new',
486 cancel_reason INT REFERENCES acq.cancel_reason( id )
487 DEFERRABLE INITIALLY DEFERRED,
488 estimated_unit_price NUMERIC,
489 claim_policy INT REFERENCES acq.claim_policy
490 DEFERRABLE INITIALLY DEFERRED,
491 queued_record BIGINT REFERENCES vandelay.queued_bib_record (id)
492 ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
493 CONSTRAINT picklist_or_po CHECK (picklist IS NOT NULL OR purchase_order IS NOT NULL)
495 CREATE INDEX li_po_idx ON acq.lineitem (purchase_order);
496 CREATE INDEX li_pl_idx ON acq.lineitem (picklist);
497 CREATE INDEX li_creator_idx ON acq.lineitem ( creator );
498 CREATE INDEX li_editor_idx ON acq.lineitem ( editor );
499 CREATE INDEX li_selector_idx ON acq.lineitem ( selector );
500 CREATE INDEX li_queued_record_idx ON acq.lineitem ( queued_record );
502 CREATE TABLE acq.lineitem_alert_text (
503 id SERIAL PRIMARY KEY,
506 owning_lib INT NOT NULL
507 REFERENCES actor.org_unit(id)
508 DEFERRABLE INITIALLY DEFERRED,
509 CONSTRAINT alert_one_code_per_org UNIQUE (code, owning_lib)
512 CREATE TABLE acq.lineitem_note (
513 id SERIAL PRIMARY KEY,
514 lineitem INT NOT NULL REFERENCES acq.lineitem (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
515 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
516 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
517 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
518 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
520 alert_text INT REFERENCES acq.lineitem_alert_text(id)
521 DEFERRABLE INITIALLY DEFERRED,
522 vendor_public BOOLEAN NOT NULL DEFAULT FALSE
524 CREATE INDEX li_note_li_idx ON acq.lineitem_note (lineitem);
525 CREATE INDEX li_note_creator_idx ON acq.lineitem_note ( creator );
526 CREATE INDEX li_note_editor_idx ON acq.lineitem_note ( editor );
528 CREATE TABLE acq.lineitem_detail (
529 id BIGSERIAL PRIMARY KEY,
530 lineitem INT NOT NULL REFERENCES acq.lineitem (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
531 fund INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
532 fund_debit INT REFERENCES acq.fund_debit (id) DEFERRABLE INITIALLY DEFERRED,
533 eg_copy_id BIGINT, -- REFERENCES asset.copy (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED, -- XXX could be an serial.issuance
537 collection_code TEXT,
538 circ_modifier TEXT REFERENCES config.circ_modifier (code) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
539 owning_lib INT REFERENCES actor.org_unit (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
540 location INT REFERENCES asset.copy_location (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
541 recv_time TIMESTAMP WITH TIME ZONE,
542 receiver INT REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
543 cancel_reason INT REFERENCES acq.cancel_reason( id ) DEFERRABLE INITIALLY DEFERRED
546 CREATE INDEX li_detail_li_idx ON acq.lineitem_detail (lineitem);
547 CREATE INDEX lineitem_detail_fund_debit_idx ON acq.lineitem_detail (fund_debit);
549 CREATE TABLE acq.lineitem_attr_definition (
550 id BIGSERIAL PRIMARY KEY,
552 description TEXT NOT NULL,
553 remove TEXT NOT NULL DEFAULT '',
554 ident BOOL NOT NULL DEFAULT FALSE
557 CREATE TABLE acq.lineitem_marc_attr_definition (
558 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
560 ) INHERITS (acq.lineitem_attr_definition);
562 CREATE TABLE acq.lineitem_provider_attr_definition (
563 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
565 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED
566 ) INHERITS (acq.lineitem_attr_definition);
568 CREATE TABLE acq.lineitem_generated_attr_definition (
569 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
571 ) INHERITS (acq.lineitem_attr_definition);
573 CREATE TABLE acq.lineitem_usr_attr_definition (
574 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
575 usr INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED
576 ) INHERITS (acq.lineitem_attr_definition);
577 CREATE INDEX li_usr_attr_def_usr_idx ON acq.lineitem_usr_attr_definition ( usr );
579 CREATE TABLE acq.lineitem_local_attr_definition (
580 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq')
581 ) INHERITS (acq.lineitem_attr_definition);
583 CREATE TABLE acq.lineitem_attr (
584 id BIGSERIAL PRIMARY KEY,
585 definition BIGINT NOT NULL,
586 lineitem BIGINT NOT NULL REFERENCES acq.lineitem (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
587 attr_type TEXT NOT NULL,
588 attr_name TEXT NOT NULL,
589 attr_value TEXT NOT NULL,
590 order_ident BOOLEAN NOT NULL DEFAULT FALSE
593 CREATE INDEX li_attr_li_idx ON acq.lineitem_attr (lineitem);
594 CREATE INDEX li_attr_value_idx ON acq.lineitem_attr (attr_value);
595 CREATE INDEX li_attr_definition_idx ON acq.lineitem_attr (definition);
601 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('title','Title of work','//*[@tag="245"]/*[contains("abcmnopr",@code)]');
602 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('author','Author of work','//*[@tag="100" or @tag="110" or @tag="113"]/*[contains("ad",@code)]');
603 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('language','Language of work','//*[@tag="240"]/*[@code="l"][1]');
604 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pagination','Pagination','//*[@tag="300"]/*[@code="a"][1]');
605 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('isbn','ISBN','//*[@tag="020"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
606 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('issn','ISSN','//*[@tag="022"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
607 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('upc', 'UPC', '//*[@tag="024" and @ind1="1"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
608 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('price','Price','//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
609 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('identifier','Identifier','//*[@tag="001"]');
610 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('publisher','Publisher','//*[@tag="260"]/*[@code="b"][1]');
611 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pubdate','Publication Date','//*[@tag="260"]/*[@code="c"][1]');
612 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('edition','Edition','//*[@tag="250"]/*[@code="a"][1]');
614 INSERT INTO acq.lineitem_local_attr_definition ( code, description ) VALUES ('estimated_price', 'Estimated Price');
617 CREATE TABLE acq.distribution_formula (
618 id SERIAL PRIMARY KEY,
620 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
622 skip_count INT NOT NULL DEFAULT 0,
623 CONSTRAINT acqdf_name_once_per_owner UNIQUE (name, owner)
626 CREATE TABLE acq.distribution_formula_entry (
627 id SERIAL PRIMARY KEY,
628 formula INTEGER NOT NULL REFERENCES acq.distribution_formula(id)
630 DEFERRABLE INITIALLY DEFERRED,
631 position INTEGER NOT NULL,
632 item_count INTEGER NOT NULL,
633 owning_lib INTEGER REFERENCES actor.org_unit(id)
634 DEFERRABLE INITIALLY DEFERRED,
635 location INTEGER REFERENCES asset.copy_location(id),
636 fund INTEGER REFERENCES acq.fund (id),
637 circ_modifier TEXT REFERENCES config.circ_modifier (code),
638 collection_code TEXT,
639 CONSTRAINT acqdfe_lib_once_per_formula UNIQUE( formula, position ),
640 CONSTRAINT acqdfe_must_be_somewhere
641 CHECK( owning_lib IS NOT NULL OR location IS NOT NULL )
644 CREATE TABLE acq.distribution_formula_application (
645 id BIGSERIAL PRIMARY KEY,
646 creator INT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED,
647 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
649 REFERENCES acq.distribution_formula(id) DEFERRABLE INITIALLY DEFERRED,
650 lineitem INT NOT NULL
651 REFERENCES acq.lineitem(id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
654 CREATE INDEX acqdfa_df_idx
655 ON acq.distribution_formula_application(formula);
656 CREATE INDEX acqdfa_li_idx
657 ON acq.distribution_formula_application(lineitem);
658 CREATE INDEX acqdfa_creator_idx
659 ON acq.distribution_formula_application(creator);
661 CREATE TABLE acq.fund_tag (
662 id SERIAL PRIMARY KEY,
664 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
666 CONSTRAINT acqft_tag_once_per_owner UNIQUE (name, owner)
669 CREATE TABLE acq.fund_tag_map (
670 id SERIAL PRIMARY KEY,
671 fund INTEGER NOT NULL REFERENCES acq.fund(id)
672 DEFERRABLE INITIALLY DEFERRED,
673 tag INTEGER REFERENCES acq.fund_tag(id)
675 DEFERRABLE INITIALLY DEFERRED,
676 CONSTRAINT acqftm_fund_once_per_tag UNIQUE( fund, tag )
679 CREATE TABLE acq.fund_transfer (
680 id SERIAL PRIMARY KEY,
681 src_fund INT NOT NULL REFERENCES acq.fund( id )
682 DEFERRABLE INITIALLY DEFERRED,
683 src_amount NUMERIC NOT NULL,
684 dest_fund INT REFERENCES acq.fund( id )
685 DEFERRABLE INITIALLY DEFERRED,
687 transfer_time TIMESTAMPTZ NOT NULL DEFAULT now(),
688 transfer_user INT NOT NULL REFERENCES actor.usr( id )
689 DEFERRABLE INITIALLY DEFERRED,
691 funding_source_credit INT NOT NULL REFERENCES acq.funding_source_credit( id )
692 DEFERRABLE INITIALLY DEFERRED
695 CREATE INDEX acqftr_usr_idx
696 ON acq.fund_transfer( transfer_user );
698 COMMENT ON TABLE acq.fund_transfer IS $$
700 Each row represents the transfer of money from a source fund
701 to a destination fund. There should be corresponding entries
702 in acq.fund_allocation. The purpose of acq.fund_transfer is
703 to record how much money moved from which fund to which other
706 The presence of two amount fields, rather than one, reflects
707 the possibility that the two funds are denominated in different
708 currencies. If they use the same currency type, the two
709 amounts should be the same.
712 CREATE TABLE acq.fiscal_calendar (
713 id SERIAL PRIMARY KEY,
717 -- Create a default calendar (though we don't specify its contents).
718 -- Create a foreign key in actor.org_unit, initially pointing to
719 -- the default calendar.
721 INSERT INTO acq.fiscal_calendar (
728 ALTER TABLE actor.org_unit ADD FOREIGN KEY
729 (fiscal_calendar) REFERENCES acq.fiscal_calendar( id )
730 DEFERRABLE INITIALLY DEFERRED;
732 CREATE TABLE acq.fiscal_year (
733 id SERIAL PRIMARY KEY,
734 calendar INT NOT NULL
735 REFERENCES acq.fiscal_calendar
737 DEFERRABLE INITIALLY DEFERRED,
739 year_begin TIMESTAMPTZ NOT NULL,
740 year_end TIMESTAMPTZ NOT NULL,
741 CONSTRAINT acq_fy_logical_key UNIQUE ( calendar, year ),
742 CONSTRAINT acq_fy_physical_key UNIQUE ( calendar, year_begin )
745 CREATE TABLE acq.edi_attr (
746 key TEXT PRIMARY KEY,
747 label TEXT NOT NULL UNIQUE
750 CREATE TABLE acq.edi_attr_set (
751 id SERIAL PRIMARY KEY,
752 label TEXT NOT NULL UNIQUE
755 CREATE TABLE acq.edi_attr_set_map (
756 id SERIAL PRIMARY KEY,
757 attr_set INTEGER NOT NULL REFERENCES acq.edi_attr_set(id)
758 ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
759 attr TEXT NOT NULL REFERENCES acq.edi_attr(key)
760 ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
761 CONSTRAINT edi_attr_set_map_attr_once UNIQUE (attr_set, attr)
764 CREATE TABLE acq.edi_account ( -- similar tables can extend remote_account for other parts of EG
765 provider INT NOT NULL REFERENCES acq.provider (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
766 in_dir TEXT, -- incoming messages dir (probably different than config.remote_account.path, the outgoing dir)
769 attr_set INTEGER REFERENCES acq.edi_attr_set(id), -- NULL OK
770 use_attrs BOOLEAN NOT NULL DEFAULT FALSE
771 ) INHERITS (config.remote_account);
773 -- We need a UNIQUE constraint here also, to support the FK from acq.provider.edi_default
774 ALTER TABLE acq.edi_account ADD PRIMARY KEY (id);
776 CREATE TABLE acq.edi_message (
777 id SERIAL PRIMARY KEY,
778 account INTEGER REFERENCES acq.edi_account(id)
779 DEFERRABLE INITIALLY DEFERRED,
781 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
782 translate_time TIMESTAMPTZ,
783 process_time TIMESTAMPTZ,
784 error_time TIMESTAMPTZ,
785 status TEXT NOT NULL DEFAULT 'new'
786 CONSTRAINT status_value CHECK
788 'new', -- needs to be translated
789 'translated', -- needs to be processed
790 'trans_error', -- error in translation step
791 'processed', -- needs to have remote_file deleted
792 'proc_error', -- error in processing step
793 'delete_error', -- error in deletion
794 'retry', -- need to retry
800 purchase_order INT REFERENCES acq.purchase_order
801 DEFERRABLE INITIALLY DEFERRED,
802 message_type TEXT NOT NULL CONSTRAINT valid_message_type CHECK
811 CREATE INDEX edi_message_account_status_idx ON acq.edi_message (account,status);
812 CREATE INDEX edi_message_po_idx ON acq.edi_message (purchase_order);
813 CREATE INDEX edi_message_remote_file_idx ON acq.edi_message (evergreen.lowercase(remote_file));
815 -- Note below that the primary key is NOT a SERIAL type. We will periodically truncate and rebuild
816 -- the table, assigning ids programmatically instead of using a sequence.
817 CREATE TABLE acq.debit_attribution (
818 id INT NOT NULL PRIMARY KEY,
819 fund_debit INT NOT NULL
820 REFERENCES acq.fund_debit
821 DEFERRABLE INITIALLY DEFERRED,
822 debit_amount NUMERIC NOT NULL,
823 funding_source_credit INT REFERENCES acq.funding_source_credit
824 DEFERRABLE INITIALLY DEFERRED,
825 credit_amount NUMERIC
828 CREATE INDEX acq_attribution_debit_idx
829 ON acq.debit_attribution( fund_debit );
831 CREATE INDEX acq_attribution_credit_idx
832 ON acq.debit_attribution( funding_source_credit );
836 CREATE TABLE acq.invoice_method (
837 code TEXT PRIMARY KEY,
838 name TEXT NOT NULL -- i18n-ize
841 CREATE TABLE acq.invoice_payment_method (
842 code TEXT PRIMARY KEY,
843 name TEXT NOT NULL -- i18n-ize
846 CREATE TABLE acq.invoice (
847 id SERIAL PRIMARY KEY,
848 receiver INT NOT NULL REFERENCES actor.org_unit (id),
849 provider INT NOT NULL REFERENCES acq.provider (id),
850 shipper INT NOT NULL REFERENCES acq.provider (id),
851 recv_date TIMESTAMPTZ NOT NULL DEFAULT NOW(),
852 recv_method TEXT NOT NULL REFERENCES acq.invoice_method (code) DEFAULT 'EDI',
853 inv_type TEXT, -- A "type" field is desired, but no idea what goes here
854 inv_ident TEXT NOT NULL, -- vendor-supplied invoice id/number
856 payment_method TEXT REFERENCES acq.invoice_payment_method (code)
857 DEFERRABLE INITIALLY DEFERRED,
859 close_date TIMESTAMPTZ,
860 closed_by INTEGER REFERENCES actor.usr (id)
861 DEFERRABLE INITIALLY DEFERRED,
863 CONSTRAINT inv_ident_once_per_provider UNIQUE(provider, inv_ident)
866 CREATE TABLE acq.invoice_entry (
867 id SERIAL PRIMARY KEY,
868 invoice INT NOT NULL REFERENCES acq.invoice (id) ON DELETE CASCADE,
869 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
870 lineitem INT REFERENCES acq.lineitem (id) ON UPDATE CASCADE ON DELETE SET NULL,
871 inv_item_count INT NOT NULL, -- How many acqlids did they say they sent
872 phys_item_count INT, -- and how many did staff count
874 billed_per_item BOOL,
875 cost_billed NUMERIC(8,2),
876 actual_cost NUMERIC(8,2),
877 amount_paid NUMERIC (8,2)
880 CREATE INDEX ie_inv_idx on acq.invoice_entry (invoice);
881 CREATE INDEX ie_po_idx on acq.invoice_entry (purchase_order);
882 CREATE INDEX ie_li_idx on acq.invoice_entry (lineitem);
884 ALTER TABLE acq.fund_debit
885 ADD COLUMN invoice_entry INTEGER
886 REFERENCES acq.invoice_entry (id)
889 CREATE INDEX fund_debit_invoice_entry_idx ON acq.fund_debit (invoice_entry);
891 CREATE TABLE acq.invoice_item_type (
892 code TEXT PRIMARY KEY,
893 name TEXT NOT NULL, -- i18n-ize
894 prorate BOOL NOT NULL DEFAULT FALSE,
895 blanket BOOL NOT NULL DEFAULT FALSE,
896 CONSTRAINT aiit_not_blanket_and_prorate
897 CHECK (blanket IS FALSE OR prorate IS FALSE)
900 CREATE TABLE acq.po_item (
901 id SERIAL PRIMARY KEY,
902 purchase_order INT REFERENCES acq.purchase_order (id)
903 ON UPDATE CASCADE ON DELETE SET NULL
904 DEFERRABLE INITIALLY DEFERRED,
905 fund_debit INT REFERENCES acq.fund_debit (id)
906 DEFERRABLE INITIALLY DEFERRED,
907 inv_item_type TEXT NOT NULL
908 REFERENCES acq.invoice_item_type (code)
909 DEFERRABLE INITIALLY DEFERRED,
913 estimated_cost NUMERIC(8,2),
914 fund INT REFERENCES acq.fund (id)
915 DEFERRABLE INITIALLY DEFERRED,
919 CREATE INDEX poi_po_idx ON acq.po_item (purchase_order);
920 CREATE INDEX poi_fund_debit_idx ON acq.po_item (fund_debit);
922 CREATE TABLE acq.invoice_item ( -- for invoice-only debits: taxes/fees/non-bib items/etc
923 id SERIAL PRIMARY KEY,
924 invoice INT NOT NULL REFERENCES acq.invoice (id) ON UPDATE CASCADE ON DELETE CASCADE,
925 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
926 fund_debit INT REFERENCES acq.fund_debit (id),
927 inv_item_type TEXT NOT NULL REFERENCES acq.invoice_item_type (code),
931 cost_billed NUMERIC(8,2),
932 actual_cost NUMERIC(8,2),
933 fund INT REFERENCES acq.fund (id)
934 DEFERRABLE INITIALLY DEFERRED,
935 amount_paid NUMERIC (8,2),
936 po_item INT REFERENCES acq.po_item (id)
937 DEFERRABLE INITIALLY DEFERRED,
941 CREATE INDEX ii_inv_idx on acq.invoice_item (invoice);
942 CREATE INDEX ii_po_idx on acq.invoice_item (purchase_order);
943 CREATE INDEX ii_poi_idx on acq.invoice_item (po_item);
944 CREATE INDEX ii_fund_debit_idx ON acq.invoice_item (fund_debit);
947 CREATE TABLE acq.user_request_type (
948 id SERIAL PRIMARY KEY,
949 label TEXT NOT NULL UNIQUE -- i18n-ize
952 CREATE TABLE acq.user_request_status_type (
953 id SERIAL PRIMARY KEY
957 INSERT INTO acq.user_request_status_type (id,label) VALUES
958 (0,oils_i18n_gettext(0,'Error','aurst','label'))
959 ,(1,oils_i18n_gettext(1,'New','aurst','label'))
960 ,(2,oils_i18n_gettext(2,'Pending','aurst','label'))
961 ,(3,oils_i18n_gettext(3,'Ordered, Hold Not Placed','aurst','label'))
962 ,(4,oils_i18n_gettext(4,'Ordered, Hold Placed','aurst','label'))
963 ,(5,oils_i18n_gettext(5,'Received','aurst','label'))
964 ,(6,oils_i18n_gettext(6,'Fulfilled','aurst','label'))
965 ,(7,oils_i18n_gettext(7,'Canceled','aurst','label'))
968 SELECT SETVAL('acq.user_request_status_type_id_seq'::TEXT, 100);
970 CREATE TABLE acq.user_request (
971 id SERIAL PRIMARY KEY,
972 usr INT NOT NULL REFERENCES actor.usr (id), -- requesting user
973 hold BOOL NOT NULL DEFAULT TRUE,
975 pickup_lib INT NOT NULL REFERENCES actor.org_unit (id), -- pickup lib
976 holdable_formats TEXT, -- nullable, for use in hold creation
978 email_notify BOOL NOT NULL DEFAULT TRUE,
979 lineitem INT REFERENCES acq.lineitem (id) ON DELETE CASCADE,
980 eg_bib BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
981 request_date TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- when they requested it
982 need_before TIMESTAMPTZ, -- don't create holds after this
985 request_type INT NOT NULL REFERENCES acq.user_request_type (id),
998 cancel_reason INT REFERENCES acq.cancel_reason( id )
999 DEFERRABLE INITIALLY DEFERRED,
1000 cancel_time TIMESTAMPTZ
1003 ALTER TABLE action.hold_request ADD COLUMN acq_request INT REFERENCES acq.user_request (id);
1007 CREATE TYPE acq.flat_lineitem_holding_subfield AS (lineitem int, holding int, subfield text, data text);
1008 CREATE OR REPLACE FUNCTION acq.extract_holding_attr_table (lineitem int, tag text) RETURNS SETOF acq.flat_lineitem_holding_subfield AS $$
1011 lida acq.flat_lineitem_holding_subfield%ROWTYPE;
1014 SELECT COUNT(*) INTO counter
1015 FROM oils_xpath_table(
1019 '//*[@tag="' || tag || '"]',
1021 ) as t(i int,c text);
1023 FOR i IN 1 .. counter LOOP
1026 FROM ( SELECT id,i,t,v
1027 FROM oils_xpath_table(
1031 '//*[@tag="' || tag || '"][position()=' || i || ']/*/@code|' ||
1032 '//*[@tag="' || tag || '"][position()=' || i || ']/*[@code]',
1034 ) as t(id int,t text,v text)
1043 $$ LANGUAGE PLPGSQL;
1045 CREATE TYPE acq.flat_lineitem_detail AS (lineitem int, holding int, attr text, data text);
1046 CREATE OR REPLACE FUNCTION acq.extract_provider_holding_data ( lineitem_i int ) RETURNS SETOF acq.flat_lineitem_detail AS $$
1050 lida acq.flat_lineitem_detail%ROWTYPE;
1052 SELECT provider INTO prov_i FROM acq.lineitem WHERE id = lineitem_i;
1053 IF NOT FOUND THEN RETURN; END IF;
1055 SELECT holding_tag INTO tag_t FROM acq.provider WHERE id = prov_i;
1056 IF NOT FOUND OR tag_t IS NULL THEN RETURN; END IF;
1063 FROM acq.extract_holding_attr_table( lineitem_i, tag_t ) h
1064 JOIN acq.provider_holding_subfield_map a USING (subfield)
1065 WHERE a.provider = prov_i
1072 $$ LANGUAGE PLPGSQL;
1074 -- select * from acq.extract_provider_holding_data(699);
1076 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field ( BIGINT, TEXT, TEXT) RETURNS TEXT AS $$
1077 SELECT extract_marc_field('acq.lineitem', $1, $2, $3);
1080 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field_set ( BIGINT, TEXT, TEXT) RETURNS SETOF TEXT AS $$
1081 SELECT extract_marc_field_set('acq.lineitem', $1, $2, $3);
1086 CREATE OR REPLACE FUNCTION public.extract_bib_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
1087 SELECT public.extract_marc_field('biblio.record_entry', $1, $2);
1090 CREATE OR REPLACE FUNCTION public.extract_authority_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
1091 SELECT public.extract_marc_field('authority.record_entry', $1, $2);
1095 -- INSERT INTO acq.lineitem_provider_attr_definition ( provider, code, description, xpath ) VALUES (1,'price','Price','//*[@tag="020" or @tag="022"]/*[@code="a"][1]');
1098 Suggested vendor fields:
1106 CREATE OR REPLACE FUNCTION public.ingest_acq_marc ( ) RETURNS TRIGGER AS $function$
1115 FOR adef IN SELECT *,tableoid FROM acq.lineitem_attr_definition LOOP
1117 SELECT relname::TEXT INTO atype FROM pg_class WHERE oid = adef.tableoid;
1119 IF (atype NOT IN ('lineitem_usr_attr_definition','lineitem_local_attr_definition')) THEN
1120 IF (atype = 'lineitem_provider_attr_definition') THEN
1121 SELECT provider INTO prov FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
1122 CONTINUE WHEN NEW.provider IS NULL OR prov <> NEW.provider;
1125 IF (atype = 'lineitem_provider_attr_definition') THEN
1126 SELECT xpath INTO xpath_string FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
1127 ELSIF (atype = 'lineitem_marc_attr_definition') THEN
1128 SELECT xpath INTO xpath_string FROM acq.lineitem_marc_attr_definition WHERE id = adef.id;
1129 ELSIF (atype = 'lineitem_generated_attr_definition') THEN
1130 SELECT xpath INTO xpath_string FROM acq.lineitem_generated_attr_definition WHERE id = adef.id;
1133 xpath_string := REGEXP_REPLACE(xpath_string,$re$//?text\(\)$$re$,'');
1135 IF (adef.code = 'title' OR adef.code = 'author') THEN
1136 -- title and author should not be split
1137 -- FIXME: once oils_xpath can grok XPATH 2.0 functions, we can use
1138 -- string-join in the xpath and remove this special case
1139 SELECT extract_acq_marc_field(id, xpath_string, adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
1140 IF (value IS NOT NULL AND value <> '') THEN
1141 INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
1142 VALUES (NEW.id, adef.id, atype, adef.code, value);
1147 -- each application of the regex may produce multiple values
1149 SELECT * FROM extract_acq_marc_field_set(
1150 NEW.id, xpath_string || '[' || pos || ']', adef.remove)
1153 IF (value IS NOT NULL AND value <> '') THEN
1154 INSERT INTO acq.lineitem_attr
1155 (lineitem, definition, attr_type, attr_name, attr_value)
1156 VALUES (NEW.id, adef.id, atype, adef.code, value);
1174 $function$ LANGUAGE PLPGSQL;
1176 CREATE OR REPLACE FUNCTION public.cleanup_acq_marc ( ) RETURNS TRIGGER AS $$
1178 IF TG_OP = 'UPDATE' THEN
1179 DELETE FROM acq.lineitem_attr
1180 WHERE lineitem = OLD.id AND attr_type IN ('lineitem_provider_attr_definition', 'lineitem_marc_attr_definition','lineitem_generated_attr_definition');
1183 DELETE FROM acq.lineitem_attr WHERE lineitem = OLD.id;
1187 $$ LANGUAGE PLPGSQL;
1189 CREATE TRIGGER cleanup_lineitem_trigger
1190 BEFORE UPDATE OR DELETE ON acq.lineitem
1191 FOR EACH ROW EXECUTE PROCEDURE public.cleanup_acq_marc();
1193 CREATE TRIGGER ingest_lineitem_trigger
1194 AFTER INSERT OR UPDATE ON acq.lineitem
1195 FOR EACH ROW EXECUTE PROCEDURE public.ingest_acq_marc();
1197 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( from_ex TEXT, to_ex TEXT ) RETURNS NUMERIC AS $$
1201 IF from_ex = to_ex THEN
1205 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = from_ex AND to_currency = to_ex;
1210 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = to_ex AND to_currency = from_ex;
1219 $$ LANGUAGE PLPGSQL;
1221 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( TEXT, TEXT, NUMERIC ) RETURNS NUMERIC AS $$
1222 SELECT $3 * acq.exchange_ratio($1, $2);
1225 CREATE OR REPLACE FUNCTION acq.find_bad_fy()
1227 Examine the acq.fiscal_year table, comparing successive years.
1228 Report any inconsistencies, i.e. years that overlap, have gaps
1229 between them, or are out of sequence.
1231 RETURNS SETOF RECORD AS $$
1255 ELSIF curr_year.calendar = prev_year.calendar THEN
1256 IF curr_year.year_begin > prev_year.year_end THEN
1257 -- This ugly kludge works around the fact that older
1258 -- versions of PostgreSQL don't support RETURN QUERY SELECT
1259 FOR return_rec IN SELECT
1262 'Gap between fiscal years'::TEXT
1264 RETURN NEXT return_rec;
1266 ELSIF curr_year.year_begin < prev_year.year_end THEN
1267 FOR return_rec IN SELECT
1270 'Overlapping fiscal years'::TEXT
1272 RETURN NEXT return_rec;
1274 ELSIF curr_year.year < prev_year.year THEN
1275 FOR return_rec IN SELECT
1278 'Fiscal years out of order'::TEXT
1280 RETURN NEXT return_rec;
1285 prev_year := curr_year;
1290 $$ LANGUAGE plpgsql;
1292 CREATE OR REPLACE FUNCTION acq.transfer_fund(
1294 old_amount IN NUMERIC, -- in currency of old fund
1296 new_amount IN NUMERIC, -- in currency of new fund
1298 xfer_note IN TEXT -- to be recorded in acq.fund_transfer
1299 -- ,funding_source_in IN INT -- if user wants to specify a funding source (see notes)
1300 ) RETURNS VOID AS $$
1301 /* -------------------------------------------------------------------------------
1303 Function to transfer money from one fund to another.
1305 A transfer is represented as a pair of entries in acq.fund_allocation, with a
1306 negative amount for the old (losing) fund and a positive amount for the new
1307 (gaining) fund. In some cases there may be more than one such pair of entries
1308 in order to pull the money from different funding sources, or more specifically
1309 from different funding source credits. For each such pair there is also an
1310 entry in acq.fund_transfer.
1312 Since funding_source is a non-nullable column in acq.fund_allocation, we must
1313 choose a funding source for the transferred money to come from. This choice
1314 must meet two constraints, so far as possible:
1316 1. The amount transferred from a given funding source must not exceed the
1317 amount allocated to the old fund by the funding source. To that end we
1318 compare the amount being transferred to the amount allocated.
1320 2. We shouldn't transfer money that has already been spent or encumbered, as
1321 defined by the funding attribution process. We attribute expenses to the
1322 oldest funding source credits first. In order to avoid transferring that
1323 attributed money, we reverse the priority, transferring from the newest funding
1324 source credits first. There can be no guarantee that this approach will
1325 avoid overcommitting a fund, but no other approach can do any better.
1327 In this context the age of a funding source credit is defined by the
1328 deadline_date for credits with deadline_dates, and by the effective_date for
1329 credits without deadline_dates, with the proviso that credits with deadline_dates
1330 are all considered "older" than those without.
1334 In the signature for this function, there is one last parameter commented out,
1335 named "funding_source_in". Correspondingly, the WHERE clause for the query
1336 driving the main loop has an OR clause commented out, which references the
1337 funding_source_in parameter.
1339 If these lines are uncommented, this function will allow the user optionally to
1340 restrict a fund transfer to a specified funding source. If the source
1341 parameter is left NULL, then there will be no such restriction.
1343 ------------------------------------------------------------------------------- */
1345 same_currency BOOLEAN;
1346 currency_ratio NUMERIC;
1347 old_fund_currency TEXT;
1348 old_remaining NUMERIC; -- in currency of old fund
1349 new_fund_currency TEXT;
1350 new_fund_active BOOLEAN;
1351 new_remaining NUMERIC; -- in currency of new fund
1352 curr_old_amt NUMERIC; -- in currency of old fund
1353 curr_new_amt NUMERIC; -- in currency of new fund
1354 source_addition NUMERIC; -- in currency of funding source
1355 source_deduction NUMERIC; -- in currency of funding source
1356 orig_allocated_amt NUMERIC; -- in currency of funding source
1357 allocated_amt NUMERIC; -- in currency of fund
1359 old_fund_row acq.fund%ROWTYPE;
1360 new_fund_row acq.fund%ROWTYPE;
1361 old_org_row actor.org_unit%ROWTYPE;
1362 new_org_row actor.org_unit%ROWTYPE;
1367 IF old_fund IS NULL THEN
1368 RAISE EXCEPTION 'acq.transfer_fund: old fund id is NULL';
1371 IF old_amount IS NULL THEN
1372 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer is NULL';
1375 -- The new fund and its amount must be both NULL or both not NULL.
1377 IF new_fund IS NOT NULL AND new_amount IS NULL THEN
1378 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer to receiving fund is NULL';
1381 IF new_fund IS NULL AND new_amount IS NOT NULL THEN
1382 RAISE EXCEPTION 'acq.transfer_fund: receiving fund is NULL, its amount is not NULL';
1385 IF user_id IS NULL THEN
1386 RAISE EXCEPTION 'acq.transfer_fund: user id is NULL';
1389 -- Initialize the amounts to be transferred, each denominated
1390 -- in the currency of its respective fund. They will be
1391 -- reduced on each iteration of the loop.
1393 old_remaining := old_amount;
1394 new_remaining := new_amount;
1396 -- RAISE NOTICE 'Transferring % in fund % to % in fund %',
1397 -- old_amount, old_fund, new_amount, new_fund;
1399 -- Get the currency types of the old and new funds.
1410 IF old_fund_currency IS NULL THEN
1411 RAISE EXCEPTION 'acq.transfer_fund: old fund id % is not defined', old_fund;
1414 IF new_fund IS NOT NULL THEN
1426 IF new_fund_currency IS NULL THEN
1427 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is not defined', new_fund;
1428 ELSIF NOT new_fund_active THEN
1430 -- No point in putting money into a fund from whence you can't spend it
1432 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is inactive', new_fund;
1435 IF new_amount = old_amount THEN
1436 same_currency := true;
1437 currency_ratio := 1;
1440 -- We'll have to translate currency between funds. We presume that
1441 -- the calling code has already applied an appropriate exchange rate,
1442 -- so we'll apply the same conversion to each sub-transfer.
1444 same_currency := false;
1445 currency_ratio := new_amount / old_amount;
1449 -- Fetch old and new fund's information
1450 -- in order to construct the allocation notes
1451 SELECT INTO old_fund_row * FROM acq.fund WHERE id = old_fund;
1452 SELECT INTO old_org_row * FROM actor.org_unit WHERE id = old_fund_row.org;
1453 SELECT INTO new_fund_row * FROM acq.fund WHERE id = new_fund;
1454 SELECT INTO new_org_row * FROM actor.org_unit WHERE id = new_fund_row.org;
1457 -- Identify the funding source(s) from which we want to transfer the money.
1458 -- The principle is that we want to transfer the newest money first, because
1459 -- we spend the oldest money first. The priority for spending is defined
1460 -- by a sort of the view acq.ordered_funding_source_credit.
1465 ofsc.funding_source,
1467 ofsc.amount * acq.exchange_ratio( fs.currency_type, old_fund_currency )
1471 acq.ordered_funding_source_credit AS ofsc,
1472 acq.funding_source fs
1474 ofsc.funding_source = fs.id
1475 and ofsc.funding_source IN
1477 SELECT funding_source
1478 FROM acq.fund_allocation
1479 WHERE fund = old_fund
1483 -- ofsc.funding_source = funding_source_in
1484 -- OR funding_source_in IS NULL
1487 ofsc.sort_priority desc,
1488 ofsc.sort_date desc,
1492 -- Determine how much money the old fund got from this funding source,
1493 -- denominated in the currency types of the source and of the fund.
1494 -- This result may reflect transfers from previous iterations.
1497 COALESCE( sum( amount ), 0 ),
1498 COALESCE( sum( amount )
1499 * acq.exchange_ratio( source.currency_type, old_fund_currency ), 0 )
1501 orig_allocated_amt, -- in currency of the source
1502 allocated_amt -- in currency of the old fund
1507 and funding_source = source.funding_source;
1509 -- Determine how much to transfer from this credit, in the currency
1510 -- of the fund. Begin with the amount remaining to be attributed:
1512 curr_old_amt := old_remaining;
1514 -- Can't attribute more than was allocated from the fund:
1516 IF curr_old_amt > allocated_amt THEN
1517 curr_old_amt := allocated_amt;
1520 -- Can't attribute more than the amount of the current credit:
1522 IF curr_old_amt > source.converted_amt THEN
1523 curr_old_amt := source.converted_amt;
1526 curr_old_amt := trunc( curr_old_amt, 2 );
1528 old_remaining := old_remaining - curr_old_amt;
1530 -- Determine the amount to be deducted, if any,
1531 -- from the old allocation.
1533 IF old_remaining > 0 THEN
1535 -- In this case we're using the whole allocation, so use that
1536 -- amount directly instead of applying a currency translation
1537 -- and thereby inviting round-off errors.
1539 source_deduction := - curr_old_amt;
1541 source_deduction := trunc(
1542 ( - curr_old_amt ) *
1543 acq.exchange_ratio( old_fund_currency, source.currency_type ),
1547 IF source_deduction <> 0 THEN
1549 -- Insert negative allocation for old fund in fund_allocation,
1550 -- converted into the currency of the funding source
1552 INSERT INTO acq.fund_allocation (
1559 source.funding_source,
1563 'Transfer to fund ' || new_fund_row.code || ' ('
1564 || new_fund_row.year || ') ('
1565 || new_org_row.shortname || ')'
1569 IF new_fund IS NOT NULL THEN
1571 -- Determine how much to add to the new fund, in
1572 -- its currency, and how much remains to be added:
1574 IF same_currency THEN
1575 curr_new_amt := curr_old_amt;
1577 IF old_remaining = 0 THEN
1579 -- This is the last iteration, so nothing should be left
1581 curr_new_amt := new_remaining;
1584 curr_new_amt := trunc( curr_old_amt * currency_ratio, 2 );
1585 new_remaining := new_remaining - curr_new_amt;
1589 -- Determine how much to add, if any,
1590 -- to the new fund's allocation.
1592 IF old_remaining > 0 THEN
1594 -- In this case we're using the whole allocation, so use that amount
1595 -- amount directly instead of applying a currency translation and
1596 -- thereby inviting round-off errors.
1598 source_addition := curr_new_amt;
1599 ELSIF source.currency_type = old_fund_currency THEN
1601 -- In this case we don't need a round trip currency translation,
1602 -- thereby inviting round-off errors:
1604 source_addition := curr_old_amt;
1606 source_addition := trunc(
1608 acq.exchange_ratio( new_fund_currency, source.currency_type ),
1612 IF source_addition <> 0 THEN
1614 -- Insert positive allocation for new fund in fund_allocation,
1615 -- converted to the currency of the founding source
1617 INSERT INTO acq.fund_allocation (
1624 source.funding_source,
1628 'Transfer from fund ' || old_fund_row.code || ' ('
1629 || old_fund_row.year || ') ('
1630 || old_org_row.shortname || ')'
1635 IF trunc( curr_old_amt, 2 ) <> 0
1636 OR trunc( curr_new_amt, 2 ) <> 0 THEN
1638 -- Insert row in fund_transfer, using amounts in the currency of the funds
1640 INSERT INTO acq.fund_transfer (
1647 funding_source_credit
1650 trunc( curr_old_amt, 2 ),
1652 trunc( curr_new_amt, 2 ),
1659 if old_remaining <= 0 THEN
1660 EXIT; -- Nothing more to be transferred
1664 $$ LANGUAGE plpgsql;
1666 CREATE OR REPLACE FUNCTION acq.attribute_debits() RETURNS VOID AS $$
1668 Function to attribute expenditures and encumbrances to funding source credits,
1669 and thereby to funding sources.
1671 Read the debits in chonological order, attributing each one to one or
1672 more funding source credits. Constraints:
1674 1. Don't attribute more to a credit than the amount of the credit.
1676 2. For a given fund, don't attribute more to a funding source than the
1677 source has allocated to that fund.
1679 3. Attribute debits to credits with deadlines before attributing them to
1680 credits without deadlines. Otherwise attribute to the earliest credits
1681 first, based on the deadline date when present, or on the effective date
1682 when there is no deadline. Use funding_source_credit.id as a tie-breaker.
1683 This ordering is defined by an ORDER BY clause on the view
1684 acq.ordered_funding_source_credit.
1686 Start by truncating the table acq.debit_attribution. Then insert a row
1687 into that table for each attribution. If a debit cannot be fully
1688 attributed, insert a row for the unattributable balance, with the
1689 funding_source_credit and credit_amount columns NULL.
1692 curr_fund_source_bal RECORD;
1693 seqno INT; -- sequence num for credits applicable to a fund
1694 fund_credit RECORD; -- current row in temp t_fund_credit table
1695 fc RECORD; -- used for loading t_fund_credit table
1696 sc RECORD; -- used for loading t_fund_credit table
1698 -- Used exclusively in the main loop:
1700 deb RECORD; -- current row from acq.fund_debit table
1701 curr_credit_bal RECORD; -- current row from temp t_credit table
1702 debit_balance NUMERIC; -- amount left to attribute for current debit
1703 conv_debit_balance NUMERIC; -- debit balance in currency of the fund
1704 attr_amount NUMERIC; -- amount being attributed, in currency of debit
1705 conv_attr_amount NUMERIC; -- amount being attributed, in currency of source
1706 conv_cred_balance NUMERIC; -- credit_balance in the currency of the fund
1707 conv_alloc_balance NUMERIC; -- allocated balance in the currency of the fund
1708 attrib_count INT; -- populates id of acq.debit_attribution
1711 -- Load a temporary table. For each combination of fund and funding source,
1712 -- load an entry with the total amount allocated to that fund by that source.
1713 -- This sum may reflect transfers as well as original allocations. We will
1714 -- reduce this balance whenever we attribute debits to it.
1716 CREATE TEMP TABLE t_fund_source_bal
1720 funding_source AS source,
1721 sum( amount ) AS balance
1730 CREATE INDEX t_fund_source_bal_idx
1731 ON t_fund_source_bal( fund, source );
1732 -------------------------------------------------------------------------------
1734 -- Load another temporary table. For each fund, load zero or more
1735 -- funding source credits from which that fund can get money.
1737 CREATE TEMP TABLE t_fund_credit (
1744 SELECT DISTINCT fund
1745 FROM acq.fund_allocation
1747 LOOP -- Loop over the funds
1753 acq.ordered_funding_source_credit AS ofsc
1755 ofsc.funding_source IN
1757 SELECT funding_source
1758 FROM acq.fund_allocation
1759 WHERE fund = fc.fund
1765 LOOP -- Add each credit to the list
1766 INSERT INTO t_fund_credit (
1775 --RAISE NOTICE 'Fund % credit %', fc.fund, sc.id;
1777 END LOOP; -- Loop over credits for a given fund
1778 END LOOP; -- Loop over funds
1780 CREATE INDEX t_fund_credit_idx
1781 ON t_fund_credit( fund, seq );
1782 -------------------------------------------------------------------------------
1784 -- Load yet another temporary table. This one is a list of funding source
1785 -- credits, with their balances. We shall reduce those balances as we
1786 -- attribute debits to them.
1788 CREATE TEMP TABLE t_credit
1792 fsc.funding_source AS source,
1793 fsc.amount AS balance,
1794 fs.currency_type AS currency_type
1796 acq.funding_source_credit AS fsc,
1797 acq.funding_source fs
1799 fsc.funding_source = fs.id
1802 CREATE INDEX t_credit_idx
1803 ON t_credit( credit );
1805 -------------------------------------------------------------------------------
1807 -- Now that we have loaded the lookup tables: loop through the debits,
1808 -- attributing each one to one or more funding source credits.
1810 truncate table acq.debit_attribution;
1828 --RAISE NOTICE 'Debit %, fund %', deb.id, deb.fund;
1830 debit_balance := deb.amount;
1832 -- Loop over the funding source credits that are eligible
1833 -- to pay for this debit
1845 --RAISE NOTICE ' Examining credit %', fund_credit.credit;
1847 -- Look up the balance for this credit. If it's zero, then
1848 -- it's not useful, so treat it as if you didn't find it.
1849 -- (Actually there shouldn't be any zero balances in the table,
1850 -- but we check just to make sure.)
1853 INTO curr_credit_bal
1856 credit = fund_credit.credit
1859 IF curr_credit_bal IS NULL THEN
1861 -- This credit is exhausted; try the next one.
1867 -- At this point we have an applicable credit with some money left.
1868 -- Now see if the relevant funding_source has any money left.
1870 -- Look up the balance of the allocation for this combination of
1871 -- fund and source. If you find such an entry, but it has a zero
1872 -- balance, then it's not useful, so treat it as unfound.
1873 -- (Actually there shouldn't be any zero balances in the table,
1874 -- but we check just to make sure.)
1877 INTO curr_fund_source_bal
1878 FROM t_fund_source_bal
1881 AND source = curr_credit_bal.source
1884 IF curr_fund_source_bal IS NULL THEN
1886 -- This fund/source doesn't exist or is already exhausted,
1887 -- so we can't use this credit. Go on to the next one.
1892 -- Convert the available balances to the currency of the fund
1894 conv_alloc_balance := curr_fund_source_bal.balance * acq.exchange_ratio(
1895 curr_credit_bal.currency_type, deb.currency_type );
1896 conv_cred_balance := curr_credit_bal.balance * acq.exchange_ratio(
1897 curr_credit_bal.currency_type, deb.currency_type );
1899 -- Determine how much we can attribute to this credit: the minimum
1900 -- of the debit amount, the fund/source balance, and the
1903 --RAISE NOTICE ' deb bal %', debit_balance;
1904 --RAISE NOTICE ' source % balance %', curr_credit_bal.source, conv_alloc_balance;
1905 --RAISE NOTICE ' credit % balance %', curr_credit_bal.credit, conv_cred_balance;
1907 conv_attr_amount := NULL;
1908 attr_amount := debit_balance;
1910 IF attr_amount > conv_alloc_balance THEN
1911 attr_amount := conv_alloc_balance;
1912 conv_attr_amount := curr_fund_source_bal.balance;
1914 IF attr_amount > conv_cred_balance THEN
1915 attr_amount := conv_cred_balance;
1916 conv_attr_amount := curr_credit_bal.balance;
1919 -- If we're attributing all of one of the balances, then that's how
1920 -- much we will deduct from the balances, and we already captured
1921 -- that amount above. Otherwise we must convert the amount of the
1922 -- attribution from the currency of the fund back to the currency of
1923 -- the funding source.
1925 IF conv_attr_amount IS NULL THEN
1926 conv_attr_amount := attr_amount * acq.exchange_ratio(
1927 deb.currency_type, curr_credit_bal.currency_type );
1930 -- Insert a row to record the attribution
1932 attrib_count := attrib_count + 1;
1933 INSERT INTO acq.debit_attribution (
1937 funding_source_credit,
1943 curr_credit_bal.credit,
1947 -- Subtract the attributed amount from the various balances
1949 debit_balance := debit_balance - attr_amount;
1950 curr_fund_source_bal.balance := curr_fund_source_bal.balance - conv_attr_amount;
1952 IF curr_fund_source_bal.balance <= 0 THEN
1954 -- This allocation is exhausted. Delete it so
1955 -- that we don't waste time looking at it again.
1957 DELETE FROM t_fund_source_bal
1959 fund = curr_fund_source_bal.fund
1960 AND source = curr_fund_source_bal.source;
1962 UPDATE t_fund_source_bal
1963 SET balance = balance - conv_attr_amount
1965 fund = curr_fund_source_bal.fund
1966 AND source = curr_fund_source_bal.source;
1969 IF curr_credit_bal.balance <= 0 THEN
1971 -- This funding source credit is exhausted. Delete it
1972 -- so that we don't waste time looking at it again.
1974 --DELETE FROM t_credit
1976 -- credit = curr_credit_bal.credit;
1978 DELETE FROM t_fund_credit
1980 credit = curr_credit_bal.credit;
1983 SET balance = curr_credit_bal.balance
1985 credit = curr_credit_bal.credit;
1988 -- Are we done with this debit yet?
1990 IF debit_balance <= 0 THEN
1991 EXIT; -- We've fully attributed this debit; stop looking at credits.
1993 END LOOP; -- End loop over credits
1995 IF debit_balance <> 0 THEN
1997 -- We weren't able to attribute this debit, or at least not
1998 -- all of it. Insert a row for the unattributed balance.
2000 attrib_count := attrib_count + 1;
2001 INSERT INTO acq.debit_attribution (
2005 funding_source_credit,
2015 END LOOP; -- End of loop over debits
2017 $$ LANGUAGE 'plpgsql';
2019 CREATE OR REPLACE FUNCTION acq.copy_fund_tags(
2020 old_fund_id INTEGER,
2022 ) RETURNS VOID AS $$
2024 fund_tag_rec RECORD;
2027 FOR fund_tag_rec IN SELECT * FROM acq.fund_tag_map WHERE fund=old_fund_id LOOP
2029 INSERT INTO acq.fund_tag_map(fund, tag) VALUES(new_fund_id, fund_tag_rec.tag);
2031 WHEN unique_violation THEN
2032 -- RAISE NOTICE 'Fund tag already propagated', old_fund.id;
2038 $$ LANGUAGE plpgsql;
2040 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_tree(
2043 org_unit_id INTEGER,
2044 include_desc BOOL DEFAULT TRUE
2045 ) RETURNS VOID AS $$
2056 IF old_year IS NULL THEN
2057 RAISE EXCEPTION 'Input year argument is NULL';
2058 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2059 RAISE EXCEPTION 'Input year is out of range';
2062 IF user_id IS NULL THEN
2063 RAISE EXCEPTION 'Input user id argument is NULL';
2066 IF org_unit_id IS NULL THEN
2067 RAISE EXCEPTION 'Org unit id argument is NULL';
2069 SELECT TRUE INTO org_found
2071 WHERE id = org_unit_id;
2073 IF org_found IS NULL THEN
2074 RAISE EXCEPTION 'Org unit id is invalid';
2078 -- Loop over the applicable funds
2080 FOR old_fund in SELECT * FROM acq.fund
2084 AND ( ( include_desc AND org IN ( SELECT id FROM actor.org_unit_descendants( org_unit_id ) ) )
2085 OR (NOT include_desc AND org = org_unit_id ) )
2089 INSERT INTO acq.fund (
2097 balance_warning_percent,
2098 balance_stop_percent
2103 old_fund.currency_type,
2107 old_fund.balance_warning_percent,
2108 old_fund.balance_stop_percent
2110 RETURNING id INTO new_id;
2112 WHEN unique_violation THEN
2113 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
2117 PERFORM acq.copy_fund_tags(old_fund.id,new_id);
2119 --RAISE NOTICE 'Propagating fund % to fund %',
2120 -- old_fund.code, new_id;
2123 $$ LANGUAGE plpgsql;
2125 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_unit( old_year INTEGER, user_id INTEGER, org_unit_id INTEGER ) RETURNS VOID AS $$
2126 SELECT acq.propagate_funds_by_org_tree( $1, $2, $3, FALSE );
2129 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_tree(
2132 org_unit_id INTEGER,
2133 encumb_only BOOL DEFAULT FALSE,
2134 include_desc BOOL DEFAULT TRUE
2135 ) RETURNS VOID AS $$
2139 new_year INT := old_year + 1;
2142 xfer_amount NUMERIC := 0;
2146 roll_distrib_forms BOOL;
2152 IF old_year IS NULL THEN
2153 RAISE EXCEPTION 'Input year argument is NULL';
2154 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2155 RAISE EXCEPTION 'Input year is out of range';
2158 IF user_id IS NULL THEN
2159 RAISE EXCEPTION 'Input user id argument is NULL';
2162 IF org_unit_id IS NULL THEN
2163 RAISE EXCEPTION 'Org unit id argument is NULL';
2166 -- Validate the org unit
2171 WHERE id = org_unit_id;
2173 IF org_found IS NULL THEN
2174 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
2175 ELSIF encumb_only THEN
2176 SELECT INTO perm_ous value::BOOL FROM
2177 actor.org_unit_ancestor_setting(
2178 'acq.fund.allow_rollover_without_money', org_unit_id
2180 IF NOT FOUND OR NOT perm_ous THEN
2181 RAISE EXCEPTION 'Encumbrance-only rollover not permitted at org %', org_unit_id;
2186 -- Loop over the propagable funds to identify the details
2187 -- from the old fund plus the id of the new one, if it exists.
2191 oldf.id AS old_fund,
2197 newf.id AS new_fund_id
2200 LEFT JOIN acq.fund AS newf
2201 ON ( oldf.code = newf.code AND oldf.org = newf.org )
2203 oldf.year = old_year
2205 AND newf.year = new_year
2206 AND ( ( include_desc AND oldf.org IN ( SELECT id FROM actor.org_unit_descendants( org_unit_id ) ) )
2207 OR (NOT include_desc AND oldf.org = org_unit_id ) )
2209 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2211 IF roll_fund.new_fund_id IS NULL THEN
2213 -- The old fund hasn't been propagated yet. Propagate it now.
2215 INSERT INTO acq.fund (
2223 balance_warning_percent,
2224 balance_stop_percent
2229 roll_fund.currency_type,
2233 roll_fund.balance_warning_percent,
2234 roll_fund.balance_stop_percent
2236 RETURNING id INTO new_fund;
2238 PERFORM acq.copy_fund_tags(roll_fund.id,new_fund);
2241 new_fund = roll_fund.new_fund_id;
2244 -- Determine the amount to transfer
2248 FROM acq.fund_spent_balance
2249 WHERE fund = roll_fund.old_fund;
2251 IF xfer_amount <> 0 THEN
2252 IF NOT encumb_only AND roll_fund.rollover THEN
2254 -- Transfer balance from old fund to new
2256 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2258 PERFORM acq.transfer_fund(
2268 -- Transfer balance from old fund to the void
2270 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2272 PERFORM acq.transfer_fund(
2278 'Rollover into the void'
2283 IF roll_fund.rollover THEN
2285 -- Move any lineitems from the old fund to the new one
2286 -- where the associated debit is an encumbrance.
2288 -- Any other tables tying expenditure details to funds should
2289 -- receive similar treatment. At this writing there are none.
2291 UPDATE acq.lineitem_detail
2294 fund = roll_fund.old_fund -- this condition may be redundant
2300 fund = roll_fund.old_fund
2304 -- Move encumbrance debits from the old fund to the new fund
2306 UPDATE acq.fund_debit
2309 fund = roll_fund.old_fund
2313 -- Rollover distribution formulae funds
2314 SELECT INTO roll_distrib_forms value::BOOL FROM
2315 actor.org_unit_ancestor_setting(
2316 'acq.fund.rollover_distrib_forms', org_unit_id
2319 IF roll_distrib_forms THEN
2320 UPDATE acq.distribution_formula_entry
2321 SET fund = roll_fund.new_fund_id
2322 WHERE fund = roll_fund.old_fund;
2326 -- Mark old fund as inactive, now that we've closed it
2330 WHERE id = roll_fund.old_fund;
2333 $$ LANGUAGE plpgsql;
2338 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_unit( old_year INTEGER, user_id INTEGER, org_unit_id INTEGER, encumb_only BOOL DEFAULT FALSE ) RETURNS VOID AS $$
2339 SELECT acq.rollover_funds_by_org_tree( $1, $2, $3, $4, FALSE );
2342 CREATE OR REPLACE VIEW acq.funding_source_credit_total AS
2343 SELECT funding_source,
2344 SUM(amount) AS amount
2345 FROM acq.funding_source_credit
2348 CREATE OR REPLACE VIEW acq.funding_source_allocation_total AS
2349 SELECT funding_source,
2350 SUM(a.amount)::NUMERIC(100,2) AS amount
2351 FROM acq.fund_allocation a
2354 CREATE OR REPLACE VIEW acq.funding_source_balance AS
2355 SELECT COALESCE(c.funding_source, a.funding_source) AS funding_source,
2356 SUM(COALESCE(c.amount,0.0) - COALESCE(a.amount,0.0))::NUMERIC(100,2) AS amount
2357 FROM acq.funding_source_credit_total c
2358 FULL JOIN acq.funding_source_allocation_total a USING (funding_source)
2361 CREATE OR REPLACE VIEW acq.fund_allocation_total AS
2363 SUM(a.amount * acq.exchange_ratio(s.currency_type, f.currency_type))::NUMERIC(100,2) AS amount
2364 FROM acq.fund_allocation a
2365 JOIN acq.fund f ON (a.fund = f.id)
2366 JOIN acq.funding_source s ON (a.funding_source = s.id)
2369 CREATE OR REPLACE VIEW acq.fund_debit_total AS
2370 SELECT fund.id AS fund,
2371 sum(COALESCE(fund_debit.amount, 0::numeric)) AS amount
2373 LEFT JOIN acq.fund_debit fund_debit ON fund.id = fund_debit.fund
2376 CREATE OR REPLACE VIEW acq.fund_encumbrance_total AS
2379 sum(COALESCE(fund_debit.amount, 0::numeric)) AS amount
2381 LEFT JOIN acq.fund_debit fund_debit ON fund.id = fund_debit.fund
2382 WHERE fund_debit.encumbrance GROUP BY fund.id;
2384 CREATE OR REPLACE VIEW acq.fund_spent_total AS
2385 SELECT fund.id AS fund,
2386 sum(COALESCE(fund_debit.amount, 0::numeric)) AS amount
2388 LEFT JOIN acq.fund_debit fund_debit ON fund.id = fund_debit.fund
2389 WHERE NOT fund_debit.encumbrance
2392 CREATE OR REPLACE VIEW acq.fund_combined_balance AS
2394 c.amount - COALESCE(d.amount, 0.0) AS amount
2395 FROM acq.fund_allocation_total c
2396 LEFT JOIN acq.fund_debit_total d USING (fund);
2398 CREATE OR REPLACE VIEW acq.fund_spent_balance AS
2400 c.amount - COALESCE(d.amount,0.0) AS amount
2401 FROM acq.fund_allocation_total c
2402 LEFT JOIN acq.fund_spent_total d USING (fund);
2404 -- For each fund: the total allocation from all sources, in the
2405 -- currency of the fund (or 0 if there are no allocations)
2407 CREATE VIEW acq.all_fund_allocation_total AS
2410 COALESCE( SUM( a.amount * acq.exchange_ratio(
2411 s.currency_type, f.currency_type))::numeric(100,2), 0 )
2415 LEFT JOIN acq.fund_allocation a
2417 LEFT JOIN acq.funding_source s
2418 ON a.funding_source = s.id
2422 -- For every fund: the total encumbrances (or 0 if none),
2423 -- in the currency of the fund.
2425 CREATE VIEW acq.all_fund_encumbrance_total AS
2428 COALESCE( encumb.amount, 0 ) AS amount
2434 sum( amount ) AS amount
2441 ON f.id = encumb.fund;
2443 -- For every fund: the total spent (or 0 if none),
2444 -- in the currency of the fund.
2446 CREATE VIEW acq.all_fund_spent_total AS
2449 COALESCE( spent.amount, 0 ) AS amount
2455 sum( amount ) AS amount
2462 ON f.id = spent.fund;
2464 -- For each fund: the amount not yet spent, in the currency
2465 -- of the fund. May include encumbrances.
2467 CREATE VIEW acq.all_fund_spent_balance AS
2470 c.amount - d.amount AS amount
2471 FROM acq.all_fund_allocation_total c
2472 LEFT JOIN acq.all_fund_spent_total d USING (fund);
2474 -- For each fund: the amount neither spent nor encumbered,
2475 -- in the currency of the fund
2477 CREATE VIEW acq.all_fund_combined_balance AS
2480 a.amount - COALESCE( c.amount, 0 ) AS amount
2482 acq.all_fund_allocation_total a
2486 SUM( amount ) AS amount
2491 ) AS c USING ( fund );
2493 CREATE TABLE acq.claim_type (
2494 id SERIAL PRIMARY KEY,
2495 org_unit INT NOT NULL REFERENCES actor.org_unit(id)
2496 DEFERRABLE INITIALLY DEFERRED,
2498 description TEXT NOT NULL,
2499 CONSTRAINT claim_type_once_per_org UNIQUE ( org_unit, code )
2502 CREATE TABLE acq.claim (
2503 id SERIAL PRIMARY KEY,
2504 type INT NOT NULL REFERENCES acq.claim_type
2505 DEFERRABLE INITIALLY DEFERRED,
2506 lineitem_detail BIGINT NOT NULL REFERENCES acq.lineitem_detail
2507 DEFERRABLE INITIALLY DEFERRED
2510 CREATE INDEX claim_lid_idx ON acq.claim( lineitem_detail );
2512 CREATE TABLE acq.claim_event (
2513 id BIGSERIAL PRIMARY KEY,
2514 type INT NOT NULL REFERENCES acq.claim_event_type
2515 DEFERRABLE INITIALLY DEFERRED,
2516 claim SERIAL NOT NULL REFERENCES acq.claim
2517 DEFERRABLE INITIALLY DEFERRED,
2518 event_date TIMESTAMPTZ NOT NULL DEFAULT now(),
2519 creator INT NOT NULL REFERENCES actor.usr
2520 DEFERRABLE INITIALLY DEFERRED,
2524 CREATE INDEX claim_event_claim_date_idx ON acq.claim_event( claim, event_date );
2526 -- And the serials version of claiming
2527 CREATE TABLE acq.serial_claim (
2528 id SERIAL PRIMARY KEY,
2529 type INT NOT NULL REFERENCES acq.claim_type
2530 DEFERRABLE INITIALLY DEFERRED,
2531 item BIGINT NOT NULL REFERENCES serial.item
2532 DEFERRABLE INITIALLY DEFERRED
2535 CREATE INDEX serial_claim_lid_idx ON acq.serial_claim( item );
2537 CREATE TABLE acq.serial_claim_event (
2538 id BIGSERIAL PRIMARY KEY,
2539 type INT NOT NULL REFERENCES acq.claim_event_type
2540 DEFERRABLE INITIALLY DEFERRED,
2541 claim SERIAL NOT NULL REFERENCES acq.serial_claim
2542 DEFERRABLE INITIALLY DEFERRED,
2543 event_date TIMESTAMPTZ NOT NULL DEFAULT now(),
2544 creator INT NOT NULL REFERENCES actor.usr
2545 DEFERRABLE INITIALLY DEFERRED,
2549 CREATE INDEX serial_claim_event_claim_date_idx ON acq.serial_claim_event( claim, event_date );
2551 CREATE OR REPLACE VIEW acq.lineitem_summary AS
2555 SELECT COUNT(lid.id)
2556 FROM acq.lineitem_detail lid
2557 WHERE lineitem = li.id
2560 SELECT COUNT(lid.id)
2561 FROM acq.lineitem_detail lid
2562 WHERE recv_time IS NOT NULL AND lineitem = li.id
2565 SELECT COUNT(lid.id)
2566 FROM acq.lineitem_detail lid
2567 JOIN acq.cancel_reason acqcr ON (acqcr.id = lid.cancel_reason)
2568 WHERE acqcr.keep_debits IS FALSE AND lineitem = li.id
2571 SELECT COUNT(lid.id)
2572 FROM acq.lineitem_detail lid
2573 JOIN acq.cancel_reason acqcr ON (acqcr.id = lid.cancel_reason)
2574 WHERE acqcr.keep_debits IS TRUE AND lineitem = li.id
2577 SELECT COUNT(lid.id)
2578 FROM acq.lineitem_detail lid
2579 JOIN acq.fund_debit debit ON (lid.fund_debit = debit.id)
2580 WHERE NOT debit.encumbrance AND lineitem = li.id
2583 SELECT COUNT(DISTINCT(lid.id))
2584 FROM acq.lineitem_detail lid
2585 JOIN acq.claim claim ON (claim.lineitem_detail = lid.id)
2586 WHERE lineitem = li.id
2589 SELECT (COUNT(lid.id) * li.estimated_unit_price)::NUMERIC(8,2)
2590 FROM acq.lineitem_detail lid
2591 WHERE lid.cancel_reason IS NULL AND lineitem = li.id
2592 ) AS estimated_amount,
2594 SELECT SUM(debit.amount)::NUMERIC(8,2)
2595 FROM acq.lineitem_detail lid
2596 JOIN acq.fund_debit debit ON (lid.fund_debit = debit.id)
2597 WHERE debit.encumbrance AND lineitem = li.id
2598 ) AS encumbrance_amount,
2600 SELECT SUM(debit.amount)::NUMERIC(8,2)
2601 FROM acq.lineitem_detail lid
2602 JOIN acq.fund_debit debit ON (lid.fund_debit = debit.id)
2603 WHERE NOT debit.encumbrance AND lineitem = li.id
2606 FROM acq.lineitem AS li;
2609 CREATE VIEW acq.li_state_label AS
2612 ('new', oils_i18n_gettext('new', 'New', 'jubstlbl', 'label')),
2613 ('selector-ready', oils_i18n_gettext('selector-ready', 'Selector-Ready', 'jubstlbl', 'label')),
2614 ('order-ready', oils_i18n_gettext('order-ready', 'Order-Ready', 'jubstlbl', 'label')),
2615 ('approved', oils_i18n_gettext('approved', 'Approved', 'jubstlbl', 'label')),
2616 ('pending-order', oils_i18n_gettext('pending-order', 'Pending-Order', 'jubstlbl', 'label')),
2617 ('on-order', oils_i18n_gettext('on-order', 'On-Order', 'jubstlbl', 'label')),
2618 ('received', oils_i18n_gettext('received', 'Received', 'jubstlbl', 'label')),
2619 ('cancelled', oils_i18n_gettext('cancelled', 'Cancelled', 'jubstlbl', 'label'))
2622 CREATE VIEW acq.po_state_label AS
2625 ('new', oils_i18n_gettext('new', 'New', 'acqpostlbl', 'label')),
2626 ('pending', oils_i18n_gettext('pending', 'Pending', 'acqpostlbl', 'label')),
2627 ('on-order', oils_i18n_gettext('on-order', 'On-Order', 'acqpostlbl', 'label')),
2628 ('received', oils_i18n_gettext('received', 'Received', 'acqpostlbl', 'label')),
2629 ('cancelled', oils_i18n_gettext('cancelled', 'Cancelled', 'acqpostlbl', 'label'))