1 DROP SCHEMA acq CASCADE;
11 CREATE TABLE acq.currency_type (
12 code TEXT PRIMARY KEY,
16 -- Use the ISO 4217 abbreviations for currency codes
17 INSERT INTO acq.currency_type (code, label) VALUES ('USD','US Dollars');
18 INSERT INTO acq.currency_type (code, label) VALUES ('CAN','Canadian Dollars');
19 INSERT INTO acq.currency_type (code, label) VALUES ('EUR','Euros');
21 CREATE TABLE acq.exchange_rate (
22 id SERIAL PRIMARY KEY,
23 from_currency TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
24 to_currency TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
25 ratio NUMERIC NOT NULL,
26 CONSTRAINT exchange_rate_from_to_once UNIQUE (from_currency,to_currency)
29 INSERT INTO acq.exchange_rate (from_currency,to_currency,ratio) VALUES ('USD','CAN',1.2);
30 INSERT INTO acq.exchange_rate (from_currency,to_currency,ratio) VALUES ('USD','EUR',0.5);
32 CREATE TABLE acq.provider (
33 id SERIAL PRIMARY KEY,
35 owner INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
36 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
40 edi_default INT, -- REFERENCES acq.edi_account (id) DEFERRABLE INITIALLY DEFERRED
41 active BOOL NOT NULL DEFAULT TRUE,
42 prepayment_required BOOL NOT NULL DEFAULT FALSE,
47 CONSTRAINT provider_name_once_per_owner UNIQUE (name,owner),
48 CONSTRAINT code_once_per_owner UNIQUE (code, owner)
51 CREATE TABLE acq.provider_holding_subfield_map (
52 id SERIAL PRIMARY KEY,
53 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
54 name TEXT NOT NULL, -- barcode, price, etc
55 subfield TEXT NOT NULL,
56 CONSTRAINT name_once_per_provider UNIQUE (provider,name)
59 CREATE TABLE acq.provider_address (
60 id SERIAL PRIMARY KEY,
61 valid BOOL NOT NULL DEFAULT TRUE,
63 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
64 street1 TEXT NOT NULL,
69 country TEXT NOT NULL,
70 post_code TEXT NOT NULL,
71 fax_phone TEXT NOT NULL
74 CREATE TABLE acq.provider_contact (
75 id SERIAL PRIMARY KEY,
76 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
78 role TEXT, -- free-form.. e.g. "our sales guy"
83 CREATE TABLE acq.provider_contact_address (
84 id SERIAL PRIMARY KEY,
85 valid BOOL NOT NULL DEFAULT TRUE,
87 contact INT NOT NULL REFERENCES acq.provider_contact (id) DEFERRABLE INITIALLY DEFERRED,
88 street1 TEXT NOT NULL,
93 country TEXT NOT NULL,
94 post_code TEXT NOT NULL,
99 CREATE TABLE acq.funding_source (
100 id SERIAL PRIMARY KEY,
102 owner INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
103 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
105 CONSTRAINT funding_source_name_once_per_owner UNIQUE (name,owner)
108 CREATE TABLE acq.funding_source_credit (
109 id SERIAL PRIMARY KEY,
110 funding_source INT NOT NULL REFERENCES acq.funding_source (id) DEFERRABLE INITIALLY DEFERRED,
111 amount NUMERIC NOT NULL,
113 deadline_date TIMESTAMPTZ,
114 effective_date TIMESTAMPTZ NOT NULL default now()
117 CREATE VIEW acq.ordered_funding_source_credit AS
119 CASE WHEN deadline_date IS NULL THEN
123 END AS sort_priority,
124 CASE WHEN deadline_date IS NULL THEN
134 acq.funding_source_credit;
136 COMMENT ON VIEW acq.ordered_funding_source_credit IS $$
138 * Copyright (C) 2009 Georgia Public Library Service
139 * Scott McKellar <scott@gmail.com>
141 * The acq.ordered_funding_source_credit view is a prioritized
142 * ordering of funding source credits. When ordered by the first
143 * three columns, this view defines the order in which the various
144 * credits are to be tapped for spending, subject to the allocations
145 * in the acq.fund_allocation table.
147 * The first column reflects the principle that we should spend
148 * money with deadlines before spending money without deadlines.
150 * The second column reflects the principle that we should spend the
151 * oldest money first. For money with deadlines, that means that we
152 * spend first from the credit with the earliest deadline. For
153 * money without deadlines, we spend first from the credit with the
154 * earliest effective date.
156 * The third column is a tie breaker to ensure a consistent
161 * This program is free software; you can redistribute it and/or
162 * modify it under the terms of the GNU General Public License
163 * as published by the Free Software Foundation; either version 2
164 * of the License, or (at your option) any later version.
166 * This program is distributed in the hope that it will be useful,
167 * but WITHOUT ANY WARRANTY; without even the implied warranty of
168 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
169 * GNU General Public License for more details.
173 CREATE TABLE acq.fund (
174 id SERIAL PRIMARY KEY,
175 org INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
177 year INT NOT NULL DEFAULT EXTRACT( YEAR FROM NOW() ),
178 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
180 rollover BOOL NOT NULL DEFAULT FALSE,
181 propagate BOOL NOT NULL DEFAULT TRUE,
182 active BOOL NOT NULL DEFAULT TRUE,
183 balance_warning_percent INT CONSTRAINT balance_warning_percent_limit
184 CHECK( balance_warning_percent <= 100 ),
185 balance_stop_percent INT CONSTRAINT balance_stop_percent_limit
186 CHECK( balance_stop_percent <= 100 ),
187 CONSTRAINT name_once_per_org_year UNIQUE (org,name,year),
188 CONSTRAINT code_once_per_org_year UNIQUE (org, code, year),
189 CONSTRAINT acq_fund_rollover_implies_propagate CHECK ( propagate OR NOT rollover )
192 CREATE TABLE acq.fund_debit (
193 id SERIAL PRIMARY KEY,
194 fund INT NOT NULL REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
195 origin_amount NUMERIC NOT NULL, -- pre-exchange-rate amount
196 origin_currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
197 amount NUMERIC NOT NULL,
198 encumbrance BOOL NOT NULL DEFAULT TRUE,
199 debit_type TEXT NOT NULL,
200 xfer_destination INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
201 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
204 CREATE TABLE acq.fund_allocation (
205 id SERIAL PRIMARY KEY,
206 funding_source INT NOT NULL REFERENCES acq.funding_source (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
207 fund INT NOT NULL REFERENCES acq.fund (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
208 amount NUMERIC NOT NULL,
209 allocator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
211 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
213 CREATE INDEX fund_alloc_allocator_idx ON acq.fund_allocation ( allocator );
215 CREATE TABLE acq.fund_allocation_percent
217 id SERIAL PRIMARY KEY,
218 funding_source INT NOT NULL REFERENCES acq.funding_source
219 DEFERRABLE INITIALLY DEFERRED,
220 org INT NOT NULL REFERENCES actor.org_unit
221 DEFERRABLE INITIALLY DEFERRED,
223 percent NUMERIC NOT NULL,
224 allocator INTEGER NOT NULL REFERENCES actor.usr
225 DEFERRABLE INITIALLY DEFERRED,
227 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
228 CONSTRAINT logical_key UNIQUE( funding_source, org, fund_code ),
229 CONSTRAINT percentage_range CHECK( percent >= 0 AND percent <= 100 )
232 -- Trigger function to validate combination of org_unit and fund_code
234 CREATE OR REPLACE FUNCTION acq.fund_alloc_percent_val()
235 RETURNS TRIGGER AS $$
250 AND code = NEW.fund_code
256 RAISE EXCEPTION 'No fund exists for org % and code %', NEW.org, NEW.fund_code;
261 CREATE TRIGGER acq_fund_alloc_percent_val_trig
262 BEFORE INSERT OR UPDATE ON acq.fund_allocation_percent
263 FOR EACH ROW EXECUTE PROCEDURE acq.fund_alloc_percent_val();
265 -- To do: trigger to verify that percentages don't add up to more than 100
267 CREATE OR REPLACE FUNCTION acq.fap_limit_100()
268 RETURNS TRIGGER AS $$
271 total_percent numeric;
279 acq.fund_allocation_percent AS fap
281 fap.funding_source = NEW.funding_source;
283 IF total_percent > 100 THEN
284 RAISE EXCEPTION 'Total percentages exceed 100 for funding_source %',
292 CREATE TRIGGER acqfap_limit_100_trig
293 AFTER INSERT OR UPDATE ON acq.fund_allocation_percent
294 FOR EACH ROW EXECUTE PROCEDURE acq.fap_limit_100();
296 CREATE TABLE acq.picklist (
297 id SERIAL PRIMARY KEY,
298 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
299 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
300 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
301 org_unit INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
303 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
304 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
305 CONSTRAINT name_once_per_owner UNIQUE (name,owner)
307 CREATE INDEX acq_picklist_owner_idx ON acq.picklist ( owner );
308 CREATE INDEX acq_picklist_creator_idx ON acq.picklist ( creator );
309 CREATE INDEX acq_picklist_editor_idx ON acq.picklist ( editor );
311 CREATE TABLE acq.purchase_order (
312 id SERIAL PRIMARY KEY,
313 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
314 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
315 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
316 ordering_agency INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
317 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
318 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
319 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
320 state TEXT NOT NULL DEFAULT 'new',
321 order_date TIMESTAMP WITH TIME ZONE,
324 CREATE INDEX po_owner_idx ON acq.purchase_order (owner);
325 CREATE INDEX po_provider_idx ON acq.purchase_order (provider);
326 CREATE INDEX po_state_idx ON acq.purchase_order (state);
327 CREATE INDEX po_creator_idx ON acq.purchase_order ( creator );
328 CREATE INDEX po_editor_idx ON acq.purchase_order ( editor );
329 CREATE INDEX acq_po_org_name_order_date_idx ON acq.purchase_order( ordering_agency, name, order_date );
331 -- The name should default to the id, as text. We can't reference a column
332 -- in a DEFAULT clause, so we use a trigger:
334 CREATE OR REPLACE FUNCTION acq.purchase_order_name_default () RETURNS TRIGGER
337 IF NEW.name IS NULL THEN
338 NEW.name := NEW.id::TEXT;
345 CREATE TRIGGER po_name_default_trg
346 BEFORE INSERT OR UPDATE ON acq.purchase_order
347 FOR EACH ROW EXECUTE PROCEDURE acq.purchase_order_name_default ();
349 -- The order name should be unique for a given ordering agency on a given order date
350 -- (truncated to midnight), but only where the order_date is not NULL. Conceptually
351 -- this rule requires a check constraint with a subquery. However you can't have a
352 -- subquery in a CHECK constraint, so we fake it with a trigger.
354 CREATE OR REPLACE FUNCTION acq.po_org_name_date_unique () RETURNS TRIGGER
360 -- If order_date is not null, then make sure we don't have a collision
361 -- on order_date (truncated to day), org, and name
363 IF NEW.order_date IS NULL THEN
367 -- In the WHERE clause, we compare the order_dates without regard to time of day.
368 -- We use a pair of inequalities instead of comparing truncated dates so that the
369 -- query can do an indexed range scan.
371 SELECT 1 INTO collision
372 FROM acq.purchase_order
374 ordering_agency = NEW.ordering_agency
376 AND order_date >= date_trunc( 'day', NEW.order_date )
377 AND order_date < date_trunc( 'day', NEW.order_date ) + '1 day'::INTERVAL
380 IF collision IS NULL THEN
381 -- okay, no collision
384 -- collision; nip it in the bud
385 RAISE EXCEPTION 'Colliding purchase orders: ordering_agency %, date %, name ''%''',
386 NEW.ordering_agency, NEW.order_date, NEW.name;
391 CREATE TRIGGER po_org_name_date_unique_trg
392 BEFORE INSERT OR UPDATE ON acq.purchase_order
393 FOR EACH ROW EXECUTE PROCEDURE acq.po_org_name_date_unique ();
395 CREATE TABLE acq.po_note (
396 id SERIAL PRIMARY KEY,
397 purchase_order INT NOT NULL REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
398 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
399 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
400 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
401 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
404 CREATE INDEX po_note_po_idx ON acq.po_note (purchase_order);
405 CREATE INDEX acq_po_note_creator_idx ON acq.po_note ( creator );
406 CREATE INDEX acq_po_note_editor_idx ON acq.po_note ( editor );
408 CREATE TABLE acq.lineitem (
409 id BIGSERIAL PRIMARY KEY,
410 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
411 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
412 selector INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
413 provider INT REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
414 purchase_order INT REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
415 picklist INT REFERENCES acq.picklist (id) DEFERRABLE INITIALLY DEFERRED,
416 expected_recv_time TIMESTAMP WITH TIME ZONE,
417 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
418 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
420 eg_bib_id INT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
422 state TEXT NOT NULL DEFAULT 'new',
423 CONSTRAINT picklist_or_po CHECK (picklist IS NOT NULL OR purchase_order IS NOT NULL)
425 CREATE INDEX li_po_idx ON acq.lineitem (purchase_order);
426 CREATE INDEX li_pl_idx ON acq.lineitem (picklist);
427 CREATE INDEX li_creator_idx ON acq.lineitem ( creator );
428 CREATE INDEX li_editor_idx ON acq.lineitem ( editor );
429 CREATE INDEX li_selector_idx ON acq.lineitem ( selector );
431 CREATE TABLE acq.lineitem_alert_text (
432 id SERIAL PRIMARY KEY,
435 owning_lib INT NOT NULL
436 REFERENCES actor.org_unit(id)
437 DEFERRABLE INITIALLY DEFERRED,
438 CONSTRAINT alert_one_code_per_org UNIQUE (code, owning_lib)
441 CREATE TABLE acq.lineitem_note (
442 id SERIAL PRIMARY KEY,
443 lineitem INT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
444 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
445 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
446 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
447 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
449 alert_text INT REFERENCES acq.lineitem_alert_text(id)
450 DEFERRABLE INITIALLY DEFERRED
452 CREATE INDEX li_note_li_idx ON acq.lineitem_note (lineitem);
453 CREATE INDEX li_note_creator_idx ON acq.lineitem_note ( creator );
454 CREATE INDEX li_note_editor_idx ON acq.lineitem_note ( editor );
456 CREATE TABLE acq.lineitem_detail (
457 id BIGSERIAL PRIMARY KEY,
458 lineitem INT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
459 fund INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
460 fund_debit INT REFERENCES acq.fund_debit (id) DEFERRABLE INITIALLY DEFERRED,
461 eg_copy_id BIGINT REFERENCES asset.copy (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
465 collection_code TEXT,
466 circ_modifier TEXT REFERENCES config.circ_modifier (code) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
467 owning_lib INT REFERENCES actor.org_unit (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
468 location INT REFERENCES asset.copy_location (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
469 recv_time TIMESTAMP WITH TIME ZONE
472 CREATE INDEX li_detail_li_idx ON acq.lineitem_detail (lineitem);
474 CREATE TABLE acq.lineitem_attr_definition (
475 id BIGSERIAL PRIMARY KEY,
477 description TEXT NOT NULL,
478 remove TEXT NOT NULL DEFAULT '',
479 ident BOOL NOT NULL DEFAULT FALSE
482 CREATE TABLE acq.lineitem_marc_attr_definition (
483 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
485 ) INHERITS (acq.lineitem_attr_definition);
487 CREATE TABLE acq.lineitem_provider_attr_definition (
488 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
490 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED
491 ) INHERITS (acq.lineitem_attr_definition);
493 CREATE TABLE acq.lineitem_generated_attr_definition (
494 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
496 ) INHERITS (acq.lineitem_attr_definition);
498 CREATE TABLE acq.lineitem_usr_attr_definition (
499 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
500 usr INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED
501 ) INHERITS (acq.lineitem_attr_definition);
502 CREATE INDEX li_usr_attr_def_usr_idx ON acq.lineitem_usr_attr_definition ( usr );
504 CREATE TABLE acq.lineitem_local_attr_definition (
505 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq')
506 ) INHERITS (acq.lineitem_attr_definition);
508 CREATE TABLE acq.lineitem_attr (
509 id BIGSERIAL PRIMARY KEY,
510 definition BIGINT NOT NULL,
511 lineitem BIGINT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
512 attr_type TEXT NOT NULL,
513 attr_name TEXT NOT NULL,
514 attr_value TEXT NOT NULL
517 CREATE INDEX li_attr_li_idx ON acq.lineitem_attr (lineitem);
518 CREATE INDEX li_attr_value_idx ON acq.lineitem_attr (attr_value);
519 CREATE INDEX li_attr_definition_idx ON acq.lineitem_attr (definition);
525 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('title','Title of work','//*[@tag="245"]/*[contains("abcmnopr",@code)]');
526 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)]');
527 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('language','Language of work','//*[@tag="240"]/*[@code="l"][1]');
528 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pagination','Pagination','//*[@tag="300"]/*[@code="a"][1]');
529 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('isbn','ISBN','//*[@tag="020"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
530 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('issn','ISSN','//*[@tag="022"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
531 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('price','Price','//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
532 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('identifier','Identifier','//*[@tag="001"]');
533 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('publisher','Publisher','//*[@tag="260"]/*[@code="b"][1]');
534 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pubdate','Publication Date','//*[@tag="260"]/*[@code="c"][1]');
535 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('edition','Edition','//*[@tag="250"]/*[@code="a"][1]');
537 INSERT INTO acq.lineitem_local_attr_definition ( code, description ) VALUES ('estimated_price', 'Estimated Price');
540 CREATE TABLE acq.distribution_formula (
541 id SERIAL PRIMARY KEY,
543 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
545 skip_count INT NOT NULL DEFAULT 0,
546 CONSTRAINT acqdf_name_once_per_owner UNIQUE (name, owner)
549 CREATE TABLE acq.distribution_formula_entry (
550 id SERIAL PRIMARY KEY,
551 formula INTEGER NOT NULL REFERENCES acq.distribution_formula(id)
553 DEFERRABLE INITIALLY DEFERRED,
554 position INTEGER NOT NULL,
555 item_count INTEGER NOT NULL,
556 owning_lib INTEGER REFERENCES actor.org_unit(id)
557 DEFERRABLE INITIALLY DEFERRED,
558 location INTEGER REFERENCES asset.copy_location(id),
559 CONSTRAINT acqdfe_lib_once_per_formula UNIQUE( formula, position ),
560 CONSTRAINT acqdfe_must_be_somewhere
561 CHECK( owning_lib IS NOT NULL OR location IS NOT NULL )
564 CREATE TABLE acq.distribution_formula_application (
565 id BIGSERIAL PRIMARY KEY,
566 creator INT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED,
567 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
569 REFERENCES acq.distribution_formula(id) DEFERRABLE INITIALLY DEFERRED,
570 lineitem INT NOT NULL
571 REFERENCES acq.lineitem(id) DEFERRABLE INITIALLY DEFERRED
574 CREATE INDEX acqdfa_df_idx
575 ON acq.distribution_formula_application(formula);
576 CREATE INDEX acqdfa_li_idx
577 ON acq.distribution_formula_application(lineitem);
578 CREATE INDEX acqdfa_creator_idx
579 ON acq.distribution_formula_application(creator);
581 CREATE TABLE acq.fund_tag (
582 id SERIAL PRIMARY KEY,
584 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
586 CONSTRAINT acqft_tag_once_per_owner UNIQUE (name, owner)
589 CREATE TABLE acq.fund_tag_map (
590 id SERIAL PRIMARY KEY,
591 fund INTEGER NOT NULL REFERENCES acq.fund(id)
592 DEFERRABLE INITIALLY DEFERRED,
593 tag INTEGER REFERENCES acq.fund_tag(id)
595 DEFERRABLE INITIALLY DEFERRED,
596 CONSTRAINT acqftm_fund_once_per_tag UNIQUE( fund, tag )
599 CREATE TABLE acq.fund_transfer (
600 id SERIAL PRIMARY KEY,
601 src_fund INT NOT NULL REFERENCES acq.fund( id )
602 DEFERRABLE INITIALLY DEFERRED,
603 src_amount NUMERIC NOT NULL,
604 dest_fund INT NOT NULL REFERENCES acq.fund( id )
605 DEFERRABLE INITIALLY DEFERRED,
606 dest_amount NUMERIC NOT NULL,
607 transfer_time TIMESTAMPTZ NOT NULL DEFAULT now(),
608 transfer_user INT NOT NULL REFERENCES actor.usr( id )
609 DEFERRABLE INITIALLY DEFERRED,
611 funding_source_credit INT NOT NULL REFERENCES acq.funding_source_credit( id )
612 DEFERRABLE INITIALLY DEFERRED
615 CREATE INDEX acqftr_usr_idx
616 ON acq.fund_transfer( transfer_user );
618 COMMENT ON TABLE acq.fund_transfer IS $$
620 * Copyright (C) 2009 Georgia Public Library Service
621 * Scott McKellar <scott@esilibrary.com>
625 * Each row represents the transfer of money from a source fund
626 * to a destination fund. There should be corresponding entries
627 * in acq.fund_allocation. The purpose of acq.fund_transfer is
628 * to record how much money moved from which fund to which other
631 * The presence of two amount fields, rather than one, reflects
632 * the possibility that the two funds are denominated in different
633 * currencies. If they use the same currency type, the two
634 * amounts should be the same.
638 * This program is free software; you can redistribute it and/or
639 * modify it under the terms of the GNU General Public License
640 * as published by the Free Software Foundation; either version 2
641 * of the License, or (at your option) any later version.
643 * This program is distributed in the hope that it will be useful,
644 * but WITHOUT ANY WARRANTY; without even the implied warranty of
645 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
646 * GNU General Public License for more details.
650 CREATE TABLE acq.fiscal_calendar (
651 id SERIAL PRIMARY KEY,
655 -- Create a default calendar (though we don't specify its contents).
656 -- Create a foreign key in actor.org_unit, initially pointing to
657 -- the default calendar.
659 INSERT INTO acq.fiscal_calendar (
666 ALTER TABLE actor.org_unit ADD FOREIGN KEY
667 (fiscal_calendar) REFERENCES acq.fiscal_calendar( id )
668 DEFERRABLE INITIALLY DEFERRED;
670 CREATE TABLE acq.fiscal_year (
671 id SERIAL PRIMARY KEY,
672 calendar INT NOT NULL
673 REFERENCES acq.fiscal_calendar
675 DEFERRABLE INITIALLY DEFERRED,
677 year_begin TIMESTAMPTZ NOT NULL,
678 year_end TIMESTAMPTZ NOT NULL,
679 CONSTRAINT acq_fy_logical_key UNIQUE ( calendar, year ),
680 CONSTRAINT acq_fy_physical_key UNIQUE ( calendar, year_begin )
683 CREATE TABLE acq.edi_account ( -- similar tables can extend remote_account for other parts of EG
684 provider INT NOT NULL REFERENCES acq.provider (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
685 in_dir TEXT -- incoming messages dir (probably different than config.remote_account.path, the outgoing dir)
686 ) INHERITS (config.remote_account);
688 -- We need a UNIQUE constraint here also, to support the FK from acq.provider.edi_default
689 ALTER TABLE acq.edi_account ADD CONSTRAINT acq_edi_account_id_unique UNIQUE (id);
691 -- Note below that the primary key is NOT a SERIAL type. We will periodically truncate and rebuild
692 -- the table, assigning ids programmatically instead of using a sequence.
693 CREATE TABLE acq.debit_attribution (
694 id INT NOT NULL PRIMARY KEY,
695 fund_debit INT NOT NULL
696 REFERENCES acq.fund_debit
697 DEFERRABLE INITIALLY DEFERRED,
698 debit_amount NUMERIC NOT NULL,
699 funding_source_credit INT REFERENCES acq.funding_source_credit
700 DEFERRABLE INITIALLY DEFERRED,
701 credit_amount NUMERIC
704 CREATE INDEX acq_attribution_debit_idx
705 ON acq.debit_attribution( fund_debit );
707 CREATE INDEX acq_attribution_credit_idx
708 ON acq.debit_attribution( funding_source_credit );
712 CREATE TABLE acq.invoice_method (
713 code TEXT PRIMARY KEY,
714 name TEXT NOT NULL -- i18n-ize
717 CREATE TABLE acq.invoice (
718 id SERIAL PRIMARY KEY,
719 receiver INT NOT NULL REFERENCES actor.org_unit (id),
720 provider INT NOT NULL REFERENCES acq.provider (id),
721 shipper INT NOT NULL REFERENCES acq.provider (id),
722 recv_date TIMESTAMPTZ NOT NULL DEFAULT NOW(),
723 recv_method TEXT NOT NULL REFERENCES acq.invoice_method (code) DEFAULT 'EDI',
724 inv_type TEXT, -- A "type" field is desired, but no idea what goes here
725 inv_ident TEXT NOT NULL -- vendor-supplied invoice id/number
728 CREATE TABLE acq.invoice_entry (
729 id SERIAL PRIMARY KEY,
730 invoice INT NOT NULL REFERENCES acq.invoice (id) ON DELETE CASCADE,
731 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
732 lineitem INT REFERENCES acq.lineitem (id) ON UPDATE CASCADE ON DELETE SET NULL,
733 inv_item_count INT NOT NULL, -- How many acqlids did they say they sent
734 phys_item_count INT, -- and how many did staff count
736 billed_per_item BOOL,
737 cost_billed NUMERIC(8,2),
738 actual_cost NUMERIC(8,2)
741 CREATE TABLE acq.invoice_item_type (
742 code TEXT PRIMARY KEY,
743 name TEXT NOT NULL -- i18n-ize
746 CREATE TABLE acq.invoice_item ( -- for invoice-only debits: taxes/fees/non-bib items/etc
747 id SERIAL PRIMARY KEY,
748 invoice INT NOT NULL REFERENCES acq.invoice (id) ON UPDATE CASCADE ON DELETE CASCADE,
749 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
750 fund_debit INT REFERENCES acq.fund_debit (id),
751 inv_item_type TEXT NOT NULL REFERENCES acq.invoice_item_type (code),
755 cost_billed NUMERIC(8,2),
756 actual_cost NUMERIC(8,2)
760 CREATE TABLE acq.user_request_type (
761 id SERIAL PRIMARY KEY,
762 label TEXT NOT NULL UNIQUE -- i18n-ize
765 INSERT INTO acq.user_request_type (id,label) VALUES (1, oils_i18n_gettext('1', 'Books', 'aurt', 'label'));
766 INSERT INTO acq.user_request_type (id,label) VALUES (2, oils_i18n_gettext('2', 'Journal/Magazine & Newspaper Articles', 'aurt', 'label'));
767 INSERT INTO acq.user_request_type (id,label) VALUES (3, oils_i18n_gettext('3', 'Audiobooks', 'aurt', 'label'));
768 INSERT INTO acq.user_request_type (id,label) VALUES (4, oils_i18n_gettext('4', 'Music', 'aurt', 'label'));
769 INSERT INTO acq.user_request_type (id,label) VALUES (5, oils_i18n_gettext('5', 'DVDs', 'aurt', 'label'));
771 SELECT SETVAL('acq.user_request_type_id_seq'::TEXT, 6);
773 CREATE TABLE acq.user_request (
774 id SERIAL PRIMARY KEY,
775 usr INT NOT NULL REFERENCES actor.usr (id), -- requesting user
776 hold BOOL NOT NULL DEFAULT TRUE,
778 pickup_lib INT NOT NULL REFERENCES actor.org_unit (id), -- pickup lib
779 holdable_formats TEXT, -- nullable, for use in hold creation
781 email_notify BOOL NOT NULL DEFAULT TRUE,
782 lineitem INT REFERENCES acq.lineitem (id) ON DELETE CASCADE,
783 eg_bib BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
784 request_date TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- when they requested it
785 need_before TIMESTAMPTZ, -- don't create holds after this
788 request_type INT NOT NULL REFERENCES acq.user_request_type (id),
805 CREATE TYPE acq.flat_lineitem_holding_subfield AS (lineitem int, holding int, subfield text, data text);
806 CREATE OR REPLACE FUNCTION acq.extract_holding_attr_table (lineitem int, tag text) RETURNS SETOF acq.flat_lineitem_holding_subfield AS $$
809 lida acq.flat_lineitem_holding_subfield%ROWTYPE;
812 SELECT COUNT(*) INTO counter
813 FROM oils_xpath_table(
817 '//*[@tag="' || tag || '"]',
819 ) as t(i int,c text);
821 FOR i IN 1 .. counter LOOP
824 FROM ( SELECT id,i,t,v
825 FROM oils_xpath_table(
829 '//*[@tag="' || tag || '"][position()=' || i || ']/*/@code|' ||
830 '//*[@tag="' || tag || '"][position()=' || i || ']/*[@code]',
832 ) as t(id int,t text,v text)
843 CREATE TYPE acq.flat_lineitem_detail AS (lineitem int, holding int, attr text, data text);
844 CREATE OR REPLACE FUNCTION acq.extract_provider_holding_data ( lineitem_i int ) RETURNS SETOF acq.flat_lineitem_detail AS $$
848 lida acq.flat_lineitem_detail%ROWTYPE;
850 SELECT provider INTO prov_i FROM acq.lineitem WHERE id = lineitem_i;
851 IF NOT FOUND THEN RETURN; END IF;
853 SELECT holding_tag INTO tag_t FROM acq.provider WHERE id = prov_i;
854 IF NOT FOUND OR tag_t IS NULL THEN RETURN; END IF;
861 FROM acq.extract_holding_attr_table( lineitem_i, tag_t ) h
862 JOIN acq.provider_holding_subfield_map a USING (subfield)
863 WHERE a.provider = prov_i
872 -- select * from acq.extract_provider_holding_data(699);
874 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field ( BIGINT, TEXT, TEXT) RETURNS TEXT AS $$
875 SELECT public.extract_marc_field('acq.lineitem', $1, $2, $3);
879 CREATE OR REPLACE FUNCTION public.extract_bib_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
880 SELECT public.extract_marc_field('biblio.record_entry', $1, $2);
883 CREATE OR REPLACE FUNCTION public.extract_authority_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
884 SELECT public.extract_marc_field('authority.record_entry', $1, $2);
888 -- INSERT INTO acq.lineitem_provider_attr_definition ( provider, code, description, xpath ) VALUES (1,'price','Price','//*[@tag="020" or @tag="022"]/*[@code="a"][1]');
891 Suggested vendor fields:
899 CREATE OR REPLACE FUNCTION public.ingest_acq_marc ( ) RETURNS TRIGGER AS $$
907 FOR adef IN SELECT *,tableoid FROM acq.lineitem_attr_definition LOOP
909 SELECT relname::TEXT INTO atype FROM pg_class WHERE oid = adef.tableoid;
911 IF (atype NOT IN ('lineitem_usr_attr_definition','lineitem_local_attr_definition')) THEN
912 IF (atype = 'lineitem_provider_attr_definition') THEN
913 SELECT provider INTO prov FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
914 CONTINUE WHEN NEW.provider IS NULL OR prov <> NEW.provider;
917 IF (atype = 'lineitem_provider_attr_definition') THEN
918 SELECT xpath INTO xpath_string FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
919 ELSIF (atype = 'lineitem_marc_attr_definition') THEN
920 SELECT xpath INTO xpath_string FROM acq.lineitem_marc_attr_definition WHERE id = adef.id;
921 ELSIF (atype = 'lineitem_generated_attr_definition') THEN
922 SELECT xpath INTO xpath_string FROM acq.lineitem_generated_attr_definition WHERE id = adef.id;
925 SELECT extract_acq_marc_field(id, xpath_string, adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
927 IF (value IS NOT NULL AND value <> '') THEN
928 INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
929 VALUES (NEW.id, adef.id, atype, adef.code, value);
940 CREATE OR REPLACE FUNCTION public.cleanup_acq_marc ( ) RETURNS TRIGGER AS $$
942 IF TG_OP = 'UPDATE' THEN
943 DELETE FROM acq.lineitem_attr
944 WHERE lineitem = OLD.id AND attr_type IN ('lineitem_provider_attr_definition', 'lineitem_marc_attr_definition','lineitem_generated_attr_definition');
947 DELETE FROM acq.lineitem_attr WHERE lineitem = OLD.id;
953 CREATE TRIGGER cleanup_lineitem_trigger
954 BEFORE UPDATE OR DELETE ON acq.lineitem
955 FOR EACH ROW EXECUTE PROCEDURE public.cleanup_acq_marc();
957 CREATE TRIGGER ingest_lineitem_trigger
958 AFTER INSERT OR UPDATE ON acq.lineitem
959 FOR EACH ROW EXECUTE PROCEDURE public.ingest_acq_marc();
961 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( from_ex TEXT, to_ex TEXT ) RETURNS NUMERIC AS $$
965 IF from_ex = to_ex THEN
969 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = from_ex AND to_currency = to_ex;
974 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = to_ex AND to_currency = from_ex;
985 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( TEXT, TEXT, NUMERIC ) RETURNS NUMERIC AS $$
986 SELECT $3 * acq.exchange_ratio($1, $2);
989 CREATE OR REPLACE FUNCTION acq.find_bad_fy()
991 Examine the acq.fiscal_year table, comparing successive years.
992 Report any inconsistencies, i.e. years that overlap, have gaps
993 between them, or are out of sequence.
995 RETURNS SETOF RECORD AS $$
1019 ELSIF curr_year.calendar = prev_year.calendar THEN
1020 IF curr_year.year_begin > prev_year.year_end THEN
1021 -- This ugly kludge works around the fact that older
1022 -- versions of PostgreSQL don't support RETURN QUERY SELECT
1023 FOR return_rec IN SELECT
1026 'Gap between fiscal years'::TEXT
1028 RETURN NEXT return_rec;
1030 ELSIF curr_year.year_begin < prev_year.year_end THEN
1031 FOR return_rec IN SELECT
1034 'Overlapping fiscal years'::TEXT
1036 RETURN NEXT return_rec;
1038 ELSIF curr_year.year < prev_year.year THEN
1039 FOR return_rec IN SELECT
1042 'Fiscal years out of order'::TEXT
1044 RETURN NEXT return_rec;
1049 prev_year := curr_year;
1054 $$ LANGUAGE plpgsql;
1056 CREATE OR REPLACE FUNCTION acq.transfer_fund(
1058 old_amount IN NUMERIC, -- in currency of old fund
1060 new_amount IN NUMERIC, -- in currency of new fund
1062 xfer_note IN TEXT -- to be recorded in acq.fund_transfer
1063 -- ,funding_source_in IN INT -- if user wants to specify a funding source (see notes)
1064 ) RETURNS VOID AS $$
1065 /* -------------------------------------------------------------------------------
1067 Function to transfer money from one fund to another.
1069 A transfer is represented as a pair of entries in acq.fund_allocation, with a
1070 negative amount for the old (losing) fund and a positive amount for the new
1071 (gaining) fund. In some cases there may be more than one such pair of entries
1072 in order to pull the money from different funding sources, or more specifically
1073 from different funding source credits. For each such pair there is also an
1074 entry in acq.fund_transfer.
1076 Since funding_source is a non-nullable column in acq.fund_allocation, we must
1077 choose a funding source for the transferred money to come from. This choice
1078 must meet two constraints, so far as possible:
1080 1. The amount transferred from a given funding source must not exceed the
1081 amount allocated to the old fund by the funding source. To that end we
1082 compare the amount being transferred to the amount allocated.
1084 2. We shouldn't transfer money that has already been spent or encumbered, as
1085 defined by the funding attribution process. We attribute expenses to the
1086 oldest funding source credits first. In order to avoid transferring that
1087 attributed money, we reverse the priority, transferring from the newest funding
1088 source credits first. There can be no guarantee that this approach will
1089 avoid overcommitting a fund, but no other approach can do any better.
1091 In this context the age of a funding source credit is defined by the
1092 deadline_date for credits with deadline_dates, and by the effective_date for
1093 credits without deadline_dates, with the proviso that credits with deadline_dates
1094 are all considered "older" than those without.
1098 In the signature for this function, there is one last parameter commented out,
1099 named "funding_source_in". Correspondingly, the WHERE clause for the query
1100 driving the main loop has an OR clause commented out, which references the
1101 funding_source_in parameter.
1103 If these lines are uncommented, this function will allow the user optionally to
1104 restrict a fund transfer to a specified funding source. If the source
1105 parameter is left NULL, then there will be no such restriction.
1107 ------------------------------------------------------------------------------- */
1109 same_currency BOOLEAN;
1110 currency_ratio NUMERIC;
1111 old_fund_currency TEXT;
1112 old_remaining NUMERIC; -- in currency of old fund
1113 new_fund_currency TEXT;
1114 new_fund_active BOOLEAN;
1115 new_remaining NUMERIC; -- in currency of new fund
1116 curr_old_amt NUMERIC; -- in currency of old fund
1117 curr_new_amt NUMERIC; -- in currency of new fund
1118 source_addition NUMERIC; -- in currency of funding source
1119 source_deduction NUMERIC; -- in currency of funding source
1120 orig_allocated_amt NUMERIC; -- in currency of funding source
1121 allocated_amt NUMERIC; -- in currency of fund
1127 IF old_fund IS NULL THEN
1128 RAISE EXCEPTION 'acq.transfer_fund: old fund id is NULL';
1131 IF old_amount IS NULL THEN
1132 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer is NULL';
1135 -- The new fund and its amount must be both NULL or both not NULL.
1137 IF new_fund IS NOT NULL AND new_amount IS NULL THEN
1138 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer to receiving fund is NULL';
1141 IF new_fund IS NULL AND new_amount IS NOT NULL THEN
1142 RAISE EXCEPTION 'acq.transfer_fund: receiving fund is NULL, its amount is not NULL';
1145 IF user_id IS NULL THEN
1146 RAISE EXCEPTION 'acq.transfer_fund: user id is NULL';
1149 -- Initialize the amounts to be transferred, each denominated
1150 -- in the currency of its respective fund. They will be
1151 -- reduced on each iteration of the loop.
1153 old_remaining := old_amount;
1154 new_remaining := new_amount;
1156 -- RAISE NOTICE 'Transferring % in fund % to % in fund %',
1157 -- old_amount, old_fund, new_amount, new_fund;
1159 -- Get the currency types of the old and new funds.
1170 IF old_fund_currency IS NULL THEN
1171 RAISE EXCEPTION 'acq.transfer_fund: old fund id % is not defined', old_fund;
1174 IF new_fund IS NOT NULL THEN
1186 IF new_fund_currency IS NULL THEN
1187 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is not defined', new_fund;
1188 ELSIF NOT new_fund_active THEN
1190 -- No point in putting money into a fund from whence you can't spend it
1192 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is inactive', new_fund;
1195 IF new_amount = old_amount THEN
1196 same_currency := true;
1197 currency_ratio := 1;
1200 -- We'll have to translate currency between funds. We presume that
1201 -- the calling code has already applied an appropriate exchange rate,
1202 -- so we'll apply the same conversion to each sub-transfer.
1204 same_currency := false;
1205 currency_ratio := new_amount / old_amount;
1209 -- Identify the funding source(s) from which we want to transfer the money.
1210 -- The principle is that we want to transfer the newest money first, because
1211 -- we spend the oldest money first. The priority for spending is defined
1212 -- by a sort of the view acq.ordered_funding_source_credit.
1217 ofsc.funding_source,
1219 ofsc.amount * acq.exchange_ratio( fs.currency_type, old_fund_currency )
1223 acq.ordered_funding_source_credit AS ofsc,
1224 acq.funding_source fs
1226 ofsc.funding_source = fs.id
1227 and ofsc.funding_source IN
1229 SELECT funding_source
1230 FROM acq.fund_allocation
1231 WHERE fund = old_fund
1235 -- ofsc.funding_source = funding_source_in
1236 -- OR funding_source_in IS NULL
1239 ofsc.sort_priority desc,
1240 ofsc.sort_date desc,
1244 -- Determine how much money the old fund got from this funding source,
1245 -- denominated in the currency types of the source and of the fund.
1246 -- This result may reflect transfers from previous iterations.
1249 COALESCE( sum( amount ), 0 ),
1250 COALESCE( sum( amount )
1251 * acq.exchange_ratio( source.currency_type, old_fund_currency ), 0 )
1253 orig_allocated_amt, -- in currency of the source
1254 allocated_amt -- in currency of the old fund
1259 and funding_source = source.funding_source;
1261 -- Determine how much to transfer from this credit, in the currency
1262 -- of the fund. Begin with the amount remaining to be attributed:
1264 curr_old_amt := old_remaining;
1266 -- Can't attribute more than was allocated from the fund:
1268 IF curr_old_amt > allocated_amt THEN
1269 curr_old_amt := allocated_amt;
1272 -- Can't attribute more than the amount of the current credit:
1274 IF curr_old_amt > source.converted_amt THEN
1275 curr_old_amt := source.converted_amt;
1278 curr_old_amt := trunc( curr_old_amt, 2 );
1280 old_remaining := old_remaining - curr_old_amt;
1282 -- Determine the amount to be deducted, if any,
1283 -- from the old allocation.
1285 IF old_remaining > 0 THEN
1287 -- In this case we're using the whole allocation, so use that
1288 -- amount directly instead of applying a currency translation
1289 -- and thereby inviting round-off errors.
1291 source_deduction := - orig_allocated_amt;
1293 source_deduction := trunc(
1294 ( - curr_old_amt ) *
1295 acq.exchange_ratio( old_fund_currency, source.currency_type ),
1299 IF source_deduction <> 0 THEN
1301 -- Insert negative allocation for old fund in fund_allocation,
1302 -- converted into the currency of the funding source
1304 INSERT INTO acq.fund_allocation (
1311 source.funding_source,
1315 'Transfer to fund ' || new_fund
1319 IF new_fund IS NOT NULL THEN
1321 -- Determine how much to add to the new fund, in
1322 -- its currency, and how much remains to be added:
1324 IF same_currency THEN
1325 curr_new_amt := curr_old_amt;
1327 IF old_remaining = 0 THEN
1329 -- This is the last iteration, so nothing should be left
1331 curr_new_amt := new_remaining;
1334 curr_new_amt := trunc( curr_old_amt * currency_ratio, 2 );
1335 new_remaining := new_remaining - curr_new_amt;
1339 -- Determine how much to add, if any,
1340 -- to the new fund's allocation.
1342 IF old_remaining > 0 THEN
1344 -- In this case we're using the whole allocation, so use that amount
1345 -- amount directly instead of applying a currency translation and
1346 -- thereby inviting round-off errors.
1348 source_addition := orig_allocated_amt;
1349 ELSIF source.currency_type = old_fund_currency THEN
1351 -- In this case we don't need a round trip currency translation,
1352 -- thereby inviting round-off errors:
1354 source_addition := curr_old_amt;
1356 source_addition := trunc(
1358 acq.exchange_ratio( new_fund_currency, source.currency_type ),
1362 IF source_addition <> 0 THEN
1364 -- Insert positive allocation for new fund in fund_allocation,
1365 -- converted to the currency of the founding source
1367 INSERT INTO acq.fund_allocation (
1374 source.funding_source,
1378 'Transfer from fund ' || old_fund
1383 IF trunc( curr_old_amt, 2 ) <> 0
1384 OR trunc( curr_new_amt, 2 ) <> 0 THEN
1386 -- Insert row in fund_transfer, using amounts in the currency of the funds
1388 INSERT INTO acq.fund_transfer (
1395 funding_source_credit
1398 trunc( curr_old_amt, 2 ),
1400 trunc( curr_new_amt, 2 ),
1407 if old_remaining <= 0 THEN
1408 EXIT; -- Nothing more to be transferred
1412 $$ LANGUAGE plpgsql;
1414 CREATE OR REPLACE FUNCTION acq.attribute_debits() RETURNS VOID AS $$
1416 Function to attribute expenditures and encumbrances to funding source credits,
1417 and thereby to funding sources.
1419 Read the debits in chonological order, attributing each one to one or
1420 more funding source credits. Constraints:
1422 1. Don't attribute more to a credit than the amount of the credit.
1424 2. For a given fund, don't attribute more to a funding source than the
1425 source has allocated to that fund.
1427 3. Attribute debits to credits with deadlines before attributing them to
1428 credits without deadlines. Otherwise attribute to the earliest credits
1429 first, based on the deadline date when present, or on the effective date
1430 when there is no deadline. Use funding_source_credit.id as a tie-breaker.
1431 This ordering is defined by an ORDER BY clause on the view
1432 acq.ordered_funding_source_credit.
1434 Start by truncating the table acq.debit_attribution. Then insert a row
1435 into that table for each attribution. If a debit cannot be fully
1436 attributed, insert a row for the unattributable balance, with the
1437 funding_source_credit and credit_amount columns NULL.
1440 curr_fund_source_bal RECORD;
1441 seqno INT; -- sequence num for credits applicable to a fund
1442 fund_credit RECORD; -- current row in temp t_fund_credit table
1443 fc RECORD; -- used for loading t_fund_credit table
1444 sc RECORD; -- used for loading t_fund_credit table
1446 -- Used exclusively in the main loop:
1448 deb RECORD; -- current row from acq.fund_debit table
1449 curr_credit_bal RECORD; -- current row from temp t_credit table
1450 debit_balance NUMERIC; -- amount left to attribute for current debit
1451 conv_debit_balance NUMERIC; -- debit balance in currency of the fund
1452 attr_amount NUMERIC; -- amount being attributed, in currency of debit
1453 conv_attr_amount NUMERIC; -- amount being attributed, in currency of source
1454 conv_cred_balance NUMERIC; -- credit_balance in the currency of the fund
1455 conv_alloc_balance NUMERIC; -- allocated balance in the currency of the fund
1456 attrib_count INT; -- populates id of acq.debit_attribution
1459 -- Load a temporary table. For each combination of fund and funding source,
1460 -- load an entry with the total amount allocated to that fund by that source.
1461 -- This sum may reflect transfers as well as original allocations. We will
1462 -- reduce this balance whenever we attribute debits to it.
1464 CREATE TEMP TABLE t_fund_source_bal
1468 funding_source AS source,
1469 sum( amount ) AS balance
1478 CREATE INDEX t_fund_source_bal_idx
1479 ON t_fund_source_bal( fund, source );
1480 -------------------------------------------------------------------------------
1482 -- Load another temporary table. For each fund, load zero or more
1483 -- funding source credits from which that fund can get money.
1485 CREATE TEMP TABLE t_fund_credit (
1492 SELECT DISTINCT fund
1493 FROM acq.fund_allocation
1495 LOOP -- Loop over the funds
1501 acq.ordered_funding_source_credit AS ofsc
1503 ofsc.funding_source IN
1505 SELECT funding_source
1506 FROM acq.fund_allocation
1507 WHERE fund = fc.fund
1513 LOOP -- Add each credit to the list
1514 INSERT INTO t_fund_credit (
1523 --RAISE NOTICE 'Fund % credit %', fc.fund, sc.id;
1525 END LOOP; -- Loop over credits for a given fund
1526 END LOOP; -- Loop over funds
1528 CREATE INDEX t_fund_credit_idx
1529 ON t_fund_credit( fund, seq );
1530 -------------------------------------------------------------------------------
1532 -- Load yet another temporary table. This one is a list of funding source
1533 -- credits, with their balances. We shall reduce those balances as we
1534 -- attribute debits to them.
1536 CREATE TEMP TABLE t_credit
1540 fsc.funding_source AS source,
1541 fsc.amount AS balance,
1542 fs.currency_type AS currency_type
1544 acq.funding_source_credit AS fsc,
1545 acq.funding_source fs
1547 fsc.funding_source = fs.id
1550 CREATE INDEX t_credit_idx
1551 ON t_credit( credit );
1553 -------------------------------------------------------------------------------
1555 -- Now that we have loaded the lookup tables: loop through the debits,
1556 -- attributing each one to one or more funding source credits.
1558 truncate table acq.debit_attribution;
1576 --RAISE NOTICE 'Debit %, fund %', deb.id, deb.fund;
1578 debit_balance := deb.amount;
1580 -- Loop over the funding source credits that are eligible
1581 -- to pay for this debit
1593 --RAISE NOTICE ' Examining credit %', fund_credit.credit;
1595 -- Look up the balance for this credit. If it's zero, then
1596 -- it's not useful, so treat it as if you didn't find it.
1597 -- (Actually there shouldn't be any zero balances in the table,
1598 -- but we check just to make sure.)
1601 INTO curr_credit_bal
1604 credit = fund_credit.credit
1607 IF curr_credit_bal IS NULL THEN
1609 -- This credit is exhausted; try the next one.
1615 -- At this point we have an applicable credit with some money left.
1616 -- Now see if the relevant funding_source has any money left.
1618 -- Look up the balance of the allocation for this combination of
1619 -- fund and source. If you find such an entry, but it has a zero
1620 -- balance, then it's not useful, so treat it as unfound.
1621 -- (Actually there shouldn't be any zero balances in the table,
1622 -- but we check just to make sure.)
1625 INTO curr_fund_source_bal
1626 FROM t_fund_source_bal
1629 AND source = curr_credit_bal.source
1632 IF curr_fund_source_bal IS NULL THEN
1634 -- This fund/source doesn't exist or is already exhausted,
1635 -- so we can't use this credit. Go on to the next one.
1640 -- Convert the available balances to the currency of the fund
1642 conv_alloc_balance := curr_fund_source_bal.balance * acq.exchange_ratio(
1643 curr_credit_bal.currency_type, deb.currency_type );
1644 conv_cred_balance := curr_credit_bal.balance * acq.exchange_ratio(
1645 curr_credit_bal.currency_type, deb.currency_type );
1647 -- Determine how much we can attribute to this credit: the minimum
1648 -- of the debit amount, the fund/source balance, and the
1651 --RAISE NOTICE ' deb bal %', debit_balance;
1652 --RAISE NOTICE ' source % balance %', curr_credit_bal.source, conv_alloc_balance;
1653 --RAISE NOTICE ' credit % balance %', curr_credit_bal.credit, conv_cred_balance;
1655 conv_attr_amount := NULL;
1656 attr_amount := debit_balance;
1658 IF attr_amount > conv_alloc_balance THEN
1659 attr_amount := conv_alloc_balance;
1660 conv_attr_amount := curr_fund_source_bal.balance;
1662 IF attr_amount > conv_cred_balance THEN
1663 attr_amount := conv_cred_balance;
1664 conv_attr_amount := curr_credit_bal.balance;
1667 -- If we're attributing all of one of the balances, then that's how
1668 -- much we will deduct from the balances, and we already captured
1669 -- that amount above. Otherwise we must convert the amount of the
1670 -- attribution from the currency of the fund back to the currency of
1671 -- the funding source.
1673 IF conv_attr_amount IS NULL THEN
1674 conv_attr_amount := attr_amount * acq.exchange_ratio(
1675 deb.currency_type, curr_credit_bal.currency_type );
1678 -- Insert a row to record the attribution
1680 attrib_count := attrib_count + 1;
1681 INSERT INTO acq.debit_attribution (
1685 funding_source_credit,
1691 curr_credit_bal.credit,
1695 -- Subtract the attributed amount from the various balances
1697 debit_balance := debit_balance - attr_amount;
1698 curr_fund_source_bal.balance := curr_fund_source_bal.balance - conv_attr_amount;
1700 IF curr_fund_source_bal.balance <= 0 THEN
1702 -- This allocation is exhausted. Delete it so
1703 -- that we don't waste time looking at it again.
1705 DELETE FROM t_fund_source_bal
1707 fund = curr_fund_source_bal.fund
1708 AND source = curr_fund_source_bal.source;
1710 UPDATE t_fund_source_bal
1711 SET balance = balance - conv_attr_amount
1713 fund = curr_fund_source_bal.fund
1714 AND source = curr_fund_source_bal.source;
1717 IF curr_credit_bal.balance <= 0 THEN
1719 -- This funding source credit is exhausted. Delete it
1720 -- so that we don't waste time looking at it again.
1722 --DELETE FROM t_credit
1724 -- credit = curr_credit_bal.credit;
1726 DELETE FROM t_fund_credit
1728 credit = curr_credit_bal.credit;
1731 SET balance = curr_credit_bal.balance
1733 credit = curr_credit_bal.credit;
1736 -- Are we done with this debit yet?
1738 IF debit_balance <= 0 THEN
1739 EXIT; -- We've fully attributed this debit; stop looking at credits.
1741 END LOOP; -- End loop over credits
1743 IF debit_balance <> 0 THEN
1745 -- We weren't able to attribute this debit, or at least not
1746 -- all of it. Insert a row for the unattributed balance.
1748 attrib_count := attrib_count + 1;
1749 INSERT INTO acq.debit_attribution (
1753 funding_source_credit,
1763 END LOOP; -- End of loop over debits
1765 $$ LANGUAGE 'plpgsql';
1767 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_unit(
1771 ) RETURNS VOID AS $$
1782 IF old_year IS NULL THEN
1783 RAISE EXCEPTION 'Input year argument is NULL';
1784 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1785 RAISE EXCEPTION 'Input year is out of range';
1788 IF user_id IS NULL THEN
1789 RAISE EXCEPTION 'Input user id argument is NULL';
1792 IF org_unit_id IS NULL THEN
1793 RAISE EXCEPTION 'Org unit id argument is NULL';
1795 SELECT TRUE INTO org_found
1797 WHERE id = org_unit_id;
1799 IF org_found IS NULL THEN
1800 RAISE EXCEPTION 'Org unit id is invalid';
1804 -- Loop over the applicable funds
1806 FOR old_fund in SELECT * FROM acq.fund
1810 AND org = org_unit_id
1813 INSERT INTO acq.fund (
1825 old_fund.currency_type,
1830 RETURNING id INTO new_id;
1832 WHEN unique_violation THEN
1833 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
1836 --RAISE NOTICE 'Propagating fund % to fund %',
1837 -- old_fund.code, new_id;
1840 $$ LANGUAGE plpgsql;
1842 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_tree(
1846 ) RETURNS VOID AS $$
1857 IF old_year IS NULL THEN
1858 RAISE EXCEPTION 'Input year argument is NULL';
1859 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1860 RAISE EXCEPTION 'Input year is out of range';
1863 IF user_id IS NULL THEN
1864 RAISE EXCEPTION 'Input user id argument is NULL';
1867 IF org_unit_id IS NULL THEN
1868 RAISE EXCEPTION 'Org unit id argument is NULL';
1870 SELECT TRUE INTO org_found
1872 WHERE id = org_unit_id;
1874 IF org_found IS NULL THEN
1875 RAISE EXCEPTION 'Org unit id is invalid';
1879 -- Loop over the applicable funds
1881 FOR old_fund in SELECT * FROM acq.fund
1886 SELECT id FROM actor.org_unit_descendants( org_unit_id )
1890 INSERT INTO acq.fund (
1902 old_fund.currency_type,
1907 RETURNING id INTO new_id;
1909 WHEN unique_violation THEN
1910 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
1913 --RAISE NOTICE 'Propagating fund % to fund %',
1914 -- old_fund.code, new_id;
1917 $$ LANGUAGE plpgsql;
1919 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_unit(
1923 ) RETURNS VOID AS $$
1927 new_year INT := old_year + 1;
1929 xfer_amount NUMERIC;
1938 IF old_year IS NULL THEN
1939 RAISE EXCEPTION 'Input year argument is NULL';
1940 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1941 RAISE EXCEPTION 'Input year is out of range';
1944 IF user_id IS NULL THEN
1945 RAISE EXCEPTION 'Input user id argument is NULL';
1948 IF org_unit_id IS NULL THEN
1949 RAISE EXCEPTION 'Org unit id argument is NULL';
1952 -- Validate the org unit
1957 WHERE id = org_unit_id;
1959 IF org_found IS NULL THEN
1960 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
1964 -- Loop over the propagable funds to identify the details
1965 -- from the old fund plus the id of the new one, if it exists.
1969 oldf.id AS old_fund,
1975 newf.id AS new_fund_id
1978 LEFT JOIN acq.fund AS newf
1979 ON ( oldf.code = newf.code )
1981 oldf.org = org_unit_id
1982 and oldf.year = old_year
1984 and newf.year = new_year
1986 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
1988 IF roll_fund.new_fund_id IS NULL THEN
1990 -- The old fund hasn't been propagated yet. Propagate it now.
1992 INSERT INTO acq.fund (
2004 roll_fund.currency_type,
2009 RETURNING id INTO new_fund;
2011 new_fund = roll_fund.new_fund_id;
2014 -- Determine the amount to transfer
2018 FROM acq.fund_spent_balance
2019 WHERE fund = roll_fund.old_fund;
2021 IF xfer_amount <> 0 THEN
2022 IF roll_fund.rollover THEN
2024 -- Transfer balance from old fund to new
2026 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2028 PERFORM acq.transfer_fund(
2038 -- Transfer balance from old fund to the void
2040 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2042 PERFORM acq.transfer_fund(
2053 IF roll_fund.rollover THEN
2055 -- Move any lineitems from the old fund to the new one
2056 -- where the associated debit is an encumbrance.
2058 -- Any other tables tying expenditure details to funds should
2059 -- receive similar treatment. At this writing there are none.
2061 UPDATE acq.lineitem_detail
2064 fund = roll_fund.old_fund -- this condition may be redundant
2070 fund = roll_fund.old_fund
2074 -- Move encumbrance debits from the old fund to the new fund
2076 UPDATE acq.fund_debit
2079 fund = roll_fund.old_fund
2083 -- Mark old fund as inactive, now that we've closed it
2087 WHERE id = roll_fund.old_fund;
2090 $$ LANGUAGE plpgsql;
2092 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_tree(
2096 ) RETURNS VOID AS $$
2100 new_year INT := old_year + 1;
2102 xfer_amount NUMERIC;
2111 IF old_year IS NULL THEN
2112 RAISE EXCEPTION 'Input year argument is NULL';
2113 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2114 RAISE EXCEPTION 'Input year is out of range';
2117 IF user_id IS NULL THEN
2118 RAISE EXCEPTION 'Input user id argument is NULL';
2121 IF org_unit_id IS NULL THEN
2122 RAISE EXCEPTION 'Org unit id argument is NULL';
2125 -- Validate the org unit
2130 WHERE id = org_unit_id;
2132 IF org_found IS NULL THEN
2133 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
2137 -- Loop over the propagable funds to identify the details
2138 -- from the old fund plus the id of the new one, if it exists.
2142 oldf.id AS old_fund,
2148 newf.id AS new_fund_id
2151 LEFT JOIN acq.fund AS newf
2152 ON ( oldf.code = newf.code )
2154 oldf.year = old_year
2156 AND newf.year = new_year
2158 SELECT id FROM actor.org_unit_descendants( org_unit_id )
2161 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2163 IF roll_fund.new_fund_id IS NULL THEN
2165 -- The old fund hasn't been propagated yet. Propagate it now.
2167 INSERT INTO acq.fund (
2179 roll_fund.currency_type,
2184 RETURNING id INTO new_fund;
2186 new_fund = roll_fund.new_fund_id;
2189 -- Determine the amount to transfer
2193 FROM acq.fund_spent_balance
2194 WHERE fund = roll_fund.old_fund;
2196 IF xfer_amount <> 0 THEN
2197 IF roll_fund.rollover THEN
2199 -- Transfer balance from old fund to new
2201 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2203 PERFORM acq.transfer_fund(
2213 -- Transfer balance from old fund to the void
2215 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2217 PERFORM acq.transfer_fund(
2228 IF roll_fund.rollover THEN
2230 -- Move any lineitems from the old fund to the new one
2231 -- where the associated debit is an encumbrance.
2233 -- Any other tables tying expenditure details to funds should
2234 -- receive similar treatment. At this writing there are none.
2236 UPDATE acq.lineitem_detail
2239 fund = roll_fund.old_fund -- this condition may be redundant
2245 fund = roll_fund.old_fund
2249 -- Move encumbrance debits from the old fund to the new fund
2251 UPDATE acq.fund_debit
2254 fund = roll_fund.old_fund
2258 -- Mark old fund as inactive, now that we've closed it
2262 WHERE id = roll_fund.old_fund;
2265 $$ LANGUAGE plpgsql;
2267 CREATE OR REPLACE VIEW acq.funding_source_credit_total AS
2268 SELECT funding_source,
2269 SUM(amount) AS amount
2270 FROM acq.funding_source_credit
2273 CREATE OR REPLACE VIEW acq.funding_source_allocation_total AS
2274 SELECT funding_source,
2275 SUM(a.amount)::NUMERIC(100,2) AS amount
2276 FROM acq.fund_allocation a
2279 CREATE OR REPLACE VIEW acq.funding_source_balance AS
2280 SELECT COALESCE(c.funding_source, a.funding_source) AS funding_source,
2281 SUM(COALESCE(c.amount,0.0) - COALESCE(a.amount,0.0))::NUMERIC(100,2) AS amount
2282 FROM acq.funding_source_credit_total c
2283 FULL JOIN acq.funding_source_allocation_total a USING (funding_source)
2286 CREATE OR REPLACE VIEW acq.fund_allocation_total AS
2288 SUM(a.amount * acq.exchange_ratio(s.currency_type, f.currency_type))::NUMERIC(100,2) AS amount
2289 FROM acq.fund_allocation a
2290 JOIN acq.fund f ON (a.fund = f.id)
2291 JOIN acq.funding_source s ON (a.funding_source = s.id)
2294 CREATE OR REPLACE VIEW acq.fund_debit_total AS
2295 SELECT fund.id AS fund,
2296 fund_debit.encumbrance AS encumbrance,
2297 SUM( COALESCE( fund_debit.amount, 0 ) ) AS amount
2298 FROM acq.fund AS fund
2299 LEFT JOIN acq.fund_debit AS fund_debit
2300 ON ( fund.id = fund_debit.fund )
2303 CREATE OR REPLACE VIEW acq.fund_encumbrance_total AS
2305 SUM(amount) AS amount
2306 FROM acq.fund_debit_total
2307 WHERE encumbrance IS TRUE
2310 CREATE OR REPLACE VIEW acq.fund_spent_total AS
2312 SUM(amount) AS amount
2313 FROM acq.fund_debit_total
2314 WHERE encumbrance IS FALSE
2317 CREATE OR REPLACE VIEW acq.fund_combined_balance AS
2319 c.amount - COALESCE(d.amount,0.0) AS amount
2320 FROM acq.fund_allocation_total c
2321 LEFT JOIN acq.fund_debit_total d USING (fund);
2323 CREATE OR REPLACE VIEW acq.fund_spent_balance AS
2325 c.amount - COALESCE(d.amount,0.0) AS amount
2326 FROM acq.fund_allocation_total c
2327 LEFT JOIN acq.fund_spent_total d USING (fund);