41 lines
2.4 KiB
PL/PgSQL
41 lines
2.4 KiB
PL/PgSQL
CREATE TABLE "messaging_consent_decisions" (
|
|
"id" UUID NOT NULL,
|
|
"organization_id" UUID NOT NULL,
|
|
"user_id" UUID NOT NULL,
|
|
"channel" VARCHAR(20) NOT NULL,
|
|
"purpose" VARCHAR(20) NOT NULL,
|
|
"granted" BOOLEAN NOT NULL,
|
|
"version" INTEGER NOT NULL,
|
|
"notice_version" VARCHAR(40),
|
|
"idempotency_key" UUID NOT NULL,
|
|
"request_hash" CHAR(64) NOT NULL,
|
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
CONSTRAINT "messaging_consent_decisions_pkey" PRIMARY KEY ("id"),
|
|
CONSTRAINT "messaging_consent_decisions_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
|
CONSTRAINT "messaging_consent_terms" CHECK (
|
|
channel IN ('EMAIL', 'WHATSAPP') AND purpose IN ('PROMOTIONS', 'CART_RECOVERY') AND version > 0
|
|
AND ((granted AND notice_version = '2026-10-07' AND notice_version IS NOT NULL) OR (NOT granted AND notice_version IS NULL))
|
|
AND request_hash ~ '^[a-f0-9]{64}$'
|
|
)
|
|
);
|
|
CREATE UNIQUE INDEX "messaging_consent_decisions_user_id_organization_id_channel_key" ON "messaging_consent_decisions"("user_id", "organization_id", "channel", "purpose", "version");
|
|
CREATE UNIQUE INDEX "messaging_consent_decisions_user_id_organization_id_idempot_key" ON "messaging_consent_decisions"("user_id", "organization_id", "idempotency_key");
|
|
CREATE INDEX "messaging_consent_decisions_user_id_organization_id_created_idx" ON "messaging_consent_decisions"("user_id", "organization_id", "created_at", "id");
|
|
|
|
CREATE FUNCTION guard_messaging_consent() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE previous_version integer;
|
|
BEGIN
|
|
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Messaging consent decisions are immutable'; END IF;
|
|
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
|
SELECT COALESCE(MAX(version), 0) INTO previous_version FROM messaging_consent_decisions
|
|
WHERE organization_id = NEW.organization_id AND user_id = NEW.user_id AND channel = NEW.channel AND purpose = NEW.purpose;
|
|
IF NEW.version::bigint <> previous_version::bigint + 1 THEN RAISE EXCEPTION 'Consent requires next version'; END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$;
|
|
CREATE TRIGGER messaging_consent_guard BEFORE INSERT OR UPDATE OR DELETE ON messaging_consent_decisions
|
|
FOR EACH ROW EXECUTE FUNCTION guard_messaging_consent();
|
|
|
|
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['messaging.read']))
|
|
WHERE is_system = true AND name = 'Owner';
|