Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,8 @@ the route-scoped Privy authentication provider.

- **Lead capture:** one browser client, `lib/leads/postLead.ts`, posts to `POST /api/leads` on the Recoup API, which owns CRM storage and notifications. Subscribe surfaces call it through `lib/marketing-subscribe.ts`; the music-video quote form calls it directly. Inquiry forms post to the same-origin `/api/inquiries` proxy (`lib/inquiries/`), which validates `source` against `lib/inquiry/inquirySourceSchema.ts`, de-duplicates, forwards `kind: booking`, and returns `{ ok: true, submission_id }`. Marketing holds no Attio client and no `ATTIO_API_KEY`. The API base is `siteConfig.apiUrl` in `lib/config.ts`; preserve its environment selection rather than hardcoding a host.
- **Attribution:** one store, `lib/attribution/` (`recoup:acquisition:v1` in sessionStorage, first + latest tagged visit). Forms read it with `currentReferralAttribution()`; CRM notes render it via `describeAcquisitionTags()` as `source=x; medium=y; campaign=z` (no underscores, Attio notes are markdown). App links go through `lib/appLink.ts` / `<AppLink>` and carry `utm_source=marketing&utm_medium=<placement>&utm_campaign=sky`, the visitor's own tags winning.
- **Analytics:** Vercel Web Analytics (`<Analytics />` in `app/layout.tsx`); custom events go through `lib/analytics/trackEvent.ts` only, and props never carry visitor details. Funnel events: `cta_clicked {cta, placement, plan?}` (`<TrackedLink>`), `pricing_billing_toggled {billing}`, `inquiry_started {source, plan?}`, `inquiry_submitted {source, plan?, budget?, timeline?, company_type?, submission_id}`, `inquiry_failed {source, reason: validation|network|rejected|timeout}`, `subscribe_submitted {source}`, `audit_completed {score}`, `roi_calculated {recommended_plan}`, `podcast_platform_clicked {platform}`, `podcast_episode_clicked {slug, platform}`, `podcast_guest_requested {placement}`.
- **Analytics:** Vercel Web Analytics (`<Analytics />` in `app/layout.tsx`); custom events go through `lib/analytics/trackEvent.ts` only, and props never carry visitor details. Funnel events: `cta_clicked {cta, placement, plan?}` (`<TrackedLink>`), `pricing_billing_toggled {billing}`, `inquiry_started {source, plan?}`, `inquiry_submitted {source, plan?, budget?, timeline?, company_type?, submission_id}`, `inquiry_rejected {source, reason: validation|blocked, http_status}` (0 means client validation), `inquiry_failed {source, reason: unavailable|invalid_receipt|network|timeout, http_status?}`, `subscribe_submitted {source}`, `audit_completed {score}`, `roi_calculated {recommended_plan}`, `podcast_platform_clicked {platform}`, `podcast_episode_clicked {slug, platform}`, `podcast_guest_requested {placement}`.
- **Inquiry diagnostics:** `/api/inquiries` errors include an allowlisted `code`; server logs contain only status/code. `readInquiryFailure` maps these to fixed recovery copy and analytics. Never forward response text, visitor fields or provider errors to analytics. Historical `inquiry_failed` events before this change mixed validation/blocking with delivery failures; do not reclassify them without evidence. The hook locks in-flight submits synchronously and waits 25 seconds, allowing the server's 20-second upstream deadline to return. A success event still requires the exact saved receipt.
- **Background work:** new platform scheduled/background jobs belong in API Vercel Workflows under Mono's architecture rules. Existing Trigger.dev jobs and Marketing's `workflows/` helpers are retained implementations, not the default location for new platform jobs.

## Code Principles
Expand Down
6 changes: 6 additions & 0 deletions content/STATUS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## Inquiry delivery diagnostics — October 25, 2026

Separated invalid/blocked submissions (`inquiry_rejected`) from delivery failures (`inquiry_failed`), added safe HTTP-status/error-code diagnostics, and preserved the exact CRM-backed success receipt. The shared hook now locks concurrent submissions before a render and gives the server timeout time to return. Existing recovery UI retains the inquiry and presents fixed, actionable error copy.

Controlled production HTTP submissions through `/contact` and `/start-project` returned valid receipts, and their corresponding notes were read back in the CRM. This verifies current HTTP-to-CRM delivery, not every browser interaction or the cause of historical rejected traffic. Private test receipts remain in Business. 74 focused tests, scoped ESLint, TypeScript and the production build (115 pages) pass. Code changes are pending review/deployment; historical failure totals cannot be retrospectively reclassified.

