Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,6 @@ AUTH_EMAIL_RATE_LIMIT=5
# REDIS_KEY_PREFIX=""

NEXT_PUBLIC_IS_CLOUD=true

# Optional: bearer token (at least 32 characters) for the internal admin API at /api/admin. Off when empty.
# ADMIN_API_TOKEN=""
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
-- CreateEnum
CREATE TYPE "FeedbackStatus" AS ENUM ('OPEN', 'REPLIED', 'CLOSED');

-- CreateEnum
CREATE TYPE "FeedbackReplyStatus" AS ENUM ('SENDING', 'SENT', 'FAILED');

-- CreateTable
CREATE TABLE "Feedback" (
"id" TEXT NOT NULL,
"userId" INTEGER,
"teamId" INTEGER,
"email" TEXT NOT NULL,
"name" TEXT,
"teamName" TEXT,
"message" TEXT NOT NULL,
"source" TEXT NOT NULL,
"clientKey" TEXT,
"externalId" TEXT,
"status" "FeedbackStatus" NOT NULL DEFAULT 'OPEN',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Feedback_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "FeedbackReply" (
"id" TEXT NOT NULL,
"feedbackId" TEXT NOT NULL,
"message" TEXT NOT NULL,
"idempotencyKey" TEXT NOT NULL,
"deliveryStatus" "FeedbackReplyStatus" NOT NULL DEFAULT 'SENDING',
"attemptId" TEXT,
"attemptStartedAt" TIMESTAMP(3),
"sentAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "FeedbackReply_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Feedback_clientKey_key" ON "Feedback"("clientKey");

-- CreateIndex
CREATE UNIQUE INDEX "Feedback_externalId_key" ON "Feedback"("externalId");

-- CreateIndex
CREATE INDEX "Feedback_status_createdAt_idx" ON "Feedback"("status", "createdAt");

-- CreateIndex
CREATE INDEX "Feedback_userId_createdAt_idx" ON "Feedback"("userId", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "FeedbackReply_idempotencyKey_key" ON "FeedbackReply"("idempotencyKey");

-- CreateIndex
CREATE INDEX "FeedbackReply_feedbackId_idx" ON "FeedbackReply"("feedbackId");

-- AddForeignKey
ALTER TABLE "Feedback" ADD CONSTRAINT "Feedback_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Feedback" ADD CONSTRAINT "Feedback_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "FeedbackReply" ADD CONSTRAINT "FeedbackReply_feedbackId_fkey" FOREIGN KEY ("feedbackId") REFERENCES "Feedback"("id") ON DELETE CASCADE ON UPDATE CASCADE;

63 changes: 63 additions & 0 deletions apps/web/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ model User {
teamUsers TeamUser[]
webhookEndpoints Webhook[]
waitlistApplication WaitlistApplication?
feedback Feedback[]
}

enum WaitlistStatus {
Expand Down Expand Up @@ -155,6 +156,7 @@ model Team {
suppressionList SuppressionList[]
webhookEndpoints Webhook[]
webhookCalls WebhookCall[]
feedback Feedback[]
}

model TeamInvite {
Expand Down Expand Up @@ -540,3 +542,64 @@ model WebhookCall {
@@index([teamId, webhookId, status])
@@index([createdAt(sort: Desc)])
}

enum FeedbackStatus {
OPEN
REPLIED
CLOSED
}

/// Feedback sent from the dashboard's Feedback button. Deleted with the user.
model Feedback {
id String @id @default(cuid())
userId Int?
/// The team they were using when they sent it
teamId Int?
/// The sender's email, name and team name when they sent it
email String
name String?
teamName String?
message String
/// `web`, or `import` for feedback copied from the old feedback emails
source String
/// Sent by the dashboard once per draft, so a retried submit doesn't save it twice
clientKey String? @unique
/// Only set on imported feedback
externalId String? @unique
status FeedbackStatus @default(OPEN)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)
replies FeedbackReply[]

@@index([status, createdAt])
@@index([userId, createdAt])
}

enum FeedbackReplyStatus {
/// Being sent, or it's unknown whether it went: never resent automatically
SENDING
SENT
/// Certainly not sent, so it's safe to send again
FAILED
}

/// A reply emailed to whoever sent the feedback.
model FeedbackReply {
id String @id @default(cuid())
feedbackId String
message String
/// One per reply: sending again with the same key never sends a second email
idempotencyKey String @unique
deliveryStatus FeedbackReplyStatus @default(SENDING)
/// The send attempt holding it while SENDING: only that attempt may complete it
attemptId String?
attemptStartedAt DateTime?
sentAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
feedback Feedback @relation(fields: [feedbackId], references: [id], onDelete: Cascade)

@@index([feedbackId])
}
46 changes: 46 additions & 0 deletions apps/web/src/app/api/admin/feedback/[id]/reply/[replyId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { AdminApiError, adminApiRoute, param } from "~/server/admin-api";
import {
ReplyNotFoundError,
ReplyNotSendingError,
ReplyStillSendingError,
settleReply,
settleReplyBody,
} from "~/server/service/feedback-admin";

export const dynamic = "force-dynamic";

/**
* PATCH /api/admin/feedback/{id}/reply/{replyId} with `{ "deliveryStatus": "SENT" | "FAILED" }`.
* Settles a reply whose send is unknown. Only after checking whether the email
* arrived: FAILED lets the same key be sent again. Allowed only for a SENDING
* reply whose attempt started at least 10 minutes ago.
*/
export const PATCH = adminApiRoute(async ({ body, params }) => {
const { deliveryStatus } = settleReplyBody.parse(body);
try {
const reply = await settleReply(
param(params.id) ?? "",
param(params.replyId) ?? "",
deliveryStatus,
);
return {
id: reply.id,
deliveryStatus: reply.deliveryStatus,
sentAt: reply.sentAt?.toISOString() ?? null,
};
} catch (error) {
if (error instanceof ReplyNotFoundError) {
throw new AdminApiError(404, "Reply not found");
}
if (error instanceof ReplyNotSendingError) {
throw new AdminApiError(
409,
"Only a reply that's still sending can be settled",
);
}
if (error instanceof ReplyStillSendingError) {
throw new AdminApiError(409, "Reply is still sending; try again later");
}
throw error;
}
});
71 changes: 71 additions & 0 deletions apps/web/src/app/api/admin/feedback/[id]/reply/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { AdminApiError, adminApiRoute, json, param } from "~/server/admin-api";
import {
FeedbackNotFoundError,
IdempotencyConflictError,
MailNotSentError,
MailUncertainError,
ReplyInProgressError,
ReplyNotSendingError,
replyBody,
replyToFeedback,
} from "~/server/service/feedback-admin";

export const dynamic = "force-dynamic";

/**
* POST /api/admin/feedback/{id}/reply with `{ "message": "...", "idempotencyKey": "..." }`.
* Emails the reply to whoever sent the feedback, at most once per key:
* - 201 sent now; 200 already sent with this key.
* - 502 certainly not sent: retry with the same key.
* - 409 being sent, or it may have been sent: check whether it arrived, then
* settle it with PATCH /api/admin/feedback/{id}/reply/{replyId}.
*/
export const POST = adminApiRoute(async ({ body, params }) => {
const input = replyBody.parse(body);
try {
const { reply, sent } = await replyToFeedback(
param(params.id) ?? "",
input,
);
return json(sent ? 201 : 200, {
id: reply.id,
deliveryStatus: reply.deliveryStatus,
sentAt: reply.sentAt?.toISOString() ?? null,
});
} catch (error) {
if (error instanceof FeedbackNotFoundError) {
throw new AdminApiError(404, "Feedback not found");
}
if (error instanceof IdempotencyConflictError) {
throw new AdminApiError(
409,
"This key was used for a different reply; use a new key",
);
}
if (error instanceof ReplyInProgressError) {
throw new AdminApiError(
409,
"This reply is being sent, or it may have been sent; check whether it arrived before settling it",
);
}
if (error instanceof ReplyNotSendingError) {
throw new AdminApiError(
409,
"This reply was settled by hand while it was sending; that decision stands",
);
}
if (error instanceof MailUncertainError) {
throw new AdminApiError(
409,
"It's unknown whether the reply was sent; check whether it arrived before settling it",
);
}
if (error instanceof MailNotSentError) {
throw new AdminApiError(
502,
"The reply was not sent; try again with the same key",
);
}
throw error;
}
});
21 changes: 21 additions & 0 deletions apps/web/src/app/api/admin/feedback/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { AdminApiError, adminApiRoute, param } from "~/server/admin-api";
import {
FeedbackNotFoundError,
setFeedbackStatus,
statusBody,
} from "~/server/service/feedback-admin";

export const dynamic = "force-dynamic";

/** PATCH /api/admin/feedback/{id} with `{ "status": "OPEN" | "REPLIED" | "CLOSED" }`. */
export const PATCH = adminApiRoute(async ({ body, params }) => {
const { status } = statusBody.parse(body);
try {
return await setFeedbackStatus(param(params.id) ?? "", status);
} catch (error) {
if (error instanceof FeedbackNotFoundError) {
throw new AdminApiError(404, "Feedback not found");
}
throw error;
}
});
15 changes: 15 additions & 0 deletions apps/web/src/app/api/admin/feedback/import/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { adminApiRoute } from "~/server/admin-api";
import { importBody, importFeedback } from "~/server/service/feedback-admin";

export const dynamic = "force-dynamic";

/**
* POST /api/admin/feedback/import with `{ "items": [...] }`, at most 500 items.
* Copies feedback from the old feedback emails. Only feedback from existing
* accounts is stored; the rest is counted as `unmatched`. Safe to run again.
*/
export const POST = adminApiRoute(
async ({ body }) => importFeedback(importBody.parse(body)),
// A full batch of long messages is past the default 1mb
{ maxBodyBytes: 10 * 1024 * 1024 },
);
Loading
Loading