CR-DBS-013 · DATABASE SCHEMA (SQL DDL)

Database Schema — SQL DDL

Production-ready PostgreSQL data definition for every in-scope Engagement & Loyalty Platform entity — tables, keys, constraints, indexes, partitions and triggers. The build target for the data layer.

ConfidentialEngine: PostgreSQL 15+Version: 1.0Date: 06 Jun 2026

Conventions

Build-target superset — authority note. This DDL is the full enterprise build target and is intentionally broader than the shipped migrations (001–016). Where this document and the shipped schema differ, the migrations and CR-DAT-005 are authoritative for what runs today. In particular the merchant-funded tables — merchant_offer (incl. match, funding_model with multiplier_split, applies_to_variant[], bank/merchant_multiplier, point_value_minor), merchant_txn_map (surrogate PK + UNIQUE(offer_id, ledger_entry_id)) and settlement/settlement_line — ship in migrations 006/007 with the shape documented in CR-DAT-005; treat those as current. Tables here without a migration (e.g. customer, card, point_lot, fulfilment_request, outbox_event, reconciliation) are roadmap.

Bootstrap — Schema, Extensions & Common Trigger

-- schema & extensions
CREATE SCHEMA IF NOT EXISTS cr;
CREATE EXTENSION IF NOT EXISTS pgcrypto;        -- gen_random_uuid(), encryption
SET search_path TO cr, public;

-- shared updated_at trigger
CREATE OR REPLACE FUNCTION cr.set_updated_at() RETURNS trigger AS $$
BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ LANGUAGE plpgsql;

-- convenience macro applied per table:
--   CREATE TRIGGER trg_<t>_upd BEFORE UPDATE ON cr.<t>
--   FOR EACH ROW EXECUTE FUNCTION cr.set_updated_at();

Reference & Partner Tables

CREATE TABLE cr.currency (
  code            CHAR(3) PRIMARY KEY,            -- ISO 4217
  minor_units     SMALLINT NOT NULL DEFAULT 2
);

CREATE TABLE cr.mcc_master (
  mcc             VARCHAR(4) PRIMARY KEY,
  description     TEXT NOT NULL,
  category_group  VARCHAR(40)
);

CREATE TABLE cr.partner (                         -- fulfilment / catalogue partners
  partner_id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  code            VARCHAR(40) UNIQUE NOT NULL,
  name            TEXT NOT NULL,
  type            VARCHAR(20) NOT NULL CHECK (type IN ('voucher','catalogue','gateway','programme')),
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','inactive')),
  endpoint        TEXT, config JSONB,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_by VARCHAR(48), updated_by VARCHAR(48)
);

