Implementa o MVP do Adaptador de Planilhas no Elo Pro.

O módulo usa a identidade Supabase, isola cada workspace e registra storage, TTL, runner e biblioteca XLSX como decisões ainda abertas.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
camilafagundesandCursor committed 2026-10-02 23:02:00 -03:00
commit 6e23f1533b
144 files changed
+19060

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
import { redirect } from "next/navigation";
import { SettingsPanel } from "@/components/settings-panel";
import { AppShell } from "@/components/shell";
import { ErrorState } from "@/components/states";
import { canManageSpreadsheetModels } from "@/domain/spreadsheet-adapter/permissions";
import { resolveAuth } from "@/server/auth/context";
export const dynamic = "force-dynamic";
export default async function SettingsPage() {
const auth = await resolveAuth();
if (auth.kind === "anonymous") redirect("/login");
if (auth.kind !== "ok" || !auth.ctx.moduleEnabled) redirect("/adaptador");
if (!canManageSpreadsheetModels(auth.ctx)) {
return (
<AppShell ctx={auth.ctx}>
<ErrorState message="Somente owner ou admin acessam as configurações do Adaptador." />
</AppShell>
);
}
return (
<AppShell ctx={auth.ctx}>
<SettingsPanel ctx={auth.ctx} />
</AppShell>
);
}
+17
View File
@@ -0,0 +1,17 @@
"use client";
import { useEffect } from "react";
export default function AdapterError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
useEffect(() => {
console.error("adaptador", error.digest ?? error.name);
}, [error]);
return (
<main className="p-8">
<h1 className="text-2xl font-semibold">Algo saiu do esperado</h1>
<p className="mt-2 text-sm">A operação foi interrompida. Você pode tentar de novo sem perder a sessão do Elo Pro.</p>
{error.digest ? <p className="mt-2 text-xs">Referência {error.digest}</p> : null}
<button type="button" className="mt-4 underline" onClick={reset}>Tentar novamente</button>
</main>
);
}
+8
View File
@@ -0,0 +1,8 @@
import type { ReactNode } from "react";
import { Providers } from "@/components/providers";
export const dynamic = "force-dynamic";
export default function AdapterLayout({ children }: { children: ReactNode }) {
return <Providers>{children}</Providers>;
}
+9
View File
@@ -0,0 +1,9 @@
import { LoadingBlock } from "@/components/states";
export default function Loading() {
return (
<main className="p-8">
<LoadingBlock label="Abrindo o Adaptador" />
</main>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { redirect } from "next/navigation";
import { Operation } from "@/components/operation";
import { AppShell } from "@/components/shell";
import { resolveAuth } from "@/server/auth/context";
export const dynamic = "force-dynamic";
export default async function OperationPage() {
const auth = await resolveAuth();
if (auth.kind === "anonymous") redirect("/login");
if (auth.kind !== "ok" || !auth.ctx.moduleEnabled) redirect("/adaptador");
return (
<AppShell ctx={auth.ctx}>
<Operation ctx={auth.ctx} />
</AppShell>
);
}
+35
View File
@@ -0,0 +1,35 @@
import { redirect } from "next/navigation";
import { Dashboard } from "@/components/dashboard";
import { AppShell } from "@/components/shell";
import { ErrorState } from "@/components/states";
import { Card } from "@/components/ui";
import { resolveAuth } from "@/server/auth/context";
export const dynamic = "force-dynamic";
export default async function AdapterHome() {
const auth = await resolveAuth();
if (auth.kind === "anonymous") redirect("/login");
if (auth.kind !== "ok") {
return (
<main className="p-8">
<ErrorState message={auth.kind === "no_workspace" ? "O Elo Pro ainda não informou o workspace ativo." : "Você não é membro deste workspace."} />
</main>
);
}
if (!auth.ctx.moduleEnabled) {
return (
<AppShell ctx={auth.ctx}>
<Card>
<h1 className="text-2xl font-semibold">Módulo não habilitado</h1>
<p className="mt-2 text-sm">O Adaptador está desligado para este workspace. A habilitação é feita na plataforma Elo Pro.</p>
</Card>
</AppShell>
);
}
return (
<AppShell ctx={auth.ctx}>
<Dashboard ctx={auth.ctx} />
</AppShell>
);
}
+24
View File
@@ -0,0 +1,24 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { createServerClient } from "@supabase/ssr";
export const runtime = "nodejs";
export async function POST() {
const jar = await cookies();
jar.delete("adapter_dev_session");
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
if (url && key) {
const supabase = createServerClient(url, key, {
cookies: {
getAll: () => jar.getAll(),
setAll: (items) => {
for (const item of items) jar.set(item.name, item.value, item.options);
},
},
});
await supabase.auth.signOut();
}
return NextResponse.json({ ok: true });
}
+29
View File
@@ -0,0 +1,29 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { getDb } from "@/infra/db/client";
import { ensureDevFixtures } from "@/dev/fixtures";
import { devAuthEnabled, signDevSession } from "@/server/auth/dev-session";
export const runtime = "nodejs";
export async function POST(request: Request) {
if (!devAuthEnabled()) return NextResponse.json({ error: { code: "NOT_FOUND", message: "Indisponível." } }, { status: 404 });
const body = (await request.json()) as { userId?: string; workspaceId?: string };
if (!body.userId || !body.workspaceId) {
return NextResponse.json({ error: { code: "UNAUTHENTICATED", message: "Identidade incompleta." } }, { status: 400 });
}
const db = await getDb();
await ensureDevFixtures(db);
const members = await db.withService((query) =>
query.query(`select role from public.workspace_members where user_id = $1 and workspace_id = $2`, [body.userId, body.workspaceId]),
);
if (!members[0]) return NextResponse.json({ error: { code: "WORKSPACE_FORBIDDEN", message: "Vínculo não encontrado." } }, { status: 403 });
const jar = await cookies();
jar.set("adapter_dev_session", signDevSession(body.userId, body.workspaceId), {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 8,
});
return NextResponse.json({ ok: true });
}
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { getDb } from "@/infra/db/client";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const db = await getDb();
await db.withService((query) => query.query("select 1 as ok"));
return NextResponse.json({
ok: true,
module: "spreadsheet-adapter",
redis: process.env.REDIS_URL ? "configured" : "not_configured",
storage: process.env.SUPABASE_STORAGE_BUCKET ? "supabase" : "unconfigured",
});
} catch {
return NextResponse.json({ ok: false }, { status: 503 });
}
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server";
import { AdapterError, isAdapterError } from "@/domain/spreadsheet-adapter/errors";
import type { RequestContext } from "@/domain/spreadsheet-adapter/types";
import { resolveAuth } from "@/server/auth/context";
import type { AppDeps } from "@/server/spreadsheet-adapter/deps";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export function errorResponse(error: unknown): NextResponse {
if (isAdapterError(error)) {
return NextResponse.json(
{ error: { code: error.code, message: error.message, details: error.details ?? null } },
{ status: error.status },
);
}
console.error("spreadsheet-adapter", error instanceof Error ? error.name : "error");
return NextResponse.json({ error: { code: "INTERNAL", message: "Erro interno." } }, { status: 500 });
}
export async function requireReady(): Promise<{ ctx: RequestContext; deps: AppDeps }> {
const auth = await resolveAuth();
if (auth.kind === "anonymous") throw new AdapterError("UNAUTHENTICATED", "Sessão Elo Pro necessária.", 401);
if (auth.kind !== "ok") throw new AdapterError("WORKSPACE_FORBIDDEN", "Workspace não autorizado.", 403);
const { runtimeDeps } = await import("@/server/spreadsheet-adapter/runtime");
return { ctx: auth.ctx, deps: await runtimeDeps() };
}
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../../_lib";
import { downloadOutput } from "@/server/spreadsheet-adapter/process-job";
import type { OutputFormat } from "@/domain/spreadsheet-adapter/types";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id } = await context.params;
const url = new URL(request.url);
const format = url.searchParams.get("format") as OutputFormat | null;
const sourceId = url.searchParams.get("sourceId");
if (!sourceId || (format !== "xlsx" && format !== "csv" && format !== "pdf")) {
return NextResponse.json({ error: { code: "INVALID_FORMAT", message: "Escolha XLSX, CSV ou PDF." } }, { status: 400 });
}
const file = await downloadOutput(deps, ctx, id, sourceId, format);
return new NextResponse(new Uint8Array(file.body), {
headers: {
"Content-Type": file.contentType,
"Content-Disposition": `attachment; filename="${file.filename}"`,
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
},
});
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../../_lib";
import { rejectWorkspaceForgery, saveMappings } from "@/server/spreadsheet-adapter/service";
import type { MappingInput } from "@/server/spreadsheet-adapter/dto";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id } = await context.params;
const body = (await request.json()) as { sourceId?: string; mappings?: MappingInput[]; workspace_id?: string };
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
if (!body.sourceId || !Array.isArray(body.mappings)) {
return NextResponse.json({ error: { code: "MAPPING_INCOMPLETE", message: "Informe o mapeamento." } }, { status: 400 });
}
return NextResponse.json({ job: await saveMappings(deps, ctx, id, body.sourceId, body.mappings) });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../../_lib";
import { previewSource, rejectWorkspaceForgery } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id } = await context.params;
const body = (await request.json()) as { sourceId?: string; workspace_id?: string };
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
if (!body.sourceId) return NextResponse.json({ error: { code: "NOT_FOUND", message: "Informe a fonte." } }, { status: 400 });
return NextResponse.json(await previewSource(deps, ctx, id, body.sourceId));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../../_lib";
import { rejectWorkspaceForgery, startProcess } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id } = await context.params;
const body = (await request.json()) as { sourceId?: string; idempotencyKey?: string; workspace_id?: string };
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
if (!body.sourceId || !body.idempotencyKey) {
return NextResponse.json({ error: { code: "IDEMPOTENCY_REQUIRED", message: "Informe a fonte e a chave de idempotência." } }, { status: 400 });
}
const job = await startProcess(deps, ctx, id, body.sourceId, body.idempotencyKey);
return NextResponse.json({ job });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../_lib";
import { getJob } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(_request: Request, context: { params: Promise<{ id: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id } = await context.params;
return NextResponse.json({ job: await getJob(deps, ctx, id) });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../../../_lib";
import { rejectWorkspaceForgery, removeSource, updateSource } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function PATCH(request: Request, context: { params: Promise<{ id: string; sourceId: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id, sourceId } = await context.params;
const body = (await request.json()) as { sheet?: string | null; headerRow?: number; workspace_id?: string };
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
const result = await updateSource(deps, ctx, id, sourceId, { sheet: body.sheet, headerRow: body.headerRow });
return NextResponse.json(result, { status: result.httpStatus });
} catch (error) {
return errorResponse(error);
}
}
export async function DELETE(request: Request, context: { params: Promise<{ id: string; sourceId: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id, sourceId } = await context.params;
const body = await request.json().catch(() => ({}));
await rejectWorkspaceForgery(deps, ctx, (body as { workspace_id?: string }).workspace_id);
return NextResponse.json({ job: await removeSource(deps, ctx, id, sourceId) });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../_lib";
import { createJob, rejectWorkspaceForgery } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
try {
const { ctx, deps } = await requireReady();
const body = (await request.json()) as { modelId?: string; idempotencyKey?: string; workspace_id?: string };
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
if (!body.modelId) return NextResponse.json({ error: { code: "NOT_FOUND", message: "Selecione um modelo." } }, { status: 400 });
const job = await createJob(deps, ctx, body.modelId, body.idempotencyKey);
return NextResponse.json({ job }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../_lib";
import { deleteModel, rejectWorkspaceForgery } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
try {
const { ctx, deps } = await requireReady();
const { id } = await context.params;
const body = await request.json().catch(() => ({}));
await rejectWorkspaceForgery(deps, ctx, (body as { workspace_id?: string }).workspace_id);
await deleteModel(deps, ctx, id);
return NextResponse.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,40 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../_lib";
import { createModel, listModels, rejectWorkspaceForgery } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const { ctx, deps } = await requireReady();
return NextResponse.json({ models: await listModels(deps, ctx) });
} catch (error) {
return errorResponse(error);
}
}
export async function POST(request: Request) {
try {
const { ctx, deps } = await requireReady();
const form = await request.formData();
await rejectWorkspaceForgery(deps, ctx, form.get("workspace_id"));
const file = form.get("file");
if (!(file instanceof File)) return errorResponse(new Error("arquivo"));
const requiredRaw = form.get("requiredColumns");
const model = await createModel(deps, ctx, {
name: String(form.get("name") ?? ""),
filename: file.name,
bytes: Buffer.from(await file.arrayBuffer()),
sheet: form.get("sheet") ? String(form.get("sheet")) : null,
headerRow: Number(form.get("headerRow") ?? 1),
requiredColumns: requiredRaw ? (JSON.parse(String(requiredRaw)) as string[]) : undefined,
});
return NextResponse.json({ model }, { status: 201 });
} catch (error) {
if (error instanceof Error && error.message === "arquivo") {
return NextResponse.json({ error: { code: "EMPTY_FILE", message: "Selecione um arquivo." } }, { status: 400 });
}
return errorResponse(error);
}
}
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../_lib";
import { getSettings, rejectWorkspaceForgery, updateSettings } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const { ctx, deps } = await requireReady();
return NextResponse.json(await getSettings(deps, ctx));
} catch (error) {
return errorResponse(error);
}
}
export async function PATCH(request: Request) {
try {
const { ctx, deps } = await requireReady();
const body = (await request.json()) as { allowNonAdminModelUpload?: boolean; workspace_id?: string };
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
if (typeof body.allowNonAdminModelUpload !== "boolean") {
return NextResponse.json({ error: { code: "INVALID_SETTING", message: "Informe o valor da configuração." } }, { status: 400 });
}
await updateSettings(deps, ctx, body.allowNonAdminModelUpload);
return NextResponse.json(await getSettings(deps, ctx));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { errorResponse, requireReady } from "../../_lib";
import { addSource, rejectWorkspaceForgery } from "@/server/spreadsheet-adapter/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
try {
const { ctx, deps } = await requireReady();
const form = await request.formData();
await rejectWorkspaceForgery(deps, ctx, form.get("workspace_id"));
const file = form.get("file");
const jobId = String(form.get("jobId") ?? "");
if (!(file instanceof File) || !jobId) {
return NextResponse.json({ error: { code: "EMPTY_FILE", message: "Envie o arquivo e a operação." } }, { status: 400 });
}
const result = await addSource(
deps,
ctx,
jobId,
{ filename: file.name, bytes: Buffer.from(await file.arrayBuffer()) },
form.get("sheet") ? String(form.get("sheet")) : null,
Number(form.get("headerRow") ?? 1),
);
return NextResponse.json(result, { status: result.httpStatus });
} catch (error) {
return errorResponse(error);
}
}
+31
View File
@@ -0,0 +1,31 @@
@import "tailwindcss";
@theme {
--font-sans: var(--font-manrope), "Manrope", sans-serif;
--color-cloud: #fbfbfe;
--color-ink: #071b45;
--color-action: #0b3d91;
--color-bright: #2f8fff;
--color-aqua: #00c2a8;
--color-warning: #f39a2d;
--color-danger: #e63946;
--color-line: #e4e7f2;
}
body {
background: var(--color-cloud);
color: var(--color-ink);
font-family: var(--font-sans);
}
:focus-visible {
outline: 2px solid var(--color-bright);
outline-offset: 2px;
}
button:disabled,
input:disabled,
select:disabled {
cursor: not-allowed;
opacity: 0.55;
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { Manrope } from "next/font/google";
import "./globals.css";
const manrope = Manrope({ subsets: ["latin"], variable: "--font-manrope" });
export const metadata: Metadata = {
title: "Adaptador de Planilhas · Elo Pro",
description: "Módulo Elo Pro para padronizar planilhas sem alterar o modelo original.",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="pt-BR">
<body className={manrope.variable}>{children}</body>
</html>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { redirect } from "next/navigation";
import { DEV_IDENTITIES } from "@/dev/fixtures";
import { resolveAuth } from "@/server/auth/context";
import { devAuthEnabled } from "@/server/auth/dev-session";
import { DevLogin } from "@/components/dev-login";
export const dynamic = "force-dynamic";
export default async function LoginPage() {
const auth = await resolveAuth();
if (auth.kind === "ok") redirect("/adaptador");
if (!devAuthEnabled() && process.env.ELO_PRO_LOGIN_URL) redirect(process.env.ELO_PRO_LOGIN_URL);
return (
<main className="mx-auto max-w-xl p-8">
<p className="text-xs font-semibold tracking-wide text-bright">ELO PRO</p>
<h1 className="mt-2 text-3xl font-semibold">Entrar no ecossistema</h1>
<p className="mt-3 text-sm text-ink/80">
O Adaptador não cria senha, cadastro ou sessão própria. A identidade é a do Elo Pro.
</p>
{devAuthEnabled() ? <DevLogin identities={DEV_IDENTITIES} /> : <p className="mt-6 text-sm">Defina ELO_PRO_LOGIN_URL com o endereço do login central.</p>}
</main>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function HomePage() {
redirect("/adaptador");
}