template-saas-database-v2/ddl/schemas/whatsapp/tables/01-whatsapp-configs.sql
Adrian Flores Cortes c1c5892364 fix(ddl): Add storage triggers and fix whatsapp RLS pattern
- Add 06-triggers.sql with trg_files_updated_at and trg_usage_updated_at
  for storage.files and storage.usage tables
- Fix RLS policies in whatsapp schema to use current_setting with true
  parameter to avoid errors when app.current_tenant_id is not set

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 17:18:07 -06:00

61 lines
2.0 KiB
SQL

-- ============================================
-- WhatsApp Configuration per Tenant
-- ============================================
CREATE TABLE whatsapp.configs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants.tenants(id) ON DELETE CASCADE,
-- Meta Cloud API credentials
phone_number_id VARCHAR(50) NOT NULL,
business_account_id VARCHAR(50) NOT NULL,
access_token TEXT NOT NULL, -- Encrypted
-- Webhook configuration
webhook_verify_token VARCHAR(100),
webhook_secret VARCHAR(255),
-- Configuration
display_phone_number VARCHAR(20),
verified_name VARCHAR(255),
quality_rating VARCHAR(50),
-- Status
is_active BOOLEAN DEFAULT true,
is_verified BOOLEAN DEFAULT false,
last_verified_at TIMESTAMPTZ,
-- Rate limiting
daily_message_limit INTEGER DEFAULT 1000,
messages_sent_today INTEGER DEFAULT 0,
last_message_at TIMESTAMPTZ,
-- Metadata
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(tenant_id)
);
-- Indexes
CREATE INDEX idx_whatsapp_configs_tenant ON whatsapp.configs(tenant_id);
CREATE INDEX idx_whatsapp_configs_phone ON whatsapp.configs(phone_number_id);
CREATE INDEX idx_whatsapp_configs_active ON whatsapp.configs(is_active) WHERE is_active = true;
-- RLS
ALTER TABLE whatsapp.configs ENABLE ROW LEVEL SECURITY;
CREATE POLICY whatsapp_configs_tenant_isolation ON whatsapp.configs
USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid);
-- Trigger for updated_at
CREATE TRIGGER update_whatsapp_configs_updated_at
BEFORE UPDATE ON whatsapp.configs
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-- Comments
COMMENT ON TABLE whatsapp.configs IS 'WhatsApp Business API configuration per tenant';
COMMENT ON COLUMN whatsapp.configs.access_token IS 'Encrypted Meta Cloud API access token';
COMMENT ON COLUMN whatsapp.configs.quality_rating IS 'GREEN, YELLOW, or RED quality rating from Meta';