// AK-P16d Interim-UI (AD-28) — signature preparation wizard as a REAL ~/ui // Dialog (D-P16 "Signatur-Wizard", size M 720) with a StepperHorizontal: // document (PDF from Files or fresh upload) → signers (structured rows with // Kontakt prefill; row order = signing order) → review & create/send. // Submits go through the project detail route's existing signature intents via // the injected actions callback — no fetching in here. Final Subframe optics // land as a tracked design-nachzug once David's D-P16 ships. // // Not built on purpose (no backend yet): sequential/parallel send enforcement, // a remote-vs-touch signature mode switch, linkedKontaktId persistence. import { useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { FeatherArrowDown, FeatherArrowUp, FeatherTrash2 } from "@subframe/core"; import type { ProjectSignatureKontaktSuggestion, ProjectSignaturePdfFileOption } from "@hivegrid/view-models"; import { Alert } from "~/ui/components/Alert"; import { Button } from "~/ui/components/Button"; import { Dialog } from "~/ui/components/Dialog"; import { IconButton } from "~/ui/components/IconButton"; import { Select } from "~/ui/components/Select"; import { StepperHorizontal } from "~/ui/components/StepperHorizontal"; import { TextArea } from "~/ui/components/TextArea"; import { TextInput } from "~/ui/components/TextInput"; export type SignatureWizardSignerRow = { name: string; email: string; role: string }; export type SignatureWizardSubmitFields = { title: string; sourcePdfFileId: string; subject: string; message: string; signers: string; }; export type SignatureWizardDialogProps = { open: boolean; pdfFileOptions: readonly ProjectSignaturePdfFileOption[]; kontaktSuggestions: readonly ProjectSignatureKontaktSuggestion[]; submitting: boolean; errorKey?: string | null; onSubmit: (intent: "create" | "createAndSend", fields: SignatureWizardSubmitFields) => void; onClose: () => void; /** Optional chunked-upload callback injected by the route; hides upload when absent. */ uploadPdf?: (file: File) => Promise<{ id: string; displayName: string }>; }; const STEPS = ["document", "signers", "review"] as const; const SIGNER_ROLES = ["kunde", "bauherr", "auftraggeber", "rechnungsempfaenger", "intern"] as const; const bodyText = "text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary"; const summaryText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary"; function emptySigner(): SignatureWizardSignerRow { return { name: "", email: "", role: "kunde" }; } function isEmailValid(email: string): boolean { return email.trim().includes("@"); } /** * Serializes structured signer rows into the existing `parseSignatureSigners` * line contract ("name; email; role" per line). Separators and line breaks are * stripped from free-text parts so a name can never split the line; row order * becomes the persisted signingOrder. */ export function serializeSignatureSigners(rows: readonly SignatureWizardSignerRow[]): string { const clean = (value: string) => value.replace(/[;\r\n]+/g, " ").replace(/\s+/g, " ").trim(); return rows.map((row) => `${clean(row.name)}; ${clean(row.email)}; ${row.role}`).join("\n"); } type UploadState = | { status: "idle" } | { status: "uploading"; percent: number } | { status: "done"; displayName: string } | { status: "error"; errorKey: string }; export function SignatureWizardDialog(props: SignatureWizardDialogProps) { const { open, pdfFileOptions, kontaktSuggestions, submitting, errorKey, onSubmit, onClose, uploadPdf } = props; const { t } = useTranslation(); const [step, setStep] = useState(0); const [title, setTitle] = useState(""); const [subject, setSubject] = useState(""); const [message, setMessage] = useState(""); const [sourcePdfFileId, setSourcePdfFileId] = useState(""); const [signers, setSigners] = useState([emptySigner()]); const [upload, setUpload] = useState({ status: "idle" }); // Controlled kontakt picker value that resets after each pick so the same // kontakt can be added again (Radix Select only fires on value change). const [kontaktPick, setKontaktPick] = useState(""); const fileInputRef = useRef(null); // Options grow when an upload finishes so the fresh file is pickable/visible. const [uploadedOptions, setUploadedOptions] = useState([]); useEffect(() => { if (open) { setStep(0); setTitle(""); setSubject(""); setMessage(""); setSourcePdfFileId(""); setSigners([emptySigner()]); setUpload({ status: "idle" }); setKontaktPick(""); setUploadedOptions([]); } }, [open]); const allPdfOptions = [...uploadedOptions, ...pdfFileOptions]; const documentIncomplete = title.trim().length === 0 || sourcePdfFileId.trim().length === 0; const signersIncomplete = signers.length === 0 || signers.some((row) => row.name.trim().length === 0 || !isEmailValid(row.email)); function updateSigner(index: number, patch: Partial) { setSigners((current) => current.map((row, i) => (i === index ? { ...row, ...patch } : row))); } function moveSigner(index: number, direction: -1 | 1) { setSigners((current) => { const target = index + direction; if (target < 0 || target >= current.length) return current; const next = [...current]; [next[index], next[target]] = [next[target], next[index]]; return next; }); } function addFromKontakt(kontaktId: string) { const kontakt = kontaktSuggestions.find((suggestion) => suggestion.kontaktId === kontaktId); if (!kontakt) return; const prefilled: SignatureWizardSignerRow = { name: kontakt.name, email: kontakt.email ?? "", role: "kunde" }; setSigners((current) => { const [first, ...rest] = current; // Fill the first still-empty row instead of stacking empty rows. if (first && first.name.trim().length === 0 && first.email.trim().length === 0) return [prefilled, ...rest]; return [...current, prefilled]; }); } async function handleFileChosen(fileList: FileList | null) { const file = fileList?.[0]; if (!file || !uploadPdf) return; if (file.type !== "application/pdf") { setUpload({ status: "error", errorKey: "signature.wizard.onlyPdf" }); return; } setUpload({ status: "uploading", percent: 0 }); try { const uploaded = await uploadPdf(file); setUploadedOptions((current) => [{ id: uploaded.id, displayName: uploaded.displayName, createdAtIso: null }, ...current]); setSourcePdfFileId(uploaded.id); setUpload({ status: "done", displayName: uploaded.displayName }); } catch (error) { const key = error instanceof Error && "errorKey" in error ? String((error as { errorKey: unknown }).errorKey) : "signature.wizard.uploadError"; setUpload({ status: "error", errorKey: key }); } finally { if (fileInputRef.current) fileInputRef.current.value = ""; } } function submit(intent: "create" | "createAndSend") { onSubmit(intent, { title: title.trim(), sourcePdfFileId: sourcePdfFileId.trim(), subject: subject.trim(), message: message.trim(), signers: serializeSignatureSigners(signers), }); } const selectedPdf = allPdfOptions.find((option) => option.id === sourcePdfFileId); return ( (nextOpen ? undefined : onClose())}>
{t("signature.wizard.title")} {errorKey ? : null}
{STEPS.map((key, index) => ( ))} {step === 0 ? (
setTitle(event.target.value)} required data-wizard-field="title" /> {allPdfOptions.length > 0 ? ( ) : ( {t("signature.wizard.noPdfOptions")} )} {uploadPdf ? (
void handleFileChosen(event.target.files)} data-wizard-field="uploadInput" />
{upload.status === "done" ? {t("signature.wizard.uploadedAs", { name: upload.displayName })} : null}
{upload.status === "error" ? : null}
) : null} setSubject(event.target.value)} data-wizard-field="subject" />
) : null} {step === 1 ? (
{kontaktSuggestions.length > 0 ? ( ) : null}
{signers.map((row, index) => { const emailInvalid = row.email.trim().length > 0 && !isEmailValid(row.email); return (
updateSigner(index, { name: event.target.value })} required /> updateSigner(index, { email: event.target.value })} required />
} disabled={index === 0} onClick={() => moveSigner(index, -1)} aria-label={t("signature.wizard.moveUp")} /> } disabled={index === signers.length - 1} onClick={() => moveSigner(index, 1)} aria-label={t("signature.wizard.moveDown")} /> } disabled={signers.length === 1} onClick={() => setSigners((current) => current.filter((_, i) => i !== index))} aria-label={t("signature.wizard.removeSigner")} />
); })}
{t("signature.wizard.orderHint")}
) : null} {step === 2 ? (
{t("signature.wizard.review.body")} {t("signature.wizard.review.document")}: {title || "—"} · {selectedPdf?.displayName ?? sourcePdfFileId ?? "—"} {t("signature.wizard.review.signers")}: {signers.map((row, index) => ( {index + 1}. {row.name} · {row.email} · {t(`signature.roles.${row.role}`)} ))}
) : null}
{step > 0 ? ( ) : null} {step < STEPS.length - 1 ? ( ) : ( <> )}
); }