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,
98 CREATE TABLE acq.provider_note (
99 id SERIAL PRIMARY KEY,
100 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
101 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
102 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
103 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
104 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
107 CREATE INDEX acq_pro_note_pro_idx ON acq.provider_note ( provider );
108 CREATE INDEX acq_pro_note_creator_idx ON acq.provider_note ( creator );
109 CREATE INDEX acq_pro_note_editor_idx ON acq.provider_note ( editor );
112 CREATE TABLE acq.funding_source (
113 id SERIAL PRIMARY KEY,
115 owner INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
116 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
118 CONSTRAINT funding_source_name_once_per_owner UNIQUE (name,owner)
121 CREATE TABLE acq.funding_source_credit (
122 id SERIAL PRIMARY KEY,
123 funding_source INT NOT NULL REFERENCES acq.funding_source (id) DEFERRABLE INITIALLY DEFERRED,
124 amount NUMERIC NOT NULL,
126 deadline_date TIMESTAMPTZ,
127 effective_date TIMESTAMPTZ NOT NULL default now()
130 CREATE VIEW acq.ordered_funding_source_credit AS
132 CASE WHEN deadline_date IS NULL THEN
136 END AS sort_priority,
137 CASE WHEN deadline_date IS NULL THEN
147 acq.funding_source_credit;
149 COMMENT ON VIEW acq.ordered_funding_source_credit IS $$
151 * Copyright (C) 2009 Georgia Public Library Service
152 * Scott McKellar <scott@gmail.com>
154 * The acq.ordered_funding_source_credit view is a prioritized
155 * ordering of funding source credits. When ordered by the first
156 * three columns, this view defines the order in which the various
157 * credits are to be tapped for spending, subject to the allocations
158 * in the acq.fund_allocation table.
160 * The first column reflects the principle that we should spend
161 * money with deadlines before spending money without deadlines.
163 * The second column reflects the principle that we should spend the
164 * oldest money first. For money with deadlines, that means that we
165 * spend first from the credit with the earliest deadline. For
166 * money without deadlines, we spend first from the credit with the
167 * earliest effective date.
169 * The third column is a tie breaker to ensure a consistent
174 * This program is free software; you can redistribute it and/or
175 * modify it under the terms of the GNU General Public License
176 * as published by the Free Software Foundation; either version 2
177 * of the License, or (at your option) any later version.
179 * This program is distributed in the hope that it will be useful,
180 * but WITHOUT ANY WARRANTY; without even the implied warranty of
181 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
182 * GNU General Public License for more details.
186 CREATE TABLE acq.fund (
187 id SERIAL PRIMARY KEY,
188 org INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
190 year INT NOT NULL DEFAULT EXTRACT( YEAR FROM NOW() ),
191 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
193 rollover BOOL NOT NULL DEFAULT FALSE,
194 propagate BOOL NOT NULL DEFAULT TRUE,
195 active BOOL NOT NULL DEFAULT TRUE,
196 balance_warning_percent INT CONSTRAINT balance_warning_percent_limit
197 CHECK( balance_warning_percent <= 100 ),
198 balance_stop_percent INT CONSTRAINT balance_stop_percent_limit
199 CHECK( balance_stop_percent <= 100 ),
200 CONSTRAINT name_once_per_org_year UNIQUE (org,name,year),
201 CONSTRAINT code_once_per_org_year UNIQUE (org, code, year),
202 CONSTRAINT acq_fund_rollover_implies_propagate CHECK ( propagate OR NOT rollover )
205 CREATE TABLE acq.fund_debit (
206 id SERIAL PRIMARY KEY,
207 fund INT NOT NULL REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
208 origin_amount NUMERIC NOT NULL, -- pre-exchange-rate amount
209 origin_currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
210 amount NUMERIC NOT NULL,
211 encumbrance BOOL NOT NULL DEFAULT TRUE,
212 debit_type TEXT NOT NULL,
213 xfer_destination INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
214 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
217 CREATE TABLE acq.fund_allocation (
218 id SERIAL PRIMARY KEY,
219 funding_source INT NOT NULL REFERENCES acq.funding_source (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
220 fund INT NOT NULL REFERENCES acq.fund (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
221 amount NUMERIC NOT NULL,
222 allocator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
224 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
226 CREATE INDEX fund_alloc_allocator_idx ON acq.fund_allocation ( allocator );
228 CREATE TABLE acq.fund_allocation_percent
230 id SERIAL PRIMARY KEY,
231 funding_source INT NOT NULL REFERENCES acq.funding_source
232 DEFERRABLE INITIALLY DEFERRED,
233 org INT NOT NULL REFERENCES actor.org_unit
234 DEFERRABLE INITIALLY DEFERRED,
236 percent NUMERIC NOT NULL,
237 allocator INTEGER NOT NULL REFERENCES actor.usr
238 DEFERRABLE INITIALLY DEFERRED,
240 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
241 CONSTRAINT logical_key UNIQUE( funding_source, org, fund_code ),
242 CONSTRAINT percentage_range CHECK( percent >= 0 AND percent <= 100 )
245 -- Trigger function to validate combination of org_unit and fund_code
247 CREATE OR REPLACE FUNCTION acq.fund_alloc_percent_val()
248 RETURNS TRIGGER AS $$
263 AND code = NEW.fund_code
269 RAISE EXCEPTION 'No fund exists for org % and code %', NEW.org, NEW.fund_code;
274 CREATE TRIGGER acq_fund_alloc_percent_val_trig
275 BEFORE INSERT OR UPDATE ON acq.fund_allocation_percent
276 FOR EACH ROW EXECUTE PROCEDURE acq.fund_alloc_percent_val();
278 -- To do: trigger to verify that percentages don't add up to more than 100
280 CREATE OR REPLACE FUNCTION acq.fap_limit_100()
281 RETURNS TRIGGER AS $$
284 total_percent numeric;
292 acq.fund_allocation_percent AS fap
294 fap.funding_source = NEW.funding_source;
296 IF total_percent > 100 THEN
297 RAISE EXCEPTION 'Total percentages exceed 100 for funding_source %',
305 CREATE TRIGGER acqfap_limit_100_trig
306 AFTER INSERT OR UPDATE ON acq.fund_allocation_percent
307 FOR EACH ROW EXECUTE PROCEDURE acq.fap_limit_100();
309 CREATE TABLE acq.picklist (
310 id SERIAL PRIMARY KEY,
311 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
312 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
313 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
314 org_unit INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
316 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
317 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
318 CONSTRAINT name_once_per_owner UNIQUE (name,owner)
320 CREATE INDEX acq_picklist_owner_idx ON acq.picklist ( owner );
321 CREATE INDEX acq_picklist_creator_idx ON acq.picklist ( creator );
322 CREATE INDEX acq_picklist_editor_idx ON acq.picklist ( editor );
324 CREATE TABLE acq.purchase_order (
325 id SERIAL PRIMARY KEY,
326 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
327 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
328 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
329 ordering_agency INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
330 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
331 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
332 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
333 state TEXT NOT NULL DEFAULT 'new',
334 order_date TIMESTAMP WITH TIME ZONE,
337 CREATE INDEX po_owner_idx ON acq.purchase_order (owner);
338 CREATE INDEX po_provider_idx ON acq.purchase_order (provider);
339 CREATE INDEX po_state_idx ON acq.purchase_order (state);
340 CREATE INDEX po_creator_idx ON acq.purchase_order ( creator );
341 CREATE INDEX po_editor_idx ON acq.purchase_order ( editor );
342 CREATE INDEX acq_po_org_name_order_date_idx ON acq.purchase_order( ordering_agency, name, order_date );
344 -- The name should default to the id, as text. We can't reference a column
345 -- in a DEFAULT clause, so we use a trigger:
347 CREATE OR REPLACE FUNCTION acq.purchase_order_name_default () RETURNS TRIGGER
350 IF NEW.name IS NULL THEN
351 NEW.name := NEW.id::TEXT;
358 CREATE TRIGGER po_name_default_trg
359 BEFORE INSERT OR UPDATE ON acq.purchase_order
360 FOR EACH ROW EXECUTE PROCEDURE acq.purchase_order_name_default ();
362 -- The order name should be unique for a given ordering agency on a given order date
363 -- (truncated to midnight), but only where the order_date is not NULL. Conceptually
364 -- this rule requires a check constraint with a subquery. However you can't have a
365 -- subquery in a CHECK constraint, so we fake it with a trigger.
367 CREATE OR REPLACE FUNCTION acq.po_org_name_date_unique () RETURNS TRIGGER
373 -- If order_date is not null, then make sure we don't have a collision
374 -- on order_date (truncated to day), org, and name
376 IF NEW.order_date IS NULL THEN
380 -- In the WHERE clause, we compare the order_dates without regard to time of day.
381 -- We use a pair of inequalities instead of comparing truncated dates so that the
382 -- query can do an indexed range scan.
384 SELECT 1 INTO collision
385 FROM acq.purchase_order
387 ordering_agency = NEW.ordering_agency
389 AND order_date >= date_trunc( 'day', NEW.order_date )
390 AND order_date < date_trunc( 'day', NEW.order_date ) + '1 day'::INTERVAL
393 IF collision IS NULL THEN
394 -- okay, no collision
397 -- collision; nip it in the bud
398 RAISE EXCEPTION 'Colliding purchase orders: ordering_agency %, date %, name ''%''',
399 NEW.ordering_agency, NEW.order_date, NEW.name;
404 CREATE TRIGGER po_org_name_date_unique_trg
405 BEFORE INSERT OR UPDATE ON acq.purchase_order
406 FOR EACH ROW EXECUTE PROCEDURE acq.po_org_name_date_unique ();
408 CREATE TABLE acq.po_note (
409 id SERIAL PRIMARY KEY,
410 purchase_order INT NOT NULL REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
411 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
412 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
413 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
414 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
417 CREATE INDEX po_note_po_idx ON acq.po_note (purchase_order);
418 CREATE INDEX acq_po_note_creator_idx ON acq.po_note ( creator );
419 CREATE INDEX acq_po_note_editor_idx ON acq.po_note ( editor );
421 CREATE TABLE acq.lineitem (
422 id BIGSERIAL PRIMARY KEY,
423 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
424 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
425 selector INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
426 provider INT REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
427 purchase_order INT REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
428 picklist INT REFERENCES acq.picklist (id) DEFERRABLE INITIALLY DEFERRED,
429 expected_recv_time TIMESTAMP WITH TIME ZONE,
430 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
431 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
433 eg_bib_id INT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
435 state TEXT NOT NULL DEFAULT 'new',
436 CONSTRAINT picklist_or_po CHECK (picklist IS NOT NULL OR purchase_order IS NOT NULL)
438 CREATE INDEX li_po_idx ON acq.lineitem (purchase_order);
439 CREATE INDEX li_pl_idx ON acq.lineitem (picklist);
440 CREATE INDEX li_creator_idx ON acq.lineitem ( creator );
441 CREATE INDEX li_editor_idx ON acq.lineitem ( editor );
442 CREATE INDEX li_selector_idx ON acq.lineitem ( selector );
444 CREATE TABLE acq.lineitem_alert_text (
445 id SERIAL PRIMARY KEY,
448 owning_lib INT NOT NULL
449 REFERENCES actor.org_unit(id)
450 DEFERRABLE INITIALLY DEFERRED,
451 CONSTRAINT alert_one_code_per_org UNIQUE (code, owning_lib)
454 CREATE TABLE acq.lineitem_note (
455 id SERIAL PRIMARY KEY,
456 lineitem INT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
457 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
458 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
459 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
460 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
462 alert_text INT REFERENCES acq.lineitem_alert_text(id)
463 DEFERRABLE INITIALLY DEFERRED
465 CREATE INDEX li_note_li_idx ON acq.lineitem_note (lineitem);
466 CREATE INDEX li_note_creator_idx ON acq.lineitem_note ( creator );
467 CREATE INDEX li_note_editor_idx ON acq.lineitem_note ( editor );
469 CREATE TABLE acq.lineitem_detail (
470 id BIGSERIAL PRIMARY KEY,
471 lineitem INT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
472 fund INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
473 fund_debit INT REFERENCES acq.fund_debit (id) DEFERRABLE INITIALLY DEFERRED,
474 eg_copy_id BIGINT REFERENCES asset.copy (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
478 collection_code TEXT,
479 circ_modifier TEXT REFERENCES config.circ_modifier (code) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
480 owning_lib INT REFERENCES actor.org_unit (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
481 location INT REFERENCES asset.copy_location (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
482 recv_time TIMESTAMP WITH TIME ZONE
485 CREATE INDEX li_detail_li_idx ON acq.lineitem_detail (lineitem);
487 CREATE TABLE acq.lineitem_attr_definition (
488 id BIGSERIAL PRIMARY KEY,
490 description TEXT NOT NULL,
491 remove TEXT NOT NULL DEFAULT '',
492 ident BOOL NOT NULL DEFAULT FALSE
495 CREATE TABLE acq.lineitem_marc_attr_definition (
496 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
498 ) INHERITS (acq.lineitem_attr_definition);
500 CREATE TABLE acq.lineitem_provider_attr_definition (
501 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
503 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED
504 ) INHERITS (acq.lineitem_attr_definition);
506 CREATE TABLE acq.lineitem_generated_attr_definition (
507 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
509 ) INHERITS (acq.lineitem_attr_definition);
511 CREATE TABLE acq.lineitem_usr_attr_definition (
512 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
513 usr INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED
514 ) INHERITS (acq.lineitem_attr_definition);
515 CREATE INDEX li_usr_attr_def_usr_idx ON acq.lineitem_usr_attr_definition ( usr );
517 CREATE TABLE acq.lineitem_local_attr_definition (
518 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq')
519 ) INHERITS (acq.lineitem_attr_definition);
521 CREATE TABLE acq.lineitem_attr (
522 id BIGSERIAL PRIMARY KEY,
523 definition BIGINT NOT NULL,
524 lineitem BIGINT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
525 attr_type TEXT NOT NULL,
526 attr_name TEXT NOT NULL,
527 attr_value TEXT NOT NULL
530 CREATE INDEX li_attr_li_idx ON acq.lineitem_attr (lineitem);
531 CREATE INDEX li_attr_value_idx ON acq.lineitem_attr (attr_value);
532 CREATE INDEX li_attr_definition_idx ON acq.lineitem_attr (definition);
538 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('title','Title of work','//*[@tag="245"]/*[contains("abcmnopr",@code)]');
539 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)]');
540 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('language','Language of work','//*[@tag="240"]/*[@code="l"][1]');
541 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pagination','Pagination','//*[@tag="300"]/*[@code="a"][1]');
542 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('isbn','ISBN','//*[@tag="020"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
543 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('issn','ISSN','//*[@tag="022"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
544 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('price','Price','//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
545 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('identifier','Identifier','//*[@tag="001"]');
546 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('publisher','Publisher','//*[@tag="260"]/*[@code="b"][1]');
547 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pubdate','Publication Date','//*[@tag="260"]/*[@code="c"][1]');
548 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('edition','Edition','//*[@tag="250"]/*[@code="a"][1]');
550 INSERT INTO acq.lineitem_local_attr_definition ( code, description ) VALUES ('estimated_price', 'Estimated Price');
553 CREATE TABLE acq.distribution_formula (
554 id SERIAL PRIMARY KEY,
556 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
558 skip_count INT NOT NULL DEFAULT 0,
559 CONSTRAINT acqdf_name_once_per_owner UNIQUE (name, owner)
562 CREATE TABLE acq.distribution_formula_entry (
563 id SERIAL PRIMARY KEY,
564 formula INTEGER NOT NULL REFERENCES acq.distribution_formula(id)
566 DEFERRABLE INITIALLY DEFERRED,
567 position INTEGER NOT NULL,
568 item_count INTEGER NOT NULL,
569 owning_lib INTEGER REFERENCES actor.org_unit(id)
570 DEFERRABLE INITIALLY DEFERRED,
571 location INTEGER REFERENCES asset.copy_location(id),
572 CONSTRAINT acqdfe_lib_once_per_formula UNIQUE( formula, position ),
573 CONSTRAINT acqdfe_must_be_somewhere
574 CHECK( owning_lib IS NOT NULL OR location IS NOT NULL )
577 CREATE TABLE acq.distribution_formula_application (
578 id BIGSERIAL PRIMARY KEY,
579 creator INT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED,
580 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
582 REFERENCES acq.distribution_formula(id) DEFERRABLE INITIALLY DEFERRED,
583 lineitem INT NOT NULL
584 REFERENCES acq.lineitem(id) DEFERRABLE INITIALLY DEFERRED
587 CREATE INDEX acqdfa_df_idx
588 ON acq.distribution_formula_application(formula);
589 CREATE INDEX acqdfa_li_idx
590 ON acq.distribution_formula_application(lineitem);
591 CREATE INDEX acqdfa_creator_idx
592 ON acq.distribution_formula_application(creator);
594 CREATE TABLE acq.fund_tag (
595 id SERIAL PRIMARY KEY,
597 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
599 CONSTRAINT acqft_tag_once_per_owner UNIQUE (name, owner)
602 CREATE TABLE acq.fund_tag_map (
603 id SERIAL PRIMARY KEY,
604 fund INTEGER NOT NULL REFERENCES acq.fund(id)
605 DEFERRABLE INITIALLY DEFERRED,
606 tag INTEGER REFERENCES acq.fund_tag(id)
608 DEFERRABLE INITIALLY DEFERRED,
609 CONSTRAINT acqftm_fund_once_per_tag UNIQUE( fund, tag )
612 CREATE TABLE acq.fund_transfer (
613 id SERIAL PRIMARY KEY,
614 src_fund INT NOT NULL REFERENCES acq.fund( id )
615 DEFERRABLE INITIALLY DEFERRED,
616 src_amount NUMERIC NOT NULL,
617 dest_fund INT NOT NULL REFERENCES acq.fund( id )
618 DEFERRABLE INITIALLY DEFERRED,
619 dest_amount NUMERIC NOT NULL,
620 transfer_time TIMESTAMPTZ NOT NULL DEFAULT now(),
621 transfer_user INT NOT NULL REFERENCES actor.usr( id )
622 DEFERRABLE INITIALLY DEFERRED,
624 funding_source_credit INT NOT NULL REFERENCES acq.funding_source_credit( id )
625 DEFERRABLE INITIALLY DEFERRED
628 CREATE INDEX acqftr_usr_idx
629 ON acq.fund_transfer( transfer_user );
631 COMMENT ON TABLE acq.fund_transfer IS $$
633 * Copyright (C) 2009 Georgia Public Library Service
634 * Scott McKellar <scott@esilibrary.com>
638 * Each row represents the transfer of money from a source fund
639 * to a destination fund. There should be corresponding entries
640 * in acq.fund_allocation. The purpose of acq.fund_transfer is
641 * to record how much money moved from which fund to which other
644 * The presence of two amount fields, rather than one, reflects
645 * the possibility that the two funds are denominated in different
646 * currencies. If they use the same currency type, the two
647 * amounts should be the same.
651 * This program is free software; you can redistribute it and/or
652 * modify it under the terms of the GNU General Public License
653 * as published by the Free Software Foundation; either version 2
654 * of the License, or (at your option) any later version.
656 * This program is distributed in the hope that it will be useful,
657 * but WITHOUT ANY WARRANTY; without even the implied warranty of
658 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
659 * GNU General Public License for more details.
663 CREATE TABLE acq.fiscal_calendar (
664 id SERIAL PRIMARY KEY,
668 -- Create a default calendar (though we don't specify its contents).
669 -- Create a foreign key in actor.org_unit, initially pointing to
670 -- the default calendar.
672 INSERT INTO acq.fiscal_calendar (
679 ALTER TABLE actor.org_unit ADD FOREIGN KEY
680 (fiscal_calendar) REFERENCES acq.fiscal_calendar( id )
681 DEFERRABLE INITIALLY DEFERRED;
683 CREATE TABLE acq.fiscal_year (
684 id SERIAL PRIMARY KEY,
685 calendar INT NOT NULL
686 REFERENCES acq.fiscal_calendar
688 DEFERRABLE INITIALLY DEFERRED,
690 year_begin TIMESTAMPTZ NOT NULL,
691 year_end TIMESTAMPTZ NOT NULL,
692 CONSTRAINT acq_fy_logical_key UNIQUE ( calendar, year ),
693 CONSTRAINT acq_fy_physical_key UNIQUE ( calendar, year_begin )
696 CREATE TABLE acq.edi_account ( -- similar tables can extend remote_account for other parts of EG
697 provider INT NOT NULL REFERENCES acq.provider (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
698 in_dir TEXT -- incoming messages dir (probably different than config.remote_account.path, the outgoing dir)
699 ) INHERITS (config.remote_account);
701 -- We need a UNIQUE constraint here also, to support the FK from acq.provider.edi_default
702 ALTER TABLE acq.edi_account ADD CONSTRAINT acq_edi_account_id_unique UNIQUE (id);
704 -- Note below that the primary key is NOT a SERIAL type. We will periodically truncate and rebuild
705 -- the table, assigning ids programmatically instead of using a sequence.
706 CREATE TABLE acq.debit_attribution (
707 id INT NOT NULL PRIMARY KEY,
708 fund_debit INT NOT NULL
709 REFERENCES acq.fund_debit
710 DEFERRABLE INITIALLY DEFERRED,
711 debit_amount NUMERIC NOT NULL,
712 funding_source_credit INT REFERENCES acq.funding_source_credit
713 DEFERRABLE INITIALLY DEFERRED,
714 credit_amount NUMERIC
717 CREATE INDEX acq_attribution_debit_idx
718 ON acq.debit_attribution( fund_debit );
720 CREATE INDEX acq_attribution_credit_idx
721 ON acq.debit_attribution( funding_source_credit );
725 CREATE TABLE acq.invoice_method (
726 code TEXT PRIMARY KEY,
727 name TEXT NOT NULL -- i18n-ize
730 CREATE TABLE acq.invoice (
731 id SERIAL PRIMARY KEY,
732 receiver INT NOT NULL REFERENCES actor.org_unit (id),
733 provider INT NOT NULL REFERENCES acq.provider (id),
734 shipper INT NOT NULL REFERENCES acq.provider (id),
735 recv_date TIMESTAMPTZ NOT NULL DEFAULT NOW(),
736 recv_method TEXT NOT NULL REFERENCES acq.invoice_method (code) DEFAULT 'EDI',
737 inv_type TEXT, -- A "type" field is desired, but no idea what goes here
738 inv_ident TEXT NOT NULL -- vendor-supplied invoice id/number
741 CREATE TABLE acq.invoice_entry (
742 id SERIAL PRIMARY KEY,
743 invoice INT NOT NULL REFERENCES acq.invoice (id) ON DELETE CASCADE,
744 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
745 lineitem INT REFERENCES acq.lineitem (id) ON UPDATE CASCADE ON DELETE SET NULL,
746 inv_item_count INT NOT NULL, -- How many acqlids did they say they sent
747 phys_item_count INT, -- and how many did staff count
749 billed_per_item BOOL,
750 cost_billed NUMERIC(8,2),
751 actual_cost NUMERIC(8,2)
754 CREATE TABLE acq.invoice_item_type (
755 code TEXT PRIMARY KEY,
756 name TEXT NOT NULL -- i18n-ize
759 CREATE TABLE acq.invoice_item ( -- for invoice-only debits: taxes/fees/non-bib items/etc
760 id SERIAL PRIMARY KEY,
761 invoice INT NOT NULL REFERENCES acq.invoice (id) ON UPDATE CASCADE ON DELETE CASCADE,
762 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
763 fund_debit INT REFERENCES acq.fund_debit (id),
764 inv_item_type TEXT NOT NULL REFERENCES acq.invoice_item_type (code),
768 cost_billed NUMERIC(8,2),
769 actual_cost NUMERIC(8,2)
773 CREATE TABLE acq.user_request_type (
774 id SERIAL PRIMARY KEY,
775 label TEXT NOT NULL UNIQUE -- i18n-ize
778 INSERT INTO acq.user_request_type (id,label) VALUES (1, oils_i18n_gettext('1', 'Books', 'aurt', 'label'));
779 INSERT INTO acq.user_request_type (id,label) VALUES (2, oils_i18n_gettext('2', 'Journal/Magazine & Newspaper Articles', 'aurt', 'label'));
780 INSERT INTO acq.user_request_type (id,label) VALUES (3, oils_i18n_gettext('3', 'Audiobooks', 'aurt', 'label'));
781 INSERT INTO acq.user_request_type (id,label) VALUES (4, oils_i18n_gettext('4', 'Music', 'aurt', 'label'));
782 INSERT INTO acq.user_request_type (id,label) VALUES (5, oils_i18n_gettext('5', 'DVDs', 'aurt', 'label'));
784 SELECT SETVAL('acq.user_request_type_id_seq'::TEXT, 6);
786 CREATE TABLE acq.user_request (
787 id SERIAL PRIMARY KEY,
788 usr INT NOT NULL REFERENCES actor.usr (id), -- requesting user
789 hold BOOL NOT NULL DEFAULT TRUE,
791 pickup_lib INT NOT NULL REFERENCES actor.org_unit (id), -- pickup lib
792 holdable_formats TEXT, -- nullable, for use in hold creation
794 email_notify BOOL NOT NULL DEFAULT TRUE,
795 lineitem INT REFERENCES acq.lineitem (id) ON DELETE CASCADE,
796 eg_bib BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
797 request_date TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- when they requested it
798 need_before TIMESTAMPTZ, -- don't create holds after this
801 request_type INT NOT NULL REFERENCES acq.user_request_type (id),
818 CREATE TYPE acq.flat_lineitem_holding_subfield AS (lineitem int, holding int, subfield text, data text);
819 CREATE OR REPLACE FUNCTION acq.extract_holding_attr_table (lineitem int, tag text) RETURNS SETOF acq.flat_lineitem_holding_subfield AS $$
822 lida acq.flat_lineitem_holding_subfield%ROWTYPE;
825 SELECT COUNT(*) INTO counter
826 FROM oils_xpath_table(
830 '//*[@tag="' || tag || '"]',
832 ) as t(i int,c text);
834 FOR i IN 1 .. counter LOOP
837 FROM ( SELECT id,i,t,v
838 FROM oils_xpath_table(
842 '//*[@tag="' || tag || '"][position()=' || i || ']/*/@code|' ||
843 '//*[@tag="' || tag || '"][position()=' || i || ']/*[@code]',
845 ) as t(id int,t text,v text)
856 CREATE TYPE acq.flat_lineitem_detail AS (lineitem int, holding int, attr text, data text);
857 CREATE OR REPLACE FUNCTION acq.extract_provider_holding_data ( lineitem_i int ) RETURNS SETOF acq.flat_lineitem_detail AS $$
861 lida acq.flat_lineitem_detail%ROWTYPE;
863 SELECT provider INTO prov_i FROM acq.lineitem WHERE id = lineitem_i;
864 IF NOT FOUND THEN RETURN; END IF;
866 SELECT holding_tag INTO tag_t FROM acq.provider WHERE id = prov_i;
867 IF NOT FOUND OR tag_t IS NULL THEN RETURN; END IF;
874 FROM acq.extract_holding_attr_table( lineitem_i, tag_t ) h
875 JOIN acq.provider_holding_subfield_map a USING (subfield)
876 WHERE a.provider = prov_i
885 -- select * from acq.extract_provider_holding_data(699);
887 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field ( BIGINT, TEXT, TEXT) RETURNS TEXT AS $$
888 SELECT public.extract_marc_field('acq.lineitem', $1, $2, $3);
892 CREATE OR REPLACE FUNCTION public.extract_bib_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
893 SELECT public.extract_marc_field('biblio.record_entry', $1, $2);
896 CREATE OR REPLACE FUNCTION public.extract_authority_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
897 SELECT public.extract_marc_field('authority.record_entry', $1, $2);
901 -- INSERT INTO acq.lineitem_provider_attr_definition ( provider, code, description, xpath ) VALUES (1,'price','Price','//*[@tag="020" or @tag="022"]/*[@code="a"][1]');
904 Suggested vendor fields:
912 CREATE OR REPLACE FUNCTION public.ingest_acq_marc ( ) RETURNS TRIGGER AS $$
920 FOR adef IN SELECT *,tableoid FROM acq.lineitem_attr_definition LOOP
922 SELECT relname::TEXT INTO atype FROM pg_class WHERE oid = adef.tableoid;
924 IF (atype NOT IN ('lineitem_usr_attr_definition','lineitem_local_attr_definition')) THEN
925 IF (atype = 'lineitem_provider_attr_definition') THEN
926 SELECT provider INTO prov FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
927 CONTINUE WHEN NEW.provider IS NULL OR prov <> NEW.provider;
930 IF (atype = 'lineitem_provider_attr_definition') THEN
931 SELECT xpath INTO xpath_string FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
932 ELSIF (atype = 'lineitem_marc_attr_definition') THEN
933 SELECT xpath INTO xpath_string FROM acq.lineitem_marc_attr_definition WHERE id = adef.id;
934 ELSIF (atype = 'lineitem_generated_attr_definition') THEN
935 SELECT xpath INTO xpath_string FROM acq.lineitem_generated_attr_definition WHERE id = adef.id;
938 SELECT extract_acq_marc_field(id, xpath_string, adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
940 IF (value IS NOT NULL AND value <> '') THEN
941 INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
942 VALUES (NEW.id, adef.id, atype, adef.code, value);
953 CREATE OR REPLACE FUNCTION public.cleanup_acq_marc ( ) RETURNS TRIGGER AS $$
955 IF TG_OP = 'UPDATE' THEN
956 DELETE FROM acq.lineitem_attr
957 WHERE lineitem = OLD.id AND attr_type IN ('lineitem_provider_attr_definition', 'lineitem_marc_attr_definition','lineitem_generated_attr_definition');
960 DELETE FROM acq.lineitem_attr WHERE lineitem = OLD.id;
966 CREATE TRIGGER cleanup_lineitem_trigger
967 BEFORE UPDATE OR DELETE ON acq.lineitem
968 FOR EACH ROW EXECUTE PROCEDURE public.cleanup_acq_marc();
970 CREATE TRIGGER ingest_lineitem_trigger
971 AFTER INSERT OR UPDATE ON acq.lineitem
972 FOR EACH ROW EXECUTE PROCEDURE public.ingest_acq_marc();
974 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( from_ex TEXT, to_ex TEXT ) RETURNS NUMERIC AS $$
978 IF from_ex = to_ex THEN
982 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = from_ex AND to_currency = to_ex;
987 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = to_ex AND to_currency = from_ex;
998 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( TEXT, TEXT, NUMERIC ) RETURNS NUMERIC AS $$
999 SELECT $3 * acq.exchange_ratio($1, $2);
1002 CREATE OR REPLACE FUNCTION acq.find_bad_fy()
1004 Examine the acq.fiscal_year table, comparing successive years.
1005 Report any inconsistencies, i.e. years that overlap, have gaps
1006 between them, or are out of sequence.
1008 RETURNS SETOF RECORD AS $$
1032 ELSIF curr_year.calendar = prev_year.calendar THEN
1033 IF curr_year.year_begin > prev_year.year_end THEN
1034 -- This ugly kludge works around the fact that older
1035 -- versions of PostgreSQL don't support RETURN QUERY SELECT
1036 FOR return_rec IN SELECT
1039 'Gap between fiscal years'::TEXT
1041 RETURN NEXT return_rec;
1043 ELSIF curr_year.year_begin < prev_year.year_end THEN
1044 FOR return_rec IN SELECT
1047 'Overlapping fiscal years'::TEXT
1049 RETURN NEXT return_rec;
1051 ELSIF curr_year.year < prev_year.year THEN
1052 FOR return_rec IN SELECT
1055 'Fiscal years out of order'::TEXT
1057 RETURN NEXT return_rec;
1062 prev_year := curr_year;
1067 $$ LANGUAGE plpgsql;
1069 CREATE OR REPLACE FUNCTION acq.transfer_fund(
1071 old_amount IN NUMERIC, -- in currency of old fund
1073 new_amount IN NUMERIC, -- in currency of new fund
1075 xfer_note IN TEXT -- to be recorded in acq.fund_transfer
1076 -- ,funding_source_in IN INT -- if user wants to specify a funding source (see notes)
1077 ) RETURNS VOID AS $$
1078 /* -------------------------------------------------------------------------------
1080 Function to transfer money from one fund to another.
1082 A transfer is represented as a pair of entries in acq.fund_allocation, with a
1083 negative amount for the old (losing) fund and a positive amount for the new
1084 (gaining) fund. In some cases there may be more than one such pair of entries
1085 in order to pull the money from different funding sources, or more specifically
1086 from different funding source credits. For each such pair there is also an
1087 entry in acq.fund_transfer.
1089 Since funding_source is a non-nullable column in acq.fund_allocation, we must
1090 choose a funding source for the transferred money to come from. This choice
1091 must meet two constraints, so far as possible:
1093 1. The amount transferred from a given funding source must not exceed the
1094 amount allocated to the old fund by the funding source. To that end we
1095 compare the amount being transferred to the amount allocated.
1097 2. We shouldn't transfer money that has already been spent or encumbered, as
1098 defined by the funding attribution process. We attribute expenses to the
1099 oldest funding source credits first. In order to avoid transferring that
1100 attributed money, we reverse the priority, transferring from the newest funding
1101 source credits first. There can be no guarantee that this approach will
1102 avoid overcommitting a fund, but no other approach can do any better.
1104 In this context the age of a funding source credit is defined by the
1105 deadline_date for credits with deadline_dates, and by the effective_date for
1106 credits without deadline_dates, with the proviso that credits with deadline_dates
1107 are all considered "older" than those without.
1111 In the signature for this function, there is one last parameter commented out,
1112 named "funding_source_in". Correspondingly, the WHERE clause for the query
1113 driving the main loop has an OR clause commented out, which references the
1114 funding_source_in parameter.
1116 If these lines are uncommented, this function will allow the user optionally to
1117 restrict a fund transfer to a specified funding source. If the source
1118 parameter is left NULL, then there will be no such restriction.
1120 ------------------------------------------------------------------------------- */
1122 same_currency BOOLEAN;
1123 currency_ratio NUMERIC;
1124 old_fund_currency TEXT;
1125 old_remaining NUMERIC; -- in currency of old fund
1126 new_fund_currency TEXT;
1127 new_fund_active BOOLEAN;
1128 new_remaining NUMERIC; -- in currency of new fund
1129 curr_old_amt NUMERIC; -- in currency of old fund
1130 curr_new_amt NUMERIC; -- in currency of new fund
1131 source_addition NUMERIC; -- in currency of funding source
1132 source_deduction NUMERIC; -- in currency of funding source
1133 orig_allocated_amt NUMERIC; -- in currency of funding source
1134 allocated_amt NUMERIC; -- in currency of fund
1140 IF old_fund IS NULL THEN
1141 RAISE EXCEPTION 'acq.transfer_fund: old fund id is NULL';
1144 IF old_amount IS NULL THEN
1145 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer is NULL';
1148 -- The new fund and its amount must be both NULL or both not NULL.
1150 IF new_fund IS NOT NULL AND new_amount IS NULL THEN
1151 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer to receiving fund is NULL';
1154 IF new_fund IS NULL AND new_amount IS NOT NULL THEN
1155 RAISE EXCEPTION 'acq.transfer_fund: receiving fund is NULL, its amount is not NULL';
1158 IF user_id IS NULL THEN
1159 RAISE EXCEPTION 'acq.transfer_fund: user id is NULL';
1162 -- Initialize the amounts to be transferred, each denominated
1163 -- in the currency of its respective fund. They will be
1164 -- reduced on each iteration of the loop.
1166 old_remaining := old_amount;
1167 new_remaining := new_amount;
1169 -- RAISE NOTICE 'Transferring % in fund % to % in fund %',
1170 -- old_amount, old_fund, new_amount, new_fund;
1172 -- Get the currency types of the old and new funds.
1183 IF old_fund_currency IS NULL THEN
1184 RAISE EXCEPTION 'acq.transfer_fund: old fund id % is not defined', old_fund;
1187 IF new_fund IS NOT NULL THEN
1199 IF new_fund_currency IS NULL THEN
1200 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is not defined', new_fund;
1201 ELSIF NOT new_fund_active THEN
1203 -- No point in putting money into a fund from whence you can't spend it
1205 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is inactive', new_fund;
1208 IF new_amount = old_amount THEN
1209 same_currency := true;
1210 currency_ratio := 1;
1213 -- We'll have to translate currency between funds. We presume that
1214 -- the calling code has already applied an appropriate exchange rate,
1215 -- so we'll apply the same conversion to each sub-transfer.
1217 same_currency := false;
1218 currency_ratio := new_amount / old_amount;
1222 -- Identify the funding source(s) from which we want to transfer the money.
1223 -- The principle is that we want to transfer the newest money first, because
1224 -- we spend the oldest money first. The priority for spending is defined
1225 -- by a sort of the view acq.ordered_funding_source_credit.
1230 ofsc.funding_source,
1232 ofsc.amount * acq.exchange_ratio( fs.currency_type, old_fund_currency )
1236 acq.ordered_funding_source_credit AS ofsc,
1237 acq.funding_source fs
1239 ofsc.funding_source = fs.id
1240 and ofsc.funding_source IN
1242 SELECT funding_source
1243 FROM acq.fund_allocation
1244 WHERE fund = old_fund
1248 -- ofsc.funding_source = funding_source_in
1249 -- OR funding_source_in IS NULL
1252 ofsc.sort_priority desc,
1253 ofsc.sort_date desc,
1257 -- Determine how much money the old fund got from this funding source,
1258 -- denominated in the currency types of the source and of the fund.
1259 -- This result may reflect transfers from previous iterations.
1262 COALESCE( sum( amount ), 0 ),
1263 COALESCE( sum( amount )
1264 * acq.exchange_ratio( source.currency_type, old_fund_currency ), 0 )
1266 orig_allocated_amt, -- in currency of the source
1267 allocated_amt -- in currency of the old fund
1272 and funding_source = source.funding_source;
1274 -- Determine how much to transfer from this credit, in the currency
1275 -- of the fund. Begin with the amount remaining to be attributed:
1277 curr_old_amt := old_remaining;
1279 -- Can't attribute more than was allocated from the fund:
1281 IF curr_old_amt > allocated_amt THEN
1282 curr_old_amt := allocated_amt;
1285 -- Can't attribute more than the amount of the current credit:
1287 IF curr_old_amt > source.converted_amt THEN
1288 curr_old_amt := source.converted_amt;
1291 curr_old_amt := trunc( curr_old_amt, 2 );
1293 old_remaining := old_remaining - curr_old_amt;
1295 -- Determine the amount to be deducted, if any,
1296 -- from the old allocation.
1298 IF old_remaining > 0 THEN
1300 -- In this case we're using the whole allocation, so use that
1301 -- amount directly instead of applying a currency translation
1302 -- and thereby inviting round-off errors.
1304 source_deduction := - orig_allocated_amt;
1306 source_deduction := trunc(
1307 ( - curr_old_amt ) *
1308 acq.exchange_ratio( old_fund_currency, source.currency_type ),
1312 IF source_deduction <> 0 THEN
1314 -- Insert negative allocation for old fund in fund_allocation,
1315 -- converted into the currency of the funding source
1317 INSERT INTO acq.fund_allocation (
1324 source.funding_source,
1328 'Transfer to fund ' || new_fund
1332 IF new_fund IS NOT NULL THEN
1334 -- Determine how much to add to the new fund, in
1335 -- its currency, and how much remains to be added:
1337 IF same_currency THEN
1338 curr_new_amt := curr_old_amt;
1340 IF old_remaining = 0 THEN
1342 -- This is the last iteration, so nothing should be left
1344 curr_new_amt := new_remaining;
1347 curr_new_amt := trunc( curr_old_amt * currency_ratio, 2 );
1348 new_remaining := new_remaining - curr_new_amt;
1352 -- Determine how much to add, if any,
1353 -- to the new fund's allocation.
1355 IF old_remaining > 0 THEN
1357 -- In this case we're using the whole allocation, so use that amount
1358 -- amount directly instead of applying a currency translation and
1359 -- thereby inviting round-off errors.
1361 source_addition := orig_allocated_amt;
1362 ELSIF source.currency_type = old_fund_currency THEN
1364 -- In this case we don't need a round trip currency translation,
1365 -- thereby inviting round-off errors:
1367 source_addition := curr_old_amt;
1369 source_addition := trunc(
1371 acq.exchange_ratio( new_fund_currency, source.currency_type ),
1375 IF source_addition <> 0 THEN
1377 -- Insert positive allocation for new fund in fund_allocation,
1378 -- converted to the currency of the founding source
1380 INSERT INTO acq.fund_allocation (
1387 source.funding_source,
1391 'Transfer from fund ' || old_fund
1396 IF trunc( curr_old_amt, 2 ) <> 0
1397 OR trunc( curr_new_amt, 2 ) <> 0 THEN
1399 -- Insert row in fund_transfer, using amounts in the currency of the funds
1401 INSERT INTO acq.fund_transfer (
1408 funding_source_credit
1411 trunc( curr_old_amt, 2 ),
1413 trunc( curr_new_amt, 2 ),
1420 if old_remaining <= 0 THEN
1421 EXIT; -- Nothing more to be transferred
1425 $$ LANGUAGE plpgsql;
1427 CREATE OR REPLACE FUNCTION acq.attribute_debits() RETURNS VOID AS $$
1429 Function to attribute expenditures and encumbrances to funding source credits,
1430 and thereby to funding sources.
1432 Read the debits in chonological order, attributing each one to one or
1433 more funding source credits. Constraints:
1435 1. Don't attribute more to a credit than the amount of the credit.
1437 2. For a given fund, don't attribute more to a funding source than the
1438 source has allocated to that fund.
1440 3. Attribute debits to credits with deadlines before attributing them to
1441 credits without deadlines. Otherwise attribute to the earliest credits
1442 first, based on the deadline date when present, or on the effective date
1443 when there is no deadline. Use funding_source_credit.id as a tie-breaker.
1444 This ordering is defined by an ORDER BY clause on the view
1445 acq.ordered_funding_source_credit.
1447 Start by truncating the table acq.debit_attribution. Then insert a row
1448 into that table for each attribution. If a debit cannot be fully
1449 attributed, insert a row for the unattributable balance, with the
1450 funding_source_credit and credit_amount columns NULL.
1453 curr_fund_source_bal RECORD;
1454 seqno INT; -- sequence num for credits applicable to a fund
1455 fund_credit RECORD; -- current row in temp t_fund_credit table
1456 fc RECORD; -- used for loading t_fund_credit table
1457 sc RECORD; -- used for loading t_fund_credit table
1459 -- Used exclusively in the main loop:
1461 deb RECORD; -- current row from acq.fund_debit table
1462 curr_credit_bal RECORD; -- current row from temp t_credit table
1463 debit_balance NUMERIC; -- amount left to attribute for current debit
1464 conv_debit_balance NUMERIC; -- debit balance in currency of the fund
1465 attr_amount NUMERIC; -- amount being attributed, in currency of debit
1466 conv_attr_amount NUMERIC; -- amount being attributed, in currency of source
1467 conv_cred_balance NUMERIC; -- credit_balance in the currency of the fund
1468 conv_alloc_balance NUMERIC; -- allocated balance in the currency of the fund
1469 attrib_count INT; -- populates id of acq.debit_attribution
1472 -- Load a temporary table. For each combination of fund and funding source,
1473 -- load an entry with the total amount allocated to that fund by that source.
1474 -- This sum may reflect transfers as well as original allocations. We will
1475 -- reduce this balance whenever we attribute debits to it.
1477 CREATE TEMP TABLE t_fund_source_bal
1481 funding_source AS source,
1482 sum( amount ) AS balance
1491 CREATE INDEX t_fund_source_bal_idx
1492 ON t_fund_source_bal( fund, source );
1493 -------------------------------------------------------------------------------
1495 -- Load another temporary table. For each fund, load zero or more
1496 -- funding source credits from which that fund can get money.
1498 CREATE TEMP TABLE t_fund_credit (
1505 SELECT DISTINCT fund
1506 FROM acq.fund_allocation
1508 LOOP -- Loop over the funds
1514 acq.ordered_funding_source_credit AS ofsc
1516 ofsc.funding_source IN
1518 SELECT funding_source
1519 FROM acq.fund_allocation
1520 WHERE fund = fc.fund
1526 LOOP -- Add each credit to the list
1527 INSERT INTO t_fund_credit (
1536 --RAISE NOTICE 'Fund % credit %', fc.fund, sc.id;
1538 END LOOP; -- Loop over credits for a given fund
1539 END LOOP; -- Loop over funds
1541 CREATE INDEX t_fund_credit_idx
1542 ON t_fund_credit( fund, seq );
1543 -------------------------------------------------------------------------------
1545 -- Load yet another temporary table. This one is a list of funding source
1546 -- credits, with their balances. We shall reduce those balances as we
1547 -- attribute debits to them.
1549 CREATE TEMP TABLE t_credit
1553 fsc.funding_source AS source,
1554 fsc.amount AS balance,
1555 fs.currency_type AS currency_type
1557 acq.funding_source_credit AS fsc,
1558 acq.funding_source fs
1560 fsc.funding_source = fs.id
1563 CREATE INDEX t_credit_idx
1564 ON t_credit( credit );
1566 -------------------------------------------------------------------------------
1568 -- Now that we have loaded the lookup tables: loop through the debits,
1569 -- attributing each one to one or more funding source credits.
1571 truncate table acq.debit_attribution;
1589 --RAISE NOTICE 'Debit %, fund %', deb.id, deb.fund;
1591 debit_balance := deb.amount;
1593 -- Loop over the funding source credits that are eligible
1594 -- to pay for this debit
1606 --RAISE NOTICE ' Examining credit %', fund_credit.credit;
1608 -- Look up the balance for this credit. If it's zero, then
1609 -- it's not useful, so treat it as if you didn't find it.
1610 -- (Actually there shouldn't be any zero balances in the table,
1611 -- but we check just to make sure.)
1614 INTO curr_credit_bal
1617 credit = fund_credit.credit
1620 IF curr_credit_bal IS NULL THEN
1622 -- This credit is exhausted; try the next one.
1628 -- At this point we have an applicable credit with some money left.
1629 -- Now see if the relevant funding_source has any money left.
1631 -- Look up the balance of the allocation for this combination of
1632 -- fund and source. If you find such an entry, but it has a zero
1633 -- balance, then it's not useful, so treat it as unfound.
1634 -- (Actually there shouldn't be any zero balances in the table,
1635 -- but we check just to make sure.)
1638 INTO curr_fund_source_bal
1639 FROM t_fund_source_bal
1642 AND source = curr_credit_bal.source
1645 IF curr_fund_source_bal IS NULL THEN
1647 -- This fund/source doesn't exist or is already exhausted,
1648 -- so we can't use this credit. Go on to the next one.
1653 -- Convert the available balances to the currency of the fund
1655 conv_alloc_balance := curr_fund_source_bal.balance * acq.exchange_ratio(
1656 curr_credit_bal.currency_type, deb.currency_type );
1657 conv_cred_balance := curr_credit_bal.balance * acq.exchange_ratio(
1658 curr_credit_bal.currency_type, deb.currency_type );
1660 -- Determine how much we can attribute to this credit: the minimum
1661 -- of the debit amount, the fund/source balance, and the
1664 --RAISE NOTICE ' deb bal %', debit_balance;
1665 --RAISE NOTICE ' source % balance %', curr_credit_bal.source, conv_alloc_balance;
1666 --RAISE NOTICE ' credit % balance %', curr_credit_bal.credit, conv_cred_balance;
1668 conv_attr_amount := NULL;
1669 attr_amount := debit_balance;
1671 IF attr_amount > conv_alloc_balance THEN
1672 attr_amount := conv_alloc_balance;
1673 conv_attr_amount := curr_fund_source_bal.balance;
1675 IF attr_amount > conv_cred_balance THEN
1676 attr_amount := conv_cred_balance;
1677 conv_attr_amount := curr_credit_bal.balance;
1680 -- If we're attributing all of one of the balances, then that's how
1681 -- much we will deduct from the balances, and we already captured
1682 -- that amount above. Otherwise we must convert the amount of the
1683 -- attribution from the currency of the fund back to the currency of
1684 -- the funding source.
1686 IF conv_attr_amount IS NULL THEN
1687 conv_attr_amount := attr_amount * acq.exchange_ratio(
1688 deb.currency_type, curr_credit_bal.currency_type );
1691 -- Insert a row to record the attribution
1693 attrib_count := attrib_count + 1;
1694 INSERT INTO acq.debit_attribution (
1698 funding_source_credit,
1704 curr_credit_bal.credit,
1708 -- Subtract the attributed amount from the various balances
1710 debit_balance := debit_balance - attr_amount;
1711 curr_fund_source_bal.balance := curr_fund_source_bal.balance - conv_attr_amount;
1713 IF curr_fund_source_bal.balance <= 0 THEN
1715 -- This allocation is exhausted. Delete it so
1716 -- that we don't waste time looking at it again.
1718 DELETE FROM t_fund_source_bal
1720 fund = curr_fund_source_bal.fund
1721 AND source = curr_fund_source_bal.source;
1723 UPDATE t_fund_source_bal
1724 SET balance = balance - conv_attr_amount
1726 fund = curr_fund_source_bal.fund
1727 AND source = curr_fund_source_bal.source;
1730 IF curr_credit_bal.balance <= 0 THEN
1732 -- This funding source credit is exhausted. Delete it
1733 -- so that we don't waste time looking at it again.
1735 --DELETE FROM t_credit
1737 -- credit = curr_credit_bal.credit;
1739 DELETE FROM t_fund_credit
1741 credit = curr_credit_bal.credit;
1744 SET balance = curr_credit_bal.balance
1746 credit = curr_credit_bal.credit;
1749 -- Are we done with this debit yet?
1751 IF debit_balance <= 0 THEN
1752 EXIT; -- We've fully attributed this debit; stop looking at credits.
1754 END LOOP; -- End loop over credits
1756 IF debit_balance <> 0 THEN
1758 -- We weren't able to attribute this debit, or at least not
1759 -- all of it. Insert a row for the unattributed balance.
1761 attrib_count := attrib_count + 1;
1762 INSERT INTO acq.debit_attribution (
1766 funding_source_credit,
1776 END LOOP; -- End of loop over debits
1778 $$ LANGUAGE 'plpgsql';
1780 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_unit(
1784 ) RETURNS VOID AS $$
1795 IF old_year IS NULL THEN
1796 RAISE EXCEPTION 'Input year argument is NULL';
1797 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1798 RAISE EXCEPTION 'Input year is out of range';
1801 IF user_id IS NULL THEN
1802 RAISE EXCEPTION 'Input user id argument is NULL';
1805 IF org_unit_id IS NULL THEN
1806 RAISE EXCEPTION 'Org unit id argument is NULL';
1808 SELECT TRUE INTO org_found
1810 WHERE id = org_unit_id;
1812 IF org_found IS NULL THEN
1813 RAISE EXCEPTION 'Org unit id is invalid';
1817 -- Loop over the applicable funds
1819 FOR old_fund in SELECT * FROM acq.fund
1823 AND org = org_unit_id
1826 INSERT INTO acq.fund (
1838 old_fund.currency_type,
1843 RETURNING id INTO new_id;
1845 WHEN unique_violation THEN
1846 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
1849 --RAISE NOTICE 'Propagating fund % to fund %',
1850 -- old_fund.code, new_id;
1853 $$ LANGUAGE plpgsql;
1855 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_tree(
1859 ) RETURNS VOID AS $$
1870 IF old_year IS NULL THEN
1871 RAISE EXCEPTION 'Input year argument is NULL';
1872 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1873 RAISE EXCEPTION 'Input year is out of range';
1876 IF user_id IS NULL THEN
1877 RAISE EXCEPTION 'Input user id argument is NULL';
1880 IF org_unit_id IS NULL THEN
1881 RAISE EXCEPTION 'Org unit id argument is NULL';
1883 SELECT TRUE INTO org_found
1885 WHERE id = org_unit_id;
1887 IF org_found IS NULL THEN
1888 RAISE EXCEPTION 'Org unit id is invalid';
1892 -- Loop over the applicable funds
1894 FOR old_fund in SELECT * FROM acq.fund
1899 SELECT id FROM actor.org_unit_descendants( org_unit_id )
1903 INSERT INTO acq.fund (
1915 old_fund.currency_type,
1920 RETURNING id INTO new_id;
1922 WHEN unique_violation THEN
1923 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
1926 --RAISE NOTICE 'Propagating fund % to fund %',
1927 -- old_fund.code, new_id;
1930 $$ LANGUAGE plpgsql;
1932 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_unit(
1936 ) RETURNS VOID AS $$
1940 new_year INT := old_year + 1;
1942 xfer_amount NUMERIC;
1951 IF old_year IS NULL THEN
1952 RAISE EXCEPTION 'Input year argument is NULL';
1953 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1954 RAISE EXCEPTION 'Input year is out of range';
1957 IF user_id IS NULL THEN
1958 RAISE EXCEPTION 'Input user id argument is NULL';
1961 IF org_unit_id IS NULL THEN
1962 RAISE EXCEPTION 'Org unit id argument is NULL';
1965 -- Validate the org unit
1970 WHERE id = org_unit_id;
1972 IF org_found IS NULL THEN
1973 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
1977 -- Loop over the propagable funds to identify the details
1978 -- from the old fund plus the id of the new one, if it exists.
1982 oldf.id AS old_fund,
1988 newf.id AS new_fund_id
1991 LEFT JOIN acq.fund AS newf
1992 ON ( oldf.code = newf.code )
1994 oldf.org = org_unit_id
1995 and oldf.year = old_year
1997 and newf.year = new_year
1999 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2001 IF roll_fund.new_fund_id IS NULL THEN
2003 -- The old fund hasn't been propagated yet. Propagate it now.
2005 INSERT INTO acq.fund (
2017 roll_fund.currency_type,
2022 RETURNING id INTO new_fund;
2024 new_fund = roll_fund.new_fund_id;
2027 -- Determine the amount to transfer
2031 FROM acq.fund_spent_balance
2032 WHERE fund = roll_fund.old_fund;
2034 IF xfer_amount <> 0 THEN
2035 IF roll_fund.rollover THEN
2037 -- Transfer balance from old fund to new
2039 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2041 PERFORM acq.transfer_fund(
2051 -- Transfer balance from old fund to the void
2053 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2055 PERFORM acq.transfer_fund(
2066 IF roll_fund.rollover THEN
2068 -- Move any lineitems from the old fund to the new one
2069 -- where the associated debit is an encumbrance.
2071 -- Any other tables tying expenditure details to funds should
2072 -- receive similar treatment. At this writing there are none.
2074 UPDATE acq.lineitem_detail
2077 fund = roll_fund.old_fund -- this condition may be redundant
2083 fund = roll_fund.old_fund
2087 -- Move encumbrance debits from the old fund to the new fund
2089 UPDATE acq.fund_debit
2092 fund = roll_fund.old_fund
2096 -- Mark old fund as inactive, now that we've closed it
2100 WHERE id = roll_fund.old_fund;
2103 $$ LANGUAGE plpgsql;
2105 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_tree(
2109 ) RETURNS VOID AS $$
2113 new_year INT := old_year + 1;
2115 xfer_amount NUMERIC;
2124 IF old_year IS NULL THEN
2125 RAISE EXCEPTION 'Input year argument is NULL';
2126 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2127 RAISE EXCEPTION 'Input year is out of range';
2130 IF user_id IS NULL THEN
2131 RAISE EXCEPTION 'Input user id argument is NULL';
2134 IF org_unit_id IS NULL THEN
2135 RAISE EXCEPTION 'Org unit id argument is NULL';
2138 -- Validate the org unit
2143 WHERE id = org_unit_id;
2145 IF org_found IS NULL THEN
2146 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
2150 -- Loop over the propagable funds to identify the details
2151 -- from the old fund plus the id of the new one, if it exists.
2155 oldf.id AS old_fund,
2161 newf.id AS new_fund_id
2164 LEFT JOIN acq.fund AS newf
2165 ON ( oldf.code = newf.code )
2167 oldf.year = old_year
2169 AND newf.year = new_year
2171 SELECT id FROM actor.org_unit_descendants( org_unit_id )
2174 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2176 IF roll_fund.new_fund_id IS NULL THEN
2178 -- The old fund hasn't been propagated yet. Propagate it now.
2180 INSERT INTO acq.fund (
2192 roll_fund.currency_type,
2197 RETURNING id INTO new_fund;
2199 new_fund = roll_fund.new_fund_id;
2202 -- Determine the amount to transfer
2206 FROM acq.fund_spent_balance
2207 WHERE fund = roll_fund.old_fund;
2209 IF xfer_amount <> 0 THEN
2210 IF roll_fund.rollover THEN
2212 -- Transfer balance from old fund to new
2214 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2216 PERFORM acq.transfer_fund(
2226 -- Transfer balance from old fund to the void
2228 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2230 PERFORM acq.transfer_fund(
2241 IF roll_fund.rollover THEN
2243 -- Move any lineitems from the old fund to the new one
2244 -- where the associated debit is an encumbrance.
2246 -- Any other tables tying expenditure details to funds should
2247 -- receive similar treatment. At this writing there are none.
2249 UPDATE acq.lineitem_detail
2252 fund = roll_fund.old_fund -- this condition may be redundant
2258 fund = roll_fund.old_fund
2262 -- Move encumbrance debits from the old fund to the new fund
2264 UPDATE acq.fund_debit
2267 fund = roll_fund.old_fund
2271 -- Mark old fund as inactive, now that we've closed it
2275 WHERE id = roll_fund.old_fund;
2278 $$ LANGUAGE plpgsql;
2280 CREATE OR REPLACE VIEW acq.funding_source_credit_total AS
2281 SELECT funding_source,
2282 SUM(amount) AS amount
2283 FROM acq.funding_source_credit
2286 CREATE OR REPLACE VIEW acq.funding_source_allocation_total AS
2287 SELECT funding_source,
2288 SUM(a.amount)::NUMERIC(100,2) AS amount
2289 FROM acq.fund_allocation a
2292 CREATE OR REPLACE VIEW acq.funding_source_balance AS
2293 SELECT COALESCE(c.funding_source, a.funding_source) AS funding_source,
2294 SUM(COALESCE(c.amount,0.0) - COALESCE(a.amount,0.0))::NUMERIC(100,2) AS amount
2295 FROM acq.funding_source_credit_total c
2296 FULL JOIN acq.funding_source_allocation_total a USING (funding_source)
2299 CREATE OR REPLACE VIEW acq.fund_allocation_total AS
2301 SUM(a.amount * acq.exchange_ratio(s.currency_type, f.currency_type))::NUMERIC(100,2) AS amount
2302 FROM acq.fund_allocation a
2303 JOIN acq.fund f ON (a.fund = f.id)
2304 JOIN acq.funding_source s ON (a.funding_source = s.id)
2307 CREATE OR REPLACE VIEW acq.fund_debit_total AS
2308 SELECT fund.id AS fund,
2309 fund_debit.encumbrance AS encumbrance,
2310 SUM( COALESCE( fund_debit.amount, 0 ) ) AS amount
2311 FROM acq.fund AS fund
2312 LEFT JOIN acq.fund_debit AS fund_debit
2313 ON ( fund.id = fund_debit.fund )
2316 CREATE OR REPLACE VIEW acq.fund_encumbrance_total AS
2318 SUM(amount) AS amount
2319 FROM acq.fund_debit_total
2320 WHERE encumbrance IS TRUE
2323 CREATE OR REPLACE VIEW acq.fund_spent_total AS
2325 SUM(amount) AS amount
2326 FROM acq.fund_debit_total
2327 WHERE encumbrance IS FALSE
2330 CREATE OR REPLACE VIEW acq.fund_combined_balance AS
2332 c.amount - COALESCE(d.amount,0.0) AS amount
2333 FROM acq.fund_allocation_total c
2334 LEFT JOIN acq.fund_debit_total d USING (fund);
2336 CREATE OR REPLACE VIEW acq.fund_spent_balance AS
2338 c.amount - COALESCE(d.amount,0.0) AS amount
2339 FROM acq.fund_allocation_total c
2340 LEFT JOIN acq.fund_spent_total d USING (fund);
2342 -- For each fund: the total allocation from all sources, in the
2343 -- currency of the fund (or 0 if there are no allocations)
2345 CREATE VIEW acq.all_fund_allocation_total AS
2348 COALESCE( SUM( a.amount * acq.exchange_ratio(
2349 s.currency_type, f.currency_type))::numeric(100,2), 0 )
2353 LEFT JOIN acq.fund_allocation a
2355 LEFT JOIN acq.funding_source s
2356 ON a.funding_source = s.id
2360 -- For every fund: the total encumbrances (or 0 if none),
2361 -- in the currency of the fund.
2363 CREATE VIEW acq.all_fund_encumbrance_total AS
2366 COALESCE( encumb.amount, 0 ) AS amount
2372 sum( amount ) AS amount
2379 ON f.id = encumb.fund;
2381 -- For every fund: the total spent (or 0 if none),
2382 -- in the currency of the fund.
2384 CREATE VIEW acq.all_fund_spent_total AS
2387 COALESCE( spent.amount, 0 ) AS amount
2393 sum( amount ) AS amount
2400 ON f.id = spent.fund;
2402 -- For each fund: the amount not yet spent, in the currency
2403 -- of the fund. May include encumbrances.
2405 CREATE VIEW acq.all_fund_spent_balance AS
2408 c.amount - d.amount AS amount
2409 FROM acq.all_fund_allocation_total c
2410 LEFT JOIN acq.all_fund_spent_total d USING (fund);
2412 -- For each fund: the amount neither spent nor encumbered,
2413 -- in the currency of the fund
2415 CREATE VIEW acq.all_fund_combined_balance AS
2418 a.amount - COALESCE( c.amount, 0 ) AS amount
2420 acq.all_fund_allocation_total a
2424 SUM( amount ) AS amount
2429 ) AS c USING ( fund );