| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346 |
- /**
- * 工单配置第三卡:施工回填扩展模板(草稿/发布/字段编辑器)。
- * 读:OPS_SIDE;写/发:仅 admin。冲突 S407/G20425 ⇒ 整卡重载。
- */
- import { useCallback, useEffect, useState } from "react";
- import { Button } from "../ui/button";
- import { FieldHint } from "../ui/field-hint";
- import {
- FORM_TEMPLATE_TICKET_TYPES,
- formTemplateGet,
- formTemplatePublish,
- formTemplateSave,
- TICKET_TYPE_NAMES,
- type FormFieldSchema,
- type FormSchema,
- type FormTemplateBundle,
- } from "../../lib/api/ticket";
- import { classifyTicketError } from "../../lib/ticket";
- const FIELD_TYPES: { code: string; label: string }[] = [
- { code: "text", label: "单行文本" },
- { code: "textarea", label: "多行文本" },
- { code: "number", label: "数字" },
- { code: "date", label: "日期" },
- { code: "select", label: "单选" },
- { code: "multiselect", label: "多选" },
- { code: "boolean", label: "是否" },
- { code: "material_ref", label: "材料引用" },
- ];
- function emptyField(): FormFieldSchema {
- return { key: "", label: "", type: "text", required: false };
- }
- function schemaFrom(raw: FormSchema | null | undefined): FormSchema {
- return {
- fields: Array.isArray(raw?.fields) ? raw!.fields.map((f) => ({ ...f, options: f.options ? [...f.options] : undefined })) : [],
- layout: { columns: raw?.layout?.columns === 1 ? 1 : 2 },
- };
- }
- export function FormTemplateAdminCard({ canEdit }: { canEdit: boolean }) {
- const [tab, setTab] = useState<string>("open");
- const [bundle, setBundle] = useState<FormTemplateBundle | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState("");
- const [schema, setSchema] = useState<FormSchema>(() => schemaFrom(null));
- const [expectVersion, setExpectVersion] = useState<number | undefined>();
- const [templateId, setTemplateId] = useState<string | undefined>();
- const [busy, setBusy] = useState(false);
- const [tip, setTip] = useState("");
- const [ackOpen, setAckOpen] = useState(false);
- const load = useCallback(async (ticketType: string) => {
- setLoading(true);
- setError("");
- setTip("");
- try {
- const r = await formTemplateGet(ticketType);
- const item = r.items.find((x) => x.ticket_type === ticketType) ?? r.items[0] ?? null;
- setBundle(item);
- const draft = item?.draft;
- const base = draft ?? item?.published ?? null;
- setSchema(schemaFrom(base?.schema));
- setExpectVersion(draft ? Number(draft.row_version) : undefined);
- setTemplateId(draft?.template_id);
- } catch (e) {
- const c = classifyTicketError(e);
- setError(c.message);
- setBundle(null);
- } finally {
- setLoading(false);
- }
- }, []);
- useEffect(() => {
- void load(tab);
- }, [tab, load]);
- function patchField(i: number, patch: Partial<FormFieldSchema>) {
- setSchema((prev) => {
- const fields = prev.fields.map((f, idx) => (idx === i ? { ...f, ...patch } : f));
- return { ...prev, fields };
- });
- }
- async function saveDraft() {
- setTip("");
- setBusy(true);
- try {
- const r = await formTemplateSave({
- ticket_type: tab,
- schema,
- expect_version: expectVersion,
- template_id: templateId,
- });
- setTip(`草稿已保存(版本锁 ${r.row_version})。`);
- await load(tab);
- } catch (e) {
- const c = classifyTicketError(e);
- setTip(c.message);
- await load(tab);
- } finally {
- setBusy(false);
- }
- }
- async function publish(ack = false) {
- setTip("");
- setBusy(true);
- try {
- if (!templateId && !bundle?.draft?.template_id) {
- setTip("请先保存草稿再发布。");
- setBusy(false);
- return;
- }
- const tid = templateId ?? bundle?.draft?.template_id ?? "";
- const ev = expectVersion ?? Number(bundle?.draft?.row_version ?? 0);
- const r = await formTemplatePublish({
- ticket_type: tab,
- template_id: tid,
- expect_version: ev,
- ack_required_change: ack || undefined,
- });
- setAckOpen(false);
- setTip(`已发布为 v${r.version}。`);
- await load(tab);
- } catch (e) {
- const c = classifyTicketError(e);
- const raw = e as { detail?: { reason?: string }; data?: { reason?: string } };
- const reason = raw?.detail?.reason ?? raw?.data?.reason ?? "";
- if (String(c.message).includes("ack_required_change") || reason === "required_change_needs_ack") {
- setAckOpen(true);
- setTip(c.message);
- } else {
- setTip(c.message);
- await load(tab);
- }
- } finally {
- setBusy(false);
- }
- }
- const pub = bundle?.published;
- const history = (bundle?.versions ?? []).filter((v) => v.status !== "draft");
- return (
- <div className="ops-record-card" style={{ marginTop: 8 }}>
- <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 12 }}>
- {FORM_TEMPLATE_TICKET_TYPES.map((code) => (
- <Button
- key={code}
- type="button"
- size="sm"
- variant={tab === code ? "default" : "outline"}
- onClick={() => setTab(code)}
- >
- {TICKET_TYPE_NAMES[code] ?? code}
- </Button>
- ))}
- </div>
- {loading && <p className="ops-empty">正在读取扩展模板…</p>}
- {error && <p className="ops-empty" role="alert">{error}</p>}
- {!loading && !error && (
- <>
- <p>
- 当前已发布:
- {pub ? (
- <>
- <strong>v{pub.version}</strong>
- {pub.published_at ? ` · ${pub.published_at.slice(0, 19).replace("T", " ")}` : ""}
- · {pub.schema?.fields?.length ?? 0} 个字段
- </>
- ) : (
- <strong>无</strong>
- )}
- {bundle?.draft ? " · 有未发布草稿" : " · 无草稿"}
- <FieldHint label="扩展模板说明">
- 扩展字段不进竣工与计费;必填仅在执行结论为「成功」时由回填口强制。同类型同时只有一个已发布版本。
- </FieldHint>
- </p>
- <div className="ops-form-grid" style={{ marginTop: 12 }}>
- <label>
- 布局列数
- <select
- disabled={!canEdit || busy}
- value={schema.layout?.columns === 1 ? 1 : 2}
- onChange={(e) =>
- setSchema((s) => ({ ...s, layout: { columns: Number(e.target.value) === 1 ? 1 : 2 } }))
- }
- >
- <option value={2}>两列</option>
- <option value={1}>一列</option>
- </select>
- </label>
- </div>
- <h3 style={{ marginTop: 16, fontSize: 15 }}>字段</h3>
- {schema.fields.length === 0 && <p className="ops-muted">暂无字段;点「增加字段」开始编辑草稿。</p>}
- {schema.fields.map((f, i) => (
- <div key={i} className="ops-form-grid" style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid var(--ops-border, #e5e7eb)" }}>
- <label>
- key
- <input
- disabled={!canEdit || busy}
- value={f.key}
- placeholder="network_vendor"
- onChange={(e) => patchField(i, { key: e.target.value.trim() })}
- />
- </label>
- <label>
- 标签
- <input
- disabled={!canEdit || busy}
- value={f.label}
- onChange={(e) => patchField(i, { label: e.target.value })}
- />
- </label>
- <label>
- 类型
- <select
- disabled={!canEdit || busy}
- value={f.type}
- onChange={(e) => patchField(i, { type: e.target.value })}
- >
- {FIELD_TYPES.map((t) => (
- <option key={t.code} value={t.code}>
- {t.label}
- </option>
- ))}
- </select>
- </label>
- <label className="work-order-repeater-flag">
- <input
- type="checkbox"
- disabled={!canEdit || busy}
- checked={!!f.required}
- onChange={(e) => patchField(i, { required: e.target.checked })}
- />
- <span>必填(仅成功结论强制)</span>
- </label>
- <label className="wide">
- 说明
- <input
- disabled={!canEdit || busy}
- value={f.help ?? ""}
- onChange={(e) => patchField(i, { help: e.target.value || undefined })}
- />
- </label>
- {(f.type === "select" || f.type === "multiselect") && (
- <label className="wide">
- 选项(每行 value|label)
- <textarea
- rows={3}
- disabled={!canEdit || busy}
- value={(f.options ?? []).map((o) => `${o.value}|${o.label}`).join("\n")}
- onChange={(e) => {
- const options = e.target.value
- .split("\n")
- .map((line) => line.trim())
- .filter(Boolean)
- .map((line) => {
- const [value, ...rest] = line.split("|");
- return { value: value.trim(), label: (rest.join("|") || value).trim() };
- });
- patchField(i, { options });
- }}
- />
- </label>
- )}
- {canEdit && (
- <div className="ops-form-actions">
- <Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => setSchema((s) => ({ ...s, fields: s.fields.filter((_, j) => j !== i) }))}>
- 删除字段
- </Button>
- </div>
- )}
- </div>
- ))}
- {canEdit ? (
- <div className="ops-form-actions" style={{ marginTop: 16, gap: 8, display: "flex", flexWrap: "wrap" }}>
- <Button type="button" variant="outline" disabled={busy || schema.fields.length >= 30} onClick={() => setSchema((s) => ({ ...s, fields: [...s.fields, emptyField()] }))}>
- 增加字段
- </Button>
- <Button type="button" disabled={busy} onClick={() => void saveDraft()}>
- 保存草稿
- </Button>
- <Button type="button" disabled={busy || (!bundle?.draft && !templateId)} onClick={() => void publish(false)}>
- 发布
- </Button>
- </div>
- ) : (
- <p>扩展模板的改动仅总运营管理员可用,当前账号只读。</p>
- )}
- {tip && <p role="alert" className="work-order-form-error">{tip}</p>}
- {ackOpen && (
- <div role="dialog" style={{ marginTop: 12, padding: 12, border: "1px solid var(--ops-border, #e5e7eb)" }}>
- <p>新版本新增或改动了必填字段,在途工单将按新模板校验。确认继续发布?</p>
- <div className="ops-form-actions" style={{ display: "flex", gap: 8 }}>
- <Button type="button" disabled={busy} onClick={() => void publish(true)}>
- 确认并发布
- </Button>
- <Button type="button" variant="outline" disabled={busy} onClick={() => setAckOpen(false)}>
- 取消
- </Button>
- </div>
- </div>
- )}
- {history.length > 0 && (
- <>
- <h3 style={{ marginTop: 20, fontSize: 15 }}>历史版本</h3>
- <div className="work-order-table-wrap compact">
- <table>
- <thead>
- <tr>
- <th>版本</th>
- <th>状态</th>
- <th>字段数</th>
- <th>发布时间</th>
- </tr>
- </thead>
- <tbody>
- {history.map((v) => (
- <tr key={`${v.template_id}-${v.version}`}>
- <td>v{v.version}</td>
- <td>{v.status}</td>
- <td>{v.schema?.fields?.length ?? 0}</td>
- <td>{v.published_at ? v.published_at.slice(0, 19).replace("T", " ") : "—"}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </>
- )}
- </>
- )}
- </div>
- );
- }
|