Add schedule api (#60)

This commit is contained in:
KM Koushik
2024-08-21 17:19:11 +10:00
committed by GitHub
parent 1e66222425
commit 9b54fc1793
21 changed files with 920 additions and 86 deletions

View File

@@ -34,6 +34,7 @@
"@unsend/email-editor": "workspace:*",
"@unsend/ui": "workspace:*",
"bullmq": "^5.8.2",
"chrono-node": "^2.7.6",
"date-fns": "^3.6.0",
"hono": "^4.2.2",
"html-to-text": "^9.0.5",

View File

@@ -0,0 +1,5 @@
-- AlterEnum
ALTER TYPE "EmailStatus" ADD VALUE 'SCHEDULED';
-- AlterTable
ALTER TABLE "Email" ADD COLUMN "scheduledAt" TIMESTAMP(3);

View File

@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "EmailStatus" ADD VALUE 'CANCELLED';

View File

@@ -166,6 +166,7 @@ model ApiKey {
}
enum EmailStatus {
SCHEDULED
QUEUED
SENT
DELIVERY_DELAYED
@@ -177,6 +178,7 @@ enum EmailStatus {
CLICKED
COMPLAINED
FAILED
CANCELLED
}
model Email {
@@ -195,6 +197,7 @@ model Email {
domainId Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
scheduledAt DateTime?
attachments String?
campaignId String?
contactId String?

View File

@@ -0,0 +1,137 @@
"use client";
import { Button } from "@unsend/ui/src/button";
import { Input } from "@unsend/ui/src/input";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@unsend/ui/src/dialog";
import { api } from "~/trpc/react";
import React, { useState } from "react";
import { toast } from "@unsend/ui/src/toaster";
import { Trash2 } from "lucide-react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@unsend/ui/src/form";
const cancelSchema = z.object({
confirmation: z.string(),
});
export const CancelEmail: React.FC<{
emailId: string;
}> = ({ emailId }) => {
const [open, setOpen] = useState(false);
const cancelEmailMutation = api.email.cancelEmail.useMutation();
const utils = api.useUtils();
const cancelForm = useForm<z.infer<typeof cancelSchema>>({
resolver: zodResolver(cancelSchema),
});
async function onEmailCancel(values: z.infer<typeof cancelSchema>) {
if (values.confirmation !== "cancel") {
cancelForm.setError("confirmation", {
message: "Confirmation does not match",
});
return;
}
cancelEmailMutation.mutate(
{
id: emailId,
},
{
onSuccess: () => {
utils.email.getEmail.invalidate({ id: emailId });
setOpen(false);
toast.success(`Email cancelled`);
},
onError: (e) => {
toast.error(`Error cancelling email: ${e.message}`);
},
}
);
}
const confirmation = cancelForm.watch("confirmation");
return (
<Dialog
open={open}
onOpenChange={(_open) => (_open !== open ? setOpen(_open) : null)}
>
<DialogTrigger asChild>
<Button variant="ghost" size="sm">
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Cancel Email</DialogTitle>
<DialogDescription>
Are you sure you want to cancel this email? This action cannot be
undone.
</DialogDescription>
</DialogHeader>
<div className="py-2">
<Form {...cancelForm}>
<form
onSubmit={cancelForm.handleSubmit(onEmailCancel)}
className="space-y-4"
>
<FormField
control={cancelForm.control}
name="confirmation"
render={({ field, formState }) => (
<FormItem>
<FormLabel>Type "cancel" to confirm</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
{formState.errors.confirmation ? (
<FormMessage />
) : (
<FormDescription className="text-transparent">
.
</FormDescription>
)}
</FormItem>
)}
/>
<div className="flex justify-end">
<Button
type="submit"
variant="destructive"
disabled={
cancelEmailMutation.isPending || confirmation !== "cancel"
}
>
{cancelEmailMutation.isPending
? "Cancelling..."
: "Cancel Email"}
</Button>
</div>
</form>
</Form>
</div>
</DialogContent>
</Dialog>
);
};
export default CancelEmail;

View File

@@ -0,0 +1,169 @@
"use client";
import { Button } from "@unsend/ui/src/button";
import { Input } from "@unsend/ui/src/input";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@unsend/ui/src/dialog";
import * as chrono from "chrono-node";
import { api } from "~/trpc/react";
import { useRef, useState } from "react";
import { Edit3 } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "@unsend/ui/src/toaster";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSubContent,
DropdownMenuTrigger,
} from "@unsend/ui/src/dropdown-menu";
import {
Command,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@unsend/ui/src/command";
export const EditSchedule: React.FC<{
emailId: string;
scheduledAt: string | null;
}> = ({ emailId, scheduledAt }) => {
const [open, setOpen] = useState(false);
const [openSuggestions, setOpenSuggestions] = useState(true);
const [scheduleInput, setScheduleInput] = useState(scheduledAt || "");
const [scheduledAtTime, setScheduledAtTime] = useState<Date | null>(
scheduledAt ? new Date(scheduledAt) : null
);
const updateEmailScheduledAtMutation =
api.email.updateEmailScheduledAt.useMutation();
const utils = api.useUtils();
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
const handleScheduleUpdate = () => {
const parsedDate = chrono.parseDate(scheduleInput);
if (!parsedDate) {
toast.error("Invalid date and time");
return;
}
updateEmailScheduledAtMutation.mutate(
{
id: emailId,
scheduledAt: parsedDate.toISOString(),
},
{
onSuccess: () => {
utils.email.getEmail.invalidate({ id: emailId });
setOpen(false);
toast.success("Email schedule updated successfully");
},
onError: (error) => {
toast.error(error.message);
},
}
);
};
const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setScheduleInput(e.target.value);
const parsedDate = chrono.parseDate(e.target.value);
if (parsedDate) {
setScheduledAtTime(parsedDate);
}
};
return (
<Dialog
open={open}
onOpenChange={(_open) => (_open !== open ? setOpen(_open) : null)}
>
<DialogTrigger asChild>
<Button variant="ghost" size="sm">
<Edit3 className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Schedule</DialogTitle>
</DialogHeader>
<div className="py-2">
<div className="space-y-4">
<div>
<label htmlFor="scheduleInput" className="block mb-2">
Schedule at
</label>
{/* <Input
id="scheduleInput"
value={scheduleInput}
onChange={onInputChange}
// onClick={() => setOpenSuggestions(true)}
onFocus={() => setOpenSuggestions(true)}
// onBlur={() => setOpenSuggestions(false)}
placeholder="Enter date and time (e.g., tomorrow at 3pm)"
/>
<DropdownMenu
open={openSuggestions}
onOpenChange={setOpenSuggestions}
>
<div className="w-full flex justify-center">
<DropdownMenuTrigger></DropdownMenuTrigger>
</div>
<DropdownMenuContent className=" min-w-[29rem]">
<DropdownMenuItem>Profile</DropdownMenuItem>
<DropdownMenuItem>Billing</DropdownMenuItem>
<DropdownMenuItem>Team</DropdownMenuItem>
<DropdownMenuItem>Subscription</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu> */}
<CommandDialog
open={openSuggestions}
onOpenChange={setOpenSuggestions}
>
<CommandInput placeholder="Type a command or search..." />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem>Calendar</CommandItem>
<CommandItem>Search Emoji</CommandItem>
<CommandItem>Calculator</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Settings">
<CommandItem>Profile</CommandItem>
<CommandItem>Billing</CommandItem>
<CommandItem>Settings</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</div>
<div className="flex justify-end">
<Button
className="w-[100px] bg-white hover:bg-gray-100 focus:bg-gray-100"
onClick={handleScheduleUpdate}
disabled={updateEmailScheduledAtMutation.isPending}
>
{updateEmailScheduledAtMutation.isPending
? "Updating..."
: "Update"}
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default EditSchedule;

View File

@@ -19,6 +19,10 @@ import {
COMPLAINT_ERROR_MESSAGES,
DELIVERY_DELAY_ERRORS,
} from "~/lib/constants/ses-errors";
import { Button } from "@unsend/ui/src/button";
import { Edit2, Edit3, Trash2 } from "lucide-react";
import CancelEmail from "./cancel-email";
import EditSchedule from "./edit-schedule";
export default function EmailDetails({ emailId }: { emailId: string }) {
const emailQuery = api.email.getEmail.useQuery({ id: emailId });
@@ -34,19 +38,43 @@ export default function EmailDetails({ emailId }: { emailId: string }) {
<div className="flex flex-col gap-8 mt-10 items-start ">
<div className="p-2 rounded-lg border flex flex-col gap-4 w-full">
<div className="flex gap-2">
<span className="w-[65px] text-muted-foreground ">From</span>
<span>{emailQuery.data?.from}</span>
<span className="w-[100px] text-muted-foreground text-sm">
From
</span>
<span className="text-sm">{emailQuery.data?.from}</span>
</div>
<Separator />
<div className="flex gap-2">
<span className="w-[65px] text-muted-foreground ">To</span>
<span>{emailQuery.data?.to}</span>
<span className="w-[100px] text-muted-foreground text-sm">To</span>
<span className="text-sm">{emailQuery.data?.to}</span>
</div>
<Separator />
<div className="flex gap-2">
<span className="w-[65px] text-muted-foreground ">Subject</span>
<span>{emailQuery.data?.subject}</span>
<span className="w-[100px] text-muted-foreground text-sm">
Subject
</span>
<span className="text-sm">{emailQuery.data?.subject}</span>
</div>
{emailQuery.data?.latestStatus === "SCHEDULED" &&
emailQuery.data?.scheduledAt ? (
<>
<Separator />
<div className="flex gap-2 items-center">
<span className="w-[100px] text-muted-foreground text-sm ">
Scheduled at
</span>
<span className="text-sm">
{formatDate(
emailQuery.data?.scheduledAt,
"MMM dd'th', hh:mm a"
)}
</span>
<div className="ml-4">
<CancelEmail emailId={emailId} />
</div>
</div>
</>
) : null}
<div className=" dark:bg-slate-200 h-[250px] overflow-auto text-black rounded">
<div
className="px-4 py-4 overflow-auto"
@@ -54,37 +82,42 @@ export default function EmailDetails({ emailId }: { emailId: string }) {
/>
</div>
</div>
<div className=" border rounded-lg w-full ">
<div className=" p-4 flex flex-col gap-8 w-full">
<div className="font-medium">Events History</div>
<div className="flex items-stretch px-4 w-full">
<div className="border-r border-dashed" />
<div className="flex flex-col gap-12 w-full">
{emailQuery.data?.emailEvents.map((evt) => (
<div
key={evt.status}
className="flex gap-5 items-start w-full"
>
<div className=" -ml-2.5">
<EmailStatusIcon status={evt.status} />
</div>
<div className="-mt-[0.125rem] w-full">
<div className=" capitalize font-medium">
<EmailStatusBadge status={evt.status} />
{emailQuery.data?.latestStatus !== "SCHEDULED" ? (
<div className=" border rounded-lg w-full ">
<div className=" p-4 flex flex-col gap-8 w-full">
<div className="font-medium">Events History</div>
<div className="flex items-stretch px-4 w-full">
<div className="border-r border-dashed" />
<div className="flex flex-col gap-12 w-full">
{emailQuery.data?.emailEvents.map((evt) => (
<div
key={evt.status}
className="flex gap-5 items-start w-full"
>
<div className=" -ml-2.5">
<EmailStatusIcon status={evt.status} />
</div>
<div className="text-xs text-muted-foreground mt-2">
{formatDate(evt.createdAt, "MMM dd, hh:mm a")}
</div>
<div className="mt-1 text-primary/80">
<EmailStatusText status={evt.status} data={evt.data} />
<div className="-mt-[0.125rem] w-full">
<div className=" capitalize font-medium">
<EmailStatusBadge status={evt.status} />
</div>
<div className="text-xs text-muted-foreground mt-2">
{formatDate(evt.createdAt, "MMM dd, hh:mm a")}
</div>
<div className="mt-1 text-primary/80">
<EmailStatusText
status={evt.status}
data={evt.data}
/>
</div>
</div>
</div>
</div>
))}
))}
</div>
</div>
</div>
</div>
</div>
) : null}
</div>
</div>
);
@@ -194,6 +227,8 @@ const EmailStatusText = ({
<p>{getComplaintMessage(_errorData.complaintFeedbackType)}</p>
</div>
);
} else if (status === "CANCELLED") {
return <div>This scheduled email was cancelled</div>;
}
return <div className="w-full">{status}</div>;

View File

@@ -17,7 +17,7 @@ import {
MailWarning,
MailX,
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { formatDate, formatDistanceToNow } from "date-fns";
import { EmailStatus } from "@prisma/client";
import { EmailStatusBadge } from "./email-status-badge";
import EmailDetails from "./email-details";
@@ -31,6 +31,12 @@ import {
SelectTrigger,
} from "@unsend/ui/src/select";
import Spinner from "@unsend/ui/src/spinner";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@unsend/ui/src/tooltip";
/* Stupid hydrating error. And I so stupid to understand the stupid NextJS docs */
const DynamicSheetWithNoSSR = dynamic(
@@ -123,16 +129,39 @@ export default function EmailsList() {
>
<TableCell className="font-medium">
<div className="flex gap-4 items-center">
<EmailIcon status={email.latestStatus ?? "Send"} />
<EmailIcon status={email.latestStatus ?? "Sent"} />
<p>{email.to}</p>
</div>
</TableCell>
<TableCell>
<EmailStatusBadge status={email.latestStatus ?? "Sent"} />
{email.latestStatus === "SCHEDULED" && email.scheduledAt ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<EmailStatusBadge
status={email.latestStatus ?? "Sent"}
/>
</TooltipTrigger>
<TooltipContent>
Scheduled at{" "}
{formatDate(
email.scheduledAt,
"MMM dd'th', hh:mm a"
)}
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<EmailStatusBadge status={email.latestStatus ?? "Sent"} />
)}
</TableCell>
<TableCell>{email.subject}</TableCell>
<TableCell className="text-right">
{formatDistanceToNow(email.createdAt, { addSuffix: true })}
{email.latestStatus !== "SCHEDULED"
? formatDistanceToNow(
email.scheduledAt ?? email.createdAt
)
: "--"}
</TableCell>
</TableRow>
))

View File

@@ -4,6 +4,7 @@ import { z } from "zod";
import { createTRPCRouter, teamProcedure } from "~/server/api/trpc";
import { db } from "~/server/db";
import { cancelEmail, updateEmail } from "~/server/service/email-service";
const statuses = Object.values(EmailStatus) as [EmailStatus];
@@ -39,6 +40,7 @@ export const emailRouter = createTRPCRouter({
latestStatus: true,
subject: true,
to: true,
scheduledAt: true,
},
orderBy: {
createdAt: "desc",
@@ -187,9 +189,22 @@ export const emailRouter = createTRPCRouter({
domainId: true,
text: true,
html: true,
scheduledAt: true,
},
});
return email;
}),
cancelEmail: teamProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input }) => {
await cancelEmail(input.id);
}),
updateEmailScheduledAt: teamProcedure
.input(z.object({ id: z.string(), scheduledAt: z.string().datetime() }))
.mutation(async ({ input }) => {
await updateEmail(input.id, { scheduledAt: input.scheduledAt });
}),
});

View File

@@ -0,0 +1,46 @@
import { createRoute, z } from "@hono/zod-openapi";
import { PublicAPIApp } from "~/server/public-api/hono";
import { getTeamFromToken } from "~/server/public-api/auth";
import { cancelEmail } from "~/server/service/email-service";
const route = createRoute({
method: "post",
path: "/v1/emails/{emailId}/cancel",
request: {
params: z.object({
emailId: z
.string()
.min(3)
.openapi({
param: {
name: "emailId",
in: "path",
},
example: "cuiwqdj74rygf74",
}),
}),
},
responses: {
200: {
content: {
"application/json": {
schema: z.object({ emailId: z.string().optional() }),
},
},
description: "Retrieve the user",
},
},
});
function cancelScheduledEmail(app: PublicAPIApp) {
app.openapi(route, async (c) => {
await getTeamFromToken(c);
const emailId = c.req.param("emailId");
await cancelEmail(emailId);
return c.json({ emailId });
});
}
export default cancelScheduledEmail;

View File

@@ -28,6 +28,7 @@ const route = createRoute({
})
)
.optional(),
scheduledAt: z.string().datetime().optional(),
}),
},
},

