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 CONSTRAINT funding_source_code_once_per_owner UNIQUE (code,owner),
160 CONSTRAINT funding_source_name_once_per_owner UNIQUE (name,owner)
163 CREATE TABLE acq.funding_source_credit (
164 id SERIAL PRIMARY KEY,
165 funding_source INT NOT NULL REFERENCES acq.funding_source (id) DEFERRABLE INITIALLY DEFERRED,
166 amount NUMERIC NOT NULL,
168 deadline_date TIMESTAMPTZ,
169 effective_date TIMESTAMPTZ NOT NULL default now()
172 CREATE VIEW acq.ordered_funding_source_credit AS
174 CASE WHEN deadline_date IS NULL THEN
178 END AS sort_priority,
179 CASE WHEN deadline_date IS NULL THEN
189 acq.funding_source_credit;
191 COMMENT ON VIEW acq.ordered_funding_source_credit IS $$
192 The acq.ordered_funding_source_credit view is a prioritized
193 ordering of funding source credits. When ordered by the first
194 three columns, this view defines the order in which the various
195 credits are to be tapped for spending, subject to the allocations
196 in the acq.fund_allocation table.
198 The first column reflects the principle that we should spend
199 money with deadlines before spending money without deadlines.
201 The second column reflects the principle that we should spend the
202 oldest money first. For money with deadlines, that means that we
203 spend first from the credit with the earliest deadline. For
204 money without deadlines, we spend first from the credit with the
205 earliest effective date.
207 The third column is a tie breaker to ensure a consistent
211 CREATE TABLE acq.fund (
212 id SERIAL PRIMARY KEY,
213 org INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
215 year INT NOT NULL DEFAULT EXTRACT( YEAR FROM NOW() ),
216 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
218 rollover BOOL NOT NULL DEFAULT FALSE,
219 propagate BOOL NOT NULL DEFAULT TRUE,
220 active BOOL NOT NULL DEFAULT TRUE,
221 balance_warning_percent INT,
222 balance_stop_percent INT,
223 CONSTRAINT name_once_per_org_year UNIQUE (org,name,year),
224 CONSTRAINT code_once_per_org_year UNIQUE (org, code, year),
225 CONSTRAINT acq_fund_rollover_implies_propagate CHECK ( propagate OR NOT rollover )
228 CREATE TABLE acq.fund_debit (
229 id SERIAL PRIMARY KEY,
230 fund INT NOT NULL REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
231 origin_amount NUMERIC NOT NULL, -- pre-exchange-rate amount
232 origin_currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
233 amount NUMERIC NOT NULL,
234 encumbrance BOOL NOT NULL DEFAULT TRUE,
235 debit_type TEXT NOT NULL,
236 xfer_destination INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
237 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
240 CREATE TABLE acq.fund_allocation (
241 id SERIAL PRIMARY KEY,
242 funding_source INT NOT NULL REFERENCES acq.funding_source (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
243 fund INT NOT NULL REFERENCES acq.fund (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
244 amount NUMERIC NOT NULL,
245 allocator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
247 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
249 CREATE INDEX fund_alloc_allocator_idx ON acq.fund_allocation ( allocator );
251 CREATE TABLE acq.fund_allocation_percent
253 id SERIAL PRIMARY KEY,
254 funding_source INT NOT NULL REFERENCES acq.funding_source
255 DEFERRABLE INITIALLY DEFERRED,
256 org INT NOT NULL REFERENCES actor.org_unit
257 DEFERRABLE INITIALLY DEFERRED,
259 percent NUMERIC NOT NULL,
260 allocator INTEGER NOT NULL REFERENCES actor.usr
261 DEFERRABLE INITIALLY DEFERRED,
263 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
264 CONSTRAINT logical_key UNIQUE( funding_source, org, fund_code ),
265 CONSTRAINT percentage_range CHECK( percent >= 0 AND percent <= 100 )
268 -- Trigger function to validate combination of org_unit and fund_code
270 CREATE OR REPLACE FUNCTION acq.fund_alloc_percent_val()
271 RETURNS TRIGGER AS $$
286 AND code = NEW.fund_code
292 RAISE EXCEPTION 'No fund exists for org % and code %', NEW.org, NEW.fund_code;
297 CREATE TRIGGER acq_fund_alloc_percent_val_trig
298 BEFORE INSERT OR UPDATE ON acq.fund_allocation_percent
299 FOR EACH ROW EXECUTE PROCEDURE acq.fund_alloc_percent_val();
301 -- To do: trigger to verify that percentages don't add up to more than 100
303 CREATE OR REPLACE FUNCTION acq.fap_limit_100()
304 RETURNS TRIGGER AS $$
307 total_percent numeric;
315 acq.fund_allocation_percent AS fap
317 fap.funding_source = NEW.funding_source;
319 IF total_percent > 100 THEN
320 RAISE EXCEPTION 'Total percentages exceed 100 for funding_source %',
328 CREATE TRIGGER acqfap_limit_100_trig
329 AFTER INSERT OR UPDATE ON acq.fund_allocation_percent
330 FOR EACH ROW EXECUTE PROCEDURE acq.fap_limit_100();
332 CREATE TABLE acq.picklist (
333 id SERIAL PRIMARY KEY,
334 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
335 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
336 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
337 org_unit INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
339 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
340 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
341 CONSTRAINT name_once_per_owner UNIQUE (name,owner)
343 CREATE INDEX acq_picklist_owner_idx ON acq.picklist ( owner );
344 CREATE INDEX acq_picklist_creator_idx ON acq.picklist ( creator );
345 CREATE INDEX acq_picklist_editor_idx ON acq.picklist ( editor );
347 CREATE TABLE acq.cancel_reason (
348 id SERIAL PRIMARY KEY,
349 org_unit INTEGER NOT NULL REFERENCES actor.org_unit( id )
350 DEFERRABLE INITIALLY DEFERRED,
352 description TEXT NOT NULL,
353 keep_debits BOOL NOT NULL DEFAULT FALSE,
354 CONSTRAINT acq_cancel_reason_one_per_org_unit UNIQUE( org_unit, label )
357 -- Reserve ids 1-999 for stock reasons
358 -- Reserve ids 1000-1999 for EDI reasons
359 -- 2000+ are available for staff to create
361 SELECT SETVAL('acq.cancel_reason_id_seq'::TEXT, 2000);
363 DROP TRIGGER IF EXISTS acq_no_deleted_reserved_cancel_reasons ON acq.cancel_reason;
365 CREATE TRIGGER acq_no_deleted_reserved_cancel_reasons BEFORE DELETE ON acq.cancel_reason
366 FOR EACH ROW EXECUTE PROCEDURE evergreen.protect_reserved_rows_from_delete(2000);
368 CREATE TABLE acq.purchase_order (
369 id SERIAL PRIMARY KEY,
370 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
371 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
372 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
373 ordering_agency INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
374 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
375 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
376 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
377 state TEXT NOT NULL DEFAULT 'new',
378 order_date TIMESTAMP WITH TIME ZONE,
380 cancel_reason INT REFERENCES acq.cancel_reason( id )
381 DEFERRABLE INITIALLY DEFERRED,
382 prepayment_required BOOLEAN NOT NULL DEFAULT FALSE,
383 CONSTRAINT valid_po_state CHECK (state IN ('new','pending','on-order','received','cancelled'))
385 CREATE INDEX po_owner_idx ON acq.purchase_order (owner);
386 CREATE INDEX po_provider_idx ON acq.purchase_order (provider);
387 CREATE INDEX po_state_idx ON acq.purchase_order (state);
388 CREATE INDEX po_creator_idx ON acq.purchase_order ( creator );
389 CREATE INDEX po_editor_idx ON acq.purchase_order ( editor );
390 CREATE INDEX acq_po_org_name_order_date_idx ON acq.purchase_order( ordering_agency, name, order_date );
392 -- The name should default to the id, as text. We can't reference a column
393 -- in a DEFAULT clause, so we use a trigger:
395 CREATE OR REPLACE FUNCTION acq.purchase_order_name_default () RETURNS TRIGGER
398 IF NEW.name IS NULL THEN
399 NEW.name := NEW.id::TEXT;
406 CREATE TRIGGER po_name_default_trg
407 BEFORE INSERT OR UPDATE ON acq.purchase_order
408 FOR EACH ROW EXECUTE PROCEDURE acq.purchase_order_name_default ();
410 -- The order name should be unique for a given ordering agency on a given order date
411 -- (truncated to midnight), but only where the order_date is not NULL. Conceptually
412 -- this rule requires a check constraint with a subquery. However you can't have a
413 -- subquery in a CHECK constraint, so we fake it with a trigger.
415 CREATE OR REPLACE FUNCTION acq.po_org_name_date_unique () RETURNS TRIGGER
421 -- If order_date is not null, then make sure we don't have a collision
422 -- on order_date (truncated to day), org, and name
424 IF NEW.order_date IS NULL THEN
428 -- In the WHERE clause, we compare the order_dates without regard to time of day.
429 -- We use a pair of inequalities instead of comparing truncated dates so that the
430 -- query can do an indexed range scan.
432 SELECT 1 INTO collision
433 FROM acq.purchase_order
435 ordering_agency = NEW.ordering_agency
437 AND order_date >= date_trunc( 'day', NEW.order_date )
438 AND order_date < date_trunc( 'day', NEW.order_date ) + '1 day'::INTERVAL
441 IF collision IS NULL THEN
442 -- okay, no collision
445 -- collision; nip it in the bud
446 RAISE EXCEPTION 'Colliding purchase orders: ordering_agency %, date %, name ''%''',
447 NEW.ordering_agency, NEW.order_date, NEW.name;
452 CREATE TRIGGER po_org_name_date_unique_trg
453 BEFORE INSERT OR UPDATE ON acq.purchase_order
454 FOR EACH ROW EXECUTE PROCEDURE acq.po_org_name_date_unique ();
456 CREATE TABLE acq.po_note (
457 id SERIAL PRIMARY KEY,
458 purchase_order INT NOT NULL REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
459 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
460 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
461 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
462 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
464 vendor_public BOOLEAN NOT NULL DEFAULT FALSE
466 CREATE INDEX po_note_po_idx ON acq.po_note (purchase_order);
467 CREATE INDEX acq_po_note_creator_idx ON acq.po_note ( creator );
468 CREATE INDEX acq_po_note_editor_idx ON acq.po_note ( editor );
470 CREATE TABLE acq.lineitem (
471 id BIGSERIAL PRIMARY KEY,
472 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
473 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
474 selector INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
475 provider INT REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
476 purchase_order INT REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
477 picklist INT REFERENCES acq.picklist (id) DEFERRABLE INITIALLY DEFERRED,
478 expected_recv_time TIMESTAMP WITH TIME ZONE,
479 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
480 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
482 eg_bib_id BIGINT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
484 state TEXT NOT NULL DEFAULT 'new',
485 cancel_reason INT REFERENCES acq.cancel_reason( id )
486 DEFERRABLE INITIALLY DEFERRED,
487 estimated_unit_price NUMERIC,
488 claim_policy INT REFERENCES acq.claim_policy
489 DEFERRABLE INITIALLY DEFERRED,
490 queued_record BIGINT REFERENCES vandelay.queued_bib_record (id)
491 ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
492 CONSTRAINT picklist_or_po CHECK (picklist IS NOT NULL OR purchase_order IS NOT NULL)
494 CREATE INDEX li_po_idx ON acq.lineitem (purchase_order);
495 CREATE INDEX li_pl_idx ON acq.lineitem (picklist);
496 CREATE INDEX li_creator_idx ON acq.lineitem ( creator );
497 CREATE INDEX li_editor_idx ON acq.lineitem ( editor );
498 CREATE INDEX li_selector_idx ON acq.lineitem ( selector );
499 CREATE INDEX li_queued_record_idx ON acq.lineitem ( queued_record );
501 CREATE TABLE acq.lineitem_alert_text (
502 id SERIAL PRIMARY KEY,
505 owning_lib INT NOT NULL
506 REFERENCES actor.org_unit(id)
507 DEFERRABLE INITIALLY DEFERRED,
508 CONSTRAINT alert_one_code_per_org UNIQUE (code, owning_lib)
511 CREATE TABLE acq.lineitem_note (
512 id SERIAL PRIMARY KEY,
513 lineitem INT NOT NULL REFERENCES acq.lineitem (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
514 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
515 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
516 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
517 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
519 alert_text INT REFERENCES acq.lineitem_alert_text(id)
520 DEFERRABLE INITIALLY DEFERRED,
521 vendor_public BOOLEAN NOT NULL DEFAULT FALSE
523 CREATE INDEX li_note_li_idx ON acq.lineitem_note (lineitem);
524 CREATE INDEX li_note_creator_idx ON acq.lineitem_note ( creator );
525 CREATE INDEX li_note_editor_idx ON acq.lineitem_note ( editor );
527 CREATE TABLE acq.lineitem_detail (
528 id BIGSERIAL PRIMARY KEY,
529 lineitem INT NOT NULL REFERENCES acq.lineitem (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
530 fund INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
531 fund_debit INT REFERENCES acq.fund_debit (id) DEFERRABLE INITIALLY DEFERRED,
532 eg_copy_id BIGINT, -- REFERENCES asset.copy (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED, -- XXX could be an serial.issuance
536 collection_code TEXT,
537 circ_modifier TEXT REFERENCES config.circ_modifier (code) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
538 owning_lib INT REFERENCES actor.org_unit (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
539 location INT REFERENCES asset.copy_location (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
540 recv_time TIMESTAMP WITH TIME ZONE,
541 receiver INT REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
542 cancel_reason INT REFERENCES acq.cancel_reason( id ) DEFERRABLE INITIALLY DEFERRED
545 CREATE INDEX li_detail_li_idx ON acq.lineitem_detail (lineitem);
546 CREATE INDEX lineitem_detail_fund_debit_idx ON acq.lineitem_detail (fund_debit);
548 CREATE TABLE acq.lineitem_attr_definition (
549 id BIGSERIAL PRIMARY KEY,
551 description TEXT NOT NULL,
552 remove TEXT NOT NULL DEFAULT '',
553 ident BOOL NOT NULL DEFAULT FALSE
556 CREATE TABLE acq.lineitem_marc_attr_definition (
557 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
559 ) INHERITS (acq.lineitem_attr_definition);
561 CREATE TABLE acq.lineitem_provider_attr_definition (
562 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
564 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED
565 ) INHERITS (acq.lineitem_attr_definition);
567 CREATE TABLE acq.lineitem_generated_attr_definition (
568 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
570 ) INHERITS (acq.lineitem_attr_definition);
572 CREATE TABLE acq.lineitem_usr_attr_definition (
573 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
574 usr INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED
575 ) INHERITS (acq.lineitem_attr_definition);
576 CREATE INDEX li_usr_attr_def_usr_idx ON acq.lineitem_usr_attr_definition ( usr );
578 CREATE TABLE acq.lineitem_local_attr_definition (
579 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq')
580 ) INHERITS (acq.lineitem_attr_definition);
582 CREATE TABLE acq.lineitem_attr (
583 id BIGSERIAL PRIMARY KEY,
584 definition BIGINT NOT NULL,
585 lineitem BIGINT NOT NULL REFERENCES acq.lineitem (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
586 attr_type TEXT NOT NULL,
587 attr_name TEXT NOT NULL,
588 attr_value TEXT NOT NULL,
589 order_ident BOOLEAN NOT NULL DEFAULT FALSE
592 CREATE INDEX li_attr_li_idx ON acq.lineitem_attr (lineitem);
593 CREATE INDEX li_attr_value_idx ON acq.lineitem_attr (attr_value);
594 CREATE INDEX li_attr_definition_idx ON acq.lineitem_attr (definition);
600 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('title','Title of work','//*[@tag="245"]/*[contains("abcmnopr",@code)]');
601 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)]');
602 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('language','Language of work','//*[@tag="240"]/*[@code="l"][1]');
603 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pagination','Pagination','//*[@tag="300"]/*[@code="a"][1]');
604 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('isbn','ISBN','//*[@tag="020"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
605 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('issn','ISSN','//*[@tag="022"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
606 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('upc', 'UPC', '//*[@tag="024" and @ind1="1"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
607 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('price','Price','//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
608 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('identifier','Identifier','//*[@tag="001"]');
609 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('publisher','Publisher','//*[@tag="260"]/*[@code="b"][1]');
610 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pubdate','Publication Date','//*[@tag="260"]/*[@code="c"][1]');
611 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('edition','Edition','//*[@tag="250"]/*[@code="a"][1]');
613 INSERT INTO acq.lineitem_local_attr_definition ( code, description ) VALUES ('estimated_price', 'Estimated Price');
616 CREATE TABLE acq.distribution_formula (
617 id SERIAL PRIMARY KEY,
619 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
621 skip_count INT NOT NULL DEFAULT 0,
622 CONSTRAINT acqdf_name_once_per_owner UNIQUE (name, owner)
625 CREATE TABLE acq.distribution_formula_entry (
626 id SERIAL PRIMARY KEY,
627 formula INTEGER NOT NULL REFERENCES acq.distribution_formula(id)
629 DEFERRABLE INITIALLY DEFERRED,
630 position INTEGER NOT NULL,
631 item_count INTEGER NOT NULL,
632 owning_lib INTEGER REFERENCES actor.org_unit(id)
633 DEFERRABLE INITIALLY DEFERRED,
634 location INTEGER REFERENCES asset.copy_location(id),
635 fund INTEGER REFERENCES acq.fund (id),
636 circ_modifier TEXT REFERENCES config.circ_modifier (code),
637 collection_code TEXT,
638 CONSTRAINT acqdfe_lib_once_per_formula UNIQUE( formula, position ),
639 CONSTRAINT acqdfe_must_be_somewhere
640 CHECK( owning_lib IS NOT NULL OR location IS NOT NULL )
643 CREATE TABLE acq.distribution_formula_application (
644 id BIGSERIAL PRIMARY KEY,
645 creator INT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED,
646 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
648 REFERENCES acq.distribution_formula(id) DEFERRABLE INITIALLY DEFERRED,
649 lineitem INT NOT NULL
650 REFERENCES acq.lineitem(id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
653 CREATE INDEX acqdfa_df_idx
654 ON acq.distribution_formula_application(formula);
655 CREATE INDEX acqdfa_li_idx
656 ON acq.distribution_formula_application(lineitem);
657 CREATE INDEX acqdfa_creator_idx
658 ON acq.distribution_formula_application(creator);
660 CREATE TABLE acq.fund_tag (
661 id SERIAL PRIMARY KEY,
663 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
665 CONSTRAINT acqft_tag_once_per_owner UNIQUE (name, owner)
668 CREATE TABLE acq.fund_tag_map (
669 id SERIAL PRIMARY KEY,
670 fund INTEGER NOT NULL REFERENCES acq.fund(id)
671 DEFERRABLE INITIALLY DEFERRED,
672 tag INTEGER REFERENCES acq.fund_tag(id)
674 DEFERRABLE INITIALLY DEFERRED,
675 CONSTRAINT acqftm_fund_once_per_tag UNIQUE( fund, tag )
678 CREATE TABLE acq.fund_transfer (
679 id SERIAL PRIMARY KEY,
680 src_fund INT NOT NULL REFERENCES acq.fund( id )
681 DEFERRABLE INITIALLY DEFERRED,
682 src_amount NUMERIC NOT NULL,
683 dest_fund INT REFERENCES acq.fund( id )
684 DEFERRABLE INITIALLY DEFERRED,
686 transfer_time TIMESTAMPTZ NOT NULL DEFAULT now(),
687 transfer_user INT NOT NULL REFERENCES actor.usr( id )
688 DEFERRABLE INITIALLY DEFERRED,
690 funding_source_credit INT NOT NULL REFERENCES acq.funding_source_credit( id )
691 DEFERRABLE INITIALLY DEFERRED
694 CREATE INDEX acqftr_usr_idx
695 ON acq.fund_transfer( transfer_user );
697 COMMENT ON TABLE acq.fund_transfer IS $$
699 Each row represents the transfer of money from a source fund
700 to a destination fund. There should be corresponding entries
701 in acq.fund_allocation. The purpose of acq.fund_transfer is
702 to record how much money moved from which fund to which other
705 The presence of two amount fields, rather than one, reflects
706 the possibility that the two funds are denominated in different
707 currencies. If they use the same currency type, the two
708 amounts should be the same.
711 CREATE TABLE acq.fiscal_calendar (
712 id SERIAL PRIMARY KEY,
716 -- Create a default calendar (though we don't specify its contents).
717 -- Create a foreign key in actor.org_unit, initially pointing to
718 -- the default calendar.
720 INSERT INTO acq.fiscal_calendar (
727 ALTER TABLE actor.org_unit ADD FOREIGN KEY
728 (fiscal_calendar) REFERENCES acq.fiscal_calendar( id )
729 DEFERRABLE INITIALLY DEFERRED;
731 CREATE TABLE acq.fiscal_year (
732 id SERIAL PRIMARY KEY,
733 calendar INT NOT NULL
734 REFERENCES acq.fiscal_calendar
736 DEFERRABLE INITIALLY DEFERRED,
738 year_begin TIMESTAMPTZ NOT NULL,
739 year_end TIMESTAMPTZ NOT NULL,
740 CONSTRAINT acq_fy_logical_key UNIQUE ( calendar, year ),
741 CONSTRAINT acq_fy_physical_key UNIQUE ( calendar, year_begin )
744 CREATE TABLE acq.edi_attr (
745 key TEXT PRIMARY KEY,
746 label TEXT NOT NULL UNIQUE
749 CREATE TABLE acq.edi_attr_set (
750 id SERIAL PRIMARY KEY,
751 label TEXT NOT NULL UNIQUE
754 CREATE TABLE acq.edi_attr_set_map (
755 id SERIAL PRIMARY KEY,
756 attr_set INTEGER NOT NULL REFERENCES acq.edi_attr_set(id)
757 ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
758 attr TEXT NOT NULL REFERENCES acq.edi_attr(key)
759 ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
760 CONSTRAINT edi_attr_set_map_attr_once UNIQUE (attr_set, attr)
763 CREATE TABLE acq.edi_account ( -- similar tables can extend remote_account for other parts of EG
764 provider INT NOT NULL REFERENCES acq.provider (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
765 in_dir TEXT, -- incoming messages dir (probably different than config.remote_account.path, the outgoing dir)
768 attr_set INTEGER REFERENCES acq.edi_attr_set(id), -- NULL OK
769 use_attrs BOOLEAN NOT NULL DEFAULT FALSE
770 ) INHERITS (config.remote_account);
772 -- We need a UNIQUE constraint here also, to support the FK from acq.provider.edi_default
773 ALTER TABLE acq.edi_account ADD PRIMARY KEY (id);
775 CREATE TABLE acq.edi_message (
776 id SERIAL PRIMARY KEY,
777 account INTEGER REFERENCES acq.edi_account(id)
778 DEFERRABLE INITIALLY DEFERRED,
780 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
781 translate_time TIMESTAMPTZ,
782 process_time TIMESTAMPTZ,
783 error_time TIMESTAMPTZ,
784 status TEXT NOT NULL DEFAULT 'new'
785 CONSTRAINT status_value CHECK
787 'new', -- needs to be translated
788 'translated', -- needs to be processed
789 'trans_error', -- error in translation step
790 'processed', -- needs to have remote_file deleted
791 'proc_error', -- error in processing step
792 'delete_error', -- error in deletion
793 'retry', -- need to retry
799 purchase_order INT REFERENCES acq.purchase_order
800 DEFERRABLE INITIALLY DEFERRED,
801 message_type TEXT NOT NULL CONSTRAINT valid_message_type CHECK
810 CREATE INDEX edi_message_account_status_idx ON acq.edi_message (account,status);
811 CREATE INDEX edi_message_po_idx ON acq.edi_message (purchase_order);
812 CREATE INDEX edi_message_remote_file_idx ON acq.edi_message (evergreen.lowercase(remote_file));
814 -- Note below that the primary key is NOT a SERIAL type. We will periodically truncate and rebuild
815 -- the table, assigning ids programmatically instead of using a sequence.
816 CREATE TABLE acq.debit_attribution (
817 id INT NOT NULL PRIMARY KEY,
818 fund_debit INT NOT NULL
819 REFERENCES acq.fund_debit
820 DEFERRABLE INITIALLY DEFERRED,
821 debit_amount NUMERIC NOT NULL,
822 funding_source_credit INT REFERENCES acq.funding_source_credit
823 DEFERRABLE INITIALLY DEFERRED,
824 credit_amount NUMERIC
827 CREATE INDEX acq_attribution_debit_idx
828 ON acq.debit_attribution( fund_debit );
830 CREATE INDEX acq_attribution_credit_idx
831 ON acq.debit_attribution( funding_source_credit );
835 CREATE TABLE acq.invoice_method (
836 code TEXT PRIMARY KEY,
837 name TEXT NOT NULL -- i18n-ize
840 CREATE TABLE acq.invoice_payment_method (
841 code TEXT PRIMARY KEY,
842 name TEXT NOT NULL -- i18n-ize
845 CREATE TABLE acq.invoice (
846 id SERIAL PRIMARY KEY,
847 receiver INT NOT NULL REFERENCES actor.org_unit (id),
848 provider INT NOT NULL REFERENCES acq.provider (id),
849 shipper INT NOT NULL REFERENCES acq.provider (id),
850 recv_date TIMESTAMPTZ NOT NULL DEFAULT NOW(),
851 recv_method TEXT NOT NULL REFERENCES acq.invoice_method (code) DEFAULT 'EDI',
852 inv_type TEXT, -- A "type" field is desired, but no idea what goes here
853 inv_ident TEXT NOT NULL, -- vendor-supplied invoice id/number
855 payment_method TEXT REFERENCES acq.invoice_payment_method (code)
856 DEFERRABLE INITIALLY DEFERRED,
858 close_date TIMESTAMPTZ,
859 closed_by INTEGER REFERENCES actor.usr (id)
860 DEFERRABLE INITIALLY DEFERRED,
862 CONSTRAINT inv_ident_once_per_provider UNIQUE(provider, inv_ident)
865 CREATE TABLE acq.invoice_entry (
866 id SERIAL PRIMARY KEY,
867 invoice INT NOT NULL REFERENCES acq.invoice (id) ON DELETE CASCADE,
868 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
869 lineitem INT REFERENCES acq.lineitem (id) ON UPDATE CASCADE ON DELETE SET NULL,
870 inv_item_count INT NOT NULL, -- How many acqlids did they say they sent
871 phys_item_count INT, -- and how many did staff count
873 billed_per_item BOOL,
874 cost_billed NUMERIC(8,2),
875 actual_cost NUMERIC(8,2),
876 amount_paid NUMERIC (8,2)
879 CREATE INDEX ie_inv_idx on acq.invoice_entry (invoice);
880 CREATE INDEX ie_po_idx on acq.invoice_entry (purchase_order);
881 CREATE INDEX ie_li_idx on acq.invoice_entry (lineitem);
883 ALTER TABLE acq.fund_debit
884 ADD COLUMN invoice_entry INTEGER
885 REFERENCES acq.invoice_entry (id)
888 CREATE INDEX fund_debit_invoice_entry_idx ON acq.fund_debit (invoice_entry);
890 CREATE TABLE acq.invoice_item_type (
891 code TEXT PRIMARY KEY,
892 name TEXT NOT NULL, -- i18n-ize
893 prorate BOOL NOT NULL DEFAULT FALSE,
894 blanket BOOL NOT NULL DEFAULT FALSE,
895 CONSTRAINT aiit_not_blanket_and_prorate
896 CHECK (blanket IS FALSE OR prorate IS FALSE)
899 CREATE TABLE acq.po_item (
900 id SERIAL PRIMARY KEY,
901 purchase_order INT REFERENCES acq.purchase_order (id)
902 ON UPDATE CASCADE ON DELETE SET NULL
903 DEFERRABLE INITIALLY DEFERRED,
904 fund_debit INT REFERENCES acq.fund_debit (id)
905 DEFERRABLE INITIALLY DEFERRED,
906 inv_item_type TEXT NOT NULL
907 REFERENCES acq.invoice_item_type (code)
908 DEFERRABLE INITIALLY DEFERRED,
912 estimated_cost NUMERIC(8,2),
913 fund INT REFERENCES acq.fund (id)
914 DEFERRABLE INITIALLY DEFERRED,
918 CREATE INDEX poi_po_idx ON acq.po_item (purchase_order);
920 CREATE TABLE acq.invoice_item ( -- for invoice-only debits: taxes/fees/non-bib items/etc
921 id SERIAL PRIMARY KEY,
922 invoice INT NOT NULL REFERENCES acq.invoice (id) ON UPDATE CASCADE ON DELETE CASCADE,
923 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
924 fund_debit INT REFERENCES acq.fund_debit (id),
925 inv_item_type TEXT NOT NULL REFERENCES acq.invoice_item_type (code),
929 cost_billed NUMERIC(8,2),
930 actual_cost NUMERIC(8,2),
931 fund INT REFERENCES acq.fund (id)
932 DEFERRABLE INITIALLY DEFERRED,
933 amount_paid NUMERIC (8,2),
934 po_item INT REFERENCES acq.po_item (id)
935 DEFERRABLE INITIALLY DEFERRED,
939 CREATE INDEX ii_inv_idx on acq.invoice_item (invoice);
940 CREATE INDEX ii_po_idx on acq.invoice_item (purchase_order);
941 CREATE INDEX ii_poi_idx on acq.invoice_item (po_item);
944 CREATE TABLE acq.user_request_type (
945 id SERIAL PRIMARY KEY,
946 label TEXT NOT NULL UNIQUE -- i18n-ize
949 CREATE TABLE acq.user_request_status_type (
950 id SERIAL PRIMARY KEY
954 INSERT INTO acq.user_request_status_type (id,label) VALUES
955 (0,oils_i18n_gettext(0,'Error','aurst','label'))
956 ,(1,oils_i18n_gettext(1,'New','aurst','label'))
957 ,(2,oils_i18n_gettext(2,'Pending','aurst','label'))
958 ,(3,oils_i18n_gettext(3,'Ordered, Hold Not Placed','aurst','label'))
959 ,(4,oils_i18n_gettext(4,'Ordered, Hold Placed','aurst','label'))
960 ,(5,oils_i18n_gettext(5,'Received','aurst','label'))
961 ,(6,oils_i18n_gettext(6,'Fulfilled','aurst','label'))
962 ,(7,oils_i18n_gettext(7,'Canceled','aurst','label'))
965 SELECT SETVAL('acq.user_request_status_type_id_seq'::TEXT, 100);
967 CREATE TABLE acq.user_request (
968 id SERIAL PRIMARY KEY,
969 usr INT NOT NULL REFERENCES actor.usr (id), -- requesting user
970 hold BOOL NOT NULL DEFAULT TRUE,
972 pickup_lib INT NOT NULL REFERENCES actor.org_unit (id), -- pickup lib
973 holdable_formats TEXT, -- nullable, for use in hold creation
975 email_notify BOOL NOT NULL DEFAULT TRUE,
976 lineitem INT REFERENCES acq.lineitem (id) ON DELETE CASCADE,
977 eg_bib BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
978 request_date TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- when they requested it
979 need_before TIMESTAMPTZ, -- don't create holds after this
982 request_type INT NOT NULL REFERENCES acq.user_request_type (id),
995 cancel_reason INT REFERENCES acq.cancel_reason( id )
996 DEFERRABLE INITIALLY DEFERRED,
997 cancel_time TIMESTAMPTZ
1000 ALTER TABLE action.hold_request ADD COLUMN acq_request INT REFERENCES acq.user_request (id);
1004 CREATE TYPE acq.flat_lineitem_holding_subfield AS (lineitem int, holding int, subfield text, data text);
1005 CREATE OR REPLACE FUNCTION acq.extract_holding_attr_table (lineitem int, tag text) RETURNS SETOF acq.flat_lineitem_holding_subfield AS $$
1008 lida acq.flat_lineitem_holding_subfield%ROWTYPE;
1011 SELECT COUNT(*) INTO counter
1012 FROM oils_xpath_table(
1016 '//*[@tag="' || tag || '"]',
1018 ) as t(i int,c text);
1020 FOR i IN 1 .. counter LOOP
1023 FROM ( SELECT id,i,t,v
1024 FROM oils_xpath_table(
1028 '//*[@tag="' || tag || '"][position()=' || i || ']/*/@code|' ||
1029 '//*[@tag="' || tag || '"][position()=' || i || ']/*[@code]',
1031 ) as t(id int,t text,v text)
1040 $$ LANGUAGE PLPGSQL;
1042 CREATE TYPE acq.flat_lineitem_detail AS (lineitem int, holding int, attr text, data text);
1043 CREATE OR REPLACE FUNCTION acq.extract_provider_holding_data ( lineitem_i int ) RETURNS SETOF acq.flat_lineitem_detail AS $$
1047 lida acq.flat_lineitem_detail%ROWTYPE;
1049 SELECT provider INTO prov_i FROM acq.lineitem WHERE id = lineitem_i;
1050 IF NOT FOUND THEN RETURN; END IF;
1052 SELECT holding_tag INTO tag_t FROM acq.provider WHERE id = prov_i;
1053 IF NOT FOUND OR tag_t IS NULL THEN RETURN; END IF;
1060 FROM acq.extract_holding_attr_table( lineitem_i, tag_t ) h
1061 JOIN acq.provider_holding_subfield_map a USING (subfield)
1062 WHERE a.provider = prov_i
1069 $$ LANGUAGE PLPGSQL;
1071 -- select * from acq.extract_provider_holding_data(699);
1073 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field ( BIGINT, TEXT, TEXT) RETURNS TEXT AS $$
1074 SELECT extract_marc_field('acq.lineitem', $1, $2, $3);
1077 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field_set ( BIGINT, TEXT, TEXT) RETURNS SETOF TEXT AS $$
1078 SELECT extract_marc_field_set('acq.lineitem', $1, $2, $3);
1083 CREATE OR REPLACE FUNCTION public.extract_bib_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
1084 SELECT public.extract_marc_field('biblio.record_entry', $1, $2);
1087 CREATE OR REPLACE FUNCTION public.extract_authority_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
1088 SELECT public.extract_marc_field('authority.record_entry', $1, $2);
1092 -- INSERT INTO acq.lineitem_provider_attr_definition ( provider, code, description, xpath ) VALUES (1,'price','Price','//*[@tag="020" or @tag="022"]/*[@code="a"][1]');
1095 Suggested vendor fields:
1103 CREATE OR REPLACE FUNCTION public.ingest_acq_marc ( ) RETURNS TRIGGER AS $function$
1112 FOR adef IN SELECT *,tableoid FROM acq.lineitem_attr_definition LOOP
1114 SELECT relname::TEXT INTO atype FROM pg_class WHERE oid = adef.tableoid;
1116 IF (atype NOT IN ('lineitem_usr_attr_definition','lineitem_local_attr_definition')) THEN
1117 IF (atype = 'lineitem_provider_attr_definition') THEN
1118 SELECT provider INTO prov FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
1119 CONTINUE WHEN NEW.provider IS NULL OR prov <> NEW.provider;
1122 IF (atype = 'lineitem_provider_attr_definition') THEN
1123 SELECT xpath INTO xpath_string FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
1124 ELSIF (atype = 'lineitem_marc_attr_definition') THEN
1125 SELECT xpath INTO xpath_string FROM acq.lineitem_marc_attr_definition WHERE id = adef.id;
1126 ELSIF (atype = 'lineitem_generated_attr_definition') THEN
1127 SELECT xpath INTO xpath_string FROM acq.lineitem_generated_attr_definition WHERE id = adef.id;
1130 xpath_string := REGEXP_REPLACE(xpath_string,$re$//?text\(\)$$re$,'');
1132 IF (adef.code = 'title' OR adef.code = 'author') THEN
1133 -- title and author should not be split
1134 -- FIXME: once oils_xpath can grok XPATH 2.0 functions, we can use
1135 -- string-join in the xpath and remove this special case
1136 SELECT extract_acq_marc_field(id, xpath_string, adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
1137 IF (value IS NOT NULL AND value <> '') THEN
1138 INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
1139 VALUES (NEW.id, adef.id, atype, adef.code, value);
1144 -- each application of the regex may produce multiple values
1146 SELECT * FROM extract_acq_marc_field_set(
1147 NEW.id, xpath_string || '[' || pos || ']', adef.remove)
1150 IF (value IS NOT NULL AND value <> '') THEN
1151 INSERT INTO acq.lineitem_attr
1152 (lineitem, definition, attr_type, attr_name, attr_value)
1153 VALUES (NEW.id, adef.id, atype, adef.code, value);
1171 $function$ LANGUAGE PLPGSQL;
1173 CREATE OR REPLACE FUNCTION public.cleanup_acq_marc ( ) RETURNS TRIGGER AS $$
1175 IF TG_OP = 'UPDATE' THEN
1176 DELETE FROM acq.lineitem_attr
1177 WHERE lineitem = OLD.id AND attr_type IN ('lineitem_provider_attr_definition', 'lineitem_marc_attr_definition','lineitem_generated_attr_definition');
1180 DELETE FROM acq.lineitem_attr WHERE lineitem = OLD.id;
1184 $$ LANGUAGE PLPGSQL;
1186 CREATE TRIGGER cleanup_lineitem_trigger
1187 BEFORE UPDATE OR DELETE ON acq.lineitem
1188 FOR EACH ROW EXECUTE PROCEDURE public.cleanup_acq_marc();
1190 CREATE TRIGGER ingest_lineitem_trigger
1191 AFTER INSERT OR UPDATE ON acq.lineitem
1192 FOR EACH ROW EXECUTE PROCEDURE public.ingest_acq_marc();
1194 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( from_ex TEXT, to_ex TEXT ) RETURNS NUMERIC AS $$
1198 IF from_ex = to_ex THEN
1202 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = from_ex AND to_currency = to_ex;
1207 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = to_ex AND to_currency = from_ex;
1216 $$ LANGUAGE PLPGSQL;
1218 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( TEXT, TEXT, NUMERIC ) RETURNS NUMERIC AS $$
1219 SELECT $3 * acq.exchange_ratio($1, $2);
1222 CREATE OR REPLACE FUNCTION acq.find_bad_fy()
1224 Examine the acq.fiscal_year table, comparing successive years.
1225 Report any inconsistencies, i.e. years that overlap, have gaps
1226 between them, or are out of sequence.
1228 RETURNS SETOF RECORD AS $$
1252 ELSIF curr_year.calendar = prev_year.calendar THEN
1253 IF curr_year.year_begin > prev_year.year_end THEN
1254 -- This ugly kludge works around the fact that older
1255 -- versions of PostgreSQL don't support RETURN QUERY SELECT
1256 FOR return_rec IN SELECT
1259 'Gap between fiscal years'::TEXT
1261 RETURN NEXT return_rec;
1263 ELSIF curr_year.year_begin < prev_year.year_end THEN
1264 FOR return_rec IN SELECT
1267 'Overlapping fiscal years'::TEXT
1269 RETURN NEXT return_rec;
1271 ELSIF curr_year.year < prev_year.year THEN
1272 FOR return_rec IN SELECT
1275 'Fiscal years out of order'::TEXT
1277 RETURN NEXT return_rec;
1282 prev_year := curr_year;
1287 $$ LANGUAGE plpgsql;
1289 CREATE OR REPLACE FUNCTION acq.transfer_fund(
1291 old_amount IN NUMERIC, -- in currency of old fund
1293 new_amount IN NUMERIC, -- in currency of new fund
1295 xfer_note IN TEXT -- to be recorded in acq.fund_transfer
1296 -- ,funding_source_in IN INT -- if user wants to specify a funding source (see notes)
1297 ) RETURNS VOID AS $$
1298 /* -------------------------------------------------------------------------------
1300 Function to transfer money from one fund to another.
1302 A transfer is represented as a pair of entries in acq.fund_allocation, with a
1303 negative amount for the old (losing) fund and a positive amount for the new
1304 (gaining) fund. In some cases there may be more than one such pair of entries
1305 in order to pull the money from different funding sources, or more specifically
1306 from different funding source credits. For each such pair there is also an
1307 entry in acq.fund_transfer.
1309 Since funding_source is a non-nullable column in acq.fund_allocation, we must
1310 choose a funding source for the transferred money to come from. This choice
1311 must meet two constraints, so far as possible:
1313 1. The amount transferred from a given funding source must not exceed the
1314 amount allocated to the old fund by the funding source. To that end we
1315 compare the amount being transferred to the amount allocated.
1317 2. We shouldn't transfer money that has already been spent or encumbered, as
1318 defined by the funding attribution process. We attribute expenses to the
1319 oldest funding source credits first. In order to avoid transferring that
1320 attributed money, we reverse the priority, transferring from the newest funding
1321 source credits first. There can be no guarantee that this approach will
1322 avoid overcommitting a fund, but no other approach can do any better.
1324 In this context the age of a funding source credit is defined by the
1325 deadline_date for credits with deadline_dates, and by the effective_date for
1326 credits without deadline_dates, with the proviso that credits with deadline_dates
1327 are all considered "older" than those without.
1331 In the signature for this function, there is one last parameter commented out,
1332 named "funding_source_in". Correspondingly, the WHERE clause for the query
1333 driving the main loop has an OR clause commented out, which references the
1334 funding_source_in parameter.
1336 If these lines are uncommented, this function will allow the user optionally to
1337 restrict a fund transfer to a specified funding source. If the source
1338 parameter is left NULL, then there will be no such restriction.
1340 ------------------------------------------------------------------------------- */
1342 same_currency BOOLEAN;
1343 currency_ratio NUMERIC;
1344 old_fund_currency TEXT;
1345 old_remaining NUMERIC; -- in currency of old fund
1346 new_fund_currency TEXT;
1347 new_fund_active BOOLEAN;
1348 new_remaining NUMERIC; -- in currency of new fund
1349 curr_old_amt NUMERIC; -- in currency of old fund
1350 curr_new_amt NUMERIC; -- in currency of new fund
1351 source_addition NUMERIC; -- in currency of funding source
1352 source_deduction NUMERIC; -- in currency of funding source
1353 orig_allocated_amt NUMERIC; -- in currency of funding source
1354 allocated_amt NUMERIC; -- in currency of fund
1360 IF old_fund IS NULL THEN
1361 RAISE EXCEPTION 'acq.transfer_fund: old fund id is NULL';
1364 IF old_amount IS NULL THEN
1365 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer is NULL';
1368 -- The new fund and its amount must be both NULL or both not NULL.
1370 IF new_fund IS NOT NULL AND new_amount IS NULL THEN
1371 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer to receiving fund is NULL';
1374 IF new_fund IS NULL AND new_amount IS NOT NULL THEN
1375 RAISE EXCEPTION 'acq.transfer_fund: receiving fund is NULL, its amount is not NULL';
1378 IF user_id IS NULL THEN
1379 RAISE EXCEPTION 'acq.transfer_fund: user id is NULL';
1382 -- Initialize the amounts to be transferred, each denominated
1383 -- in the currency of its respective fund. They will be
1384 -- reduced on each iteration of the loop.
1386 old_remaining := old_amount;
1387 new_remaining := new_amount;
1389 -- RAISE NOTICE 'Transferring % in fund % to % in fund %',
1390 -- old_amount, old_fund, new_amount, new_fund;
1392 -- Get the currency types of the old and new funds.
1403 IF old_fund_currency IS NULL THEN
1404 RAISE EXCEPTION 'acq.transfer_fund: old fund id % is not defined', old_fund;
1407 IF new_fund IS NOT NULL THEN
1419 IF new_fund_currency IS NULL THEN
1420 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is not defined', new_fund;
1421 ELSIF NOT new_fund_active THEN
1423 -- No point in putting money into a fund from whence you can't spend it
1425 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is inactive', new_fund;
1428 IF new_amount = old_amount THEN
1429 same_currency := true;
1430 currency_ratio := 1;
1433 -- We'll have to translate currency between funds. We presume that
1434 -- the calling code has already applied an appropriate exchange rate,
1435 -- so we'll apply the same conversion to each sub-transfer.
1437 same_currency := false;
1438 currency_ratio := new_amount / old_amount;
1442 -- Identify the funding source(s) from which we want to transfer the money.
1443 -- The principle is that we want to transfer the newest money first, because
1444 -- we spend the oldest money first. The priority for spending is defined
1445 -- by a sort of the view acq.ordered_funding_source_credit.
1450 ofsc.funding_source,
1452 ofsc.amount * acq.exchange_ratio( fs.currency_type, old_fund_currency )
1456 acq.ordered_funding_source_credit AS ofsc,
1457 acq.funding_source fs
1459 ofsc.funding_source = fs.id
1460 and ofsc.funding_source IN
1462 SELECT funding_source
1463 FROM acq.fund_allocation
1464 WHERE fund = old_fund
1468 -- ofsc.funding_source = funding_source_in
1469 -- OR funding_source_in IS NULL
1472 ofsc.sort_priority desc,
1473 ofsc.sort_date desc,
1477 -- Determine how much money the old fund got from this funding source,
1478 -- denominated in the currency types of the source and of the fund.
1479 -- This result may reflect transfers from previous iterations.
1482 COALESCE( sum( amount ), 0 ),
1483 COALESCE( sum( amount )
1484 * acq.exchange_ratio( source.currency_type, old_fund_currency ), 0 )
1486 orig_allocated_amt, -- in currency of the source
1487 allocated_amt -- in currency of the old fund
1492 and funding_source = source.funding_source;
1494 -- Determine how much to transfer from this credit, in the currency
1495 -- of the fund. Begin with the amount remaining to be attributed:
1497 curr_old_amt := old_remaining;
1499 -- Can't attribute more than was allocated from the fund:
1501 IF curr_old_amt > allocated_amt THEN
1502 curr_old_amt := allocated_amt;
1505 -- Can't attribute more than the amount of the current credit:
1507 IF curr_old_amt > source.converted_amt THEN
1508 curr_old_amt := source.converted_amt;
1511 curr_old_amt := trunc( curr_old_amt, 2 );
1513 old_remaining := old_remaining - curr_old_amt;
1515 -- Determine the amount to be deducted, if any,
1516 -- from the old allocation.
1518 IF old_remaining > 0 THEN
1520 -- In this case we're using the whole allocation, so use that
1521 -- amount directly instead of applying a currency translation
1522 -- and thereby inviting round-off errors.
1524 source_deduction := - curr_old_amt;
1526 source_deduction := trunc(
1527 ( - curr_old_amt ) *
1528 acq.exchange_ratio( old_fund_currency, source.currency_type ),
1532 IF source_deduction <> 0 THEN
1534 -- Insert negative allocation for old fund in fund_allocation,
1535 -- converted into the currency of the funding source
1537 INSERT INTO acq.fund_allocation (
1544 source.funding_source,
1548 'Transfer to fund ' || new_fund
1552 IF new_fund IS NOT NULL THEN
1554 -- Determine how much to add to the new fund, in
1555 -- its currency, and how much remains to be added:
1557 IF same_currency THEN
1558 curr_new_amt := curr_old_amt;
1560 IF old_remaining = 0 THEN
1562 -- This is the last iteration, so nothing should be left
1564 curr_new_amt := new_remaining;
1567 curr_new_amt := trunc( curr_old_amt * currency_ratio, 2 );
1568 new_remaining := new_remaining - curr_new_amt;
1572 -- Determine how much to add, if any,
1573 -- to the new fund's allocation.
1575 IF old_remaining > 0 THEN
1577 -- In this case we're using the whole allocation, so use that amount
1578 -- amount directly instead of applying a currency translation and
1579 -- thereby inviting round-off errors.
1581 source_addition := curr_new_amt;
1582 ELSIF source.currency_type = old_fund_currency THEN
1584 -- In this case we don't need a round trip currency translation,
1585 -- thereby inviting round-off errors:
1587 source_addition := curr_old_amt;
1589 source_addition := trunc(
1591 acq.exchange_ratio( new_fund_currency, source.currency_type ),
1595 IF source_addition <> 0 THEN
1597 -- Insert positive allocation for new fund in fund_allocation,
1598 -- converted to the currency of the founding source
1600 INSERT INTO acq.fund_allocation (
1607 source.funding_source,
1611 'Transfer from fund ' || old_fund
1616 IF trunc( curr_old_amt, 2 ) <> 0
1617 OR trunc( curr_new_amt, 2 ) <> 0 THEN
1619 -- Insert row in fund_transfer, using amounts in the currency of the funds
1621 INSERT INTO acq.fund_transfer (
1628 funding_source_credit
1631 trunc( curr_old_amt, 2 ),
1633 trunc( curr_new_amt, 2 ),
1640 if old_remaining <= 0 THEN
1641 EXIT; -- Nothing more to be transferred
1645 $$ LANGUAGE plpgsql;
1647 CREATE OR REPLACE FUNCTION acq.attribute_debits() RETURNS VOID AS $$
1649 Function to attribute expenditures and encumbrances to funding source credits,
1650 and thereby to funding sources.
1652 Read the debits in chonological order, attributing each one to one or
1653 more funding source credits. Constraints:
1655 1. Don't attribute more to a credit than the amount of the credit.
1657 2. For a given fund, don't attribute more to a funding source than the
1658 source has allocated to that fund.
1660 3. Attribute debits to credits with deadlines before attributing them to
1661 credits without deadlines. Otherwise attribute to the earliest credits
1662 first, based on the deadline date when present, or on the effective date
1663 when there is no deadline. Use funding_source_credit.id as a tie-breaker.
1664 This ordering is defined by an ORDER BY clause on the view
1665 acq.ordered_funding_source_credit.
1667 Start by truncating the table acq.debit_attribution. Then insert a row
1668 into that table for each attribution. If a debit cannot be fully
1669 attributed, insert a row for the unattributable balance, with the
1670 funding_source_credit and credit_amount columns NULL.
1673 curr_fund_source_bal RECORD;
1674 seqno INT; -- sequence num for credits applicable to a fund
1675 fund_credit RECORD; -- current row in temp t_fund_credit table
1676 fc RECORD; -- used for loading t_fund_credit table
1677 sc RECORD; -- used for loading t_fund_credit table
1679 -- Used exclusively in the main loop:
1681 deb RECORD; -- current row from acq.fund_debit table
1682 curr_credit_bal RECORD; -- current row from temp t_credit table
1683 debit_balance NUMERIC; -- amount left to attribute for current debit
1684 conv_debit_balance NUMERIC; -- debit balance in currency of the fund
1685 attr_amount NUMERIC; -- amount being attributed, in currency of debit
1686 conv_attr_amount NUMERIC; -- amount being attributed, in currency of source
1687 conv_cred_balance NUMERIC; -- credit_balance in the currency of the fund
1688 conv_alloc_balance NUMERIC; -- allocated balance in the currency of the fund
1689 attrib_count INT; -- populates id of acq.debit_attribution
1692 -- Load a temporary table. For each combination of fund and funding source,
1693 -- load an entry with the total amount allocated to that fund by that source.
1694 -- This sum may reflect transfers as well as original allocations. We will
1695 -- reduce this balance whenever we attribute debits to it.
1697 CREATE TEMP TABLE t_fund_source_bal
1701 funding_source AS source,
1702 sum( amount ) AS balance
1711 CREATE INDEX t_fund_source_bal_idx
1712 ON t_fund_source_bal( fund, source );
1713 -------------------------------------------------------------------------------
1715 -- Load another temporary table. For each fund, load zero or more
1716 -- funding source credits from which that fund can get money.
1718 CREATE TEMP TABLE t_fund_credit (
1725 SELECT DISTINCT fund
1726 FROM acq.fund_allocation
1728 LOOP -- Loop over the funds
1734 acq.ordered_funding_source_credit AS ofsc
1736 ofsc.funding_source IN
1738 SELECT funding_source
1739 FROM acq.fund_allocation
1740 WHERE fund = fc.fund
1746 LOOP -- Add each credit to the list
1747 INSERT INTO t_fund_credit (
1756 --RAISE NOTICE 'Fund % credit %', fc.fund, sc.id;
1758 END LOOP; -- Loop over credits for a given fund
1759 END LOOP; -- Loop over funds
1761 CREATE INDEX t_fund_credit_idx
1762 ON t_fund_credit( fund, seq );
1763 -------------------------------------------------------------------------------
1765 -- Load yet another temporary table. This one is a list of funding source
1766 -- credits, with their balances. We shall reduce those balances as we
1767 -- attribute debits to them.
1769 CREATE TEMP TABLE t_credit
1773 fsc.funding_source AS source,
1774 fsc.amount AS balance,
1775 fs.currency_type AS currency_type
1777 acq.funding_source_credit AS fsc,
1778 acq.funding_source fs
1780 fsc.funding_source = fs.id
1783 CREATE INDEX t_credit_idx
1784 ON t_credit( credit );
1786 -------------------------------------------------------------------------------
1788 -- Now that we have loaded the lookup tables: loop through the debits,
1789 -- attributing each one to one or more funding source credits.
1791 truncate table acq.debit_attribution;
1809 --RAISE NOTICE 'Debit %, fund %', deb.id, deb.fund;
1811 debit_balance := deb.amount;
1813 -- Loop over the funding source credits that are eligible
1814 -- to pay for this debit
1826 --RAISE NOTICE ' Examining credit %', fund_credit.credit;
1828 -- Look up the balance for this credit. If it's zero, then
1829 -- it's not useful, so treat it as if you didn't find it.
1830 -- (Actually there shouldn't be any zero balances in the table,
1831 -- but we check just to make sure.)
1834 INTO curr_credit_bal
1837 credit = fund_credit.credit
1840 IF curr_credit_bal IS NULL THEN
1842 -- This credit is exhausted; try the next one.
1848 -- At this point we have an applicable credit with some money left.
1849 -- Now see if the relevant funding_source has any money left.
1851 -- Look up the balance of the allocation for this combination of
1852 -- fund and source. If you find such an entry, but it has a zero
1853 -- balance, then it's not useful, so treat it as unfound.
1854 -- (Actually there shouldn't be any zero balances in the table,
1855 -- but we check just to make sure.)
1858 INTO curr_fund_source_bal
1859 FROM t_fund_source_bal
1862 AND source = curr_credit_bal.source
1865 IF curr_fund_source_bal IS NULL THEN
1867 -- This fund/source doesn't exist or is already exhausted,
1868 -- so we can't use this credit. Go on to the next one.
1873 -- Convert the available balances to the currency of the fund
1875 conv_alloc_balance := curr_fund_source_bal.balance * acq.exchange_ratio(
1876 curr_credit_bal.currency_type, deb.currency_type );
1877 conv_cred_balance := curr_credit_bal.balance * acq.exchange_ratio(
1878 curr_credit_bal.currency_type, deb.currency_type );
1880 -- Determine how much we can attribute to this credit: the minimum
1881 -- of the debit amount, the fund/source balance, and the
1884 --RAISE NOTICE ' deb bal %', debit_balance;
1885 --RAISE NOTICE ' source % balance %', curr_credit_bal.source, conv_alloc_balance;
1886 --RAISE NOTICE ' credit % balance %', curr_credit_bal.credit, conv_cred_balance;
1888 conv_attr_amount := NULL;
1889 attr_amount := debit_balance;
1891 IF attr_amount > conv_alloc_balance THEN
1892 attr_amount := conv_alloc_balance;
1893 conv_attr_amount := curr_fund_source_bal.balance;
1895 IF attr_amount > conv_cred_balance THEN
1896 attr_amount := conv_cred_balance;
1897 conv_attr_amount := curr_credit_bal.balance;
1900 -- If we're attributing all of one of the balances, then that's how
1901 -- much we will deduct from the balances, and we already captured
1902 -- that amount above. Otherwise we must convert the amount of the
1903 -- attribution from the currency of the fund back to the currency of
1904 -- the funding source.
1906 IF conv_attr_amount IS NULL THEN
1907 conv_attr_amount := attr_amount * acq.exchange_ratio(
1908 deb.currency_type, curr_credit_bal.currency_type );
1911 -- Insert a row to record the attribution
1913 attrib_count := attrib_count + 1;
1914 INSERT INTO acq.debit_attribution (
1918 funding_source_credit,
1924 curr_credit_bal.credit,
1928 -- Subtract the attributed amount from the various balances
1930 debit_balance := debit_balance - attr_amount;
1931 curr_fund_source_bal.balance := curr_fund_source_bal.balance - conv_attr_amount;
1933 IF curr_fund_source_bal.balance <= 0 THEN
1935 -- This allocation is exhausted. Delete it so
1936 -- that we don't waste time looking at it again.
1938 DELETE FROM t_fund_source_bal
1940 fund = curr_fund_source_bal.fund
1941 AND source = curr_fund_source_bal.source;
1943 UPDATE t_fund_source_bal
1944 SET balance = balance - conv_attr_amount
1946 fund = curr_fund_source_bal.fund
1947 AND source = curr_fund_source_bal.source;
1950 IF curr_credit_bal.balance <= 0 THEN
1952 -- This funding source credit is exhausted. Delete it
1953 -- so that we don't waste time looking at it again.
1955 --DELETE FROM t_credit
1957 -- credit = curr_credit_bal.credit;
1959 DELETE FROM t_fund_credit
1961 credit = curr_credit_bal.credit;
1964 SET balance = curr_credit_bal.balance
1966 credit = curr_credit_bal.credit;
1969 -- Are we done with this debit yet?
1971 IF debit_balance <= 0 THEN
1972 EXIT; -- We've fully attributed this debit; stop looking at credits.
1974 END LOOP; -- End loop over credits
1976 IF debit_balance <> 0 THEN
1978 -- We weren't able to attribute this debit, or at least not
1979 -- all of it. Insert a row for the unattributed balance.
1981 attrib_count := attrib_count + 1;
1982 INSERT INTO acq.debit_attribution (
1986 funding_source_credit,
1996 END LOOP; -- End of loop over debits
1998 $$ LANGUAGE 'plpgsql';
2000 CREATE OR REPLACE FUNCTION acq.copy_fund_tags(
2001 old_fund_id INTEGER,
2003 ) RETURNS VOID AS $$
2005 fund_tag_rec RECORD;
2008 FOR fund_tag_rec IN SELECT * FROM acq.fund_tag_map WHERE fund=old_fund_id LOOP
2010 INSERT INTO acq.fund_tag_map(fund, tag) VALUES(new_fund_id, fund_tag_rec.tag);
2012 WHEN unique_violation THEN
2013 -- RAISE NOTICE 'Fund tag already propagated', old_fund.id;
2019 $$ LANGUAGE plpgsql;
2021 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_tree(
2024 org_unit_id INTEGER,
2025 include_desc BOOL DEFAULT TRUE
2026 ) RETURNS VOID AS $$
2037 IF old_year IS NULL THEN
2038 RAISE EXCEPTION 'Input year argument is NULL';
2039 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2040 RAISE EXCEPTION 'Input year is out of range';
2043 IF user_id IS NULL THEN
2044 RAISE EXCEPTION 'Input user id argument is NULL';
2047 IF org_unit_id IS NULL THEN
2048 RAISE EXCEPTION 'Org unit id argument is NULL';
2050 SELECT TRUE INTO org_found
2052 WHERE id = org_unit_id;
2054 IF org_found IS NULL THEN
2055 RAISE EXCEPTION 'Org unit id is invalid';
2059 -- Loop over the applicable funds
2061 FOR old_fund in SELECT * FROM acq.fund
2065 AND ( ( include_desc AND org IN ( SELECT id FROM actor.org_unit_descendants( org_unit_id ) ) )
2066 OR (NOT include_desc AND org = org_unit_id ) )
2070 INSERT INTO acq.fund (
2078 balance_warning_percent,
2079 balance_stop_percent
2084 old_fund.currency_type,
2088 old_fund.balance_warning_percent,
2089 old_fund.balance_stop_percent
2091 RETURNING id INTO new_id;
2093 WHEN unique_violation THEN
2094 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
2098 PERFORM acq.copy_fund_tags(old_fund.id,new_id);
2100 --RAISE NOTICE 'Propagating fund % to fund %',
2101 -- old_fund.code, new_id;
2104 $$ LANGUAGE plpgsql;
2106 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_unit( old_year INTEGER, user_id INTEGER, org_unit_id INTEGER ) RETURNS VOID AS $$
2107 SELECT acq.propagate_funds_by_org_tree( $1, $2, $3, FALSE );
2110 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_tree(
2113 org_unit_id INTEGER,
2114 encumb_only BOOL DEFAULT FALSE,
2115 include_desc BOOL DEFAULT TRUE
2116 ) RETURNS VOID AS $$
2120 new_year INT := old_year + 1;
2123 xfer_amount NUMERIC := 0;
2127 roll_distrib_forms BOOL;
2133 IF old_year IS NULL THEN
2134 RAISE EXCEPTION 'Input year argument is NULL';
2135 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2136 RAISE EXCEPTION 'Input year is out of range';
2139 IF user_id IS NULL THEN
2140 RAISE EXCEPTION 'Input user id argument is NULL';
2143 IF org_unit_id IS NULL THEN
2144 RAISE EXCEPTION 'Org unit id argument is NULL';
2147 -- Validate the org unit
2152 WHERE id = org_unit_id;
2154 IF org_found IS NULL THEN
2155 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
2156 ELSIF encumb_only THEN
2157 SELECT INTO perm_ous value::BOOL FROM
2158 actor.org_unit_ancestor_setting(
2159 'acq.fund.allow_rollover_without_money', org_unit_id
2161 IF NOT FOUND OR NOT perm_ous THEN
2162 RAISE EXCEPTION 'Encumbrance-only rollover not permitted at org %', org_unit_id;
2167 -- Loop over the propagable funds to identify the details
2168 -- from the old fund plus the id of the new one, if it exists.
2172 oldf.id AS old_fund,
2178 newf.id AS new_fund_id
2181 LEFT JOIN acq.fund AS newf
2182 ON ( oldf.code = newf.code AND oldf.org = newf.org )
2184 oldf.year = old_year
2186 AND newf.year = new_year
2187 AND ( ( include_desc AND oldf.org IN ( SELECT id FROM actor.org_unit_descendants( org_unit_id ) ) )
2188 OR (NOT include_desc AND oldf.org = org_unit_id ) )
2190 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2192 IF roll_fund.new_fund_id IS NULL THEN
2194 -- The old fund hasn't been propagated yet. Propagate it now.
2196 INSERT INTO acq.fund (
2204 balance_warning_percent,
2205 balance_stop_percent
2210 roll_fund.currency_type,
2214 roll_fund.balance_warning_percent,
2215 roll_fund.balance_stop_percent
2217 RETURNING id INTO new_fund;
2219 PERFORM acq.copy_fund_tags(roll_fund.id,new_fund);
2222 new_fund = roll_fund.new_fund_id;
2225 -- Determine the amount to transfer
2229 FROM acq.fund_spent_balance
2230 WHERE fund = roll_fund.old_fund;
2232 IF xfer_amount <> 0 THEN
2233 IF NOT encumb_only AND roll_fund.rollover THEN
2235 -- Transfer balance from old fund to new
2237 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2239 PERFORM acq.transfer_fund(
2249 -- Transfer balance from old fund to the void
2251 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2253 PERFORM acq.transfer_fund(
2259 'Rollover into the void'
2264 IF roll_fund.rollover THEN
2266 -- Move any lineitems from the old fund to the new one
2267 -- where the associated debit is an encumbrance.
2269 -- Any other tables tying expenditure details to funds should
2270 -- receive similar treatment. At this writing there are none.
2272 UPDATE acq.lineitem_detail
2275 fund = roll_fund.old_fund -- this condition may be redundant
2281 fund = roll_fund.old_fund
2285 -- Move encumbrance debits from the old fund to the new fund
2287 UPDATE acq.fund_debit
2290 fund = roll_fund.old_fund
2294 -- Rollover distribution formulae funds
2295 SELECT INTO roll_distrib_forms value::BOOL FROM
2296 actor.org_unit_ancestor_setting(
2297 'acq.fund.rollover_distrib_forms', org_unit_id
2300 IF roll_distrib_forms THEN
2301 UPDATE acq.distribution_formula_entry
2302 SET fund = roll_fund.new_fund_id
2303 WHERE fund = roll_fund.old_fund;
2307 -- Mark old fund as inactive, now that we've closed it
2311 WHERE id = roll_fund.old_fund;
2314 $$ LANGUAGE plpgsql;
2319 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 $$
2320 SELECT acq.rollover_funds_by_org_tree( $1, $2, $3, $4, FALSE );
2323 CREATE OR REPLACE VIEW acq.funding_source_credit_total AS
2324 SELECT funding_source,
2325 SUM(amount) AS amount
2326 FROM acq.funding_source_credit
2329 CREATE OR REPLACE VIEW acq.funding_source_allocation_total AS
2330 SELECT funding_source,
2331 SUM(a.amount)::NUMERIC(100,2) AS amount
2332 FROM acq.fund_allocation a
2335 CREATE OR REPLACE VIEW acq.funding_source_balance AS
2336 SELECT COALESCE(c.funding_source, a.funding_source) AS funding_source,
2337 SUM(COALESCE(c.amount,0.0) - COALESCE(a.amount,0.0))::NUMERIC(100,2) AS amount
2338 FROM acq.funding_source_credit_total c
2339 FULL JOIN acq.funding_source_allocation_total a USING (funding_source)
2342 CREATE OR REPLACE VIEW acq.fund_allocation_total AS
2344 SUM(a.amount * acq.exchange_ratio(s.currency_type, f.currency_type))::NUMERIC(100,2) AS amount
2345 FROM acq.fund_allocation a
2346 JOIN acq.fund f ON (a.fund = f.id)
2347 JOIN acq.funding_source s ON (a.funding_source = s.id)
2350 CREATE OR REPLACE VIEW acq.fund_debit_total AS
2351 SELECT fund.id AS fund,
2352 sum(COALESCE(fund_debit.amount, 0::numeric)) AS amount
2354 LEFT JOIN acq.fund_debit fund_debit ON fund.id = fund_debit.fund
2357 CREATE OR REPLACE VIEW acq.fund_encumbrance_total AS
2360 sum(COALESCE(fund_debit.amount, 0::numeric)) AS amount
2362 LEFT JOIN acq.fund_debit fund_debit ON fund.id = fund_debit.fund
2363 WHERE fund_debit.encumbrance GROUP BY fund.id;
2365 CREATE OR REPLACE VIEW acq.fund_spent_total AS
2366 SELECT fund.id AS fund,
2367 sum(COALESCE(fund_debit.amount, 0::numeric)) AS amount
2369 LEFT JOIN acq.fund_debit fund_debit ON fund.id = fund_debit.fund
2370 WHERE NOT fund_debit.encumbrance
2373 CREATE OR REPLACE VIEW acq.fund_combined_balance AS
2375 c.amount - COALESCE(d.amount, 0.0) AS amount
2376 FROM acq.fund_allocation_total c
2377 LEFT JOIN acq.fund_debit_total d USING (fund);
2379 CREATE OR REPLACE VIEW acq.fund_spent_balance AS
2381 c.amount - COALESCE(d.amount,0.0) AS amount
2382 FROM acq.fund_allocation_total c
2383 LEFT JOIN acq.fund_spent_total d USING (fund);
2385 -- For each fund: the total allocation from all sources, in the
2386 -- currency of the fund (or 0 if there are no allocations)
2388 CREATE VIEW acq.all_fund_allocation_total AS
2391 COALESCE( SUM( a.amount * acq.exchange_ratio(
2392 s.currency_type, f.currency_type))::numeric(100,2), 0 )
2396 LEFT JOIN acq.fund_allocation a
2398 LEFT JOIN acq.funding_source s
2399 ON a.funding_source = s.id
2403 -- For every fund: the total encumbrances (or 0 if none),
2404 -- in the currency of the fund.
2406 CREATE VIEW acq.all_fund_encumbrance_total AS
2409 COALESCE( encumb.amount, 0 ) AS amount
2415 sum( amount ) AS amount
2422 ON f.id = encumb.fund;
2424 -- For every fund: the total spent (or 0 if none),
2425 -- in the currency of the fund.
2427 CREATE VIEW acq.all_fund_spent_total AS
2430 COALESCE( spent.amount, 0 ) AS amount
2436 sum( amount ) AS amount
2443 ON f.id = spent.fund;
2445 -- For each fund: the amount not yet spent, in the currency
2446 -- of the fund. May include encumbrances.
2448 CREATE VIEW acq.all_fund_spent_balance AS
2451 c.amount - d.amount AS amount
2452 FROM acq.all_fund_allocation_total c
2453 LEFT JOIN acq.all_fund_spent_total d USING (fund);
2455 -- For each fund: the amount neither spent nor encumbered,
2456 -- in the currency of the fund
2458 CREATE VIEW acq.all_fund_combined_balance AS
2461 a.amount - COALESCE( c.amount, 0 ) AS amount
2463 acq.all_fund_allocation_total a
2467 SUM( amount ) AS amount
2472 ) AS c USING ( fund );
2474 CREATE TABLE acq.claim_type (
2475 id SERIAL PRIMARY KEY,
2476 org_unit INT NOT NULL REFERENCES actor.org_unit(id)
2477 DEFERRABLE INITIALLY DEFERRED,
2479 description TEXT NOT NULL,
2480 CONSTRAINT claim_type_once_per_org UNIQUE ( org_unit, code )
2483 CREATE TABLE acq.claim (
2484 id SERIAL PRIMARY KEY,
2485 type INT NOT NULL REFERENCES acq.claim_type
2486 DEFERRABLE INITIALLY DEFERRED,
2487 lineitem_detail BIGINT NOT NULL REFERENCES acq.lineitem_detail
2488 DEFERRABLE INITIALLY DEFERRED
2491 CREATE INDEX claim_lid_idx ON acq.claim( lineitem_detail );
2493 CREATE TABLE acq.claim_event (
2494 id BIGSERIAL PRIMARY KEY,
2495 type INT NOT NULL REFERENCES acq.claim_event_type
2496 DEFERRABLE INITIALLY DEFERRED,
2497 claim SERIAL NOT NULL REFERENCES acq.claim
2498 DEFERRABLE INITIALLY DEFERRED,
2499 event_date TIMESTAMPTZ NOT NULL DEFAULT now(),
2500 creator INT NOT NULL REFERENCES actor.usr
2501 DEFERRABLE INITIALLY DEFERRED,
2505 CREATE INDEX claim_event_claim_date_idx ON acq.claim_event( claim, event_date );
2507 -- And the serials version of claiming
2508 CREATE TABLE acq.serial_claim (
2509 id SERIAL PRIMARY KEY,
2510 type INT NOT NULL REFERENCES acq.claim_type
2511 DEFERRABLE INITIALLY DEFERRED,
2512 item BIGINT NOT NULL REFERENCES serial.item
2513 DEFERRABLE INITIALLY DEFERRED
2516 CREATE INDEX serial_claim_lid_idx ON acq.serial_claim( item );
2518 CREATE TABLE acq.serial_claim_event (
2519 id BIGSERIAL PRIMARY KEY,
2520 type INT NOT NULL REFERENCES acq.claim_event_type
2521 DEFERRABLE INITIALLY DEFERRED,
2522 claim SERIAL NOT NULL REFERENCES acq.serial_claim
2523 DEFERRABLE INITIALLY DEFERRED,
2524 event_date TIMESTAMPTZ NOT NULL DEFAULT now(),
2525 creator INT NOT NULL REFERENCES actor.usr
2526 DEFERRABLE INITIALLY DEFERRED,
2530 CREATE INDEX serial_claim_event_claim_date_idx ON acq.serial_claim_event( claim, event_date );
2532 CREATE OR REPLACE VIEW acq.lineitem_summary AS
2536 SELECT COUNT(lid.id)
2537 FROM acq.lineitem_detail lid
2538 WHERE lineitem = li.id
2541 SELECT COUNT(lid.id)
2542 FROM acq.lineitem_detail lid
2543 WHERE recv_time IS NOT NULL AND lineitem = li.id
2546 SELECT COUNT(lid.id)
2547 FROM acq.lineitem_detail lid
2548 JOIN acq.cancel_reason acqcr ON (acqcr.id = lid.cancel_reason)
2549 WHERE acqcr.keep_debits IS FALSE AND lineitem = li.id
2552 SELECT COUNT(lid.id)
2553 FROM acq.lineitem_detail lid
2554 JOIN acq.cancel_reason acqcr ON (acqcr.id = lid.cancel_reason)
2555 WHERE acqcr.keep_debits IS TRUE AND lineitem = li.id
2558 SELECT COUNT(lid.id)
2559 FROM acq.lineitem_detail lid
2560 JOIN acq.fund_debit debit ON (lid.fund_debit = debit.id)
2561 WHERE NOT debit.encumbrance AND lineitem = li.id
2564 SELECT COUNT(DISTINCT(lid.id))
2565 FROM acq.lineitem_detail lid
2566 JOIN acq.claim claim ON (claim.lineitem_detail = lid.id)
2567 WHERE lineitem = li.id
2570 SELECT (COUNT(lid.id) * li.estimated_unit_price)::NUMERIC(8,2)
2571 FROM acq.lineitem_detail lid
2572 WHERE lid.cancel_reason IS NULL AND lineitem = li.id
2573 ) AS estimated_amount,
2575 SELECT SUM(debit.amount)::NUMERIC(8,2)
2576 FROM acq.lineitem_detail lid
2577 JOIN acq.fund_debit debit ON (lid.fund_debit = debit.id)
2578 WHERE debit.encumbrance AND lineitem = li.id
2579 ) AS encumbrance_amount,
2581 SELECT SUM(debit.amount)::NUMERIC(8,2)
2582 FROM acq.lineitem_detail lid
2583 JOIN acq.fund_debit debit ON (lid.fund_debit = debit.id)
2584 WHERE NOT debit.encumbrance AND lineitem = li.id
2587 FROM acq.lineitem AS li;
2590 CREATE VIEW acq.li_state_label AS
2593 ('new', oils_i18n_gettext('new', 'New', 'jubstlbl', 'label')),
2594 ('selector-ready', oils_i18n_gettext('selector-ready', 'Selector-Ready', 'jubstlbl', 'label')),
2595 ('order-ready', oils_i18n_gettext('order-ready', 'Order-Ready', 'jubstlbl', 'label')),
2596 ('approved', oils_i18n_gettext('approved', 'Approved', 'jubstlbl', 'label')),
2597 ('pending-order', oils_i18n_gettext('pending-order', 'Pending-Order', 'jubstlbl', 'label')),
2598 ('on-order', oils_i18n_gettext('on-order', 'On-Order', 'jubstlbl', 'label')),
2599 ('received', oils_i18n_gettext('received', 'Received', 'jubstlbl', 'label')),
2600 ('cancelled', oils_i18n_gettext('cancelled', 'Cancelled', 'jubstlbl', 'label'))
2603 CREATE VIEW acq.po_state_label AS
2606 ('new', oils_i18n_gettext('new', 'New', 'acqpostlbl', 'label')),
2607 ('pending', oils_i18n_gettext('pending', 'Pending', 'acqpostlbl', 'label')),
2608 ('on-order', oils_i18n_gettext('on-order', 'On-Order', 'acqpostlbl', 'label')),
2609 ('received', oils_i18n_gettext('received', 'Received', 'acqpostlbl', 'label')),
2610 ('cancelled', oils_i18n_gettext('cancelled', 'Cancelled', 'acqpostlbl', 'label'))