491 lines
23 KiB
TypeScript
491 lines
23 KiB
TypeScript
/**
|
||
* OA 与"被嵌进来的那个页面"之间那几条消息的唯一口径。
|
||
*
|
||
* 单独一个文件是因为这里面的判断**必须能被测**:三道校验写在组件里就只能靠人肉点,
|
||
* 而这三道里少一道都不是"体验差一点",是别人家的页面能改这张单。方案见
|
||
* docs/embed-page-field-design.md §5,给对接方照抄的那一份在同文 §11。
|
||
*
|
||
* 三道校验,一条都不能少:
|
||
*
|
||
* 1. ``event.origin`` 等于发票那条地址的 origin——别的站点往顶层窗口 postMessage 是免费的;
|
||
* 2. ``event.source === iframe.contentWindow``——少了这一道,iframe 里 302 到别的站点之后,
|
||
* 那个站点同样能顶着同一个 origin 说话(origin 是它自己的,但它是"我们打开的那个 frame");
|
||
* 3. 装载前 OA 递一条一次性 ``nonce``,**要动数据的那一条**(``oa:result``)必须原样带回。
|
||
* ``oa:resize`` / ``oa:ready`` 这两条只改框高与那层"加载中",动不了数据,不逼对方带 nonce——
|
||
* 已经照 §11 实现了 resize 的页面不用改一行就能继续用,这也是把 nonce 只压在那一条上的理由。
|
||
*
|
||
* nonce 由 OA 前端现生成、只递给这一个 frame:它证明的是"说话的就是我刚装载的那个页面",
|
||
* 不是服务端凭证,所以不进地址、不进日志、也不经后端。真要在服务端判"这一格能不能改这几格",
|
||
* 那道闸在**设计期**(``service/embed.py:writeback_refusal``)——存下来之后没人能分辨某个值是
|
||
* 人在框里敲的还是 iframe 写进来的,所以判断必须压在保存那一刻,而不是事后。
|
||
*/
|
||
|
||
export const EMBED_HANDSHAKE = 'oa:handshake'
|
||
/** OA 回给对方那一句回执:哪几格收下了、哪几格为什么没收(``oa:result`` 之后才发) */
|
||
export const EMBED_ACK = 'oa:ack'
|
||
export const EMBED_READY = 'oa:ready'
|
||
export const EMBED_RESIZE = 'oa:resize'
|
||
export const EMBED_RESULT = 'oa:result'
|
||
/**
|
||
* 对方**自己那边**点完提交那一刻发的一句:「我这单子交出去了,你去看看成单了没有」。
|
||
*
|
||
* 它不动 OA 的任何数据,也不带 nonce(同 ``oa:ready`` / ``oa:resize``:那两条也只改
|
||
* 那层"加载中"和框高)。它换的是**时间**:第三方在自己页面点提交、再由他们的后端调
|
||
* OA 的发起接口,中间那一两秒里 OA 这一屏什么都不知道,只能按 ``STATE_POLL_MS`` 那一拍
|
||
* 问。发了这一句,OA 就在当场问、并且连着追问几拍,那一屏从"还停在编辑页"变成"一两秒内
|
||
* 自己走到那张单上"。不发也不影响正确性,只是慢一拍。
|
||
*/
|
||
export const EMBED_SUBMITTED = 'oa:submitted'
|
||
/** OA 往 iframe 里推那一份参数值(值变了但不想让人在半填的页面上被刷新) */
|
||
export const EMBED_PARAMS = 'oa:params'
|
||
/**
|
||
* 对方请 OA 做一件事:发起 / 存草稿 / 提交本环节 / 重新打开这一页。
|
||
*
|
||
* 与 ``oa:result`` 的区别是代价:那条只搬几个值进格子,这一条会让 OA 真的动一张单。
|
||
* 所以它必须带 nonce(同 ``oa:result``),而且**只能出现在这一格开放过的那几件事里**
|
||
* ——开放清单是后端算好随发票一起给的(``launchEmbed().actions``),前端不自己读配置。
|
||
*/
|
||
export const EMBED_ACTION = 'oa:action'
|
||
|
||
/** 那四件事的名字。与后端 ``service/embed.py:ACTIONS`` 一一对应,多一个少一个都是错 */
|
||
export const EMBED_ACTION_SUBMIT = 'submit'
|
||
export const EMBED_ACTION_SAVE = 'save'
|
||
export const EMBED_ACTION_DECIDE = 'decide'
|
||
export const EMBED_ACTION_REFRESH = 'refresh'
|
||
export const EMBED_ACTIONS: string[] = [
|
||
EMBED_ACTION_SUBMIT,
|
||
EMBED_ACTION_SAVE,
|
||
EMBED_ACTION_DECIDE,
|
||
EMBED_ACTION_REFRESH
|
||
]
|
||
|
||
/** 对方报的框高只认这个区间:比这小的看不见,比这大的会把整页顶走 */
|
||
export const EMBED_RESIZE_MIN = 160
|
||
export const EMBED_RESIZE_MAX = 4000
|
||
/** 一句 ``oa:result`` 最多带几个键、单个值最多多少字(与参数值那把尺子同量级) */
|
||
export const EMBED_RESULT_MAX_KEYS = 20
|
||
export const EMBED_RESULT_MAX_CHARS = 2000
|
||
|
||
/**
|
||
* 一条回填对应:``from`` 是对方 ``oa:result`` 里那个键,``to`` 是写进表单上哪一格的 key。
|
||
*
|
||
* 合成这份清单的口径不在这里(那边读配置,见 utils/formRuntime.ts:embedWritebackRulesOf),
|
||
* 这儿只管"来了一句回填,按这份清单落到哪一格"。同名直写就是 ``from === to`` 的那几条。
|
||
*/
|
||
export type EmbedWritebackRule = { from: string; to: string }
|
||
|
||
/** 对方照抄 OA 字段名时的那份清单:存量表单全是这一档 */
|
||
export function sameNameRules(keys?: string[] | null): EmbedWritebackRule[] {
|
||
return (keys ?? [])
|
||
.map((key) => String(key ?? '').trim())
|
||
.filter(Boolean)
|
||
.map((key) => ({ from: key, to: key }))
|
||
}
|
||
|
||
export type EmbedMessage =
|
||
| { kind: 'ready' }
|
||
| { kind: 'resize'; height: number }
|
||
/** 对方那边刚点了提交:不动数据,只让 OA 这一屏立刻去问一句「成单了吗」 */
|
||
| { kind: 'submitted' }
|
||
/**
|
||
* ``values`` 按**表单字段 key** 收(下游五道闸全按字段名判,不该再认对方的名字),
|
||
* ``sources`` 记下每一格是被对方哪个键写来的——回执要按对方的键回给他,不然他对着
|
||
* 自己那份 ``values`` 找不到被拒的是哪一条。
|
||
*/
|
||
| { kind: 'result'; values: Record<string, string>; sources: Record<string, string> }
|
||
/**
|
||
* 对方请 OA 动一张单。``values`` 是"先把这几格写上,再办这件事",走的是与
|
||
* ``oa:result`` 完全同一套落格判断(同一个 ``applyWriteback``),不在这里另开一条路。
|
||
*
|
||
* ``route`` / ``opinion`` 只在 ``decide`` 上有意义,而且只是**替这个人填好那两个字**:
|
||
* 提交那一步仍由屏幕上那个人按原来那颗按钮完成。外部系统可以提供值,不能决定流转,
|
||
* 这条红线在嵌页面这一档也一样不松(见 docs/embed-action-design.md §5)。
|
||
*/
|
||
| {
|
||
kind: 'action'
|
||
action: string
|
||
values: Record<string, string>
|
||
sources: Record<string, string>
|
||
route?: string
|
||
opinion?: string
|
||
}
|
||
|
||
/**
|
||
* 往上抛给"能提交这张单的那个人"(发起页 / 审批页)的那一份。
|
||
*
|
||
* 带 ``source`` 是因为属性面板上那一格的名字要出现在确认框里——「合同详情(ERP)要提交这张单」
|
||
* 说得清是谁在说话,「要提交这张单」说不清。
|
||
*/
|
||
export type EmbedActionRequest = {
|
||
action: string
|
||
values: Record<string, string>
|
||
route?: string
|
||
opinion?: string
|
||
/** 说这句话的那一格(要它的名字与 key) */
|
||
field?: { key?: string; label?: string }
|
||
/** 这一格在标签页里的哪一页;回填结果按页分开存,这句也得跟着 */
|
||
slot?: string
|
||
/**
|
||
* 提交之前要不要再问那个人一句。后端随发票给的(``launchEmbed().confirmAction``),
|
||
* 跟着这句话一起往上飘,是为了让发起页与审批页用的是同一份配置而不是各读一遍属性。
|
||
*/
|
||
confirm?: boolean
|
||
}
|
||
|
||
/*
|
||
* 没有 ``oa:title`` 这一条,是想过之后的决定:那一格叫什么由管理员在外部数据源注册表里
|
||
* 定(``oa_data_source.name``),不给外部页面改 OA 界面文案的口子——一个能自由改标题的
|
||
* 内嵌框,早晚被人用来在审批页上摆一句"本单已通过"。对方页面自己标题栏里写什么随它,
|
||
* OA 这一侧的字只有 OA 能写。
|
||
*/
|
||
|
||
/**
|
||
* 装载之后递给对方那一条:nonce、OA 自己的 origin,外加后端算好的那一份参数值。
|
||
*
|
||
* 值本来就在地址里,但让对端去解析自己的查询串是给自己找麻烦(尤其短码还在片段里);
|
||
* 直接给一份现成的,接口对接收一步就少一处能写歪的地方。
|
||
*/
|
||
export function embedHandshake(
|
||
nonce: string,
|
||
origin: string,
|
||
params: Record<string, string> = {},
|
||
extra: {
|
||
actions?: string[]
|
||
session?: Record<string, unknown> | null
|
||
prekey?: string
|
||
context?: Record<string, unknown> | null
|
||
} = {}
|
||
): Record<string, unknown> {
|
||
return {
|
||
type: EMBED_HANDSHAKE,
|
||
nonce,
|
||
origin,
|
||
params,
|
||
// 那三样都是后端给的,界面只是转述。prekey 单独提到顶层是为了让对方少解一层:
|
||
// 它是那一页唯一需要在**还没拿到单据**时就能报出口的东西(写在工单标题上、印在回执上)
|
||
actions: extra.actions ?? [],
|
||
prekey: extra.prekey ?? '',
|
||
session: extra.session ?? null,
|
||
context: extra.context ?? null
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 现编一条一次性 nonce。
|
||
*
|
||
* 用 ``crypto`` 而不是 ``Math.random``:后者可预测,而这条消息的唯一用途就是
|
||
* "证明说话的那个 frame 是我刚装载的",可预测就等于没这道闸。
|
||
*/
|
||
export function embedNonce(): string {
|
||
const buffer = new Uint8Array(16)
|
||
const crypto = globalThis.crypto as Crypto | undefined
|
||
if (crypto?.getRandomValues) {
|
||
crypto.getRandomValues(buffer)
|
||
} else {
|
||
for (let index = 0; index < buffer.length; index += 1) buffer[index] = Math.floor(Math.random() * 256)
|
||
}
|
||
return Array.from(buffer, (item) => item.toString(16).padStart(2, '0')).join('')
|
||
}
|
||
|
||
/** 只有 plain object 才认:数组、字符串、null 都不算(对方系统里一个 JSON 数组也能发过来) */
|
||
function plainObject(value: unknown): Record<string, unknown> | null {
|
||
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null
|
||
return value as Record<string, unknown>
|
||
}
|
||
|
||
/** 值只收能安全变成一行文本的那几种;对象与数组一律丢——回填进去的格子多半是个文本框 */
|
||
function asText(value: unknown): string {
|
||
if (typeof value === 'string') return value.trim()
|
||
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
|
||
return ''
|
||
}
|
||
|
||
/** 一句回填按那份对应关系落到哪几格:没收上来的那几格连键都不出现。 */
|
||
export type EmbedResolved = { values: Record<string, string>; sources: Record<string, string> }
|
||
|
||
/**
|
||
* 回填那份对应:只有点过名的格子收,其余一条都不写。
|
||
*
|
||
* **清单是空的就一条都不收**,这里必须"失败即关"。写成"空清单=没限制"太顺手也太自然,
|
||
* 而它的后果是属性面板上一个都没勾的那一格反而什么格子都能写——安全边界上最坏的那种默认值。
|
||
*
|
||
* 对方那个键叫什么在这儿只管一次(查表换成表单字段 key),往后的五道闸、界面上那句话、
|
||
* 写进 ``modelValue`` 的那个键,全按字段名走:外部系统的口径不许渗到这一层以外。
|
||
*/
|
||
function resolveTargets(values: Record<string, unknown>, rules: EmbedWritebackRule[] | undefined): EmbedResolved {
|
||
const byFrom = new Map<string, string>()
|
||
for (const rule of rules ?? []) {
|
||
const from = String(rule?.from ?? '').trim()
|
||
const to = String(rule?.to ?? '').trim()
|
||
if (from && to && !byFrom.has(from)) byFrom.set(from, to)
|
||
}
|
||
const valuesOut: Record<string, string> = {}
|
||
const sources: Record<string, string> = {}
|
||
if (!byFrom.size) return { values: valuesOut, sources }
|
||
for (const [key, raw] of Object.entries(values)) {
|
||
const to = byFrom.get(key.trim())
|
||
if (!to) continue
|
||
if (Object.keys(valuesOut).length >= EMBED_RESULT_MAX_KEYS) break
|
||
const text = asText(raw)
|
||
if (!text) continue
|
||
valuesOut[to] = text.slice(0, EMBED_RESULT_MAX_CHARS)
|
||
sources[to] = key.trim()
|
||
}
|
||
return { values: valuesOut, sources }
|
||
}
|
||
|
||
/**
|
||
* 把对方发来的那条消息读成一句听得懂的话;读不懂回 ``null``(不猜、不"大概是 resize 吧")。
|
||
*
|
||
* ``rules`` 是这一格点过名的那些对应(对方键 → 表单字段)。空数组与没给都一样:一条都不收,
|
||
* ``oa:result`` 最终读成 ``null``(属性面板上没勾过任何格子,就等于这条通道没开)。
|
||
*/
|
||
export function readEmbedMessage(
|
||
data: unknown,
|
||
opts: { nonce?: string; rules?: EmbedWritebackRule[]; actions?: string[] } = {}
|
||
): EmbedMessage | null {
|
||
const body = plainObject(data)
|
||
if (!body) return null
|
||
const type = String(body.type ?? '')
|
||
if (type === EMBED_READY) return { kind: 'ready' }
|
||
if (type === EMBED_SUBMITTED) return { kind: 'submitted' }
|
||
if (type === EMBED_RESIZE) {
|
||
const height = Number(body.height)
|
||
if (!Number.isFinite(height) || height < EMBED_RESIZE_MIN || height > EMBED_RESIZE_MAX) return null
|
||
return { kind: 'resize', height: Math.round(height) }
|
||
}
|
||
if (type === EMBED_RESULT) {
|
||
// 要动数据的那一条才必须带 nonce,而且必须一个字符都不差
|
||
if (!opts.nonce || String(body.nonce ?? '') !== opts.nonce) return null
|
||
const values = plainObject(body.values)
|
||
if (!values) return null
|
||
const picked = resolveTargets(values, opts.rules)
|
||
return Object.keys(picked.values).length ? { kind: 'result', ...picked } : null
|
||
}
|
||
if (type === EMBED_ACTION) {
|
||
// 两道闸:nonce 一个字符都不能差(同 oa:result),而且这件事**必须在开放清单里**。
|
||
// 清单是后端随发票给的,不在这里重读表单配置——两处判据迟早会漂成两套,
|
||
// 而它漂出来的样子是"界面上有那颗按钮,后端说没权限"
|
||
if (!opts.nonce || String(body.nonce ?? '') !== opts.nonce) return null
|
||
const action = String(body.action ?? '').trim()
|
||
if (!action || !(opts.actions ?? []).includes(action)) return null
|
||
const values = plainObject(body.values)
|
||
const picked = values ? resolveTargets(values, opts.rules) : { values: {}, sources: {} }
|
||
return {
|
||
kind: 'action',
|
||
action,
|
||
values: picked.values,
|
||
sources: picked.sources,
|
||
route: String(body.route ?? '').trim().slice(0, 120) || undefined,
|
||
opinion: String(body.opinion ?? '').trim().slice(0, EMBED_RESULT_MAX_CHARS) || undefined
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
/* ---------------------------------------------------------------------------
|
||
* 回执(OA → 对方)
|
||
*
|
||
* 发完 ``oa:result`` 就没了下文,对端只能显示"已提交",而 OA 这边可能一句
|
||
* 「金额那格:值不是一个数字」挂在格子底下——两边看见的不是同一件事,对接期这点最费时间:
|
||
* 对方以为写成功了,OA 这边根本没有。所以写完不管成没成都回一句,回执里只有字段名与
|
||
* 界面上那句一样的话,没有别的值(值本来就是他给我们的,回出去不增加任何泄露面)。
|
||
* ------------------------------------------------------------------------- */
|
||
|
||
/** 一格的回执:字段名加上给人看的那句 */
|
||
export type EmbedWritebackCell = { key: string; label: string }
|
||
export type EmbedWritebackRejection = { key: string; label: string; reason: string }
|
||
/** 一次 ``oa:result`` 处理完的结果,FormRenderer 算、EmbedFrame 显示并回执 */
|
||
export type EmbedWritebackOutcome = { accepted: EmbedWritebackCell[]; rejected: EmbedWritebackRejection[] }
|
||
|
||
/**
|
||
* ``sources`` 是这一句 ``oa:result`` 那份"字段 → 对方那个键":回执里的键回成**他发来的那个**,
|
||
* 而不是 OA 的字段名。同名直写时两者一样,配了对应时才看得出差别——对端拿回执是为了对着
|
||
* 自己发出去的那份值找哪条没收下,回一个他名单上没有的名字等于没回。
|
||
*/
|
||
export function embedAck(
|
||
nonce: string,
|
||
outcome: EmbedWritebackOutcome,
|
||
sources?: Record<string, string>
|
||
): { type: string; nonce: string; accepted: string[]; rejected: { key: string; reason: string }[] } {
|
||
const back = (key: string) => sources?.[key] ?? key
|
||
return {
|
||
type: EMBED_ACK,
|
||
nonce,
|
||
accepted: outcome.accepted.map((item) => back(item.key)),
|
||
rejected: outcome.rejected.map((item) => ({
|
||
key: back(item.key),
|
||
reason: item.reason.slice(0, EMBED_RESULT_MAX_CHARS)
|
||
}))
|
||
}
|
||
}
|
||
|
||
/** 装载后递给对方的那一份参数值:只装后端算出来的那几个键 */
|
||
export function embedParamsPush(
|
||
nonce: string,
|
||
params: Record<string, string>
|
||
): { type: string; nonce: string; params: Record<string, string> } {
|
||
return { type: EMBED_PARAMS, nonce, params }
|
||
}
|
||
|
||
/* ---------------------------------------------------------------------------
|
||
* 回填的值怎么落进这一格
|
||
*
|
||
* 对方发来的永远是文本(``postMessage`` 里什么都能装,但业务系统那边多半是拼出来的字符串),
|
||
* 而这一格可能是数字、是开关、是日期、是下拉里已有的某一项。**照类型收下来**是这里唯一
|
||
* 讲究的地方:把 "1,200.00" 原样写进一个 money 格,人看到的不是"外部页面写了什么",
|
||
* 而是提交时一句「金额不是数字」——那个红字追不回来源,比不写还糟。
|
||
*
|
||
* 所以收不下就当场说清楚是哪一格、为什么(``FormRenderer.applyWriteback`` 把这几句摆在
|
||
* iframe 下面),而不是先写进去再让人去猜校验为什么红。
|
||
* ------------------------------------------------------------------------- */
|
||
|
||
/** 结构类的那些格子:值不是"一行文本"能表达的东西,一律不收 */
|
||
const STRUCTURED_TYPES = [
|
||
'table',
|
||
'attachment',
|
||
'image',
|
||
'signature',
|
||
'user',
|
||
'dept',
|
||
'cascader',
|
||
'location',
|
||
'relation',
|
||
'daterange',
|
||
'timerange',
|
||
'months',
|
||
'auto',
|
||
'formula',
|
||
'embed',
|
||
'group',
|
||
'divider',
|
||
'description',
|
||
'spacer',
|
||
'hidden'
|
||
]
|
||
|
||
/** 开关那类的两种说法,中英文都收:对方系统给 true / 是 / 1 的都见过 */
|
||
const TRUTHY = ['1', 'true', 'yes', 'y', 'on', '是', '开', '同意']
|
||
const FALSY = ['0', 'false', 'no', 'n', 'off', '否', '关', '不同意']
|
||
|
||
export type WritebackValue = { ok: true; value: unknown } | { ok: false; reason: string }
|
||
|
||
/** 一个字段能收的回填值长什么样,只读这几样,不要求整份 FormFieldDef */
|
||
export type WritebackField = {
|
||
type?: string
|
||
multiple?: boolean
|
||
options?: { value: string | number; label?: string }[] | null
|
||
} | null | undefined
|
||
|
||
/** 拆列表用的那几种分隔符:中文顿号、逗号、分号、竖线,加换行 */
|
||
function splitList(text: string): string[] {
|
||
return text
|
||
.split(/[、,,;;|\n]+/)
|
||
.map((item) => item.trim())
|
||
.filter(Boolean)
|
||
}
|
||
|
||
/** 数字:千分位、全角逗号、货币符号、空白都先擦掉,剩下的必须整个是个数 */
|
||
function asNumber(text: string): number | null {
|
||
const clean = text.replace(/[,,\s\u00a5¥¥$€]/g, '')
|
||
if (!clean || !/^-?\d+(\.\d+)?$/.test(clean)) return null
|
||
const value = Number(clean)
|
||
return Number.isFinite(value) ? value : null
|
||
}
|
||
|
||
/**
|
||
* 日期类:只认这一格自己存的那种写法。
|
||
*
|
||
* 不做"尽力解析"(``new Date('1/2/2026')`` 那种):这一格的值最后要进 ``work.data`` 并被
|
||
* 条件与打印读,解析出一个带时区的 Date 再序列化,会写出一个看起来对、比一天差一天的值。
|
||
* 认不出就退回一句人话,让对方系统改口径——这是对接问题,不是运行时该猜的事。
|
||
*/
|
||
function asDate(text: string, kind: string): string | null {
|
||
const value = text.trim().replace(/\//g, '-')
|
||
if (kind === 'date') {
|
||
const match = /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?$/.exec(value)
|
||
if (!match) return null
|
||
const [, y, m, d] = match
|
||
return `${y}-${m.padStart(2, '0')}-${(d ?? '1').padStart(2, '0')}`
|
||
}
|
||
if (kind === 'month') {
|
||
const match = /^(\d{4})(?:-(\d{1,2}))?$/.exec(value)
|
||
if (!match) return null
|
||
const month = match[2]
|
||
return month ? `${match[1]}-${month.padStart(2, '0')}` : `${match[1]}-01`
|
||
}
|
||
if (kind === 'year') {
|
||
const year = asNumber(value)
|
||
return year !== null && Number.isInteger(year) && year >= 1900 && year <= 2999 ? String(year) : null
|
||
}
|
||
if (kind === 'time') {
|
||
const match = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(value)
|
||
if (!match) return null
|
||
return `${match[1].padStart(2, '0')}:${match[2]}`
|
||
}
|
||
// datetime:日期与时间中间给 T,秒不要
|
||
const match = /^(\d{4}-\d{1,2}-\d{1,2})[T ](\d{1,2}):(\d{2})(?::\d{2})?$/.exec(value)
|
||
if (!match) return null
|
||
return `${asDate(match[1], 'date')}T${match[2].padStart(2, '0')}:${match[3]}`
|
||
}
|
||
|
||
/** 下拉与单选的候选:优先按要存的值匹,其次按唯一的名称匹(对方给的是"已盖章"这种中文名) */
|
||
function matchOption(field: WritebackField, text: string): string | null {
|
||
const options = Array.isArray(field?.options) ? field?.options : []
|
||
if (!options.length) return text // 候选来自字典或外部源:本地没有清单,不瞎判
|
||
const hit = options.filter((item) => String(item.value) === text || String(item.label ?? '') === text)
|
||
if (!hit.length) return null
|
||
if (hit.length > 1) return null // 同名两项就让他自己选,别赌第一个
|
||
return String(hit[0].value)
|
||
}
|
||
|
||
/**
|
||
* 把对方给的那句话收成这一格存得下的值。
|
||
*
|
||
* 收不下时回的那句 reason 是要显示给人看的(``「金额」没写进来:值不是一个数字``),
|
||
* 所以宁可短、别绕。
|
||
*/
|
||
export function coerceWritebackValue(field: WritebackField, raw: string): WritebackValue {
|
||
const type = String(field?.type ?? '')
|
||
const text = String(raw ?? '').trim()
|
||
if (!text) return { ok: false, reason: '对方给的是空的' }
|
||
if (STRUCTURED_TYPES.includes(type)) {
|
||
return { ok: false, reason: '这一格的值不是一行文本能表达的,外部页面回填不了' }
|
||
}
|
||
if (type === 'number' || type === 'money') {
|
||
const value = asNumber(text)
|
||
return value === null ? { ok: false, reason: '值不是一个数字' } : { ok: true, value }
|
||
}
|
||
if (type === 'rate') {
|
||
const value = asNumber(text)
|
||
return value === null || !Number.isInteger(value) ? { ok: false, reason: '评分要是一个整数' } : { ok: true, value }
|
||
}
|
||
if (type === 'switch') {
|
||
const low = text.toLowerCase()
|
||
if (TRUTHY.includes(low)) return { ok: true, value: true }
|
||
if (FALSY.includes(low)) return { ok: true, value: false }
|
||
return { ok: false, reason: '开关只认 是/否、true/false、1/0 这一类写法' }
|
||
}
|
||
if (type === 'date' || type === 'datetime' || type === 'time' || type === 'month' || type === 'year') {
|
||
const value = asDate(text, type)
|
||
return value === null ? { ok: false, reason: `值不是${type === 'year' ? '年份' : type === 'time' ? '时间' : '这格要的日期写法'}(例如要 ${exampleOf(type)})` } : { ok: true, value }
|
||
}
|
||
const arrayed = type === 'checkbox' || type === 'week' || ((type === 'select' || type === 'picker') && Boolean(field?.multiple))
|
||
if (arrayed) {
|
||
const items = (splitList(text).length ? splitList(text) : [text]).map((item) => matchOption(field, item)).filter((item): item is string => item !== null)
|
||
return items.length ? { ok: true, value: items } : { ok: false, reason: '这些值都不在这一格的候选里' }
|
||
}
|
||
const single = matchOption(field, text)
|
||
if (single === null) return { ok: false, reason: '值不在这一格的候选里' }
|
||
return { ok: true, value: single }
|
||
}
|
||
|
||
/** 报错里给一个例子,比"格式不对"有用得多 */
|
||
function exampleOf(kind: string): string {
|
||
if (kind === 'datetime') return '2026-01-31T09:00'
|
||
if (kind === 'time') return '09:30'
|
||
if (kind === 'month') return '2026-03'
|
||
if (kind === 'year') return '2026'
|
||
return '2026-01-31'
|
||
}
|