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 default_claim_interval INTERVAL,
48 CONSTRAINT provider_name_once_per_owner UNIQUE (name,owner),
49 CONSTRAINT code_once_per_owner UNIQUE (code, owner)
52 CREATE TABLE acq.provider_holding_subfield_map (
53 id SERIAL PRIMARY KEY,
54 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
55 name TEXT NOT NULL, -- barcode, price, etc
56 subfield TEXT NOT NULL,
57 CONSTRAINT name_once_per_provider UNIQUE (provider,name)
60 CREATE TABLE acq.provider_address (
61 id SERIAL PRIMARY KEY,
62 valid BOOL NOT NULL DEFAULT TRUE,
64 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
65 street1 TEXT NOT NULL,
70 country TEXT NOT NULL,
71 post_code TEXT NOT NULL,
72 fax_phone TEXT NOT NULL
75 CREATE TABLE acq.provider_contact (
76 id SERIAL PRIMARY KEY,
77 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
79 role TEXT, -- free-form.. e.g. "our sales guy"
84 CREATE TABLE acq.provider_contact_address (
85 id SERIAL PRIMARY KEY,
86 valid BOOL NOT NULL DEFAULT TRUE,
88 contact INT NOT NULL REFERENCES acq.provider_contact (id) DEFERRABLE INITIALLY DEFERRED,
89 street1 TEXT NOT NULL,
94 country TEXT NOT NULL,
95 post_code TEXT NOT NULL,
99 CREATE TABLE acq.provider_note (
100 id SERIAL PRIMARY KEY,
101 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
102 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
103 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
104 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
105 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
108 CREATE INDEX acq_pro_note_pro_idx ON acq.provider_note ( provider );
109 CREATE INDEX acq_pro_note_creator_idx ON acq.provider_note ( creator );
110 CREATE INDEX acq_pro_note_editor_idx ON acq.provider_note ( editor );
113 CREATE TABLE acq.funding_source (
114 id SERIAL PRIMARY KEY,
116 owner INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
117 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
119 CONSTRAINT funding_source_name_once_per_owner UNIQUE (name,owner)
122 CREATE TABLE acq.funding_source_credit (
123 id SERIAL PRIMARY KEY,
124 funding_source INT NOT NULL REFERENCES acq.funding_source (id) DEFERRABLE INITIALLY DEFERRED,
125 amount NUMERIC NOT NULL,
127 deadline_date TIMESTAMPTZ,
128 effective_date TIMESTAMPTZ NOT NULL default now()
131 CREATE VIEW acq.ordered_funding_source_credit AS
133 CASE WHEN deadline_date IS NULL THEN
137 END AS sort_priority,
138 CASE WHEN deadline_date IS NULL THEN
148 acq.funding_source_credit;
150 COMMENT ON VIEW acq.ordered_funding_source_credit IS $$
152 * Copyright (C) 2009 Georgia Public Library Service
153 * Scott McKellar <scott@gmail.com>
155 * The acq.ordered_funding_source_credit view is a prioritized
156 * ordering of funding source credits. When ordered by the first
157 * three columns, this view defines the order in which the various
158 * credits are to be tapped for spending, subject to the allocations
159 * in the acq.fund_allocation table.
161 * The first column reflects the principle that we should spend
162 * money with deadlines before spending money without deadlines.
164 * The second column reflects the principle that we should spend the
165 * oldest money first. For money with deadlines, that means that we
166 * spend first from the credit with the earliest deadline. For
167 * money without deadlines, we spend first from the credit with the
168 * earliest effective date.
170 * The third column is a tie breaker to ensure a consistent
175 * This program is free software; you can redistribute it and/or
176 * modify it under the terms of the GNU General Public License
177 * as published by the Free Software Foundation; either version 2
178 * of the License, or (at your option) any later version.
180 * This program is distributed in the hope that it will be useful,
181 * but WITHOUT ANY WARRANTY; without even the implied warranty of
182 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
183 * GNU General Public License for more details.
187 CREATE TABLE acq.fund (
188 id SERIAL PRIMARY KEY,
189 org INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
191 year INT NOT NULL DEFAULT EXTRACT( YEAR FROM NOW() ),
192 currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
194 rollover BOOL NOT NULL DEFAULT FALSE,
195 propagate BOOL NOT NULL DEFAULT TRUE,
196 active BOOL NOT NULL DEFAULT TRUE,
197 balance_warning_percent INT CONSTRAINT balance_warning_percent_limit
198 CHECK( balance_warning_percent <= 100 ),
199 balance_stop_percent INT CONSTRAINT balance_stop_percent_limit
200 CHECK( balance_stop_percent <= 100 ),
201 CONSTRAINT name_once_per_org_year UNIQUE (org,name,year),
202 CONSTRAINT code_once_per_org_year UNIQUE (org, code, year),
203 CONSTRAINT acq_fund_rollover_implies_propagate CHECK ( propagate OR NOT rollover )
206 CREATE TABLE acq.fund_debit (
207 id SERIAL PRIMARY KEY,
208 fund INT NOT NULL REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
209 origin_amount NUMERIC NOT NULL, -- pre-exchange-rate amount
210 origin_currency_type TEXT NOT NULL REFERENCES acq.currency_type (code) DEFERRABLE INITIALLY DEFERRED,
211 amount NUMERIC NOT NULL,
212 encumbrance BOOL NOT NULL DEFAULT TRUE,
213 debit_type TEXT NOT NULL,
214 xfer_destination INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
215 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
218 CREATE TABLE acq.fund_allocation (
219 id SERIAL PRIMARY KEY,
220 funding_source INT NOT NULL REFERENCES acq.funding_source (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
221 fund INT NOT NULL REFERENCES acq.fund (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
222 amount NUMERIC NOT NULL,
223 allocator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
225 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
227 CREATE INDEX fund_alloc_allocator_idx ON acq.fund_allocation ( allocator );
229 CREATE TABLE acq.fund_allocation_percent
231 id SERIAL PRIMARY KEY,
232 funding_source INT NOT NULL REFERENCES acq.funding_source
233 DEFERRABLE INITIALLY DEFERRED,
234 org INT NOT NULL REFERENCES actor.org_unit
235 DEFERRABLE INITIALLY DEFERRED,
237 percent NUMERIC NOT NULL,
238 allocator INTEGER NOT NULL REFERENCES actor.usr
239 DEFERRABLE INITIALLY DEFERRED,
241 create_time TIMESTAMPTZ NOT NULL DEFAULT now(),
242 CONSTRAINT logical_key UNIQUE( funding_source, org, fund_code ),
243 CONSTRAINT percentage_range CHECK( percent >= 0 AND percent <= 100 )
246 -- Trigger function to validate combination of org_unit and fund_code
248 CREATE OR REPLACE FUNCTION acq.fund_alloc_percent_val()
249 RETURNS TRIGGER AS $$
264 AND code = NEW.fund_code
270 RAISE EXCEPTION 'No fund exists for org % and code %', NEW.org, NEW.fund_code;
275 CREATE TRIGGER acq_fund_alloc_percent_val_trig
276 BEFORE INSERT OR UPDATE ON acq.fund_allocation_percent
277 FOR EACH ROW EXECUTE PROCEDURE acq.fund_alloc_percent_val();
279 -- To do: trigger to verify that percentages don't add up to more than 100
281 CREATE OR REPLACE FUNCTION acq.fap_limit_100()
282 RETURNS TRIGGER AS $$
285 total_percent numeric;
293 acq.fund_allocation_percent AS fap
295 fap.funding_source = NEW.funding_source;
297 IF total_percent > 100 THEN
298 RAISE EXCEPTION 'Total percentages exceed 100 for funding_source %',
306 CREATE TRIGGER acqfap_limit_100_trig
307 AFTER INSERT OR UPDATE ON acq.fund_allocation_percent
308 FOR EACH ROW EXECUTE PROCEDURE acq.fap_limit_100();
310 CREATE TABLE acq.picklist (
311 id SERIAL PRIMARY KEY,
312 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
313 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
314 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
315 org_unit 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 CONSTRAINT name_once_per_owner UNIQUE (name,owner)
321 CREATE INDEX acq_picklist_owner_idx ON acq.picklist ( owner );
322 CREATE INDEX acq_picklist_creator_idx ON acq.picklist ( creator );
323 CREATE INDEX acq_picklist_editor_idx ON acq.picklist ( editor );
325 CREATE TABLE acq.purchase_order (
326 id SERIAL PRIMARY KEY,
327 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
328 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
329 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
330 ordering_agency INT NOT NULL REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
331 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
332 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
333 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
334 state TEXT NOT NULL DEFAULT 'new',
335 order_date TIMESTAMP WITH TIME ZONE,
338 CREATE INDEX po_owner_idx ON acq.purchase_order (owner);
339 CREATE INDEX po_provider_idx ON acq.purchase_order (provider);
340 CREATE INDEX po_state_idx ON acq.purchase_order (state);
341 CREATE INDEX po_creator_idx ON acq.purchase_order ( creator );
342 CREATE INDEX po_editor_idx ON acq.purchase_order ( editor );
343 CREATE INDEX acq_po_org_name_order_date_idx ON acq.purchase_order( ordering_agency, name, order_date );
345 -- The name should default to the id, as text. We can't reference a column
346 -- in a DEFAULT clause, so we use a trigger:
348 CREATE OR REPLACE FUNCTION acq.purchase_order_name_default () RETURNS TRIGGER
351 IF NEW.name IS NULL THEN
352 NEW.name := NEW.id::TEXT;
359 CREATE TRIGGER po_name_default_trg
360 BEFORE INSERT OR UPDATE ON acq.purchase_order
361 FOR EACH ROW EXECUTE PROCEDURE acq.purchase_order_name_default ();
363 -- The order name should be unique for a given ordering agency on a given order date
364 -- (truncated to midnight), but only where the order_date is not NULL. Conceptually
365 -- this rule requires a check constraint with a subquery. However you can't have a
366 -- subquery in a CHECK constraint, so we fake it with a trigger.
368 CREATE OR REPLACE FUNCTION acq.po_org_name_date_unique () RETURNS TRIGGER
374 -- If order_date is not null, then make sure we don't have a collision
375 -- on order_date (truncated to day), org, and name
377 IF NEW.order_date IS NULL THEN
381 -- In the WHERE clause, we compare the order_dates without regard to time of day.
382 -- We use a pair of inequalities instead of comparing truncated dates so that the
383 -- query can do an indexed range scan.
385 SELECT 1 INTO collision
386 FROM acq.purchase_order
388 ordering_agency = NEW.ordering_agency
390 AND order_date >= date_trunc( 'day', NEW.order_date )
391 AND order_date < date_trunc( 'day', NEW.order_date ) + '1 day'::INTERVAL
394 IF collision IS NULL THEN
395 -- okay, no collision
398 -- collision; nip it in the bud
399 RAISE EXCEPTION 'Colliding purchase orders: ordering_agency %, date %, name ''%''',
400 NEW.ordering_agency, NEW.order_date, NEW.name;
405 CREATE TRIGGER po_org_name_date_unique_trg
406 BEFORE INSERT OR UPDATE ON acq.purchase_order
407 FOR EACH ROW EXECUTE PROCEDURE acq.po_org_name_date_unique ();
409 CREATE TABLE acq.po_note (
410 id SERIAL PRIMARY KEY,
411 purchase_order INT NOT NULL REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
412 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
413 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
414 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
415 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
418 CREATE INDEX po_note_po_idx ON acq.po_note (purchase_order);
419 CREATE INDEX acq_po_note_creator_idx ON acq.po_note ( creator );
420 CREATE INDEX acq_po_note_editor_idx ON acq.po_note ( editor );
422 CREATE TABLE acq.lineitem (
423 id BIGSERIAL PRIMARY KEY,
424 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
425 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
426 selector INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
427 provider INT REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED,
428 purchase_order INT REFERENCES acq.purchase_order (id) DEFERRABLE INITIALLY DEFERRED,
429 picklist INT REFERENCES acq.picklist (id) DEFERRABLE INITIALLY DEFERRED,
430 expected_recv_time TIMESTAMP WITH TIME ZONE,
431 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
432 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
434 eg_bib_id INT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
436 state TEXT NOT NULL DEFAULT 'new',
437 claim_interval INTERVAL,
438 CONSTRAINT picklist_or_po CHECK (picklist IS NOT NULL OR purchase_order IS NOT NULL)
440 CREATE INDEX li_po_idx ON acq.lineitem (purchase_order);
441 CREATE INDEX li_pl_idx ON acq.lineitem (picklist);
442 CREATE INDEX li_creator_idx ON acq.lineitem ( creator );
443 CREATE INDEX li_editor_idx ON acq.lineitem ( editor );
444 CREATE INDEX li_selector_idx ON acq.lineitem ( selector );
446 CREATE TABLE acq.lineitem_alert_text (
447 id SERIAL PRIMARY KEY,
450 owning_lib INT NOT NULL
451 REFERENCES actor.org_unit(id)
452 DEFERRABLE INITIALLY DEFERRED,
453 CONSTRAINT alert_one_code_per_org UNIQUE (code, owning_lib)
456 CREATE TABLE acq.lineitem_note (
457 id SERIAL PRIMARY KEY,
458 lineitem INT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
459 creator INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
460 editor INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
461 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
462 edit_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
464 alert_text INT REFERENCES acq.lineitem_alert_text(id)
465 DEFERRABLE INITIALLY DEFERRED
467 CREATE INDEX li_note_li_idx ON acq.lineitem_note (lineitem);
468 CREATE INDEX li_note_creator_idx ON acq.lineitem_note ( creator );
469 CREATE INDEX li_note_editor_idx ON acq.lineitem_note ( editor );
471 CREATE TABLE acq.lineitem_detail (
472 id BIGSERIAL PRIMARY KEY,
473 lineitem INT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
474 fund INT REFERENCES acq.fund (id) DEFERRABLE INITIALLY DEFERRED,
475 fund_debit INT REFERENCES acq.fund_debit (id) DEFERRABLE INITIALLY DEFERRED,
476 eg_copy_id BIGINT REFERENCES asset.copy (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
480 collection_code TEXT,
481 circ_modifier TEXT REFERENCES config.circ_modifier (code) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
482 owning_lib INT REFERENCES actor.org_unit (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
483 location INT REFERENCES asset.copy_location (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
484 recv_time TIMESTAMP WITH TIME ZONE
487 CREATE INDEX li_detail_li_idx ON acq.lineitem_detail (lineitem);
489 CREATE TABLE acq.lineitem_attr_definition (
490 id BIGSERIAL PRIMARY KEY,
492 description TEXT NOT NULL,
493 remove TEXT NOT NULL DEFAULT '',
494 ident BOOL NOT NULL DEFAULT FALSE
497 CREATE TABLE acq.lineitem_marc_attr_definition (
498 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
500 ) INHERITS (acq.lineitem_attr_definition);
502 CREATE TABLE acq.lineitem_provider_attr_definition (
503 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
505 provider INT NOT NULL REFERENCES acq.provider (id) DEFERRABLE INITIALLY DEFERRED
506 ) INHERITS (acq.lineitem_attr_definition);
508 CREATE TABLE acq.lineitem_generated_attr_definition (
509 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
511 ) INHERITS (acq.lineitem_attr_definition);
513 CREATE TABLE acq.lineitem_usr_attr_definition (
514 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq'),
515 usr INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED
516 ) INHERITS (acq.lineitem_attr_definition);
517 CREATE INDEX li_usr_attr_def_usr_idx ON acq.lineitem_usr_attr_definition ( usr );
519 CREATE TABLE acq.lineitem_local_attr_definition (
520 id BIGINT PRIMARY KEY DEFAULT NEXTVAL('acq.lineitem_attr_definition_id_seq')
521 ) INHERITS (acq.lineitem_attr_definition);
523 CREATE TABLE acq.lineitem_attr (
524 id BIGSERIAL PRIMARY KEY,
525 definition BIGINT NOT NULL,
526 lineitem BIGINT NOT NULL REFERENCES acq.lineitem (id) DEFERRABLE INITIALLY DEFERRED,
527 attr_type TEXT NOT NULL,
528 attr_name TEXT NOT NULL,
529 attr_value TEXT NOT NULL
532 CREATE INDEX li_attr_li_idx ON acq.lineitem_attr (lineitem);
533 CREATE INDEX li_attr_value_idx ON acq.lineitem_attr (attr_value);
534 CREATE INDEX li_attr_definition_idx ON acq.lineitem_attr (definition);
540 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('title','Title of work','//*[@tag="245"]/*[contains("abcmnopr",@code)]');
541 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)]');
542 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('language','Language of work','//*[@tag="240"]/*[@code="l"][1]');
543 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pagination','Pagination','//*[@tag="300"]/*[@code="a"][1]');
544 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('isbn','ISBN','//*[@tag="020"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
545 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath, remove ) VALUES ('issn','ISSN','//*[@tag="022"]/*[@code="a"]', $r$(?:-|\s.+$)$r$);
546 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('price','Price','//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
547 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('identifier','Identifier','//*[@tag="001"]');
548 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('publisher','Publisher','//*[@tag="260"]/*[@code="b"][1]');
549 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('pubdate','Publication Date','//*[@tag="260"]/*[@code="c"][1]');
550 INSERT INTO acq.lineitem_marc_attr_definition ( code, description, xpath ) VALUES ('edition','Edition','//*[@tag="250"]/*[@code="a"][1]');
552 INSERT INTO acq.lineitem_local_attr_definition ( code, description ) VALUES ('estimated_price', 'Estimated Price');
555 CREATE TABLE acq.distribution_formula (
556 id SERIAL PRIMARY KEY,
558 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
560 skip_count INT NOT NULL DEFAULT 0,
561 CONSTRAINT acqdf_name_once_per_owner UNIQUE (name, owner)
564 CREATE TABLE acq.distribution_formula_entry (
565 id SERIAL PRIMARY KEY,
566 formula INTEGER NOT NULL REFERENCES acq.distribution_formula(id)
568 DEFERRABLE INITIALLY DEFERRED,
569 position INTEGER NOT NULL,
570 item_count INTEGER NOT NULL,
571 owning_lib INTEGER REFERENCES actor.org_unit(id)
572 DEFERRABLE INITIALLY DEFERRED,
573 location INTEGER REFERENCES asset.copy_location(id),
574 CONSTRAINT acqdfe_lib_once_per_formula UNIQUE( formula, position ),
575 CONSTRAINT acqdfe_must_be_somewhere
576 CHECK( owning_lib IS NOT NULL OR location IS NOT NULL )
579 CREATE TABLE acq.distribution_formula_application (
580 id BIGSERIAL PRIMARY KEY,
581 creator INT NOT NULL REFERENCES actor.usr(id) DEFERRABLE INITIALLY DEFERRED,
582 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
584 REFERENCES acq.distribution_formula(id) DEFERRABLE INITIALLY DEFERRED,
585 lineitem INT NOT NULL
586 REFERENCES acq.lineitem(id) DEFERRABLE INITIALLY DEFERRED
589 CREATE INDEX acqdfa_df_idx
590 ON acq.distribution_formula_application(formula);
591 CREATE INDEX acqdfa_li_idx
592 ON acq.distribution_formula_application(lineitem);
593 CREATE INDEX acqdfa_creator_idx
594 ON acq.distribution_formula_application(creator);
596 CREATE TABLE acq.fund_tag (
597 id SERIAL PRIMARY KEY,
599 REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
601 CONSTRAINT acqft_tag_once_per_owner UNIQUE (name, owner)
604 CREATE TABLE acq.fund_tag_map (
605 id SERIAL PRIMARY KEY,
606 fund INTEGER NOT NULL REFERENCES acq.fund(id)
607 DEFERRABLE INITIALLY DEFERRED,
608 tag INTEGER REFERENCES acq.fund_tag(id)
610 DEFERRABLE INITIALLY DEFERRED,
611 CONSTRAINT acqftm_fund_once_per_tag UNIQUE( fund, tag )
614 CREATE TABLE acq.fund_transfer (
615 id SERIAL PRIMARY KEY,
616 src_fund INT NOT NULL REFERENCES acq.fund( id )
617 DEFERRABLE INITIALLY DEFERRED,
618 src_amount NUMERIC NOT NULL,
619 dest_fund INT NOT NULL REFERENCES acq.fund( id )
620 DEFERRABLE INITIALLY DEFERRED,
621 dest_amount NUMERIC NOT NULL,
622 transfer_time TIMESTAMPTZ NOT NULL DEFAULT now(),
623 transfer_user INT NOT NULL REFERENCES actor.usr( id )
624 DEFERRABLE INITIALLY DEFERRED,
626 funding_source_credit INT NOT NULL REFERENCES acq.funding_source_credit( id )
627 DEFERRABLE INITIALLY DEFERRED
630 CREATE INDEX acqftr_usr_idx
631 ON acq.fund_transfer( transfer_user );
633 COMMENT ON TABLE acq.fund_transfer IS $$
635 * Copyright (C) 2009 Georgia Public Library Service
636 * Scott McKellar <scott@esilibrary.com>
640 * Each row represents the transfer of money from a source fund
641 * to a destination fund. There should be corresponding entries
642 * in acq.fund_allocation. The purpose of acq.fund_transfer is
643 * to record how much money moved from which fund to which other
646 * The presence of two amount fields, rather than one, reflects
647 * the possibility that the two funds are denominated in different
648 * currencies. If they use the same currency type, the two
649 * amounts should be the same.
653 * This program is free software; you can redistribute it and/or
654 * modify it under the terms of the GNU General Public License
655 * as published by the Free Software Foundation; either version 2
656 * of the License, or (at your option) any later version.
658 * This program is distributed in the hope that it will be useful,
659 * but WITHOUT ANY WARRANTY; without even the implied warranty of
660 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
661 * GNU General Public License for more details.
665 CREATE TABLE acq.fiscal_calendar (
666 id SERIAL PRIMARY KEY,
670 -- Create a default calendar (though we don't specify its contents).
671 -- Create a foreign key in actor.org_unit, initially pointing to
672 -- the default calendar.
674 INSERT INTO acq.fiscal_calendar (
681 ALTER TABLE actor.org_unit ADD FOREIGN KEY
682 (fiscal_calendar) REFERENCES acq.fiscal_calendar( id )
683 DEFERRABLE INITIALLY DEFERRED;
685 CREATE TABLE acq.fiscal_year (
686 id SERIAL PRIMARY KEY,
687 calendar INT NOT NULL
688 REFERENCES acq.fiscal_calendar
690 DEFERRABLE INITIALLY DEFERRED,
692 year_begin TIMESTAMPTZ NOT NULL,
693 year_end TIMESTAMPTZ NOT NULL,
694 CONSTRAINT acq_fy_logical_key UNIQUE ( calendar, year ),
695 CONSTRAINT acq_fy_physical_key UNIQUE ( calendar, year_begin )
698 CREATE TABLE acq.edi_account ( -- similar tables can extend remote_account for other parts of EG
699 provider INT NOT NULL REFERENCES acq.provider (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
700 in_dir TEXT -- incoming messages dir (probably different than config.remote_account.path, the outgoing dir)
701 ) INHERITS (config.remote_account);
703 -- We need a UNIQUE constraint here also, to support the FK from acq.provider.edi_default
704 ALTER TABLE acq.edi_account ADD CONSTRAINT acq_edi_account_id_unique UNIQUE (id);
706 -- Note below that the primary key is NOT a SERIAL type. We will periodically truncate and rebuild
707 -- the table, assigning ids programmatically instead of using a sequence.
708 CREATE TABLE acq.debit_attribution (
709 id INT NOT NULL PRIMARY KEY,
710 fund_debit INT NOT NULL
711 REFERENCES acq.fund_debit
712 DEFERRABLE INITIALLY DEFERRED,
713 debit_amount NUMERIC NOT NULL,
714 funding_source_credit INT REFERENCES acq.funding_source_credit
715 DEFERRABLE INITIALLY DEFERRED,
716 credit_amount NUMERIC
719 CREATE INDEX acq_attribution_debit_idx
720 ON acq.debit_attribution( fund_debit );
722 CREATE INDEX acq_attribution_credit_idx
723 ON acq.debit_attribution( funding_source_credit );
727 CREATE TABLE acq.invoice_method (
728 code TEXT PRIMARY KEY,
729 name TEXT NOT NULL -- i18n-ize
732 CREATE TABLE acq.invoice (
733 id SERIAL PRIMARY KEY,
734 receiver INT NOT NULL REFERENCES actor.org_unit (id),
735 provider INT NOT NULL REFERENCES acq.provider (id),
736 shipper INT NOT NULL REFERENCES acq.provider (id),
737 recv_date TIMESTAMPTZ NOT NULL DEFAULT NOW(),
738 recv_method TEXT NOT NULL REFERENCES acq.invoice_method (code) DEFAULT 'EDI',
739 inv_type TEXT, -- A "type" field is desired, but no idea what goes here
740 inv_ident TEXT NOT NULL -- vendor-supplied invoice id/number
743 CREATE TABLE acq.invoice_entry (
744 id SERIAL PRIMARY KEY,
745 invoice INT NOT NULL REFERENCES acq.invoice (id) ON DELETE CASCADE,
746 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
747 lineitem INT REFERENCES acq.lineitem (id) ON UPDATE CASCADE ON DELETE SET NULL,
748 inv_item_count INT NOT NULL, -- How many acqlids did they say they sent
749 phys_item_count INT, -- and how many did staff count
751 billed_per_item BOOL,
752 cost_billed NUMERIC(8,2),
753 actual_cost NUMERIC(8,2)
756 CREATE TABLE acq.invoice_item_type (
757 code TEXT PRIMARY KEY,
758 name TEXT NOT NULL -- i18n-ize
761 CREATE TABLE acq.invoice_item ( -- for invoice-only debits: taxes/fees/non-bib items/etc
762 id SERIAL PRIMARY KEY,
763 invoice INT NOT NULL REFERENCES acq.invoice (id) ON UPDATE CASCADE ON DELETE CASCADE,
764 purchase_order INT REFERENCES acq.purchase_order (id) ON UPDATE CASCADE ON DELETE SET NULL,
765 fund_debit INT REFERENCES acq.fund_debit (id),
766 inv_item_type TEXT NOT NULL REFERENCES acq.invoice_item_type (code),
770 cost_billed NUMERIC(8,2),
771 actual_cost NUMERIC(8,2)
775 CREATE TABLE acq.user_request_type (
776 id SERIAL PRIMARY KEY,
777 label TEXT NOT NULL UNIQUE -- i18n-ize
780 INSERT INTO acq.user_request_type (id,label) VALUES (1, oils_i18n_gettext('1', 'Books', 'aurt', 'label'));
781 INSERT INTO acq.user_request_type (id,label) VALUES (2, oils_i18n_gettext('2', 'Journal/Magazine & Newspaper Articles', 'aurt', 'label'));
782 INSERT INTO acq.user_request_type (id,label) VALUES (3, oils_i18n_gettext('3', 'Audiobooks', 'aurt', 'label'));
783 INSERT INTO acq.user_request_type (id,label) VALUES (4, oils_i18n_gettext('4', 'Music', 'aurt', 'label'));
784 INSERT INTO acq.user_request_type (id,label) VALUES (5, oils_i18n_gettext('5', 'DVDs', 'aurt', 'label'));
786 SELECT SETVAL('acq.user_request_type_id_seq'::TEXT, 6);
788 CREATE TABLE acq.user_request (
789 id SERIAL PRIMARY KEY,
790 usr INT NOT NULL REFERENCES actor.usr (id), -- requesting user
791 hold BOOL NOT NULL DEFAULT TRUE,
793 pickup_lib INT NOT NULL REFERENCES actor.org_unit (id), -- pickup lib
794 holdable_formats TEXT, -- nullable, for use in hold creation
796 email_notify BOOL NOT NULL DEFAULT TRUE,
797 lineitem INT REFERENCES acq.lineitem (id) ON DELETE CASCADE,
798 eg_bib BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
799 request_date TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- when they requested it
800 need_before TIMESTAMPTZ, -- don't create holds after this
803 request_type INT NOT NULL REFERENCES acq.user_request_type (id),
820 CREATE TYPE acq.flat_lineitem_holding_subfield AS (lineitem int, holding int, subfield text, data text);
821 CREATE OR REPLACE FUNCTION acq.extract_holding_attr_table (lineitem int, tag text) RETURNS SETOF acq.flat_lineitem_holding_subfield AS $$
824 lida acq.flat_lineitem_holding_subfield%ROWTYPE;
827 SELECT COUNT(*) INTO counter
828 FROM oils_xpath_table(
832 '//*[@tag="' || tag || '"]',
834 ) as t(i int,c text);
836 FOR i IN 1 .. counter LOOP
839 FROM ( SELECT id,i,t,v
840 FROM oils_xpath_table(
844 '//*[@tag="' || tag || '"][position()=' || i || ']/*/@code|' ||
845 '//*[@tag="' || tag || '"][position()=' || i || ']/*[@code]',
847 ) as t(id int,t text,v text)
858 CREATE TYPE acq.flat_lineitem_detail AS (lineitem int, holding int, attr text, data text);
859 CREATE OR REPLACE FUNCTION acq.extract_provider_holding_data ( lineitem_i int ) RETURNS SETOF acq.flat_lineitem_detail AS $$
863 lida acq.flat_lineitem_detail%ROWTYPE;
865 SELECT provider INTO prov_i FROM acq.lineitem WHERE id = lineitem_i;
866 IF NOT FOUND THEN RETURN; END IF;
868 SELECT holding_tag INTO tag_t FROM acq.provider WHERE id = prov_i;
869 IF NOT FOUND OR tag_t IS NULL THEN RETURN; END IF;
876 FROM acq.extract_holding_attr_table( lineitem_i, tag_t ) h
877 JOIN acq.provider_holding_subfield_map a USING (subfield)
878 WHERE a.provider = prov_i
887 -- select * from acq.extract_provider_holding_data(699);
889 CREATE OR REPLACE FUNCTION public.extract_acq_marc_field ( BIGINT, TEXT, TEXT) RETURNS TEXT AS $$
890 SELECT public.extract_marc_field('acq.lineitem', $1, $2, $3);
894 CREATE OR REPLACE FUNCTION public.extract_bib_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
895 SELECT public.extract_marc_field('biblio.record_entry', $1, $2);
898 CREATE OR REPLACE FUNCTION public.extract_authority_marc_field ( BIGINT, TEXT ) RETURNS TEXT AS $$
899 SELECT public.extract_marc_field('authority.record_entry', $1, $2);
903 -- INSERT INTO acq.lineitem_provider_attr_definition ( provider, code, description, xpath ) VALUES (1,'price','Price','//*[@tag="020" or @tag="022"]/*[@code="a"][1]');
906 Suggested vendor fields:
914 CREATE OR REPLACE FUNCTION public.ingest_acq_marc ( ) RETURNS TRIGGER AS $$
922 FOR adef IN SELECT *,tableoid FROM acq.lineitem_attr_definition LOOP
924 SELECT relname::TEXT INTO atype FROM pg_class WHERE oid = adef.tableoid;
926 IF (atype NOT IN ('lineitem_usr_attr_definition','lineitem_local_attr_definition')) THEN
927 IF (atype = 'lineitem_provider_attr_definition') THEN
928 SELECT provider INTO prov FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
929 CONTINUE WHEN NEW.provider IS NULL OR prov <> NEW.provider;
932 IF (atype = 'lineitem_provider_attr_definition') THEN
933 SELECT xpath INTO xpath_string FROM acq.lineitem_provider_attr_definition WHERE id = adef.id;
934 ELSIF (atype = 'lineitem_marc_attr_definition') THEN
935 SELECT xpath INTO xpath_string FROM acq.lineitem_marc_attr_definition WHERE id = adef.id;
936 ELSIF (atype = 'lineitem_generated_attr_definition') THEN
937 SELECT xpath INTO xpath_string FROM acq.lineitem_generated_attr_definition WHERE id = adef.id;
940 SELECT extract_acq_marc_field(id, xpath_string, adef.remove) INTO value FROM acq.lineitem WHERE id = NEW.id;
942 IF (value IS NOT NULL AND value <> '') THEN
943 INSERT INTO acq.lineitem_attr (lineitem, definition, attr_type, attr_name, attr_value)
944 VALUES (NEW.id, adef.id, atype, adef.code, value);
955 CREATE OR REPLACE FUNCTION public.cleanup_acq_marc ( ) RETURNS TRIGGER AS $$
957 IF TG_OP = 'UPDATE' THEN
958 DELETE FROM acq.lineitem_attr
959 WHERE lineitem = OLD.id AND attr_type IN ('lineitem_provider_attr_definition', 'lineitem_marc_attr_definition','lineitem_generated_attr_definition');
962 DELETE FROM acq.lineitem_attr WHERE lineitem = OLD.id;
968 CREATE TRIGGER cleanup_lineitem_trigger
969 BEFORE UPDATE OR DELETE ON acq.lineitem
970 FOR EACH ROW EXECUTE PROCEDURE public.cleanup_acq_marc();
972 CREATE TRIGGER ingest_lineitem_trigger
973 AFTER INSERT OR UPDATE ON acq.lineitem
974 FOR EACH ROW EXECUTE PROCEDURE public.ingest_acq_marc();
976 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( from_ex TEXT, to_ex TEXT ) RETURNS NUMERIC AS $$
980 IF from_ex = to_ex THEN
984 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = from_ex AND to_currency = to_ex;
989 SELECT ratio INTO rat FROM acq.exchange_rate WHERE from_currency = to_ex AND to_currency = from_ex;
1000 CREATE OR REPLACE FUNCTION acq.exchange_ratio ( TEXT, TEXT, NUMERIC ) RETURNS NUMERIC AS $$
1001 SELECT $3 * acq.exchange_ratio($1, $2);
1004 CREATE OR REPLACE FUNCTION acq.find_bad_fy()
1006 Examine the acq.fiscal_year table, comparing successive years.
1007 Report any inconsistencies, i.e. years that overlap, have gaps
1008 between them, or are out of sequence.
1010 RETURNS SETOF RECORD AS $$
1034 ELSIF curr_year.calendar = prev_year.calendar THEN
1035 IF curr_year.year_begin > prev_year.year_end THEN
1036 -- This ugly kludge works around the fact that older
1037 -- versions of PostgreSQL don't support RETURN QUERY SELECT
1038 FOR return_rec IN SELECT
1041 'Gap between fiscal years'::TEXT
1043 RETURN NEXT return_rec;
1045 ELSIF curr_year.year_begin < prev_year.year_end THEN
1046 FOR return_rec IN SELECT
1049 'Overlapping fiscal years'::TEXT
1051 RETURN NEXT return_rec;
1053 ELSIF curr_year.year < prev_year.year THEN
1054 FOR return_rec IN SELECT
1057 'Fiscal years out of order'::TEXT
1059 RETURN NEXT return_rec;
1064 prev_year := curr_year;
1069 $$ LANGUAGE plpgsql;
1071 CREATE OR REPLACE FUNCTION acq.transfer_fund(
1073 old_amount IN NUMERIC, -- in currency of old fund
1075 new_amount IN NUMERIC, -- in currency of new fund
1077 xfer_note IN TEXT -- to be recorded in acq.fund_transfer
1078 -- ,funding_source_in IN INT -- if user wants to specify a funding source (see notes)
1079 ) RETURNS VOID AS $$
1080 /* -------------------------------------------------------------------------------
1082 Function to transfer money from one fund to another.
1084 A transfer is represented as a pair of entries in acq.fund_allocation, with a
1085 negative amount for the old (losing) fund and a positive amount for the new
1086 (gaining) fund. In some cases there may be more than one such pair of entries
1087 in order to pull the money from different funding sources, or more specifically
1088 from different funding source credits. For each such pair there is also an
1089 entry in acq.fund_transfer.
1091 Since funding_source is a non-nullable column in acq.fund_allocation, we must
1092 choose a funding source for the transferred money to come from. This choice
1093 must meet two constraints, so far as possible:
1095 1. The amount transferred from a given funding source must not exceed the
1096 amount allocated to the old fund by the funding source. To that end we
1097 compare the amount being transferred to the amount allocated.
1099 2. We shouldn't transfer money that has already been spent or encumbered, as
1100 defined by the funding attribution process. We attribute expenses to the
1101 oldest funding source credits first. In order to avoid transferring that
1102 attributed money, we reverse the priority, transferring from the newest funding
1103 source credits first. There can be no guarantee that this approach will
1104 avoid overcommitting a fund, but no other approach can do any better.
1106 In this context the age of a funding source credit is defined by the
1107 deadline_date for credits with deadline_dates, and by the effective_date for
1108 credits without deadline_dates, with the proviso that credits with deadline_dates
1109 are all considered "older" than those without.
1113 In the signature for this function, there is one last parameter commented out,
1114 named "funding_source_in". Correspondingly, the WHERE clause for the query
1115 driving the main loop has an OR clause commented out, which references the
1116 funding_source_in parameter.
1118 If these lines are uncommented, this function will allow the user optionally to
1119 restrict a fund transfer to a specified funding source. If the source
1120 parameter is left NULL, then there will be no such restriction.
1122 ------------------------------------------------------------------------------- */
1124 same_currency BOOLEAN;
1125 currency_ratio NUMERIC;
1126 old_fund_currency TEXT;
1127 old_remaining NUMERIC; -- in currency of old fund
1128 new_fund_currency TEXT;
1129 new_fund_active BOOLEAN;
1130 new_remaining NUMERIC; -- in currency of new fund
1131 curr_old_amt NUMERIC; -- in currency of old fund
1132 curr_new_amt NUMERIC; -- in currency of new fund
1133 source_addition NUMERIC; -- in currency of funding source
1134 source_deduction NUMERIC; -- in currency of funding source
1135 orig_allocated_amt NUMERIC; -- in currency of funding source
1136 allocated_amt NUMERIC; -- in currency of fund
1142 IF old_fund IS NULL THEN
1143 RAISE EXCEPTION 'acq.transfer_fund: old fund id is NULL';
1146 IF old_amount IS NULL THEN
1147 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer is NULL';
1150 -- The new fund and its amount must be both NULL or both not NULL.
1152 IF new_fund IS NOT NULL AND new_amount IS NULL THEN
1153 RAISE EXCEPTION 'acq.transfer_fund: amount to transfer to receiving fund is NULL';
1156 IF new_fund IS NULL AND new_amount IS NOT NULL THEN
1157 RAISE EXCEPTION 'acq.transfer_fund: receiving fund is NULL, its amount is not NULL';
1160 IF user_id IS NULL THEN
1161 RAISE EXCEPTION 'acq.transfer_fund: user id is NULL';
1164 -- Initialize the amounts to be transferred, each denominated
1165 -- in the currency of its respective fund. They will be
1166 -- reduced on each iteration of the loop.
1168 old_remaining := old_amount;
1169 new_remaining := new_amount;
1171 -- RAISE NOTICE 'Transferring % in fund % to % in fund %',
1172 -- old_amount, old_fund, new_amount, new_fund;
1174 -- Get the currency types of the old and new funds.
1185 IF old_fund_currency IS NULL THEN
1186 RAISE EXCEPTION 'acq.transfer_fund: old fund id % is not defined', old_fund;
1189 IF new_fund IS NOT NULL THEN
1201 IF new_fund_currency IS NULL THEN
1202 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is not defined', new_fund;
1203 ELSIF NOT new_fund_active THEN
1205 -- No point in putting money into a fund from whence you can't spend it
1207 RAISE EXCEPTION 'acq.transfer_fund: new fund id % is inactive', new_fund;
1210 IF new_amount = old_amount THEN
1211 same_currency := true;
1212 currency_ratio := 1;
1215 -- We'll have to translate currency between funds. We presume that
1216 -- the calling code has already applied an appropriate exchange rate,
1217 -- so we'll apply the same conversion to each sub-transfer.
1219 same_currency := false;
1220 currency_ratio := new_amount / old_amount;
1224 -- Identify the funding source(s) from which we want to transfer the money.
1225 -- The principle is that we want to transfer the newest money first, because
1226 -- we spend the oldest money first. The priority for spending is defined
1227 -- by a sort of the view acq.ordered_funding_source_credit.
1232 ofsc.funding_source,
1234 ofsc.amount * acq.exchange_ratio( fs.currency_type, old_fund_currency )
1238 acq.ordered_funding_source_credit AS ofsc,
1239 acq.funding_source fs
1241 ofsc.funding_source = fs.id
1242 and ofsc.funding_source IN
1244 SELECT funding_source
1245 FROM acq.fund_allocation
1246 WHERE fund = old_fund
1250 -- ofsc.funding_source = funding_source_in
1251 -- OR funding_source_in IS NULL
1254 ofsc.sort_priority desc,
1255 ofsc.sort_date desc,
1259 -- Determine how much money the old fund got from this funding source,
1260 -- denominated in the currency types of the source and of the fund.
1261 -- This result may reflect transfers from previous iterations.
1264 COALESCE( sum( amount ), 0 ),
1265 COALESCE( sum( amount )
1266 * acq.exchange_ratio( source.currency_type, old_fund_currency ), 0 )
1268 orig_allocated_amt, -- in currency of the source
1269 allocated_amt -- in currency of the old fund
1274 and funding_source = source.funding_source;
1276 -- Determine how much to transfer from this credit, in the currency
1277 -- of the fund. Begin with the amount remaining to be attributed:
1279 curr_old_amt := old_remaining;
1281 -- Can't attribute more than was allocated from the fund:
1283 IF curr_old_amt > allocated_amt THEN
1284 curr_old_amt := allocated_amt;
1287 -- Can't attribute more than the amount of the current credit:
1289 IF curr_old_amt > source.converted_amt THEN
1290 curr_old_amt := source.converted_amt;
1293 curr_old_amt := trunc( curr_old_amt, 2 );
1295 old_remaining := old_remaining - curr_old_amt;
1297 -- Determine the amount to be deducted, if any,
1298 -- from the old allocation.
1300 IF old_remaining > 0 THEN
1302 -- In this case we're using the whole allocation, so use that
1303 -- amount directly instead of applying a currency translation
1304 -- and thereby inviting round-off errors.
1306 source_deduction := - orig_allocated_amt;
1308 source_deduction := trunc(
1309 ( - curr_old_amt ) *
1310 acq.exchange_ratio( old_fund_currency, source.currency_type ),
1314 IF source_deduction <> 0 THEN
1316 -- Insert negative allocation for old fund in fund_allocation,
1317 -- converted into the currency of the funding source
1319 INSERT INTO acq.fund_allocation (
1326 source.funding_source,
1330 'Transfer to fund ' || new_fund
1334 IF new_fund IS NOT NULL THEN
1336 -- Determine how much to add to the new fund, in
1337 -- its currency, and how much remains to be added:
1339 IF same_currency THEN
1340 curr_new_amt := curr_old_amt;
1342 IF old_remaining = 0 THEN
1344 -- This is the last iteration, so nothing should be left
1346 curr_new_amt := new_remaining;
1349 curr_new_amt := trunc( curr_old_amt * currency_ratio, 2 );
1350 new_remaining := new_remaining - curr_new_amt;
1354 -- Determine how much to add, if any,
1355 -- to the new fund's allocation.
1357 IF old_remaining > 0 THEN
1359 -- In this case we're using the whole allocation, so use that amount
1360 -- amount directly instead of applying a currency translation and
1361 -- thereby inviting round-off errors.
1363 source_addition := orig_allocated_amt;
1364 ELSIF source.currency_type = old_fund_currency THEN
1366 -- In this case we don't need a round trip currency translation,
1367 -- thereby inviting round-off errors:
1369 source_addition := curr_old_amt;
1371 source_addition := trunc(
1373 acq.exchange_ratio( new_fund_currency, source.currency_type ),
1377 IF source_addition <> 0 THEN
1379 -- Insert positive allocation for new fund in fund_allocation,
1380 -- converted to the currency of the founding source
1382 INSERT INTO acq.fund_allocation (
1389 source.funding_source,
1393 'Transfer from fund ' || old_fund
1398 IF trunc( curr_old_amt, 2 ) <> 0
1399 OR trunc( curr_new_amt, 2 ) <> 0 THEN
1401 -- Insert row in fund_transfer, using amounts in the currency of the funds
1403 INSERT INTO acq.fund_transfer (
1410 funding_source_credit
1413 trunc( curr_old_amt, 2 ),
1415 trunc( curr_new_amt, 2 ),
1422 if old_remaining <= 0 THEN
1423 EXIT; -- Nothing more to be transferred
1427 $$ LANGUAGE plpgsql;
1429 CREATE OR REPLACE FUNCTION acq.attribute_debits() RETURNS VOID AS $$
1431 Function to attribute expenditures and encumbrances to funding source credits,
1432 and thereby to funding sources.
1434 Read the debits in chonological order, attributing each one to one or
1435 more funding source credits. Constraints:
1437 1. Don't attribute more to a credit than the amount of the credit.
1439 2. For a given fund, don't attribute more to a funding source than the
1440 source has allocated to that fund.
1442 3. Attribute debits to credits with deadlines before attributing them to
1443 credits without deadlines. Otherwise attribute to the earliest credits
1444 first, based on the deadline date when present, or on the effective date
1445 when there is no deadline. Use funding_source_credit.id as a tie-breaker.
1446 This ordering is defined by an ORDER BY clause on the view
1447 acq.ordered_funding_source_credit.
1449 Start by truncating the table acq.debit_attribution. Then insert a row
1450 into that table for each attribution. If a debit cannot be fully
1451 attributed, insert a row for the unattributable balance, with the
1452 funding_source_credit and credit_amount columns NULL.
1455 curr_fund_source_bal RECORD;
1456 seqno INT; -- sequence num for credits applicable to a fund
1457 fund_credit RECORD; -- current row in temp t_fund_credit table
1458 fc RECORD; -- used for loading t_fund_credit table
1459 sc RECORD; -- used for loading t_fund_credit table
1461 -- Used exclusively in the main loop:
1463 deb RECORD; -- current row from acq.fund_debit table
1464 curr_credit_bal RECORD; -- current row from temp t_credit table
1465 debit_balance NUMERIC; -- amount left to attribute for current debit
1466 conv_debit_balance NUMERIC; -- debit balance in currency of the fund
1467 attr_amount NUMERIC; -- amount being attributed, in currency of debit
1468 conv_attr_amount NUMERIC; -- amount being attributed, in currency of source
1469 conv_cred_balance NUMERIC; -- credit_balance in the currency of the fund
1470 conv_alloc_balance NUMERIC; -- allocated balance in the currency of the fund
1471 attrib_count INT; -- populates id of acq.debit_attribution
1474 -- Load a temporary table. For each combination of fund and funding source,
1475 -- load an entry with the total amount allocated to that fund by that source.
1476 -- This sum may reflect transfers as well as original allocations. We will
1477 -- reduce this balance whenever we attribute debits to it.
1479 CREATE TEMP TABLE t_fund_source_bal
1483 funding_source AS source,
1484 sum( amount ) AS balance
1493 CREATE INDEX t_fund_source_bal_idx
1494 ON t_fund_source_bal( fund, source );
1495 -------------------------------------------------------------------------------
1497 -- Load another temporary table. For each fund, load zero or more
1498 -- funding source credits from which that fund can get money.
1500 CREATE TEMP TABLE t_fund_credit (
1507 SELECT DISTINCT fund
1508 FROM acq.fund_allocation
1510 LOOP -- Loop over the funds
1516 acq.ordered_funding_source_credit AS ofsc
1518 ofsc.funding_source IN
1520 SELECT funding_source
1521 FROM acq.fund_allocation
1522 WHERE fund = fc.fund
1528 LOOP -- Add each credit to the list
1529 INSERT INTO t_fund_credit (
1538 --RAISE NOTICE 'Fund % credit %', fc.fund, sc.id;
1540 END LOOP; -- Loop over credits for a given fund
1541 END LOOP; -- Loop over funds
1543 CREATE INDEX t_fund_credit_idx
1544 ON t_fund_credit( fund, seq );
1545 -------------------------------------------------------------------------------
1547 -- Load yet another temporary table. This one is a list of funding source
1548 -- credits, with their balances. We shall reduce those balances as we
1549 -- attribute debits to them.
1551 CREATE TEMP TABLE t_credit
1555 fsc.funding_source AS source,
1556 fsc.amount AS balance,
1557 fs.currency_type AS currency_type
1559 acq.funding_source_credit AS fsc,
1560 acq.funding_source fs
1562 fsc.funding_source = fs.id
1565 CREATE INDEX t_credit_idx
1566 ON t_credit( credit );
1568 -------------------------------------------------------------------------------
1570 -- Now that we have loaded the lookup tables: loop through the debits,
1571 -- attributing each one to one or more funding source credits.
1573 truncate table acq.debit_attribution;
1591 --RAISE NOTICE 'Debit %, fund %', deb.id, deb.fund;
1593 debit_balance := deb.amount;
1595 -- Loop over the funding source credits that are eligible
1596 -- to pay for this debit
1608 --RAISE NOTICE ' Examining credit %', fund_credit.credit;
1610 -- Look up the balance for this credit. If it's zero, then
1611 -- it's not useful, so treat it as if you didn't find it.
1612 -- (Actually there shouldn't be any zero balances in the table,
1613 -- but we check just to make sure.)
1616 INTO curr_credit_bal
1619 credit = fund_credit.credit
1622 IF curr_credit_bal IS NULL THEN
1624 -- This credit is exhausted; try the next one.
1630 -- At this point we have an applicable credit with some money left.
1631 -- Now see if the relevant funding_source has any money left.
1633 -- Look up the balance of the allocation for this combination of
1634 -- fund and source. If you find such an entry, but it has a zero
1635 -- balance, then it's not useful, so treat it as unfound.
1636 -- (Actually there shouldn't be any zero balances in the table,
1637 -- but we check just to make sure.)
1640 INTO curr_fund_source_bal
1641 FROM t_fund_source_bal
1644 AND source = curr_credit_bal.source
1647 IF curr_fund_source_bal IS NULL THEN
1649 -- This fund/source doesn't exist or is already exhausted,
1650 -- so we can't use this credit. Go on to the next one.
1655 -- Convert the available balances to the currency of the fund
1657 conv_alloc_balance := curr_fund_source_bal.balance * acq.exchange_ratio(
1658 curr_credit_bal.currency_type, deb.currency_type );
1659 conv_cred_balance := curr_credit_bal.balance * acq.exchange_ratio(
1660 curr_credit_bal.currency_type, deb.currency_type );
1662 -- Determine how much we can attribute to this credit: the minimum
1663 -- of the debit amount, the fund/source balance, and the
1666 --RAISE NOTICE ' deb bal %', debit_balance;
1667 --RAISE NOTICE ' source % balance %', curr_credit_bal.source, conv_alloc_balance;
1668 --RAISE NOTICE ' credit % balance %', curr_credit_bal.credit, conv_cred_balance;
1670 conv_attr_amount := NULL;
1671 attr_amount := debit_balance;
1673 IF attr_amount > conv_alloc_balance THEN
1674 attr_amount := conv_alloc_balance;
1675 conv_attr_amount := curr_fund_source_bal.balance;
1677 IF attr_amount > conv_cred_balance THEN
1678 attr_amount := conv_cred_balance;
1679 conv_attr_amount := curr_credit_bal.balance;
1682 -- If we're attributing all of one of the balances, then that's how
1683 -- much we will deduct from the balances, and we already captured
1684 -- that amount above. Otherwise we must convert the amount of the
1685 -- attribution from the currency of the fund back to the currency of
1686 -- the funding source.
1688 IF conv_attr_amount IS NULL THEN
1689 conv_attr_amount := attr_amount * acq.exchange_ratio(
1690 deb.currency_type, curr_credit_bal.currency_type );
1693 -- Insert a row to record the attribution
1695 attrib_count := attrib_count + 1;
1696 INSERT INTO acq.debit_attribution (
1700 funding_source_credit,
1706 curr_credit_bal.credit,
1710 -- Subtract the attributed amount from the various balances
1712 debit_balance := debit_balance - attr_amount;
1713 curr_fund_source_bal.balance := curr_fund_source_bal.balance - conv_attr_amount;
1715 IF curr_fund_source_bal.balance <= 0 THEN
1717 -- This allocation is exhausted. Delete it so
1718 -- that we don't waste time looking at it again.
1720 DELETE FROM t_fund_source_bal
1722 fund = curr_fund_source_bal.fund
1723 AND source = curr_fund_source_bal.source;
1725 UPDATE t_fund_source_bal
1726 SET balance = balance - conv_attr_amount
1728 fund = curr_fund_source_bal.fund
1729 AND source = curr_fund_source_bal.source;
1732 IF curr_credit_bal.balance <= 0 THEN
1734 -- This funding source credit is exhausted. Delete it
1735 -- so that we don't waste time looking at it again.
1737 --DELETE FROM t_credit
1739 -- credit = curr_credit_bal.credit;
1741 DELETE FROM t_fund_credit
1743 credit = curr_credit_bal.credit;
1746 SET balance = curr_credit_bal.balance
1748 credit = curr_credit_bal.credit;
1751 -- Are we done with this debit yet?
1753 IF debit_balance <= 0 THEN
1754 EXIT; -- We've fully attributed this debit; stop looking at credits.
1756 END LOOP; -- End loop over credits
1758 IF debit_balance <> 0 THEN
1760 -- We weren't able to attribute this debit, or at least not
1761 -- all of it. Insert a row for the unattributed balance.
1763 attrib_count := attrib_count + 1;
1764 INSERT INTO acq.debit_attribution (
1768 funding_source_credit,
1778 END LOOP; -- End of loop over debits
1780 $$ LANGUAGE 'plpgsql';
1782 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_unit(
1786 ) RETURNS VOID AS $$
1797 IF old_year IS NULL THEN
1798 RAISE EXCEPTION 'Input year argument is NULL';
1799 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1800 RAISE EXCEPTION 'Input year is out of range';
1803 IF user_id IS NULL THEN
1804 RAISE EXCEPTION 'Input user id argument is NULL';
1807 IF org_unit_id IS NULL THEN
1808 RAISE EXCEPTION 'Org unit id argument is NULL';
1810 SELECT TRUE INTO org_found
1812 WHERE id = org_unit_id;
1814 IF org_found IS NULL THEN
1815 RAISE EXCEPTION 'Org unit id is invalid';
1819 -- Loop over the applicable funds
1821 FOR old_fund in SELECT * FROM acq.fund
1825 AND org = org_unit_id
1828 INSERT INTO acq.fund (
1840 old_fund.currency_type,
1845 RETURNING id INTO new_id;
1847 WHEN unique_violation THEN
1848 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
1851 --RAISE NOTICE 'Propagating fund % to fund %',
1852 -- old_fund.code, new_id;
1855 $$ LANGUAGE plpgsql;
1857 CREATE OR REPLACE FUNCTION acq.propagate_funds_by_org_tree(
1861 ) RETURNS VOID AS $$
1872 IF old_year IS NULL THEN
1873 RAISE EXCEPTION 'Input year argument is NULL';
1874 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1875 RAISE EXCEPTION 'Input year is out of range';
1878 IF user_id IS NULL THEN
1879 RAISE EXCEPTION 'Input user id argument is NULL';
1882 IF org_unit_id IS NULL THEN
1883 RAISE EXCEPTION 'Org unit id argument is NULL';
1885 SELECT TRUE INTO org_found
1887 WHERE id = org_unit_id;
1889 IF org_found IS NULL THEN
1890 RAISE EXCEPTION 'Org unit id is invalid';
1894 -- Loop over the applicable funds
1896 FOR old_fund in SELECT * FROM acq.fund
1901 SELECT id FROM actor.org_unit_descendants( org_unit_id )
1905 INSERT INTO acq.fund (
1917 old_fund.currency_type,
1922 RETURNING id INTO new_id;
1924 WHEN unique_violation THEN
1925 --RAISE NOTICE 'Fund % already propagated', old_fund.id;
1928 --RAISE NOTICE 'Propagating fund % to fund %',
1929 -- old_fund.code, new_id;
1932 $$ LANGUAGE plpgsql;
1934 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_unit(
1938 ) RETURNS VOID AS $$
1942 new_year INT := old_year + 1;
1944 xfer_amount NUMERIC;
1953 IF old_year IS NULL THEN
1954 RAISE EXCEPTION 'Input year argument is NULL';
1955 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
1956 RAISE EXCEPTION 'Input year is out of range';
1959 IF user_id IS NULL THEN
1960 RAISE EXCEPTION 'Input user id argument is NULL';
1963 IF org_unit_id IS NULL THEN
1964 RAISE EXCEPTION 'Org unit id argument is NULL';
1967 -- Validate the org unit
1972 WHERE id = org_unit_id;
1974 IF org_found IS NULL THEN
1975 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
1979 -- Loop over the propagable funds to identify the details
1980 -- from the old fund plus the id of the new one, if it exists.
1984 oldf.id AS old_fund,
1990 newf.id AS new_fund_id
1993 LEFT JOIN acq.fund AS newf
1994 ON ( oldf.code = newf.code )
1996 oldf.org = org_unit_id
1997 and oldf.year = old_year
1999 and newf.year = new_year
2001 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2003 IF roll_fund.new_fund_id IS NULL THEN
2005 -- The old fund hasn't been propagated yet. Propagate it now.
2007 INSERT INTO acq.fund (
2019 roll_fund.currency_type,
2024 RETURNING id INTO new_fund;
2026 new_fund = roll_fund.new_fund_id;
2029 -- Determine the amount to transfer
2033 FROM acq.fund_spent_balance
2034 WHERE fund = roll_fund.old_fund;
2036 IF xfer_amount <> 0 THEN
2037 IF roll_fund.rollover THEN
2039 -- Transfer balance from old fund to new
2041 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2043 PERFORM acq.transfer_fund(
2053 -- Transfer balance from old fund to the void
2055 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2057 PERFORM acq.transfer_fund(
2068 IF roll_fund.rollover THEN
2070 -- Move any lineitems from the old fund to the new one
2071 -- where the associated debit is an encumbrance.
2073 -- Any other tables tying expenditure details to funds should
2074 -- receive similar treatment. At this writing there are none.
2076 UPDATE acq.lineitem_detail
2079 fund = roll_fund.old_fund -- this condition may be redundant
2085 fund = roll_fund.old_fund
2089 -- Move encumbrance debits from the old fund to the new fund
2091 UPDATE acq.fund_debit
2094 fund = roll_fund.old_fund
2098 -- Mark old fund as inactive, now that we've closed it
2102 WHERE id = roll_fund.old_fund;
2105 $$ LANGUAGE plpgsql;
2107 CREATE OR REPLACE FUNCTION acq.rollover_funds_by_org_tree(
2111 ) RETURNS VOID AS $$
2115 new_year INT := old_year + 1;
2117 xfer_amount NUMERIC;
2126 IF old_year IS NULL THEN
2127 RAISE EXCEPTION 'Input year argument is NULL';
2128 ELSIF old_year NOT BETWEEN 2008 and 2200 THEN
2129 RAISE EXCEPTION 'Input year is out of range';
2132 IF user_id IS NULL THEN
2133 RAISE EXCEPTION 'Input user id argument is NULL';
2136 IF org_unit_id IS NULL THEN
2137 RAISE EXCEPTION 'Org unit id argument is NULL';
2140 -- Validate the org unit
2145 WHERE id = org_unit_id;
2147 IF org_found IS NULL THEN
2148 RAISE EXCEPTION 'Org unit id % is invalid', org_unit_id;
2152 -- Loop over the propagable funds to identify the details
2153 -- from the old fund plus the id of the new one, if it exists.
2157 oldf.id AS old_fund,
2163 newf.id AS new_fund_id
2166 LEFT JOIN acq.fund AS newf
2167 ON ( oldf.code = newf.code )
2169 oldf.year = old_year
2171 AND newf.year = new_year
2173 SELECT id FROM actor.org_unit_descendants( org_unit_id )
2176 --RAISE NOTICE 'Processing fund %', roll_fund.old_fund;
2178 IF roll_fund.new_fund_id IS NULL THEN
2180 -- The old fund hasn't been propagated yet. Propagate it now.
2182 INSERT INTO acq.fund (
2194 roll_fund.currency_type,
2199 RETURNING id INTO new_fund;
2201 new_fund = roll_fund.new_fund_id;
2204 -- Determine the amount to transfer
2208 FROM acq.fund_spent_balance
2209 WHERE fund = roll_fund.old_fund;
2211 IF xfer_amount <> 0 THEN
2212 IF roll_fund.rollover THEN
2214 -- Transfer balance from old fund to new
2216 --RAISE NOTICE 'Transferring % from fund % to %', xfer_amount, roll_fund.old_fund, new_fund;
2218 PERFORM acq.transfer_fund(
2228 -- Transfer balance from old fund to the void
2230 -- RAISE NOTICE 'Transferring % from fund % to the void', xfer_amount, roll_fund.old_fund;
2232 PERFORM acq.transfer_fund(
2243 IF roll_fund.rollover THEN
2245 -- Move any lineitems from the old fund to the new one
2246 -- where the associated debit is an encumbrance.
2248 -- Any other tables tying expenditure details to funds should
2249 -- receive similar treatment. At this writing there are none.
2251 UPDATE acq.lineitem_detail
2254 fund = roll_fund.old_fund -- this condition may be redundant
2260 fund = roll_fund.old_fund
2264 -- Move encumbrance debits from the old fund to the new fund
2266 UPDATE acq.fund_debit
2269 fund = roll_fund.old_fund
2273 -- Mark old fund as inactive, now that we've closed it
2277 WHERE id = roll_fund.old_fund;
2280 $$ LANGUAGE plpgsql;
2282 CREATE OR REPLACE VIEW acq.funding_source_credit_total AS
2283 SELECT funding_source,
2284 SUM(amount) AS amount
2285 FROM acq.funding_source_credit
2288 CREATE OR REPLACE VIEW acq.funding_source_allocation_total AS
2289 SELECT funding_source,
2290 SUM(a.amount)::NUMERIC(100,2) AS amount
2291 FROM acq.fund_allocation a
2294 CREATE OR REPLACE VIEW acq.funding_source_balance AS
2295 SELECT COALESCE(c.funding_source, a.funding_source) AS funding_source,
2296 SUM(COALESCE(c.amount,0.0) - COALESCE(a.amount,0.0))::NUMERIC(100,2) AS amount
2297 FROM acq.funding_source_credit_total c
2298 FULL JOIN acq.funding_source_allocation_total a USING (funding_source)
2301 CREATE OR REPLACE VIEW acq.fund_allocation_total AS
2303 SUM(a.amount * acq.exchange_ratio(s.currency_type, f.currency_type))::NUMERIC(100,2) AS amount
2304 FROM acq.fund_allocation a
2305 JOIN acq.fund f ON (a.fund = f.id)
2306 JOIN acq.funding_source s ON (a.funding_source = s.id)
2309 CREATE OR REPLACE VIEW acq.fund_debit_total AS
2310 SELECT fund.id AS fund,
2311 fund_debit.encumbrance AS encumbrance,
2312 SUM( COALESCE( fund_debit.amount, 0 ) ) AS amount
2313 FROM acq.fund AS fund
2314 LEFT JOIN acq.fund_debit AS fund_debit
2315 ON ( fund.id = fund_debit.fund )
2318 CREATE OR REPLACE VIEW acq.fund_encumbrance_total AS
2320 SUM(amount) AS amount
2321 FROM acq.fund_debit_total
2322 WHERE encumbrance IS TRUE
2325 CREATE OR REPLACE VIEW acq.fund_spent_total AS
2327 SUM(amount) AS amount
2328 FROM acq.fund_debit_total
2329 WHERE encumbrance IS FALSE
2332 CREATE OR REPLACE VIEW acq.fund_combined_balance AS
2334 c.amount - COALESCE(d.amount,0.0) AS amount
2335 FROM acq.fund_allocation_total c
2336 LEFT JOIN acq.fund_debit_total d USING (fund);
2338 CREATE OR REPLACE VIEW acq.fund_spent_balance AS
2340 c.amount - COALESCE(d.amount,0.0) AS amount
2341 FROM acq.fund_allocation_total c
2342 LEFT JOIN acq.fund_spent_total d USING (fund);
2344 -- For each fund: the total allocation from all sources, in the
2345 -- currency of the fund (or 0 if there are no allocations)
2347 CREATE VIEW acq.all_fund_allocation_total AS
2350 COALESCE( SUM( a.amount * acq.exchange_ratio(
2351 s.currency_type, f.currency_type))::numeric(100,2), 0 )
2355 LEFT JOIN acq.fund_allocation a
2357 LEFT JOIN acq.funding_source s
2358 ON a.funding_source = s.id
2362 -- For every fund: the total encumbrances (or 0 if none),
2363 -- in the currency of the fund.
2365 CREATE VIEW acq.all_fund_encumbrance_total AS
2368 COALESCE( encumb.amount, 0 ) AS amount
2374 sum( amount ) AS amount
2381 ON f.id = encumb.fund;
2383 -- For every fund: the total spent (or 0 if none),
2384 -- in the currency of the fund.
2386 CREATE VIEW acq.all_fund_spent_total AS
2389 COALESCE( spent.amount, 0 ) AS amount
2395 sum( amount ) AS amount
2402 ON f.id = spent.fund;
2404 -- For each fund: the amount not yet spent, in the currency
2405 -- of the fund. May include encumbrances.
2407 CREATE VIEW acq.all_fund_spent_balance AS
2410 c.amount - d.amount AS amount
2411 FROM acq.all_fund_allocation_total c
2412 LEFT JOIN acq.all_fund_spent_total d USING (fund);
2414 -- For each fund: the amount neither spent nor encumbered,
2415 -- in the currency of the fund
2417 CREATE VIEW acq.all_fund_combined_balance AS
2420 a.amount - COALESCE( c.amount, 0 ) AS amount
2422 acq.all_fund_allocation_total a
2426 SUM( amount ) AS amount
2431 ) AS c USING ( fund );