## Files account-scope release reconciliation — October 25, 2026

The public Files reference, scoped examples, producer tests and generated artifacts
Expand Down
32 changes: 32 additions & 0 deletions hooks/useInquirySubmit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { afterEach, expect, it, vi } from "vitest";
import type { FormEvent } from "react";
import { useInquirySubmit } from "./useInquirySubmit";
import { trackInquiryConversion } from "@/lib/analytics/trackInquiryConversion";
import { trackEvent } from "@/lib/analytics/trackEvent";

vi.mock("react", () => ({ useRef: (current: unknown) => ({ current }), useState: (value: unknown) => [value, vi.fn()] }));
vi.mock("@/lib/analytics/trackEvent", () => ({ trackEvent: vi.fn() }));
Expand Down Expand Up @@ -40,3 +41,34 @@ it("does not report email fallback as a delivered inquiry", async () => {
expect(fetch).not.toHaveBeenCalled();
expect(trackInquiryConversion).not.toHaveBeenCalled();
});

it.each([
[400, { ok: false, code: "validation" }, "inquiry_rejected", "validation"],
[400, { ok: false, code: "blocked" }, "inquiry_rejected", "blocked"],
[403, { ok: false }, "inquiry_rejected", "blocked"],
[503, { ok: false, code: "unavailable" }, "inquiry_failed", "unavailable"],
[503, { ok: false, code: "timeout" }, "inquiry_failed", "timeout"],
[200, { ok: true }, "inquiry_failed", "invalid_receipt"],
] as const)("classifies HTTP %s separately from confirmed delivery", async (status, body, event, reason) => {
await submit(Response.json(body, { status }));
expect(trackEvent).toHaveBeenCalledWith(event, { source: "/contact", reason, http_status: status });
expect(trackEvent).not.toHaveBeenCalledWith("inquiry_submitted", expect.anything());
});

