Phase 1: Forward Assist initial build
Multi-tenant AI help desk SaaS for the firearms industry. Full monorepo: API (Express/Prisma), Worker (BullMQ), Frontend (React/Vite/Tailwind). PostgreSQL 16 + pgvector, Redis 7, JWT auth, RLS tenant isolation. Dark Armory theme with tactical branding throughout. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,367 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "plans" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"maxUsers" INTEGER NOT NULL DEFAULT 3,
|
||||
"maxEmailAccounts" INTEGER NOT NULL DEFAULT 1,
|
||||
"maxTicketsPerMonth" INTEGER NOT NULL DEFAULT 500,
|
||||
"aiDraftsEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"knowledgeBaseEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"priceMonthly" DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
"priceYearly" DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "plans_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "tenants" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"plan_id" TEXT NOT NULL,
|
||||
"settings" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "tenants_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "users" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"password_hash" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT NOT NULL DEFAULT 'agent',
|
||||
"avatar_url" TEXT,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"last_login_at" TIMESTAMP(3),
|
||||
"refresh_token" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "email_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"email_address" TEXT NOT NULL,
|
||||
"imap_host" TEXT NOT NULL,
|
||||
"imap_port" INTEGER NOT NULL DEFAULT 993,
|
||||
"imap_user" TEXT NOT NULL,
|
||||
"imap_password" TEXT NOT NULL,
|
||||
"imap_tls" BOOLEAN NOT NULL DEFAULT true,
|
||||
"smtp_host" TEXT NOT NULL,
|
||||
"smtp_port" INTEGER NOT NULL DEFAULT 587,
|
||||
"smtp_user" TEXT NOT NULL,
|
||||
"smtp_password" TEXT NOT NULL,
|
||||
"smtp_tls" BOOLEAN NOT NULL DEFAULT true,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"last_poll_at" TIMESTAMP(3),
|
||||
"last_error" TEXT,
|
||||
"poll_interval_seconds" INTEGER NOT NULL DEFAULT 60,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "email_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "tickets" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"ticket_number" TEXT NOT NULL,
|
||||
"email_account_id" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'incoming',
|
||||
"priority" TEXT NOT NULL DEFAULT 'medium',
|
||||
"assignee_id" TEXT,
|
||||
"customer_email" TEXT NOT NULL,
|
||||
"customer_name" TEXT,
|
||||
"customer_profile_id" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"message_count" INTEGER NOT NULL DEFAULT 1,
|
||||
"last_message_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"resolved_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "tickets_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "messages" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ticket_id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"direction" TEXT NOT NULL,
|
||||
"from_email" TEXT NOT NULL,
|
||||
"from_name" TEXT,
|
||||
"to_email" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"body_text" TEXT NOT NULL,
|
||||
"body_html" TEXT,
|
||||
"message_id" TEXT,
|
||||
"in_reply_to" TEXT,
|
||||
"references" TEXT,
|
||||
"headers" JSONB,
|
||||
"sent_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "messages_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "attachments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"message_id" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
"content_type" TEXT NOT NULL,
|
||||
"size" INTEGER NOT NULL,
|
||||
"storage_key" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "attachments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ai_drafts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ticket_id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"message_id" TEXT NOT NULL,
|
||||
"draft_body" TEXT NOT NULL,
|
||||
"confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"model" TEXT NOT NULL DEFAULT 'gpt-4o',
|
||||
"tokens_used" INTEGER NOT NULL DEFAULT 0,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"edited_body" TEXT,
|
||||
"reviewed_by" TEXT,
|
||||
"reviewed_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ai_drafts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "knowledge_base" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL DEFAULT 'general',
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "knowledge_base_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "audit_log" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"user_id" TEXT,
|
||||
"action" TEXT NOT NULL,
|
||||
"entity" TEXT NOT NULL,
|
||||
"entity_id" TEXT,
|
||||
"details" JSONB,
|
||||
"ip_address" TEXT,
|
||||
"user_agent" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "audit_log_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "customer_profiles" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"name" TEXT,
|
||||
"phone" TEXT,
|
||||
"company" TEXT,
|
||||
"notes" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"ticket_count" INTEGER NOT NULL DEFAULT 0,
|
||||
"first_contact_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"last_contact_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "customer_profiles_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "canned_responses" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"body" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL DEFAULT 'general',
|
||||
"shortcut" TEXT,
|
||||
"created_by" TEXT NOT NULL,
|
||||
"is_shared" BOOLEAN NOT NULL DEFAULT true,
|
||||
"usage_count" INTEGER NOT NULL DEFAULT 0,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "canned_responses_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notification_preferences" (
|
||||
"id" TEXT NOT NULL,
|
||||
"user_id" TEXT NOT NULL,
|
||||
"tenant_id" TEXT NOT NULL,
|
||||
"new_ticket" BOOLEAN NOT NULL DEFAULT true,
|
||||
"ticket_assigned" BOOLEAN NOT NULL DEFAULT true,
|
||||
"ticket_reply" BOOLEAN NOT NULL DEFAULT true,
|
||||
"ai_draft_ready" BOOLEAN NOT NULL DEFAULT true,
|
||||
"daily_digest" BOOLEAN NOT NULL DEFAULT false,
|
||||
"email_notifications" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "notification_preferences_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "plans_slug_key" ON "plans"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "tenants_slug_key" ON "tenants"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "users_tenant_id_idx" ON "users"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_tenant_id_email_key" ON "users"("tenant_id", "email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "email_accounts_tenant_id_idx" ON "email_accounts"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "email_accounts_tenant_id_email_address_key" ON "email_accounts"("tenant_id", "email_address");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "tickets_tenant_id_status_idx" ON "tickets"("tenant_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "tickets_tenant_id_assignee_id_idx" ON "tickets"("tenant_id", "assignee_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "tickets_tenant_id_customer_email_idx" ON "tickets"("tenant_id", "customer_email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "tickets_tenant_id_created_at_idx" ON "tickets"("tenant_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "tickets_tenant_id_ticket_number_key" ON "tickets"("tenant_id", "ticket_number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "messages_ticket_id_idx" ON "messages"("ticket_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "messages_tenant_id_idx" ON "messages"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "messages_message_id_idx" ON "messages"("message_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ai_drafts_ticket_id_idx" ON "ai_drafts"("ticket_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ai_drafts_tenant_id_idx" ON "ai_drafts"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "knowledge_base_tenant_id_idx" ON "knowledge_base"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "audit_log_tenant_id_created_at_idx" ON "audit_log"("tenant_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "audit_log_tenant_id_entity_idx" ON "audit_log"("tenant_id", "entity");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "customer_profiles_tenant_id_idx" ON "customer_profiles"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "customer_profiles_tenant_id_email_key" ON "customer_profiles"("tenant_id", "email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "canned_responses_tenant_id_idx" ON "canned_responses"("tenant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notification_preferences_user_id_key" ON "notification_preferences"("user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notification_preferences_tenant_id_idx" ON "notification_preferences"("tenant_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tenants" ADD CONSTRAINT "tenants_plan_id_fkey" FOREIGN KEY ("plan_id") REFERENCES "plans"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "users" ADD CONSTRAINT "users_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "email_accounts" ADD CONSTRAINT "email_accounts_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tickets" ADD CONSTRAINT "tickets_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tickets" ADD CONSTRAINT "tickets_email_account_id_fkey" FOREIGN KEY ("email_account_id") REFERENCES "email_accounts"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tickets" ADD CONSTRAINT "tickets_assignee_id_fkey" FOREIGN KEY ("assignee_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tickets" ADD CONSTRAINT "tickets_customer_profile_id_fkey" FOREIGN KEY ("customer_profile_id") REFERENCES "customer_profiles"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "messages" ADD CONSTRAINT "messages_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "messages" ADD CONSTRAINT "messages_ticket_id_fkey" FOREIGN KEY ("ticket_id") REFERENCES "tickets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "attachments" ADD CONSTRAINT "attachments_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ai_drafts" ADD CONSTRAINT "ai_drafts_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ai_drafts" ADD CONSTRAINT "ai_drafts_ticket_id_fkey" FOREIGN KEY ("ticket_id") REFERENCES "tickets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ai_drafts" ADD CONSTRAINT "ai_drafts_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "knowledge_base" ADD CONSTRAINT "knowledge_base_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "audit_log" ADD CONSTRAINT "audit_log_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "audit_log" ADD CONSTRAINT "audit_log_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "customer_profiles" ADD CONSTRAINT "customer_profiles_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "canned_responses" ADD CONSTRAINT "canned_responses_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "canned_responses" ADD CONSTRAINT "canned_responses_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notification_preferences" ADD CONSTRAINT "notification_preferences_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notification_preferences" ADD CONSTRAINT "notification_preferences_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,48 @@
|
||||
-- ============================================================
|
||||
-- Forward Assist — Row Level Security Setup
|
||||
-- Run after Prisma migrations to enable tenant isolation
|
||||
-- ============================================================
|
||||
|
||||
-- Enable RLS on tenant-scoped tables
|
||||
-- Note: Prisma handles the actual filtering via middleware,
|
||||
-- but these policies provide defense-in-depth at the DB level.
|
||||
|
||||
-- We use a session variable app.current_tenant_id set per connection.
|
||||
|
||||
-- Function to get current tenant
|
||||
CREATE OR REPLACE FUNCTION current_tenant_id() RETURNS TEXT AS $$
|
||||
SELECT current_setting('app.current_tenant_id', true);
|
||||
$$ LANGUAGE sql STABLE;
|
||||
|
||||
-- Enable RLS on all tenant-scoped tables
|
||||
DO $$
|
||||
DECLARE
|
||||
t TEXT;
|
||||
BEGIN
|
||||
FOR t IN
|
||||
SELECT unnest(ARRAY[
|
||||
'users', 'email_accounts', 'tickets', 'messages',
|
||||
'ai_drafts', 'knowledge_base', 'audit_log',
|
||||
'customer_profiles', 'canned_responses', 'notification_preferences'
|
||||
])
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t);
|
||||
|
||||
-- Policy: tenant isolation
|
||||
EXECUTE format(
|
||||
'CREATE POLICY IF NOT EXISTS tenant_isolation ON %I
|
||||
FOR ALL
|
||||
USING (tenant_id = current_tenant_id())
|
||||
WITH CHECK (tenant_id = current_tenant_id())',
|
||||
t
|
||||
);
|
||||
|
||||
-- Allow the app user to bypass RLS (Prisma uses this role)
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I FORCE ROW LEVEL SECURITY', t
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- Grant the application user the ability to set tenant context
|
||||
-- The Prisma middleware will SET app.current_tenant_id before each query
|
||||
@@ -0,0 +1,343 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Plans
|
||||
// ============================================================
|
||||
model Plan {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
slug String @unique
|
||||
maxUsers Int @default(3)
|
||||
maxEmailAccounts Int @default(1)
|
||||
maxTicketsPerMonth Int @default(500)
|
||||
aiDraftsEnabled Boolean @default(false)
|
||||
knowledgeBaseEnabled Boolean @default(false)
|
||||
priceMonthly Decimal @default(0) @db.Decimal(10, 2)
|
||||
priceYearly Decimal @default(0) @db.Decimal(10, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
tenants Tenant[]
|
||||
|
||||
@@map("plans")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Tenants (Multi-tenant root)
|
||||
// ============================================================
|
||||
model Tenant {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
slug String @unique
|
||||
planId String @map("plan_id")
|
||||
settings Json @default("{}")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
plan Plan @relation(fields: [planId], references: [id])
|
||||
users User[]
|
||||
emailAccounts EmailAccount[]
|
||||
tickets Ticket[]
|
||||
messages Message[]
|
||||
aiDrafts AiDraft[]
|
||||
knowledgeBase KnowledgeBaseEntry[]
|
||||
auditLogs AuditLog[]
|
||||
customerProfiles CustomerProfile[]
|
||||
cannedResponses CannedResponse[]
|
||||
notificationPreferences NotificationPreference[]
|
||||
|
||||
@@map("tenants")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Users
|
||||
// ============================================================
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
email String
|
||||
passwordHash String @map("password_hash")
|
||||
name String
|
||||
role String @default("agent")
|
||||
avatarUrl String? @map("avatar_url")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
lastLoginAt DateTime? @map("last_login_at")
|
||||
refreshToken String? @map("refresh_token")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
assignedTickets Ticket[] @relation("TicketAssignee")
|
||||
auditLogs AuditLog[]
|
||||
notificationPreference NotificationPreference?
|
||||
createdCannedResponses CannedResponse[]
|
||||
|
||||
@@unique([tenantId, email])
|
||||
@@index([tenantId])
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Email Accounts
|
||||
// ============================================================
|
||||
model EmailAccount {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
name String
|
||||
emailAddress String @map("email_address")
|
||||
imapHost String @map("imap_host")
|
||||
imapPort Int @default(993) @map("imap_port")
|
||||
imapUser String @map("imap_user")
|
||||
imapPassword String @map("imap_password")
|
||||
imapTls Boolean @default(true) @map("imap_tls")
|
||||
smtpHost String @map("smtp_host")
|
||||
smtpPort Int @default(587) @map("smtp_port")
|
||||
smtpUser String @map("smtp_user")
|
||||
smtpPassword String @map("smtp_password")
|
||||
smtpTls Boolean @default(true) @map("smtp_tls")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
lastPollAt DateTime? @map("last_poll_at")
|
||||
lastError String? @map("last_error")
|
||||
pollIntervalSeconds Int @default(60) @map("poll_interval_seconds")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
tickets Ticket[]
|
||||
|
||||
@@unique([tenantId, emailAddress])
|
||||
@@index([tenantId])
|
||||
@@map("email_accounts")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Tickets
|
||||
// ============================================================
|
||||
model Ticket {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
ticketNumber String @map("ticket_number")
|
||||
emailAccountId String @map("email_account_id")
|
||||
subject String
|
||||
status String @default("incoming")
|
||||
priority String @default("medium")
|
||||
assigneeId String? @map("assignee_id")
|
||||
customerEmail String @map("customer_email")
|
||||
customerName String? @map("customer_name")
|
||||
customerProfileId String? @map("customer_profile_id")
|
||||
tags String[] @default([])
|
||||
messageCount Int @default(1) @map("message_count")
|
||||
lastMessageAt DateTime @default(now()) @map("last_message_at")
|
||||
resolvedAt DateTime? @map("resolved_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
emailAccount EmailAccount @relation(fields: [emailAccountId], references: [id])
|
||||
assignee User? @relation("TicketAssignee", fields: [assigneeId], references: [id])
|
||||
customerProfile CustomerProfile? @relation(fields: [customerProfileId], references: [id])
|
||||
messages Message[]
|
||||
aiDrafts AiDraft[]
|
||||
|
||||
@@unique([tenantId, ticketNumber])
|
||||
@@index([tenantId, status])
|
||||
@@index([tenantId, assigneeId])
|
||||
@@index([tenantId, customerEmail])
|
||||
@@index([tenantId, createdAt])
|
||||
@@map("tickets")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Messages
|
||||
// ============================================================
|
||||
model Message {
|
||||
id String @id @default(uuid())
|
||||
ticketId String @map("ticket_id")
|
||||
tenantId String @map("tenant_id")
|
||||
direction String // 'inbound' | 'outbound'
|
||||
fromEmail String @map("from_email")
|
||||
fromName String? @map("from_name")
|
||||
toEmail String @map("to_email")
|
||||
subject String
|
||||
bodyText String @map("body_text")
|
||||
bodyHtml String? @map("body_html")
|
||||
messageId String? @map("message_id")
|
||||
inReplyTo String? @map("in_reply_to")
|
||||
references String?
|
||||
headers Json?
|
||||
sentAt DateTime @default(now()) @map("sent_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
|
||||
attachments Attachment[]
|
||||
aiDrafts AiDraft[]
|
||||
|
||||
@@index([ticketId])
|
||||
@@index([tenantId])
|
||||
@@index([messageId])
|
||||
@@map("messages")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Attachments
|
||||
// ============================================================
|
||||
model Attachment {
|
||||
id String @id @default(uuid())
|
||||
messageId String @map("message_id")
|
||||
filename String
|
||||
contentType String @map("content_type")
|
||||
size Int
|
||||
storageKey String @map("storage_key")
|
||||
|
||||
message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("attachments")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// AI Drafts
|
||||
// ============================================================
|
||||
model AiDraft {
|
||||
id String @id @default(uuid())
|
||||
ticketId String @map("ticket_id")
|
||||
tenantId String @map("tenant_id")
|
||||
messageId String @map("message_id")
|
||||
draftBody String @map("draft_body")
|
||||
confidence Float @default(0)
|
||||
model String @default("gpt-4o")
|
||||
tokensUsed Int @default(0) @map("tokens_used")
|
||||
status String @default("pending")
|
||||
editedBody String? @map("edited_body")
|
||||
reviewedBy String? @map("reviewed_by")
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
|
||||
message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([ticketId])
|
||||
@@index([tenantId])
|
||||
@@map("ai_drafts")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Knowledge Base
|
||||
// ============================================================
|
||||
model KnowledgeBaseEntry {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
title String
|
||||
content String
|
||||
category String @default("general")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([tenantId])
|
||||
@@map("knowledge_base")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Audit Log
|
||||
// ============================================================
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
userId String? @map("user_id")
|
||||
action String
|
||||
entity String
|
||||
entityId String? @map("entity_id")
|
||||
details Json?
|
||||
ipAddress String? @map("ip_address")
|
||||
userAgent String? @map("user_agent")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
user User? @relation(fields: [userId], references: [id])
|
||||
|
||||
@@index([tenantId, createdAt])
|
||||
@@index([tenantId, entity])
|
||||
@@map("audit_log")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Customer Profiles
|
||||
// ============================================================
|
||||
model CustomerProfile {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
email String
|
||||
name String?
|
||||
phone String?
|
||||
company String?
|
||||
notes String?
|
||||
tags String[] @default([])
|
||||
ticketCount Int @default(0) @map("ticket_count")
|
||||
firstContactAt DateTime @default(now()) @map("first_contact_at")
|
||||
lastContactAt DateTime @default(now()) @map("last_contact_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
tickets Ticket[]
|
||||
|
||||
@@unique([tenantId, email])
|
||||
@@index([tenantId])
|
||||
@@map("customer_profiles")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Canned Responses
|
||||
// ============================================================
|
||||
model CannedResponse {
|
||||
id String @id @default(uuid())
|
||||
tenantId String @map("tenant_id")
|
||||
title String
|
||||
body String
|
||||
category String @default("general")
|
||||
shortcut String?
|
||||
createdBy String @map("created_by")
|
||||
isShared Boolean @default(true) @map("is_shared")
|
||||
usageCount Int @default(0) @map("usage_count")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
creator User @relation(fields: [createdBy], references: [id])
|
||||
|
||||
@@index([tenantId])
|
||||
@@map("canned_responses")
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Notification Preferences
|
||||
// ============================================================
|
||||
model NotificationPreference {
|
||||
id String @id @default(uuid())
|
||||
userId String @unique @map("user_id")
|
||||
tenantId String @map("tenant_id")
|
||||
newTicket Boolean @default(true) @map("new_ticket")
|
||||
ticketAssigned Boolean @default(true) @map("ticket_assigned")
|
||||
ticketReply Boolean @default(true) @map("ticket_reply")
|
||||
aiDraftReady Boolean @default(true) @map("ai_draft_ready")
|
||||
dailyDigest Boolean @default(false) @map("daily_digest")
|
||||
emailNotifications Boolean @default(true) @map("email_notifications")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([tenantId])
|
||||
@@map("notification_preferences")
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('Seeding Forward Assist database...');
|
||||
|
||||
// Create plans
|
||||
const trialPlan = await prisma.plan.upsert({
|
||||
where: { slug: 'trial' },
|
||||
update: {},
|
||||
create: {
|
||||
name: 'Trial',
|
||||
slug: 'trial',
|
||||
maxUsers: 2,
|
||||
maxEmailAccounts: 1,
|
||||
maxTicketsPerMonth: 100,
|
||||
aiDraftsEnabled: true,
|
||||
knowledgeBaseEnabled: false,
|
||||
priceMonthly: 0,
|
||||
priceYearly: 0,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.plan.upsert({
|
||||
where: { slug: 'starter' },
|
||||
update: {},
|
||||
create: {
|
||||
name: 'Starter',
|
||||
slug: 'starter',
|
||||
maxUsers: 5,
|
||||
maxEmailAccounts: 2,
|
||||
maxTicketsPerMonth: 1000,
|
||||
aiDraftsEnabled: true,
|
||||
knowledgeBaseEnabled: false,
|
||||
priceMonthly: 49,
|
||||
priceYearly: 470,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.plan.upsert({
|
||||
where: { slug: 'pro' },
|
||||
update: {},
|
||||
create: {
|
||||
name: 'Pro',
|
||||
slug: 'pro',
|
||||
maxUsers: 20,
|
||||
maxEmailAccounts: 10,
|
||||
maxTicketsPerMonth: 10000,
|
||||
aiDraftsEnabled: true,
|
||||
knowledgeBaseEnabled: true,
|
||||
priceMonthly: 149,
|
||||
priceYearly: 1430,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.plan.upsert({
|
||||
where: { slug: 'enterprise' },
|
||||
update: {},
|
||||
create: {
|
||||
name: 'Enterprise',
|
||||
slug: 'enterprise',
|
||||
maxUsers: 999,
|
||||
maxEmailAccounts: 50,
|
||||
maxTicketsPerMonth: 999999,
|
||||
aiDraftsEnabled: true,
|
||||
knowledgeBaseEnabled: true,
|
||||
priceMonthly: 499,
|
||||
priceYearly: 4790,
|
||||
},
|
||||
});
|
||||
|
||||
// Create test tenant
|
||||
const tenant = await prisma.tenant.upsert({
|
||||
where: { slug: 'demo-armory' },
|
||||
update: {},
|
||||
create: {
|
||||
name: 'Demo Armory',
|
||||
slug: 'demo-armory',
|
||||
planId: trialPlan.id,
|
||||
settings: {
|
||||
timezone: 'America/Chicago',
|
||||
businessHours: {
|
||||
monday: { enabled: true, start: '09:00', end: '17:00' },
|
||||
tuesday: { enabled: true, start: '09:00', end: '17:00' },
|
||||
wednesday: { enabled: true, start: '09:00', end: '17:00' },
|
||||
thursday: { enabled: true, start: '09:00', end: '17:00' },
|
||||
friday: { enabled: true, start: '09:00', end: '17:00' },
|
||||
saturday: { enabled: false, start: '10:00', end: '14:00' },
|
||||
sunday: { enabled: false, start: '10:00', end: '14:00' },
|
||||
},
|
||||
autoReplyEnabled: false,
|
||||
autoReplyMessage: 'Thank you for contacting us. We will respond within 24 hours.',
|
||||
aiDraftEnabled: false,
|
||||
aiTone: 'professional',
|
||||
ticketPrefix: 'FA',
|
||||
maxTicketsPerDay: 100,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create admin user (password: "admin123")
|
||||
const passwordHash = await bcrypt.hash('admin123', 12);
|
||||
const adminUser = await prisma.user.upsert({
|
||||
where: { tenantId_email: { tenantId: tenant.id, email: 'admin@demo-armory.com' } },
|
||||
update: {},
|
||||
create: {
|
||||
tenantId: tenant.id,
|
||||
email: 'admin@demo-armory.com',
|
||||
passwordHash,
|
||||
name: 'Range Master',
|
||||
role: 'owner',
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Create notification preferences for admin
|
||||
await prisma.notificationPreference.upsert({
|
||||
where: { userId: adminUser.id },
|
||||
update: {},
|
||||
create: {
|
||||
userId: adminUser.id,
|
||||
tenantId: tenant.id,
|
||||
newTicket: true,
|
||||
ticketAssigned: true,
|
||||
ticketReply: true,
|
||||
aiDraftReady: true,
|
||||
dailyDigest: false,
|
||||
emailNotifications: true,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('Seed complete!');
|
||||
console.log(` Plans: trial, starter, pro, enterprise`);
|
||||
console.log(` Tenant: ${tenant.name} (${tenant.slug})`);
|
||||
console.log(` Admin: ${adminUser.email} / admin123`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
Reference in New Issue
Block a user