Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(email): report failed invitation and support deliveries accurately
Rishabh Bothra7543750d5a0f
diff --git a/apps/web/__tests__/unit/email-delivery-ui.test.ts b/apps/web/__tests__/unit/email-delivery-ui.test.tsnew file mode 100644index 000000000..e153c87e9--- /dev/null+++ b/apps/web/__tests__/unit/email-delivery-ui.test.ts@@ -0,0 +1,159 @@+// @vitest-environment jsdom++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, createElement, type ReactElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { sendOrganizationInvites } from "@/actions/organization/send-invites";+import { InviteDialog } from "@/app/(org)/dashboard/settings/organization/components/InviteDialog";+import { VerifyOTPForm } from "@/app/(org)/verify-otp/form";++const mocks = vi.hoisted(() => ({+ invites: vi.fn<typeof sendOrganizationInvites>(),+ signIn: vi.fn(),+ refresh: vi.fn(),+ close: vi.fn(),+ toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },+}));++vi.mock("@/actions/organization/send-invites", () => ({+ sendOrganizationInvites: mocks.invites,+}));+vi.mock("@/app/(org)/dashboard/Contexts", () => ({+ useDashboardContext: () => ({+ activeOrganization: { organization: { id: "org-1", name: "Team" } },+ }),+}));+vi.mock("next/navigation", () => ({+ useRouter: () => ({ refresh: mocks.refresh }),+}));+vi.mock("next-auth/react", () => ({ signIn: mocks.signIn }));+vi.mock("sonner", () => ({ toast: mocks.toast }));+vi.mock("@cap/utils", async () => await import("@cap/utils/helpers"));+vi.mock("@cap/ui", async () => ({+ ...(await import("../../../../packages/ui/src/components/Button")),+ ...(await import("../../../../packages/ui/src/components/Dialog")),+ ...(await import("../../../../packages/ui/src/components/Select")),+ ...(await import("../../../../packages/ui/src/components/Switch")),+ ...(await import("../../../../packages/ui/src/components/input/Input")),+ ...(await import("../../../../packages/ui/src/components/icons/LogoBadge")),+}));++let root: Root;+let container: HTMLDivElement;+let queryClient: QueryClient;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ mocks.invites.mockReset();+ mocks.signIn.mockResolvedValue({ ok: true });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ queryClient = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ queryClient.clear();+ vi.unstubAllGlobals();+});++async function render(element: ReactElement) {+ await act(async () => {+ root.render(+ createElement(QueryClientProvider, { client: queryClient }, element),+ );+ });+}++async function clickButton(label: string) {+ const button = Array.from(document.querySelectorAll("button")).find(+ (element) => element.textContent?.trim() === label,+ );+ if (!button) throw new Error(`Missing button: ${label}`);+ await act(async () => {+ button.click();+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+}++describe("verification email delivery messages", () => {+ it.each([false, true])(+ "reports the correct resend destination when email configured is %s",+ async (emailDeliveryConfigured) => {+ await render(+ createElement(VerifyOTPForm, {+ email: "[email protected]",+ emailDeliveryConfigured,+ }),+ );+ expect(container.textContent).toContain(+ emailDeliveryConfigured+ ? "We sent a 6-digit code"+ : "was printed to the server logs",+ );+ await clickButton("Didn't receive the code? Resend");+ expect(mocks.signIn).toHaveBeenCalledWith("email", {+ email: "[email protected]",+ redirect: false,+ });+ expect(mocks.toast.success).toHaveBeenCalledExactlyOnceWith(+ emailDeliveryConfigured+ ? "A new code has been sent to your email!"+ : "A new code was printed to the server logs",+ );+ },+ );+});++describe("invitation email delivery messages", () => {+ it.each([false, true])(+ "does not claim skipped emails were sent when delivery failures are %s",+ async (hasFailures) => {+ mocks.invites.mockResolvedValue({+ success: true,+ failedEmails: hasFailures ? ["[email protected]"] : [],+ skippedEmails: ["[email protected]"],+ });+ await render(+ createElement(InviteDialog, { isOpen: true, setIsOpen: mocks.close }),+ );+ const input = document.querySelector<HTMLInputElement>(+ "input[placeholder='[email protected]']",+ );+ if (!input) throw new Error("Missing invitation email input");+ await act(async () => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value",+ )?.set?.call(+ input,+ hasFailures+ : "[email protected]",+ );+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await clickButton("Send Invites");+ expect(mocks.invites).toHaveBeenCalledOnce();+ expect(mocks.toast.warning).toHaveBeenCalledWith(+ "Invites created but not emailed because email is not configured. Share the invite links with: [email protected]",+ );+ if (hasFailures) {+ expect(mocks.toast.warning).toHaveBeenCalledWith(+ "Invite email delivery failed for: [email protected]",+ );+ }+ expect(mocks.toast.warning).not.toHaveBeenCalledWith(+ expect.stringContaining("Invites sent"),+ );+ expect(mocks.toast.success).not.toHaveBeenCalled();+ expect(mocks.close).toHaveBeenCalledWith(false);+ expect(mocks.refresh).toHaveBeenCalledOnce();+ },+ );+});diff --git a/apps/web/__tests__/unit/messenger-support-email.test.ts b/apps/web/__tests__/unit/messenger-support-email.test.tsindex 64b48e828..80f8ab38e 100644--- a/apps/web/__tests__/unit/messenger-support-email.test.ts+++ b/apps/web/__tests__/unit/messenger-support-email.test.ts@@ -142,6 +142,32 @@ describe("sendMessengerSupportEmail", () => {expect(valuesMock).not.toHaveBeenCalled();});+ it.each([+ ["email_not_configured", "Email is not configured"],+ ["validation_error", "Sender domain is not verified"],+ ])("does not report a returned %s as sent", async (name, message) => {+ whereMock.mockReturnValueOnce(mockDb).mockResolvedValueOnce([{ value: 0 }]);+ sendEmailMock.mockResolvedValueOnce({+ data: null,+ error: { name, message },+ });+ const { sendMessengerSupportEmail } = await import(+ "@/lib/messenger/support-email"+ );++ await expect(+ sendMessengerSupportEmail({+ user: {+ id: User.UserId.make("user-123"),+ email: "[email protected]",+ },+ conversationId: "conversation-123",+ subject: "Upload issue",+ message: "Uploads keep failing.",+ }),+ ).rejects.toThrow(message);+ });+it("does not send when the audit reservation fails", async () => {whereMock.mockReturnValueOnce(mockDb).mockResolvedValueOnce([{ value: 1 }]);valuesMock.mockRejectedValueOnce(new Error("insert failed"));diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsxindex a66e862c7..fbbfa5053 100644--- a/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx+++ b/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx@@ -122,7 +122,7 @@ export const InviteDialog = ({ isOpen, setIsOpen }: InviteDialogProps) => {if (result.failedEmails.length > 0) {toast.warning(sendEmailNotifications- ? `Invites sent, but delivery failed for: ${result.failedEmails.join(", ")}`+ ? `Invite email delivery failed for: ${result.failedEmails.join(", ")}`: `Users added, but provisioning failed for: ${result.failedEmails.join(", ")}`,);} else if (result.skippedEmails.length === 0) {diff --git a/apps/web/lib/messenger/support-email.ts b/apps/web/lib/messenger/support-email.tsindex d09b8219f..db10811ef 100644--- a/apps/web/lib/messenger/support-email.ts+++ b/apps/web/lib/messenger/support-email.ts@@ -105,7 +105,7 @@ export const sendMessengerSupportEmail = async ({return reserved;}- await sendEmail({+ const delivery = await sendEmail({email: SUPPORT_EMAIL_TO,subject: `Messenger support: ${normalizedSubject}`,react: MessengerSupportEmail({@@ -117,6 +117,9 @@ export const sendMessengerSupportEmail = async ({replyTo: user.email,fromOverride: SUPPORT_EMAIL_FROM,});+ if (delivery?.error) {+ throw new Error(`Support email was not sent: ${delivery.error.message}`);+ }return reserved;};