it("locks concurrent submissions before React rerenders, then permits an explicit retry", async () => {
vi.stubGlobal("FormData", class { entries() { return Object.entries({ name: "Test", email: "test@example.com", message: "test" }); } });
let finish!: (response: Response) => void;
const transport = vi.fn().mockImplementationOnce(() => new Promise<Response>(resolve => { finish = resolve; }))
.mockResolvedValueOnce(Response.json({ ok: true, submission_id: "b".repeat(64) }));
vi.stubGlobal("fetch", transport);
const form = useInquirySubmit({ source: "/contact", connected: true, qualified: false, websitePath: "/contact" });
const event = { preventDefault: vi.fn(), currentTarget: {} } as unknown as FormEvent<HTMLFormElement>;
const first = form.submit(event);
const second = form.submit(event);
expect(transport).toHaveBeenCalledTimes(1);
finish(Response.json({ ok: false }, { status: 503 }));
await Promise.all([first, second]);
await form.submit(event);
expect(transport).toHaveBeenCalledTimes(2);
expect(trackInquiryConversion).toHaveBeenCalledExactlyOnceWith("b".repeat(64));
});
19 changes: 15 additions & 4 deletions hooks/useInquirySubmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { currentReferralAttribution } from "@/lib/attribution/currentReferralAtt
import { inquiryMessageWithContext } from "@/lib/attribution/inquiryMessageWithContext";
import { prepareInquiryEmail } from "@/lib/inquiry/prepareInquiryEmail";
import { readInquiryReceipt } from "@/lib/inquiry/readInquiryReceipt";
import { readInquiryFailure } from "@/lib/inquiry/readInquiryFailure";
import type { InquirySource } from "@/lib/inquiry/inquirySourceSchema";
import { validateLeadQualification, type LeadQualification } from "@/lib/lead-qualification";
import { siteConfig } from "@/lib/config";
Expand All @@ -20,6 +21,7 @@ const qualificationKeys = ["companyType", "role", "companyWebsite", "phone", "bu
/** Owns the submission lifecycle and the funnel events tied to it; no visitor details reach analytics. */
export function useInquirySubmit({ source, plan, connected, qualified, compact = false, websitePath, pricingContext }: Options) {
const startedAt = useRef(0);
const pending = useRef(false);
const [status, setStatus] = useState<InquiryStatus>("idle");
const [preparedEmail, setPreparedEmail] = useState<PreparedEmail | null>(null);
const [qualificationError, setQualificationError] = useState<string | null>(null);
Expand All @@ -44,7 +46,8 @@ export function useInquirySubmit({ source, plan, connected, qualified, compact =
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (status === "sending") return;
if (pending.current || status === "sending") return;
markStarted();
const fields = Object.fromEntries(new FormData(event.currentTarget).entries());
const text = (key: string) => String(fields[key] ?? "");
let qualification: LeadQualification | undefined;
Expand All @@ -53,7 +56,7 @@ export function useInquirySubmit({ source, plan, connected, qualified, compact =
qualification = validateLeadQualification(Object.fromEntries(qualificationKeys.map((key) => [key, text(key)])), { requireCompanyType: !compact });
} catch (error) {
setQualificationError(error instanceof Error ? error.message : "Please check the company and project details.");
trackEvent("inquiry_failed", { source, reason: "validation" });
trackEvent("inquiry_rejected", { source, reason: "validation", http_status: 0 });
return;
}
}
Expand All @@ -68,17 +71,23 @@ export function useInquirySubmit({ source, plan, connected, qualified, compact =
setStatus("email");
return;
}
// A ref closes the interval before React rerenders the disabled button.
pending.current = true;
setStatus("sending");
setQualificationError(null);
try {
const response = await fetch("/api/inquiries", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...data, source, website: text("website"), startedAt: startedAt.current || Date.now() - 5000 }),
signal: AbortSignal.timeout(20000),
// Give the server's 20-second upstream timeout time to return its diagnosis.
signal: AbortSignal.timeout(25000),
});
const receipt = await readInquiryReceipt(response);
if (!receipt) {
trackEvent("inquiry_failed", { source, reason: "rejected" });
const failure = await readInquiryFailure(response);
trackEvent(failure.event, { source, reason: failure.reason, http_status: response.status });
setQualificationError(failure.message);
setStatus("error");
return;
}
Expand All @@ -92,6 +101,8 @@ export function useInquirySubmit({ source, plan, connected, qualified, compact =
const timedOut = error instanceof DOMException && error.name === "TimeoutError";
trackEvent("inquiry_failed", { source, reason: timedOut ? "timeout" : "network" });
setStatus("error");
} finally {
pending.current = false;
}
}
return { status, preparedEmail, qualificationError, submit, reset, clearFeedback, markStarted };
Expand Down
4 changes: 3 additions & 1 deletion lib/inquiries/InquiryError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ const UNAVAILABLE_MESSAGE = "We couldn't save your inquiry. Please try again, or

export class InquiryError extends Error {
readonly status: number;
readonly code: "validation" | "blocked" | "unavailable" | "timeout";

constructor(status: number, message = INVALID_MESSAGE) {
constructor(status: number, message = INVALID_MESSAGE, code?: InquiryError["code"]) {
super(message);
this.status = status;
this.code = code ?? (status >= 500 ? "unavailable" : status === 403 ? "blocked" : "validation");
}

/** The CRM could not be reached or did not confirm the save. */
Expand Down
28 changes: 27 additions & 1 deletion lib/inquiries/__tests__/createInquiryHandler.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { createInquiryHandler } from "../createInquiryHandler";

const now = 1_800_000_000_000;
Expand Down Expand Up @@ -29,6 +29,32 @@ function handler() {
}

describe("createInquiryHandler", () => {
it("distinguishes validation and blocked requests without forwarding either to the CRM", async () => {
const { handle, calls } = handler();
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
expect(await (await handle(request({ ...valid, email: "invalid" }))).json()).toMatchObject({ ok: false, code: "validation" });
expect(await (await handle(request({ ...valid, website: "https://spam.test" }))).json()).toMatchObject({ ok: false, code: "blocked" });
expect(calls).toHaveLength(0);
expect(JSON.stringify(warning.mock.calls)).not.toContain(valid.email);
expect(JSON.stringify(warning.mock.calls)).not.toContain("spam.test");
expect(warning).toHaveBeenCalledWith("[inquiries] rejected", { status: 400, code: "blocked" });
} finally { warning.mockRestore(); }
});

it.each([
[new DOMException("Timed out", "TimeoutError"), "timeout"],
[new Error("provider payload including private@example.com"), "unavailable"],
])("returns safe diagnostics for transport errors", async (error, code) => {
const handle = createInquiryHandler({ getApiUrl: () => "https://api.recoup.test/api", now: () => now, fetch: async () => { throw error; } });
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
const response = await handle(request(valid));
expect(response.status).toBe(503);
expect(await response.json()).toMatchObject({ ok: false, code });
expect(JSON.stringify(warning.mock.calls)).not.toContain("private@example.com");
} finally { warning.mockRestore(); }
});
it("forwards the page the visitor submitted from as the lead source", async () => {
const { handle, calls } = handler();
expect((await handle(request(valid))).status).toBe(200);
Expand Down
5 changes: 4 additions & 1 deletion lib/inquiries/createInquiryHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@ export function createInquiryHandler(options: InquiryOptions) {
} catch (error) {
const status = error instanceof InquiryError ? error.status : 503;
const message = error instanceof InquiryError ? error.message : InquiryError.unavailable().message;
const code = error instanceof InquiryError ? error.code
: error instanceof Error && error.name === "TimeoutError" ? "timeout" : "unavailable";
// Deliberately do not log request bodies, provider errors, or credentials.
return Response.json({ ok: false, error: message }, { status, headers });
console.warn("[inquiries] rejected", { status, code });
return Response.json({ ok: false, error: message, code }, { status, headers });
}
};
}
2 changes: 1 addition & 1 deletion lib/inquiries/validateInquiry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function isObject(value: unknown): value is Record<string, unknown> {

export function validateInquiry(input: unknown, now = Date.now()): Inquiry {
if (!isObject(input)) throw new InquiryError(400);
if (input.website !== "") throw new InquiryError(400);
if (input.website !== "") throw new InquiryError(400, undefined, "blocked");
const source = inquirySourceSchema.safeParse(input.source);
if (!source.success) throw new InquiryError(400);
const compactProject = source.data === "/start-project" && input.interest !== podcastGuestInterest;
Expand Down
24 changes: 24 additions & 0 deletions lib/inquiry/__tests__/readInquiryFailure.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { readInquiryFailure } from "../readInquiryFailure";

describe("readInquiryFailure", () => {
it("never displays or tracks arbitrary response text", async () => {
const failure = await readInquiryFailure(Response.json({ ok: false, code: "someone@example.com", error: "provider secret" }, { status: 400 }));
expect(failure.reason).toBe("validation");
expect(JSON.stringify(failure)).not.toContain("someone@example.com");
expect(JSON.stringify(failure)).not.toContain("provider secret");
});

it("does not let an unexpected code reclassify a server outage as a rejection", async () => {
expect(await readInquiryFailure(Response.json({ ok: false, code: "blocked" }, { status: 503 })))
.toMatchObject({ event: "inquiry_failed", reason: "unavailable" });
});

it("handles non-JSON gateway errors and an already-consumed invalid receipt", async () => {
expect(await readInquiryFailure(new Response("Gateway error", { status: 502 })))
.toMatchObject({ event: "inquiry_failed", reason: "unavailable" });
const response = Response.json({ ok: true });
await response.json();
expect(await readInquiryFailure(response)).toMatchObject({ event: "inquiry_failed", reason: "invalid_receipt" });
});
});
20 changes: 20 additions & 0 deletions lib/inquiry/readInquiryFailure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
type InquiryFailure = {
event: "inquiry_rejected" | "inquiry_failed";
reason: "validation" | "blocked" | "unavailable" | "timeout" | "invalid_receipt";
message: string;
};

/** Read only allowlisted codes; provider bodies and visitor details never become analytics props or UI copy. */
export async function readInquiryFailure(response: Response): Promise<InquiryFailure> {
// A malformed 200 may already have been consumed by readInquiryReceipt.
const body: unknown = response.status === 200 ? null : await response.json().catch(() => null);
const code = body && typeof body === "object" && "ok" in body && body.ok === false && "code" in body ? body.code : undefined;
if (response.status === 403 || response.status === 429 || (response.status === 400 && code === "blocked")) {
return { event: "inquiry_rejected", reason: "blocked", message: "This submission was blocked. Your details are still here; try again or use the email option below." };
}
if ([400, 413, 415, 422].includes(response.status)) {
return { event: "inquiry_rejected", reason: "validation", message: "Please check your email and required fields, then try again. Your details are still here." };
}
const reason = response.status >= 500 ? code === "timeout" ? "timeout" : "unavailable" : "invalid_receipt";
return { event: "inquiry_failed", reason, message: "We couldn't confirm delivery. Your details are still here; try again or use the email option below." };
}
Loading