PackagePlanEditor.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import { useEffect, useId, useMemo, useState, type FormEvent } from "react";
  2. import { FieldHint } from "./ui/field-hint";
  3. import { LockKeyhole, Plus, X } from "lucide-react";
  4. import { FetchError } from "./fetchError";
  5. import { planLockedFieldLabels, PLAN_COST_ITEM_SAVE_NOTE, WORD_FETCH_FAILED } from "../lib/api/lockedCopy";
  6. import { catalogCreate, catalogCustomerOptions, catalogUpdate, planCostItemList, planCostItemSave, rowsOf } from "../lib/api/bos";
  7. import type { CatalogPlanRow, IpBandwidthTierListResult, PlanCostItemRow } from "../lib/api/types";
  8. import { ApiError } from "../lib/api/http";
  9. import { useLoad, type Load } from "../lib/useLoad";
  10. import { COST_BILLING_UNIT, COST_CATEGORY, PLAN_FAMILY } from "../lib/api/labels";
  11. import { IP_TIER_UNCOMMITTED } from "../domain/contract-items";
  12. import { useCostItems } from "../lib/cost-demo";
  13. /** 目录档位编辑器(套餐页新增/编辑与合同页「就地新建本客户自定义档」共用)。 */
  14. export type EditorState = { plan?: CatalogPlanRow; owner: string | null; planKind?: "fixed" | "custom"; lockOwner?: boolean };
  15. export type EditorValues = {
  16. name: string; family: string; owner: string; annualPrice: string; quota: string;
  17. bandwidthMode: "committed" | "uncommitted" | ""; upload: string; download: string; description: string;
  18. };
  19. /** 成本项行=`plan_cost_item` 真实字段面(⛔ 本地「份数」口径,后端无该列)。
  20. * D-1:`cost_item_id` 为对全局 `cost_item` 的强引用,是选择成本项的唯一键;名称/类别/计费口径
  21. * 随选中的全局项带入并只读跟随,⛔ 自由文本录名。 */
  22. type CostDraft = { cost_item_id: string; item_name: string; amount: string; billing_unit: string; category: string; remark: string };
  23. /** 与后端 `COST_ITEMS_MAX`/openapi `maxItems: 50` 对齐。 */
  24. const COST_ITEMS_MAX = 50;
  25. /** 与后端 `NAME_MAX`/`QUOTA_MAX` 对齐。 */
  26. const PLAN_NAME_MAX = 128;
  27. const QUOTA_MAX = 9999;
  28. const BILLING_OPTIONS = Object.entries(COST_BILLING_UNIT);
  29. const CATEGORY_OPTIONS = Object.entries(COST_CATEGORY);
  30. const costDraftOf = (row: PlanCostItemRow): CostDraft => ({
  31. cost_item_id: row.cost_item_id ?? "",
  32. item_name: row.item_name ?? "",
  33. amount: row.amount_cents === null || row.amount_cents === undefined ? "" : String(row.amount_cents / 100),
  34. billing_unit: row.billing_unit ?? "",
  35. category: row.category ?? "",
  36. remark: row.remark ?? "",
  37. });
  38. const costRowOf = (draft: CostDraft): PlanCostItemRow => ({
  39. cost_item_id: draft.cost_item_id.trim(),
  40. item_name: draft.item_name.trim(),
  41. amount_cents: draft.amount.trim() === "" ? null : Math.round(Number(draft.amount) * 100),
  42. billing_unit: draft.billing_unit.trim() || null,
  43. category: draft.category.trim() || null,
  44. remark: draft.remark.trim() || null,
  45. });
  46. const emptyCost = (): CostDraft => ({ cost_item_id: "", item_name: "", amount: "", billing_unit: "", category: "", remark: "" });
  47. export function formOf(plan: CatalogPlanRow | undefined, owner: string | null): EditorValues {
  48. const committed = plan?.bandwidth_committed;
  49. const up = plan?.bandwidth_up_mbps;
  50. const down = plan?.bandwidth_down_mbps;
  51. /** 存量 DEFAULT TRUE + 上下行空:按「不承诺」回显,⛔ 开成承诺态却两格空白。 */
  52. const bandwidthMode: EditorValues["bandwidthMode"] =
  53. committed === undefined || committed === null
  54. ? ""
  55. : committed && up != null && down != null
  56. ? "committed"
  57. : "uncommitted";
  58. return {
  59. name: plan?.plan_name ?? "",
  60. family: plan?.plan_family ?? (owner === null ? "link" : ""),
  61. owner: plan?.customer_id ?? owner ?? "",
  62. annualPrice: plan?.annual_price_cents === undefined || plan.annual_price_cents === null ? "" : String(plan.annual_price_cents / 100),
  63. quota: plan?.sub_account_quota === undefined || plan.sub_account_quota === null ? "" : String(plan.sub_account_quota),
  64. bandwidthMode,
  65. upload: up === null || up === undefined ? "" : String(up),
  66. download: down === null || down === undefined ? "" : String(down),
  67. description: plan?.plan_desc ?? "",
  68. };
  69. }
  70. const tierKeyOf = (mbps: number | null) => (mbps === null ? IP_TIER_UNCOMMITTED : `mbps-${mbps}`);
  71. function CatalogInfo({ label, children }: { label: string; children: string }) {
  72. return <FieldHint label={label}>{children}</FieldHint>;
  73. }
  74. export function PackagePlanEditor({ state, tiers, onClose, onSaved }: {
  75. state: EditorState; tiers: Load<IpBandwidthTierListResult>; onClose: () => void; onSaved: (message: string, savedPlan: CatalogPlanRow | null) => void;
  76. }) {
  77. const original = state.plan;
  78. /** 锁定:被引用冻结(K204);页面放开名称/说明/成本项,服务端裁决后原样回显拒绝原因。 */
  79. const locked = Boolean(original && original.frozen === true);
  80. const isCustom = original ? original.plan_kind === "custom" : (state.planKind ?? (state.owner === null ? "fixed" : "custom")) === "custom";
  81. const ownerLocked = Boolean(state.lockOwner);
  82. const settlementId = useId();
  83. const [values, setValues] = useState(() => formOf(original, state.owner));
  84. const [costs, setCosts] = useState<CostDraft[]>([]);
  85. const [costsDirty, setCostsDirty] = useState(false);
  86. const [error, setError] = useState("");
  87. const costLoad = useLoad(
  88. () => (original ? planCostItemList({ plan_id: original.plan_id }).then(rowsOf) : Promise.resolve([] as PlanCostItemRow[])),
  89. [original?.plan_id],
  90. );
  91. useEffect(() => {
  92. if (original && costLoad.data && !costsDirty) setCosts(costLoad.data.map(costDraftOf));
  93. }, [costLoad.data, original, costsDirty]);
  94. useEffect(() => {
  95. const dialog = document.getElementById("catalog-editor") as HTMLDialogElement | null;
  96. const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
  97. if (!dialog) return;
  98. const previousOverflow = document.body.style.overflow;
  99. document.body.style.overflow = "hidden";
  100. dialog.showModal();
  101. return () => { dialog.close(); document.body.style.overflow = previousOverflow; previous?.focus(); };
  102. }, []);
  103. /** 归属客户可选项:后端下发的操作人可见客户集合,⛔ 前端拼权限。 */
  104. const customerOptions = useLoad(() => catalogCustomerOptions().then(rowsOf), []);
  105. /** 全局成本项清单(D-1:只能从此清单按 id 选择,⛔ 自由文本录名)。allPages 取满,避免下拉被分页截断。 */
  106. const costItemCatalog = useCostItems({ allPages: true });
  107. const globalCostItems = costItemCatalog.data?.items ?? [];
  108. /** 选中全局成本项 ⇒ 把 id+名称+类别+计费口径带入该行(金额/备注仍可编辑)。 */
  109. const pickGlobalCostItem = (index: number, costItemId: string) => {
  110. const picked = globalCostItems.find((it) => it.id === costItemId);
  111. setCostsDirty(true);
  112. setCosts((current) => current.map((item, i) => i === index
  113. ? {
  114. ...item,
  115. cost_item_id: picked?.id ?? "",
  116. item_name: picked?.name ?? item.item_name,
  117. category: picked?.categoryKey ?? "",
  118. billing_unit: picked?.billingUnitKey ?? "",
  119. }
  120. : item));
  121. setError("");
  122. };
  123. const field = <K extends keyof EditorValues>(key: K, value: EditorValues[K]) => {
  124. setValues((current) => ({ ...current, [key]: value }));
  125. setError("");
  126. };
  127. /** 带宽档位快捷(2026-11-17 业主裁定):套餐配置里维护的档位即带宽权益的预设备选。
  128. * 点一条=上下行同值填入;「不承诺带宽」档只切口径、⛔ 清空两格(同 CU-D5 的置灰不清空纪律)。 */
  129. const tierPresets = useMemo(() => {
  130. const seen = new Set<string>();
  131. const rows: { key: string; label: string; mbps: number | null }[] = [];
  132. for (const item of tiers.data?.items ?? []) {
  133. const key = tierKeyOf(item.bandwidth_tier_mbps ?? null);
  134. if (seen.has(key)) continue;
  135. seen.add(key);
  136. rows.push({ key, label: item.bandwidth_tier_mbps === null ? "不承诺带宽" : item.tier_name || `${item.bandwidth_tier_mbps} 兆`, mbps: item.bandwidth_tier_mbps ?? null });
  137. }
  138. return rows;
  139. }, [tiers.data]);
  140. const applyTier = (mbps: number | null) => {
  141. setValues((current) => mbps === null
  142. ? { ...current, bandwidthMode: "uncommitted" }
  143. : { ...current, bandwidthMode: "committed", upload: String(mbps), download: String(mbps) });
  144. setError("");
  145. };
  146. async function submit(event: FormEvent<HTMLFormElement>) {
  147. event.preventDefault();
  148. const name = values.name.trim();
  149. const owner = state.owner === null ? null : values.owner;
  150. if (!name) { setError("请填写套餐名称。"); return; }
  151. if (owner !== null && !owner) { setError("请选择归属客户。"); return; }
  152. if (costLoad.error && costsDirty) { setError("成本项取数失败,整段保存会覆盖后端构成,请重试或放弃本次改动。"); return; }
  153. if (!values.family) { setError("请选择交付形态(跨境链路/叠加服务)。"); return; }
  154. const isLink = values.family === "link";
  155. let annualPrice = 0;
  156. let quota = 0;
  157. let upload: number | null = null;
  158. let download: number | null = null;
  159. if (!locked) {
  160. if (!/^\d+(?:\.\d{1,2})?$/.test(values.annualPrice) || !Number.isFinite(Number(values.annualPrice)) || Number(values.annualPrice) < 0 || Number(values.annualPrice) > 10_000_000) {
  161. setError("年订阅价格需为非负金额。"); return;
  162. }
  163. annualPrice = Number(values.annualPrice);
  164. if (isLink) {
  165. if (!/^\d+$/.test(values.quota) || Number(values.quota) <= 0) { setError("跨境链路档的分账号额度须为正整数。"); return; }
  166. quota = Number(values.quota);
  167. if (quota > QUOTA_MAX) { setError(`分账号额度须在 1~${QUOTA_MAX} 之间。`); return; }
  168. if (values.bandwidthMode === "") { setError("请选择带宽口径(承诺或不承诺)。"); return; }
  169. if (values.bandwidthMode === "committed") {
  170. // 成对校验(D-PKG-05):缺格 ⇒ 指名填哪一向;越界 ⇒ 1–1000。
  171. if (!values.upload.trim()) { setError("请填写上行带宽(承诺带宽时上下行须成对填写)。"); return; }
  172. if (!values.download.trim()) { setError("请填写下行带宽(承诺带宽时上下行须成对填写)。"); return; }
  173. upload = Number(values.upload);
  174. download = Number(values.download);
  175. if (!/^\d+$/.test(values.upload) || !/^\d+$/.test(values.download) || upload < 1 || upload > 1000 || download < 1 || download > 1000) {
  176. setError("上行和下行带宽须分别为 1–1000 Mbps 的整数。"); return;
  177. }
  178. }
  179. } else {
  180. // 叠加服务额度恒 0、不设任何带宽列(D-15/D-18)。
  181. quota = 0;
  182. }
  183. }
  184. if (costs.length > COST_ITEMS_MAX) {
  185. setError(`成本项最多 ${COST_ITEMS_MAX} 条,请删减后重试。`); return;
  186. }
  187. if (costs.some((cost) => !cost.cost_item_id.trim() || (cost.amount.trim() !== "" && !/^\d+(?:\.\d{1,2})?$/.test(cost.amount.trim())))) {
  188. setError("成本项需从全局清单选择(D-1:按 id 引用,⛔ 自由录名),金额留空表示未配置、否则为非负金额。"); return;
  189. }
  190. const costRows = costs.map(costRowOf);
  191. /** 契约:开关关闭⇒上行/下行两格⛔ 提交(服务端记 FALSE +两列 NULL)。 */
  192. const bandwidth = isLink
  193. ? values.bandwidthMode === "committed" && upload !== null && download !== null
  194. ? { bandwidth_committed: true, bandwidth_up_mbps: upload, bandwidth_down_mbps: download }
  195. : { bandwidth_committed: false }
  196. : { bandwidth_committed: false };
  197. try {
  198. if (!original) {
  199. const created = await catalogCreate({
  200. plan_kind: owner === null ? "fixed" : "custom",
  201. plan_name: name,
  202. plan_family: values.family,
  203. annual_price_cents: Math.round(annualPrice * 100),
  204. sub_account_quota: quota,
  205. ...bandwidth,
  206. ...(owner ? { customer_id: owner } : {}),
  207. ...(values.description.trim() ? { plan_desc: values.description.trim() } : {}),
  208. ...(costRows.length ? { cost_items: costRows } : {}),
  209. });
  210. /** 就地新建的调用方要拿新档继续填条目 ⇒ 回一份最小行(字段面与列表行同键)。 */
  211. onSaved(`${name}已新建。`, {
  212. plan_id: created.plan_id,
  213. plan_name: name,
  214. plan_kind: owner === null ? "fixed" : "custom",
  215. plan_family: values.family,
  216. annual_price_cents: Math.round(annualPrice * 100),
  217. sub_account_quota: quota,
  218. bandwidth_committed: bandwidth.bandwidth_committed ? true : false,
  219. bandwidth_up_mbps: (bandwidth as { bandwidth_up_mbps?: number | null }).bandwidth_up_mbps ?? null,
  220. bandwidth_down_mbps: (bandwidth as { bandwidth_down_mbps?: number | null }).bandwidth_down_mbps ?? null,
  221. customer_id: owner || null,
  222. status: "active",
  223. created_at: "",
  224. row_version: "",
  225. });
  226. return;
  227. }
  228. await catalogUpdate({
  229. plan_id: original.plan_id,
  230. plan_name: name,
  231. plan_desc: values.description.trim(),
  232. ...(locked ? {} : {
  233. annual_price_cents: Math.round(annualPrice * 100),
  234. sub_account_quota: quota,
  235. ...bandwidth,
  236. }),
  237. ...(original.row_version === undefined || original.row_version === null || original.row_version === "" ? {} : { row_version: Number(original.row_version) }),
  238. });
  239. if (costsDirty) await planCostItemSave({ plan_id: original.plan_id, items: costRows });
  240. onSaved(`${name}已保存。`, original);
  241. } catch (e) {
  242. setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。");
  243. }
  244. }
  245. const settlement = locked
  246. ? (original?.monthly_settle_cents === null || original?.monthly_settle_cents === undefined ? "" : String(original.monthly_settle_cents / 100))
  247. : values.annualPrice && /^\d+(?:\.\d{1,2})?$/.test(values.annualPrice)
  248. ? (Math.floor(Math.round(Number(values.annualPrice) * 100) / 12) / 100).toFixed(2)
  249. : "";
  250. const isLinkValue = values.family === "link";
  251. const lockedLabels = planLockedFieldLabels(original?.locked_fields);
  252. return <dialog id="catalog-editor" className="catalog-editor" aria-labelledby="catalog-editor-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
  253. <header className="catalog-editor-head"><div><span>{isCustom ? "客户专属套餐" : "公共固定套餐"}</span><h2 id="catalog-editor-title">{original ? "编辑套餐档位" : "新增套餐档位"}</h2></div><button type="button" aria-label="关闭" className="catalog-icon-button" onClick={onClose}><X size={19} /></button></header>
  254. <form onSubmit={submit} className="catalog-editor-body">
  255. {locked && <div className="catalog-locked-note"><LockKeyhole size={18} /><p>已被 {original?.referred_count ?? "—"} 处引用,字段「{lockedLabels.join("、")}」已锁定;调整价格或额度请新建档位,再升级订阅。</p></div>}
  256. <section><h3><span>01</span> 基本信息</h3><label>套餐名称 <em>*</em><input autoFocus required maxLength={PLAN_NAME_MAX} value={values.name} onChange={(event) => field("name", event.target.value)} placeholder="输入套餐名称" /></label>
  257. <div className="catalog-editor-grid">
  258. <label>交付形态 <em>*</em>
  259. <select disabled={Boolean(original) || locked} value={values.family} onChange={(event) => field("family", event.target.value)}>
  260. {!values.family && <option value="">未配置</option>}
  261. {Object.entries(PLAN_FAMILY).map(([value, text]) => <option key={value} value={value}>{text}</option>)}
  262. </select>
  263. </label>
  264. <label>订阅周期<input disabled value="按年" /></label>
  265. </div>
  266. {isCustom && <label>归属客户 <em>*</em>
  267. <select disabled={locked || ownerLocked || Boolean(original)} required value={values.owner} onChange={(event) => field("owner", event.target.value)}>
  268. <option value="">{customerOptions.loading ? "载入中…" : customerOptions.error ? WORD_FETCH_FAILED : "选择客户"}</option>
  269. {(customerOptions.data ?? []).map((item) => <option key={item.customer_id} value={item.customer_id}>{item.customer_name}</option>)}
  270. </select>
  271. {customerOptions.error && <FetchError message={customerOptions.error.message} onRetry={customerOptions.reload} className="catalog-editor-error" />}
  272. </label>}
  273. </section>
  274. <section>
  275. <h3><span>02</span> 价格与额度</h3>
  276. <div className="catalog-editor-grid">
  277. <label>
  278. 年订阅价格<span className="sr-only">(元)</span> <em>*</em>
  279. <span className="catalog-price-input">
  280. <input disabled={locked} inputMode="decimal" value={values.annualPrice} onChange={(event) => field("annualPrice", event.target.value)} placeholder="0.00" />
  281. <span className="catalog-price-unit" aria-hidden="true">元</span>
  282. </span>
  283. </label>
  284. <div>
  285. <div className="catalog-heading-with-info">
  286. <label htmlFor={settlementId}>月结算标准<span className="sr-only">(元)</span></label>
  287. <CatalogInfo label="月结算标准说明">年订阅价格除以 12 后向下取整到分。订阅签约时可按合同冻结价格。</CatalogInfo>
  288. </div>
  289. <span className="catalog-price-input">
  290. <input id={settlementId} disabled value={settlement} placeholder="由年价自动计算" />
  291. <span className="catalog-price-unit" aria-hidden="true">元</span>
  292. </span>
  293. </div>
  294. </div>
  295. {isLinkValue
  296. ? <label>分账号额度(个) <em>*</em><input disabled={locked} inputMode="numeric" value={values.quota} onChange={(event) => field("quota", event.target.value)} placeholder="0" /></label>
  297. : <label>分账号额度(个)<input disabled value="0(叠加服务额度恒 0,D-15)" /></label>}
  298. </section>
  299. {isLinkValue && <section><h3><span>03</span> 带宽与权益</h3><label className="catalog-bandwidth-field">带宽口径<select disabled={locked} value={values.bandwidthMode} onChange={(event) => field("bandwidthMode", event.target.value as EditorValues["bandwidthMode"])}>{values.bandwidthMode === "" && <option value="">未配置</option>}<option value="committed">承诺上下行带宽</option><option value="uncommitted">不承诺带宽</option></select></label>
  300. {/* 两格**常驻**、非承诺时置灰但⛔ 清空:卸载再挂载会让回切后输入框回读空串
  301. (18 册 CU-D5),且 DOM 与 state 脱节。 */}
  302. <div className="catalog-editor-grid"><label>上行带宽(Mbps)<input disabled={locked || values.bandwidthMode !== "committed"} inputMode="numeric" value={values.upload} onChange={(event) => field("upload", event.target.value)} placeholder="1–1000" /></label><label>下行带宽(Mbps)<input disabled={locked || values.bandwidthMode !== "committed"} inputMode="numeric" value={values.download} onChange={(event) => field("download", event.target.value)} placeholder="1–1000" /></label></div>
  303. {!locked && tierPresets.length > 0 && <div className="catalog-bandwidth-presets">
  304. <span className="catalog-bandwidth-presets-label">档位快捷<small>(取自「线路出口」Tab 的带宽档位)</small></span>
  305. <div className="catalog-bandwidth-presets-list">
  306. {tierPresets.map((preset) => {
  307. const on = preset.mbps === null
  308. ? values.bandwidthMode === "uncommitted"
  309. : values.bandwidthMode === "committed" && values.upload.trim() === String(preset.mbps) && values.download.trim() === String(preset.mbps);
  310. return <button key={preset.key} type="button" aria-pressed={on} className={`catalog-bandwidth-preset${on ? " is-on" : ""}`} title={preset.mbps === null ? "口径设为不承诺带宽(两格仅置灰,⛔ 不清空)" : `上下行各 ${preset.mbps} Mbps`} onClick={() => applyTier(preset.mbps)}>{preset.label}</button>;
  311. })}
  312. </div>
  313. </div>}
  314. <p>带宽作为套餐属性保存,首期不按带宽拆分计价。</p></section>}
  315. <section><h3><span>{isLinkValue ? "04" : "03"}</span> 套餐说明</h3><label>套餐说明<textarea rows={4} value={values.description} onChange={(event) => field("description", event.target.value)} placeholder="说明适用场景、服务权益和报价口径" /></label></section>
  316. <section className="catalog-cost-editor">
  317. <div className="catalog-heading-with-info">
  318. <h3><span>{isLinkValue ? "05" : "04"}</span> 月成本项</h3>
  319. <CatalogInfo label="月成本项说明">{`${PLAN_COST_ITEM_SAVE_NOTE}(整段全量替换,逐行增删不单独提交;最多 ${COST_ITEMS_MAX} 条)`}</CatalogInfo>
  320. </div>
  321. {costLoad.error && <FetchError message={costLoad.error.message} onRetry={costLoad.reload} className="catalog-editor-error" />}
  322. {costs.length > 0 && <div className="catalog-cost-editor-head" aria-hidden="true"><span>成本项</span><span>金额(元)</span><span>计价口径</span><span>类别</span><span /></div>}
  323. {costItemCatalog.error && <FetchError message={costItemCatalog.error.message} onRetry={costItemCatalog.reload} className="catalog-editor-error" />}
  324. {costs.map((cost, index) => <div className="catalog-cost-editor-row" key={index}>
  325. <div className="catalog-cost-field">
  326. <span className="catalog-cost-field-label" aria-hidden="true">成本项</span>
  327. <select aria-label={`成本项 ${index + 1}`} value={cost.cost_item_id} onChange={(event) => pickGlobalCostItem(index, event.target.value)} disabled={costItemCatalog.loading && globalCostItems.length === 0} title="从全局成本项清单选择">
  328. <option value="">{costItemCatalog.loading ? "载入中…" : costItemCatalog.error ? WORD_FETCH_FAILED : "选择成本项"}</option>
  329. {globalCostItems.map((it) => <option key={it.id} value={it.id}>{it.name}</option>)}
  330. {cost.cost_item_id && !globalCostItems.some((it) => it.id === cost.cost_item_id) && (
  331. <option value={cost.cost_item_id}>{cost.item_name || cost.cost_item_id}(全局已删除)</option>
  332. )}
  333. </select>
  334. </div>
  335. <div className="catalog-cost-field">
  336. <span className="catalog-cost-field-label" aria-hidden="true">金额(元)</span>
  337. <input aria-label={`成本项 ${index + 1} 金额`} inputMode="decimal" maxLength={14} value={cost.amount} onChange={(event) => { setCostsDirty(true); setCosts((current) => current.map((item, i) => i === index ? { ...item, amount: event.target.value } : item)); }} placeholder="金额" />
  338. </div>
  339. <div className="catalog-cost-field">
  340. <span className="catalog-cost-field-label" aria-hidden="true">计价口径</span>
  341. <input readOnly aria-label={`成本项 ${index + 1} 计价口径`} value={BILLING_OPTIONS.find(([value]) => value === cost.billing_unit)?.[1] ?? "未配置"} title="随选中的全局成本项带入" />
  342. </div>
  343. <div className="catalog-cost-field">
  344. <span className="catalog-cost-field-label" aria-hidden="true">类别</span>
  345. <input readOnly aria-label={`成本项 ${index + 1} 类别`} value={CATEGORY_OPTIONS.find(([value]) => value === cost.category)?.[1] ?? "未配置"} title="随选中的全局成本项带入" />
  346. </div>
  347. <button aria-label={`移除成本项 ${index + 1}`} onClick={() => { setCostsDirty(true); setCosts((current) => current.filter((_, i) => i !== index)); }} type="button"><X size={16} /></button>
  348. </div>)}
  349. <button
  350. className="catalog-cost-add"
  351. type="button"
  352. aria-disabled={costs.length >= COST_ITEMS_MAX}
  353. aria-describedby={costs.length >= COST_ITEMS_MAX ? "catalog-cost-limit-note" : undefined}
  354. title={costs.length >= COST_ITEMS_MAX ? `成本项最多 ${COST_ITEMS_MAX} 条` : undefined}
  355. onClick={() => {
  356. if (costs.length >= COST_ITEMS_MAX) {
  357. setError(`成本项最多 ${COST_ITEMS_MAX} 条(收到 ${COST_ITEMS_MAX + 1})`);
  358. return;
  359. }
  360. setCostsDirty(true);
  361. setCosts((current) => [...current, emptyCost()]);
  362. }}
  363. ><Plus size={15} /> 添加成本项{costs.length > 0 ? `(${costs.length}/${COST_ITEMS_MAX})` : ""}</button>
  364. {costs.length >= COST_ITEMS_MAX && <p id="catalog-cost-limit-note" className="catalog-cost-limit-note" role="status" aria-live="polite">成本项最多 {COST_ITEMS_MAX} 条,请删减后再添加。</p>}
  365. </section>
  366. {error && <p className="catalog-editor-error" role="alert" aria-live="assertive">{error}</p>}
  367. <footer><button type="button" className="catalog-button catalog-button-secondary" onClick={onClose}>取消</button><button type="submit" className="catalog-button catalog-button-primary">{original ? "保存修改" : "新建套餐"}</button></footer>
  368. </form>
  369. </dialog>;
  370. }