-- ============================================================================ -- IDEMPOTENCY NOTE -- This script is safe to re-run on PostgreSQL 14+. -- Existing schema/DDL is preserved. -- Plain CREATE TRIGGER statements use CREATE OR REPLACE TRIGGER. -- ADD CONSTRAINT operations that lack native IF NOT EXISTS are catalog-guarded. -- ============================================================================ -- ============================================================================ -- AccuPedia Consolidated Database Schema v5.0 -- Four-Schema Source of Truth: auth / content / commerce / platform -- Explicit cross-schema referential integrity; PostgreSQL 14+ -- Target: PostgreSQL 14+ -- ============================================================================ begin; -- ============================================================================ -- EXTENSIONS -- ============================================================================ create extension if not exists pgcrypto; create extension if not exists pg_trgm; -- ============================================================================ -- SCHEMA SETUP -- ============================================================================ create schema if not exists auth; create schema if not exists content; create schema if not exists commerce; create schema if not exists platform; -- All application objects are explicitly schema-qualified. set search_path to public; -- ============================================================================ -- FINAL SCHEMA OWNERSHIP MATRIX -- ============================================================================ -- auth -- Identity, credentials, RBAC, password recovery, device security. -- -- content -- Clinical content, typed-EAV definitions/values, presentation contracts, -- modules, tags, media, and canonical search projections. -- -- commerce -- Billing profiles, plans, subscriptions, entitlements, coupons, payments, -- invoices, and refunds. -- -- platform -- Activity logs, admin audit logs, and notifications. -- -- Cross-schema dependency policy: -- auth -> no application schema -- content -> auth -- commerce -> auth, content -- platform -> auth -- -- API boundary corresponding to this ownership model: -- /auth/me = identity + roles only -- /access/me = subscriptions + entitlements + effective module access -- ============================================================================ -- ============================================================================ -- SYSTEM ENUM TYPES — OWNED BY BOUNDED CONTEXT -- ============================================================================ do $$ begin if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'device_request_status_enum' and n.nspname = 'auth' ) then create type auth.device_request_status_enum as enum ('pending', 'approved', 'rejected'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'content_kind_enum' and n.nspname = 'content' ) then create type content.content_kind_enum as enum ('point', 'pattern', 'nutrition', 'therapeutic'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'record_status_enum' and n.nspname = 'content' ) then create type content.record_status_enum as enum ('draft', 'published', 'archived'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'module_status_enum' and n.nspname = 'content' ) then create type content.module_status_enum as enum ('draft', 'active', 'inactive', 'archived'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'media_kind_enum' and n.nspname = 'content' ) then create type content.media_kind_enum as enum ('image', 'video', 'audio', 'document', 'diagram'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'attribute_value_type_enum' and n.nspname = 'content' ) then create type content.attribute_value_type_enum as enum ('text', 'number', 'boolean', 'json', 'date'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'subscription_status_enum' and n.nspname = 'commerce' ) then create type commerce.subscription_status_enum as enum ('pending', 'active', 'grace_period', 'expired', 'cancelled', 'refunded', 'suspended'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'entitlement_status_enum' and n.nspname = 'commerce' ) then create type commerce.entitlement_status_enum as enum ('active', 'expired', 'revoked'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'plan_type_enum' and n.nspname = 'commerce' ) then create type commerce.plan_type_enum as enum ('free', 'subscription', 'one_time', 'bundle'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'billing_period_enum' and n.nspname = 'commerce' ) then create type commerce.billing_period_enum as enum ('none', 'monthly', 'quarterly', 'yearly', 'lifetime'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'payment_status_enum' and n.nspname = 'commerce' ) then create type commerce.payment_status_enum as enum ('pending', 'success', 'failed', 'reversed'); end if; if not exists ( select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typname = 'notification_delivery_enum' and n.nspname = 'platform' ) then create type platform.notification_delivery_enum as enum ('pending', 'sent', 'delivered', 'failed', 'bounced'); end if; end $$; -- ============================================================================ -- UPDATED-AT TRIGGER FUNCTIONS — LOCAL TO EACH BOUNDED CONTEXT -- ============================================================================ create or replace function auth.set_updated_at() returns trigger language plpgsql as $$ begin new.updated_at := now(); return new; end; $$; create or replace function content.set_updated_at() returns trigger language plpgsql as $$ begin new.updated_at := now(); return new; end; $$; create or replace function commerce.set_updated_at() returns trigger language plpgsql as $$ begin new.updated_at := now(); return new; end; $$; create or replace function platform.set_updated_at() returns trigger language plpgsql as $$ begin new.updated_at := now(); return new; end; $$; -- ============================================================================ -- DOMAIN 1: IDENTITY, ACCESS CONTROL, RBAC & BILLING PROFILES -- ============================================================================ create table if not exists auth.app_users ( id uuid primary key default gen_random_uuid(), external_ref text, email text not null, password_hash text, display_name text, phone_number text, country text not null default 'India', preferred_language text not null default 'en', is_active boolean not null default true, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_app_users_email unique (email), constraint uq_app_users_external_ref unique (external_ref) ); create or replace trigger trg_app_users_updated_at before update on auth.app_users for each row execute function auth.set_updated_at(); create table if not exists auth.roles ( id uuid primary key default gen_random_uuid(), role_name text not null, description text, is_system_role boolean not null default false, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_roles_name unique (role_name) ); create or replace trigger trg_roles_updated_at before update on auth.roles for each row execute function auth.set_updated_at(); create table if not exists auth.user_roles ( user_id uuid not null references auth.app_users(id) on delete cascade, role_id uuid not null references auth.roles(id) on delete cascade, assigned_at timestamptz not null default now(), assigned_by uuid references auth.app_users(id) on delete set null, primary key (user_id, role_id) ); create table if not exists auth.permissions ( id uuid primary key default gen_random_uuid(), permission_key text not null, description text, module text not null default 'system', created_at timestamptz not null default now(), constraint uq_permissions_key unique (permission_key) ); create table if not exists auth.role_permissions ( role_id uuid not null references auth.roles(id) on delete cascade, permission_id uuid not null references auth.permissions(id) on delete cascade, created_at timestamptz not null default now(), primary key (role_id, permission_id) ); create table if not exists commerce.user_billing_profiles ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, label text not null default 'Default', billing_name text not null, billing_email text not null, billing_phone text, address_line1 text not null, address_line2 text, city text not null, state text not null, postal_code text not null, country text not null default 'India', gstin text, is_default boolean not null default false, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create or replace trigger trg_user_billing_profiles_updated_at before update on commerce.user_billing_profiles for each row execute function commerce.set_updated_at(); create index if not exists idx_billing_profiles_user on commerce.user_billing_profiles (user_id, is_default); -- ============================================================================ -- DOMAIN 2: DEVICE RESTRICTIONS & SESSION BOUNDARIES (SECURITY) -- ============================================================================ create table if not exists auth.devices ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, device_token text not null, device_name text, os_type text, os_version text, hardware_fingerprint text not null, is_active boolean not null default true, last_login timestamptz not null default now(), registered_at timestamptz not null default now(), constraint uq_devices_token unique (device_token), constraint uq_devices_fingerprint unique (hardware_fingerprint) ); create table if not exists auth.device_change_requests ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, old_device_fingerprint text not null, new_device_fingerprint text not null, support_ticket_id text not null, reason text, status auth.device_request_status_enum not null default 'pending', resolved_by_admin_id uuid references auth.app_users(id) on delete restrict, resolution_note text, resolved_at timestamptz, created_at timestamptz not null default now() ); -- ============================================================================ -- DOMAIN 3: CLINICAL CONTENT CATALOG -- ============================================================================ create table if not exists content.attribute_definition_sets ( id uuid primary key default gen_random_uuid(), code text not null, name text not null, attribute_prefix_code text not null, attribute_prefix_name text not null, content_kind content.content_kind_enum, description text, is_active boolean not null default true, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_attribute_definition_sets_code unique (code), constraint uq_attribute_definition_sets_prefix_code unique (attribute_prefix_code) ); -- ============================================================================ -- TEMPLATE PRESENTATION CONTRACTS -- ============================================================================ -- Presentation is intentionally separate from content.attribute_definition_sets.metadata. -- Attribute definition sets describe content structure; this table describes how -- that content is presented by a client surface (mobile/web/admin). -- -- Historical versions are retained. A partial unique index below guarantees one -- active contract per (attribute_definition_set_id, client_type). -- ============================================================================ create table if not exists content.template_presentation_contracts ( id uuid primary key default gen_random_uuid(), attribute_definition_set_id uuid not null references content.attribute_definition_sets(id) on delete cascade, client_type text not null default 'mobile', presentation_mode text not null, collection_renderer text, collection_item_renderer text, detail_renderer text not null, version_no integer not null default 1, is_active boolean not null default true, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_template_presentation_contract_version unique (attribute_definition_set_id, client_type, version_no), constraint ck_template_presentation_client_type check (length(btrim(client_type)) > 0), constraint ck_template_presentation_mode check (presentation_mode in ('collection', 'single')), constraint ck_template_presentation_version check (version_no > 0), constraint ck_template_presentation_detail_renderer check (length(btrim(detail_renderer)) > 0), constraint ck_template_presentation_collection_renderer check ( collection_renderer is null or length(btrim(collection_renderer)) > 0 ), constraint ck_template_presentation_collection_item_renderer check ( collection_item_renderer is null or length(btrim(collection_item_renderer)) > 0 ), constraint ck_template_presentation_collection_requirements check ( presentation_mode <> 'collection' or ( collection_renderer is not null and collection_item_renderer is not null ) ), constraint ck_template_presentation_single_requirements check ( presentation_mode <> 'single' or ( collection_renderer is null and collection_item_renderer is null ) ), constraint ck_template_presentation_metadata_object check (jsonb_typeof(metadata) = 'object') ); create unique index if not exists uq_template_presentation_active_client on content.template_presentation_contracts ( attribute_definition_set_id, client_type ) where is_active = true; create index if not exists idx_template_presentation_definition_set on content.template_presentation_contracts ( attribute_definition_set_id, client_type, is_active, version_no desc ); create index if not exists idx_template_presentation_client_active on content.template_presentation_contracts (client_type, is_active); create index if not exists idx_template_presentation_metadata_gin on content.template_presentation_contracts using gin (metadata jsonb_path_ops); create or replace trigger trg_template_presentation_contracts_updated_at before update on content.template_presentation_contracts for each row execute function content.set_updated_at(); comment on table content.template_presentation_contracts is 'Versioned semantic renderer contracts for content definition sets.'; comment on column content.template_presentation_contracts.client_type is 'Client presentation surface, for example mobile, web, or admin.'; comment on column content.template_presentation_contracts.presentation_mode is 'Template navigation mode: collection or single.'; comment on column content.template_presentation_contracts.collection_renderer is 'Semantic collection renderer ID; required only for collection mode.'; comment on column content.template_presentation_contracts.collection_item_renderer is 'Semantic card/list-item renderer ID; required only for collection mode.'; comment on column content.template_presentation_contracts.detail_renderer is 'Semantic detail renderer ID; always required.'; create table if not exists content.content_items ( id uuid primary key default gen_random_uuid(), attribute_definition_set_id uuid not null references content.attribute_definition_sets(id) on delete cascade, content_kind content.content_kind_enum, title text not null, slug text not null, summary text, source_key text, status content.record_status_enum not null default 'draft', is_active boolean not null default true, sort_title text generated always as (lower(title)) stored, default_language text not null default 'en', created_by uuid references auth.app_users(id) on delete restrict, updated_by uuid references auth.app_users(id) on delete restrict, published_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), version_no integer not null default 1, metadata jsonb not null default '{}'::jsonb, constraint uq_content_items_slug unique (slug), constraint ck_content_items_version check (version_no > 0) ); create unique index if not exists uq_content_items_source_key on content.content_items(source_key) where source_key is not null; create index if not exists idx_content_items_definition_set on content.content_items (attribute_definition_set_id); create index if not exists idx_content_items_slug on content.content_items(slug); create index if not exists idx_content_items_metadata_gin on content.content_items using gin (metadata jsonb_path_ops); create or replace trigger trg_content_items_updated_at before update on content.content_items for each row execute function content.set_updated_at(); create or replace function content.validate_content_status_transition() returns trigger language plpgsql set search_path = pg_catalog, public as $$ begin if old.status = new.status then return new; end if; if old.status = 'draft' and new.status in ('published', 'archived') then return new; end if; if old.status = 'published' and new.status = 'archived' then return new; end if; if old.status = 'archived' and new.status = 'draft' then return new; end if; raise exception 'Invalid content status transition: % -> %', old.status, new.status; end; $$; create or replace trigger trg_validate_content_status_transition before update of status on content.content_items for each row execute function content.validate_content_status_transition(); create or replace function content.maintain_content_published_at() returns trigger language plpgsql set search_path = pg_catalog, public as $$ begin if new.status = 'published' and old.status is distinct from 'published' then new.published_at := coalesce( new.published_at, now() ); end if; return new; end; $$; create or replace trigger trg_maintain_content_published_at before update of status on content.content_items for each row execute function content.maintain_content_published_at(); -- Multi-language Translations Table create table if not exists content.content_translations ( id uuid primary key default gen_random_uuid(), content_id uuid not null references content.content_items(id) on delete cascade, language_code text not null, title text not null, summary text, body_json jsonb not null default '{}'::jsonb, is_machine_translated boolean not null default false, translated_by uuid references auth.app_users(id) on delete set null, reviewed_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_content_translation unique (content_id, language_code) ); create or replace trigger trg_content_translations_updated_at before update on content.content_translations for each row execute function content.set_updated_at(); -- ============================================================================ -- DOMAIN 4: TAXONOMIES & TAGS -- ============================================================================ create table if not exists content.tags ( id uuid primary key default gen_random_uuid(), name text, -- Maintained for v1 queries slug text, -- Maintained for v1 queries code text, -- v2 mapping label text, -- v2 mapping description text, is_active boolean not null default true, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_tags_slug unique (slug), constraint uq_tags_code unique (code) ); create index if not exists idx_tags_slug on content.tags(slug); create or replace trigger trg_tags_updated_at before update on content.tags for each row execute function content.set_updated_at(); create table if not exists content.content_tags ( id uuid primary key default gen_random_uuid(), content_id uuid not null references content.content_items(id) on delete cascade, tag_id uuid not null references content.tags(id) on delete cascade, unique(content_id, tag_id) ); create index if not exists idx_content_tags_content on content.content_tags(content_id); create index if not exists idx_content_tags_tag on content.content_tags(tag_id); -- ============================================================================ -- DOMAIN 5: MEDIA ASSETS -- ============================================================================ create table if not exists content.media_assets ( id uuid primary key default gen_random_uuid(), media_kind content.media_kind_enum, -- v2 type safety file_name text, -- v1 column name file_path text, -- v1 column name original_filename text, -- v2 column name storage_key text, -- v2 column name mime_type text, file_size bigint, -- v1 size file_size_bytes bigint, -- v2 size width integer, -- v1 dimension width_px integer, -- v2 dimension height integer, -- v1 dimension height_px integer, -- v2 dimension duration integer, -- v1 seconds duration_seconds numeric(12,2), -- v2 seconds alt_text text, status text, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create or replace trigger trg_media_assets_updated_at before update on content.media_assets for each row execute function content.set_updated_at(); CREATE TABLE IF NOT EXISTS content.content_media ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), content_id uuid NOT NULL REFERENCES content.content_items(id) ON DELETE CASCADE, media_asset_id uuid NOT NULL REFERENCES content.media_assets(id) ON DELETE RESTRICT, media_role text NOT NULL DEFAULT 'gallery', usage_type text NOT NULL, sort_order integer NOT NULL DEFAULT 1, alt_text text, caption text, metadata jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT uq_content_media_content_asset UNIQUE (content_id, media_asset_id), CONSTRAINT ck_content_media_role CHECK (media_role IN ('primary', 'gallery')), CONSTRAINT ck_content_media_sort_order CHECK (sort_order >= 1), CONSTRAINT ck_content_media_usage_type_nonempty CHECK (btrim(usage_type) <> '') ); CREATE INDEX IF NOT EXISTS ix_content_media_content_sort ON content.content_media (content_id, sort_order); CREATE INDEX IF NOT EXISTS ix_content_media_content_usage ON content.content_media (content_id, usage_type); -- Enforce at most one primary media association per content item. CREATE UNIQUE INDEX IF NOT EXISTS uq_content_media_one_primary ON content.content_media (content_id) WHERE media_role = 'primary'; -- Recommended content.media_assets constraints/indexes. CREATE UNIQUE INDEX IF NOT EXISTS uq_media_assets_storage_key ON content.media_assets (storage_key); ALTER TABLE content.content_media ADD CONSTRAINT uq_content_media_content_asset_usage UNIQUE (content_id, media_asset_id, usage_type); -- CREATE INDEX IF NOT EXISTS ix_media_assets_sha256 -- ON content.media_assets (sha256); CREATE TABLE IF NOT EXISTS auth.password_reset_otps ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), email VARCHAR(255) NOT NULL, otp_code VARCHAR(6) NOT NULL, expires_at TIMESTAMPTZ NOT NULL, is_used BOOLEAN DEFAULT FALSE, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_password_reset_email ON auth.password_reset_otps(email); -- ============================================================================ -- DOMAIN 6: FLEXIBLE ATTRIBUTES — PRODUCTION TYPED-EAV -- ============================================================================ -- ============================================================================ -- ATTRIBUTE DEFINITIONS -- ============================================================================ create table if not exists content.attribute_definitions ( id uuid primary key default gen_random_uuid(), attribute_definition_set_id uuid not null references content.attribute_definition_sets(id) on delete cascade, -- NULL = definition may be shared by all content kinds. content_kind content.content_kind_enum, -- Stable machine-readable key. attribute_key text not null, -- Human-readable label. attribute_label text not null, -- Scalar datatype. -- -- NULL is required for object/container definitions. data_type text, -- scalar = stores an actual value. -- object = logical container composed of child definitions. definition_kind text not null default 'scalar', -- Whether this definition may appear directly at the root -- of a content item. -- -- Child-only definitions should use FALSE. is_root boolean not null default true, description text, -- For root definitions: -- required directly on the content item. -- -- For child definitions: -- may additionally be overridden/contextualized by -- content.attribute_definition_members.is_required. is_required boolean not null default false, is_searchable boolean not null default true, is_filterable boolean not null default false, -- FALSE: -- at most one value/instance under the same parent. -- -- TRUE: -- multiple ordered values/instances are permitted. is_multivalue boolean not null default false, -- Optional controlled vocabulary. -- -- Examples: -- -- ["wood", "fire", "earth", "metal", "water"] -- -- [1, 2, 3] -- -- [true, false] allowed_values jsonb, sort_order integer not null default 0, is_active boolean not null default true, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint ck_attribute_definition_kind check ( definition_kind in ( 'scalar', 'object' ) ), constraint ck_attribute_definition_data_type check ( data_type is null or data_type in ( 'text', 'rich_text', 'number', 'boolean', 'date', 'json', 'media' ) ), -- Scalar definitions require a datatype. constraint ck_attribute_definition_scalar_type check ( definition_kind <> 'scalar' or data_type is not null ), -- Object definitions are pure containers. constraint ck_attribute_definition_object_type check ( definition_kind <> 'object' or data_type is null ), constraint ck_attribute_definition_sort_order check ( sort_order >= 0 ), constraint ck_attribute_definition_allowed_values check ( allowed_values is null or jsonb_typeof(allowed_values) = 'array' ), -- Controlled values make sense only for scalar definitions. constraint ck_attribute_definition_object_allowed_values check ( definition_kind <> 'object' or allowed_values is null ) ); create unique index if not exists uq_attribute_definition_set_key on content.attribute_definitions ( attribute_definition_set_id, attribute_key ) where attribute_definition_set_id is not null; create unique index if not exists uq_attribute_definition_unscoped_key on content.attribute_definitions ( attribute_key ) where attribute_definition_set_id is null; create index if not exists idx_attribute_definitions_set on content.attribute_definitions ( attribute_definition_set_id, sort_order ); -- ============================================================================ -- ATTRIBUTE DEFINITION INDEXES -- ============================================================================ -- ============================================================ -- 1. Core lookup for definitions belonging to a definition set -- KEEP / ADD -- ============================================================ create index if not exists idx_attribute_definitions_set on content.attribute_definitions ( attribute_definition_set_id ); -- ============================================================ -- 2. Active definitions for a definition set -- REPLACE old idx_attribute_definitions_active -- ============================================================ create index if not exists idx_attribute_definitions_set_active on content.attribute_definitions ( attribute_definition_set_id, sort_order ) where is_active = true; -- ============================================================ -- 3. Active root definitions -- REPLACE old idx_attribute_definitions_root -- ============================================================ create index if not exists idx_attribute_definitions_set_root on content.attribute_definitions ( attribute_definition_set_id, sort_order ) where is_active = true and is_root = true; -- ============================================================ -- 4. Filterable definitions -- Useful for your dynamic multi-criteria search/filter builder -- ============================================================ create index if not exists idx_attribute_definitions_set_filterable on content.attribute_definitions ( attribute_definition_set_id, sort_order ) where is_active = true and is_filterable = true; -- ============================================================ -- 5. Searchable definitions -- Keep if application discovers searchable fields dynamically -- ============================================================ create index if not exists idx_attribute_definitions_set_searchable on content.attribute_definitions ( attribute_definition_set_id, sort_order ) where is_active = true and is_searchable = true; create or replace trigger trg_attribute_definitions_updated_at before update on content.attribute_definitions for each row execute function content.set_updated_at(); -- ============================================================================ -- TEMPLATE ATTRIBUTE PRESENTATIONS -- ============================================================================ -- Per-template + per-client + per-contract-version + per-attribute presentation -- overrides. Template/client/version scope is inherited from the parent -- content.template_presentation_contracts row. -- -- Effective behavior when no row exists: -- empty_behavior = 'hide' -- -- A row is therefore required only for explicit overrides or future -- attribute-presentation metadata. -- ============================================================================ create table if not exists content.template_attribute_presentations ( id uuid primary key default gen_random_uuid(), template_presentation_contract_id uuid not null references content.template_presentation_contracts(id) on delete cascade, attribute_definition_id uuid not null references content.attribute_definitions(id) on delete cascade, empty_behavior text not null default 'hide', empty_text text, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_template_attribute_presentation_contract_attribute unique (template_presentation_contract_id, attribute_definition_id), constraint ck_template_attribute_presentation_empty_behavior check (empty_behavior in ('hide', 'show')), constraint ck_template_attribute_presentation_empty_text check ( empty_text is null or length(btrim(empty_text)) > 0 ), constraint ck_template_attribute_presentation_empty_text_behavior check ( empty_behavior = 'show' or empty_text is null ), constraint ck_template_attribute_presentation_metadata_object check (jsonb_typeof(metadata) = 'object') ); create index if not exists idx_template_attribute_presentations_contract on content.template_attribute_presentations (template_presentation_contract_id); create index if not exists idx_template_attribute_presentations_attribute on content.template_attribute_presentations (attribute_definition_id); -- Enforce that the configured attribute belongs to the same definition set as -- the parent presentation contract. This invariant cannot be expressed by the -- two simple foreign keys above without duplicating the definition-set key. create or replace function content.validate_template_attribute_presentation_scope() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_contract_definition_set_id uuid; v_attribute_definition_set_id uuid; begin select attribute_definition_set_id into v_contract_definition_set_id from content.template_presentation_contracts where id = new.template_presentation_contract_id; if v_contract_definition_set_id is null then raise exception 'Presentation contract % does not exist', new.template_presentation_contract_id; end if; select attribute_definition_set_id into v_attribute_definition_set_id from content.attribute_definitions where id = new.attribute_definition_id; if v_attribute_definition_set_id is null then raise exception 'Attribute definition % does not exist', new.attribute_definition_id; end if; if v_contract_definition_set_id <> v_attribute_definition_set_id then raise exception 'Attribute definition % belongs to definition set %, but presentation contract % belongs to definition set %', new.attribute_definition_id, v_attribute_definition_set_id, new.template_presentation_contract_id, v_contract_definition_set_id; end if; return new; end; $$; create or replace trigger trg_validate_template_attribute_presentation_scope before insert or update of template_presentation_contract_id, attribute_definition_id on content.template_attribute_presentations for each row execute function content.validate_template_attribute_presentation_scope(); create or replace trigger trg_template_attribute_presentations_updated_at before update on content.template_attribute_presentations for each row execute function content.set_updated_at(); -- ============================================================================ -- ATTRIBUTE DEFINITION MEMBERS -- -- Defines recursive object composition. -- -- Example: -- -- clinical_examination -- ├── tongue -- │ ├── body -- │ └── coating -- └── pulse -- ├── rate -- └── quality -- -- Supports arbitrary practical N-level depth. -- ============================================================================ create table if not exists content.attribute_definition_members ( id uuid primary key default gen_random_uuid(), parent_attribute_definition_id uuid not null references content.attribute_definitions(id) on delete cascade, child_attribute_definition_id uuid not null references content.attribute_definitions(id) on delete restrict, sort_order integer not null default 0, -- Context-specific requirement. -- -- A child may be optional globally but required -- inside this particular parent composition. is_required boolean not null default false, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), constraint uq_attribute_definition_member unique ( parent_attribute_definition_id, child_attribute_definition_id ), constraint ck_attribute_definition_member_no_self check ( parent_attribute_definition_id <> child_attribute_definition_id ), constraint ck_attribute_definition_member_sort_order check ( sort_order >= 0 ) ); create index if not exists idx_attribute_definition_members_parent on content.attribute_definition_members ( parent_attribute_definition_id, sort_order ); create index if not exists idx_attribute_definition_members_child on content.attribute_definition_members ( child_attribute_definition_id ); -- ============================================================================ -- VALIDATE DEFINITION PARENT -- -- Rules: -- -- 1. Parent must be definition_kind='object'. -- 2. A global parent may only contain global children. -- 3. A content-kind parent may contain: -- - same content-kind child -- - global child -- ============================================================================ create or replace function content.validate_attribute_definition_member() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_parent_kind text; v_parent_content_kind content.content_kind_enum; v_child_content_kind content.content_kind_enum; begin select ad.definition_kind, ad.content_kind into v_parent_kind, v_parent_content_kind from content.attribute_definitions ad where ad.id = new.parent_attribute_definition_id; if not found then raise exception 'Parent attribute definition % does not exist', new.parent_attribute_definition_id; end if; if v_parent_kind <> 'object' then raise exception 'Attribute definition % cannot contain children because it is not an object definition', new.parent_attribute_definition_id; end if; select ad.content_kind into v_child_content_kind from content.attribute_definitions ad where ad.id = new.child_attribute_definition_id; if not found then raise exception 'Child attribute definition % does not exist', new.child_attribute_definition_id; end if; -- Global object definitions must remain globally reusable. if v_parent_content_kind is null and v_child_content_kind is not null then raise exception 'Global object definition % cannot contain content-kind-specific child definition %', new.parent_attribute_definition_id, new.child_attribute_definition_id; end if; -- Domain-specific parent may use: -- same domain -- global definition if v_parent_content_kind is not null and v_child_content_kind is not null and v_parent_content_kind <> v_child_content_kind then raise exception 'Parent and child attribute definitions belong to incompatible content kinds'; end if; return new; end; $$; create or replace trigger trg_validate_attribute_definition_member before insert or update of parent_attribute_definition_id, child_attribute_definition_id on content.attribute_definition_members for each row execute function content.validate_attribute_definition_member(); -- ============================================================================ -- DEFINITION HIERARCHY CYCLE PREVENTION -- -- Important: -- The current row is excluded during UPDATE so the previous edge -- does not interfere with cycle detection. -- ============================================================================ create or replace function content.prevent_attribute_definition_cycle() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_cycle_found boolean; begin if new.parent_attribute_definition_id = new.child_attribute_definition_id then raise exception 'Attribute definition cannot reference itself'; end if; with recursive descendants as ( select adm.child_attribute_definition_id from content.attribute_definition_members adm where adm.parent_attribute_definition_id = new.child_attribute_definition_id and adm.id <> new.id union select adm.child_attribute_definition_id from content.attribute_definition_members adm join descendants d on adm.parent_attribute_definition_id = d.child_attribute_definition_id where adm.id <> new.id ) select exists ( select 1 from descendants where child_attribute_definition_id = new.parent_attribute_definition_id ) into v_cycle_found; if v_cycle_found then raise exception 'Attribute definition hierarchy cycle detected'; end if; return new; end; $$; create or replace trigger trg_prevent_attribute_definition_cycle before insert or update of parent_attribute_definition_id, child_attribute_definition_id on content.attribute_definition_members for each row execute function content.prevent_attribute_definition_cycle(); -- ============================================================================ -- CONTENT ATTRIBUTE VALUES -- ============================================================================ create table if not exists content.content_attributes ( id uuid primary key default gen_random_uuid(), content_id uuid not null references content.content_items(id) on delete cascade, attribute_definition_id uuid not null references content.attribute_definitions(id) on delete restrict, -- NULL = root-level value -- -- UUID = child value belonging to another object value. parent_attribute_value_id uuid references content.content_attributes(id) on delete cascade, -- -------------------------------------------------------------------------- -- TYPED VALUE CONTAINERS -- -- Scalar definition: -- exactly one appropriate column populated. -- -- Object definition: -- all value columns NULL. -- -------------------------------------------------------------------------- value_text text, value_number numeric(18,6), value_boolean boolean, value_date date, value_json jsonb, media_asset_id uuid references content.media_assets(id) on delete restrict, sort_order integer not null default 0, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint ck_content_attributes_sort_order check ( sort_order >= 0 ) ); -- ============================================================================ -- ORDER UNIQUENESS -- ============================================================================ create unique index if not exists uq_content_attribute_top_level on content.content_attributes ( content_id, attribute_definition_id, sort_order ) where parent_attribute_value_id is null; create unique index if not exists uq_content_attribute_child on content.content_attributes ( content_id, parent_attribute_value_id, attribute_definition_id, sort_order ) where parent_attribute_value_id is not null; -- ============================================================================ -- CORE ATTRIBUTE INDEXES -- ============================================================================ create index if not exists idx_content_attributes_content on content.content_attributes ( content_id ); create index if not exists idx_content_attributes_definition on content.content_attributes ( attribute_definition_id ); create index if not exists idx_content_attributes_parent on content.content_attributes ( parent_attribute_value_id ) where parent_attribute_value_id is not null; -- ============================================================================ -- TYPED FILTERING INDEXES -- ============================================================================ create index if not exists idx_content_attributes_text on content.content_attributes ( attribute_definition_id, value_text ) where value_text is not null; create index if not exists idx_content_attributes_number on content.content_attributes ( attribute_definition_id, value_number ) where value_number is not null; create index if not exists idx_content_attributes_boolean on content.content_attributes ( attribute_definition_id, value_boolean ) where value_boolean is not null; create index if not exists idx_content_attributes_date on content.content_attributes ( attribute_definition_id, value_date ) where value_date is not null; create index if not exists idx_content_attributes_json on content.content_attributes using gin ( value_json jsonb_path_ops ) where value_json is not null; create index if not exists idx_content_attributes_media on content.content_attributes ( media_asset_id ) where media_asset_id is not null; create or replace trigger trg_content_attributes_updated_at before update on content.content_attributes for each row execute function content.set_updated_at(); -- ============================================================================ -- CONTENT ATTRIBUTE VALUE VALIDATION -- -- Covers: -- -- 2. is_multivalue enforcement -- 3. content_kind compatibility -- 7. allowed_values enforcement -- -- Also validates typed physical storage. -- ============================================================================ create or replace function content.validate_content_attribute_value() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_data_type text; v_definition_kind text; v_definition_content_kind content.content_kind_enum; v_content_kind content.content_kind_enum; v_is_multivalue boolean; v_is_root boolean; v_allowed_values jsonb; v_typed_value jsonb; v_duplicate_exists boolean; v_allowed boolean; begin -- -------------------------------------------------------------------------- -- LOAD ATTRIBUTE DEFINITION -- -------------------------------------------------------------------------- select ad.data_type, ad.definition_kind, ad.content_kind, ad.is_multivalue, ad.is_root, ad.allowed_values into v_data_type, v_definition_kind, v_definition_content_kind, v_is_multivalue, v_is_root, v_allowed_values from content.attribute_definitions ad where ad.id = new.attribute_definition_id and ad.is_active = true; if not found then raise exception 'Invalid or inactive attribute definition: %', new.attribute_definition_id; end if; -- -------------------------------------------------------------------------- -- CONTENT KIND COMPATIBILITY -- -------------------------------------------------------------------------- select ci.content_kind into v_content_kind from content.content_items ci where ci.id = new.content_id; if not found then raise exception 'Content item % does not exist', new.content_id; end if; if v_definition_content_kind is not null and v_definition_content_kind is distinct from v_content_kind then raise exception 'Attribute definition % belongs to content kind %, but content item % belongs to %', new.attribute_definition_id, v_definition_content_kind, new.content_id, v_content_kind; end if; -- Child-only definitions cannot be stored directly at root. if new.parent_attribute_value_id is null and v_is_root = false then raise exception 'Attribute definition % is not permitted at the content root', new.attribute_definition_id; end if; -- -------------------------------------------------------------------------- -- OBJECT / CONTAINER -- -------------------------------------------------------------------------- if v_definition_kind = 'object' then if new.value_text is not null or new.value_number is not null or new.value_boolean is not null or new.value_date is not null or new.value_json is not null or new.media_asset_id is not null then raise exception 'Object attribute definition % cannot store scalar value', new.attribute_definition_id; end if; -- -------------------------------------------------------------------------- -- SCALAR -- -------------------------------------------------------------------------- else if v_data_type in ( 'text', 'rich_text' ) then if new.value_text is null or new.value_number is not null or new.value_boolean is not null or new.value_date is not null or new.value_json is not null or new.media_asset_id is not null then raise exception 'Attribute % expects a text value', new.attribute_definition_id; end if; v_typed_value := to_jsonb(new.value_text); elsif v_data_type = 'number' then if new.value_number is null or new.value_text is not null or new.value_boolean is not null or new.value_date is not null or new.value_json is not null or new.media_asset_id is not null then raise exception 'Attribute % expects a numeric value', new.attribute_definition_id; end if; v_typed_value := to_jsonb(new.value_number); elsif v_data_type = 'boolean' then if new.value_boolean is null or new.value_text is not null or new.value_number is not null or new.value_date is not null or new.value_json is not null or new.media_asset_id is not null then raise exception 'Attribute % expects a boolean value', new.attribute_definition_id; end if; v_typed_value := to_jsonb(new.value_boolean); elsif v_data_type = 'date' then if new.value_date is null or new.value_text is not null or new.value_number is not null or new.value_boolean is not null or new.value_json is not null or new.media_asset_id is not null then raise exception 'Attribute % expects a date value', new.attribute_definition_id; end if; v_typed_value := to_jsonb(new.value_date); elsif v_data_type = 'json' then if new.value_json is null or new.value_text is not null or new.value_number is not null or new.value_boolean is not null or new.value_date is not null or new.media_asset_id is not null then raise exception 'Attribute % expects a JSON value', new.attribute_definition_id; end if; v_typed_value := new.value_json; elsif v_data_type = 'media' then if new.media_asset_id is null or new.value_text is not null or new.value_number is not null or new.value_boolean is not null or new.value_date is not null or new.value_json is not null then raise exception 'Attribute % expects a media value', new.attribute_definition_id; end if; v_typed_value := to_jsonb(new.media_asset_id); else raise exception 'Unsupported attribute datatype: %', v_data_type; end if; -- ------------------------------------------------------------------------ -- POINT 7: -- ALLOWED VALUES -- ------------------------------------------------------------------------ if v_allowed_values is not null then select exists ( select 1 from jsonb_array_elements( v_allowed_values ) as allowed(value) where allowed.value = v_typed_value ) into v_allowed; if not v_allowed then raise exception 'Value % is not allowed for attribute definition %', v_typed_value, new.attribute_definition_id; end if; end if; end if; -- -------------------------------------------------------------------------- -- IS_MULTIVALUE ENFORCEMENT -- -- Advisory transaction lock avoids a concurrent race where two writers -- simultaneously attempt to insert a non-multivalue attribute. -- -------------------------------------------------------------------------- if v_is_multivalue = false then perform pg_advisory_xact_lock( hashtextextended( concat_ws( ':', new.content_id::text, new.attribute_definition_id::text, coalesce( new.parent_attribute_value_id::text, 'ROOT' ) ), 0 ) ); select exists ( select 1 from content.content_attributes ca where ca.content_id = new.content_id and ca.attribute_definition_id = new.attribute_definition_id and ca.parent_attribute_value_id is not distinct from new.parent_attribute_value_id and ca.id <> new.id ) into v_duplicate_exists; if v_duplicate_exists then raise exception 'Attribute definition % does not allow multiple values under the same parent', new.attribute_definition_id; end if; end if; return new; end; $$; create or replace trigger trg_validate_content_attribute_value before insert or update on content.content_attributes for each row execute function content.validate_content_attribute_value(); -- ============================================================================ -- CONTENT ATTRIBUTE PARENT VALIDATION -- -- Ensures: -- -- 1. parent exists -- 2. same content item -- 3. parent definition is an object -- 4. child definition is permitted by content.attribute_definition_members -- ============================================================================ create or replace function content.validate_content_attribute_parent() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_parent_content_id uuid; v_parent_definition_id uuid; v_parent_definition_kind text; v_allowed boolean; begin if new.parent_attribute_value_id is null then return new; end if; select ca.content_id, ca.attribute_definition_id, ad.definition_kind into v_parent_content_id, v_parent_definition_id, v_parent_definition_kind from content.content_attributes ca join content.attribute_definitions ad on ad.id = ca.attribute_definition_id where ca.id = new.parent_attribute_value_id; if not found then raise exception 'Parent attribute value % does not exist', new.parent_attribute_value_id; end if; if v_parent_content_id <> new.content_id then raise exception 'Parent and child attribute values must belong to the same content item'; end if; if v_parent_definition_kind <> 'object' then raise exception 'Parent attribute value % does not represent an object attribute', new.parent_attribute_value_id; end if; select exists ( select 1 from content.attribute_definition_members adm where adm.parent_attribute_definition_id = v_parent_definition_id and adm.child_attribute_definition_id = new.attribute_definition_id ) into v_allowed; if not v_allowed then raise exception 'Attribute definition % is not a valid child of definition %', new.attribute_definition_id, v_parent_definition_id; end if; return new; end; $$; create or replace trigger trg_validate_content_attribute_parent before insert or update of content_id, attribute_definition_id, parent_attribute_value_id on content.content_attributes for each row execute function content.validate_content_attribute_parent(); -- ============================================================================ -- VALUE TREE CYCLE PREVENTION -- -- Prevent: -- -- A -> B -> C -> A -- ============================================================================ create or replace function content.prevent_content_attribute_cycle() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_cycle_found boolean; begin if new.parent_attribute_value_id is null then return new; end if; if new.parent_attribute_value_id = new.id then raise exception 'Content attribute value cannot be its own parent'; end if; with recursive ancestors as ( select ca.id, ca.parent_attribute_value_id from content.content_attributes ca where ca.id = new.parent_attribute_value_id union select ca.id, ca.parent_attribute_value_id from content.content_attributes ca join ancestors a on ca.id = a.parent_attribute_value_id ) select exists ( select 1 from ancestors where id = new.id ) into v_cycle_found; if v_cycle_found then raise exception 'Content attribute value hierarchy cycle detected'; end if; return new; end; $$; create or replace trigger trg_prevent_content_attribute_cycle before insert or update of parent_attribute_value_id on content.content_attributes for each row execute function content.prevent_content_attribute_cycle(); -- ============================================================================ -- REQUIRED ATTRIBUTE VALIDATION -- -- Required values are NOT validated during every INSERT because objects -- may legitimately be assembled incrementally inside a transaction. -- -- Validation happens when: -- -- 1. content is published -- 2. attributes of already-published content are changed -- -- Validation triggers are DEFERRABLE INITIALLY DEFERRED so a transaction -- may temporarily contain an incomplete object tree. -- ============================================================================ CREATE OR REPLACE FUNCTION content.validate_content_required_attributes( p_content_id uuid ) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$ DECLARE v_definition_set_id uuid; v_content_status text; v_missing_attribute_key text; v_missing_parent_id uuid; BEGIN -- -------------------------------------------------------------------------- -- CONTENT -- -------------------------------------------------------------------------- SELECT ci.attribute_definition_set_id, ci.status INTO v_definition_set_id, v_content_status FROM content.content_items ci WHERE ci.id = p_content_id; -- Content may have been cascade-deleted. IF NOT FOUND THEN RETURN; END IF; -- Required validation matters only for published content. IF v_content_status <> 'published' THEN RETURN; END IF; -- -------------------------------------------------------------------------- -- REQUIRED ROOT ATTRIBUTES -- -- IMPORTANT: -- Required root definitions must come from the exact definition set used by -- this content item. Scoping only by content_kind incorrectly mixes required -- attributes across templates that share the same content kind. -- -------------------------------------------------------------------------- SELECT ad.attribute_key INTO v_missing_attribute_key FROM content.attribute_definitions ad WHERE ad.attribute_definition_set_id = v_definition_set_id AND ad.is_active = true AND ad.is_root = true AND ad.is_required = true AND NOT EXISTS ( SELECT 1 FROM content.content_attributes ca WHERE ca.content_id = p_content_id AND ca.attribute_definition_id = ad.id AND ca.parent_attribute_value_id IS NULL ) ORDER BY ad.sort_order, ad.attribute_key LIMIT 1; IF FOUND THEN RAISE EXCEPTION 'Cannot publish content %. Required root attribute "%" is missing', p_content_id, v_missing_attribute_key; END IF; -- -------------------------------------------------------------------------- -- REQUIRED CHILD ATTRIBUTES -- -- Evaluate every existing object instance regardless of depth. Keep the -- validation inside the same definition set as the content item as an extra -- guard against stale/cross-template member relationships. -- -- Requirement applies when: -- member.is_required = TRUE -- OR child definition.is_required = TRUE -- -------------------------------------------------------------------------- SELECT child_ad.attribute_key, parent_ca.id INTO v_missing_attribute_key, v_missing_parent_id FROM content.content_attributes parent_ca JOIN content.attribute_definitions parent_ad ON parent_ad.id = parent_ca.attribute_definition_id AND parent_ad.attribute_definition_set_id = v_definition_set_id JOIN content.attribute_definition_members adm ON adm.parent_attribute_definition_id = parent_ca.attribute_definition_id JOIN content.attribute_definitions child_ad ON child_ad.id = adm.child_attribute_definition_id AND child_ad.attribute_definition_set_id = v_definition_set_id WHERE parent_ca.content_id = p_content_id AND parent_ad.definition_kind = 'object' AND child_ad.is_active = true AND ( adm.is_required = true OR child_ad.is_required = true ) AND NOT EXISTS ( SELECT 1 FROM content.content_attributes child_ca WHERE child_ca.content_id = p_content_id AND child_ca.parent_attribute_value_id = parent_ca.id AND child_ca.attribute_definition_id = child_ad.id ) ORDER BY parent_ca.id, adm.sort_order, child_ad.attribute_key LIMIT 1; IF FOUND THEN RAISE EXCEPTION 'Cannot publish content %. Required child attribute "%" is missing under attribute value %', p_content_id, v_missing_attribute_key, v_missing_parent_id; END IF; END; $$; -- ============================================================================ -- CONTENT PUBLISH VALIDATION TRIGGER FUNCTION -- ============================================================================ create or replace function content.trg_validate_content_publish() returns trigger language plpgsql set search_path = pg_catalog, public as $$ begin if new.status = 'published' then perform content.validate_content_required_attributes( new.id ); end if; return new; end; $$; -- Constraint trigger is recreated explicitly because we need it -- DEFERRABLE INITIALLY DEFERRED. drop trigger if exists trg_validate_content_publish on content.content_items; create constraint trigger trg_validate_content_publish after insert or update on content.content_items deferrable initially deferred for each row execute function content.trg_validate_content_publish(); -- ============================================================================ -- KEEP PUBLISHED CONTENT VALID AFTER ATTRIBUTE CHANGES -- ============================================================================ create or replace function content.trg_validate_published_content_attributes() returns trigger language plpgsql set search_path = pg_catalog, public as $$ declare v_content_id uuid; begin v_content_id := coalesce( new.content_id, old.content_id ); perform content.validate_content_required_attributes( v_content_id ); return coalesce( new, old ); end; $$; drop trigger if exists trg_validate_published_content_attributes on content.content_attributes; create constraint trigger trg_validate_published_content_attributes after insert or update or delete on content.content_attributes deferrable initially deferred for each row execute function content.trg_validate_published_content_attributes(); -- ============================================================================ -- NORMALIZED ATTRIBUTE VALUE VIEW -- -- Convenience view for API/service reconstruction. -- ============================================================================ create or replace view v_content_attribute_values as select ca.id, ca.content_id, ca.attribute_definition_id, ca.parent_attribute_value_id, ca.sort_order, ad.attribute_key, ad.attribute_label, ad.definition_kind, ad.data_type, ad.is_root, ad.is_multivalue, ad.sort_order as definition_sort_order, case when ad.definition_kind = 'object' then null when ad.data_type in ( 'text', 'rich_text' ) then to_jsonb( ca.value_text ) when ad.data_type = 'number' then to_jsonb( ca.value_number ) when ad.data_type = 'boolean' then to_jsonb( ca.value_boolean ) when ad.data_type = 'date' then to_jsonb( ca.value_date ) when ad.data_type = 'json' then ca.value_json when ad.data_type = 'media' then to_jsonb( ca.media_asset_id ) else null end as typed_value from content.content_attributes ca join content.attribute_definitions ad on ad.id = ca.attribute_definition_id; -- ============================================================================ -- DOMAIN 7: CURATION MODULES & DISPLAY TEMPLATES -- ============================================================================ create table if not exists content.modules ( id uuid primary key default gen_random_uuid(), name text not null, slug text not null, description text, thumbnail_media_asset_id uuid references content.media_assets(id) on delete set null, status content.module_status_enum not null default 'draft', is_active boolean not null default true, preview_enabled boolean not null default false, preview_item_limit integer not null default 0, release_version text, expected_release_date date, release_notes text, metadata jsonb not null default '{}'::jsonb, created_by uuid references auth.app_users(id) on delete restrict, updated_by uuid references auth.app_users(id) on delete restrict, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_modules_slug unique (slug), constraint ck_modules_preview_limit check (preview_item_limit >= 0) ); alter table content.modules add column if not exists code text; create unique index if not exists uq_modules_code on content.modules(code) where code is not null; -- Backwards compatibility view/alias (allows queries pointing to singular 'module' to resolve) create or replace view module as select * from content.modules; create or replace trigger trg_modules_updated_at before update on content.modules for each row execute function content.set_updated_at(); create table if not exists content.module_contents ( module_id uuid not null references content.modules(id) on delete cascade, content_id uuid not null references content.content_items(id) on delete cascade, sort_order integer not null default 0, is_highlighted boolean not null default false, created_at timestamptz not null default now(), created_by uuid references auth.app_users(id), primary key (module_id, content_id) ); create table if not exists content.module_tags ( module_id uuid not null references content.modules(id) on delete cascade, tag_id uuid not null references content.tags(id) on delete cascade, created_at timestamptz not null default now(), primary key (module_id, tag_id) ); -- ============================================================================ -- DOMAIN 8: MONETIZATION, BILLING, TAX COMPLIANCE & COUPONS -- ============================================================================ create table if not exists commerce.access_plans ( id uuid primary key default gen_random_uuid(), code text not null, name text not null, description text, plan_type commerce.plan_type_enum not null, billing_period commerce.billing_period_enum not null default 'none', member_fee numeric(12,2) not null default 0, module_fee numeric(12,2) not null default 0, total_fee numeric(12,2) generated always as (member_fee + module_fee) stored, currency_code char(3) not null default 'INR', country text not null default 'India', trial_days integer not null default 0, is_active boolean not null default true, sort_order integer not null default 0, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_access_plans_code unique (code), constraint ck_member_fee_nonnegative check (member_fee >= 0), constraint ck_module_fee_nonnegative check (module_fee >= 0), constraint ck_trial_days_nonnegative check (trial_days >= 0) ); create or replace trigger trg_access_plans_updated_at before update on commerce.access_plans for each row execute function commerce.set_updated_at(); create table if not exists commerce.access_plan_modules ( plan_id uuid not null references commerce.access_plans(id) on delete cascade, module_id uuid not null references content.modules(id) on delete cascade, created_at timestamptz not null default now(), primary key (plan_id, module_id) ); create table if not exists commerce.user_subscriptions ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, plan_id uuid references commerce.access_plans(id) on delete restrict, status commerce.subscription_status_enum not null default 'pending', started_at timestamptz not null, expires_at timestamptz, cancelled_at timestamptz, cancellation_reason text, cancellation_note text, cancelled_by uuid references auth.app_users(id) on delete set null, auto_renew boolean not null default true, payment_provider text, payment_reference text, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint ck_subscription_dates check (expires_at is null or expires_at >= started_at) ); create or replace trigger trg_user_subscriptions_updated_at before update on commerce.user_subscriptions for each row execute function commerce.set_updated_at(); create table if not exists commerce.user_entitlements ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, module_id uuid not null references content.modules(id) on delete cascade, source_subscription_id uuid references commerce.user_subscriptions(id) on delete set null, source_plan_id uuid references commerce.access_plans(id) on delete set null, status commerce.entitlement_status_enum not null default 'active', granted_at timestamptz not null default now(), granted_by uuid references auth.app_users(id) on delete set null, grant_reason text, expires_at timestamptz, revoked_at timestamptz, revoked_by uuid references auth.app_users(id) on delete set null, revoke_reason text, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), metadata jsonb not null default '{}'::jsonb, constraint uq_user_entitlements_active unique (user_id, module_id, granted_at), constraint ck_user_entitlements_dates check (expires_at is null or expires_at >= granted_at) ); create or replace trigger trg_user_entitlements_updated_at before update on commerce.user_entitlements for each row execute function commerce.set_updated_at(); create table if not exists commerce.coupons ( id uuid primary key default gen_random_uuid(), code text not null, discount_type text not null, coupon_category text not null default 'general', value decimal(10,2) not null, max_discount_limit decimal(10,2) not null default 0.00, start_date timestamptz not null, end_date timestamptz not null, usage_limit integer not null default 0, usage_count integer not null default 0, applicable_plan_ids uuid[], applicable_module_ids uuid[], min_purchase_amount decimal(10,2) default 0.00, is_first_purchase_only boolean not null default false, is_active boolean not null default true, description text, created_by uuid references auth.app_users(id) on delete set null, created_at timestamptz not null default now(), constraint uq_coupons_code unique (code), constraint ck_coupon_cap check (max_discount_limit >= 0.00), constraint ck_coupon_dates check (end_date > start_date) ); create table if not exists commerce.coupon_redemptions ( id uuid primary key default gen_random_uuid(), coupon_id uuid not null references commerce.coupons(id) on delete cascade, user_id uuid not null references auth.app_users(id) on delete cascade, invoice_id uuid, redeemed_at timestamptz not null default now(), constraint uq_coupon_user unique (coupon_id, user_id) ); create table if not exists commerce.payment_transactions ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, subscription_id uuid not null references commerce.user_subscriptions(id) on delete restrict, gateway_name text not null, gateway_transaction_id text not null, status commerce.payment_status_enum not null default 'pending', amount decimal(12,2) not null, currency char(3) not null default 'INR', created_at timestamptz not null default now(), constraint uq_payment_transactions_gateway_id unique (gateway_transaction_id) ); create table if not exists commerce.invoices ( id uuid primary key default gen_random_uuid(), payment_transaction_id uuid not null references commerce.payment_transactions(id) on delete cascade, invoice_number text not null, billing_name text not null, billing_email text not null, billing_address text not null, gstin text, billing_profile_id uuid references commerce.user_billing_profiles(id) on delete set null, applied_coupon_id uuid references commerce.coupons(id) on delete restrict, base_amount decimal(12,2) not null, discount_amount decimal(12,2) not null default 0.00, taxable_amount decimal(12,2) not null, gst_amount decimal(12,2) not null default 0.00, total_amount decimal(12,2) not null, currency_code char(3) not null default 'INR', exchange_rate_to_inr decimal(12,6) not null default 1.000000, total_amount_inr decimal(12,2), created_at timestamptz not null default now(), constraint uq_invoices_number unique (invoice_number), constraint ck_gst_invoice check ( (currency_code = 'INR' and gst_amount = round(taxable_amount * 0.18, 2)) or (currency_code != 'INR' and gst_amount = 0.00) ) ); do $$ begin if not exists ( select 1 from pg_constraint c join pg_class t on t.oid = c.conrelid join pg_namespace n on n.oid = t.relnamespace where c.conname = 'fk_coupon_redemptions_invoice' and n.nspname = 'commerce' and t.relname = 'commerce.coupon_redemptions' ) then alter table commerce.coupon_redemptions add constraint fk_coupon_redemptions_invoice foreign key (invoice_id) references commerce.invoices(id) on delete set null; end if; end $$; -- ============================================================================ -- DOMAIN 9: REFUNDS & LEDGERS -- ============================================================================ create table if not exists commerce.refund_decisions ( id uuid primary key default gen_random_uuid(), payment_transaction_id uuid not null references commerce.payment_transactions(id) on delete restrict, original_paid_amount decimal(12,2) not null, original_currency char(3) not null default 'INR', calculated_reduction_percent decimal(5,2) not null, refund_amount decimal(12,2) not null, active_duration_months integer not null, support_ticket_reference text not null, reason_detail text, status auth.device_request_status_enum not null default 'pending', approved_by_admin_id uuid references auth.app_users(id) on delete restrict, decided_at timestamptz, created_at timestamptz not null default now() ); -- ============================================================================ -- DOMAIN 10: LOGS, COMPLIANCE TRIGGERS, AUDITING & NOTIFICATIONS -- ============================================================================ create table if not exists platform.user_activity_logs ( id uuid primary key default gen_random_uuid(), user_id uuid references auth.app_users(id) on delete set null, session_token text, activity_type text not null, resource_type text, resource_id uuid, search_query text, metadata jsonb not null default '{}'::jsonb, ip_address text, created_at timestamptz not null default now() ); create table if not exists platform.admin_audit_logs ( id uuid primary key default gen_random_uuid(), admin_id uuid references auth.app_users(id) on delete set null, action_type text not null, target_table text not null, target_record_id uuid not null, description text, ip_address text, created_at timestamptz not null default now() ); create table if not exists platform.notifications ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.app_users(id) on delete cascade, channel text not null default 'in_app', category text not null, title text not null, body text not null, action_url text, metadata jsonb not null default '{}'::jsonb, is_read boolean not null default false, read_at timestamptz, sent_at timestamptz, delivery_status platform.notification_delivery_enum not null default 'pending', created_at timestamptz not null default now() ); create index if not exists idx_notifications_user_unread on platform.notifications (user_id, is_read, created_at desc); -- DEVICE RESTRICTION TRIGGERS: Max 2 Active Devices Bound (Deregister Oldest) create or replace function auth.enforce_max_devices() returns trigger language plpgsql as $$ declare active_count integer; oldest_device_id uuid; begin if new.is_active = true then select count(*) into active_count from auth.devices where user_id = new.user_id and is_active = true and id != coalesce(new.id, '00000000-0000-0000-0000-000000000000'::uuid); if active_count >= 2 then select id into oldest_device_id from auth.devices where user_id = new.user_id and is_active = true and id != coalesce(new.id, '00000000-0000-0000-0000-000000000000'::uuid) order by last_login asc limit 1; update auth.devices set is_active = false where id = oldest_device_id; insert into platform.user_activity_logs (user_id, activity_type, resource_type, resource_id, metadata, ip_address) values (new.user_id, 'device_autoderegistration', 'device', oldest_device_id, jsonb_build_object('reason', 'Maximum 2 active auth.devices threshold reached', 'activated_new_device', new.hardware_fingerprint), '0.0.0.0'); end if; end if; return new; end; $$; create or replace trigger trg_enforce_max_devices before insert or update of is_active on auth.devices for each row execute function auth.enforce_max_devices(); -- DEVICE RESET TRIGGERS: Max 3 Manual Support Resets in Sliding 30-Day Window create or replace function auth.enforce_monthly_device_resets() returns trigger language plpgsql as $$ declare resets_count integer; begin select count(*) into resets_count from auth.device_change_requests where user_id = new.user_id and status = 'approved' and resolved_at >= (now() - interval '30 days'); if resets_count >= 3 then raise exception 'Device reset limit exceeded: This user has already hit the maximum of 3 manual support resets within a 30-day sliding window.'; end if; return new; end; $$; create or replace trigger trg_enforce_monthly_device_resets before insert or update of status on auth.device_change_requests for each row when (new.status = 'approved') execute function auth.enforce_monthly_device_resets(); -- ============================================================================ -- PLATFORM AUTHORIZATION VIEWS -- ============================================================================ create or replace view v_active_entitlements as select ue.user_id, ue.module_id, ue.granted_at, ue.expires_at, ue.status from commerce.user_entitlements ue where ue.status = 'active' and (ue.expires_at is null or ue.expires_at > now()); -- ============================================================================ -- DOMAIN 9: CONTENT SEARCH -- ============================================================================ create table if not exists content.search_facet_definitions ( id uuid primary key default gen_random_uuid(), code text not null, label text not null, category text not null default 'General', description text, control_type text not null default 'typeahead_multi', allow_multiple_values boolean not null default true, value_source text not null default 'projected', sort_order integer not null default 0, is_active boolean not null default true, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_search_facet_definitions_code unique (code), constraint ck_search_facet_control_type check ( control_type in ('typeahead','typeahead_multi','single_select','multi_select') ), constraint ck_search_facet_value_source check ( value_source in ('projected','controlled') ) ); create table if not exists content.search_facet_values ( id uuid primary key default gen_random_uuid(), facet_id uuid not null references content.search_facet_definitions(id) on delete cascade, value_key text not null, label text not null, aliases jsonb not null default '[]'::jsonb, sort_order integer not null default 0, is_active boolean not null default true, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint uq_search_facet_values_key unique (facet_id, value_key) ); create table if not exists content.search_facet_mappings ( id uuid primary key default gen_random_uuid(), facet_id uuid not null references content.search_facet_definitions(id) on delete cascade, attribute_definition_id uuid not null references content.attribute_definitions(id) on delete cascade, module_id uuid references content.modules(id) on delete cascade, content_kind text, mapping_strategy text not null default 'auto', weight numeric(8,4) not null default 1.0, sort_order integer not null default 0, is_active boolean not null default true, metadata jsonb not null default '{}'::jsonb, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), constraint ck_search_facet_mapping_strategy check ( mapping_strategy in ('auto','scalar','multivalue','content_ref_label') ), constraint ck_search_facet_mapping_weight check (weight > 0) ); -- PostgreSQL UNIQUE treats NULL as distinct. Expression indexes provide the -- desired idempotent mapping identity when module/content kind are optional. create unique index if not exists uq_search_facet_mapping_identity on content.search_facet_mappings ( facet_id, attribute_definition_id, coalesce(module_id, '00000000-0000-0000-0000-000000000000'::uuid), coalesce(content_kind, '') ); create table if not exists content.content_search_documents ( content_id uuid primary key references content.content_items(id) on delete cascade, template_code text not null, search_text text not null default '', search_vector tsvector not null, indexed_at timestamptz not null default now() ); create table if not exists content.content_search_facets ( id uuid primary key default gen_random_uuid(), content_id uuid not null references content.content_items(id) on delete cascade, facet_id uuid not null references content.search_facet_definitions(id) on delete cascade, mapping_id uuid not null references content.search_facet_mappings(id) on delete cascade, value_key text not null, value_label text not null, value_text text, value_number numeric, source_attribute_definition_id uuid not null references content.attribute_definitions(id) on delete cascade, source_value jsonb, indexed_at timestamptz not null default now(), constraint uq_content_search_facet_projection unique ( content_id, facet_id, mapping_id, value_key ) ); create index if not exists ix_search_facet_definitions_active_sort on content.search_facet_definitions (is_active, category, sort_order); create index if not exists ix_search_facet_values_lookup on content.search_facet_values (facet_id, is_active, label); create index if not exists ix_search_facet_mappings_attribute on content.search_facet_mappings (attribute_definition_id) where is_active = true; create index if not exists ix_search_documents_vector on content.content_search_documents using gin (search_vector); create index if not exists ix_search_documents_template on content.content_search_documents (template_code); create index if not exists ix_content_search_facets_lookup on content.content_search_facets (facet_id, value_key, content_id); create index if not exists ix_content_search_facets_content on content.content_search_facets (content_id, facet_id); create index if not exists ix_content_search_facets_label_trgm on content.content_search_facets using gin (value_label gin_trgm_ops); commit;