Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -0,0 +1,258 @@
|
||||
import {
|
||||
adminLeadAdvancedMutationFormSchema,
|
||||
adminLeadMutationFormSchema,
|
||||
buildAdminLeadDetailVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { PlatformLeadAdminError } from "@hivegrid/db/platform-leads-admin.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect, useActionData, useLoaderData, useNavigate, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminPlatformLeadDetailPage } from "~/components/screens/admin/leads/AdminPlatformLeadDetailPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
assertPlatformLeadVisibleToOperator,
|
||||
listPlatformLeadAssignees,
|
||||
platformLeadNotFound,
|
||||
requirePlatformLeadWrite,
|
||||
runAsPlatformLeadOperator,
|
||||
} from "~/services/admin/platform-leads.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = { readonly error: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const leadId = params.id?.trim();
|
||||
if (!leadId) throw platformLeadNotFound();
|
||||
|
||||
const data = await runAsPlatformLeadOperator(request, async ({ access, service }) => {
|
||||
const [lead, assignees] = await Promise.all([service.getLead({ leadId }), listPlatformLeadAssignees()]);
|
||||
if (!lead) throw platformLeadNotFound();
|
||||
assertPlatformLeadVisibleToOperator(lead, access);
|
||||
const assigneeLabels = new Map(assignees.map((option) => [option.id, option.label]));
|
||||
return {
|
||||
vm: buildAdminLeadDetailVM({
|
||||
lead: {
|
||||
id: lead.id,
|
||||
firstName: lead.firstName,
|
||||
lastName: lead.lastName,
|
||||
email: lead.email,
|
||||
phone: lead.phone,
|
||||
company: lead.company,
|
||||
message: lead.message,
|
||||
status: lead.status,
|
||||
sourceId: lead.source.id,
|
||||
sourceDisplayName: lead.source.displayName,
|
||||
sourceDetail: lead.sourceDetail,
|
||||
externalId: lead.externalId,
|
||||
assignedToAdminUserId: lead.assignedToAdminUserId,
|
||||
assigneeLabel: lead.assignedToAdminUserId ? (assigneeLabels.get(lead.assignedToAdminUserId) ?? null) : null,
|
||||
duplicateHintOfLeadId: lead.duplicateHintOfLeadId,
|
||||
capturedAt: lead.capturedAt,
|
||||
createdAt: lead.createdAt,
|
||||
updatedAt: lead.updatedAt,
|
||||
archivedAt: lead.archivedAt,
|
||||
attribution: {
|
||||
utmSource: lead.utmSource,
|
||||
utmMedium: lead.utmMedium,
|
||||
utmCampaign: lead.utmCampaign,
|
||||
utmTerm: lead.utmTerm,
|
||||
utmContent: lead.utmContent,
|
||||
referrer: lead.referrer,
|
||||
landingPage: lead.landingPage,
|
||||
},
|
||||
qualification: lead.qualification,
|
||||
duplicateCandidates: lead.duplicateCandidates,
|
||||
conversion: lead.conversion,
|
||||
activities: lead.activities.map((activity) => ({
|
||||
id: activity.id,
|
||||
type: activity.type,
|
||||
actorAdminUserId: activity.actorAdminUserId,
|
||||
actorLabel: activity.actorAdminUserId ? (assigneeLabels.get(activity.actorAdminUserId) ?? null) : null,
|
||||
note: typeof activity.payload.note === "string" ? activity.payload.note : null,
|
||||
createdAt: activity.createdAt,
|
||||
})),
|
||||
},
|
||||
assigneeOptions: assignees,
|
||||
permissions: {
|
||||
canWrite: access.canWrite,
|
||||
canAssign: access.canAdmin,
|
||||
canMerge: access.canMerge,
|
||||
},
|
||||
}),
|
||||
feedback: (() => {
|
||||
const feedback = new URL(request.url).searchParams.get("feedback");
|
||||
return feedback === "created" || feedback === "updated" ? feedback : null;
|
||||
})(),
|
||||
};
|
||||
});
|
||||
const session = await getUserInfo(request);
|
||||
return { ...data, csrf: session.csrf ?? "" };
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const leadId = params.id?.trim();
|
||||
if (!leadId) throw platformLeadNotFound();
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const baseParsed = adminLeadMutationFormSchema.safeParse({
|
||||
intent,
|
||||
status: form.get("status"),
|
||||
assignedToAdminUserId:
|
||||
form.get("assignedToAdminUserId") === "unassigned"
|
||||
? null
|
||||
: form.get("assignedToAdminUserId"),
|
||||
note: form.get("note"),
|
||||
});
|
||||
const advancedParsed = adminLeadAdvancedMutationFormSchema.safeParse({
|
||||
intent,
|
||||
provider: form.get("provider"),
|
||||
companyName: form.get("companyName"),
|
||||
domain: form.get("domain"),
|
||||
website: form.get("website"),
|
||||
region: form.get("region"),
|
||||
countryCode: form.get("countryCode"),
|
||||
industry: form.get("industry"),
|
||||
employeeRange: form.get("employeeRange"),
|
||||
candidateId: form.get("candidateId"),
|
||||
survivorLeadId: form.get("survivorLeadId"),
|
||||
mergedLeadId: form.get("mergedLeadId"),
|
||||
firstName: form.get("firstName"),
|
||||
lastName: form.get("lastName"),
|
||||
dealTitle: form.get("dealTitle"),
|
||||
ownerAdminUserId: form.get("ownerAdminUserId"),
|
||||
amountCents: form.get("amountCents"),
|
||||
expectedCloseDate: form.get("expectedCloseDate"),
|
||||
nextStep: form.get("nextStep"),
|
||||
});
|
||||
const reason = String(form.get("reason") ?? "").trim();
|
||||
if ((!baseParsed.success && !advancedParsed.success) || (intent !== "note" && reason.length < 5)) {
|
||||
return Response.json({ error: t("admin.platformLeads.errors.invalidForm") } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
let redirectLeadId = leadId;
|
||||
await runAsPlatformLeadOperator(request, async ({ access, service, advancedService }) => {
|
||||
const parsed = baseParsed.success ? baseParsed.data : advancedParsed.success ? advancedParsed.data : null;
|
||||
if (!parsed) throw new Error("Lead action could not be parsed.");
|
||||
requirePlatformLeadWrite(access);
|
||||
const audit = access.audit(parsed.intent === "note" ? parsed.note : reason);
|
||||
const advancedActor = {
|
||||
adminUserId: audit.actorAdminUserId,
|
||||
email: audit.actorEmail,
|
||||
reason: audit.reason,
|
||||
requestId: audit.requestId,
|
||||
ip: audit.actorIp,
|
||||
userAgent: audit.actorUserAgent,
|
||||
};
|
||||
const visibility = access.canReadAll ? {} : { requiredAssigneeAdminUserId: access.actorAdminUserId };
|
||||
|
||||
switch (parsed.intent) {
|
||||
case "status":
|
||||
await service.updateStatus({ leadId, status: parsed.status, ...visibility, ...audit });
|
||||
return;
|
||||
case "assign":
|
||||
await service.assignLead({ leadId, assignedToAdminUserId: parsed.assignedToAdminUserId, ...visibility, ...audit });
|
||||
return;
|
||||
case "note":
|
||||
await service.addNote({ leadId, note: parsed.note, ...visibility, ...audit });
|
||||
return;
|
||||
case "archive":
|
||||
await service.archiveLead({ leadId, ...visibility, ...audit });
|
||||
return;
|
||||
case "restore":
|
||||
await service.restoreLead({ leadId, ...visibility, ...audit });
|
||||
return;
|
||||
case "auto-assign":
|
||||
await advancedService.autoAssignLead({ leadId, actor: advancedActor });
|
||||
return;
|
||||
case "score":
|
||||
await advancedService.scoreLead({ leadId, actor: advancedActor });
|
||||
return;
|
||||
case "detect-duplicates":
|
||||
await advancedService.detectDuplicates({ leadId, actor: advancedActor });
|
||||
return;
|
||||
case "enrich":
|
||||
await advancedService.enrichLead({
|
||||
leadId,
|
||||
result: {
|
||||
provider: parsed.provider,
|
||||
companyName: parsed.companyName,
|
||||
domain: parsed.domain,
|
||||
website: parsed.website,
|
||||
region: parsed.region,
|
||||
countryCode: parsed.countryCode,
|
||||
industry: parsed.industry,
|
||||
employeeRange: parsed.employeeRange,
|
||||
},
|
||||
actor: advancedActor,
|
||||
});
|
||||
return;
|
||||
case "dismiss-duplicate":
|
||||
await advancedService.dismissDuplicate({
|
||||
candidateId: parsed.candidateId,
|
||||
reason,
|
||||
actor: advancedActor,
|
||||
});
|
||||
return;
|
||||
case "merge":
|
||||
redirectLeadId = (
|
||||
await advancedService.mergeLeads({
|
||||
candidateId: parsed.candidateId,
|
||||
survivorLeadId: parsed.survivorLeadId,
|
||||
mergedLeadId: parsed.mergedLeadId,
|
||||
reason,
|
||||
actor: advancedActor,
|
||||
})
|
||||
).survivorLeadId;
|
||||
return;
|
||||
case "convert":
|
||||
await advancedService.convertLead({
|
||||
leadId,
|
||||
companyName: parsed.companyName,
|
||||
firstName: parsed.firstName,
|
||||
lastName: parsed.lastName,
|
||||
dealTitle: parsed.dealTitle,
|
||||
ownerAdminUserId: parsed.ownerAdminUserId,
|
||||
amountCents: parsed.amountCents,
|
||||
expectedCloseDate: parsed.expectedCloseDate,
|
||||
nextStep: parsed.nextStep,
|
||||
actor: advancedActor,
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
return redirect(`${adminPath(`leads/${redirectLeadId}`, { mode: "host-aware" })}?feedback=updated`);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
if (error instanceof PlatformLeadAdminError && error.code === "NOT_FOUND") throw platformLeadNotFound();
|
||||
return Response.json({ error: t("admin.platformLeads.errors.actionFailed") } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminPlatformLeadDetailRoute(): React.JSX.Element {
|
||||
const data = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<AdminPlatformLeadDetailPage
|
||||
vm={data.vm}
|
||||
csrf={data.csrf}
|
||||
submitting={navigation.state === "submitting"}
|
||||
feedback={{
|
||||
success: data.feedback ? t(`admin.platformLeads.feedback.${data.feedback}`) : undefined,
|
||||
error: actionData?.error,
|
||||
}}
|
||||
actions={{
|
||||
onBack: () => void navigate(adminPath("leads", { mode: "host-aware" })),
|
||||
onSubmit: (input) => void submit(input, { method: "post" }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { buildAdminLeadListVM, adminLeadStatuses, type AdminLeadStatus } from "@hivegrid/view-models";
|
||||
import { toPlatformLeadsProps } from "@hivegrid/ui-app";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData, useLocation, useNavigate, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminPlatformLeadsPage } from "~/components/screens/admin/leads/AdminPlatformLeadsPage";
|
||||
import { listPlatformLeadAssignees, requirePlatformLeadRead, runAsPlatformLeadOperator } from "~/services/admin/platform-leads.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
const archiveFilters = ["active", "archived", "all"] as const;
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) =>
|
||||
runAsPlatformLeadOperator(request, async ({ access, service }) => {
|
||||
requirePlatformLeadRead(access);
|
||||
const search = new URL(request.url).searchParams;
|
||||
const requestedStatus = search.get("status") ?? "all";
|
||||
const status: AdminLeadStatus | "all" = (adminLeadStatuses as readonly string[]).includes(requestedStatus) ? (requestedStatus as AdminLeadStatus) : "all";
|
||||
const requestedArchive = search.get("archive") ?? "active";
|
||||
const archive = (archiveFilters as readonly string[]).includes(requestedArchive) ? (requestedArchive as (typeof archiveFilters)[number]) : "active";
|
||||
const requestedSourceId = search.get("sourceId")?.trim() || "all";
|
||||
const requestedAssignee = search.get("assignee")?.trim() || "all";
|
||||
const requestedCursor = search.get("cursor")?.trim() ?? "";
|
||||
const cursor = /^[A-Za-z0-9_-]{1,191}$/u.test(requestedCursor) ? requestedCursor : null;
|
||||
const assignedToAdminUserIds = access.canReadAll
|
||||
? requestedAssignee !== "all" && requestedAssignee !== "unassigned"
|
||||
? [requestedAssignee]
|
||||
: []
|
||||
: [access.actorAdminUserId];
|
||||
const includeUnassigned = access.canReadAll && requestedAssignee === "unassigned";
|
||||
|
||||
const [page, sources, assignees] = await Promise.all([
|
||||
service.listLeads({
|
||||
search: search.get("q"),
|
||||
statuses: status === "all" ? [] : [status],
|
||||
sourceIds: requestedSourceId === "all" ? [] : [requestedSourceId],
|
||||
assignedToAdminUserIds,
|
||||
includeUnassigned,
|
||||
archive,
|
||||
cursor,
|
||||
limit: 100,
|
||||
}),
|
||||
service.listSources(),
|
||||
listPlatformLeadAssignees(),
|
||||
]);
|
||||
const assigneeLabels = new Map(assignees.map((option) => [option.id, option.label]));
|
||||
|
||||
return {
|
||||
vm: toPlatformLeadsProps(
|
||||
buildAdminLeadListVM({
|
||||
rows: page.items.map((lead) => ({
|
||||
id: lead.id,
|
||||
firstName: lead.firstName,
|
||||
lastName: lead.lastName,
|
||||
email: lead.email,
|
||||
phone: lead.phone,
|
||||
company: lead.company,
|
||||
status: lead.status,
|
||||
sourceId: lead.source.id,
|
||||
sourceDisplayName: lead.source.displayName,
|
||||
assignedToAdminUserId: lead.assignedToAdminUserId,
|
||||
assigneeLabel: lead.assignedToAdminUserId ? (assigneeLabels.get(lead.assignedToAdminUserId) ?? null) : null,
|
||||
duplicateHintOfLeadId: lead.duplicateHintOfLeadId,
|
||||
capturedAt: lead.capturedAt,
|
||||
archivedAt: lead.archivedAt,
|
||||
})),
|
||||
sourceOptions: sources.map((source) => ({ id: source.id, label: source.displayName })),
|
||||
assigneeOptions: assignees,
|
||||
filters: {
|
||||
query: search.get("q")?.trim() ?? "",
|
||||
status,
|
||||
sourceId: requestedSourceId,
|
||||
assignedToAdminUserId: access.canReadAll ? requestedAssignee : access.actorAdminUserId,
|
||||
archive,
|
||||
},
|
||||
summary: page.summary,
|
||||
pagination: { hasPrevious: cursor !== null, nextCursor: page.nextCursor },
|
||||
permissions: {
|
||||
canCreate: access.canWrite,
|
||||
canWrite: access.canWrite,
|
||||
canAdminSources: access.canAdmin,
|
||||
},
|
||||
})
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
export default function AdminPlatformLeadsIndexRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
return (
|
||||
<AdminPlatformLeadsPage
|
||||
vm={vm}
|
||||
loading={navigation.state === "loading"}
|
||||
actions={{
|
||||
onApplyFilters: (input) => void submit(input, { method: "get" }),
|
||||
onFirstPage: () => {
|
||||
const search = new URLSearchParams(location.search);
|
||||
search.delete("cursor");
|
||||
void navigate({ pathname: adminPath("leads", { mode: "host-aware" }), search: search.toString() });
|
||||
},
|
||||
onNew: () => void navigate(adminPath("leads/new", { mode: "host-aware" })),
|
||||
onNextPage: (cursor) => {
|
||||
const search = new URLSearchParams(location.search);
|
||||
search.set("cursor", cursor);
|
||||
void navigate({ pathname: adminPath("leads", { mode: "host-aware" }), search: search.toString() });
|
||||
},
|
||||
onReset: () => void navigate(adminPath("leads", { mode: "host-aware" })),
|
||||
onSources: () => void navigate(adminPath("leads/sources", { mode: "host-aware" })),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { adminLeadManualFormSchema } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect, useActionData, useLoaderData, useNavigate, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminPlatformLeadNewPage } from "~/components/screens/admin/leads/AdminPlatformLeadNewPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { listPlatformLeadAssignees, requirePlatformLeadWrite, runAsPlatformLeadOperator } from "~/services/admin/platform-leads.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = { readonly error: string };
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const data = await runAsPlatformLeadOperator(request, async ({ access, service }) => {
|
||||
requirePlatformLeadWrite(access);
|
||||
const [sources, assignees] = await Promise.all([service.listSources(), listPlatformLeadAssignees()]);
|
||||
return {
|
||||
sourceOptions: sources.filter((source) => source.enabled).map((source) => ({ id: source.id, label: source.displayName })),
|
||||
assigneeOptions: assignees,
|
||||
};
|
||||
});
|
||||
const session = await getUserInfo(request);
|
||||
return { ...data, csrf: session.csrf ?? "" };
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const parsed = adminLeadManualFormSchema.safeParse({
|
||||
sourceId: form.get("sourceId"),
|
||||
firstName: form.get("firstName") ?? "",
|
||||
lastName: form.get("lastName") ?? "",
|
||||
email: form.get("email") ?? "",
|
||||
phone: form.get("phone") ?? "",
|
||||
company: form.get("company") ?? "",
|
||||
message: form.get("message") ?? "",
|
||||
sourceDetail: form.get("sourceDetail") ?? "",
|
||||
assignedToAdminUserId:
|
||||
form.get("assignedToAdminUserId") && form.get("assignedToAdminUserId") !== "unassigned" ? form.get("assignedToAdminUserId") : undefined,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
const messageKey = parsed.error.issues.find((issue) => issue.message.startsWith("admin."))?.message;
|
||||
return Response.json({ error: t(messageKey ?? "admin.platformLeads.errors.invalidForm") } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const created = await runAsPlatformLeadOperator(request, async ({ access, service }) => {
|
||||
requirePlatformLeadWrite(access);
|
||||
return service.createManual({
|
||||
channel: "manual",
|
||||
sourceId: parsed.data.sourceId,
|
||||
assignedToAdminUserId: parsed.data.assignedToAdminUserId ?? null,
|
||||
payload: {
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
email: parsed.data.email,
|
||||
phone: parsed.data.phone,
|
||||
company: parsed.data.company,
|
||||
message: parsed.data.message,
|
||||
sourceDetail: parsed.data.sourceDetail,
|
||||
},
|
||||
...access.audit("Platform lead created manually"),
|
||||
});
|
||||
});
|
||||
return redirect(`${adminPath(`leads/${created.lead.id}`, { mode: "host-aware" })}?feedback=created`);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
return Response.json({ error: t("admin.platformLeads.errors.actionFailed") } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminPlatformLeadNewRoute(): React.JSX.Element {
|
||||
const data = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
return (
|
||||
<AdminPlatformLeadNewPage
|
||||
sourceOptions={data.sourceOptions}
|
||||
assigneeOptions={data.assigneeOptions}
|
||||
csrf={data.csrf}
|
||||
submitting={navigation.state === "submitting"}
|
||||
error={actionData?.error}
|
||||
actions={{
|
||||
onBack: () => void navigate(adminPath("leads", { mode: "host-aware" })),
|
||||
onCreate: (input) => void submit(input, { method: "post" }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
getPlatformNotificationStreamSnapshot,
|
||||
markPlatformInAppNotificationDeliveryRead,
|
||||
} from "@hivegrid/db/notifications.server";
|
||||
import { REALTIME_EVENT_NAMES, serializeRealtimeEvent } from "@hivegrid/realtime";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import {
|
||||
platformLeadNotFound,
|
||||
requirePlatformLeadRead,
|
||||
runAsPlatformLeadOperator,
|
||||
} from "~/services/admin/platform-leads.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
const MAX_READ_IDS = 100;
|
||||
const IDENTIFIER_PATTERN = /^[A-Za-z0-9_-]{1,191}$/u;
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) =>
|
||||
runAsPlatformLeadOperator(request, async ({ access }) => {
|
||||
requirePlatformLeadRead(access);
|
||||
const requestUrl = new URL(request.url);
|
||||
const rawCursor = request.headers.get("last-event-id") ?? requestUrl.searchParams.get("afterCursor");
|
||||
const afterCursor = rawCursor?.trim().slice(0, 500) || null;
|
||||
const snapshot = await getPlatformNotificationStreamSnapshot({
|
||||
userId: access.actorAdminUserId,
|
||||
afterCursor,
|
||||
});
|
||||
if (snapshot.items.some((item) => item.tenantId !== null || item.userId !== access.actorAdminUserId)) {
|
||||
throw platformLeadNotFound();
|
||||
}
|
||||
const cursor = snapshot.cursor ?? afterCursor ?? "initial";
|
||||
const body = serializeRealtimeEvent({
|
||||
event: REALTIME_EVENT_NAMES.notificationSnapshot,
|
||||
requestId: randomUUID(),
|
||||
tenantId: null,
|
||||
userId: access.actorAdminUserId,
|
||||
cursor,
|
||||
items: snapshot.items,
|
||||
});
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"cache-control": "no-cache",
|
||||
"content-type": "text/event-stream; charset=utf-8",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const deliveryIds = [...new Set(form.getAll("deliveryId").map(String).map((value) => value.trim()))];
|
||||
if (deliveryIds.length > MAX_READ_IDS || deliveryIds.some((id) => !IDENTIFIER_PATTERN.test(id))) {
|
||||
return Response.json({ error: "invalid_request" }, { status: 400 });
|
||||
}
|
||||
return runAsPlatformLeadOperator(request, async ({ access }) => {
|
||||
requirePlatformLeadRead(access);
|
||||
for (const id of deliveryIds) {
|
||||
await markPlatformInAppNotificationDeliveryRead({
|
||||
id,
|
||||
userId: access.actorAdminUserId,
|
||||
readAt: new Date(),
|
||||
});
|
||||
}
|
||||
return Response.json({ ok: true, marked: deliveryIds.length });
|
||||
});
|
||||
};
|
||||
|
||||
export default function PlatformLeadNotificationStreamRoute(): null {
|
||||
return null;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
function getValueAtPath(source: Record<string, unknown>, path: string): unknown {
|
||||
return path.split(".").reduce<unknown>((current, segment) => {
|
||||
if (!current || typeof current !== "object") return undefined;
|
||||
return (current as Record<string, unknown>)[segment];
|
||||
}, source);
|
||||
}
|
||||
|
||||
describe("platform lead notification i18n", () => {
|
||||
it("keeps the persisted worker message key renderable in every supported locale", () => {
|
||||
const messageKey = "platform.leads.captured";
|
||||
for (const locale of ["de", "en"]) {
|
||||
const translations = JSON.parse(readRepoFile(`apps/web/public/locales/${locale}/translations.json`)) as Record<string, unknown>;
|
||||
expect(getValueAtPath(translations, messageKey), `${locale}:${messageKey}`).toEqual(expect.any(String));
|
||||
}
|
||||
});
|
||||
});
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const access = {
|
||||
actorAdminUserId: "operator_1",
|
||||
actorEmail: "operator@example.test",
|
||||
canReadOwn: true,
|
||||
canReadAll: false,
|
||||
canWrite: true,
|
||||
canAdmin: true,
|
||||
canMerge: true,
|
||||
audit: (reason: string) => ({
|
||||
actorAdminUserId: "operator_1",
|
||||
actorEmail: "operator@example.test",
|
||||
actorIp: null,
|
||||
actorUserAgent: null,
|
||||
requestId: "request_1",
|
||||
reason,
|
||||
}),
|
||||
};
|
||||
return {
|
||||
access,
|
||||
service: {
|
||||
listLeads: vi.fn(),
|
||||
listSources: vi.fn(),
|
||||
getLead: vi.fn(),
|
||||
createManual: vi.fn(),
|
||||
updateStatus: vi.fn(),
|
||||
assignLead: vi.fn(),
|
||||
addNote: vi.fn(),
|
||||
archiveLead: vi.fn(),
|
||||
restoreLead: vi.fn(),
|
||||
createSource: vi.fn(),
|
||||
updateSource: vi.fn(),
|
||||
createSourceCredential: vi.fn(),
|
||||
rotateSourceCredential: vi.fn(),
|
||||
revokeSourceCredential: vi.fn(),
|
||||
},
|
||||
advancedService: {
|
||||
listAutomationConfig: vi.fn(),
|
||||
createAssignmentRule: vi.fn(),
|
||||
createScoreRule: vi.fn(),
|
||||
autoAssignLead: vi.fn(),
|
||||
scoreLead: vi.fn(),
|
||||
detectDuplicates: vi.fn(),
|
||||
enrichLead: vi.fn(),
|
||||
dismissDuplicate: vi.fn(),
|
||||
mergeLeads: vi.fn(),
|
||||
convertLead: vi.fn(),
|
||||
},
|
||||
validateCsrf: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/screens/admin/leads/AdminPlatformLeadsPage", () => ({ AdminPlatformLeadsPage: () => null }));
|
||||
vi.mock("~/components/screens/admin/leads/AdminPlatformLeadDetailPage", () => ({ AdminPlatformLeadDetailPage: () => null }));
|
||||
vi.mock("~/components/screens/admin/leads/AdminPlatformLeadNewPage", () => ({ AdminPlatformLeadNewPage: () => null }));
|
||||
vi.mock("~/components/screens/admin/leads/AdminPlatformLeadSourcesPage", () => ({ AdminPlatformLeadSourcesPage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: async () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: async () => ({ userId: "operator_1", csrf: "csrf" }),
|
||||
validateCSRFToken: mocks.validateCsrf,
|
||||
}));
|
||||
vi.mock("~/services/admin/platform-leads.server", () => ({
|
||||
runAsPlatformLeadOperator: async (_request: Request, callback: (input: unknown) => Promise<unknown>) =>
|
||||
callback({ access: mocks.access, service: mocks.service, advancedService: mocks.advancedService }),
|
||||
requirePlatformLeadRead: vi.fn(),
|
||||
requirePlatformLeadWrite: vi.fn(),
|
||||
requirePlatformLeadAdmin: vi.fn(),
|
||||
assertPlatformLeadVisibleToOperator: vi.fn(),
|
||||
platformLeadNotFound: () => new Response("Not Found", { status: 404 }),
|
||||
listPlatformLeadAssignees: async () => [{ id: "operator_1", label: "Operator One" }],
|
||||
}));
|
||||
|
||||
import { action as detailAction, loader as detailLoader } from "./$id";
|
||||
import { loader as listLoader } from "./index";
|
||||
import { action as manualAction } from "./new";
|
||||
import { action as sourcesAction } from "./sources";
|
||||
|
||||
const source = {
|
||||
id: "source_1",
|
||||
key: "hivegrid-website",
|
||||
displayName: "HiveGrid Website",
|
||||
createdAt: "2026-07-16T00:00:00.000Z",
|
||||
updatedAt: "2026-07-16T00:00:00.000Z",
|
||||
enabled: true,
|
||||
defaultAssigneeAdminUserId: "operator_1",
|
||||
notifyAdminUserIds: ["operator_1"],
|
||||
rateLimitPerMinute: 60,
|
||||
metadata: null,
|
||||
leadCount: 1,
|
||||
credentials: [],
|
||||
};
|
||||
|
||||
const lead = {
|
||||
id: "lead_1",
|
||||
createdAt: "2026-07-16T00:00:00.000Z",
|
||||
updatedAt: "2026-07-16T00:00:00.000Z",
|
||||
capturedAt: "2026-07-16T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
firstName: "Petra",
|
||||
lastName: "Muster",
|
||||
email: "petra@example.test",
|
||||
phone: null,
|
||||
company: "Muster GmbH",
|
||||
status: "new" as const,
|
||||
assignedToAdminUserId: "operator_1",
|
||||
duplicateHintOfLeadId: null,
|
||||
source: { id: source.id, key: source.key, displayName: source.displayName },
|
||||
sourceDetail: null,
|
||||
externalId: "submission_1",
|
||||
message: "Bitte melden",
|
||||
utmSource: null,
|
||||
utmMedium: null,
|
||||
utmCampaign: null,
|
||||
utmTerm: null,
|
||||
utmContent: null,
|
||||
referrer: null,
|
||||
landingPage: null,
|
||||
metadata: null,
|
||||
qualification: null,
|
||||
duplicateCandidates: [],
|
||||
conversion: { companyId: null, contactId: null, dealId: null },
|
||||
activities: [
|
||||
{
|
||||
id: "activity_1",
|
||||
createdAt: "2026-07-16T00:00:00.000Z",
|
||||
type: "captured" as const,
|
||||
actorAdminUserId: null,
|
||||
payload: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function loaderArgs(url: string, params: Record<string, string> = {}): LoaderFunctionArgs {
|
||||
return { request: new Request(url), params, context: {} } as LoaderFunctionArgs;
|
||||
}
|
||||
|
||||
function actionArgs(url: string, form: Record<string, string>, params: Record<string, string> = {}): ActionFunctionArgs {
|
||||
return {
|
||||
request: new Request(url, { method: "POST", body: new URLSearchParams({ csrf: "csrf", ...form }) }),
|
||||
params,
|
||||
context: {},
|
||||
} as ActionFunctionArgs;
|
||||
}
|
||||
|
||||
describe("platform lead admin routes", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.access.canReadAll = false;
|
||||
mocks.service.listLeads.mockResolvedValue({ items: [lead], nextCursor: null });
|
||||
mocks.service.listSources.mockResolvedValue([source]);
|
||||
mocks.service.getLead.mockResolvedValue(lead);
|
||||
mocks.service.createManual.mockResolvedValue({ outcome: "created", lead: { id: lead.id, status: "new", createdAt: lead.createdAt } });
|
||||
});
|
||||
|
||||
it("builds the inbox VM and forces read-own queries to the current operator", async () => {
|
||||
const data = await listLoader(loaderArgs("https://admin.example.test/leads?status=new&assignee=operator_2"));
|
||||
|
||||
expect(mocks.service.listLeads).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
statuses: ["new"],
|
||||
assignedToAdminUserIds: ["operator_1"],
|
||||
includeUnassigned: false,
|
||||
})
|
||||
);
|
||||
expect(data.vm.rows[0]).toMatchObject({ id: "lead_1", displayName: "Petra Muster", assigneeLabel: "Operator One" });
|
||||
});
|
||||
|
||||
it("loads a detail VM with activity labels and assignee resolution", async () => {
|
||||
const data = await detailLoader(loaderArgs("https://admin.example.test/leads/lead_1", { id: "lead_1" }));
|
||||
expect(data.vm).toMatchObject({ id: "lead_1", displayName: "Petra Muster", statusLabelKey: "admin.platformLeads.status.new" });
|
||||
expect(data.vm.activities[0]).toMatchObject({ labelKey: "admin.platformLeads.activity.captured" });
|
||||
});
|
||||
|
||||
it("uses the central service for manual creation and status mutations", async () => {
|
||||
const manualResponse = await manualAction(
|
||||
actionArgs("https://admin.example.test/leads/new", {
|
||||
sourceId: "source_1",
|
||||
firstName: "Petra",
|
||||
company: "Muster GmbH",
|
||||
})
|
||||
);
|
||||
expect(manualResponse.status).toBe(302);
|
||||
expect(mocks.service.createManual).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
channel: "manual",
|
||||
sourceId: "source_1",
|
||||
actorAdminUserId: "operator_1",
|
||||
})
|
||||
);
|
||||
|
||||
const detailResponse = await detailAction(
|
||||
actionArgs(
|
||||
"https://admin.example.test/leads/lead_1",
|
||||
{
|
||||
intent: "status",
|
||||
status: "qualified",
|
||||
reason: "Lead was qualified",
|
||||
},
|
||||
{ id: "lead_1" }
|
||||
)
|
||||
);
|
||||
expect(detailResponse.status).toBe(302);
|
||||
expect(mocks.service.updateStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
leadId: "lead_1",
|
||||
status: "qualified",
|
||||
actorAdminUserId: "operator_1",
|
||||
reason: "Lead was qualified",
|
||||
})
|
||||
);
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("routes scoring and controlled conversion through the advanced lead service", async () => {
|
||||
const scoreResponse = await detailAction(
|
||||
actionArgs(
|
||||
"https://admin.example.test/leads/lead_1",
|
||||
{ intent: "score", reason: "Lead erneut bewertet" },
|
||||
{ id: "lead_1" }
|
||||
)
|
||||
);
|
||||
expect(scoreResponse.status).toBe(302);
|
||||
expect(mocks.advancedService.scoreLead).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
leadId: "lead_1",
|
||||
actor: expect.objectContaining({ adminUserId: "operator_1", reason: "Lead erneut bewertet" }),
|
||||
})
|
||||
);
|
||||
|
||||
const conversionResponse = await detailAction(
|
||||
actionArgs(
|
||||
"https://admin.example.test/leads/lead_1",
|
||||
{
|
||||
intent: "convert",
|
||||
companyName: "Muster GmbH",
|
||||
firstName: "Petra",
|
||||
lastName: "Muster",
|
||||
dealTitle: "HiveGrid SaaS",
|
||||
ownerAdminUserId: "operator_1",
|
||||
amountCents: "120000",
|
||||
expectedCloseDate: "2026-08-31",
|
||||
nextStep: "Demo vereinbaren",
|
||||
reason: "Lead kontrolliert konvertiert",
|
||||
},
|
||||
{ id: "lead_1" }
|
||||
)
|
||||
);
|
||||
expect(conversionResponse.status).toBe(302);
|
||||
expect(mocks.advancedService.convertLead).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
leadId: "lead_1",
|
||||
companyName: "Muster GmbH",
|
||||
ownerAdminUserId: "operator_1",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("redirects a duplicate merge to the server-verified survivor", async () => {
|
||||
mocks.advancedService.mergeLeads.mockResolvedValue({
|
||||
survivorLeadId: "lead_primary",
|
||||
mergedLeadId: "lead_1",
|
||||
replayed: false,
|
||||
});
|
||||
const response = await detailAction(
|
||||
actionArgs(
|
||||
"https://admin.example.test/leads/lead_1",
|
||||
{
|
||||
intent: "merge",
|
||||
candidateId: "candidate_1",
|
||||
survivorLeadId: "lead_primary",
|
||||
mergedLeadId: "lead_1",
|
||||
reason: "Doppelte Anfrage zusammengeführt",
|
||||
},
|
||||
{ id: "lead_1" }
|
||||
)
|
||||
);
|
||||
|
||||
expect(mocks.advancedService.mergeLeads).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
candidateId: "candidate_1",
|
||||
survivorLeadId: "lead_primary",
|
||||
mergedLeadId: "lead_1",
|
||||
})
|
||||
);
|
||||
expect(response.headers.get("location")).toContain("/leads/lead_primary?feedback=updated");
|
||||
});
|
||||
|
||||
it("returns a rotated source credential exactly once through action data", async () => {
|
||||
mocks.service.rotateSourceCredential.mockResolvedValue({ credential: { id: "credential_2" }, secret: "one-time-secret" });
|
||||
const response = await sourcesAction(
|
||||
actionArgs("https://admin.example.test/leads/sources", {
|
||||
intent: "rotate-credential",
|
||||
sourceId: "source_1",
|
||||
credentialId: "credential_1",
|
||||
reason: "Rotate credential safely",
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
success: "admin.platformLeads.feedback.credentialRotated",
|
||||
revealedCredential: { sourceId: "source_1", plaintext: "one-time-secret" },
|
||||
});
|
||||
expect(mocks.service.rotateSourceCredential).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sourceId: "source_1",
|
||||
credentialId: "credential_1",
|
||||
actorAdminUserId: "operator_1",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getSnapshot: vi.fn(),
|
||||
markRead: vi.fn(),
|
||||
requireRead: vi.fn(),
|
||||
runAsOperator: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({
|
||||
getPlatformNotificationStreamSnapshot: mocks.getSnapshot,
|
||||
markPlatformInAppNotificationDeliveryRead: mocks.markRead,
|
||||
}));
|
||||
|
||||
vi.mock("~/services/admin/platform-leads.server", () => ({
|
||||
platformLeadNotFound: () => new Response("Not Found", { status: 404 }),
|
||||
requirePlatformLeadRead: mocks.requireRead,
|
||||
runAsPlatformLeadOperator: mocks.runAsOperator,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
|
||||
|
||||
import { action, loader } from "./notifications-stream";
|
||||
|
||||
const access = {
|
||||
actorAdminUserId: "operator_1",
|
||||
canReadOwn: true,
|
||||
canReadAll: false,
|
||||
canWrite: true,
|
||||
canAdmin: false,
|
||||
};
|
||||
|
||||
function loaderArgs(request = new Request("https://admin.example.test/leads/notifications-stream")) {
|
||||
return { request, params: {}, context: {} } as never;
|
||||
}
|
||||
|
||||
function formRequest(entries: Array<[string, string]>): Request {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of entries) body.append(key, value);
|
||||
return new Request("https://admin.example.test/leads/notifications-stream", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
describe("platform lead notification stream route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getSnapshot.mockResolvedValue({ cursor: null, items: [] });
|
||||
mocks.markRead.mockResolvedValue({ count: 1 });
|
||||
mocks.runAsOperator.mockImplementation(async (_request: Request, callback: (context: unknown) => Promise<unknown>) =>
|
||||
callback({ access, service: {} })
|
||||
);
|
||||
mocks.validateCsrf.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("streams only the current operator's tenantless notification scope", async () => {
|
||||
const request = new Request("https://admin.example.test/leads/notifications-stream?afterCursor=cursor_1");
|
||||
const response = (await loader(loaderArgs(request))) as Response;
|
||||
const body = await response.text();
|
||||
|
||||
expect(mocks.requireRead).toHaveBeenCalledWith(access);
|
||||
expect(mocks.getSnapshot).toHaveBeenCalledWith({ userId: "operator_1", afterCursor: "cursor_1" });
|
||||
expect(response.headers.get("content-type")).toBe("text/event-stream; charset=utf-8");
|
||||
expect(response.headers.get("cache-control")).toBe("no-cache");
|
||||
expect(body).toContain("event: notification.snapshot\n");
|
||||
expect(body).toContain('"tenantId":null');
|
||||
expect(body).toContain('"userId":"operator_1"');
|
||||
});
|
||||
|
||||
it("fails closed if the database snapshot ever escapes the current user scope", async () => {
|
||||
mocks.getSnapshot.mockResolvedValue({
|
||||
cursor: "cursor_escape",
|
||||
items: [{ tenantId: "tenant_escape", userId: "operator_2" }],
|
||||
});
|
||||
|
||||
await expect(loader(loaderArgs())).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("preserves the route-wide 404 contract for feature or read-permission denial", async () => {
|
||||
mocks.runAsOperator.mockRejectedValueOnce(new Response("Not Found", { status: 404 }));
|
||||
await expect(loader(loaderArgs())).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
mocks.requireRead.mockImplementationOnce(() => {
|
||||
throw new Response("Not Found", { status: 404 });
|
||||
});
|
||||
await expect(loader(loaderArgs())).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.getSnapshot).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validates CSRF and rejects malformed or oversized delivery identifiers before a write", async () => {
|
||||
const malformed = (await action(loaderArgs(formRequest([["deliveryId", "delivery/escape"]])))) as Response;
|
||||
expect(malformed.status).toBe(400);
|
||||
|
||||
const oversizedEntries = Array.from({ length: 101 }, (_, index) => ["deliveryId", `delivery_${index}`] as [string, string]);
|
||||
const oversized = (await action(loaderArgs(formRequest(oversizedEntries)))) as Response;
|
||||
expect(oversized.status).toBe(400);
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.markRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not enter operator scope when CSRF validation fails", async () => {
|
||||
mocks.validateCsrf.mockRejectedValueOnce(new Response("Forbidden", { status: 403 }));
|
||||
|
||||
await expect(action(loaderArgs(formRequest([["deliveryId", "delivery_1"]])))).rejects.toMatchObject({ status: 403 });
|
||||
expect(mocks.runAsOperator).not.toHaveBeenCalled();
|
||||
expect(mocks.markRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks unique delivery ids read only for the current operator", async () => {
|
||||
const response = (await action(
|
||||
loaderArgs(
|
||||
formRequest([
|
||||
["deliveryId", "delivery_1"],
|
||||
["deliveryId", "delivery_1"],
|
||||
["deliveryId", "delivery_2"],
|
||||
])
|
||||
)
|
||||
)) as Response;
|
||||
|
||||
expect(await response.json()).toEqual({ ok: true, marked: 2 });
|
||||
expect(mocks.markRead).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.markRead).toHaveBeenNthCalledWith(1, {
|
||||
id: "delivery_1",
|
||||
userId: "operator_1",
|
||||
readAt: expect.any(Date),
|
||||
});
|
||||
expect(mocks.markRead).toHaveBeenNthCalledWith(2, {
|
||||
id: "delivery_2",
|
||||
userId: "operator_1",
|
||||
readAt: expect.any(Date),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { adminLeadSourceFormSchema, buildAdminLeadSourcesVM } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigate, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminPlatformLeadSourcesPage } from "~/components/screens/admin/leads/AdminPlatformLeadSourcesPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { listPlatformLeadAssignees, requirePlatformLeadAdmin, runAsPlatformLeadOperator } from "~/services/admin/platform-leads.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = {
|
||||
readonly success?: string;
|
||||
readonly error?: string;
|
||||
readonly revealedCredential?: { readonly sourceId: string; readonly plaintext: string };
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const data = await runAsPlatformLeadOperator(request, async ({ access, service }) => {
|
||||
requirePlatformLeadAdmin(access);
|
||||
const now = new Date();
|
||||
const [sources, assignees] = await Promise.all([service.listSources({ now }), listPlatformLeadAssignees()]);
|
||||
const assigneeLabels = new Map(assignees.map((option) => [option.id, option.label]));
|
||||
return {
|
||||
vm: buildAdminLeadSourcesVM({
|
||||
rows: sources.map((source) => ({
|
||||
id: source.id,
|
||||
key: source.key,
|
||||
displayName: source.displayName,
|
||||
enabled: source.enabled,
|
||||
defaultAssigneeAdminUserId: source.defaultAssigneeAdminUserId,
|
||||
defaultAssigneeLabel: source.defaultAssigneeAdminUserId ? (assigneeLabels.get(source.defaultAssigneeAdminUserId) ?? null) : null,
|
||||
notifyAdminUserIds: source.notifyAdminUserIds,
|
||||
notifyAdminUserLabels: source.notifyAdminUserIds.map((id) => assigneeLabels.get(id) ?? id),
|
||||
rateLimitPerMinute: source.rateLimitPerMinute,
|
||||
leadCount: source.leadCount,
|
||||
credentials: source.credentials,
|
||||
})),
|
||||
assigneeOptions: assignees,
|
||||
canAdmin: access.canAdmin,
|
||||
now: now.toISOString(),
|
||||
}),
|
||||
};
|
||||
});
|
||||
const session = await getUserInfo(request);
|
||||
return { ...data, csrf: session.csrf ?? "" };
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const expiresAtValue = String(form.get("expiresAt") ?? "").trim();
|
||||
const parsed = adminLeadSourceFormSchema.safeParse({
|
||||
intent,
|
||||
sourceId: form.get("sourceId"),
|
||||
credentialId: form.get("credentialId"),
|
||||
key: form.get("key"),
|
||||
displayName: form.get("displayName"),
|
||||
enabled: form.get("enabled") === "true",
|
||||
defaultAssigneeAdminUserId: form.get("defaultAssigneeAdminUserId") === "unassigned" ? undefined : form.get("defaultAssigneeAdminUserId"),
|
||||
notifyAdminUserIds: form.getAll("notifyAdminUserIds").map(String),
|
||||
rateLimitPerMinute: form.get("rateLimitPerMinute"),
|
||||
expiresAt: expiresAtValue || undefined,
|
||||
});
|
||||
const reason = String(form.get("reason") ?? "").trim();
|
||||
if (!parsed.success || (intent !== "create-source" && reason.length < 5)) {
|
||||
return Response.json({ error: t("admin.platformLeads.errors.invalidForm") } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
return await runAsPlatformLeadOperator(request, async ({ access, service }) => {
|
||||
requirePlatformLeadAdmin(access);
|
||||
const audit = access.audit(reason || "Platform lead source created");
|
||||
switch (parsed.data.intent) {
|
||||
case "create-source":
|
||||
await service.createSource({
|
||||
key: parsed.data.key,
|
||||
displayName: parsed.data.displayName,
|
||||
enabled: false,
|
||||
defaultAssigneeAdminUserId: parsed.data.defaultAssigneeAdminUserId ?? null,
|
||||
notifyAdminUserIds: parsed.data.notifyAdminUserIds,
|
||||
rateLimitPerMinute: parsed.data.rateLimitPerMinute,
|
||||
...audit,
|
||||
});
|
||||
return Response.json({ success: t("admin.platformLeads.feedback.sourceCreated") } satisfies ActionData);
|
||||
case "set-enabled":
|
||||
await service.updateSource({ sourceId: parsed.data.sourceId, enabled: parsed.data.enabled, ...audit });
|
||||
return Response.json({ success: t("admin.platformLeads.feedback.sourceUpdated") } satisfies ActionData);
|
||||
case "update-routing":
|
||||
await service.updateSource({
|
||||
sourceId: parsed.data.sourceId,
|
||||
defaultAssigneeAdminUserId: parsed.data.defaultAssigneeAdminUserId ?? null,
|
||||
notifyAdminUserIds: parsed.data.notifyAdminUserIds,
|
||||
rateLimitPerMinute: parsed.data.rateLimitPerMinute,
|
||||
...audit,
|
||||
});
|
||||
return Response.json({ success: t("admin.platformLeads.feedback.sourceUpdated") } satisfies ActionData);
|
||||
case "create-credential": {
|
||||
const issued = await service.createSourceCredential({
|
||||
sourceId: parsed.data.sourceId,
|
||||
expiresAt: parsed.data.expiresAt ?? null,
|
||||
...audit,
|
||||
});
|
||||
return Response.json({
|
||||
success: t("admin.platformLeads.feedback.credentialCreated"),
|
||||
revealedCredential: { sourceId: parsed.data.sourceId, plaintext: issued.secret },
|
||||
} satisfies ActionData);
|
||||
}
|
||||
case "rotate-credential": {
|
||||
const issued = await service.rotateSourceCredential({
|
||||
sourceId: parsed.data.sourceId,
|
||||
credentialId: parsed.data.credentialId,
|
||||
expiresAt: parsed.data.expiresAt ?? null,
|
||||
...audit,
|
||||
});
|
||||
return Response.json({
|
||||
success: t("admin.platformLeads.feedback.credentialRotated"),
|
||||
revealedCredential: { sourceId: parsed.data.sourceId, plaintext: issued.secret },
|
||||
} satisfies ActionData);
|
||||
}
|
||||
case "revoke-credential":
|
||||
await service.revokeSourceCredential({
|
||||
sourceId: parsed.data.sourceId,
|
||||
credentialId: parsed.data.credentialId,
|
||||
...audit,
|
||||
});
|
||||
return Response.json({ success: t("admin.platformLeads.feedback.credentialRevoked") } satisfies ActionData);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
return Response.json({ error: t("admin.platformLeads.errors.actionFailed") } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminPlatformLeadSourcesRoute(): React.JSX.Element {
|
||||
const data = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
return (
|
||||
<AdminPlatformLeadSourcesPage
|
||||
vm={{ ...data.vm, revealedCredential: actionData?.revealedCredential ?? null }}
|
||||
csrf={data.csrf}
|
||||
submitting={navigation.state === "submitting"}
|
||||
feedback={{ success: actionData?.success, error: actionData?.error }}
|
||||
actions={{
|
||||
onBack: () => void navigate(adminPath("leads", { mode: "host-aware" })),
|
||||
onSubmit: (input) => void submit(input, { method: "post" }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user