Add schedule api (#60)
This commit is contained in:
137
apps/web/src/app/(dashboard)/emails/cancel-email.tsx
Normal file
137
apps/web/src/app/(dashboard)/emails/cancel-email.tsx
Normal 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;
|
169
apps/web/src/app/(dashboard)/emails/edit-schedule.tsx
Normal file
169
apps/web/src/app/(dashboard)/emails/edit-schedule.tsx
Normal 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;
|
@@ -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>;
|
||||
|
@@ -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>
|
||||
))
|
||||
|
@@ -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 });
|
||||
}),
|
||||
});
|
||||
|
46
apps/web/src/server/public-api/api/emails/cancel-email.ts
Normal file
46
apps/web/src/server/public-api/api/emails/cancel-email.ts
Normal 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;
|
@@ -28,6 +28,7 @@ const route = createRoute({
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
scheduledAt: z.string().datetime().optional(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
|
58
apps/web/src/server/public-api/api/emails/update-email.ts
Normal file
58
apps/web/src/server/public-api/api/emails/update-email.ts
Normal 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;
|
@@ -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);
|
||||
|
@@ -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() {
|
||||
|
@@ -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",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
@@ -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
|
||||
|
@@ -9,6 +9,7 @@ export type EmailContent = {
|
||||
bcc?: string | string[];
|
||||
attachments?: Array<EmailAttachment>;
|
||||
unsubUrl?: string;
|
||||
scheduledAt?: string;
|
||||
};
|
||||
|
||||
export type EmailAttachment = {
|
||||
|
Reference in New Issue
Block a user