CREATE TABLE cr.partner_program (                 -- airline/hotel point-transfer partners (M12)
  program_id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  partner_id      BIGINT NOT NULL REFERENCES cr.partner(partner_id),
  name            TEXT NOT NULL,
  transfer_ratio  NUMERIC(8,4) NOT NULL,          -- points -> partner units
  min_points      BIGINT NOT NULL DEFAULT 0,
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','inactive')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Operational — Customer, Card & Account

CREATE TABLE cr.customer (
  customer_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_ref    VARCHAR(64) UNIQUE NOT NULL,     -- tokenised the Bank customer id
  segment_hint    VARCHAR(40),
  birth_month_day VARCHAR(5),                       -- MM-DD for birthday rewards (no PII DOB)
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','inactive','closed')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_by VARCHAR(48), updated_by VARCHAR(48)
);

CREATE TABLE cr.card (
  card_id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  card_ref        VARCHAR(64) UNIQUE NOT NULL,      -- tokenised PAN
  customer_id     BIGINT NOT NULL REFERENCES cr.customer(customer_id),
  variant         VARCHAR(24) NOT NULL CHECK (variant IN ('CLASSIC','GOLD','PLATINUM','SIGNATURE','CORPORATE')),
  is_supplementary BOOLEAN NOT NULL DEFAULT false,
  issued_on       DATE,
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','dormant','blocked','closed')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.loyalty_account (
  account_id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id     BIGINT NOT NULL REFERENCES cr.customer(customer_id),
  card_id         BIGINT REFERENCES cr.card(card_id),
  card_variant    VARCHAR(24) NOT NULL,
  current_tier    VARCHAR(16),                       -- denormalised active tier (see account_tier)
  enrolment_date  DATE NOT NULL DEFAULT current_date,
  anniversary_md  VARCHAR(5),
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','dormant','blocked','closed')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_account_customer ON cr.loyalty_account(customer_id);

-- family / supplementary pooling (M12)
CREATE TABLE cr.account_pool (
  pool_id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  primary_account BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  name            TEXT,
  pooling_mode    VARCHAR(16) NOT NULL DEFAULT 'shared' CHECK (pooling_mode IN ('shared','separate')),
  status          VARCHAR(16) NOT NULL DEFAULT 'active',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE cr.account_pool_member (
  pool_id         BIGINT NOT NULL REFERENCES cr.account_pool(pool_id),
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  role            VARCHAR(12) NOT NULL DEFAULT 'member' CHECK (role IN ('primary','member')),
  PRIMARY KEY (pool_id, account_id)
);

Transactions (range-partitioned)

CREATE TABLE cr.ingestion_batch (
  batch_id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  source          VARCHAR(24) NOT NULL CHECK (source IN ('batch_file','api','stream')),
  received_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
  record_count    INT, control_total_minor BIGINT, checksum VARCHAR(80),
  status          VARCHAR(16) NOT NULL DEFAULT 'received' CHECK (status IN ('received','validated','processed','rejected'))
);

CREATE TABLE cr.transaction (
  txn_id          BIGINT GENERATED ALWAYS AS IDENTITY,
  external_txn_ref VARCHAR(64) NOT NULL,             -- dedupe key
  account_id      BIGINT NOT NULL,
  batch_id        BIGINT,
  amount_minor    BIGINT NOT NULL CHECK (amount_minor >= 0),
  currency        CHAR(3) NOT NULL DEFAULT 'INR',
  amount_inr_minor BIGINT,                            -- converted for intl spend
  mcc             VARCHAR(4),
  merchant_id     VARCHAR(40),
  channel         VARCHAR(16) NOT NULL CHECK (channel IN ('POS','ECOM','ATM','INTL','SI','EMI')),
  txn_type        VARCHAR(24) NOT NULL CHECK (txn_type IN ('purchase','refund','fee','emi','cash_advance','reversal')),
  txn_status      VARCHAR(16) NOT NULL DEFAULT 'posted' CHECK (txn_status IN ('posted','reversed')),
  accrual_status  VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (accrual_status IN ('pending','accrued','excluded','reversed')),
  txn_datetime    TIMESTAMPTZ NOT NULL,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (txn_id, txn_datetime),
  UNIQUE (external_txn_ref, txn_datetime)
) PARTITION BY RANGE (txn_datetime);

-- monthly partitions (created by maintenance job; example)
CREATE TABLE cr.transaction_2026_06 PARTITION OF cr.transaction
  FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
CREATE INDEX ix_txn_account ON cr.transaction(account_id, txn_datetime);
CREATE INDEX ix_txn_mcc ON cr.transaction(mcc);
CREATE INDEX ix_txn_merchant ON cr.transaction(merchant_id);

Loyalty Ledger (system of record)

CREATE TABLE cr.ledger_entry (
  entry_id        BIGINT GENERATED ALWAYS AS IDENTITY,
  account_id      BIGINT NOT NULL,
  entry_type      VARCHAR(16) NOT NULL CHECK (entry_type IN
                    ('ACCRUAL','REDEMPTION','REVERSAL','EXPIRY','ADJUSTMENT','CLAWBACK','TRANSFER','MIGRATION')),
  direction       CHAR(1) NOT NULL CHECK (direction IN ('C','D')),
  points          BIGINT NOT NULL CHECK (points > 0),
  source_type     VARCHAR(24) NOT NULL CHECK (source_type IN
                    ('transaction','campaign','tier','referral','transfer','manual','fulfilment','clawback','migration','gamification')),
  source_ref      VARCHAR(64),
  rule_id         BIGINT,
  expiry_date     DATE,                               -- for accrual lots (FIFO expiry)
  idempotency_key VARCHAR(80) UNIQUE,
  reversal_of     BIGINT,
  reason_code     VARCHAR(24),
  posted_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_by      VARCHAR(48),
  PRIMARY KEY (entry_id, posted_at)
) PARTITION BY RANGE (posted_at);
CREATE TABLE cr.ledger_entry_2026_06 PARTITION OF cr.ledger_entry
  FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
CREATE INDEX ix_ledger_account ON cr.ledger_entry(account_id, posted_at);

CREATE TABLE cr.point_lot (                           -- open accrual lots for FIFO expiry
  lot_id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  entry_id        BIGINT NOT NULL,
  original_points BIGINT NOT NULL,
  remaining_points BIGINT NOT NULL,
  earned_on       DATE NOT NULL,
  expiry_date     DATE NOT NULL,
  status          VARCHAR(12) NOT NULL DEFAULT 'open' CHECK (status IN ('open','consumed','expired'))
);
CREATE INDEX ix_lot_acct_exp ON cr.point_lot(account_id, expiry_date) WHERE status='open';

CREATE TABLE cr.point_balance (                       -- projection of ledger; reconciled nightly
  account_id      BIGINT PRIMARY KEY REFERENCES cr.loyalty_account(account_id),
  available       BIGINT NOT NULL DEFAULT 0 CHECK (available >= 0),
  pending         BIGINT NOT NULL DEFAULT 0,
  locked          BIGINT NOT NULL DEFAULT 0,
  lifetime_earned BIGINT NOT NULL DEFAULT 0,
  lifetime_redeemed BIGINT NOT NULL DEFAULT 0,
  clawback_pending BIGINT NOT NULL DEFAULT 0 CHECK (clawback_pending >= 0), -- migration 009: recoverable debt
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);
Negative-balance / clawback (migration 009). When a reversal or refund must claw back more points than the cardholder still holds (they were already redeemed), the recovery is clamped at available = 0 and the remainder is carried in clawback_pending — a recoverable debt the next accrual settles before crediting the cardholder. This keeps CHECK(available >= 0) intact and preserves the invariant (available − clawback_pending) == net ledger position. See CR-EDG-017.

Points Lots & Scheduler (migration 017)

Lot-based FIFO-by-expiry accounting + the daily scheduler's run history and status. The loyalty-scheduler worker maintains point_lot from the append-only ledger and lapses past-dated lots as idempotent EXPIRY debits.

CREATE TABLE cr.point_lot (                            -- a parcel of points with its own expiry
  lot_id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id       BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  ledger_entry_id  BIGINT REFERENCES cr.ledger_entry(entry_id),   -- ACCRUAL credit that created the lot
  rule_id          BIGINT,                                        -- accrual rule → expiry window
  source_type      VARCHAR(24) NOT NULL DEFAULT 'transaction',
  points_earned    BIGINT NOT NULL CHECK (points_earned > 0),
  points_remaining BIGINT NOT NULL CHECK (points_remaining >= 0),
  earned_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
  expires_at       DATE NOT NULL,                                 -- earned_at + rule.points_expiry_days
  status           VARCHAR(12) NOT NULL DEFAULT 'open' CHECK (status IN ('open','consumed','expired')),
  created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX uq_point_lot_entry ON cr.point_lot (ledger_entry_id) WHERE ledger_entry_id IS NOT NULL;
CREATE INDEX ix_point_lot_open ON cr.point_lot (account_id, expires_at) WHERE points_remaining > 0;
CREATE INDEX ix_point_lot_due  ON cr.point_lot (expires_at) WHERE status='open' AND points_remaining > 0;

CREATE TABLE cr.job_schedule (                        -- one row per scheduled job, live status
  job_key       VARCHAR(40) PRIMARY KEY,
  name          VARCHAR(80) NOT NULL,
  description   TEXT,
  interval_sec  INT NOT NULL DEFAULT 86400,            -- daily
  enabled       BOOLEAN NOT NULL DEFAULT true,
  last_run_id   BIGINT,
  last_status   VARCHAR(12),                            -- ok | error | running
  last_run_at   TIMESTAMPTZ,
  next_run_at   TIMESTAMPTZ,
  updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.job_run (                              -- one row per execution — pull results
  run_id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  job_key          VARCHAR(40) NOT NULL REFERENCES cr.job_schedule(job_key),
  status           VARCHAR(12) NOT NULL DEFAULT 'running' CHECK (status IN ('running','ok','error')),
  trigger          VARCHAR(12) NOT NULL DEFAULT 'schedule' CHECK (trigger IN ('schedule','manual')),
  started_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  finished_at      TIMESTAMPTZ,
  duration_ms      INT,
  accounts_scanned INT NOT NULL DEFAULT 0,
  lots_created     INT NOT NULL DEFAULT 0,
  lots_expired     INT NOT NULL DEFAULT 0,
  points_expired   BIGINT NOT NULL DEFAULT 0,
  entries_posted   INT NOT NULL DEFAULT 0,
  rules_applied    JSONB,        -- accrual rules / expiry windows that drove the run
  result           JSONB,        -- full machine-readable result (mirrored to the artifact file)
  artifact_path    TEXT,         -- kept JSON artifact on disk
  error            TEXT
);
FIFO-by-expiry. On redemption/clawback, lots are drawn down in expires_at order (soonest first by default — config_param points.consumption_order), so a customer never loses points they could have spent. The expiry job posts one idempotent EXPIRY debit per account per cutoff date (idempotency_key = expiry:<acct>:<YYYY-MM-DD>), keeping re-runs safe.

Accrual, Tier & Campaign Configuration

CREATE TABLE cr.accrual_rule (
  rule_id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name            TEXT NOT NULL,
  card_variant    VARCHAR(24)[] ,                     -- applicable variants
  earn_points     INT NOT NULL, per_amount_minor BIGINT NOT NULL,
  accelerator     JSONB,                              -- { factor, mcc_in[], merchant_in[], channel_in[] }
  exclusions      VARCHAR(24)[],
  caps            JSONB,                              -- { per_txn, daily, cycle, lifetime }
  rounding        VARCHAR(10) NOT NULL DEFAULT 'floor' CHECK (rounding IN ('floor','nearest','ceil')),
  valid_from      DATE NOT NULL, valid_to DATE,
  version         INT NOT NULL DEFAULT 1,
  status          VARCHAR(20) NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','pending_approval','active','retired')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_by VARCHAR(48), updated_by VARCHAR(48)
);

CREATE TABLE cr.tier_rule (                           -- M10
  tier_rule_id    BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tier            VARCHAR(16) NOT NULL,
  qualify_window_months INT NOT NULL DEFAULT 12,
  min_spend_minor BIGINT, min_points BIGINT,
  earn_multiplier NUMERIC(4,2) NOT NULL DEFAULT 1.0,
  benefits        JSONB,
  downgrade_grace_days INT NOT NULL DEFAULT 30,
  rank            SMALLINT NOT NULL,
  status          VARCHAR(20) NOT NULL DEFAULT 'active'
);
CREATE TABLE cr.account_tier (
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  tier            VARCHAR(16) NOT NULL,
  effective_from  DATE NOT NULL,
  effective_to    DATE,
  reason          VARCHAR(24) CHECK (reason IN ('qualified','upgrade','downgrade','grace','manual')),
  PRIMARY KEY (account_id, effective_from)
);

CREATE TABLE cr.segment (
  segment_id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name            TEXT NOT NULL,
  type            VARCHAR(12) NOT NULL DEFAULT 'dynamic' CHECK (type IN ('static','dynamic')),
  criteria        JSONB, est_size INT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.campaign (
  campaign_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name            TEXT NOT NULL,
  type            VARCHAR(28) NOT NULL CHECK (type IN
                    ('spend_threshold','milestone_ladder','first_txn','category','dormant_reactivation',
                     'festival','welcome','anniversary','birthday','surprise_delight','referral')),
  segment_id      BIGINT REFERENCES cr.segment(segment_id),
  conditions      JSONB, reward_def JSONB NOT NULL,
  budget_points   BIGINT, auto_pause_pct SMALLINT,
  enrolment_mode  VARCHAR(10) NOT NULL DEFAULT 'auto' CHECK (enrolment_mode IN ('auto','opt_in')),
  once_per_customer BOOLEAN NOT NULL DEFAULT true,
  start_date      DATE, end_date DATE,
  version         INT NOT NULL DEFAULT 1,
  status          VARCHAR(20) NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','pending_approval','active','paused','ended')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_by VARCHAR(48), updated_by VARCHAR(48)
);
CREATE TABLE cr.milestone (
  milestone_id    BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  campaign_id     BIGINT NOT NULL REFERENCES cr.campaign(campaign_id),
  sequence        SMALLINT NOT NULL,
  threshold_minor BIGINT NOT NULL, reward_def JSONB NOT NULL
);
CREATE TABLE cr.campaign_enrolment (
  campaign_id     BIGINT NOT NULL REFERENCES cr.campaign(campaign_id),
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  progress_minor  BIGINT NOT NULL DEFAULT 0,
  reward_status   VARCHAR(16) NOT NULL DEFAULT 'in_progress' CHECK (reward_status IN ('in_progress','unlocked','granted','expired')),
  unlocked_at     TIMESTAMPTZ,
  PRIMARY KEY (campaign_id, account_id)
);

Reward Catalogue, Redemption & Fulfilment

CREATE TABLE cr.reward_catalogue (
  sku             VARCHAR(48) PRIMARY KEY,
  category        VARCHAR(24) NOT NULL CHECK (category IN
                    ('gift_card','voucher','coupon','ott','dining','travel','bundle','merchandise','charity')),
  partner_id      BIGINT REFERENCES cr.partner(partner_id),
  title           TEXT NOT NULL,
  point_price     BIGINT NOT NULL,
  cash_value_minor BIGINT,
  funding_type    VARCHAR(16) NOT NULL DEFAULT 'bank_funded' CHECK (funding_type IN ('bank_funded','merchant_funded')),
  stock           INT, eligibility JSONB, tnc TEXT,
  expiry_days     INT,
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','inactive','out_of_stock')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.redemption (
  redemption_id   BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  catalogue_sku   VARCHAR(48) REFERENCES cr.reward_catalogue(sku),
  method          VARCHAR(20) NOT NULL CHECK (method IN
                    ('voucher','statement_credit','cashback','pos','charity','emi_waiver','partner_transfer')),
  points_debited  BIGINT NOT NULL CHECK (points_debited >= 0),
  cash_paid_minor BIGINT NOT NULL DEFAULT 0,          -- points + cash
  fulfilment_mode VARCHAR(12) NOT NULL DEFAULT 'instant' CHECK (fulfilment_mode IN ('instant','deferred')),
  status          VARCHAR(16) NOT NULL DEFAULT 'requested' CHECK (status IN
                    ('requested','locked','fulfilled','failed','reversed')),
  fulfilment_ref  VARCHAR(64),
  reversed_of     BIGINT,
  -- cryptographically signed / verified redemption request (anti-tamper, non-repudiation)
  request_signature BYTEA,                            -- detached signature over canonical request
  signature_alg   VARCHAR(24) CHECK (signature_alg IN ('RS256','ES256','Ed25519','HMAC-SHA256')),
  signing_key_id  VARCHAR(64),                        -- KID of channel/customer signing key (Vault/KMS)
  nonce           VARCHAR(64),                         -- single-use anti-replay nonce
  signed_at       TIMESTAMPTZ,
  verification_status VARCHAR(16) NOT NULL DEFAULT 'unverified'
                    CHECK (verification_status IN ('unverified','verified','failed','expired')),
  verified_at     TIMESTAMPTZ,
  idempotency_key VARCHAR(80) UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_rdm_account ON cr.redemption(account_id, status);
CREATE UNIQUE INDEX ux_rdm_nonce ON cr.redemption(nonce) WHERE nonce IS NOT NULL;  -- enforce replay protection

CREATE TABLE cr.fulfilment_request (
  fulfilment_id   BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  redemption_id   BIGINT NOT NULL REFERENCES cr.redemption(redemption_id),
  partner_id      BIGINT REFERENCES cr.partner(partner_id),
  request_payload JSONB, response_payload JSONB,
  -- signed partner request / response (mutual non-repudiation with fulfilment partner)
  request_signature  BYTEA,
  response_signature BYTEA,
  signature_alg   VARCHAR(24) CHECK (signature_alg IN ('RS256','ES256','Ed25519','HMAC-SHA256')),
  signature_verified BOOLEAN NOT NULL DEFAULT false,  -- partner response signature verified
  status          VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','success','failed','timeout')),
  attempts        SMALLINT NOT NULL DEFAULT 0,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.voucher (
  voucher_id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  redemption_id   BIGINT NOT NULL REFERENCES cr.redemption(redemption_id),
  partner_id      BIGINT REFERENCES cr.partner(partner_id),
  code_encrypted  BYTEA NOT NULL,                     -- pgcrypto-encrypted
  value_minor     BIGINT,
  issued_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  expiry_date     DATE,
  status          VARCHAR(12) NOT NULL DEFAULT 'active' CHECK (status IN ('active','used','expired'))
);

CREATE TABLE cr.auto_redeem_rule (                    -- M4 auto-redeem
  rule_id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  trigger         VARCHAR(12) NOT NULL CHECK (trigger IN ('threshold','scheduled')),
  threshold_points BIGINT, schedule_cron VARCHAR(40),
  target_method   VARCHAR(20) NOT NULL, target_sku VARCHAR(48),
  status          VARCHAR(16) NOT NULL DEFAULT 'active'
);

Transfers, Referral & Gamification (M12)

CREATE TABLE cr.points_transfer (
  transfer_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  from_account    BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  to_account      BIGINT REFERENCES cr.loyalty_account(account_id),
  to_program_id   BIGINT REFERENCES cr.partner_program(program_id),
  kind            VARCHAR(12) NOT NULL CHECK (kind IN ('member_gift','pool','partner')),
  points          BIGINT NOT NULL CHECK (points > 0),
  ratio_applied   NUMERIC(8,4),
  status          VARCHAR(16) NOT NULL DEFAULT 'completed' CHECK (status IN ('pending','completed','failed','reversed')),
  idempotency_key VARCHAR(80) UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.referral (
  referral_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  referrer_account BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  referee_ref     VARCHAR(64),
  code            VARCHAR(24) UNIQUE NOT NULL,
  status          VARCHAR(16) NOT NULL DEFAULT 'issued' CHECK (status IN ('issued','qualified','rewarded','expired')),
  reward_points   BIGINT,
  qualified_at    TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.gamification_grant (
  grant_id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  mechanic        VARCHAR(20) NOT NULL CHECK (mechanic IN ('scratch_card','spin','streak','badge')),
  reward_def      JSONB, granted_points BIGINT,
  status          VARCHAR(16) NOT NULL DEFAULT 'granted',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Merchant-Funded & Settlement

CREATE TABLE cr.merchant (
  merchant_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  code            VARCHAR(40) UNIQUE NOT NULL, name TEXT NOT NULL,
  category        VARCHAR(40), kyc_ref VARCHAR(64),
  settlement_terms JSONB,
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','inactive','suspended')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE cr.merchant_offer (
  offer_id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  merchant_id     BIGINT NOT NULL REFERENCES cr.merchant(merchant_id),
  conditions      JSONB, funding_per_reward_minor BIGINT,
  budget_minor    BIGINT, period_start DATE, period_end DATE,
  status          VARCHAR(20) NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','pending_approval','active','ended'))
);
CREATE TABLE cr.merchant_txn_map (
  offer_id        BIGINT NOT NULL REFERENCES cr.merchant_offer(offer_id),
  txn_ref         VARCHAR(64) NOT NULL,
  funded_points   BIGINT NOT NULL, funded_minor BIGINT NOT NULL,
  mapped_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (offer_id, txn_ref)
);
CREATE TABLE cr.settlement (
  settlement_id   BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  merchant_id     BIGINT NOT NULL REFERENCES cr.merchant(merchant_id),
  period          VARCHAR(7) NOT NULL,               -- YYYY-MM
  eligible_txn_count INT, funded_points BIGINT, amount_due_minor BIGINT,
  status          VARCHAR(16) NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','generated','settled')),
  generated_at    TIMESTAMPTZ
);

Integrity & Risk (M11)

CREATE TABLE cr.clawback (
  clawback_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  original_entry  BIGINT,                              -- ledger_entry being reversed
  reason          VARCHAR(24) NOT NULL CHECK (reason IN ('fraud','chargeback','error','abuse')),
  points          BIGINT NOT NULL,
  status          VARCHAR(16) NOT NULL DEFAULT 'applied' CHECK (status IN ('applied','recovered','disputed')),
  approved_by     VARCHAR(48),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE cr.dispute (
  dispute_id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  ref_type        VARCHAR(16) CHECK (ref_type IN ('accrual','redemption','clawback')),
  ref_id          VARCHAR(64),
  description     TEXT,
  status          VARCHAR(16) NOT NULL DEFAULT 'open' CHECK (status IN ('open','investigating','resolved','rejected')),
  resolution      TEXT, resolved_by VARCHAR(48),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Communication

CREATE TABLE cr.notification_template (
  template_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event           VARCHAR(40) NOT NULL,
  channel         VARCHAR(12) NOT NULL CHECK (channel IN ('sms','email','push','whatsapp','in_app')),
  locale          VARCHAR(8) NOT NULL DEFAULT 'en-IN',
  subject         TEXT, body TEXT NOT NULL, variables JSONB,
  version         INT NOT NULL DEFAULT 1,
  status          VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('draft','active','retired')),
  UNIQUE (event, channel, locale, version)
);
CREATE TABLE cr.consent (
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  channel         VARCHAR(12) NOT NULL,
  opted_in        BOOLEAN NOT NULL DEFAULT true,
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, channel)
);
CREATE TABLE cr.notification_log (
  notif_id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT, template_id BIGINT, channel VARCHAR(12),
  event           VARCHAR(40), rendered_hash VARCHAR(64),
  status          VARCHAR(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','sent','delivered','failed')),
  sent_at         TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_notif_account ON cr.notification_log(account_id, created_at);

Governance, Audit & Platform

CREATE TABLE cr.role (
  role_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name VARCHAR(40) UNIQUE NOT NULL, description TEXT
);
CREATE TABLE cr.permission (
  permission_key VARCHAR(48) PRIMARY KEY,             -- e.g. campaign:write
  module VARCHAR(24), action VARCHAR(24)
);
CREATE TABLE cr.role_permission (
  role_id BIGINT REFERENCES cr.role(role_id),
  permission_key VARCHAR(48) REFERENCES cr.permission(permission_key),
  PRIMARY KEY (role_id, permission_key)
);
CREATE TABLE cr.app_user (
  user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  username VARCHAR(64) UNIQUE NOT NULL, idp_subject VARCHAR(128) UNIQUE,
  role_id BIGINT REFERENCES cr.role(role_id),
  status VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','disabled')),
  last_login TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.approval_request (                    -- maker-checker
  approval_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  entity_type     VARCHAR(24) NOT NULL,               -- accrual_rule, campaign, catalogue, budget, adjustment
  entity_id       VARCHAR(48),
  change_payload  JSONB NOT NULL,
  maker           VARCHAR(48) NOT NULL,
  checker         VARCHAR(48),
  status          VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','approved','rejected')),
  notes           TEXT, decided_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  CONSTRAINT chk_no_self_approve CHECK (checker IS NULL OR checker <> maker)
);

CREATE TABLE cr.budget (
  budget_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  scope VARCHAR(16) NOT NULL CHECK (scope IN ('programme','campaign')),
  scope_ref VARCHAR(48),
  allocated_points BIGINT NOT NULL, consumed_points BIGINT NOT NULL DEFAULT 0,
  threshold_pct SMALLINT NOT NULL DEFAULT 90,
  status VARCHAR(16) NOT NULL DEFAULT 'active'
);

CREATE TABLE cr.config_param (
  key VARCHAR(64) PRIMARY KEY, value TEXT NOT NULL,
  data_type VARCHAR(12) NOT NULL DEFAULT 'string', scope VARCHAR(24) DEFAULT 'global',
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_by VARCHAR(48)
);

CREATE TABLE cr.outbox_event (                        -- transactional outbox
  event_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  aggregate VARCHAR(24), event_type VARCHAR(40) NOT NULL,
  payload JSONB NOT NULL, published BOOLEAN NOT NULL DEFAULT false,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), published_at TIMESTAMPTZ
);
CREATE INDEX ix_outbox_unpub ON cr.outbox_event(created_at) WHERE published = false;

CREATE TABLE cr.reconciliation (
  run_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  run_date DATE NOT NULL, scope VARCHAR(24) NOT NULL,
  source_total BIGINT, ledger_total BIGINT, variance BIGINT,
  status VARCHAR(16) NOT NULL DEFAULT 'completed' CHECK (status IN ('running','completed','exceptions')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE cr.recon_exception (
  exception_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  run_id BIGINT REFERENCES cr.reconciliation(run_id),
  detail JSONB, status VARCHAR(16) NOT NULL DEFAULT 'open' CHECK (status IN ('open','resolved')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE cr.audit_log (                           -- immutable, partitioned
  audit_id BIGINT GENERATED ALWAYS AS IDENTITY,
  actor VARCHAR(64) NOT NULL, action VARCHAR(40) NOT NULL,
  entity_type VARCHAR(32), entity_id VARCHAR(48),
  before_state JSONB, after_state JSONB, ip INET,
  occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (audit_id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE cr.audit_log_2026_06 PARTITION OF cr.audit_log
  FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
CREATE INDEX ix_audit_entity ON cr.audit_log(entity_type, entity_id);

CREATE TABLE cr.api_client (
  client_id VARCHAR(48) PRIMARY KEY, name TEXT,
  scopes VARCHAR(48)[], rate_limit_per_min INT NOT NULL DEFAULT 600,
  status VARCHAR(16) NOT NULL DEFAULT 'active'
);

-- API access log (SIEM / audit readiness) — range-partitioned, append-only
CREATE TABLE cr.api_access_log (
  access_id   BIGINT GENERATED ALWAYS AS IDENTITY,
  client_id   VARCHAR(48),
  actor       VARCHAR(64),                            -- user/service principal
  method      VARCHAR(8) NOT NULL, path VARCHAR(200) NOT NULL,
  status_code SMALLINT NOT NULL,
  latency_ms  INT,
  ip          INET, user_agent TEXT,
  trace_id    VARCHAR(48), request_id VARCHAR(48),
  occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (access_id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE cr.api_access_log_2026_06 PARTITION OF cr.api_access_log
  FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
CREATE INDEX ix_apilog_client ON cr.api_access_log(client_id, occurred_at);
CREATE INDEX ix_apilog_trace  ON cr.api_access_log(trace_id);

-- outbound/inbound integration log (CBS, switch, channels, gateways, fulfilment partners)
CREATE TABLE cr.integration_log (
  log_id      BIGINT GENERATED ALWAYS AS IDENTITY,
  system      VARCHAR(40) NOT NULL,                   -- cbs, switch, notif_gateway, partner:<code>
  direction   VARCHAR(8) NOT NULL CHECK (direction IN ('inbound','outbound')),
  operation   VARCHAR(48), correlation_id VARCHAR(64),
  request_hash  VARCHAR(64), response_hash VARCHAR(64),
  http_status SMALLINT, status VARCHAR(16) NOT NULL DEFAULT 'ok'
                    CHECK (status IN ('ok','error','timeout','retry')),
  latency_ms  INT, attempt SMALLINT NOT NULL DEFAULT 1,
  error_detail TEXT,
  occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (log_id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE cr.integration_log_2026_06 PARTITION OF cr.integration_log
  FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
CREATE INDEX ix_intlog_system ON cr.integration_log(system, occurred_at);
CREATE INDEX ix_intlog_corr   ON cr.integration_log(correlation_id);

MIS & Reporting

-- report catalogue: liability, reconciliation, settlement, campaign-performance,
-- redemption, fulfilment, expiry/reversal, budget and audit reports
CREATE TABLE cr.report_definition (
  report_id    BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  code         VARCHAR(48) UNIQUE NOT NULL,           -- e.g. RPT_LIABILITY, RPT_SETTLEMENT
  name         TEXT NOT NULL,
  category     VARCHAR(24) NOT NULL CHECK (category IN
                    ('liability','reconciliation','settlement','campaign_performance',
                     'redemption','fulfilment','expiry_reversal','budget','audit','custom')),
  query_def    JSONB NOT NULL,                        -- parameterised source/columns/filters
  output_formats VARCHAR(12)[] NOT NULL DEFAULT ARRAY['csv','xlsx','pdf'],
  schedule_cron VARCHAR(40),                          -- null = on-demand
  retention_days INT NOT NULL DEFAULT 400,
  status       VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('draft','active','retired')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_by VARCHAR(48), updated_by VARCHAR(48)
);
CREATE TABLE cr.report_run (
  run_id       BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  report_id    BIGINT NOT NULL REFERENCES cr.report_definition(report_id),
  params       JSONB,
  period_start DATE, period_end DATE,
  format       VARCHAR(12) NOT NULL DEFAULT 'csv',
  row_count    BIGINT,
  artifact_uri TEXT,                                  -- object-store location of generated file
  artifact_hash VARCHAR(64),                          -- integrity hash of artefact
  status       VARCHAR(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','running','completed','failed')),
  requested_by VARCHAR(48),
  started_at   TIMESTAMPTZ, completed_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_reportrun_def ON cr.report_run(report_id, created_at);

Performance Indexes (migration 008)

The read-heavy reporting, reconciliation and engine hot paths are backed by a dedicated index migration. In production these are applied with CREATE INDEX CONCURRENTLY (outside a transaction) so they do not lock writes on the large fact tables.

-- ledger_entry: MIS aggregates by entry-type/date, reconciliation joins, reversals, funded roll-ups
CREATE INDEX ix_ledger_type_posted       ON cr.ledger_entry(entry_type, posted_at);
CREATE INDEX ix_ledger_source            ON cr.ledger_entry(source_type, source_ref);
CREATE INDEX ix_ledger_reversal          ON cr.ledger_entry(reversal_of) WHERE reversal_of IS NOT NULL;
CREATE INDEX ix_ledger_funding_merchant  ON cr.ledger_entry(funding_merchant_id) WHERE funding_merchant_id IS NOT NULL;

-- transaction: global date scans + tier-qualification spend sums
CREATE INDEX ix_txn_datetime             ON cr.transaction(txn_datetime);
CREATE INDEX ix_txn_purchase_posted      ON cr.transaction(account_id, txn_datetime)
                                            WHERE txn_type='purchase' AND txn_status='posted';

-- redemption: customer history, partner consumption reports, category/partner attribution
CREATE INDEX ix_redemption_account       ON cr.redemption(account_id);
CREATE INDEX ix_redemption_status_created ON cr.redemption(status, created_at);
CREATE INDEX ix_redemption_sku           ON cr.redemption(catalogue_sku);

-- campaign milestone ladder, voucher vault, audit trail, comms history
CREATE INDEX ix_milestone_campaign       ON cr.milestone(campaign_id, sequence);
CREATE INDEX ix_voucher_redemption       ON cr.voucher(redemption_id);
CREATE INDEX ix_audit_occurred           ON cr.audit_log(occurred_at DESC);
CREATE INDEX ix_notif_account            ON cr.notification_log(account_id) WHERE account_id IS NOT NULL;
Every standard MIS report can be filtered by user (account_id / customer_ref / card_ref), card segment (card_variant / tier), campaign and date range. Each predicate resolves through one of the indexes above — the user/segment dimensions through loyalty_account keys, the campaign dimension through ix_ledger_source / campaign_enrolment, and the date dimension through the (…, posted_at) / (…, created_at) composites.

Card Variant, BIN & MCC-Scoped Accrual (migrations 009–012)

The card / loyalty hierarchy: Card Variant is the master; many BINs (card products) map to a variant; an Accrual Rule is scoped to one or more variants and carries the MCC selection, rate, tier multiplier, caps and points-expiry; a transaction’s card resolves to its variant by BIN, then the matching variant + MCC rule earns the points. Campaigns target a segment (and variant via conditions).

erDiagram
  card_variant   ||--o{ card_product    : "has many BINs"
  card_variant   ||--o{ loyalty_account : "variant of"
  card_product   ||--o{ loyalty_account : "BIN of"
  card_variant   ||--o{ accrual_rule    : "rule scoped to (card_variant[])"
  segment        ||--o{ campaign        : "targets"
  campaign       ||--o{ milestone       : "ladder"
  loyalty_account ||--o{ ledger_entry  : "posts"
  loyalty_account ||--|| point_balance : "reconciled projection"
  card_variant {
    varchar code PK
    text    name
    smallint rank
  }
  card_product {
    bigint  card_product_id PK
    varchar bin UK
    text    card_name
    varchar variant FK
    varchar network
  }
  loyalty_account {
    bigint  account_id PK
    varchar card_variant FK
    varchar bin
    bigint  card_product_id FK
    varchar current_tier
  }
  accrual_rule {
    bigint  rule_id PK
    text_   card_variant "variant scope[]"
    text_   eligible_mccs "MCC selection"
    text_   excluded_mccs
    int     earn_points "rate"
    jsonb   tier_multipliers "multiplier"
    jsonb   caps "per_txn/daily/monthly"
    int     points_expiry_days
  }
  campaign {
    bigint  campaign_id PK
    varchar type "objective"
    bigint  segment_id FK
    jsonb   conditions "variant/mcc/window"
    jsonb   reward_def
  }
  

DDL — card variant & BIN master (migration 010)

-- Card Variant = the master (extensible — add bank-defined variants here)
CREATE TABLE cr.card_variant (
  code   VARCHAR(24) PRIMARY KEY,            -- CLASSIC / GOLD / PLATINUM / SIGNATURE / CORPORATE / …
  name   TEXT NOT NULL,
  rank   SMALLINT NOT NULL DEFAULT 0,
  status VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','retired'))
);

-- Card product / BIN master — many BINs per variant
CREATE TABLE cr.card_product (
  card_product_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  bin       VARCHAR(11) UNIQUE NOT NULL,                       -- BIN / IIN prefix, e.g. 489486
  card_name TEXT NOT NULL,                                     -- "the Bank Signature Visa"
  variant   VARCHAR(24) NOT NULL REFERENCES cr.card_variant(code),
  network   VARCHAR(16) NOT NULL DEFAULT 'VISA' CHECK (network IN ('VISA','MASTERCARD','RUPAY','AMEX','DINERS')),
  status    VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','retired')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_card_product_variant ON cr.card_product(variant);

-- account carries its BIN + product; card_variant is now an FK to the lookup
ALTER TABLE cr.loyalty_account ADD COLUMN bin VARCHAR(11);
ALTER TABLE cr.loyalty_account ADD COLUMN card_product_id BIGINT REFERENCES cr.card_product(card_product_id);
ALTER TABLE cr.loyalty_account ADD CONSTRAINT loyalty_account_card_variant_fk
  FOREIGN KEY (card_variant) REFERENCES cr.card_variant(code);

DDL — MCC-scoped accrual rule (migrations 011–012)

-- Accrual rule is scoped to the card variant and selects spend by MCC (not "all spend")
ALTER TABLE cr.accrual_rule ADD COLUMN eligible_mccs TEXT[];        -- empty/null = all MCCs (catch-all)
ALTER TABLE cr.accrual_rule ADD COLUMN excluded_mccs TEXT[];        -- never earn (ATM 6011 / FX 6051 / govt 9311)
ALTER TABLE cr.accrual_rule ADD COLUMN points_expiry_days INT NOT NULL DEFAULT 730;
CREATE INDEX ix_accrual_eligible_mccs ON cr.accrual_rule USING GIN (eligible_mccs);
-- existing columns already carry: card_variant TEXT[] (variant scope), earn_points / per_amount_minor (rate),
-- tier_multipliers (multiplier), caps JSONB {per_txn, daily, monthly} (caps).

-- Negative-balance clawback (migration 009)
ALTER TABLE cr.point_balance ADD COLUMN clawback_pending BIGINT NOT NULL DEFAULT 0 CHECK (clawback_pending >= 0);

How Card · Variant · BIN · Rule · Campaign map

RelationshipCardinalityEnforced by
Variant has many BINscard_variant 1 → * card_productcard_product.variant FK
Card belongs to a variantloyalty_account * → 1 card_variantloyalty_account.card_variant FK (+ bin/card_product_id)
Accrual rule applies across variant(s)accrual_rule * ↔ * variantaccrual_rule.card_variant TEXT[]
Campaign targets segment (+ variant via conditions)campaign * → 1 segmentcampaign.segment_id FK + conditions
Runtime accrual selection: txn → resolve loyalty_account (by card_ref/BIN) → {card_variant, current_tier, mcc} → pick accrual_rule WHERE variant ∈ card_variant[] AND mcc ∈ eligible_mccs (∅ = all) AND mcc ∉ excluded_mccs ORDER BY (MCC-specific first), priority → points = floor(amount / per_amount_minor) × earn_points × tier_multiplier[tier], capped by caps, expiring in points_expiry_days. BIN only resolves the card to its variant; it does not select the rule.

Engagement: Event Triggers, Scratch Cards & Milestones (migration 022)

The engagement layer (see HLD M13) adds five tables under db/migrations/022_axis_engagement.sql, seeded by db/seeds/008_axis_triggers.sql. All ledger writes reuse cr.ledger_entry + cr.point_balance with idempotency keys (scr:{scratchCardId}, evt:{eventRef}:{triggerId}).

DDL — bank event & trigger rule (migration 022)

-- External bank events (USER_REGISTERED / CARD_ACTIVATED / KYC_COMPLETED / UPI_TRANSACTION /
-- BILL_PAYMENT / SALARY_CREDIT / FD_BOOKED); event_ref is the idempotency key — replay-safe
CREATE TABLE cr.bank_event (
  event_id     BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_ref    VARCHAR(64) UNIQUE NOT NULL,           -- e.g. evt-upi-000123; duplicate replay returns original result
  event_type   VARCHAR(32) NOT NULL,                  -- canonical event set above
  account_id   BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  amount_minor BIGINT,                                -- paise, where applicable (UPI / bill / FD / salary)
  occurred_at  TIMESTAMPTZ NOT NULL,
  payload      JSONB,                                 -- vpa / merchant / biller / tenureMonths …
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_bank_event_account_type ON cr.bank_event(account_id, event_type, occurred_at);

-- Trigger rule — matches events and issues rewards (scratch card or direct points)
CREATE TABLE cr.trigger_rule (
  trigger_rule_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name        TEXT NOT NULL,                          -- "First UPI transaction"
  event_type  VARCHAR(32) NOT NULL,                   -- event listened to (or CARD_SPEND internal)
  conditions  JSONB NOT NULL DEFAULT '{}',            -- { first_occurrence, min_amount_minor, max_per_window {count, window} }
  reward_type VARCHAR(16) NOT NULL DEFAULT 'SCRATCH_CARD' CHECK (reward_type IN ('SCRATCH_CARD','POINTS')),
  prizes      JSONB,                                  -- weighted prize table [{kind, points|voucherLabel, weight, label}]
  expiry_days INT NOT NULL DEFAULT 30,                -- scratch-card validity from issue
  status      VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('draft','pending_approval','active','paused','retired')),
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ix_trigger_rule_event ON cr.trigger_rule(event_type) WHERE status = 'active';

DDL — scratch card (migration 022)

-- Prize is drawn at ISSUE time (weighted random) and stored hidden; scratching only reveals it (idempotent)
CREATE TABLE cr.scratch_card (
  scratch_card_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  trigger_rule_id BIGINT REFERENCES cr.trigger_rule(trigger_rule_id),   -- NULL for milestone-issued cards
  source_event_id BIGINT REFERENCES cr.bank_event(event_id),
  milestone_code  VARCHAR(48),                        -- set when issued by a milestone
  state           VARCHAR(16) NOT NULL DEFAULT 'ISSUED' CHECK (state IN ('ISSUED','SCRATCHED','EXPIRED')),
  prize           JSONB NOT NULL,                     -- hidden until scratched: {kind: POINTS|VOUCHER, points|voucherLabel, voucherValueMinor, label}
  ledger_entry_id BIGINT REFERENCES cr.ledger_entry(entry_id),          -- set on reveal for POINTS prizes (source_type scratch_card)
  issued_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  scratched_at    TIMESTAMPTZ,
  expires_at      TIMESTAMPTZ NOT NULL,               -- issued_at + 30 days by default; scratch after expiry → 409
  idempotency_key VARCHAR(96) UNIQUE NOT NULL         -- evt:{eventRef}:{triggerId} — one card per event per rule
);
CREATE INDEX ix_scratch_card_account_state ON cr.scratch_card(account_id, state);
CREATE INDEX ix_scratch_card_expiry ON cr.scratch_card(expires_at) WHERE state = 'ISSUED';

DDL — milestone definition & progress (migration 022)

-- Milestone definitions — count/amount targets over lifetime / weekly / monthly windows
CREATE TABLE cr.milestone_def (
  code        VARCHAR(48) PRIMARY KEY,                -- UPI_STREAK_3_WEEKLY / SPEND_25K_MONTHLY / BILL_PAY_3_MONTHLY
  name        TEXT NOT NULL,
  description TEXT,
  source      VARCHAR(32) NOT NULL,                   -- eventType (e.g. UPI_TRANSACTION) or CARD_SPEND (internal, after posted card txns)
  target_count        INT,                            -- e.g. 3 UPI txns / week
  target_amount_minor BIGINT,                         -- e.g. ₹25,000 card spend / month
  window      VARCHAR(16) NOT NULL DEFAULT 'lifetime' CHECK (window IN ('lifetime','weekly','monthly')),
  reward      JSONB NOT NULL,                         -- {"type":"SCRATCH_CARD","prizes":[...]} or {"type":"POINTS","points":N}
  status      VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active','paused','retired'))
);

-- Per-account progress within the current window; rolls over at window boundary
CREATE TABLE cr.milestone_progress (
  milestone_progress_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id      BIGINT NOT NULL REFERENCES cr.loyalty_account(account_id),
  milestone_code  VARCHAR(48) NOT NULL REFERENCES cr.milestone_def(code),
  window_start    DATE NOT NULL,                      -- start of the lifetime/weekly/monthly window
  progress_count        INT NOT NULL DEFAULT 0,
  progress_amount_minor BIGINT NOT NULL DEFAULT 0,
  status          VARCHAR(16) NOT NULL DEFAULT 'in_progress' CHECK (status IN ('in_progress','completed','rewarded')),
  completed_at    TIMESTAMPTZ,
  UNIQUE (account_id, milestone_code, window_start)   -- one reward per account per window
);
CREATE INDEX ix_milestone_progress_account ON cr.milestone_progress(account_id, status);

Migrations & Partition Maintenance

This DDL realises every entity in the Data Model (CR-DAT-005) and supports all SRS modules M1–M13 (including the engagement trigger/scratch-card/milestone layer). It is the authoritative build target for the data layer; service-owned subsets map per service decomposition.