FormTemplateAdminCard.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /**
  2. * 工单配置第三卡:施工回填扩展模板(草稿/发布/字段编辑器)。
  3. * 读:OPS_SIDE;写/发:仅 admin。冲突 S407/G20425 ⇒ 整卡重载。
  4. */
  5. import { useCallback, useEffect, useState } from "react";
  6. import { Button } from "../ui/button";
  7. import { FieldHint } from "../ui/field-hint";
  8. import {
  9. FORM_TEMPLATE_TICKET_TYPES,
  10. formTemplateGet,
  11. formTemplatePublish,
  12. formTemplateSave,
  13. TICKET_TYPE_NAMES,
  14. type FormFieldSchema,
  15. type FormSchema,
  16. type FormTemplateBundle,
  17. } from "../../lib/api/ticket";
  18. import { classifyTicketError } from "../../lib/ticket";
  19. const FIELD_TYPES: { code: string; label: string }[] = [
  20. { code: "text", label: "单行文本" },
  21. { code: "textarea", label: "多行文本" },
  22. { code: "number", label: "数字" },
  23. { code: "date", label: "日期" },
  24. { code: "select", label: "单选" },
  25. { code: "multiselect", label: "多选" },
  26. { code: "boolean", label: "是否" },
  27. { code: "material_ref", label: "材料引用" },
  28. ];
  29. function emptyField(): FormFieldSchema {
  30. return { key: "", label: "", type: "text", required: false };
  31. }
  32. function schemaFrom(raw: FormSchema | null | undefined): FormSchema {
  33. return {
  34. fields: Array.isArray(raw?.fields) ? raw!.fields.map((f) => ({ ...f, options: f.options ? [...f.options] : undefined })) : [],
  35. layout: { columns: raw?.layout?.columns === 1 ? 1 : 2 },
  36. };
  37. }
  38. export function FormTemplateAdminCard({ canEdit }: { canEdit: boolean }) {
  39. const [tab, setTab] = useState<string>("open");
  40. const [bundle, setBundle] = useState<FormTemplateBundle | null>(null);
  41. const [loading, setLoading] = useState(true);
  42. const [error, setError] = useState("");
  43. const [schema, setSchema] = useState<FormSchema>(() => schemaFrom(null));
  44. const [expectVersion, setExpectVersion] = useState<number | undefined>();
  45. const [templateId, setTemplateId] = useState<string | undefined>();
  46. const [busy, setBusy] = useState(false);
  47. const [tip, setTip] = useState("");
  48. const [ackOpen, setAckOpen] = useState(false);
  49. const load = useCallback(async (ticketType: string) => {
  50. setLoading(true);
  51. setError("");
  52. setTip("");
  53. try {
  54. const r = await formTemplateGet(ticketType);
  55. const item = r.items.find((x) => x.ticket_type === ticketType) ?? r.items[0] ?? null;
  56. setBundle(item);
  57. const draft = item?.draft;
  58. const base = draft ?? item?.published ?? null;
  59. setSchema(schemaFrom(base?.schema));
  60. setExpectVersion(draft ? Number(draft.row_version) : undefined);
  61. setTemplateId(draft?.template_id);
  62. } catch (e) {
  63. const c = classifyTicketError(e);
  64. setError(c.message);
  65. setBundle(null);
  66. } finally {
  67. setLoading(false);
  68. }
  69. }, []);
  70. useEffect(() => {
  71. void load(tab);
  72. }, [tab, load]);
  73. function patchField(i: number, patch: Partial<FormFieldSchema>) {
  74. setSchema((prev) => {
  75. const fields = prev.fields.map((f, idx) => (idx === i ? { ...f, ...patch } : f));
  76. return { ...prev, fields };
  77. });
  78. }
  79. async function saveDraft() {
  80. setTip("");
  81. setBusy(true);
  82. try {
  83. const r = await formTemplateSave({
  84. ticket_type: tab,
  85. schema,
  86. expect_version: expectVersion,
  87. template_id: templateId,
  88. });
  89. setTip(`草稿已保存(版本锁 ${r.row_version})。`);
  90. await load(tab);
  91. } catch (e) {
  92. const c = classifyTicketError(e);
  93. setTip(c.message);
  94. await load(tab);
  95. } finally {
  96. setBusy(false);
  97. }
  98. }
  99. async function publish(ack = false) {
  100. setTip("");
  101. setBusy(true);
  102. try {
  103. if (!templateId && !bundle?.draft?.template_id) {
  104. setTip("请先保存草稿再发布。");
  105. setBusy(false);
  106. return;
  107. }
  108. const tid = templateId ?? bundle?.draft?.template_id ?? "";
  109. const ev = expectVersion ?? Number(bundle?.draft?.row_version ?? 0);
  110. const r = await formTemplatePublish({
  111. ticket_type: tab,
  112. template_id: tid,
  113. expect_version: ev,
  114. ack_required_change: ack || undefined,
  115. });
  116. setAckOpen(false);
  117. setTip(`已发布为 v${r.version}。`);
  118. await load(tab);
  119. } catch (e) {
  120. const c = classifyTicketError(e);
  121. const raw = e as { detail?: { reason?: string }; data?: { reason?: string } };
  122. const reason = raw?.detail?.reason ?? raw?.data?.reason ?? "";
  123. if (String(c.message).includes("ack_required_change") || reason === "required_change_needs_ack") {
  124. setAckOpen(true);
  125. setTip(c.message);
  126. } else {
  127. setTip(c.message);
  128. await load(tab);
  129. }
  130. } finally {
  131. setBusy(false);
  132. }
  133. }
  134. const pub = bundle?.published;
  135. const history = (bundle?.versions ?? []).filter((v) => v.status !== "draft");
  136. return (
  137. <div className="ops-record-card" style={{ marginTop: 8 }}>
  138. <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 12 }}>
  139. {FORM_TEMPLATE_TICKET_TYPES.map((code) => (
  140. <Button
  141. key={code}
  142. type="button"
  143. size="sm"
  144. variant={tab === code ? "default" : "outline"}
  145. onClick={() => setTab(code)}
  146. >
  147. {TICKET_TYPE_NAMES[code] ?? code}
  148. </Button>
  149. ))}
  150. </div>
  151. {loading && <p className="ops-empty">正在读取扩展模板…</p>}
  152. {error && <p className="ops-empty" role="alert">{error}</p>}
  153. {!loading && !error && (
  154. <>
  155. <p>
  156. 当前已发布:
  157. {pub ? (
  158. <>
  159. <strong>v{pub.version}</strong>
  160. {pub.published_at ? ` · ${pub.published_at.slice(0, 19).replace("T", " ")}` : ""}
  161. · {pub.schema?.fields?.length ?? 0} 个字段
  162. </>
  163. ) : (
  164. <strong>无</strong>
  165. )}
  166. {bundle?.draft ? " · 有未发布草稿" : " · 无草稿"}
  167. <FieldHint label="扩展模板说明">
  168. 扩展字段不进竣工与计费;必填仅在执行结论为「成功」时由回填口强制。同类型同时只有一个已发布版本。
  169. </FieldHint>
  170. </p>
  171. <div className="ops-form-grid" style={{ marginTop: 12 }}>
  172. <label>
  173. 布局列数
  174. <select
  175. disabled={!canEdit || busy}
  176. value={schema.layout?.columns === 1 ? 1 : 2}
  177. onChange={(e) =>
  178. setSchema((s) => ({ ...s, layout: { columns: Number(e.target.value) === 1 ? 1 : 2 } }))
  179. }
  180. >
  181. <option value={2}>两列</option>
  182. <option value={1}>一列</option>
  183. </select>
  184. </label>
  185. </div>
  186. <h3 style={{ marginTop: 16, fontSize: 15 }}>字段</h3>
  187. {schema.fields.length === 0 && <p className="ops-muted">暂无字段;点「增加字段」开始编辑草稿。</p>}
  188. {schema.fields.map((f, i) => (
  189. <div key={i} className="ops-form-grid" style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid var(--ops-border, #e5e7eb)" }}>
  190. <label>
  191. key
  192. <input
  193. disabled={!canEdit || busy}
  194. value={f.key}
  195. placeholder="network_vendor"
  196. onChange={(e) => patchField(i, { key: e.target.value.trim() })}
  197. />
  198. </label>
  199. <label>
  200. 标签
  201. <input
  202. disabled={!canEdit || busy}
  203. value={f.label}
  204. onChange={(e) => patchField(i, { label: e.target.value })}
  205. />
  206. </label>
  207. <label>
  208. 类型
  209. <select
  210. disabled={!canEdit || busy}
  211. value={f.type}
  212. onChange={(e) => patchField(i, { type: e.target.value })}
  213. >
  214. {FIELD_TYPES.map((t) => (
  215. <option key={t.code} value={t.code}>
  216. {t.label}
  217. </option>
  218. ))}
  219. </select>
  220. </label>
  221. <label className="work-order-repeater-flag">
  222. <input
  223. type="checkbox"
  224. disabled={!canEdit || busy}
  225. checked={!!f.required}
  226. onChange={(e) => patchField(i, { required: e.target.checked })}
  227. />
  228. <span>必填(仅成功结论强制)</span>
  229. </label>
  230. <label className="wide">
  231. 说明
  232. <input
  233. disabled={!canEdit || busy}
  234. value={f.help ?? ""}
  235. onChange={(e) => patchField(i, { help: e.target.value || undefined })}
  236. />
  237. </label>
  238. {(f.type === "select" || f.type === "multiselect") && (
  239. <label className="wide">
  240. 选项(每行 value|label)
  241. <textarea
  242. rows={3}
  243. disabled={!canEdit || busy}
  244. value={(f.options ?? []).map((o) => `${o.value}|${o.label}`).join("\n")}
  245. onChange={(e) => {
  246. const options = e.target.value
  247. .split("\n")
  248. .map((line) => line.trim())
  249. .filter(Boolean)
  250. .map((line) => {
  251. const [value, ...rest] = line.split("|");
  252. return { value: value.trim(), label: (rest.join("|") || value).trim() };
  253. });
  254. patchField(i, { options });
  255. }}
  256. />
  257. </label>
  258. )}
  259. {canEdit && (
  260. <div className="ops-form-actions">
  261. <Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => setSchema((s) => ({ ...s, fields: s.fields.filter((_, j) => j !== i) }))}>
  262. 删除字段
  263. </Button>
  264. </div>
  265. )}
  266. </div>
  267. ))}
  268. {canEdit ? (
  269. <div className="ops-form-actions" style={{ marginTop: 16, gap: 8, display: "flex", flexWrap: "wrap" }}>
  270. <Button type="button" variant="outline" disabled={busy || schema.fields.length >= 30} onClick={() => setSchema((s) => ({ ...s, fields: [...s.fields, emptyField()] }))}>
  271. 增加字段
  272. </Button>
  273. <Button type="button" disabled={busy} onClick={() => void saveDraft()}>
  274. 保存草稿
  275. </Button>
  276. <Button type="button" disabled={busy || (!bundle?.draft && !templateId)} onClick={() => void publish(false)}>
  277. 发布
  278. </Button>
  279. </div>
  280. ) : (
  281. <p>扩展模板的改动仅总运营管理员可用,当前账号只读。</p>
  282. )}
  283. {tip && <p role="alert" className="work-order-form-error">{tip}</p>}
  284. {ackOpen && (
  285. <div role="dialog" style={{ marginTop: 12, padding: 12, border: "1px solid var(--ops-border, #e5e7eb)" }}>
  286. <p>新版本新增或改动了必填字段,在途工单将按新模板校验。确认继续发布?</p>
  287. <div className="ops-form-actions" style={{ display: "flex", gap: 8 }}>
  288. <Button type="button" disabled={busy} onClick={() => void publish(true)}>
  289. 确认并发布
  290. </Button>
  291. <Button type="button" variant="outline" disabled={busy} onClick={() => setAckOpen(false)}>
  292. 取消
  293. </Button>
  294. </div>
  295. </div>
  296. )}
  297. {history.length > 0 && (
  298. <>
  299. <h3 style={{ marginTop: 20, fontSize: 15 }}>历史版本</h3>
  300. <div className="work-order-table-wrap compact">
  301. <table>
  302. <thead>
  303. <tr>
  304. <th>版本</th>
  305. <th>状态</th>
  306. <th>字段数</th>
  307. <th>发布时间</th>
  308. </tr>
  309. </thead>
  310. <tbody>
  311. {history.map((v) => (
  312. <tr key={`${v.template_id}-${v.version}`}>
  313. <td>v{v.version}</td>
  314. <td>{v.status}</td>
  315. <td>{v.schema?.fields?.length ?? 0}</td>
  316. <td>{v.published_at ? v.published_at.slice(0, 19).replace("T", " ") : "—"}</td>
  317. </tr>
  318. ))}
  319. </tbody>
  320. </table>
  321. </div>
  322. </>
  323. )}
  324. </>
  325. )}
  326. </div>
  327. );
  328. }