View File

@@ -0,0 +1,58 @@
import { createRoute, z } from "@hono/zod-openapi";
import { PublicAPIApp } from "~/server/public-api/hono";
import { getTeamFromToken } from "~/server/public-api/auth";
import { updateEmail } from "~/server/service/email-service";
const route = createRoute({
method: "patch",
path: "/v1/emails/{emailId}",
request: {
params: z.object({
emailId: z
.string()
.min(3)
.openapi({
param: {
name: "emailId",
in: "path",
},
example: "cuiwqdj74rygf74",
}),
}),
body: {
required: true,
content: {
"application/json": {
schema: z.object({
scheduledAt: z.string().datetime(),
}),
},
},
},
},
responses: {
200: {
content: {
"application/json": {
schema: z.object({ emailId: z.string().optional() }),
},
},
description: "Retrieve the user",
},
},
});
function updateEmailScheduledAt(app: PublicAPIApp) {
app.openapi(route, async (c) => {
await getTeamFromToken(c);
const emailId = c.req.param("emailId");
await updateEmail(emailId, {
scheduledAt: c.req.valid("json").scheduledAt,
});
return c.json({ emailId });
});
}
export default updateEmailScheduledAt;

View File

@@ -5,6 +5,8 @@ import getEmail from "./api/emails/get-email";
import addContact from "./api/contacts/add-contact";
import updateContactInfo from "./api/contacts/update-contact";
import getContact from "./api/contacts/get-contact";
import updateEmailScheduledAt from "./api/emails/update-email";
import cancelScheduledEmail from "./api/emails/cancel-email";
export const app = getApp();
@@ -14,6 +16,8 @@ getDomains(app);
/**Email related APIs */
getEmail(app);
sendEmail(app);
updateEmailScheduledAt(app);
cancelScheduledEmail(app);
/**Contact related APIs */
addContact(app);

