diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b74098ae..95890d52 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,17 +5,18 @@ on: branches: [main] pull_request: +env: + NEXT_PUBLIC_APP_URL: http://localhost:3000 + AUTH_SECRET: ci-placeholder-auth-secret-value + GOOGLE_CLIENT_ID: ci-google-client-id + GOOGLE_CLIENT_SECRET: ci-google-client-secret + DATABASE_URL: postgresql://postgres:postgres@localhost:5432/guddesk + RESEND_API_KEY: re_ci_placeholder + jobs: - ci: - name: CI + test: + name: Test runs-on: ubuntu-latest - env: - DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/guddesk?sslmode=disable - AUTH_SECRET: ci-auth-secret-not-used - GOOGLE_CLIENT_ID: ci-google-client-id - GOOGLE_CLIENT_SECRET: ci-google-client-secret - RESEND_API_KEY: re_ci_placeholder - NEXT_PUBLIC_APP_URL: http://localhost:3000 steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 @@ -25,16 +26,12 @@ jobs: with: node-version-file: ".nvmrc" cache: pnpm - - name: Validate GudBot AI eval set - run: node qa/ai-eval/score.mjs validate - name: Install run: pnpm install --frozen-lockfile + - name: Validate GudBot AI eval set + run: node qa/ai-eval/score.mjs validate - name: Prisma generate - run: pnpm prisma generate - - name: Typecheck - run: pnpm run build:content && pnpm exec tsc --noEmit - - name: Lint - run: pnpm lint + run: pnpm exec prisma generate - name: Test run: | set -o pipefail @@ -45,5 +42,47 @@ jobs: exit 1 fi echo "Ran $count tests" + - name: Build content + run: pnpm build:content + - name: Typecheck + run: pnpm exec tsc --noEmit + - name: Lint + run: pnpm lint - name: Build run: pnpm build + + migrations: + name: Migrations (empty Postgres) + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + # A throwaway service container; nothing here reaches a real database. + DATABASE_ADMIN_URL: postgresql://postgres:postgres@localhost:5432/postgres + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + version: 10 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + cache: pnpm + - name: Install + run: pnpm install --frozen-lockfile + - name: Prisma generate + run: pnpm exec prisma generate + - name: prisma migrate deploy on an empty database (no drift, smoke), then upgrade one with data + run: bash scripts/ci-migrate-check.sh diff --git a/prisma/migrations/0006_workspace_app_id/migration.sql b/prisma/migrations/0006_workspace_app_id/migration.sql new file mode 100644 index 00000000..a17cc040 --- /dev/null +++ b/prisma/migrations/0006_workspace_app_id/migration.sql @@ -0,0 +1,22 @@ +-- Workspace.appId + drop orphan 0001_init workspaces.apiKey. +-- 0002/0003 are reserved for owner-blocked SQL (flowchat #32/#46/#37). +-- Safe on an empty database and on an upgrade that still has apiKey rows. +-- Prisma sets appId defaults (cuid()) in the client, not in the database. + +-- AlterTable +ALTER TABLE "workspaces" ADD COLUMN "appId" TEXT; + +-- Backfill unique values for existing rows +UPDATE "workspaces" +SET "appId" = 'app_' || "id" +WHERE "appId" IS NULL; + +-- AlterTable +ALTER TABLE "workspaces" ALTER COLUMN "appId" SET NOT NULL; + +-- CreateIndex +CREATE UNIQUE INDEX "workspaces_appId_key" ON "workspaces"("appId"); + +-- Drop orphan 0001_init column +DROP INDEX IF EXISTS "workspaces_apiKey_key"; +ALTER TABLE "workspaces" DROP COLUMN "apiKey"; diff --git a/prisma/migrations/0007_schema_catch_up/migration.sql b/prisma/migrations/0007_schema_catch_up/migration.sql new file mode 100644 index 00000000..cb1ea9db --- /dev/null +++ b/prisma/migrations/0007_schema_catch_up/migration.sql @@ -0,0 +1,636 @@ +-- Catch-up, add-only: brings a database built with `prisma migrate deploy` +-- up to prisma/schema.prisma. Generated with +-- prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script +-- against a throwaway Postgres that had 0001..0004 applied, then guarded so +-- every statement is a no-op when the object already exists: +-- enums and foreign keys: DO $$ ... EXCEPTION WHEN duplicate_object +-- tables, columns, indexes: IF NOT EXISTS +-- Nothing is renamed or retyped. workspaces.apiKey is dropped in +-- 0006_workspace_app_id; this catch-up does not re-drop it. +-- +-- Only for fresh installs, or databases whose _prisma_migrations is empty +-- and that were built from migrations. A database made with `prisma db push` +-- should stay on `db push` (see the self-hosting docs). + +-- CreateEnum ConversationChannel +DO $$ BEGIN + CREATE TYPE "ConversationChannel" AS ENUM ('WIDGET', 'EMAIL', 'API'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum SurveyType +DO $$ BEGIN + CREATE TYPE "SurveyType" AS ENUM ('CSAT', 'NPS'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum SurveyTriggerType +DO $$ BEGIN + CREATE TYPE "SurveyTriggerType" AS ENUM ('ON_CLOSE', 'AFTER_DELAY'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum AgentAvailability +DO $$ BEGIN + CREATE TYPE "AgentAvailability" AS ENUM ('ONLINE', 'AWAY', 'OFFLINE'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum ApiKeyPermission +DO $$ BEGIN + CREATE TYPE "ApiKeyPermission" AS ENUM ('READ_ONLY', 'READ_WRITE', 'FULL_ACCESS'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum AgentType +DO $$ BEGIN + CREATE TYPE "AgentType" AS ENUM ('BUILT_IN', 'MARKETPLACE', 'CUSTOM'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum WebhookDeliveryStatus +DO $$ BEGIN + CREATE TYPE "WebhookDeliveryStatus" AS ENUM ('PENDING', 'SUCCESS', 'FAILED'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- CreateEnum CustomFieldType +DO $$ BEGIN + CREATE TYPE "CustomFieldType" AS ENUM ('TEXT', 'NUMBER', 'BOOLEAN', 'DATE', 'ENUM'); +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- workspaces.apiKey / workspaces_apiKey_key: owned by 0006_workspace_app_id. +-- Do not re-drop them here. + +-- AlterTable +ALTER TABLE "conversations" ADD COLUMN IF NOT EXISTS "channel" "ConversationChannel" NOT NULL DEFAULT 'WIDGET', +ADD COLUMN IF NOT EXISTS "customFieldValues" JSONB, +ADD COLUMN IF NOT EXISTS "firstResponseAt" TIMESTAMP(3), +ADD COLUMN IF NOT EXISTS "firstResponseDueAt" TIMESTAMP(3), +ADD COLUMN IF NOT EXISTS "resolutionDueAt" TIMESTAMP(3), +ADD COLUMN IF NOT EXISTS "slaBreachedAt" TIMESTAMP(3), +ADD COLUMN IF NOT EXISTS "slaPolicyId" TEXT, +ADD COLUMN IF NOT EXISTS "ticketFormId" TEXT; + +-- AlterTable +ALTER TABLE "messages" ADD COLUMN IF NOT EXISTS "emailMessageId" TEXT, +ADD COLUMN IF NOT EXISTS "mentions" TEXT[]; + +-- AlterTable +ALTER TABLE "visitors" ADD COLUMN IF NOT EXISTS "companyId" TEXT; + +-- AlterTable +ALTER TABLE "widget_settings" ADD COLUMN IF NOT EXISTS "identitySecret" TEXT, +ADD COLUMN IF NOT EXISTS "offline_form_timeout" INTEGER, +ADD COLUMN IF NOT EXISTS "pageVisibilityMode" TEXT NOT NULL DEFAULT 'exclude', +ADD COLUMN IF NOT EXISTS "pageVisibilityPatterns" JSONB NOT NULL DEFAULT '[]'; + +-- AlterTable +ALTER TABLE "workspace_members" ADD COLUMN IF NOT EXISTS "availability" "AgentAvailability" NOT NULL DEFAULT 'OFFLINE', +ADD COLUMN IF NOT EXISTS "currentViewingId" TEXT, +ADD COLUMN IF NOT EXISTS "lastActiveAt" TIMESTAMP(3); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "agents" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT, + "type" "AgentType" NOT NULL DEFAULT 'CUSTOM', + "iconUrl" TEXT, + "creatorName" TEXT, + "creatorUrl" TEXT, + "webhookEndpointId" TEXT, + "apiKeyId" TEXT, + "config" JSONB, + "isEnabled" BOOLEAN NOT NULL DEFAULT true, + "priority" INTEGER NOT NULL DEFAULT 0, + "installedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "agents_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "webhook_endpoints" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "url" TEXT NOT NULL, + "secret" TEXT NOT NULL, + "description" TEXT, + "isEnabled" BOOLEAN NOT NULL DEFAULT true, + "onMessageCreated" BOOLEAN NOT NULL DEFAULT true, + "onConversationCreated" BOOLEAN NOT NULL DEFAULT true, + "onConversationClosed" BOOLEAN NOT NULL DEFAULT false, + "onConversationAssigned" BOOLEAN NOT NULL DEFAULT false, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "webhook_endpoints_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "webhook_deliveries" ( + "id" TEXT NOT NULL, + "endpointId" TEXT NOT NULL, + "event" TEXT NOT NULL, + "payload" TEXT NOT NULL, + "status" "WebhookDeliveryStatus" NOT NULL DEFAULT 'PENDING', + "attemptCount" INTEGER NOT NULL DEFAULT 0, + "maxAttempts" INTEGER NOT NULL DEFAULT 6, + "nextRetryAt" TIMESTAMP(3), + "httpStatus" INTEGER, + "responseBody" TEXT, + "errorMessage" TEXT, + "durationMs" INTEGER, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + "completedAt" TIMESTAMP(3), + + CONSTRAINT "webhook_deliveries_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "api_keys" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "workspaceId" TEXT, + "name" TEXT NOT NULL, + "keyHash" TEXT NOT NULL, + "keyPrefix" TEXT NOT NULL, + "permission" "ApiKeyPermission" NOT NULL DEFAULT 'READ_WRITE', + "isEnabled" BOOLEAN NOT NULL DEFAULT true, + "lastUsedAt" TIMESTAMP(3), + "expiresAt" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "api_keys_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "companies" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "domain" TEXT, + "website" TEXT, + "logoUrl" TEXT, + "industry" TEXT, + "metadata" JSONB, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "companies_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "custom_fields" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "key" TEXT NOT NULL, + "fieldType" "CustomFieldType" NOT NULL, + "entityType" TEXT NOT NULL, + "isRequired" BOOLEAN NOT NULL DEFAULT false, + "enumOptions" TEXT[], + "displayOrder" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "custom_fields_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "customer_events" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "visitorId" TEXT NOT NULL, + "type" TEXT NOT NULL, + "title" TEXT NOT NULL, + "metadata" JSONB, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "customer_events_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "customer_segments" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT, + "conditions" JSONB NOT NULL, + "color" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "customer_segments_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "sla_policies" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "firstResponseMinutes" INTEGER NOT NULL, + "resolutionMinutes" INTEGER NOT NULL, + "priority" INTEGER, + "isDefault" BOOLEAN NOT NULL DEFAULT false, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "sla_policies_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "business_hours" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "timezone" TEXT NOT NULL DEFAULT 'UTC', + "schedule" JSONB NOT NULL, + "holidays" JSONB NOT NULL DEFAULT '[]', + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "business_hours_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "ticket_forms" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT, + "fieldKeys" TEXT[], + "isDefault" BOOLEAN NOT NULL DEFAULT false, + "isEnabled" BOOLEAN NOT NULL DEFAULT true, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "ticket_forms_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "survey_configs" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "type" "SurveyType" NOT NULL, + "isEnabled" BOOLEAN NOT NULL DEFAULT false, + "trigger" "SurveyTriggerType" NOT NULL DEFAULT 'ON_CLOSE', + "delayMinutes" INTEGER NOT NULL DEFAULT 0, + "questionText" TEXT NOT NULL DEFAULT 'How would you rate your experience?', + "thankYouText" TEXT NOT NULL DEFAULT 'Thank you for your feedback!', + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "survey_configs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "survey_responses" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "conversationId" TEXT, + "visitorId" TEXT NOT NULL, + "type" "SurveyType" NOT NULL, + "rating" INTEGER NOT NULL, + "comment" TEXT, + "assigneeId" TEXT, + "respondedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "survey_responses_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "email_channel_configs" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "isEnabled" BOOLEAN NOT NULL DEFAULT false, + "supportAddress" TEXT, + "forwardAddress" TEXT, + "fromName" TEXT, + "fromAddress" TEXT, + "signature" TEXT, + "autoReopen" BOOLEAN NOT NULL DEFAULT true, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "email_channel_configs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "shared_drafts" ( + "id" TEXT NOT NULL, + "conversationId" TEXT NOT NULL, + "body" TEXT NOT NULL DEFAULT '', + "lastEditedBy" TEXT, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "shared_drafts_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "side_conversations" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "conversationId" TEXT NOT NULL, + "subject" TEXT NOT NULL, + "createdById" TEXT NOT NULL, + "status" TEXT NOT NULL DEFAULT 'OPEN', + "participantIds" TEXT[], + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "side_conversations_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "side_conversation_messages" ( + "id" TEXT NOT NULL, + "sideConversationId" TEXT NOT NULL, + "senderId" TEXT NOT NULL, + "senderName" TEXT, + "body" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "side_conversation_messages_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE IF NOT EXISTS "agent_performance_snapshots" ( + "id" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "memberId" TEXT NOT NULL, + "date" DATE NOT NULL, + "conversationsHandled" INTEGER NOT NULL DEFAULT 0, + "messagesCount" INTEGER NOT NULL DEFAULT 0, + "avgFirstResponseMs" INTEGER, + "avgResolutionMs" INTEGER, + "csatAverage" DOUBLE PRECISION, + "csatCount" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "agent_performance_snapshots_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "agents_webhookEndpointId_key" ON "agents"("webhookEndpointId"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "agents_apiKeyId_key" ON "agents"("apiKeyId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "agents_workspaceId_isEnabled_idx" ON "agents"("workspaceId", "isEnabled"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "webhook_endpoints_workspaceId_idx" ON "webhook_endpoints"("workspaceId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "webhook_deliveries_endpointId_created_at_idx" ON "webhook_deliveries"("endpointId", "created_at"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "webhook_deliveries_status_nextRetryAt_idx" ON "webhook_deliveries"("status", "nextRetryAt"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "webhook_deliveries_endpointId_status_idx" ON "webhook_deliveries"("endpointId", "status"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "api_keys_keyHash_key" ON "api_keys"("keyHash"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "api_keys_userId_idx" ON "api_keys"("userId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "api_keys_workspaceId_idx" ON "api_keys"("workspaceId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "companies_workspaceId_idx" ON "companies"("workspaceId"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "companies_workspaceId_domain_key" ON "companies"("workspaceId", "domain"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "custom_fields_workspaceId_entityType_idx" ON "custom_fields"("workspaceId", "entityType"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "custom_fields_workspaceId_key_entityType_key" ON "custom_fields"("workspaceId", "key", "entityType"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "customer_events_visitorId_created_at_idx" ON "customer_events"("visitorId", "created_at"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "customer_events_workspaceId_created_at_idx" ON "customer_events"("workspaceId", "created_at"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "customer_segments_workspaceId_idx" ON "customer_segments"("workspaceId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "sla_policies_workspaceId_idx" ON "sla_policies"("workspaceId"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "sla_policies_workspaceId_priority_key" ON "sla_policies"("workspaceId", "priority"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "business_hours_workspaceId_key" ON "business_hours"("workspaceId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "ticket_forms_workspaceId_idx" ON "ticket_forms"("workspaceId"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "survey_configs_workspaceId_type_key" ON "survey_configs"("workspaceId", "type"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "survey_responses_workspaceId_type_respondedAt_idx" ON "survey_responses"("workspaceId", "type", "respondedAt"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "survey_responses_workspaceId_assigneeId_respondedAt_idx" ON "survey_responses"("workspaceId", "assigneeId", "respondedAt"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "survey_responses_conversationId_idx" ON "survey_responses"("conversationId"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "email_channel_configs_workspaceId_key" ON "email_channel_configs"("workspaceId"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "shared_drafts_conversationId_key" ON "shared_drafts"("conversationId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "side_conversations_conversationId_idx" ON "side_conversations"("conversationId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "side_conversations_workspaceId_idx" ON "side_conversations"("workspaceId"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "side_conversation_messages_sideConversationId_created_at_idx" ON "side_conversation_messages"("sideConversationId", "created_at"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "agent_performance_snapshots_workspaceId_date_idx" ON "agent_performance_snapshots"("workspaceId", "date"); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "agent_performance_snapshots_memberId_date_key" ON "agent_performance_snapshots"("memberId", "date"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "conversations_workspaceId_channel_idx" ON "conversations"("workspaceId", "channel"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "visitors_companyId_idx" ON "visitors"("companyId"); + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "visitors" ADD CONSTRAINT "visitors_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "companies"("id") ON DELETE SET NULL ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "conversations" ADD CONSTRAINT "conversations_slaPolicyId_fkey" FOREIGN KEY ("slaPolicyId") REFERENCES "sla_policies"("id") ON DELETE SET NULL ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "conversations" ADD CONSTRAINT "conversations_ticketFormId_fkey" FOREIGN KEY ("ticketFormId") REFERENCES "ticket_forms"("id") ON DELETE SET NULL ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "agents" ADD CONSTRAINT "agents_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "agents" ADD CONSTRAINT "agents_webhookEndpointId_fkey" FOREIGN KEY ("webhookEndpointId") REFERENCES "webhook_endpoints"("id") ON DELETE SET NULL ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "agents" ADD CONSTRAINT "agents_apiKeyId_fkey" FOREIGN KEY ("apiKeyId") REFERENCES "api_keys"("id") ON DELETE SET NULL ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "webhook_endpoints" ADD CONSTRAINT "webhook_endpoints_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "webhook_deliveries" ADD CONSTRAINT "webhook_deliveries_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "webhook_endpoints"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "companies" ADD CONSTRAINT "companies_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "custom_fields" ADD CONSTRAINT "custom_fields_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "customer_events" ADD CONSTRAINT "customer_events_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "customer_events" ADD CONSTRAINT "customer_events_visitorId_fkey" FOREIGN KEY ("visitorId") REFERENCES "visitors"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "customer_segments" ADD CONSTRAINT "customer_segments_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "sla_policies" ADD CONSTRAINT "sla_policies_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "business_hours" ADD CONSTRAINT "business_hours_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "ticket_forms" ADD CONSTRAINT "ticket_forms_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "survey_configs" ADD CONSTRAINT "survey_configs_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "survey_responses" ADD CONSTRAINT "survey_responses_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "email_channel_configs" ADD CONSTRAINT "email_channel_configs_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "shared_drafts" ADD CONSTRAINT "shared_drafts_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "conversations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "side_conversations" ADD CONSTRAINT "side_conversations_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "side_conversations" ADD CONSTRAINT "side_conversations_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "conversations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "side_conversation_messages" ADD CONSTRAINT "side_conversation_messages_sideConversationId_fkey" FOREIGN KEY ("sideConversationId") REFERENCES "side_conversations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; + +-- AddForeignKey +DO $$ BEGIN + ALTER TABLE "agent_performance_snapshots" ADD CONSTRAINT "agent_performance_snapshots_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN null; +END $$; diff --git a/scripts/ci-migrate-check.sh b/scripts/ci-migrate-check.sh new file mode 100755 index 00000000..0fc7ea10 --- /dev/null +++ b/scripts/ci-migrate-check.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# CI: the migrations must build, on an empty Postgres, exactly the database +# schema.prisma describes, and must upgrade an older database that has data. +# +# Needs DATABASE_ADMIN_URL (a superuser URL ending in /postgres) and psql. +# Creates throwaway databases on that server. Never point it at a real +# database. +set -euo pipefail + +admin="${DATABASE_ADMIN_URL:?set DATABASE_ADMIN_URL}" +base="${admin%/*}" +migrations=prisma/migrations + +psql_admin() { psql "$admin" -v ON_ERROR_STOP=1 -qAtc "$1"; } +for db in migrate_fresh migrate_upgrade; do + psql_admin "DROP DATABASE IF EXISTS $db" + psql_admin "CREATE DATABASE $db" +done + +# NOT NULL, unique: " " +check_not_null_unique() { + local url="$1" table="$2" column="$3" index="$4" nullable + nullable=$(psql "$url" -qAtc "SELECT is_nullable FROM information_schema.columns WHERE table_name = '$table' AND column_name = '$column'") + [ "$nullable" = "NO" ] || { echo "FAIL: $table.$column missing or nullable (got '${nullable}')"; exit 1; } + psql "$url" -qAtc "SELECT 1 FROM pg_indexes WHERE indexname = '$index'" | grep -q 1 \ + || { echo "FAIL: unique index $index missing"; exit 1; } +} +check_workspaces() { + check_not_null_unique "$1" workspaces appId workspaces_appId_key + # 0006 drops the orphan 0001_init column workspaces.apiKey and its index. + local leftover + leftover=$(psql "$1" -qAtc "SELECT count(*) FROM information_schema.columns WHERE table_name = 'workspaces' AND column_name = 'apiKey'") + [ "$leftover" = "0" ] || { echo "FAIL: workspaces.apiKey still exists"; exit 1; } + leftover=$(psql "$1" -qAtc "SELECT count(*) FROM pg_indexes WHERE indexname = 'workspaces_apiKey_key'") + [ "$leftover" = "0" ] || { echo "FAIL: index workspaces_apiKey_key still exists"; exit 1; } +} + +echo "== 1. migrate deploy on an empty database" +fresh="$base/migrate_fresh" +DATABASE_URL="$fresh" pnpm exec prisma migrate deploy +check_workspaces "$fresh" +echo "== 1b. a second deploy is a no-op" +DATABASE_URL="$fresh" pnpm exec prisma migrate deploy | tee /tmp/second-deploy.txt +grep -q "No pending migrations" /tmp/second-deploy.txt + +echo "== 2. no drift: migrations match schema.prisma" +# The diff must be empty: not a single statement. +DATABASE_URL="$fresh" pnpm exec prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script > /tmp/drift.sql +if grep -vE '^\s*$|^--' /tmp/drift.sql; then + echo "FAIL: the migrations don't match schema.prisma (statements above). Add a migration." + exit 1 +fi + +echo "== 3. smoke: every model reads, and a workspace can be created" +DATABASE_URL="$fresh" pnpm exec tsx scripts/ci-migrate-smoke.ts + +echo "== 4. upgrade a pre-appId database that has data" +upgrade="$base/migrate_upgrade" +for name in $(ls -1 "$migrations" | grep -E '^[0-9]' | sort); do + case "$name" in 0004_*) break ;; esac + psql "$upgrade" -v ON_ERROR_STOP=1 -q -f "$migrations/$name/migration.sql" + DATABASE_URL="$upgrade" pnpm exec prisma migrate resolve --applied "$name" >/dev/null +done +# Rows as an older install has them (0001_init: apiKey NOT NULL, no appId). +psql "$upgrade" -v ON_ERROR_STOP=1 -qc \ + "INSERT INTO \"workspaces\" (\"id\", \"name\", \"slug\", \"apiKey\", \"updated_at\") + SELECT 'ws_ci_' || g, 'CI ' || g, 'ci-' || g, 'key_ci_' || g, now() FROM generate_series(1, 3) AS g" +DATABASE_URL="$upgrade" pnpm exec prisma migrate deploy +check_workspaces "$upgrade" +distinct=$(psql "$upgrade" -qAtc 'SELECT count(DISTINCT "appId") FROM "workspaces" WHERE "appId" IS NOT NULL') +[ "$distinct" = "3" ] || { echo "FAIL: expected 3 distinct backfilled appIds, got $distinct"; exit 1; } +rows=$(psql "$upgrade" -qAtc 'SELECT count(*) FROM "workspaces"') +[ "$rows" = "3" ] || { echo "FAIL: expected the 3 existing workspaces to survive, got $rows"; exit 1; } +DATABASE_URL="$upgrade" pnpm exec tsx scripts/ci-migrate-smoke.ts + +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + echo "Migrations build schema.prisma on an empty Postgres (empty migrate diff) and upgrade an older database." >> "$GITHUB_STEP_SUMMARY" +fi +echo "OK" diff --git a/scripts/ci-migrate-smoke.ts b/scripts/ci-migrate-smoke.ts new file mode 100644 index 00000000..7154ec1c --- /dev/null +++ b/scripts/ci-migrate-smoke.ts @@ -0,0 +1,56 @@ +/** + * CI smoke for a database built only with `prisma migrate deploy` + * (scripts/ci-migrate-check.sh). Never point it at a real database. + * + * 1. Every model in schema.prisma can be read: findFirst selects every + * scalar column, so a missing table or column fails here. + * 2. A workspace can be created the way actions/create-workspace.ts does + * it: an owner and widget settings, and no workspaces.apiKey (0006 + * drops that orphan 0001_init column). + */ +import { PrismaPg } from "@prisma/adapter-pg"; +import { Prisma, PrismaClient } from "@prisma/client"; + +async function main() { + const url = process.env.DATABASE_URL ?? ""; + if (!/@(localhost|127\.0\.0\.1)[:/]/.test(url)) { + throw new Error("ci-migrate-smoke only runs against a local database"); + } + const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: url }) }); + try { + const models = Object.values(Prisma.ModelName); + for (const model of models) { + const delegate = (prisma as unknown as Record }>)[ + model[0].toLowerCase() + model.slice(1) + ]; + try { + await delegate.findFirst(); + } catch (error) { + throw new Error(`model ${model} can't be read: ${error instanceof Error ? error.message.split("\n").pop() : error}`); + } + } + console.log(`read ${models.length} models`); + + const user = await prisma.user.create({ data: { email: `ci-smoke-${Date.now()}@example.test`, name: "CI" } }); + const workspace = await prisma.workspace.create({ + data: { + name: "CI smoke", + slug: `ci-smoke-${Date.now()}`, + members: { create: { userId: user.id, role: "OWNER" } }, + widgetSettings: { create: { workspaceName: "CI smoke" } }, + }, + include: { members: true, widgetSettings: true }, + }); + if (!workspace.appId || workspace.members.length !== 1 || !workspace.widgetSettings) { + throw new Error("workspace create returned an incomplete row"); + } + console.log("created a workspace with an appId, an owner and widget settings"); + } finally { + await prisma.$disconnect(); + } +} + +main().catch((error) => { + console.error("FAIL:", error instanceof Error ? error.message : error); + process.exit(1); +}); diff --git a/scripts/sync-oss.sh b/scripts/sync-oss.sh index 3b11df7f..85b96756 100644 --- a/scripts/sync-oss.sh +++ b/scripts/sync-oss.sh @@ -43,12 +43,26 @@ exclude_files = { "PRODUCT.md", "DESIGN.md", ".github/workflows/cron.yml", + ".github/workflows/ci.yml", "lib/scheduled/cron-workflow.test.ts", } +# Core owns CI and prisma/migrations. Do not copy hosted versions over them +# and do not delete dest files hosted omitted. Hosted numbering can skip +# catch-up migrations; #74 wiped 0005_schema_catch_up that way. +exclude_rel_dirs = {"prisma/migrations"} +keep_dest_files = {".github/workflows/ci.yml"} + +def skip_rel(rel): + s = "." if rel == Path(".") else str(rel) + return s in exclude_rel_dirs or any(s == p or s.startswith(p + os.sep) for p in exclude_rel_dirs) + src_files = set() for dirpath, dirnames, filenames in os.walk(src): - dirnames[:] = [d for d in dirnames if d not in exclude_dirs] rel = Path(dirpath).relative_to(src) + if skip_rel(rel): + dirnames[:] = [] + continue + dirnames[:] = [d for d in dirnames if d not in exclude_dirs and not skip_rel(Path(d) if rel == Path(".") else rel / d)] for f in filenames: relf = str(rel / f) if rel != Path(".") else f if relf in exclude_files or f.endswith(".pem") or f == ".DS_Store": @@ -60,12 +74,17 @@ for dirpath, dirnames, filenames in os.walk(src): target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src / relf, target) for dirpath, dirnames, filenames in os.walk(dst): - dirnames[:] = [d for d in dirnames if d not in exclude_dirs] rel = Path(dirpath).relative_to(dst) + if skip_rel(rel): + dirnames[:] = [] + continue + dirnames[:] = [d for d in dirnames if d not in exclude_dirs and not skip_rel(Path(d) if rel == Path(".") else rel / d)] for f in filenames: relf = str(rel / f) if rel != Path(".") else f if relf.startswith(".git"): continue + if relf in keep_dest_files: + continue if relf not in src_files: (dst / relf).unlink() PY