Files
crawler-plugin/frontend-vue/tests/expiry-notice.test.ts
T
huangzd1997 95e2318c42 feat(账号到期+公司超管): 级联过期判定、过期停任务巡检与两端续费提醒弹窗
需求两条:站点超管可开设其他公司的超级管理员(站点超管看全站、公司超管只看本公司、
组内管理员仍只看本组);账号要有过期时间,管理员过期后名下普通账户一并停用、
正在跑的任务也要停掉。落库只有 users.expires_at(V146,NULL=永不过期),级联一律现算,
不写"上级过期就把下级置成过期"那种续费也救不回来的数据。

- AccountExpiryService:生效到期 = min(自身, 本公司公司超管, 成员表组长, 创建人)。
  登录拦 403(文案给续费提示)、每次请求鉴权拦 401(前端按下线踢回登录页),super_admin
  永不适用。级联口径与数据可见范围同源(成员表基本未用、实际按 created_by_id 派生)。
- ExpiredAccountTaskStopService:每分钟把过期账号(含级联成员)名下 biz_file_task
  PENDING/SCHEDULED/RUNNING → FAILED,含未领取的 PENDING(防内部通道继续派发)。原因文案
  刻意不以「客户端异常中断」开头,否则会被 TaskResumeService 自动复活。品牌采集与跟价循环
  不在那张表上,经 ExpiredAccountTaskStopSpi 由各自模块停:品牌 pending/running→cancelled
  且 UPDATE 的 WHERE 二次核对状态(抢到行后被客户端推进成完成的行不得误杀),跟价循环只置
  stop_requested=1、沿用用户点「停止循环」那条收尾路径,绝不动 status。任务心跳接口保持匿名
  不走 requireUser,所以过期账号的客户端仍能拿到 alive=false 协作停止。
- 角色 company_super_admin:由站点超管开设(唯一要显式选公司的建号场景),建号/授菜单/改用户/
  看数据四条链路都按"本公司"收口;公司超管之间、以及公司超管与站点超管互相碰不得。
- 续费提醒:剩余 <5 天在数富后台与用户端弹窗,只能收起不能关闭(无关闭按钮,收起态是右下角
  浮标),续费到 ≥5 天自动消失。后台读 /api/admin/current-user 的 expiresAt/daysToExpire;
  用户端无 Pinia,走 localStorage 的 account_expires_at(登录/check_login 落键、被顶下线清键,
  换账号不残留)。只反映账号自身到期,弹窗不做任何级联推断。
- V146 撞掉了 V145 那批的一条护栏:它按"db/ 里不许出现 V146__ 前缀"编死号位,被一条正常的
  前向迁移占用就红。改成钉动作——剥注释后的可执行 SQL 不得写 flyway_schema_history(回滚
  一律是扫描路径外的人工补丁),并把盘点文档改 V146 时丢掉的 V145 文件名补回去。

验证(本会话亲跑,不是转述):后端定向 14 类 123/0(同一轮 mvn 里连批次③的 4 类 53 例、以及既有 ShopDataCrawl/SimilarAsin 两条回归对照 21 例一起跑,合计 197 例 0 红);admin-frontend-vue 本批定向 44/0(弹窗 7 +
公司建号/列表/入口/日期默认 21 + 角色 task-48/task-251 16),全量 1726 例里那 1 支红是另一条
会话刻意留的「公司 tab 接线缺口」尺子(点名 admin_task_center 等 6 页,与本批无关);
frontend-vue 弹窗 9/0、全量 710/0。变异自证两批共 34 点:弹窗语义 16 点全杀(阈值 5、只能收起
不能关闭、挂载点含"注释掉挂载"、落键/清键链路),本批 SPI+迁移护栏 17 点全杀(含 G2 反向:
前向迁移只在注释里提 flyway_schema_history 必须照样绿),注入文件还原 dirty=0、探针残留 0。
2026-10-05 11:51:33 +08:00