View File

@@ -41,13 +41,6 @@ export class EmailQueueService {
);
const marketingQuota = quota - transactionalQuota;
console.log(
"is transactional queue",
this.transactionalQueue.has(region),
"is marketing queue",
this.marketingQueue.has(region)
);
if (this.transactionalQueue.has(region)) {
console.log(
`[EmailQueueService]: Updating transactional quota for region ${region} to ${transactionalQuota}`
@@ -98,7 +91,8 @@ export class EmailQueueService {
emailId: string,
region: string,
transactional: boolean,
unsubUrl?: string
unsubUrl?: string,
delay?: number
) {
if (!this.initialized) {
await this.init();
@@ -109,7 +103,56 @@ export class EmailQueueService {
if (!queue) {
throw new Error(`Queue for region ${region} not found`);
}
queue.add("send-email", { emailId, timestamp: Date.now(), unsubUrl });
queue.add(
emailId,
{ emailId, timestamp: Date.now(), unsubUrl },
{ jobId: emailId, delay }
);
}
public static async changeDelay(
emailId: string,
region: string,
transactional: boolean,
delay: number
) {
if (!this.initialized) {
await this.init();
}
const queue = transactional
? this.transactionalQueue.get(region)
: this.marketingQueue.get(region);
if (!queue) {
throw new Error(`Queue for region ${region} not found`);
}
const job = await queue.getJob(emailId);
if (!job) {
throw new Error(`Job ${emailId} not found`);
}
await job.changeDelay(delay);
}
public static async chancelEmail(
emailId: string,
region: string,
transactional: boolean
) {
if (!this.initialized) {
await this.init();
}
const queue = transactional
? this.transactionalQueue.get(region)
: this.marketingQueue.get(region);
if (!queue) {
throw new Error(`Queue for region ${region} not found`);
}
const job = await queue.getJob(emailId);
if (!job) {
throw new Error(`Job ${emailId} not found`);
}
await job.remove();
}
public static async init() {

View File

@@ -3,9 +3,32 @@ import { db } from "../db";
import { UnsendApiError } from "~/server/public-api/api-error";
import { EmailQueueService } from "./email-queue-service";
import { validateDomainFromEmail } from "./domain-service";
import { Campaign, Contact } from "@prisma/client";
import { EmailRenderer } from "@unsend/email-editor/src/renderer";
import { createUnsubUrl } from "./campaign-service";
async function checkIfValidEmail(emailId: string) {
const email = await db.email.findUnique({
where: { id: emailId },
});
if (!email || !email.domainId) {
throw new UnsendApiError({
code: "BAD_REQUEST",
message: "Email not found",
});
}
const domain = await db.domain.findUnique({
where: { id: email.domainId },
});
if (!domain) {
throw new UnsendApiError({
code: "BAD_REQUEST",
message: "Email not found",
});
}
return { email, domain };
}
/**
Send transactional email
@@ -24,10 +47,16 @@ export async function sendEmail(
replyTo,
cc,
bcc,
scheduledAt,
} = emailContent;
const domain = await validateDomainFromEmail(from, teamId);
const scheduledAtDate = scheduledAt ? new Date(scheduledAt) : undefined;
const delay = scheduledAtDate
? Math.max(0, scheduledAtDate.getTime() - Date.now())
: undefined;
const email = await db.email.create({
data: {
to: Array.isArray(to) ? to : [to],
@@ -45,11 +74,19 @@ export async function sendEmail(
teamId,
domainId: domain.id,
attachments: attachments ? JSON.stringify(attachments) : undefined,
scheduledAt: scheduledAtDate,
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
},
});
try {
await EmailQueueService.queueEmail(email.id, domain.region, true);
await EmailQueueService.queueEmail(
email.id,
domain.region,
true,
undefined,
delay
);
} catch (error: any) {
await db.emailEvent.create({
data: {
@@ -69,3 +106,62 @@ export async function sendEmail(
return email;
}
export async function updateEmail(
emailId: string,
{
scheduledAt,
}: {
scheduledAt?: string;
}
) {
const { email, domain } = await checkIfValidEmail(emailId);
if (email.latestStatus !== "SCHEDULED") {
throw new UnsendApiError({
code: "BAD_REQUEST",
message: "Email already processed",
});
}
const scheduledAtDate = scheduledAt ? new Date(scheduledAt) : undefined;
const delay = scheduledAtDate
? Math.max(0, scheduledAtDate.getTime() - Date.now())
: undefined;
await db.email.update({
where: { id: emailId },
data: {
scheduledAt: scheduledAtDate,
},
});
await EmailQueueService.changeDelay(emailId, domain.region, true, delay ?? 0);
}
export async function cancelEmail(emailId: string) {
const { email, domain } = await checkIfValidEmail(emailId);
if (email.latestStatus !== "SCHEDULED") {
throw new UnsendApiError({
code: "BAD_REQUEST",
message: "Email already processed",
});
}
await EmailQueueService.chancelEmail(emailId, domain.region, true);
await db.email.update({
where: { id: emailId },
data: {
latestStatus: "CANCELLED",
},
});
await db.emailEvent.create({
data: {
emailId,
status: "CANCELLED",
},
});
}

View File

@@ -38,7 +38,7 @@ export async function parseSesHook(data: SesEvent) {
await db.$executeRaw`
UPDATE "Email"
SET "latestStatus" = CASE
WHEN ${mailStatus}::text::\"EmailStatus\" > "latestStatus" OR "latestStatus" IS NULL
WHEN ${mailStatus}::text::\"EmailStatus\" > "latestStatus" OR "latestStatus" IS NULL OR "latestStatus" = 'SCHEDULED'::\"EmailStatus\"
THEN ${mailStatus}::text::\"EmailStatus\"
ELSE "latestStatus"
END

View File

@@ -9,6 +9,7 @@ export type EmailContent = {
bcc?: string | string[];
attachments?: Array<EmailAttachment>;
unsubUrl?: string;
scheduledAt?: string;
};
export type EmailAttachment = {

View File

@@ -43,6 +43,7 @@
"add": "^2.0.6",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"cmdk": "^1.0.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.359.0",
"next-themes": "^0.3.0",

155
packages/ui/src/command.tsx Normal file
View File

@@ -0,0 +1,155 @@
"use client";
import * as React from "react";
import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "../lib/utils";
import { Dialog, DialogContent } from "./dialog";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
interface CommandDialogProps extends DialogProps {}
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
className
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
);
};
CommandShortcut.displayName = "CommandShortcut";
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -11,7 +11,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/20 disabled:cursor-not-allowed disabled:opacity-50",
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}

105
pnpm-lock.yaml generated
View File

@@ -182,6 +182,9 @@ importers:
bullmq:
specifier: ^5.8.2
version: 5.8.2
chrono-node:
specifier: ^2.7.6
version: 2.7.6
date-fns:
specifier: ^3.6.0
version: 3.6.0
@@ -545,6 +548,9 @@ importers:
clsx:
specifier: ^2.1.0
version: 2.1.0
cmdk:
specifier: ^1.0.0
version: 1.0.0(@types/react-dom@18.2.22)(@types/react@18.2.66)(react-dom@18.2.0)(react@18.2.0)
input-otp:
specifier: ^1.2.4
version: 1.2.4(react-dom@18.2.0)(react@18.2.0)
@@ -7857,6 +7863,13 @@ packages:
engines: {node: '>=10'}
dev: true
/chrono-node@2.7.6:
resolution: {integrity: sha512-yugKSRLHc6B6kXxm/DwNc94zhaddAjCSO9IOGH3w7NIWNM+gUoLl/2/XLndiw4I+XhU4H2LOhC5Ab2JjS6JWsA==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
dayjs: 1.11.13
dev: false
/ci-info@3.9.0:
resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==}
engines: {node: '>=8'}
@@ -7958,6 +7971,21 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
/cmdk@1.0.0(@types/react-dom@18.2.22)(@types/react@18.2.66)(react-dom@18.2.0)(react@18.2.0):
resolution: {integrity: sha512-gDzVf0a09TvoJ5jnuPvygTB77+XdOSwEmJ88L6XPFPlv7T3RxbP9jgenfylrAMD0+Le1aO0nVjQUzl2g+vjz5Q==}
peerDependencies:
react: ^18.0.0
react-dom: ^18.0.0
dependencies:
'@radix-ui/react-dialog': 1.0.5(@types/react-dom@18.2.22)(@types/react@18.2.66)(react-dom@18.2.0)(react@18.2.0)
'@radix-ui/react-primitive': 1.0.3(@types/react-dom@18.2.22)(@types/react@18.2.66)(react-dom@18.2.0)(react@18.2.0)
react: 18.2.0
react-dom: 18.2.0(react@18.2.0)
transitivePeerDependencies:
- '@types/react'
- '@types/react-dom'
dev: false
/collapse-white-space@2.1.0:
resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==}
dev: false
@@ -8273,6 +8301,10 @@ packages:
resolution: {integrity: sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==}
dev: false
/dayjs@1.11.13:
resolution: {integrity: sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==}
dev: false
/debug@2.6.9:
resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
peerDependencies:
@@ -8923,7 +8955,7 @@ packages:
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1)(eslint@8.57.0)
eslint-plugin-import: 2.29.1(eslint@8.57.0)
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-typescript@3.6.1)(eslint@8.57.0)
eslint-plugin-jsx-a11y: 6.8.0(eslint@8.57.0)
eslint-plugin-react: 7.34.0(eslint@8.57.0)
eslint-plugin-react-hooks: 4.6.0(eslint@8.57.0)
@@ -8981,7 +9013,7 @@ packages:
enhanced-resolve: 5.16.0
eslint: 8.57.0
eslint-module-utils: 2.8.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1)(eslint@8.57.0)
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@7.2.0)(eslint@8.57.0)
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-typescript@3.6.1)(eslint@8.57.0)
fast-glob: 3.3.2
get-tsconfig: 4.7.3
is-core-module: 2.13.1
@@ -9115,6 +9147,41 @@ packages:
ignore: 5.3.1
dev: true
/eslint-plugin-import@2.29.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-typescript@3.6.1)(eslint@8.57.0):
resolution: {integrity: sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==}
engines: {node: '>=4'}
peerDependencies:
'@typescript-eslint/parser': '*'
eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8
peerDependenciesMeta:
'@typescript-eslint/parser':
optional: true
dependencies:
'@typescript-eslint/parser': 6.21.0(eslint@8.57.0)(typescript@5.4.2)
array-includes: 3.1.7
array.prototype.findlastindex: 1.2.4
array.prototype.flat: 1.3.2
array.prototype.flatmap: 1.3.2
debug: 3.2.7
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
eslint-module-utils: 2.8.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1)(eslint@8.57.0)
hasown: 2.0.2
is-core-module: 2.13.1
is-glob: 4.0.3
minimatch: 3.1.2
object.fromentries: 2.0.7
object.groupby: 1.0.2
object.values: 1.1.7
semver: 6.3.1
tsconfig-paths: 3.15.0
transitivePeerDependencies:
- eslint-import-resolver-typescript
- eslint-import-resolver-webpack
- supports-color
dev: true
/eslint-plugin-import@2.29.1(@typescript-eslint/parser@7.2.0)(eslint@8.57.0):
resolution: {integrity: sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==}
engines: {node: '>=4'}
@@ -9150,40 +9217,6 @@ packages:
- supports-color
dev: true
/eslint-plugin-import@2.29.1(eslint@8.57.0):
resolution: {integrity: sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==}
engines: {node: '>=4'}
peerDependencies:
'@typescript-eslint/parser': '*'
eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8
peerDependenciesMeta:
'@typescript-eslint/parser':
optional: true
dependencies:
array-includes: 3.1.7
array.prototype.findlastindex: 1.2.4
array.prototype.flat: 1.3.2
array.prototype.flatmap: 1.3.2
debug: 3.2.7
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
eslint-module-utils: 2.8.1(@typescript-eslint/parser@6.21.0)(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1)(eslint@8.57.0)
hasown: 2.0.2
is-core-module: 2.13.1
is-glob: 4.0.3
minimatch: 3.1.2
object.fromentries: 2.0.7
object.groupby: 1.0.2
object.values: 1.1.7
semver: 6.3.1
tsconfig-paths: 3.15.0
transitivePeerDependencies:
- eslint-import-resolver-typescript
- eslint-import-resolver-webpack
- supports-color
dev: true
/eslint-plugin-jest@27.9.0(@typescript-eslint/eslint-plugin@6.21.0)(eslint@8.57.0)(typescript@5.4.2):
resolution: {integrity: sha512-QIT7FH7fNmd9n4se7FFKHbsLKGQiw885Ds6Y/sxKgCZ6natwCsXdgPOADnYVxN2QrRweF0FZWbJ6S7Rsn7llug==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}