369 lines
17 KiB
TypeScript
369 lines
17 KiB
TypeScript
// 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<SignatureWizardSignerRow[]>([emptySigner()]);
|
|
const [upload, setUpload] = useState<UploadState>({ 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<HTMLInputElement>(null);
|
|
// Options grow when an upload finishes so the fresh file is pickable/visible.
|
|
const [uploadedOptions, setUploadedOptions] = useState<ProjectSignaturePdfFileOption[]>([]);
|
|
|
|
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<SignatureWizardSignerRow>) {
|
|
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 (
|
|
<Dialog open={open} onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : onClose())}>
|
|
<Dialog.Content className="w-[720px] max-w-[90vw] p-6">
|
|
<div className="flex w-full flex-col gap-6" data-ui-id="ui.projects.signature.wizard">
|
|
<div className="flex flex-col gap-2">
|
|
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">{t("signature.wizard.title")}</span>
|
|
{errorKey ? <Alert variant="error" title={t(errorKey)} /> : null}
|
|
</div>
|
|
|
|
<StepperHorizontal>
|
|
{STEPS.map((key, index) => (
|
|
<StepperHorizontal.Step
|
|
key={key}
|
|
firstStep={index === 0}
|
|
lastStep={index === STEPS.length - 1}
|
|
stepNumber={String(index + 1)}
|
|
label={t(`signature.wizard.step.${key}`)}
|
|
variant={index === step ? "active" : index < step ? "completed" : "default"}
|
|
/>
|
|
))}
|
|
</StepperHorizontal>
|
|
|
|
{step === 0 ? (
|
|
<div className="flex w-full flex-col gap-4" data-wizard-step="document">
|
|
<TextInput className="w-full" label={t("signature.fields.title")} showLabel>
|
|
<TextInput.Input value={title} onChange={(event) => setTitle(event.target.value)} required data-wizard-field="title" />
|
|
</TextInput>
|
|
{allPdfOptions.length > 0 ? (
|
|
<Select
|
|
className="w-full max-w-none"
|
|
showLabel
|
|
label={t("signature.wizard.selectPdf")}
|
|
placeholder={t("signature.wizard.selectPdfPlaceholder")}
|
|
value={sourcePdfFileId || undefined}
|
|
onValueChange={(value: string) => setSourcePdfFileId(value)}
|
|
data-wizard-field="sourcePdf"
|
|
>
|
|
{allPdfOptions.map((option) => (
|
|
<Select.Item key={option.id} value={option.id}>
|
|
{option.displayName}
|
|
</Select.Item>
|
|
))}
|
|
</Select>
|
|
) : (
|
|
<span className={bodyText}>{t("signature.wizard.noPdfOptions")}</span>
|
|
)}
|
|
{uploadPdf ? (
|
|
<div className="flex flex-col gap-2">
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept="application/pdf"
|
|
className="hidden"
|
|
onChange={(event) => void handleFileChosen(event.target.files)}
|
|
data-wizard-field="uploadInput"
|
|
/>
|
|
<div className="flex items-center gap-2">
|
|
<Button
|
|
variant="secondary"
|
|
loading={upload.status === "uploading"}
|
|
onClick={() => fileInputRef.current?.click()}
|
|
data-ui-id="ui.projects.signature.wizard.upload"
|
|
>
|
|
{t("signature.wizard.uploadPdf")}
|
|
</Button>
|
|
{upload.status === "done" ? <span className={bodyText}>{t("signature.wizard.uploadedAs", { name: upload.displayName })}</span> : null}
|
|
</div>
|
|
{upload.status === "error" ? <Alert variant="error" title={t(upload.errorKey)} /> : null}
|
|
</div>
|
|
) : null}
|
|
<TextInput className="w-full" label={t("signature.fields.subject")} showLabel>
|
|
<TextInput.Input value={subject} onChange={(event) => setSubject(event.target.value)} data-wizard-field="subject" />
|
|
</TextInput>
|
|
<TextArea className="w-full max-w-none" label={t("signature.fields.message")} showLabel>
|
|
<TextArea.Input value={message} onChange={(event) => setMessage(event.target.value)} data-wizard-field="message" />
|
|
</TextArea>
|
|
</div>
|
|
) : null}
|
|
|
|
{step === 1 ? (
|
|
<div className="flex w-full flex-col gap-4" data-wizard-step="signers">
|
|
{kontaktSuggestions.length > 0 ? (
|
|
<Select
|
|
className="w-full max-w-none"
|
|
showLabel
|
|
label={t("signature.wizard.addFromKontakt")}
|
|
placeholder={t("signature.wizard.addFromKontaktPlaceholder")}
|
|
value={kontaktPick || undefined}
|
|
onValueChange={(value: string) => {
|
|
addFromKontakt(value);
|
|
setKontaktPick("");
|
|
}}
|
|
data-wizard-field="kontaktSuggestion"
|
|
>
|
|
{kontaktSuggestions.map((suggestion) => (
|
|
<Select.Item key={suggestion.kontaktId} value={suggestion.kontaktId}>
|
|
{suggestion.email ? `${suggestion.name} (${suggestion.email})` : suggestion.name}
|
|
</Select.Item>
|
|
))}
|
|
</Select>
|
|
) : null}
|
|
<div className="flex w-full flex-col gap-4">
|
|
{signers.map((row, index) => {
|
|
const emailInvalid = row.email.trim().length > 0 && !isEmailValid(row.email);
|
|
return (
|
|
<div key={index} className="flex w-full items-end gap-2" data-wizard-signer-row={index}>
|
|
<TextInput className="grow" label={t("signature.fields.signerName")} showLabel>
|
|
<TextInput.Input value={row.name} onChange={(event) => updateSigner(index, { name: event.target.value })} required />
|
|
</TextInput>
|
|
<TextInput className="grow" label={t("signature.fields.signerEmail")} showLabel error={emailInvalid} message={emailInvalid ? t("signature.wizard.emailInvalid") : undefined}>
|
|
<TextInput.Input type="email" value={row.email} onChange={(event) => updateSigner(index, { email: event.target.value })} required />
|
|
</TextInput>
|
|
<Select
|
|
className="w-48 flex-none"
|
|
showLabel
|
|
label={t("signature.fields.signerRole")}
|
|
value={row.role}
|
|
onValueChange={(value: string) => updateSigner(index, { role: value })}
|
|
>
|
|
{SIGNER_ROLES.map((role) => (
|
|
<Select.Item key={role} value={role}>
|
|
{t(`signature.roles.${role}`)}
|
|
</Select.Item>
|
|
))}
|
|
</Select>
|
|
<div className="flex flex-none items-center gap-1 pb-1">
|
|
<IconButton size="small" icon={<FeatherArrowUp />} disabled={index === 0} onClick={() => moveSigner(index, -1)} aria-label={t("signature.wizard.moveUp")} />
|
|
<IconButton size="small" icon={<FeatherArrowDown />} disabled={index === signers.length - 1} onClick={() => moveSigner(index, 1)} aria-label={t("signature.wizard.moveDown")} />
|
|
<IconButton
|
|
size="small"
|
|
icon={<FeatherTrash2 />}
|
|
disabled={signers.length === 1}
|
|
onClick={() => setSigners((current) => current.filter((_, i) => i !== index))}
|
|
aria-label={t("signature.wizard.removeSigner")}
|
|
/>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
<div className="flex items-center justify-between gap-2">
|
|
<Button variant="secondary" onClick={() => setSigners((current) => [...current, emptySigner()])} data-ui-id="ui.projects.signature.wizard.add-signer">
|
|
{t("signature.wizard.addSigner")}
|
|
</Button>
|
|
<span className={bodyText}>{t("signature.wizard.orderHint")}</span>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
{step === 2 ? (
|
|
<div className="flex w-full flex-col gap-2" data-wizard-step="review">
|
|
<span className={bodyText}>{t("signature.wizard.review.body")}</span>
|
|
<span className={summaryText}>
|
|
{t("signature.wizard.review.document")}: {title || "—"} · {selectedPdf?.displayName ?? sourcePdfFileId ?? "—"}
|
|
</span>
|
|
<span className={summaryText}>{t("signature.wizard.review.signers")}:</span>
|
|
{signers.map((row, index) => (
|
|
<span key={index} className={bodyText}>
|
|
{index + 1}. {row.name} · {row.email} · {t(`signature.roles.${row.role}`)}
|
|
</span>
|
|
))}
|
|
</div>
|
|
) : null}
|
|
|
|
<div className="flex w-full items-center justify-end gap-2">
|
|
<Button variant="tertiary" onClick={onClose}>
|
|
{t("shared.cancel")}
|
|
</Button>
|
|
{step > 0 ? (
|
|
<Button variant="secondary" onClick={() => setStep(step - 1)}>
|
|
{t("shared.back")}
|
|
</Button>
|
|
) : null}
|
|
{step < STEPS.length - 1 ? (
|
|
<Button
|
|
disabled={(step === 0 && documentIncomplete) || (step === 1 && signersIncomplete)}
|
|
onClick={() => setStep(step + 1)}
|
|
data-ui-id="ui.projects.signature.wizard.next"
|
|
>
|
|
{t("shared.next")}
|
|
</Button>
|
|
) : (
|
|
<>
|
|
<Button variant="secondary" loading={submitting} onClick={() => submit("create")} data-ui-id="ui.projects.signature.wizard.create">
|
|
{t("signature.actions.createDraft")}
|
|
</Button>
|
|
<Button loading={submitting} onClick={() => submit("createAndSend")} data-ui-id="ui.projects.signature.wizard.create-send">
|
|
{t("signature.wizard.createAndSend")}
|
|
</Button>
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</Dialog.Content>
|
|
</Dialog>
|
|
);
|
|
}
|