202 lines
9.7 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 { readFileSync } from 'node:fs'
import { join } from 'node:path'
/**
* 用户端(app-web / 桌面壳内页)「服务即将到期」续费提醒护栏(V146,2026-10-05 需求)。
*
* 需求原话:仅剩不到 5 天开始提醒、只能缩小不能关闭、续费到超过 5 天才消失。
* 用户端与后台不同:后端只在登录/check_login 时下发 expiresAt,剩余天数由页面自己按
* 当前时间算——所以分两层钉:
* ① 行为层:account-expiry.ts 的落键/清键/算天数(可真跑,用 window 桩);
* ② 源码层:ExpiryNotice.vue 的阈值、按钮、收起态键(SFC 编译不了,断言打在实际源码上)。
* 链路断言(登录写键、恢复会话写键、被顶下线清键、挂载点)防的是"数据源断了但界面静默不弹"。
*/
const COMPONENT = 'src/shared/components/ExpiryNotice.vue'
const APP = 'src/App.vue'
const LOGIN = 'src/pages/login/DesktopLoginPage.vue'
const ENSURE = 'src/shared/auth/ensure-auth.ts'
const KICK = 'src/shared/auth/kick-handler.ts'
function read(rel: string): string {
return readFileSync(join(process.cwd(), rel), 'utf8')
}
/** 非重叠子串计数。不走 execSync('grep'):node 在 Windows 上交给 cmd.exe,那里没 grep,命令会「成功返回空串」而不是报错——正是恒绿的形状。 */
function occurrences(text: string, token: string): number {
if (!token) return 0
let count = 0
let index = text.indexOf(token)
while (index !== -1) {
count += 1
index = text.indexOf(token, index + token.length)
}
return count
}
function templateOf(source: string): string {
const start = source.indexOf('<template>')
const end = source.lastIndexOf('</template>')
assert.ok(start !== -1 && end > start, `${COMPONENT} 没有 <template> 段`)
return source.slice(start, end)
}
function scriptOf(source: string): string {
const start = source.indexOf('<script setup')
const end = source.indexOf('</script>')
assert.ok(start !== -1 && end > start, `${COMPONENT} 没有 <script setup> 段`)
return source.slice(start, end)
}
/** 剥掉 HTML 注释:注释掉的 `<ExpiryNotice />` 在源码里照样匹配得上,挂载点断言必须是活代码。 */
function withoutComments(source: string): string {
return source.replace(/<!--[\s\S]*?-->/g, '')
}
// ---------------------------------------------------------------- 行为层:window.localStorage 桩
interface Store {
[k: string]: string
}
/** 装一个最小 localStorage 桩跑一遍,跑完还原 globalThis.window。 */
function withStorage(run: (store: Store) => void): void {
const store: Store = {}
const localStorageStub = {
getItem: (k: string) => (Object.prototype.hasOwnProperty.call(store, k) ? store[k] : null),
setItem: (k: string, v: string) => {
store[k] = String(v)
},
removeItem: (k: string) => {
delete store[k]
},
}
const hadWindow = 'window' in globalThis
const previous = (globalThis as Record<string, unknown>).window
;(globalThis as Record<string, unknown>).window = { localStorage: localStorageStub }
try {
run(store)
} finally {
if (hadWindow) (globalThis as Record<string, unknown>).window = previous
else delete (globalThis as Record<string, unknown>).window
}
}
const DAY = 86_400_000
/** 把「距今 msFromNow 毫秒」写成后端的 yyyy-MM-dd HH:mm(分钟精度,秒被截掉)。 */
function stamp(msFromNow: number): string {
const d = new Date(Date.now() + msFromNow)
const p = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
}
test('落键:带 expiresAt 就存(trim 后),缺字段/空白一律清键,snake_case 也认', async () => {
const expiry = await import('../src/shared/auth/account-expiry.ts')
withStorage((store) => {
const key = expiry.ACCOUNT_EXPIRY_STORAGE_KEY
expiry.writeAccountExpiry({ expiresAt: ' 2026-12-31 23:59 ' })
assert.equal(store[key], '2026-12-31 23:59', '到期值没 trim 落键')
expiry.writeAccountExpiry({ expires_at: '2026-11-01 08:00' })
assert.equal(store[key], '2026-11-01 08:00', 'snake_case 也要认(老接口形状)')
expiry.writeAccountExpiry({})
assert.equal(Object.prototype.hasOwnProperty.call(store, key), false, '缺字段必须删键')
expiry.writeAccountExpiry({ expiresAt: '2026-12-31 23:59' })
expiry.writeAccountExpiry({ expiresAt: ' ' })
assert.equal(Object.prototype.hasOwnProperty.call(store, key), false, '空白一律清键')
expiry.writeAccountExpiry(null)
expiry.writeAccountExpiry(undefined)
assert.equal(expiry.readAccountExpiry(), '', '无键读出来是空串,不是 undefined')
})
})
test('换账号不残留:清键后读不到上一账号的到期值,天数返回 null 而不是 0', async () => {
const expiry = await import('../src/shared/auth/account-expiry.ts')
withStorage(() => {
expiry.writeAccountExpiry({ expiresAt: '2026-12-31 23:59' })
assert.equal(expiry.readAccountExpiry(), '2026-12-31 23:59')
expiry.clearAccountExpiry()
assert.equal(expiry.readAccountExpiry(), '', '登出/切号/被顶下线后必须读不到')
assert.equal(expiry.daysToAccountExpiry(), null, '无到期返回 null,弹窗不得按 0 天渲染')
})
})
test('剩余天数 floor 取整:4 天 12 小时算 4 天,已过期给负数,非法值给 null', async () => {
const expiry = await import('../src/shared/auth/account-expiry.ts')
withStorage(() => {
expiry.writeAccountExpiry({ expiresAt: stamp(4.5 * DAY) })
assert.equal(expiry.daysToAccountExpiry(), 4, '必须 floor,四舍五入会把 4.5 天报成 5 天而漏掉提醒')
expiry.writeAccountExpiry({ expiresAt: stamp(-1.5 * DAY) })
assert.ok((expiry.daysToAccountExpiry() ?? 0) < 0, '已过期要返回负数,由弹窗的 >=0 分支挡掉')
expiry.writeAccountExpiry({ expiresAt: '不是日期' })
assert.equal(expiry.daysToAccountExpiry(), null, '解析失败必须 null,不能当成今天到期')
})
})
// ---------------------------------------------------------------- 源码层:弹窗口径
const source = read(COMPONENT)
const template = templateOf(source)
const script = scriptOf(source)
test('提醒阈值 5 天,渲染条件 0 ≤ 剩余 < 5(整 5 天不弹,已过期不弹)', () => {
assert.match(script, /const THRESHOLD = props\.threshold \?\? 5\b/, '阈值没写成 5 的兜底')
const numericFallbacks = script.match(/\?\?\s*\d+/g) ?? []
assert.deepEqual(numericFallbacks, ['?? 5'], '数字兜底只能有阈值 5 这一个')
assert.match(script, /days\.value >= 0 && days\.value < THRESHOLD/, '没按「未过期且不足阈值」判定')
assert.doesNotMatch(script, /days\.value <= THRESHOLD/, '写成 <= 则整 5 天也弹')
})
test('只能缩小不能关闭:模板里恰好「收起 + 浮标」两个可点项,没有任何关闭件', () => {
assert.equal(occurrences(template, '@click="'), 2, '可点项必须恰好两个:minimize 与 restore')
assert.match(template, /@click="minimize"/, '收起按钮没接 minimize')
assert.match(template, /@click="restore"/, '缩小态浮标没接 restore')
assert.match(template, /收起\s*<\/button>/, '收起动作文案是「收起」')
assert.equal(occurrences(source, 'el-dialog'), 0, '对话框会带来关闭件')
assert.doesNotMatch(source, /@click="[^"]*close/i, '存在 close 点击处理器')
assert.doesNotMatch(source, /show-close|close-on-click-modal|close-on-press-escape|:closable/, '存在任何关闭开关')
})
test('收起态按「uid + 到期值」记键:续费换了到期值,新键没记录,回到展开', () => {
assert.equal(occurrences(script, 'expiry-notice-min:'), 1, '收起态键名只应有一处定义')
assert.match(script, /`expiry-notice-min:\$\{uid\}:\$\{expiresAt\.value\}`/, '键必须同时带 uid 与到期值')
assert.equal(occurrences(script, 'window.localStorage.setItem('), 1, '持久化写入只能有收起态这一处')
assert.equal(occurrences(script, 'window.localStorage.removeItem('), 1, '只有恢复展开时清键')
assert.match(
script,
/minimized\.value = window\.localStorage\.getItem\(minimizedKey\.value\) === '1'/,
'初值必须由「当前键」读出,键含到期值才会在续费后自动展开',
)
})
test('页面常开也要跨阈值出现:按分钟重算剩余,卸载时清计时器,未登录不渲染', () => {
assert.match(script, /window\.setInterval\(\(\) => \{ now\.value = Date\.now\(\) \}, 60_000\)/, '没有按分钟重算剩余天数')
assert.match(script, /onUnmounted\(\(\) => \{[\s\S]*?window\.clearInterval\(timer\)/, '卸载没清计时器')
assert.match(script, /Boolean\(uid\)/, '未登录(无 uid)不该渲染')
})
test('挂在 App.vue:桌面壳与网页共用同一个根组件,不挂就整站看不见', () => {
const app = withoutComments(read(APP))
assert.match(app, /import ExpiryNotice from '@\/shared\/components\/ExpiryNotice\.vue'/, 'App.vue 没引组件')
assert.match(app, /<ExpiryNotice\s*\/>/, 'App.vue 没渲染组件(注释掉等于没挂)')
})
test('数据源链路:登录写键、恢复会话两处写键、被顶下线清键,断了就静默不弹', () => {
const login = read(LOGIN)
const ensure = read(ENSURE)
const kick = read(KICK)
assert.equal(occurrences(login, 'writeAccountExpiry(data)'), 1, '登录成功没落到期键')
assert.equal(occurrences(login, 'clearAccountExpiry()'), 1, '登录页挂载清理没接上')
assert.equal(occurrences(ensure, 'writeAccountExpiry(response.data)'), 2, 'ensure-auth 两条恢复路径都要落键')
assert.match(kick, /storage\.removeItem\(ACCOUNT_EXPIRY_STORAGE_KEY\)/, '被顶下线没清到期键,换账号会残留')
})