diff --git a/apps/backend/contacts/src/model/contact.model.ts b/apps/backend/contacts/src/model/contact.model.ts index 051f6c8d7..0ef3c266c 100644 --- a/apps/backend/contacts/src/model/contact.model.ts +++ b/apps/backend/contacts/src/model/contact.model.ts @@ -365,7 +365,10 @@ export namespace ContactModel { updatedAt: t.Date(), contacts: t.Array(groupContactItem), }), - total: t.Number(), + total: t.Number({ + description: + "Members matching search and status (every member when neither is set)", + }), subscribedContacts: t.Number({ description: "Members with subscribed status", }), diff --git a/apps/backend/contacts/src/routes/group/list-group-contacts/list-group-contacts.controllers.ts b/apps/backend/contacts/src/routes/group/list-group-contacts/list-group-contacts.controllers.ts index 7a12fe516..60a144850 100644 --- a/apps/backend/contacts/src/routes/group/list-group-contacts/list-group-contacts.controllers.ts +++ b/apps/backend/contacts/src/routes/group/list-group-contacts/list-group-contacts.controllers.ts @@ -5,6 +5,7 @@ import { } from "@be/contacts/error/contacts.error-response"; import type { ContactModel } from "@be/contacts/model/contact.model"; import type { GroupModel } from "@be/contacts/model/group.model"; +import { parseStatusFilter } from "@be/contacts/routes/contact/list-contacts/list-contacts.controllers"; import { db } from "@reloop/db/client"; import { afterCursor, @@ -14,9 +15,14 @@ import { } from "@reloop/db/pagination"; import * as schema from "@reloop/db/schema"; import { GROUP_LIST_WEBHOOK_EVENT } from "@reloop/webhook-events"; -import { and, eq, isNull, sql } from "drizzle-orm"; +import { and, eq, ilike, inArray, isNull, type SQL, sql } from "drizzle-orm"; import { useLogger } from "evlog/elysia"; +/** + * Contacts in a group, paginated in membership order. `search` (email) and + * `status` narrow the page and `total`; the subscribed/unsubscribed counts + * always cover the whole group, as in the main contacts list. + */ export const listGroupContactsController = async ({ organizationId, group_id, @@ -28,6 +34,8 @@ export const listGroupContactsController = async ({ page?: number; limit?: number; cursor?: string; + search?: string; + status?: string; }; }): Promise< | ContactModel.GroupContactListResponse @@ -51,6 +59,37 @@ export const listGroupContactsController = async ({ isNull(schema.contactGroup.deletedAt), ); + // search/status were accepted by the route schema but ignored, so + // filtering only ever covered the page the client had loaded. + const matchFilters: SQL[] = []; + const statuses = parseStatusFilter(query.status); + if (statuses.length > 0) { + matchFilters.push(inArray(schema.contact.status, statuses)); + } + if (query.search) { + const escapedSearch = query.search.replace(/[%_\\]/g, "\\$&"); + matchFilters.push(ilike(schema.contact.email, `%${escapedSearch}%`)); + } + const matchSql = matchFilters.length > 0 ? and(...matchFilters) : undefined; + const pageWhere = matchSql + ? and( + memberWhere, + inArray( + schema.contactGroup.contactId, + db + .select({ id: schema.contact.id }) + .from(schema.contact) + .where( + and( + eq(schema.contact.organizationId, organizationId), + isNull(schema.contact.deletedAt), + matchSql, + ), + ), + ), + ) + : memberWhere; + // Run group fetch and member status counts in parallel const [group, statusCountRows] = await Promise.all([ db.query.group.findFirst({ @@ -64,6 +103,9 @@ export const listGroupContactsController = async ({ .select({ status: schema.contact.status, count: sql`COUNT(*)`, + matching: matchSql + ? sql`COUNT(*) FILTER (WHERE ${matchSql})` + : sql`COUNT(*)`, }) .from(schema.contactGroup) .innerJoin( @@ -84,7 +126,7 @@ export const listGroupContactsController = async ({ let total = 0; for (const row of statusCountRows) { const count = Number(row.count ?? 0); - total += count; + total += Number(row.matching ?? 0); if (row.status === "subscribed") subscribedContacts = count; else if (row.status === "unsubscribed") unsubscribedContacts = count; } @@ -92,8 +134,8 @@ export const listGroupContactsController = async ({ // Fetch paginated contacts with properties via contactGroup relation const rows = await db.query.contactGroup.findMany({ where: position - ? and(memberWhere, afterCursor(schema.contactGroup, position, "asc")) - : memberWhere, + ? and(pageWhere, afterCursor(schema.contactGroup, position, "asc")) + : pageWhere, limit: limit + 1, offset, orderBy: cursorOrderBy(schema.contactGroup, "asc"), diff --git a/apps/frontend/dashboard/src/features/agent-inbox/components/mail-list/agent-inbox-content.tsx b/apps/frontend/dashboard/src/features/agent-inbox/components/mail-list/agent-inbox-content.tsx index 6c0e43acf..d6e4eaed4 100644 --- a/apps/frontend/dashboard/src/features/agent-inbox/components/mail-list/agent-inbox-content.tsx +++ b/apps/frontend/dashboard/src/features/agent-inbox/components/mail-list/agent-inbox-content.tsx @@ -39,6 +39,7 @@ import { ActionKbd } from "#/features/dashboard/keyboard-shortcuts-reveal"; const INBOX_VIEW_IDS = new Set(INBOX_VIEWS.map((view) => view.id)); +/** Reads the tab URL param, falling back to the all view for unknown values. */ function parseInboxView(value: string): InboxView { return INBOX_VIEW_IDS.has(value) ? (value as InboxView) : "all"; } @@ -75,6 +76,26 @@ const FOLDER_TITLES: Record = { needs_approval: "Needs approval", }; +// Empty-state copy per folder. The old fallback, "Choose an email to view +// details", read as if there were mail to pick. +const FOLDER_EMPTY_DESCRIPTIONS: Record = { + agent: "Threads your agent is handling will show up here.", + archive: "Archived conversations will show up here.", + archived: "Archived conversations will show up here.", + spam: "Mail marked as spam will show up here.", + trash: "Deleted conversations will show up here.", + drafts: "Drafts you save will show up here.", + starred: "Star a thread to keep it here.", + needs_approval: "Agent drafts that need your approval will show up here.", +}; + +/** Empty-state description for a folder that has no threads. */ +const folderEmptyDescription = (folder: string): string => + FOLDER_EMPTY_DESCRIPTIONS[folder] ?? + (folder.startsWith("label:") + ? "Threads with this label will show up here." + : "Nothing here yet."); + const isTypingTarget = (target: EventTarget | null) => { if (!(target instanceof HTMLElement)) return false; const tag = target.tagName; @@ -135,6 +156,7 @@ export const AgentInboxContent = ({ parseAsString.withDefault(""), ); const activeTab = parseInboxView(tabParam); + const hasListFilters = searchQuery !== "" || activeFilterCount > 0; const showInboxTabs = folder === "inbox"; const folderTitle = folder.startsWith("label:") @@ -730,7 +752,9 @@ export const AgentInboxContent = ({ ) : (listLoading || isLoadingMailboxes) && filteredThreads.length === 0 ? ( - ) : filteredThreads.length === 0 && !threadsError ? ( + ) : filteredThreads.length === 0 && !threadsError && !hasListFilters ? ( + // Folder or tab is empty. When search or filters hide every + // thread, ThreadList shows its no-matches state with clear filters.
@@ -760,7 +784,7 @@ export const AgentInboxContent = ({ selectedId={selectedThreadId} onSelect={handleSelectThread} isLoading={listLoading} - hasFilters={searchQuery !== "" || activeFilterCount > 0} + hasFilters={hasListFilters} onClearFilters={() => { setSearchQuery(null); setFilterParam(null); diff --git a/apps/frontend/dashboard/src/features/api-keys/modals/delete-api-key-modal.tsx b/apps/frontend/dashboard/src/features/api-keys/modals/delete-api-key-modal.tsx index b4ae2cab6..868790160 100644 --- a/apps/frontend/dashboard/src/features/api-keys/modals/delete-api-key-modal.tsx +++ b/apps/frontend/dashboard/src/features/api-keys/modals/delete-api-key-modal.tsx @@ -252,7 +252,7 @@ export function DeleteApiKeyModal({ {isBulk - ? `Delete ${bulkKeysToDelete.length || "selected"} API keys` + ? `Delete ${bulkKeysToDelete.length || "selected"} ${bulkKeysToDelete.length === 1 ? "API key" : "API keys"}` : "Delete API key"}
diff --git a/apps/frontend/dashboard/src/features/campaigns/campaigns-provider.tsx b/apps/frontend/dashboard/src/features/campaigns/campaigns-provider.tsx index 56f625e40..35a5864f8 100644 --- a/apps/frontend/dashboard/src/features/campaigns/campaigns-provider.tsx +++ b/apps/frontend/dashboard/src/features/campaigns/campaigns-provider.tsx @@ -225,11 +225,30 @@ export function useCampaigns() { return context; } -/** Returns a function that invalidates every cached campaign query. */ -export function useInvalidateCampaigns() { +/** + * Returns a function that invalidates every cached campaign query. Pass + * `exceptId` after deleting a campaign so its own detail and recipients + * queries aren't refetched (they would 404 on the open detail page). + */ +export function useInvalidateCampaigns(): (exceptId?: string) => Promise { const queryClient = useQueryClient(); - return () => - queryClient.invalidateQueries({ queryKey: queryKeys.campaigns.all }); + return (exceptId?: string) => + queryClient.invalidateQueries({ + queryKey: queryKeys.campaigns.all, + predicate: exceptId + ? (query) => !query.queryKey.includes(exceptId) + : undefined, + }); +} + +/** Drops every cached query for a deleted campaign. */ +export function useForgetCampaign(): (id: string) => void { + const queryClient = useQueryClient(); + return (id: string) => + queryClient.removeQueries({ + queryKey: queryKeys.campaigns.all, + predicate: (query) => query.queryKey.includes(id), + }); } /** Loads one campaign by id, using the cached list row as placeholder data. */ diff --git a/apps/frontend/dashboard/src/features/campaigns/components/delete-campaign.tsx b/apps/frontend/dashboard/src/features/campaigns/components/delete-campaign.tsx index c8f15b0a4..b733cf1f9 100644 --- a/apps/frontend/dashboard/src/features/campaigns/components/delete-campaign.tsx +++ b/apps/frontend/dashboard/src/features/campaigns/components/delete-campaign.tsx @@ -19,12 +19,16 @@ import { } from "#/features/dashboard/keyboard-shortcuts-reveal"; import type { Campaign } from "../campaign-types"; import { deleteCampaignRequest } from "../campaigns-api"; -import { useInvalidateCampaigns } from "../campaigns-provider"; +import { + useForgetCampaign, + useInvalidateCampaigns, +} from "../campaigns-provider"; const actionKbdOnButtonClassName = actionKbdOnSolidClassName; type DeleteState = "idle" | "deleting" | "success"; +/** Confirms and deletes one or more campaigns, leaving the detail page first when deleting from it. */ export function DeleteCampaignModal({ campaigns, selectedCampaigns = [], @@ -43,6 +47,7 @@ export function DeleteCampaignModal({ const pathname = usePathname(); const router = useRouter(); const invalidate = useInvalidateCampaigns(); + const forgetCampaign = useForgetCampaign(); const isBulk = deleteId === "bulk" || deleteId === "selected"; @@ -144,9 +149,12 @@ export function DeleteCampaignModal({ try { setDeleteState("deleting"); const deletedName = campaignToDelete.name; - await deleteCampaignRequest(campaignToDelete.id); + const deletedId = campaignToDelete.id; + await deleteCampaignRequest(deletedId); setDeleteState("success"); - await invalidate(); + // Don't refetch the deleted campaign: on its detail page that 404s + // and the error state replaced the page before the redirect. + await invalidate(deletedId); setTimeout(() => { void setDeleteId(null); @@ -154,7 +162,12 @@ export function DeleteCampaignModal({ if (isOnDetailPage) { setTimeout(() => { router.push("/campaigns"); + // Drop the cached item once the detail page has unmounted; + // removing an active query makes it refetch and 404. + setTimeout(() => forgetCampaign(deletedId), 1000); }, 100); + } else { + forgetCampaign(deletedId); } setTimeout(() => { setDeleteState("idle"); @@ -227,7 +240,7 @@ export function DeleteCampaignModal({
{isBulk - ? `Delete ${bulkCampaignsToDelete.length || "selected"} campaigns` + ? `Delete ${bulkCampaignsToDelete.length || "selected"} ${bulkCampaignsToDelete.length === 1 ? "campaign" : "campaigns"}` : "Delete campaign"} diff --git a/apps/frontend/dashboard/src/features/contacts/components/contacts/contact-table.tsx b/apps/frontend/dashboard/src/features/contacts/components/contacts/contact-table.tsx index bea6122a3..a18d054a4 100644 --- a/apps/frontend/dashboard/src/features/contacts/components/contacts/contact-table.tsx +++ b/apps/frontend/dashboard/src/features/contacts/components/contacts/contact-table.tsx @@ -35,6 +35,8 @@ interface ContactTableProps { onAddContact?: () => void; searchQuery?: string; onClearSearch?: () => void; + /** Passed to the empty state when filters aren't in the contacts list URL. */ + isFiltered?: boolean; emptyStateTitle?: string; emptyStateDescription?: string; emptyStateButtonText?: string; @@ -55,6 +57,7 @@ export const ContactTable = ({ onAddContact, searchQuery, onClearSearch, + isFiltered, emptyStateTitle, emptyStateDescription, emptyStateButtonText, @@ -193,6 +196,7 @@ export const ContactTable = ({ onAddContact={onAddContact} searchQuery={searchQuery} onClearSearch={onClearSearch} + isFiltered={isFiltered} title={emptyStateTitle} description={emptyStateDescription} buttonText={emptyStateButtonText} diff --git a/apps/frontend/dashboard/src/features/contacts/components/contacts/contacts-empty-state.tsx b/apps/frontend/dashboard/src/features/contacts/components/contacts/contacts-empty-state.tsx index 67a1b685b..de8ceff2b 100644 --- a/apps/frontend/dashboard/src/features/contacts/components/contacts/contacts-empty-state.tsx +++ b/apps/frontend/dashboard/src/features/contacts/components/contacts/contacts-empty-state.tsx @@ -23,8 +23,14 @@ interface ContactsEmptyStateProps { buttonText?: string; /** Override the default single-key ActionKbd (e.g. sequence "A" "C"). */ shortcut?: ReactNode; + /** + * Whether a filter is active. Defaults to the contacts list URL filters; + * pass it when filters live elsewhere (e.g. local state on a group page). + */ + isFiltered?: boolean; } +/** Empty state for a contacts table: a no-matches message when filtered, otherwise an add-contact prompt. */ export function ContactsEmptyState({ onAddContact, searchQuery = "", @@ -33,6 +39,7 @@ export function ContactsEmptyState({ description, buttonText, shortcut, + isFiltered: isFilteredProp, }: ContactsEmptyStateProps) { const router = useRouter(); const [statusFilter, setStatusFilter] = useQueryState( @@ -53,9 +60,10 @@ export function ContactsEmptyState({ ); const isFiltered = - searchQuery.trim() !== "" || - statusFilter.length > 0 || - channelId.trim() !== ""; + isFilteredProp ?? + (searchQuery.trim() !== "" || + statusFilter.length > 0 || + channelId.trim() !== ""); const handleClearFilters = () => { void setStatusFilter([]); diff --git a/apps/frontend/dashboard/src/features/contacts/components/contacts/delete-contact-confirm-modal.tsx b/apps/frontend/dashboard/src/features/contacts/components/contacts/delete-contact-confirm-modal.tsx index c56c96675..dec4796ab 100644 --- a/apps/frontend/dashboard/src/features/contacts/components/contacts/delete-contact-confirm-modal.tsx +++ b/apps/frontend/dashboard/src/features/contacts/components/contacts/delete-contact-confirm-modal.tsx @@ -33,6 +33,7 @@ const actionKbdOnButtonClassName = actionKbdOnSolidClassName; type DeleteState = "idle" | "deleting" | "success"; +/** Confirms and deletes one or more contacts. */ export function DeleteContactConfirmModal({ contacts, selectedContacts = [], @@ -195,7 +196,7 @@ export function DeleteContactConfirmModal({ if (!open) { if (deleteStateRef.current === "success") { const name = isBulk - ? `${targetBulkContactsRef.current.length || bulkContactsToDelete.length} contacts` + ? `${targetBulkContactsRef.current.length || bulkContactsToDelete.length} contact${(targetBulkContactsRef.current.length || bulkContactsToDelete.length) === 1 ? "" : "s"}` : targetContactRef.current?.email || "Unnamed contact"; onDeleteSuccess?.(name); if (isBulk) onClearSelection?.(); @@ -223,7 +224,7 @@ export function DeleteContactConfirmModal({
{isBulk - ? `Delete ${bulkContactsToDelete.length || "selected"} contacts` + ? `Delete ${bulkContactsToDelete.length || "selected"} ${bulkContactsToDelete.length === 1 ? "contact" : "contacts"}` : "Delete contact"} diff --git a/apps/frontend/dashboard/src/features/contacts/components/groups/delete-group-confirm-modal.tsx b/apps/frontend/dashboard/src/features/contacts/components/groups/delete-group-confirm-modal.tsx index f39a1dcd4..158f42a91 100644 --- a/apps/frontend/dashboard/src/features/contacts/components/groups/delete-group-confirm-modal.tsx +++ b/apps/frontend/dashboard/src/features/contacts/components/groups/delete-group-confirm-modal.tsx @@ -27,6 +27,7 @@ const actionKbdOnButtonClassName = actionKbdOnSolidClassName; type DeleteState = "idle" | "deleting" | "success"; +/** Confirms and deletes one or more contact groups. */ export function DeleteGroupConfirmModal({ groups, selectedGroups = [], @@ -180,7 +181,7 @@ export function DeleteGroupConfirmModal({ if (!open) { if (deleteStateRef.current === "success") { const name = isBulk - ? `${targetBulkGroupsRef.current.length || bulkGroupsToDelete.length} groups` + ? `${targetBulkGroupsRef.current.length || bulkGroupsToDelete.length} group${(targetBulkGroupsRef.current.length || bulkGroupsToDelete.length) === 1 ? "" : "s"}` : targetGroupRef.current?.name || "Unnamed group"; onDeleteSuccess?.(name); if (isBulk) onClearSelection?.(); @@ -206,7 +207,7 @@ export function DeleteGroupConfirmModal({
{isBulk - ? `Delete ${bulkGroupsToDelete.length || "selected"} groups` + ? `Delete ${bulkGroupsToDelete.length || "selected"} ${bulkGroupsToDelete.length === 1 ? "group" : "groups"}` : "Delete group"} diff --git a/apps/frontend/dashboard/src/features/contacts/components/properties/delete-property-confirm-modal.tsx b/apps/frontend/dashboard/src/features/contacts/components/properties/delete-property-confirm-modal.tsx index 65420c05e..063e9cbdb 100644 --- a/apps/frontend/dashboard/src/features/contacts/components/properties/delete-property-confirm-modal.tsx +++ b/apps/frontend/dashboard/src/features/contacts/components/properties/delete-property-confirm-modal.tsx @@ -39,6 +39,7 @@ const getBadgeColor = (type: string) => { } }; +/** Confirms and deletes one or more contact properties. */ export function DeletePropertyConfirmModal({ properties, selectedProperties = [], @@ -225,7 +226,7 @@ export function DeletePropertyConfirmModal({
{isBulk - ? `Delete ${bulkPropertiesToDelete.length || "selected"} properties` + ? `Delete ${bulkPropertiesToDelete.length || "selected"} ${bulkPropertiesToDelete.length === 1 ? "property" : "properties"}` : "Delete property"} diff --git a/apps/frontend/dashboard/src/features/contacts/group-detail/group-contact-list.tsx b/apps/frontend/dashboard/src/features/contacts/group-detail/group-contact-list.tsx index 6023fa183..a4cf5defe 100644 --- a/apps/frontend/dashboard/src/features/contacts/group-detail/group-contact-list.tsx +++ b/apps/frontend/dashboard/src/features/contacts/group-detail/group-contact-list.tsx @@ -2,7 +2,7 @@ import * as Button from "@reloop/ui/button"; import { Icon } from "@reloop/ui/icon"; import * as Input from "@reloop/ui/input"; import { parseAsInteger, useQueryState } from "nuqs"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { ContactExportModal } from "#/features/contacts/components/contacts/contact-export-modal"; import { ContactFilterDropdown, @@ -15,6 +15,9 @@ import { actionKbdOnSolidClassName, } from "#/features/dashboard/keyboard-shortcuts-reveal"; +const SEARCH_DEBOUNCE_MS = 250; + +/** Members of one contact group, with server-side search, status filter, pagination and export. */ export const GroupContactList = ({ groupId }: { groupId: string }) => { const [currentPage, setCurrentPage] = useQueryState( "page", @@ -24,6 +27,16 @@ export const GroupContactList = ({ groupId }: { groupId: string }) => { const [modal, setModal] = useQueryState("modal", { history: "replace" }); const [statusFilter, setStatusFilter] = useState(null); const [searchQuery, setSearchQuery] = useState(""); + // The input updates searchQuery on every keystroke; the request and the + // filtered state follow the debounced value so the shown rows match them. + const [debouncedSearch, setDebouncedSearch] = useState(""); + useEffect(() => { + const timer = setTimeout( + () => setDebouncedSearch(searchQuery.trim()), + SEARCH_DEBOUNCE_MS, + ); + return () => clearTimeout(timer); + }, [searchQuery]); const exportOpen = modal === "export-contacts"; const setExportOpen = (open: boolean) => void setModal(open ? "export-contacts" : null); @@ -36,19 +49,27 @@ export const GroupContactList = ({ groupId }: { groupId: string }) => { groupId, page: currentPage ?? 1, limit: pageSize ?? 10, + // Filter on the server: filtering the loaded page in the browser missed + // members on other pages and showed the group as empty. + search: debouncedSearch || undefined, + status: statusFilter ?? undefined, }); - const filteredContacts = - data?.group?.contacts?.filter((contact) => { - const matchesStatus = - statusFilter === null || contact.status === statusFilter; - const matchesSearch = - searchQuery === "" || - contact.email.toLowerCase().includes(searchQuery.toLowerCase()); - return matchesStatus && matchesSearch; - }) || []; - - const hasContacts = !!data?.group?.contacts && data.group.contacts.length > 0; + const contacts = data?.group?.contacts ?? []; + const isFiltered = debouncedSearch !== "" || statusFilter !== null; + // total is the filtered count, so with a filter fall back to the + // whole-group status counts; export stays available while a filter + // matches nothing. + const hasContacts = + contacts.length > 0 || + (!isFiltered && (data?.total ?? 0) > 0) || + (data?.subscribedContacts ?? 0) + (data?.unsubscribedContacts ?? 0) > 0; + const clearFilters = () => { + setSearchQuery(""); + setDebouncedSearch(""); + setStatusFilter(null); + void setCurrentPage(1); + }; if (error) { return ( @@ -82,7 +103,10 @@ export const GroupContactList = ({ groupId }: { groupId: string }) => { { + setStatusFilter(value); + void setCurrentPage(1); + }} /> {
{ groupName={data?.group?.name} onAddContact={() => void setModal("add-contact-to-group")} searchQuery={searchQuery} - onClearSearch={() => setSearchQuery("")} - emptyStateTitle="No contacts in this group" - emptyStateDescription="This group doesn't have any contacts yet. Add contacts to start segmenting your audience." + onClearSearch={clearFilters} + isFiltered={isFiltered} + emptyStateTitle={isFiltered ? undefined : "No contacts in this group"} + emptyStateDescription={ + isFiltered + ? undefined + : "This group doesn't have any contacts yet. Add contacts to start segmenting your audience." + } emptyStateButtonText="Add contact to group" emptyStateShortcut={ @@ -123,7 +152,7 @@ export const GroupContactList = ({ groupId }: { groupId: string }) => { scope={{ groupId, groupName: data?.group?.name, - search: searchQuery || undefined, + search: debouncedSearch || undefined, }} counts={{ total: data?.total ?? 0, diff --git a/apps/frontend/dashboard/src/features/contacts/hooks/use-contacts-query.ts b/apps/frontend/dashboard/src/features/contacts/hooks/use-contacts-query.ts index a80fb0a5f..e5c3bdfe1 100644 --- a/apps/frontend/dashboard/src/features/contacts/hooks/use-contacts-query.ts +++ b/apps/frontend/dashboard/src/features/contacts/hooks/use-contacts-query.ts @@ -74,6 +74,7 @@ async function fetchContacts( return res.json() as Promise; } +/** Fetches one contact by id. */ export async function fetchContact(id: string): Promise { const res = await fetch(`/api/contacts/retrieve/${id}`, { credentials: "include", @@ -82,6 +83,7 @@ export async function fetchContact(id: string): Promise { return res.json() as Promise; } +/** Paginated contacts list for the current filters. */ export function useContactsQuery(params: ContactsListParams) { return useQuery({ queryKey: queryKeys.contacts.list(params), @@ -100,6 +102,7 @@ export type SubscriptionActivityResponse = { event: string; }; +/** Subscribe and unsubscribe activity over the last given number of days. */ export function useSubscriptionActivityQuery(days = 7, enabled = true) { return useQuery({ queryKey: queryKeys.contacts.subscriptionActivity(days), @@ -118,6 +121,7 @@ export function useSubscriptionActivityQuery(days = 7, enabled = true) { }); } +/** One contact by id; disabled until an id is set. */ export function useContactQuery(id: string | null | undefined) { return useQuery({ queryKey: queryKeys.contacts.detail(id ?? ""), @@ -126,6 +130,7 @@ export function useContactQuery(id: string | null | undefined) { }); } +/** Returns a function that invalidates every contacts query. */ export function useInvalidateContacts() { const queryClient = useQueryClient(); return () => @@ -240,6 +245,7 @@ export type GroupDetail = { createdBy?: GroupCreatedBy; }; +/** Fetches one contact group by id. */ export async function fetchGroup(id: string): Promise { const res = await fetch(`/api/contacts/v1/groups/${id}`, { credentials: "include", @@ -248,6 +254,7 @@ export async function fetchGroup(id: string): Promise { return res.json() as Promise; } +/** One contact group by id; disabled until an id is set. */ export function useGroupQuery(id: string | null | undefined) { return useQuery({ queryKey: queryKeys.contacts.groupDetail(id ?? ""), @@ -268,23 +275,33 @@ export type GroupContactsResponse = { limit: number; }; +/** One page of a group's contacts, filtered server-side by email search and status. */ export function useGroupContactsQuery(params: { groupId: string; page: number; limit: number; + search?: string; + status?: string; enabled?: boolean; }) { + const { enabled, ...keyParams } = params; return useQuery({ - queryKey: queryKeys.contacts.groupContacts(params), + queryKey: queryKeys.contacts.groupContacts(keyParams), queryFn: async () => { + const search = new URLSearchParams({ + limit: String(params.limit), + page: String(params.page), + }); + if (params.search) search.set("search", params.search); + if (params.status) search.set("status", params.status); const res = await fetch( - `/api/contacts/v1/groups/${params.groupId}/contacts?limit=${params.limit}&page=${params.page}`, + `/api/contacts/v1/groups/${params.groupId}/contacts?${search.toString()}`, { credentials: "include" }, ); if (!res.ok) throw new Error("Failed to load group contacts"); return res.json() as Promise; }, - enabled: params.enabled !== false && !!params.groupId, + enabled: enabled !== false && !!params.groupId, placeholderData: (prev) => prev, }); } @@ -295,6 +312,7 @@ export type GroupContactStats = { unsubscribedContacts: number; }; +/** Member count for one contact group. */ export function useGroupContactsCountQuery(groupId: string | null | undefined) { return useQuery({ queryKey: queryKeys.contacts.groupCount(groupId ?? ""), @@ -317,6 +335,7 @@ export function useGroupContactsCountQuery(groupId: string | null | undefined) { }); } +/** First 100 contact properties, for pickers and filters. */ export function useAllPropertiesQuery(enabled = true) { return useQuery({ queryKey: queryKeys.contacts.propertiesAll(), @@ -348,6 +367,7 @@ export type GroupListResponse = { limit: number; }; +/** Paginated contact groups list. */ export function useGroupsQuery(params: { page: number; limit: number; @@ -392,6 +412,7 @@ export type PropertyListResponse = { limit: number; }; +/** Paginated contact properties list. */ export function usePropertiesQuery(params: { page: number; limit: number; @@ -440,6 +461,7 @@ export type ChannelListResponse = { limit: number; }; +/** First 100 subscription channels for the organization. */ export function useChannelsQuery(enabled = true) { return useQuery({ queryKey: queryKeys.contacts.channels(), diff --git a/apps/frontend/dashboard/src/features/domain/components/delete-domain.tsx b/apps/frontend/dashboard/src/features/domain/components/delete-domain.tsx index fb3cd89f1..637daedbc 100644 --- a/apps/frontend/dashboard/src/features/domain/components/delete-domain.tsx +++ b/apps/frontend/dashboard/src/features/domain/components/delete-domain.tsx @@ -18,7 +18,10 @@ import { ActionKbd, actionKbdOnSolidClassName, } from "#/features/dashboard/keyboard-shortcuts-reveal"; -import { useInvalidateDomains } from "../hooks/use-domains-query"; +import { + useForgetDomain, + useInvalidateDomains, +} from "../hooks/use-domains-query"; import type { Domain } from "../types"; /** Light keycap so it reads on the red/destructive FancyButton fill. */ @@ -26,6 +29,7 @@ const actionKbdOnButtonClassName = actionKbdOnSolidClassName; type DeleteState = "idle" | "deleting" | "success"; +/** Confirms and deletes one or more domains, leaving the detail page first when deleting from it. */ export function DeleteDomainModal({ domains, selectedDomains = [], @@ -46,6 +50,7 @@ export function DeleteDomainModal({ const pathname = usePathname(); const router = useRouter(); const invalidate = useInvalidateDomains(); + const forgetDomain = useForgetDomain(); const isBulk = deleteId === "bulk" || deleteId === "selected"; @@ -147,11 +152,14 @@ export function DeleteDomainModal({ try { setDeleteState("deleting"); const deletedName = domainToDelete.domain; - await axios.delete(`/api/domain/v1/${domainToDelete.id}`, { + const deletedId = domainToDelete.id; + await axios.delete(`/api/domain/v1/${deletedId}`, { withCredentials: true, }); setDeleteState("success"); - await invalidate(); + // Don't refetch the deleted domain: on its detail page that 404s and + // the not-found state replaced the page before the redirect. + await invalidate(deletedId); setTimeout(() => { onDeleteSuccess?.(deletedName); @@ -159,7 +167,12 @@ export function DeleteDomainModal({ if (isOnDetailPage) { setTimeout(() => { router.push("/domain"); + // Drop the cached item once the detail page has unmounted; + // removing an active query makes it refetch and 404. + setTimeout(() => forgetDomain(deletedId), 1000); }, 100); + } else { + forgetDomain(deletedId); } setTimeout(() => { setDeleteState("idle"); @@ -244,7 +257,7 @@ export function DeleteDomainModal({
{isBulk - ? `Delete ${bulkDomainsToDelete.length || "selected"} domains` + ? `Delete ${bulkDomainsToDelete.length || "selected"} ${bulkDomainsToDelete.length === 1 ? "domain" : "domains"}` : "Delete domain"} diff --git a/apps/frontend/dashboard/src/features/domain/hooks/use-domains-query.ts b/apps/frontend/dashboard/src/features/domain/hooks/use-domains-query.ts index ad38fd296..a5c2184d7 100644 --- a/apps/frontend/dashboard/src/features/domain/hooks/use-domains-query.ts +++ b/apps/frontend/dashboard/src/features/domain/hooks/use-domains-query.ts @@ -101,9 +101,28 @@ export function useDomainNameserversQuery( }); } -/** Returns a function that invalidates every cached domain query. */ -export function useInvalidateDomains() { +/** + * Returns a function that invalidates every cached domain query. Pass + * `exceptId` after deleting a domain so its own detail queries aren't + * refetched (they would 404 on the open detail page). + */ +export function useInvalidateDomains(): (exceptId?: string) => Promise { const queryClient = useQueryClient(); - return () => - queryClient.invalidateQueries({ queryKey: queryKeys.domain.all }); + return (exceptId?: string) => + queryClient.invalidateQueries({ + queryKey: queryKeys.domain.all, + predicate: exceptId + ? (query) => !query.queryKey.includes(exceptId) + : undefined, + }); +} + +/** Drops every cached query for a deleted domain. */ +export function useForgetDomain(): (id: string) => void { + const queryClient = useQueryClient(); + return (id: string) => + queryClient.removeQueries({ + queryKey: queryKeys.domain.all, + predicate: (query) => query.queryKey.includes(id), + }); } diff --git a/apps/frontend/dashboard/src/features/emails/components/email-list-error.tsx b/apps/frontend/dashboard/src/features/emails/components/email-list-error.tsx new file mode 100644 index 000000000..89cfa28aa --- /dev/null +++ b/apps/frontend/dashboard/src/features/emails/components/email-list-error.tsx @@ -0,0 +1,28 @@ +import { Icon } from "@reloop/ui/icon"; +import type { ReactElement } from "react"; + +/** + * Error state shown in place of an email table. The toolbar stays above it, + * so the user can change filters or search, or retry the request. + */ +export function EmailListError({ + message, + onRetry, +}: { + message: string; + onRetry: () => void; +}): ReactElement { + return ( +
+ +

{message}

+ +
+ ); +} diff --git a/apps/frontend/dashboard/src/features/emails/components/email-list.tsx b/apps/frontend/dashboard/src/features/emails/components/email-list.tsx index 65a8ca6ad..a3479d220 100644 --- a/apps/frontend/dashboard/src/features/emails/components/email-list.tsx +++ b/apps/frontend/dashboard/src/features/emails/components/email-list.tsx @@ -19,6 +19,7 @@ import { import { queryKeys } from "#/lib/query-keys"; import { ApiKeySelector } from "./api-key-selector"; import { DomainSelector } from "./domain-selector"; +import { EmailListError } from "./email-list-error"; import { RefreshButton } from "./email-refresh-button"; import { EmailTable } from "./email-table"; import { StatusSelector } from "./status-selector"; @@ -159,17 +160,6 @@ export function EmailList() { { enableOnFormTags: false, preventDefault: true }, ); - if (error) { - return ( -
- -

- Failed to load email logs -

-
- ); - } - return (
@@ -286,22 +276,30 @@ export function EmailList() {
- void setCurrentPage(page)} - onPageSizeChange={(value) => { - void setPageSize(value); - void setCurrentPage(1); - }} - hasFilters={hasAnyFilter} - onClearFilters={handleClearAll} - variant="sent" - /> + {/* Keep the toolbar on errors so filters and search can be changed. */} + {error ? ( + + ) : ( + void setCurrentPage(page)} + onPageSizeChange={(value) => { + void setPageSize(value); + void setCurrentPage(1); + }} + hasFilters={hasAnyFilter} + onClearFilters={handleClearAll} + variant="sent" + /> + )}
); diff --git a/apps/frontend/dashboard/src/features/emails/components/received-email-list.tsx b/apps/frontend/dashboard/src/features/emails/components/received-email-list.tsx index b3254525b..44c608318 100644 --- a/apps/frontend/dashboard/src/features/emails/components/received-email-list.tsx +++ b/apps/frontend/dashboard/src/features/emails/components/received-email-list.tsx @@ -12,6 +12,7 @@ import { ActionKbd } from "#/features/dashboard/keyboard-shortcuts-reveal"; import { useActiveOrganization } from "#/features/dashboard/page-header/use-active-organization"; import { useReceivedEmailsQuery } from "#/features/emails/hooks/use-emails-query"; import { queryKeys } from "#/lib/query-keys"; +import { EmailListError } from "./email-list-error"; import { RefreshButton } from "./email-refresh-button"; import { InboundStatusSelector } from "./inbound-status-selector"; import { MailboxSelector } from "./mailbox-selector"; @@ -19,6 +20,7 @@ import { ReceivedEmailTable } from "./received-email-table"; const SEARCH_INPUT_ID = "received-emails-search-input"; +/** Received emails table with filters, search and pagination. */ export function ReceivedEmailList() { const { activeOrganization } = useActiveOrganization(); const queryClient = useQueryClient(); @@ -121,17 +123,6 @@ export function ReceivedEmailList() { { enableOnFormTags: false, preventDefault: true }, ); - if (error) { - return ( -
- -

- Failed to load received emails -

-
- ); - } - return (
@@ -233,21 +224,29 @@ export function ReceivedEmailList() {
- void setCurrentPage(page)} - onPageSizeChange={(value) => { - void setPageSize(value); - void setCurrentPage(1); - }} - hasFilters={hasAnyFilter} - onClearFilters={handleClearAll} - /> + {/* Keep the toolbar on errors so filters and search can be changed. */} + {error ? ( + + ) : ( + void setCurrentPage(page)} + onPageSizeChange={(value) => { + void setPageSize(value); + void setCurrentPage(1); + }} + hasFilters={hasAnyFilter} + onClearFilters={handleClearAll} + /> + )}
); diff --git a/apps/frontend/dashboard/src/features/home/components/recent-emails-card.tsx b/apps/frontend/dashboard/src/features/home/components/recent-emails-card.tsx index 6316ec77e..d453e6d72 100644 --- a/apps/frontend/dashboard/src/features/home/components/recent-emails-card.tsx +++ b/apps/frontend/dashboard/src/features/home/components/recent-emails-card.tsx @@ -19,6 +19,7 @@ const getEmailIconColorClass = (status: string) => ? "text-information-base" : emailStatusTone(status).text; +/** Home card listing the latest sent emails, or a first-send prompt when there are none. */ export function RecentEmailsCard({ enabled, canSendFirstEmail, @@ -128,7 +129,9 @@ export function RecentEmailsCard({

{readyDomainName ? `${readyDomainName} is ready. One click sends a test email from hello@${readyDomainName}.` - : "One click sends a test email to you from your verified domain."} + : canSendFirstEmail + ? "One click sends a test email to you from your verified domain." + : "Add and verify a domain to send your first email."}

{canSendFirstEmail ? (
diff --git a/apps/frontend/dashboard/src/features/settings/teams/team-list.tsx b/apps/frontend/dashboard/src/features/settings/teams/team-list.tsx index 4b7720c22..2d9d59ce9 100644 --- a/apps/frontend/dashboard/src/features/settings/teams/team-list.tsx +++ b/apps/frontend/dashboard/src/features/settings/teams/team-list.tsx @@ -138,6 +138,7 @@ import { RemoveMemberModal } from "./remove-member-modal"; import { RevokeInviteModal } from "./revoke-invite-modal"; import type { TeamFilterValue } from "./team-filter-dropdown"; +/** Members and pending invitations of the active organization, with an error state and retry. */ export function TeamList({ searchQuery, filters = "all", @@ -161,29 +162,40 @@ export function TeamList({ const orgId = activeOrganization?.id; - const { data: membersData, isPending: membersLoading } = useQuery({ + // The auth client returns { data, error } instead of throwing. Throw on + // error so a failed load shows an error state, not an empty team (API + // error) or a skeleton that never ends (network error). + const membersQuery = useQuery({ queryKey: queryKeys.organization.members(orgId ?? ""), queryFn: async (): Promise<{ members: Member[] }> => { if (!orgId) return { members: [] }; const result = await authClient.organization.listMembers({ query: { organizationId: orgId }, }); + if (result.error) { + throw new Error(result.error.message || "Failed to load members"); + } return (result.data as { members: Member[] }) ?? { members: [] }; }, enabled: !!orgId, }); + const { data: membersData, isPending: membersLoading } = membersQuery; - const { data: invites, isPending: invitesLoading } = useQuery({ + const invitesQuery = useQuery({ queryKey: queryKeys.organization.invitations(orgId ?? ""), queryFn: async (): Promise => { if (!orgId) return []; const result = await authClient.organization.listInvitations({ query: { organizationId: orgId }, }); + if (result.error) { + throw new Error(result.error.message || "Failed to load invitations"); + } return (result.data as Invite[]) ?? []; }, enabled: !!orgId, }); + const { data: invites, isPending: invitesLoading } = invitesQuery; const invalidateMembers = () => queryClient.invalidateQueries({ @@ -424,6 +436,34 @@ export function TeamList({ await handleCancelInvite(inviteToRevoke.id); }; + const loadError = membersQuery.error ?? invitesQuery.error; + if (loadError && (!membersData || !invites)) { + return ( + + +
+ +

+ Couldn't load your team +

+

+ {loadError.message} +

+ +
+
+ ); + } + const isLoading = membersLoading || invitesLoading || !membersData; if (isLoading) { diff --git a/apps/frontend/dashboard/src/features/workflows/components/delete-workflow-modal.tsx b/apps/frontend/dashboard/src/features/workflows/components/delete-workflow-modal.tsx index b14ee6215..7b9892ebe 100644 --- a/apps/frontend/dashboard/src/features/workflows/components/delete-workflow-modal.tsx +++ b/apps/frontend/dashboard/src/features/workflows/components/delete-workflow-modal.tsx @@ -26,6 +26,7 @@ const actionKbdOnButtonClassName = actionKbdOnSolidClassName; type DeleteState = "idle" | "deleting" | "success"; +/** Confirms and deletes one or more automations. */ export function DeleteWorkflowModal({ workflows, selectedWorkflows = [], @@ -223,7 +224,7 @@ export function DeleteWorkflowModal({
{isBulk - ? `Delete ${bulkWorkflowsToDelete.length || "selected"} automations` + ? `Delete ${bulkWorkflowsToDelete.length || "selected"} ${bulkWorkflowsToDelete.length === 1 ? "automation" : "automations"}` : "Delete automation"} diff --git a/apps/frontend/dashboard/src/lib/query-keys.ts b/apps/frontend/dashboard/src/lib/query-keys.ts index dcbc9cd5b..28c3194ce 100644 --- a/apps/frontend/dashboard/src/lib/query-keys.ts +++ b/apps/frontend/dashboard/src/lib/query-keys.ts @@ -78,8 +78,13 @@ export const queryKeys = { [...queryKeys.contacts.all, "groups", params] as const, groupDetail: (id: string) => [...queryKeys.contacts.all, "group-detail", id] as const, - groupContacts: (params: { groupId: string; page: number; limit: number }) => - [...queryKeys.contacts.all, "group-contacts", params] as const, + groupContacts: (params: { + groupId: string; + page: number; + limit: number; + search?: string; + status?: string; + }) => [...queryKeys.contacts.all, "group-contacts", params] as const, groupCount: (groupId: string) => [...queryKeys.contacts.all, "group-count", groupId] as const, properties: (params: {