Files
crawler-plugin/admin-frontend-vue/tests/date-range-order.test.ts
T

312 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { fileURLToPath } from 'node:url'
import { resolve, dirname, join } from 'node:path'
import { orderedPair } from '../src/utils/datetime.ts'
/**
* 全项目时间控件顺序尺子(2026-10-09)。
*
* 起因:用户指令"项目所有的前端时间控件 开始日期不能晚于结束日期"。普查
* (ops 仓 scripts/_census_time_controls.py)在四棵活树里数出 55 个日期/时间控件实例、
* 21 个成对区间,其中后管 8 对与麦象控制台 2 对两头裸奔——起止能选到倒挂,查询恒定
* 返回空表,页面上却没有任何提示。
*
* 每一对成对控件判两条,缺一即红:
* ① 日历面板禁选:起侧 max 指向止、止侧 min 指向起;
* ② 手输兜底:值落回状态时把倒挂的两端交换(本树 @change="clampDatePair",
* 财务系统走 useDateRange 的 setter)。
* 只做 ① 不够:原生 input 手输、粘贴仍能越界,浏览器只把控件标成 :invalid,
* 状态里留下的还是倒挂值。
*
* 分母硬钉(实例数/对数):扫描器一旦失明(改写法、挪目录、文件名换了),
* 当场判红,而不是拿着"0 违规"报绿。
*/
const here = dirname(fileURLToPath(import.meta.url))
const WS = resolve(here, '../../..')
const DATE_TYPES = new Set(['date', 'datetime-local', 'month', 'week', 'time'])
const RANGE_TYPES = new Set(['daterange', 'datetimerange', 'monthrange', 'yearsrange', 'dates', 'times'])
const PICKERS = new Set(['el-date-picker', 'el-time-picker', 'el-time-select', 'datepicker', 'rangepicker'])
const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', '.venv', '__pycache__', 'target', 'app_resource', 'app_client_baseline', 'crawler_cache'])
const EXTS = new Set(['.vue', '.tsx', '.jsx', '.ts', '.js', '.html'])
interface Control {
file: string
line: number
type: string
model: string
role: 'start' | 'end' | 'single' | 'range'
family: string
minToPartner: boolean
maxToPartner: boolean
clamp: boolean
}
function walk(base: string): string[] {
const out: string[] = []
for (const name of readdirSync(base)) {
const p = join(base, name)
const st = statSync(p)
if (st.isDirectory()) {
if (!SKIP_DIRS.has(name)) out.push(...walk(p))
} else if (EXTS.has(name.slice(name.lastIndexOf('.'))) && !/\.(test|spec)\.[tj]sx?$/.test(name)) {
out.push(p)
}
}
return out
}
/** 注释区涂成等长空格(保住行号);引号里的 // 不当注释。 */
function blankComments(src: string): string {
const out = src.split('')
let i = 0
let q: string | null = null
while (i < src.length) {
const c = src[i]
if (q) {
if (c === '\\') i += 2
else if (c === q) { q = null; i += 1 }
else i += 1
continue
}
if (c === '"' || c === "'" || c === '`') { q = c; i += 1; continue }
let end = -1
if (src.startsWith('<!--', i)) { const j = src.indexOf('-->', i); end = j < 0 ? src.length : j + 3 }
else if (src.startsWith('/*', i)) { const j = src.indexOf('*/', i); end = j < 0 ? src.length : j + 2 }
else if (src.startsWith('//', i)) { const j = src.indexOf('\n', i); end = j < 0 ? src.length : j }
if (end > i) {
for (let k = i; k < end; k++) if (out[k] !== '\n') out[k] = ' '
i = end
continue
}
i += 1
}
return out.join('')
}
/** 从 '<' 取到配平的 '>':跳过引号与 JSX 花括号里的 '>'。 */
function tagSlice(src: string, from: number): string {
let depth = 0
let q: string | null = null
for (let i = from; i < src.length; i++) {
const c = src[i]
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue }
if (c === '"' || c === "'" || c === '`') { q = c; continue }
if (c === '{' || c === '(' || c === '[') depth++
else if (c === '}' || c === ')' || c === ']') depth--
else if (c === '>' && depth === 0) return src.slice(from, i + 1)
}
return src.slice(from)
}
function quotedAttr(tag: string, name: string): string {
const m = new RegExp('[\\s:]' + name + '\\s*=\\s*"([^"]*)"', 'i').exec(tag)
return m ? m[1] : ''
}
function bracedAttr(tag: string, name: string): string {
const m = new RegExp('[\\s:]' + name + '\\s*=\\{([^}]*)\\}', 'i').exec(tag)
return m ? m[1].trim() : ''
}
function modelOf(tag: string): string {
const vue = /[\s]v-model(?::[\w-]+)?(?:\.\w+)*="([^"]*)"/.exec(tag)
if (vue) return vue[1]
const bound = /[\s]:model-value="([^"]*)"/.exec(tag)
if (bound) return bound[1]
const jsx = /\bvalue=\{([^}]*)\}/.exec(tag)
if (jsx) return jsx[1].replace(/^String\(/, '').replace(/\|\|.*$/, '').replace(/[()'\s"]/g, '')
return quotedAttr(tag, 'name') || quotedAttr(tag, 'id')
}
const isStartWord = /start|begin|first|from|\[0\]/i
// to(?![a-z]) 认 dateTo 为止,又不把 total/auto 这类词误判成止
const isEndWord = /end|finish|last|to(?![a-z])|\[1\]/i
function roleOf(type: string, model: string): Control['role'] {
if (RANGE_TYPES.has(type) || type === 'range') return 'range'
const norm = model.replace(/]/g, '')
if (/\[0$/.test(norm)) return 'start'
if (/\[1$/.test(norm)) return 'end'
const tail = norm.split('.').pop() || ''
const s = isStartWord.test(tail)
const e = isEndWord.test(tail)
if (s && !e) return 'start'
if (e && !s) return 'end'
return 'single'
}
function familyOf(model: string): string {
const dot = model.lastIndexOf('.')
const head = dot < 0 ? '' : model.slice(0, dot + 1)
const tail = (dot < 0 ? model : model.slice(dot + 1))
.replace(/start|end|finish|begin|first|last|from|to(?![a-z])|\[\d\]|_\d/gi, '')
.replace(/^_+|_+$/g, '')
return (head + (tail || 'x')).toLowerCase()
}
function scan(base: string, clampRule: (tag: string) => boolean): Control[] {
const found: Control[] = []
for (const file of walk(base)) {
const raw = readFileSync(file, 'utf-8')
const clean = blankComments(raw)
const re = /<\s*([A-Za-z][\w\-.]*)/g
let m: RegExpExecArray | null
while ((m = re.exec(clean))) {
const tag = tagSlice(clean, m.index)
const isPicker = PICKERS.has(m[1].toLowerCase())
const type = quotedAttr(tag, 'type').replace(/[{}"]/g, '') || bracedAttr(tag, 'type')
if (!isPicker && !DATE_TYPES.has(type) && !RANGE_TYPES.has(type)) continue
const model = modelOf(tag)
const minVal = quotedAttr(tag, 'min') || bracedAttr(tag, 'min')
const maxVal = quotedAttr(tag, 'max') || bracedAttr(tag, 'max')
found.push({
file: file.slice(WS.length + 1).replace(/\\/g, '/'),
line: clean.slice(0, m.index).split('\n').length,
type,
model,
role: roleOf(type, model),
family: familyOf(model),
minToPartner: isStartWord.test(minVal),
maxToPartner: isEndWord.test(maxVal),
clamp: clampRule(tag),
})
}
}
return found
}
/** 成对控件逐对判:两头都要"禁选对家 + 手输兜底",缺一样登记违规。 */
function nakedPairs(controls: Control[]): string[] {
const pairs = new Map<string, Control[]>()
for (const c of controls) {
if (c.role !== 'start' && c.role !== 'end') continue
const key = c.file + '#' + c.family
pairs.set(key, (pairs.get(key) || []).concat(c))
}
const bad: string[] = []
for (const [key, list] of pairs) {
const start = list.find(c => c.role === 'start')
const end = list.find(c => c.role === 'end')
if (!start || !end) {
bad.push(`配对失败(多半是变量名换了写法):${key} -> ${list.map(c => `${c.model}:${c.role}`).join(', ')}`)
continue
}
const miss: string[] = []
if (!start.maxToPartner) miss.push('起侧 max 没指向止')
if (!end.minToPartner) miss.push('止侧 min 没指向起')
if (!start.clamp || !end.clamp) miss.push('缺手输兜底(倒挂交换)')
if (miss.length) bad.push(`${start.file}:${start.line}/${end.line} ${start.model}~${end.model} 缺:${miss.join('、')}`)
}
return bad
}
const pairCount = (controls: Control[]) => {
const keys = new Set<string>()
for (const c of controls) if (c.role === 'start' || c.role === 'end') keys.add(c.file + '#' + c.family)
return [...keys].filter(k => {
const list = controls.filter(c => (c.file + '#' + c.family) === k)
return list.some(c => c.role === 'start') && list.some(c => c.role === 'end')
}).length
}
const vueClamp = (tag: string) => /@change="clamp\w*"/.test(tag)
const jsxClamp = (tag: string) => /onChange=\{[\s\S]{0,200}?(setStartDate|setEndDate|set\w+Input)\s*\(/.test(tag)
const adminCtrls = scan(resolve(here, '../src'), vueClamp)
const userCtrls = scan(resolve(WS, 'crawler-plugin/frontend-vue/src'), vueClamp)
const finCtrls = scan(resolve(WS, 'shop-finance-source/shop-finance-src/client/src'), jsxClamp)
const mxCtrls = scan(resolve(WS, 'maixiang_run_task/maixiang_task_api'), vueClamp)
test('orderedPair 只在两端都有值且倒挂时交换', () => {
assert.deepEqual(orderedPair('2026-10-01', '2026-10-05'), ['2026-10-01', '2026-10-05'])
assert.deepEqual(orderedPair('2026-10-05', '2026-10-01'), ['2026-10-01', '2026-10-05'])
assert.deepEqual(orderedPair('', '2026-10-05'), ['', '2026-10-05'])
assert.deepEqual(orderedPair('2026-10-05', ''), ['2026-10-05', ''])
assert.deepEqual(orderedPair('2026-10-05T09:00', '2026-10-05T08:30'), ['2026-10-05T08:30', '2026-10-05T09:00'])
})
test('分母硬钉:四面控件实例数与成对数(扫描失明即红)', () => {
assert.equal(adminCtrls.length, 23, '后管实例数变了,先复算普查再改这里(v1.4 京东数据库页同步时间起止再落一对=2 实例)')
assert.equal(userCtrls.length, 2, '用户端实例数变了')
assert.equal(finCtrls.length, 30, '财务系统实例数变了')
assert.equal(mxCtrls.length, 4, '麦象实例数变了')
assert.equal(pairCount(adminCtrls), 10, '后管成对区间应为 10(v1.4 京东数据库页同步时间起止再落一对)')
assert.equal(pairCount(finCtrls), 11, '财务系统成对区间应为 11')
assert.equal(pairCount(mxCtrls), 2, '麦象成对区间应为 2')
assert.equal(pairCount(userCtrls), 0, '用户端出现成对区间说明新加了两个单只控件')
})
test('反例自证:裸对、只有一头、只有 min/max 都要被判出', () => {
const naked: Control[] = [
{ file: 'x.vue', line: 1, type: 'date', model: 'a.startDate', role: 'start', family: 'a.date', minToPartner: false, maxToPartner: false, clamp: false },
{ file: 'x.vue', line: 2, type: 'date', model: 'a.endDate', role: 'end', family: 'a.date', minToPartner: false, maxToPartner: false, clamp: false },
]
assert.equal(nakedPairs(naked).length, 1, '判不出裸对,那它报的"0 违规"不作数')
assert.equal(nakedPairs([{ ...naked[0], maxToPartner: true, clamp: true }, { ...naked[1], clamp: true }]).length, 1, '只给一头加约束不算收口')
assert.equal(nakedPairs([{ ...naked[0], maxToPartner: true }, { ...naked[1], minToPartner: true }]).length, 1, '只有 min/max、手输能越界,不算收口')
assert.deepEqual(nakedPairs([{ ...naked[0], maxToPartner: true, clamp: true }, { ...naked[1], minToPartner: true, clamp: true }]), [], '正例被误报')
assert.equal(nakedPairs([naked[0]]).length, 1, '孤儿起止(只有一头)必须露出来')
})
test('反例自证(真文件):裸对判红、写法换了扫描器要掉分母', () => {
const dir = mkdtempSync(join(tmpdir(), 'date-ruler-'))
try {
// ① 一对裸控件:两头都没有对家约束,必须被点名
writeFileSync(join(dir, 'naked.vue'), '<template>\n <input v-model="filter.startDate" type="date" />\n <input v-model="filter.endDate" type="date" />\n</template>\n')
// ② 一对齐的:min/max 互绑 + @change 兜手输,不许误报
writeFileSync(join(dir, 'good.vue'), '<template>\n <input v-model="f.startDate" type="date" :max="f.endDate" @change="clampDatePair" />\n <input v-model="f.endDate" type="date" :min="f.startDate" @change="clampDatePair" />\n</template>\n')
// ③ 只给一头加约束
writeFileSync(join(dir, 'half.vue'), '<template>\n <input v-model="q.startDate" type="date" :max="q.endDate" @change="clampDatePair" />\n <input v-model="q.endDate" type="date" />\n</template>\n')
const found = scan(dir, vueClamp)
assert.equal(found.length, 6, '扫描器从真文件里数出的实例数不对(写法换了就会掉分母)')
const bad = nakedPairs(found)
assert.equal(bad.length, 2, `应点名 naked 与 half 两组:${bad.join(' | ')}`)
assert.ok(bad.some(t => /naked\.vue/.test(t)), '裸对没被点名')
assert.ok(bad.some(t => /half\.vue/.test(t)), '只有单侧的没被点名')
// ④ 换成扫描器词表外的写法:分母必须掉下来,否则"0 违规"是假的
writeFileSync(join(dir, 'naked.vue'), '<template>\n <DateField v-model="filter.startDate" kind="date" />\n <DateField v-model="filter.endDate" kind="date" />\n</template>\n')
assert.equal(scan(dir, vueClamp).length, 4, '换了组件写法后实例数没掉——说明分母根本不是数出来的')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
test('后管 8 对日期筛选:max/min 互绑 + @change 倒挂交换', () => {
assert.deepEqual(nakedPairs(adminCtrls), [])
})
test('麦象控制台 2 对:任务列表与批次列表的起止都收口', () => {
assert.deepEqual(nakedPairs(mxCtrls), [])
})
test('财务系统 11 对:max/min 互绑 + onChange 走 useDateRange 的 setter', () => {
assert.deepEqual(nakedPairs(finCtrls), [])
})
test('口径统一:财务系统的兜底是交换,不是塌缩', () => {
const hook = readFileSync(resolve(WS, 'shop-finance-source/shop-finance-src/client/src/hooks/useDateRange.ts'), 'utf-8')
assert.ok(!/\{ startDate: next, endDate: next \}/.test(hook), '还在把区间塌缩到刚点那天——与后管 orderedPair 的交换口径分叉')
assert.match(hook, /\{ startDate: prev\.endDate, endDate: next \}/, '起越过止时应交换成 [止, 起]')
assert.match(hook, /\{ startDate: next, endDate: prev\.startDate \}/, '止越过起时应交换成 [止, 起]')
})
test('反向钉:交换已接管有序,页面不许再自己弹"开始日期不能晚于结束"', () => {
const texts = ['src/pages/asin/DedupeRegistryPage.vue', 'src/pages/tasks/DuplicateCheckPage.vue']
.map(rel => readFileSync(resolve(here, '..', rel), 'utf-8'))
for (const t of texts) {
assert.ok(!t.includes('开始日期不能晚于结束日期'), '倒挂值在 change 时就被换掉了,这条拦截够不着,属死分支')
}
})
test('用户端维持:区间型由组件自身保序,单只那处不变量', () => {
assert.equal(userCtrls.filter(c => c.role === 'range').length, 1, 'daterange 型数量变了要重新分档')
const single = userCtrls.find(c => c.role === 'single')
assert.ok(single && /BrandShopMatchTab/.test(single.file), '用户端单只日期控件变了,按首屏语义重新分档')
assert.deepEqual(nakedPairs(userCtrls), [])
})