CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (pull_request) Successful in 4s
masterplan-lock / check (push) Successful in 4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
Security Scan (SIAX Cloud) / security (push) Successful in 18s
CI (SIAX Cloud) / security (push) Successful in 26s
CI (SIAX Cloud) / security (pull_request) Successful in 37s
CI (SIAX Cloud) / integration (pull_request) Successful in 43s
CI (SIAX Cloud) / quality (push) Successful in 1m7s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m8s
Never assume 'low'; the UI offers only the server-approved data classes and the route refuses external models for high/restricted data.
525 lines
20 KiB
TypeScript
525 lines
20 KiB
TypeScript
'use client';
|
||
|
||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||
import { useT } from '@/components/locale-provider';
|
||
import { PortalShell } from '@/components/portal-shell';
|
||
|
||
/**
|
||
* /portal/dokument — the customer's document workspace.
|
||
*
|
||
* Three honest steps:
|
||
* 1. Upload the original file (real bytes, multipart) into DOC0.
|
||
* 2. Describe the structure you want and the fields to extract.
|
||
* 3. Review the evidence-bound output and download JSON/CSV.
|
||
*
|
||
* Nothing on this page fabricates success: a 503 means the capability is not
|
||
* configured, and an "outcome unknown" upload is shown as exactly that.
|
||
*/
|
||
|
||
type Receipt = {
|
||
document_id: string;
|
||
version_id: string;
|
||
checksum_sha256: string;
|
||
pipeline_stage: string;
|
||
};
|
||
|
||
type FieldRow = { name: string; type: 'string' | 'integer' | 'boolean' | 'decimal' | 'date' };
|
||
|
||
type Evidence = {
|
||
field: string;
|
||
sourceId: string;
|
||
start: number;
|
||
end: number;
|
||
transform: string;
|
||
};
|
||
|
||
type StructureResponse = {
|
||
status: 'mechanically_validated' | 'needs_review' | 'outcome_unknown';
|
||
value?: Record<string, string | number | boolean>;
|
||
evidence?: Evidence[];
|
||
issues?: { field: string; code: string; row?: number }[];
|
||
model?: {
|
||
modelExecuted: string;
|
||
promptTokens: number;
|
||
completionTokens: number;
|
||
totalTokens: number;
|
||
costUsd?: number;
|
||
};
|
||
credits?: { reserved: number; charged: number; balance?: { available: number; reserved: number } };
|
||
export?: { media_type: string; content: string };
|
||
message?: string;
|
||
error?: string;
|
||
reservation_id?: string;
|
||
};
|
||
|
||
type ModelsResponse = {
|
||
models: string[];
|
||
data_classes: string[];
|
||
destination: string;
|
||
external_transfer_allowed: boolean;
|
||
max_input_tokens: number;
|
||
max_output_tokens: number;
|
||
price_book_version: string | null;
|
||
};
|
||
|
||
const TYPES: FieldRow['type'][] = ['string', 'integer', 'decimal', 'date', 'boolean'];
|
||
|
||
export default function DocumentsPage() {
|
||
const t = useT();
|
||
const [projectId, setProjectId] = useState('');
|
||
const [file, setFile] = useState<File | null>(null);
|
||
const [receipt, setReceipt] = useState<Receipt | null>(null);
|
||
const [uploadNote, setUploadNote] = useState<string | null>(null);
|
||
const [uploading, setUploading] = useState(false);
|
||
const [unknownOutcome, setUnknownOutcome] = useState<unknown | null>(null);
|
||
const inputRef = useRef<HTMLInputElement>(null);
|
||
|
||
const [instruction, setInstruction] = useState('');
|
||
const [fields, setFields] = useState<FieldRow[]>([{ name: 'organization', type: 'string' }]);
|
||
const [models, setModels] = useState<ModelsResponse | null>(null);
|
||
const [modelsError, setModelsError] = useState<string | null>(null);
|
||
const [modelId, setModelId] = useState('');
|
||
const [dataClass, setDataClass] = useState('low');
|
||
const [format, setFormat] = useState<'json' | 'csv'>('json');
|
||
const [structuring, setStructuring] = useState(false);
|
||
const [result, setResult] = useState<StructureResponse | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
const stored = window.localStorage.getItem('0pt.project_id');
|
||
if (stored) setProjectId(stored);
|
||
fetch('/api/0pt/documents/models', { cache: 'no-store' })
|
||
.then(async (r) => {
|
||
const body = (await r.json()) as ModelsResponse & { message?: string };
|
||
if (!r.ok) {
|
||
setModelsError(body.message ?? 'Modellpolicyn är inte konfigurerad');
|
||
return;
|
||
}
|
||
setModels(body);
|
||
setModelId((current) => current || body.models[0] || '');
|
||
setDataClass((current) =>
|
||
body.data_classes.includes(current) ? current : (body.data_classes[0] ?? 'low'),
|
||
);
|
||
})
|
||
.catch(() => setModelsError('Kunde inte läsa modellpolicyn'));
|
||
}, []);
|
||
|
||
const upload = useCallback(async () => {
|
||
if (!file || uploading) return;
|
||
if (!projectId.trim()) {
|
||
setError(t({ en: 'A project id is required', sv: 'Ett projekt-id krävs' }));
|
||
return;
|
||
}
|
||
setUploading(true);
|
||
setError(null);
|
||
setUploadNote(null);
|
||
setUnknownOutcome(null);
|
||
setReceipt(null);
|
||
window.localStorage.setItem('0pt.project_id', projectId.trim());
|
||
const form = new FormData();
|
||
form.set('file', file);
|
||
form.set('project_id', projectId.trim());
|
||
form.set('idempotency_key', crypto.randomUUID());
|
||
form.set('classification', 'restricted');
|
||
try {
|
||
const response = await fetch('/api/0pt/documents/upload', {
|
||
method: 'POST',
|
||
body: form,
|
||
headers: { 'x-request-id': crypto.randomUUID() },
|
||
});
|
||
const body = (await response.json().catch(() => ({}))) as Record<string, unknown> & {
|
||
status?: string;
|
||
message?: string;
|
||
error?: string;
|
||
};
|
||
if (response.status === 201) {
|
||
setReceipt({
|
||
document_id: String(body.document_id),
|
||
version_id: String(body.version_id),
|
||
checksum_sha256: String(body.checksum_sha256),
|
||
pipeline_stage: String(body.pipeline_stage),
|
||
});
|
||
return;
|
||
}
|
||
if (response.status === 202) {
|
||
setUnknownOutcome(body.observation ?? body);
|
||
setUploadNote(
|
||
t({
|
||
en: 'The upload may have been accepted. It is not confirmed.',
|
||
sv: 'Uppladdningen kan ha tagits emot. Den är inte bekräftad.',
|
||
}),
|
||
);
|
||
return;
|
||
}
|
||
setUploadNote(
|
||
body.message ?? body.error ?? t({ en: 'Upload failed', sv: 'Uppladdningen misslyckades' }),
|
||
);
|
||
} catch {
|
||
setUploadNote(t({ en: 'Upload failed', sv: 'Uppladdningen misslyckades' }));
|
||
} finally {
|
||
setUploading(false);
|
||
}
|
||
}, [file, projectId, t, uploading]);
|
||
|
||
const structure = useCallback(async () => {
|
||
if (!receipt || structuring) return;
|
||
if (!instruction.trim()) {
|
||
setError(t({ en: 'Describe the structure you want', sv: 'Beskriv strukturen du vill ha' }));
|
||
return;
|
||
}
|
||
if (!modelId) {
|
||
setError(t({ en: 'No approved model is configured', sv: 'Ingen godkänd modell är konfigurerad' }));
|
||
return;
|
||
}
|
||
setStructuring(true);
|
||
setError(null);
|
||
setResult(null);
|
||
try {
|
||
const response = await fetch('/api/0pt/documents/structure', {
|
||
method: 'POST',
|
||
headers: { 'content-type': 'application/json', 'x-request-id': crypto.randomUUID() },
|
||
body: JSON.stringify({
|
||
project_id: projectId.trim(),
|
||
document_id: receipt.document_id,
|
||
version_id: receipt.version_id,
|
||
checksum_sha256: receipt.checksum_sha256,
|
||
pipeline_stage: receipt.pipeline_stage,
|
||
instruction,
|
||
fields,
|
||
model_id: modelId,
|
||
data_class: dataClass,
|
||
format,
|
||
}),
|
||
});
|
||
const body = (await response.json().catch(() => ({}))) as StructureResponse;
|
||
if (response.ok || response.status === 202) {
|
||
setResult(body);
|
||
} else {
|
||
setError(
|
||
body.message ?? body.error ?? t({ en: 'Structuring failed', sv: 'Struktureringen misslyckades' }),
|
||
);
|
||
}
|
||
} catch {
|
||
setError(t({ en: 'Structuring failed', sv: 'Struktureringen misslyckades' }));
|
||
} finally {
|
||
setStructuring(false);
|
||
}
|
||
}, [receipt, structuring, instruction, modelId, dataClass, projectId, fields, format, t]);
|
||
|
||
function download() {
|
||
if (!result?.export) return;
|
||
const blob = new Blob([result.export.content], { type: result.export.media_type });
|
||
const url = URL.createObjectURL(blob);
|
||
const anchor = document.createElement('a');
|
||
anchor.href = url;
|
||
anchor.download = `0pt-${receipt?.document_id ?? 'result'}.${format}`;
|
||
anchor.click();
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
function addField() {
|
||
if (fields.length >= 100) return;
|
||
setFields((current) => [...current, { name: `field_${current.length + 1}`, type: 'string' }]);
|
||
}
|
||
|
||
function updateField(index: number, patch: Partial<FieldRow>) {
|
||
setFields((current) => current.map((row, i) => (i === index ? { ...row, ...patch } : row)));
|
||
}
|
||
|
||
function removeField(index: number) {
|
||
setFields((current) => current.filter((_, i) => i !== index));
|
||
}
|
||
|
||
const card = 'border border-border bg-background p-6';
|
||
const label = 'font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground';
|
||
const input =
|
||
'mt-2 w-full border border-border bg-background px-3 py-2 font-mono text-[13px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||
|
||
return (
|
||
<PortalShell variant="customer" title={t({ en: 'Documents', sv: 'Dokument' })}>
|
||
<div className="mx-auto w-full max-w-4xl space-y-6">
|
||
<p className="max-w-2xl text-pretty text-[15px] leading-relaxed text-muted-foreground">
|
||
{t({
|
||
en: 'Upload a file, describe how it should be structured, and get evidence-bound data you can download.',
|
||
sv: 'Ladda upp en fil, beskriv hur den ska struktureras och få evidensbunden data som du kan ladda ner.',
|
||
})}
|
||
</p>
|
||
|
||
{/* 1 · upload */}
|
||
<section className={card}>
|
||
<div className="flex items-baseline justify-between gap-4">
|
||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||
{t({ en: '1 · Source', sv: '1 · Underlag' })}
|
||
</h2>
|
||
{receipt ? (
|
||
<span
|
||
className="font-mono text-[10px] uppercase tracking-[0.18em]"
|
||
style={{ color: 'var(--accent-red)' }}
|
||
>
|
||
{t({ en: 'uploaded', sv: 'uppladdad' })}
|
||
</span>
|
||
) : null}
|
||
</div>
|
||
|
||
<label className="mt-4 block">
|
||
<span className={label}>{t({ en: 'project id', sv: 'projekt-id' })}</span>
|
||
<input
|
||
className={input}
|
||
value={projectId}
|
||
onChange={(event) => setProjectId(event.target.value)}
|
||
placeholder="prj_…"
|
||
/>
|
||
</label>
|
||
|
||
<div
|
||
role="button"
|
||
tabIndex={0}
|
||
onClick={() => inputRef.current?.click()}
|
||
onKeyDown={(event) => {
|
||
if (event.key === 'Enter' || event.key === ' ') {
|
||
event.preventDefault();
|
||
inputRef.current?.click();
|
||
}
|
||
}}
|
||
className="mt-4 flex cursor-pointer flex-col items-center justify-center border border-dashed border-border px-6 py-10 text-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||
>
|
||
<span className={label}>{t({ en: 'choose a file', sv: 'välj en fil' })}</span>
|
||
<span className="mt-3 text-[15px]">
|
||
{file
|
||
? file.name
|
||
: t({ en: 'PDF, Word, Excel, CSV, images…', sv: 'PDF, Word, Excel, CSV, bilder…' })}
|
||
</span>
|
||
<input
|
||
ref={inputRef}
|
||
type="file"
|
||
className="hidden"
|
||
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
|
||
/>
|
||
</div>
|
||
|
||
<button
|
||
type="button"
|
||
onClick={upload}
|
||
disabled={!file || uploading}
|
||
className="mt-4 border border-foreground bg-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em] text-background disabled:opacity-40"
|
||
>
|
||
{uploading ? t({ en: 'uploading…', sv: 'laddar upp…' }) : t({ en: 'upload', sv: 'ladda upp' })}
|
||
</button>
|
||
|
||
{receipt ? (
|
||
<dl className="mt-4 grid gap-2 font-mono text-[11px] text-muted-foreground sm:grid-cols-2">
|
||
<div>
|
||
<dt className="uppercase tracking-[0.16em]">document</dt>
|
||
<dd className="break-all">{receipt.document_id}</dd>
|
||
</div>
|
||
<div>
|
||
<dt className="uppercase tracking-[0.16em]">version</dt>
|
||
<dd className="break-all">{receipt.version_id}</dd>
|
||
</div>
|
||
<div className="sm:col-span-2">
|
||
<dt className="uppercase tracking-[0.16em]">sha-256</dt>
|
||
<dd className="break-all">{receipt.checksum_sha256}</dd>
|
||
</div>
|
||
</dl>
|
||
) : null}
|
||
{uploadNote ? <p className="mt-4 text-[14px] text-muted-foreground">{uploadNote}</p> : null}
|
||
{unknownOutcome ? (
|
||
<pre className="mt-3 overflow-auto border border-border bg-muted/30 p-3 font-mono text-[11px]">
|
||
{JSON.stringify(unknownOutcome, null, 2)}
|
||
</pre>
|
||
) : null}
|
||
</section>
|
||
|
||
{/* 2 · structure */}
|
||
<section className={card}>
|
||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||
{t({ en: '2 · Desired structure', sv: '2 · Önskad struktur' })}
|
||
</h2>
|
||
|
||
<label className="mt-4 block">
|
||
<span className={label}>{t({ en: 'instruction', sv: 'instruktion' })}</span>
|
||
<textarea
|
||
className={`${input} min-h-[96px]`}
|
||
value={instruction}
|
||
maxLength={4000}
|
||
onChange={(event) => setInstruction(event.target.value)}
|
||
placeholder={t({
|
||
en: 'One row per agreement with parties, term, price and notice period.',
|
||
sv: 'En rad per avtal med parter, avtalstid, pris och uppsägningstid.',
|
||
})}
|
||
/>
|
||
</label>
|
||
|
||
<div className="mt-4">
|
||
<span className={label}>{t({ en: 'fields', sv: 'fält' })}</span>
|
||
<div className="mt-2 space-y-2">
|
||
{fields.map((field, index) => (
|
||
<div key={index} className="flex flex-wrap items-center gap-2">
|
||
<input
|
||
className="min-w-[160px] flex-1 border border-border bg-background px-3 py-2 font-mono text-[12px]"
|
||
value={field.name}
|
||
onChange={(event) => updateField(index, { name: event.target.value })}
|
||
aria-label={`field ${index + 1}`}
|
||
/>
|
||
<select
|
||
className="border border-border bg-background px-3 py-2 font-mono text-[12px]"
|
||
value={field.type}
|
||
onChange={(event) => updateField(index, { type: event.target.value as FieldRow['type'] })}
|
||
>
|
||
{TYPES.map((type) => (
|
||
<option key={type} value={type}>
|
||
{type}
|
||
</option>
|
||
))}
|
||
</select>
|
||
<button
|
||
type="button"
|
||
onClick={() => removeField(index)}
|
||
className="px-2 font-mono text-[11px] text-muted-foreground"
|
||
>
|
||
×
|
||
</button>
|
||
</div>
|
||
))}
|
||
</div>
|
||
<button
|
||
type="button"
|
||
onClick={addField}
|
||
className="mt-2 font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground"
|
||
>
|
||
+ {t({ en: 'add field', sv: 'lägg till fält' })}
|
||
</button>
|
||
</div>
|
||
|
||
<div className="mt-4 grid gap-4 sm:grid-cols-2">
|
||
<label className="block">
|
||
<span className={label}>{t({ en: 'model', sv: 'modell' })}</span>
|
||
<select
|
||
className={input}
|
||
value={modelId}
|
||
onChange={(event) => setModelId(event.target.value)}
|
||
disabled={!models}
|
||
>
|
||
{models?.models.map((model) => (
|
||
<option key={model} value={model}>
|
||
{model}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label className="block">
|
||
<span className={label}>{t({ en: 'format', sv: 'format' })}</span>
|
||
<select
|
||
className={input}
|
||
value={format}
|
||
onChange={(event) => setFormat(event.target.value as 'json' | 'csv')}
|
||
>
|
||
<option value="json">JSON</option>
|
||
<option value="csv">CSV</option>
|
||
</select>
|
||
</label>
|
||
<label className="block">
|
||
<span className={label}>{t({ en: 'data class', sv: 'dataklass' })}</span>
|
||
<select
|
||
className={input}
|
||
value={dataClass}
|
||
onChange={(event) => setDataClass(event.target.value)}
|
||
disabled={!models}
|
||
>
|
||
{(models?.data_classes ?? [dataClass]).map((value) => (
|
||
<option key={value} value={value}>
|
||
{value}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
</div>
|
||
<p className="mt-2 font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
|
||
{t({
|
||
en: 'External models are refused for high/restricted data.',
|
||
sv: 'Externa modeller nekas för hög/restricted data.',
|
||
})}
|
||
</p>
|
||
|
||
{modelsError ? <p className="mt-3 text-[13px] text-muted-foreground">{modelsError}</p> : null}
|
||
|
||
<button
|
||
type="button"
|
||
onClick={structure}
|
||
disabled={!receipt || structuring}
|
||
className="mt-4 border border-foreground bg-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em] text-background disabled:opacity-40"
|
||
>
|
||
{structuring
|
||
? t({ en: 'structuring…', sv: 'strukturerar…' })
|
||
: t({ en: 'structure', sv: 'strukturera' })}
|
||
</button>
|
||
</section>
|
||
|
||
{/* 3 · result */}
|
||
{(result || error) && (
|
||
<section className={card}>
|
||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||
{t({ en: '3 · Result', sv: '3 · Resultat' })}
|
||
</h2>
|
||
{error ? <p className="mt-4 text-[14px]">{error}</p> : null}
|
||
|
||
{result?.status === 'mechanically_validated' ? (
|
||
<>
|
||
<div className="mt-4 overflow-auto border border-border">
|
||
<table className="w-full border-collapse text-left font-mono text-[12px]">
|
||
<tbody>
|
||
{Object.entries(result.value ?? {}).map(([key, value]) => (
|
||
<tr key={key} className="border-b border-border last:border-b-0">
|
||
<th className="px-3 py-2 font-normal uppercase tracking-[0.14em] text-muted-foreground">
|
||
{key}
|
||
</th>
|
||
<td className="px-3 py-2">{String(value)}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<p className="mt-3 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
|
||
{result.evidence?.length ?? 0} {t({ en: 'evidence spans', sv: 'evidensspann' })}
|
||
{result.credits ? ` · ${result.credits.charged} credits` : ''}
|
||
</p>
|
||
{result.export ? (
|
||
<button
|
||
type="button"
|
||
onClick={download}
|
||
className="mt-4 border border-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em]"
|
||
>
|
||
{t({ en: 'download', sv: 'ladda ner' })} {format.toUpperCase()}
|
||
</button>
|
||
) : null}
|
||
</>
|
||
) : null}
|
||
|
||
{result?.status === 'needs_review' ? (
|
||
<div className="mt-4">
|
||
<p className="text-[14px]">
|
||
{t({
|
||
en: 'The model output did not pass evidence validation. Nothing was exported.',
|
||
sv: 'Modellens svar klarade inte evidenskontrollen. Inget exporterades.',
|
||
})}
|
||
</p>
|
||
<ul className="mt-3 space-y-1 font-mono text-[11px] text-muted-foreground">
|
||
{result.issues?.map((issue, index) => (
|
||
<li key={index}>
|
||
{issue.field || '(root)'} · {issue.code}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
) : null}
|
||
|
||
{result?.status === 'outcome_unknown' ? (
|
||
<p className="mt-4 text-[14px]">{result.message}</p>
|
||
) : null}
|
||
</section>
|
||
)}
|
||
</div>
|
||
</PortalShell>
|
||
);
|
||
}
|