Skip to content
Merged
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
33 changes: 8 additions & 25 deletions app/platform/[projectId]/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -240,41 +240,24 @@ export default function DashboardPage() {
const endDate = period === "Custom" ? customEnd : malaysiaDateString();
if (!startDate || !endDate || startDate > endDate) throw new Error("Select a valid date range before exporting.");
const { data: { session } } = await supabase.auth.getSession();
if (!session?.access_token) throw new Error("Your session has expired. Please sign in again.");
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const publishableKey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY;
if (!supabaseUrl || !publishableKey) throw new Error("Supabase export configuration is missing.");

const response = await fetch(supabaseUrl.replace(/\/$/, "") + "/functions/v1/export-raw-responses", {
method: "POST",
headers: {
Authorization: "Bearer " + session.access_token,
apikey: publishableKey,
"Content-Type": "application/json",
},
body: JSON.stringify({ project_id: projectId, start_date: startDate, end_date: endDate, tracking_location: trackingLocation }),
if (!session) throw new Error("Your session has expired. Please sign in again.");
// Loaded on demand so the compression library is not part of the initial dashboard bundle.
const { buildRawExport } = await import("@/lib/raw-export");
const { blob, filename, total } = await buildRawExport(supabase, {
projectId, trackingLocation, startDate, endDate,
onProgress: (done, count) => setTrackingMessage("Preparing Excel: " + done.toLocaleString("en-US") + " / " + count.toLocaleString("en-US") + " responses"),
});
if (!response.ok) {
let message = "Unable to export raw AI responses.";
try {
const body = await response.json();
message = body?.error || body?.message || message;
} catch { /* response may not be JSON */ }
throw new Error(message);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
const disposition = response.headers.get("content-disposition");
const filename = disposition?.match(/filename="?([^";]+)"?/i)?.[1] || ("lifewood-raw-responses-" + startDate + "-to-" + endDate + ".xlsx");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
setTrackingMessage("Excel export prepared for " + startDate + " to " + endDate + ".");
setTrackingMessage("Excel export of " + total.toLocaleString("en-US") + " responses prepared for " + startDate + " to " + endDate + ".");
} catch (e) {
setTrackingMessage("");
setError(e instanceof Error ? e.message : String(e));
} finally {
setExporting(false);
Expand Down
6 changes: 4 additions & 2 deletions app/platform/[projectId]/responses/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { CalendarDays, ChevronDown, ChevronRight, Download, ExternalLink, FileText, Search } from "lucide-react";
import * as XLSX from "xlsx";
import { fitCell } from "@/lib/excel-cell";
import { ProjectShell } from "@/components/project-shell";
import { supabase } from "@/lib/supabase";
import { MIN_TRACKING_DATE, malaysiaDateString, shiftDateString, malaysiaDayStart, malaysiaDayEndExclusive } from "@/lib/reporting-date";
Expand Down Expand Up @@ -197,8 +198,9 @@ export default function ResponsesPage() {
Region: row.tracking_location ?? "",
Status: row.response_status,
Brand_Mentioned: row.response_status !== "completed" || !responseText(row).trim() ? "Unable to verify" : containsTrackedBrand(row) ? "Yes" : "No",
Response: responseText(row),
Raw_Response_JSON: row.raw_response == null ? "" : JSON.stringify(row.raw_response),
// Excel cells hold at most 32,767 characters; longer values are shortened here and complete in the dashboard export.
Response: fitCell(responseText(row)),
Raw_Response_JSON: fitCell(row.raw_response == null ? "" : JSON.stringify(row.raw_response)),
Error: row.error_message ?? "",
Run_ID: row.run_id ?? "",
Response_ID: row.id,
Expand Down
11 changes: 11 additions & 0 deletions lib/excel-cell.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const EXCEL_CELL_LIMIT = 32767;
const NOTE = "\n[Shortened to fit an Excel cell. Use Export Raw Data on the dashboard for the complete value.]";

/** Excel cannot store more than 32,767 characters in a cell. */
export function fitCell(value: string) {
if (value.length <= EXCEL_CELL_LIMIT) return value;
let end = EXCEL_CELL_LIMIT - NOTE.length;
const previous = value.charCodeAt(end - 1);
if (previous >= 0xd800 && previous <= 0xdbff) end -= 1;
return value.slice(0, end) + NOTE;
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
// Streaming raw-response workbook writer.
// Streaming raw-response workbook writer, run in the browser by lib/raw-export.ts.
//
// The export used to hold every response, its raw JSON, a second stringified copy, the chunk sheets and the finished
// XML in memory at once, which exceeded the Edge Function worker's limit once an export covered a few weeks of data.
// This writer fetches responses in small pages and writes each sheet straight into a streaming zip, so memory stays
// flat however many responses are exported. The workbook layout (sheets, columns, chunking) is unchanged.
// This used to run in a Supabase Edge Function. Large exports exceeded the function's CPU time limit after the
// download had already started, so the browser saved a cut-off file that Excel reported as corrupted.

export type ZipLib = {
// deno-lint-ignore no-explicit-any
Zip: new () => any;
// deno-lint-ignore no-explicit-any
ZipDeflate: new (name: string, opts?: { level?: number }) => any;
ZipDeflate: new (name: string, opts?: { level?: 1 }) => any;
strToU8: (value: string) => Uint8Array;
};

export type ResponseRow = Record<string, unknown>;
export type PromptRow = { prompt_number?: unknown; prompt?: unknown; category?: unknown; language?: unknown };

export type ExportSource = {
/** Pages of responses: "full" has every column, "raw" only id/prompt/captured_at/raw_response. */
pages: (kind: "full" | "raw") => AsyncIterable<ResponseRow[]>;
/** Pages of responses, oldest first. */
pages: () => AsyncIterable<ResponseRow[]>;
prompts: Map<string, PromptRow>;
};

Expand All @@ -32,17 +30,33 @@ export type ExportMeta = {

const MAX_CELL = 30000;
const FLUSH_AT = 256 * 1024;
// Excel refuses to open a worksheet with more hyperlinks than this, or with a longer link target.
export const MAX_SHEET_LINKS = 65530;
const MAX_LINK_LENGTH = 2079;
// Half of a surrogate pair on its own cannot be written as valid UTF-8 XML.
const LONE_SURROGATES = /\p{Surrogate}/gu;
const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;

/** Moves a cut back by one if it would split a surrogate pair (emoji, rarer Chinese characters). */
function cutPoint(value: string, index: number) {
if (index >= value.length) return value.length;
const previous = value.charCodeAt(index - 1);
return previous >= 0xd800 && previous <= 0xdbff ? index - 1 : index;
}

export function splitText(value: string, maxLength = MAX_CELL) {
if (!value) return [""];
const parts: string[] = [];
for (let i = 0; i < value.length; i += maxLength) parts.push(value.slice(i, i + maxLength));
for (let start = 0; start < value.length;) {
const end = cutPoint(value, start + maxLength);
parts.push(value.slice(start, end));
start = end;
}
return parts;
}

export function safeSheetText(value: string) {
return value.length <= 32767 ? value : value.slice(0, MAX_CELL) + "\n[Truncated in this cell; see the corresponding chunks sheet for the complete value.]";
return value.length <= 32767 ? value : value.slice(0, cutPoint(value, MAX_CELL)) + "\n[Truncated in this cell; see the corresponding chunks sheet for the complete value.]";
}

export function extractCitationLinks(raw: unknown, responseText: string) {
Expand Down Expand Up @@ -87,6 +101,7 @@ export function extractCitationLinks(raw: unknown, responseText: string) {
function xmlEscape(value: unknown) {
return String(value ?? "")
.replace(CONTROL_CHARS, "")
.replace(LONE_SURROGATES, "")
.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
.replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
Expand All @@ -104,6 +119,17 @@ function columnName(index: number) {

type Link = { ref: string; id: string; target: string };

/** The link target Excel will accept for a cell, or null to leave the cell as plain text. */
export function linkTarget(text: string) {
if (!/^https?:\/\/\S+$/i.test(text)) return null;
try {
const href = new URL(text).href;
return href.length <= MAX_LINK_LENGTH ? href : null;
} catch {
return null;
}
}

function rowXml(rowNumber: number, values: unknown[], linkColumn: number, links: Link[]) {
let cells = "";
for (let columnIndex = 0; columnIndex < values.length; columnIndex++) {
Expand All @@ -114,8 +140,9 @@ function rowXml(rowNumber: number, values: unknown[], linkColumn: number, links:
continue;
}
const text = String(value ?? "");
if (columnIndex === linkColumn && rowNumber > 1 && /^https?:\/\/\S+$/i.test(text)) {
links.push({ ref, id: "rId" + (links.length + 1), target: text });
if (columnIndex === linkColumn && rowNumber > 1 && links.length < MAX_SHEET_LINKS) {
const target = linkTarget(text);
if (target) links.push({ ref, id: "rId" + (links.length + 1), target });
}
cells += '<c r="' + ref + '" t="inlineStr"><is><t xml:space="preserve">' + xmlEscape(text) + "</t></is></c>";
}
Expand Down Expand Up @@ -171,13 +198,14 @@ export function streamWorkbook(lib: ZipLib, source: ExportSource, meta: ExportMe
];

async function run() {
// Pass 1: Raw Responses, streamed. Citation rows and the (rare) oversized text chunks are small and kept for the later sheets.
// Raw Responses is streamed. Citation rows and the (rare) oversized values are kept for the later sheets.
const citationRows: unknown[][] = [];
const textChunkRows: unknown[][] = [];
const jsonChunkRows: unknown[][] = [];
let total = 0, completed = 0, failed = 0;
const distinctPrompts = new Set<string>();
await addSheet(2, responseHeaders, -1, async (emit) => {
for await (const page of source.pages("full")) {
for await (const page of source.pages()) {
for (const row of page) {
total++;
if (row.response_status === "completed") completed++;
Expand All @@ -203,26 +231,18 @@ export function streamWorkbook(lib: ZipLib, source: ExportSource, meta: ExportMe
const chunks = splitText(text);
chunks.forEach((chunk, index) => textChunkRows.push([String(row.id ?? ""), prompt?.prompt_number ?? "", String(row.captured_at ?? ""), index + 1, chunks.length, chunk]));
}
if (rawJson.length > MAX_CELL) {
const chunks = splitText(rawJson);
chunks.forEach((chunk, index) => jsonChunkRows.push([String(row.id ?? ""), prompt?.prompt_number ?? "", String(row.captured_at ?? ""), index + 1, chunks.length, chunk]));
}
}
}
});

await addSheet(3, citationHeaders, 11, (emit) => { for (const values of citationRows) emit(values); });
await addSheet(4, ["Response_ID", "Prompt_No", "Captured_At", "Chunk_No", "Total_Chunks", "Response_Text_Chunk"], -1, (emit) => { for (const values of textChunkRows) emit(values); });

// Pass 2: complete raw JSON for responses whose JSON does not fit in one cell. Only these rows are written.
await addSheet(5, ["Response_ID", "Prompt_No", "Captured_At", "Chunk_No", "Total_Chunks", "Raw_JSON_Chunk"], -1, async (emit) => {
for await (const page of source.pages("raw")) {
for (const row of page) {
if (row.raw_response == null) continue;
const rawJson = JSON.stringify(row.raw_response);
if (rawJson.length <= MAX_CELL) continue;
const prompt = source.prompts.get(String(row.prompt_id ?? ""));
const chunks = splitText(rawJson);
chunks.forEach((chunk, index) => emit([String(row.id ?? ""), prompt?.prompt_number ?? "", String(row.captured_at ?? ""), index + 1, chunks.length, chunk]));
}
}
});
await addSheet(5, ["Response_ID", "Prompt_No", "Captured_At", "Chunk_No", "Total_Chunks", "Raw_JSON_Chunk"], -1, (emit) => { for (const values of jsonChunkRows) emit(values); });

const summary: unknown[][] = [
["Project", meta.brandName], ["Project ID", meta.projectId], ["Tracking Location", meta.trackingLocation],
Expand Down
94 changes: 94 additions & 0 deletions lib/raw-export.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import test from "node:test";
import assert from "node:assert/strict";
import { unzipSync, strFromU8 } from "fflate";
import type { SupabaseClient } from "@supabase/supabase-js";
import { buildRawExport } from "./raw-export.ts";
import { linkTarget, safeSheetText, splitText, MAX_SHEET_LINKS } from "./raw-export-xlsx.ts";
import { fitCell, EXCEL_CELL_LIMIT } from "./excel-cell.ts";

type Row = Record<string, unknown>;

/** Just enough of the Supabase query builder: results are served in the order the rows are given. */
function fakeClient(responses: Row[], options: { failAfter?: number; pageCap?: number; count?: number } = {}) {
let served = 0;
return {
from(table: string) {
let head = false, afterId = "", limit = Infinity;
const query = {
select(_: string, opts?: { head?: boolean }) { head = Boolean(opts?.head); return query; },
eq: () => query, gte: () => query, lt: () => query, order: () => query, single: () => query, range: () => query,
or(filter: string) { afterId = /id\.gt\.([^)]+)\)/.exec(filter)![1]; return query; },
limit(n: number) { limit = n; return query; },
then(resolve: (value: unknown) => unknown) {
if (table === "projects") return resolve({ data: { brand_name: "Dr D Signature Clinic" }, error: null });
if (table === "prompts") return resolve({ data: [{ id: "p1", prompt_number: 1, prompt: "Best clinic?", category: "Overall", language: "English" }], error: null });
if (head) return resolve({ data: null, error: null, count: options.count ?? responses.length });
if (options.failAfter !== undefined && served >= options.failAfter) return resolve({ data: null, error: { message: "boom" } });
const start = afterId ? responses.findIndex((row) => row.id === afterId) + 1 : 0;
const rows = responses.slice(start, start + Math.min(limit, options.pageCap ?? Infinity));
served += rows.length;
return resolve({ data: rows, error: null });
},
};
return query;
},
} as unknown as SupabaseClient;
}

const makeResponses = (n: number): Row[] => Array.from({ length: n }, (_, i) => ({
id: "r" + String(i).padStart(5, "0"), prompt_id: "p1", llm_provider: "openai", captured_at: "2026-11-01T00:00:00+00:00",
response_status: "completed", response_text: "See https://example.com/page-" + i, raw_response: { n: i }, tracking_location: "MY",
}));

const request = { projectId: "x", trackingLocation: "MY", startDate: "2026-10-01", endDate: "2026-12-04" };

async function open(blob: Blob) {
const files = unzipSync(new Uint8Array(await blob.arrayBuffer()));
return (name: string) => strFromU8(files[name]);
}

const rowCount = (xml: string) => xml.split("<row ").length - 1;

test("a large export is a complete workbook with every response", async () => {
const progress: number[] = [];
const result = await buildRawExport(fakeClient(makeResponses(4113)), { ...request, onProgress: (done) => progress.push(done) });
const read = await open(result.blob);
assert.equal(result.total, 4113);
assert.equal(rowCount(read("xl/worksheets/sheet2.xml")), 4114);
assert.equal(rowCount(read("xl/worksheets/sheet3.xml")), 4114);
assert.match(read("xl/workbook.xml"), /Raw JSON Chunks/);
assert.equal(progress.at(-1), 4113);
assert.equal(result.filename, "dr-d-signature-clinic-raw-responses-2026-10-01-to-2026-12-04.xlsx");
});

test("a server page cap smaller than the page size does not shorten the export", async () => {
const result = await buildRawExport(fakeClient(makeResponses(250), { pageCap: 90 }), request);
assert.equal(result.total, 250);
});

test("a failed or short read produces an error instead of a file", async () => {
await assert.rejects(buildRawExport(fakeClient(makeResponses(600), { failAfter: 200 }), request), /boom/);
await assert.rejects(buildRawExport(fakeClient(makeResponses(10), { count: 20 }), request), /only 10 of 20/);
});

test("oversized values are chunked without splitting characters and reassemble exactly", async () => {
const long = "a" + "😀中".repeat(30000);
assert.equal(splitText(long).join(""), long);
for (const part of [...splitText(long), safeSheetText(long)]) assert.doesNotMatch(part, /\p{Surrogate}/u);
assert.doesNotMatch(fitCell(long), /\p{Surrogate}/u);
assert.ok(fitCell(long).length <= EXCEL_CELL_LIMIT);
const [row] = makeResponses(1);
const read = await open((await buildRawExport(fakeClient([{ ...row, response_text: long, raw_response: { long } }]), request)).blob);
assert.ok(rowCount(read("xl/worksheets/sheet4.xml")) > 2);
assert.ok(rowCount(read("xl/worksheets/sheet5.xml")) > 2);
});

test("hyperlinks stay within what Excel accepts", async () => {
assert.equal(linkTarget("https://[broken"), null);
assert.equal(linkTarget("https://example.com/" + "a".repeat(3000)), null);
assert.equal(linkTarget("https://example.com/中"), "https://example.com/%E4%B8%AD");
const urls = Array.from({ length: MAX_SHEET_LINKS + 5 }, (_, i) => "https://e.com/" + i).join(" ");
const [row] = makeResponses(1);
const read = await open((await buildRawExport(fakeClient([{ ...row, response_text: urls }]), request)).blob);
assert.equal(read("xl/worksheets/sheet3.xml").split("<hyperlink ").length - 1, MAX_SHEET_LINKS);
});
Loading
Loading