Files
SGF/database/sql/fiscal_obligations.sql
2026-11-11 09:00:17 +02:00

26 lines
2.0 KiB
PL/PgSQL

CREATE TABLE fo_meta(policy text PRIMARY KEY,composition text NOT NULL,source_hash char(64) NOT NULL);
CREATE TABLE fo_versions(
id bigserial PRIMARY KEY,tenant_id bigint NOT NULL,company_id bigint NOT NULL,unit_id bigint NOT NULL,
record_key uuid NOT NULL,version bigint NOT NULL CHECK(version>0),previous_id bigint UNIQUE REFERENCES fo_versions(id),
action text NOT NULL CHECK(action IN('prepare','review')),state text NOT NULL CHECK(state IN('prepared','approved','refused')),
prepared_by bigint NOT NULL REFERENCES users(id),actor_id bigint NOT NULL REFERENCES users(id),
preparer_identity char(64) NOT NULL,data jsonb NOT NULL,source_basis char(64) NOT NULL,
impact jsonb NOT NULL,reason text NOT NULL CHECK(length(reason)>=10),created_at timestamptz NOT NULL,
UNIQUE(tenant_id,company_id,unit_id,record_key,version),
FOREIGN KEY(tenant_id,company_id,unit_id) REFERENCES units(tenant_id,company_id,id),
CHECK(jsonb_typeof(data)='object'),CHECK(jsonb_typeof(impact)='object'),
CHECK((action='prepare' AND state='prepared') OR (action='review' AND state IN('approved','refused'))),
CHECK(action<>'review' OR prepared_by<>actor_id)
);
CREATE TABLE fo_commands(
id bigserial PRIMARY KEY,tenant_id bigint NOT NULL,company_id bigint NOT NULL,unit_id bigint NOT NULL,
actor_id bigint NOT NULL REFERENCES users(id),command_key uuid NOT NULL,request_hash char(64) NOT NULL,
result jsonb NOT NULL,input jsonb NOT NULL,created_at timestamptz NOT NULL,
UNIQUE(tenant_id,company_id,unit_id,actor_id,command_key)
);
CREATE FUNCTION fo_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'SGF_FISCAL_OBLIGATIONS_APPEND_ONLY'; END; $$;
CREATE TRIGGER fo_meta_immutable BEFORE UPDATE OR DELETE ON fo_meta FOR EACH ROW EXECUTE FUNCTION fo_append_only();
CREATE TRIGGER fo_versions_immutable BEFORE UPDATE OR DELETE ON fo_versions FOR EACH ROW EXECUTE FUNCTION fo_append_only();
CREATE TRIGGER fo_commands_immutable BEFORE UPDATE OR DELETE ON fo_commands FOR EACH ROW EXECUTE FUNCTION fo_append_only();