feat(店铺密钥): 筛选改走服务端、新增认当前 tab,操作列不再裁掉删除

三家公司的密钥挤在一页上,而"筛选"是拿当前页那 10 行在前端筛的:total 不动,
第 2 家的令牌要翻到它所在页才筛得出来。操作列给 160px 装不下三颗按钮,
最后一颗(删除)被 td 的 overflow:hidden + table-layout:fixed 整颗裁掉——
DOM 里在、事件也在,就是看不见点不到,这就是"没有删除功能"的真相。

- GET /api/admin/shop-keys 新增 keyword / token / whitelist_status,在公司读范围之内
  由服务端筛。keyword 那组 OR 必须括起来:不括就被后续 AND 短路成
  「备注名命中 OR (账号命中 AND 本公司)」,第 2 家的 tab 能读到第 1 家的令牌。
- create 的归属改为过读门(认当前 tab),不再只认操作者会话那一家。
  读认 tab、写认会话=两把尺子:admin 是 super_admin 且 company_id=1,
  他在别家 tab 点新增会"提示已新增、行却落进米椿花名下",再点一次就撞令牌唯一键。
  这一条推翻 10-06 定案,controller 的反向钉子(create 不许碰读门)同步换成
  「tab 必须过门 + 不许把请求原值直传下去」。
- 操作列 160→270px,.ops-cell 补 flex-wrap: wrap,把"超宽=静默消失"退化成"多占一行";
  同族结构隐患一次扫过 8 个页面(宽度够不够是像素账,会不会消失是结构账)。
- 护栏:ops-cell-must-wrap 钉跨页结构,shop-key-filter-params 钉参数下发与列宽;
  source-pin 棘轮补第二把尺子 reads=全文读点(体内+体外),
  pins 降而 reads 不同步降=把 readSource 挪出用例体冒充改进,当场红。

验证:将要提交的树(HEAD + 本批白名单)在独立 worktree 实跑——前端 1762 例 0 红、
vue-tsc rc=0、Java 41 例 0 红且 959 主源 + 498 测试源全量编译过(证明不依赖并行会话
未提交的符号);主树全量 1766 例 0 红。变异自证三支全杀:摘掉一页的 flex-wrap ⇒ 恰好
1 红点名该页;把体内读盘挪进 helper ⇒ 棘轮 1 红且文案点名"不算改进";
归属退回按会话、controller 绕门直传原值 ⇒ 各自红。
This commit is contained in:
2026-10-08 18:39:19 +08:00
parent f142744ed4
commit 6d835e947e
22 changed files with 1139 additions and 324 deletions
@@ -355,6 +355,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
@@ -538,6 +538,7 @@ tr.is-column-dragging td {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
@@ -449,6 +449,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.expiry-cell-expired { .expiry-cell-expired {
color: #c0392b; color: #c0392b;
@@ -408,6 +408,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
@@ -700,6 +700,7 @@ h3 {
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
text-align: right; text-align: right;
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
@@ -710,6 +710,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.load-more-row td { .load-more-row td {
@@ -488,6 +488,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
@@ -7,8 +7,8 @@ import { ElMessage } from 'element-plus'
import { useCompanyTabStore } from '@/stores/company-tab' import { useCompanyTabStore } from '@/stores/company-tab'
import { fetchShopKeyList, submitCreateShopKey, updateShopKey, deleteShopKey, checkShopKeyWhitelist } from './shop-key-api.ts' import { fetchShopKeyList, submitCreateShopKey, updateShopKey, deleteShopKey, checkShopKeyWhitelist } from './shop-key-api.ts'
import { emptyShopKeyForm, normalizeZiniaoToken, validateProxyUrl } from './shop-key-form-model.ts' import { emptyShopKeyForm, normalizeZiniaoToken, validateProxyUrl } from './shop-key-form-model.ts'
import type { ShopKeyItem } from './shop-dto.ts' import type { IpWhitelistStatus, ShopKeyItem } from './shop-dto.ts'
import { whitelistStatusMeta } from './shop-key-model.ts' import { whitelistStatusMeta, whitelistStatusOptions } from './shop-key-model.ts'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
const companyTab = useCompanyTabStore() const companyTab = useCompanyTabStore()
@@ -19,15 +19,13 @@ const page = ref(1)
const pageSize = ref(10) const pageSize = ref(10)
const jumpPage = ref('') const jumpPage = ref('')
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value))) const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
/** 筛选:备注名/紫鸟账号(用户要求店铺密钥列表补筛选)。 */ /** 筛选:三个条件全部交后端做。曾经的"备注名/紫鸟账号"是前端 computed,只在**当前这一页的
const filterKeyword = ref('') * 10 行**里过滤且 total 纹丝不动 —— 第 11 行起就筛不掉,翻页后结果还会自己变回去。 */
const filteredRows = computed(() => { const filter = reactive({ keyword: '', token: '', whitelistStatus: null as IpWhitelistStatus | null })
const kw = (filterKeyword.value || '').trim().toLowerCase() const statusOptions = whitelistStatusOptions()
if (!kw) return rows.value const anyFilterActive = computed(
return rows.value.filter((r) => () => Boolean(filter.keyword.trim() || filter.token.trim() || filter.whitelistStatus),
`${r.remarkName || ''} ${r.ziniaoAccountName || ''}`.toLowerCase().includes(kw), )
)
})
const dialogVisible = ref(false) const dialogVisible = ref(false)
const editingId = ref<number | null>(null) const editingId = ref<number | null>(null)
@@ -61,6 +59,9 @@ async function load() {
const result = await fetchShopKeyList({ const result = await fetchShopKeyList({
page: page.value, page: page.value,
pageSize: pageSize.value, pageSize: pageSize.value,
keyword: filter.keyword.trim() || undefined,
token: filter.token.trim() || undefined,
whitelistStatus: filter.whitelistStatus || undefined,
companyId: companyTab.requestCompanyId, companyId: companyTab.requestCompanyId,
}) })
rows.value = result.items rows.value = result.items
@@ -130,7 +131,7 @@ async function submit() {
saving.value = true saving.value = true
try { try {
if (creating) { if (creating) {
await submitCreateShopKey({ ...form }) await submitCreateShopKey({ ...form }, companyTab.requestCompanyId)
} else { } else {
await updateShopKey(editingId.value as number, { ...form }) await updateShopKey(editingId.value as number, { ...form })
} }
@@ -178,7 +179,16 @@ function goJump() {
changePage(Math.min(Math.max(n, 1), totalPages.value)) changePage(Math.min(Math.max(n, 1), totalPages.value))
} }
watch(() => companyTab.activeId, () => { filterKeyword.value = ''; page.value = 1; void load() }) function apply() {
page.value = 1
void load()
}
// 切公司 = 清掉全部筛选 + 回第 1 页 + 重取数,与其余 9 页同一条约定
// (护栏 company-tab-wiring 的 WATCH_BODY_PINS 逐字钉着这一行)。
// 筛选改到服务端做之后这条更要守:留着上一家填的词去筛新一家,首屏就是一张
// 「暂无匹配密钥」而框里还显示着那个词——tab 看着像坏了,请求/后端/权限三处都没错。
watch(() => companyTab.activeId, () => { filter.keyword = ''; filter.token = ''; filter.whitelistStatus = null; page.value = 1; void load() })
onMounted(load) onMounted(load)
</script> </script>
@@ -194,8 +204,19 @@ onMounted(load)
<div class="form-row keys-filter-row"> <div class="form-row keys-filter-row">
<div class="form-group" style="min-width: 220px"> <div class="form-group" style="min-width: 220px">
<label>备注名 / 紫鸟账号</label> <label>备注名 / 紫鸟账号</label>
<input v-model="filterKeyword" type="text" placeholder="模糊搜索备注名或紫鸟账号" /> <input v-model="filter.keyword" type="text" placeholder="模糊搜索备注名或紫鸟账号" @keyup.enter="apply" />
</div> </div>
<div class="form-group" style="min-width: 220px">
<label>紫鸟令牌</label>
<input v-model="filter.token" type="text" placeholder="粘贴令牌或其片段定位这一把" @keyup.enter="apply" />
</div>
<div class="form-group" style="min-width: 160px">
<label>白名单状态</label>
<el-select v-model="filter.whitelistStatus" class="admin-filter" clearable placeholder="全部状态">
<el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
</el-select>
</div>
<button class="btn" type="button" @click="apply">查询</button>
</div> </div>
<div class="shop-key-table-scroll"> <div class="shop-key-table-scroll">
@@ -210,12 +231,12 @@ onMounted(load)
<th style="width: 150px">白名单状态 <span class="table-help" aria-hidden="true">?</span></th> <th style="width: 150px">白名单状态 <span class="table-help" aria-hidden="true">?</span></th>
<th style="width: 170px">创建时间</th> <th style="width: 170px">创建时间</th>
<th style="width: 170px">修改时间</th> <th style="width: 170px">修改时间</th>
<th style="width: 160px">操作</th> <th style="width: 270px">操作</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<template v-if="filteredRows.length"> <template v-if="rows.length">
<tr v-for="(row, index) in filteredRows" :key="row.id"> <tr v-for="(row, index) in rows" :key="row.id">
<td>{{ (page - 1) * pageSize + index + 1 }}</td> <td>{{ (page - 1) * pageSize + index + 1 }}</td>
<td>{{ row.remarkName || '—' }}</td> <td>{{ row.remarkName || '—' }}</td>
<td>{{ row.ziniaoAccountName }}</td> <td>{{ row.ziniaoAccountName }}</td>
@@ -258,7 +279,7 @@ onMounted(load)
<td colspan="9" class="empty-tip">加载中...</td> <td colspan="9" class="empty-tip">加载中...</td>
</tr> </tr>
<tr v-else> <tr v-else>
<td colspan="9" class="empty-tip">{{ filterKeyword ? '暂无匹配密钥' : '暂无店铺密钥' }}</td> <td colspan="9" class="empty-tip">{{ anyFilterActive ? '暂无匹配密钥' : '暂无店铺密钥' }}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -516,6 +537,10 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
/* 兜底:单元格是 overflow:hidden + table-layout:fixed,按钮总宽一旦超过列宽,
最后一颗会整颗被裁掉(看不见也点不到,2026-10-08 的"删除按钮没了"就是这么来的)。
允许换行等于把"静默消失"换成"多占一行"。 */
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
@@ -520,6 +520,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.empty-tip { .empty-tip {
+34 -5
View File
@@ -12,8 +12,10 @@ export function toSensitiveString(value: string): SensitiveString {
return value as SensitiveString return value as SensitiveString
} }
/** 紫鸟 IP 白名单状态。 */ /** 紫鸟 IP 白名单状态。取值清单住在这里(DTO 层),model 的归一与筛选下拉共用同一份,
* 否则"下拉里有的、后端说非法"和"药丸渲染出的态、筛不出来"会各错一次。 */
export type IpWhitelistStatus = 'UNKNOWN' | 'ALLOWED' | 'BLOCKED' export type IpWhitelistStatus = 'UNKNOWN' | 'ALLOWED' | 'BLOCKED'
export const IP_WHITELIST_VALUES: readonly IpWhitelistStatus[] = ['UNKNOWN', 'ALLOWED', 'BLOCKED']
/** 店铺密钥行(GET /api/admin/shop-keys data.items;Java ShopKeyItemVo)。 */ /** 店铺密钥行(GET /api/admin/shop-keys data.items;Java ShopKeyItemVo)。 */
export interface ShopKeyItem { export interface ShopKeyItem {
@@ -81,10 +83,16 @@ export interface ShopGroupOption {
leaderUsername?: string leaderUsername?: string
} }
/** 店铺密钥列表分页参数(分页 + 公司 tab;归一是白名单构造,不点名 companyId)。 */ /** 店铺密钥列表分页参数(分页 + 三个筛选 + 公司 tab;归一是白名单构造,不点名 companyId)。 */
export interface ShopKeyListParams { export interface ShopKeyListParams {
page: number page: number
pageSize: number pageSize: number
/** 备注名 / 紫鸟账号 模糊词。 */
keyword?: string
/** 紫鸟令牌 模糊词。 */
token?: string
/** 白名单状态等值筛;空 = 不筛。 */
whitelistStatus?: IpWhitelistStatus | null
/** 公司 tab 的值;normalizeKeyListParams 不点名它,只有 api 层能从原始 params 读到。 */ /** 公司 tab 的值;normalizeKeyListParams 不点名它,只有 api 层能从原始 params 读到。 */
companyId?: number | null companyId?: number | null
} }
@@ -102,6 +110,10 @@ export interface ShopManageListParams {
export interface ShopKeyPageQuery { export interface ShopKeyPageQuery {
page: number page: number
pageSize: number pageSize: number
/** 下划线形:与后端 @RequestParam(name = "keyword"/"token"/"whitelist_status") 逐字对齐。 */
keyword?: string
token?: string
whitelist_status?: string
/** 下划线形:与后端 @RequestParam(name = "company_id") 逐字对齐。 */ /** 下划线形:与后端 @RequestParam(name = "company_id") 逐字对齐。 */
company_id?: number company_id?: number
} }
@@ -128,6 +140,14 @@ function trimOrUndefined(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined return typeof value === 'string' && value.trim() ? value.trim() : undefined
} }
/** 白名单状态归一:大小写/空白容忍,不在清单里的一律当"不筛"(下拉只可能给清单内的值)。 */
function statusOrUndefined(value: unknown): IpWhitelistStatus | undefined {
const textValue = typeof value === 'string' ? value.trim().toUpperCase() : ''
return IP_WHITELIST_VALUES.includes(textValue as IpWhitelistStatus)
? (textValue as IpWhitelistStatus)
: undefined
}
/** 归一化分页:页码下限 1、页大小钳制在 1..100(与 Java 服务端一致)。 */ /** 归一化分页:页码下限 1、页大小钳制在 1..100(与 Java 服务端一致)。 */
function normalizePageCore(raw: { page?: unknown; pageSize?: unknown }): { page: number; pageSize: number } { function normalizePageCore(raw: { page?: unknown; pageSize?: unknown }): { page: number; pageSize: number } {
const page = Math.max(finiteInt(raw.page) ?? SHOP_PAGE_MIN_PAGE, SHOP_PAGE_MIN_PAGE) const page = Math.max(finiteInt(raw.page) ?? SHOP_PAGE_MIN_PAGE, SHOP_PAGE_MIN_PAGE)
@@ -139,9 +159,14 @@ function normalizePageCore(raw: { page?: unknown; pageSize?: unknown }): { page:
return { page, pageSize } return { page, pageSize }
} }
/** 店铺密钥列表分页归一。 */ /** 店铺密钥列表分页/筛选归一:空白筛选词与非法状态都归成"不筛",与 toKeyPageQuery 只下发非空一致。 */
export function normalizeKeyListParams(raw: Partial<ShopKeyListParams>): ShopKeyListParams { export function normalizeKeyListParams(raw: Partial<ShopKeyListParams>): ShopKeyListParams {
return normalizePageCore(raw) return {
...normalizePageCore(raw),
keyword: trimOrUndefined(raw.keyword),
token: trimOrUndefined(raw.token),
whitelistStatus: statusOrUndefined(raw.whitelistStatus),
}
} }
/** 店铺列表分页/筛选归一:负/缺分组 id 视为无筛选,空白店铺名视为无过滤。 */ /** 店铺列表分页/筛选归一:负/缺分组 id 视为无筛选,空白店铺名视为无过滤。 */
@@ -154,7 +179,11 @@ export function normalizeShopListParams(raw: Partial<ShopManageListParams>): Sho
} }
export function toKeyPageQuery(params: ShopKeyListParams): ShopKeyPageQuery { export function toKeyPageQuery(params: ShopKeyListParams): ShopKeyPageQuery {
return { page: params.page, pageSize: params.pageSize } const query: ShopKeyPageQuery = { page: params.page, pageSize: params.pageSize }
if (params.keyword) query.keyword = params.keyword
if (params.token) query.token = params.token
if (params.whitelistStatus) query.whitelist_status = params.whitelistStatus
return query
} }
/** 前端状态 → Java 查询参数(camelCase);仅下发非空可选字段。 */ /** 前端状态 → Java 查询参数(camelCase);仅下发非空可选字段。 */
@@ -27,13 +27,23 @@ export async function fetchShopKeyList(params: Partial<ShopKeyListParams> = {}):
return parseShopKeyPage(data) return parseShopKeyPage(data)
} }
/** 提交新增店铺密钥:先校验(失败抛首条错误不发请求),再 POST,解析返回的新记录。 */ /**
export async function submitCreateShopKey(form: ShopKeyFormValues): Promise<ShopKeyItem> { * 提交新增店铺密钥:先校验(失败抛首条错误不发请求),再 POST,解析返回的新记录。
*
* 归属走**查询参数** `company_id`(不进请求体——Java 侧 requestDtoCarriesNoCompanyField 钉着 body
* 不许有 companyId 字段),取值是公司 tab;非超管时 `requestCompanyId` 恒为 null,
* 后端那道门会按会话落本公司,所以这里不为 null 编一个默认公司。
*/
export async function submitCreateShopKey(form: ShopKeyFormValues, companyId?: number | null): Promise<ShopKeyItem> {
const { valid, errors } = validateShopKeyForm(form) const { valid, errors } = validateShopKeyForm(form)
if (!valid) { if (!valid) {
throw new Error(Object.values(errors)[0] || '店铺密钥表单校验未通过') throw new Error(Object.values(errors)[0] || '店铺密钥表单校验未通过')
} }
const { data } = await http.post<unknown>(SHOP_KEYS_ENDPOINT, toShopKeyCreateRequest(form)) const { data } = await http.post<unknown>(
SHOP_KEYS_ENDPOINT,
toShopKeyCreateRequest(form),
companyId != null ? { params: { company_id: companyId } } : undefined,
)
const item = toShopKeyItem(unwrap<unknown>(data)) const item = toShopKeyItem(unwrap<unknown>(data))
if (!item) { if (!item) {
throw new Error('新增店铺密钥响应异常:未返回有效记录') throw new Error('新增店铺密钥响应异常:未返回有效记录')
@@ -3,13 +3,12 @@ import { unwrap } from '../../api/envelope.ts'
import { import {
emptyShopKeyPageResult, emptyShopKeyPageResult,
toSensitiveString, toSensitiveString,
IP_WHITELIST_VALUES,
type IpWhitelistStatus, type IpWhitelistStatus,
type ShopKeyItem, type ShopKeyItem,
type ShopKeyPageResult, type ShopKeyPageResult,
} from './shop-dto.ts' } from './shop-dto.ts'
const IP_WHITELIST_VALUES: readonly string[] = ['UNKNOWN', 'ALLOWED', 'BLOCKED']
function text(value: unknown): string { function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : '' return typeof value === 'string' ? value.trim() : ''
} }
@@ -21,7 +20,7 @@ function numberOrNull(value: unknown): number | null {
/** 归一白名单状态;未知/缺省一律回 UNKNOWN。 */ /** 归一白名单状态;未知/缺省一律回 UNKNOWN。 */
export function normalizeIpWhitelistStatus(value: unknown): IpWhitelistStatus { export function normalizeIpWhitelistStatus(value: unknown): IpWhitelistStatus {
const textValue = typeof value === 'string' ? value.trim().toUpperCase() : '' const textValue = typeof value === 'string' ? value.trim().toUpperCase() : ''
return (IP_WHITELIST_VALUES.includes(textValue) ? textValue : 'UNKNOWN') as IpWhitelistStatus return (IP_WHITELIST_VALUES.includes(textValue as IpWhitelistStatus) ? textValue : 'UNKNOWN') as IpWhitelistStatus
} }
export interface WhitelistStatusMeta { export interface WhitelistStatusMeta {
@@ -44,6 +43,18 @@ export function whitelistStatusMeta(status: IpWhitelistStatus | null | undefined
return SHOP_KEY_STATUS_META[key] || SHOP_KEY_STATUS_META.UNKNOWN return SHOP_KEY_STATUS_META[key] || SHOP_KEY_STATUS_META.UNKNOWN
} }
/**
* 筛选下拉的选项表:从上面那张文案表推导,不另立第二份「正常/未加白名单/未检测」。
* 顺序照 IP_WHITELIST_VALUES,下拉与列表药丸同名同序才不会让"筛出来的是未检测、
* 行上写着未加白名单"这种对不上的读法出现。
*/
export function whitelistStatusOptions(): Array<{ value: IpWhitelistStatus; label: string }> {
return IP_WHITELIST_VALUES.map((value) => ({
value: value as IpWhitelistStatus,
label: SHOP_KEY_STATUS_META[value as IpWhitelistStatus].label,
}))
}
/** 解析单条店铺密钥行;缺 id 视为无效。 */ /** 解析单条店铺密钥行;缺 id 视为无效。 */
export function toShopKeyItem(raw: unknown): ShopKeyItem | null { export function toShopKeyItem(raw: unknown): ShopKeyItem | null {
if (!raw || typeof raw !== 'object') return null if (!raw || typeof raw !== 'object') return null
File diff suppressed because it is too large Load Diff
@@ -681,9 +681,9 @@ const WATCH_BODY_PINS: ReadonlyArray<{
// ↓ 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)。 // ↓ 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)。
{ {
file: 'src/pages/shop/ShopKeysPage.vue', file: 'src/pages/shop/ShopKeysPage.vue',
token: "filterKeyword.value = ''; page.value = 1; void load()", token: "filter.keyword = ''; filter.token = ''; filter.whitelistStatus = null; page.value = 1; void load()",
why: '这一页的「备注名 / 紫鸟账号」是客户端过滤(filteredRows 在本页 rows 上筛,不进请求):' why: '2026-10-08 这一页的筛选从客户端挪进请求(keyword/token/whitelist_status 三个参数),'
+ '留着上一家填的关键字,切到新一家就是拿别家的字符串去筛本公司那几行 ⇒ 首屏「暂无符合条件的密钥」而筛选框里还显示着它;' + '清筛选项的理由反而更硬:留着上一家填的词去筛新一家,首屏就是一张「暂无匹配密钥」而输入框里还显示着那个词;'
+ '页码回 1 是因为新一家的令牌更少,末尾的 void load() 才让切 tab 真的换数据', + '页码回 1 是因为新一家的令牌更少,末尾的 void load() 才让切 tab 真的换数据',
premise: [ premise: [
{ file: 'src/pages/shop/shop-key-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] }, { file: 'src/pages/shop/shop-key-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
@@ -0,0 +1,66 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { existsSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { readSource } from './helpers.ts'
/**
* 操作列的按钮一旦超过列宽,会**整颗消失**而不是换行:这些页的 td 是 `overflow:hidden` +
* `table-layout:fixed`,而 `.ops-cell` 是 nowrap flex。2026-10-08 店铺密钥那单"没有删除功能"
* 就是这么来的——按钮在线上包的 DOM 里、事件也在,只是被裁到看不见点不到(列给 160px、实测需 240px)。
*
* 这条看守钉的是**结构**不是像素:宽度按当前文案够,改天多一颗按钮或文案变长就又塌了,
* 而 `flex-wrap: wrap` 让"超宽"从"静默消失"退化成"多占一行",不需要有人去重算宽度。
*/
const SRC = 'src/pages'
function vueFiles(dir: string): string[] {
const out: string[] = []
for (const name of readdirSync(dir)) {
const p = join(dir, name)
if (statSync(p).isDirectory()) out.push(...vueFiles(p))
else if (name.endsWith('.vue')) out.push(p)
}
return out
}
interface Cell {
file: string
buttons: number
wrapped: boolean
}
/** 只做解析,不碰磁盘:读源码这一步留在用例体内(见 source-pin-ratchet 对"隔层 helper"的口径)。 */
function opsCells(sources: Array<{ file: string; source: string }>): Cell[] {
const cells: Cell[] = []
for (const { file, source } of sources) {
const block = /\.ops-cell[ \t]*\{([^}]*)\}/.exec(source)
if (!block) continue
const td = /<td[^>]*class="[^"]*ops[^"]*"[^>]*>([\s\S]*?)<\/td>/.exec(source)
const buttons = td ? (td[1].match(/<button/g) || []).length : 0
// 行锚 + 分号:不锚就会被块内注释里的散文喂饱(本仓踩过一次)。
const wrapped = /\n[ \t]*flex-wrap:[ \t]*wrap[ \t]*;/.test(block[1])
cells.push({ file: file.replace(/\\/g, '/'), buttons, wrapped })
}
return cells
}
test('ops_cell_ruler_actually_sees_the_family', () => {
assert.ok(existsSync(SRC), `扫不到 ${SRC}:目录挪了就是整面恒绿`)
const cells = opsCells(vueFiles(SRC).map((file) => ({ file, source: readSource(file) })))
assert.ok(cells.length >= 14,
`只认出 ${cells.length} 个带 .ops-cell 的页(今天 14 个)⇒ 扫描形状与源码脱节,这条看守已经失明`)
const multi = cells.filter((c) => c.buttons >= 2)
assert.ok(multi.length >= 11,
`只认出 ${multi.length} 页操作列有 ≥2 颗按钮(今天 11 页)⇒ 按钮计数读不到,下面的断言无从判定`)
})
test('every_multi_button_ops_cell_wraps', () => {
const offenders = opsCells(vueFiles(SRC).map((file) => ({ file, source: readSource(file) })))
.filter((c) => c.buttons >= 2 && !c.wrapped)
.map((c) => `${c.file}(${c.buttons} 颗按钮)`)
assert.deepEqual(offenders, [],
'这些页的操作列是 nowrap flex + td overflow:hidden:按钮总宽一旦超过列宽,'
+ '最后一颗会整颗被裁掉(看不见也点不到),补一行 flex-wrap: wrap 即可')
})
@@ -0,0 +1,120 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
import {
normalizeKeyListParams,
toKeyPageQuery,
} from '../src/pages/shop/shop-dto.ts'
import { whitelistStatusOptions } from '../src/pages/shop/shop-key-model.ts'
/**
* 店铺密钥列表的筛选与操作列(2026-10-08)。
*
* 两支各管一次真事故:
* 1. 三个筛选必须**由后端做**。改前的"备注名/紫鸟账号"是前端 computed,只在当前页那 10 行里过滤,
* total 一动不动 —— 第 11 行起筛不掉,翻一页结果还会自己变回来,看着像"搜索坏了"。
* 2. 操作列定宽 160px 装不下三颗 btn-sm,`td{overflow:hidden}` 把第三颗(删除)整颗裁掉:
* 看不见也点不到,被报成"没有删除功能",而线上包里那颗按钮的 DOM 一直都在。
*/
const PAGE = 'src/pages/shop/ShopKeysPage.vue'
// ---------------------------------------------------------------- 下发查询
test('key_filters_reach_the_query_with_backend_param_names', () => {
const query = toKeyPageQuery(normalizeKeyListParams({
page: 2,
pageSize: 10,
keyword: ' 先锋1 ',
token: ' zn-15-549 ',
whitelistStatus: 'BLOCKED',
}))
assert.deepEqual(query, {
page: 2,
pageSize: 10,
keyword: '先锋1',
token: 'zn-15-549',
whitelist_status: 'BLOCKED',
}, '后端 @RequestParam 是下划线名,写成 camelCase 会静默不筛')
})
test('key_filters_blank_illegal_and_case_variants_normalize', () => {
// 空白 = 不筛:一个参数位都不占,否则后端收到 keyword='' 会筛成"备注名含空串"= 全表。
const blank = toKeyPageQuery(normalizeKeyListParams({ page: 1, pageSize: 10, keyword: ' ', token: '' }))
assert.deepEqual(Object.keys(blank).sort(), ['page', 'pageSize'])
// 大小写容忍:下拉给的是大写,手搓请求给小写也得筛得动。
const lower = toKeyPageQuery(normalizeKeyListParams({ page: 1, pageSize: 10, whitelistStatus: 'blocked' as never }))
assert.equal(lower.whitelist_status, 'BLOCKED')
// 清单外的值当"不筛"而不是原样下发:下发一个后端必拒的值等于让这一页整个打不开。
const bogus = toKeyPageQuery(normalizeKeyListParams({ page: 1, pageSize: 10, whitelistStatus: 'WHATEVER' as never }))
assert.equal(bogus.whitelist_status, undefined)
assert.deepEqual(Object.keys(bogus).sort(), ['page', 'pageSize'])
})
test('key_filter_options_are_the_same_three_labels_the_pill_renders', () => {
// 下拉文案与列表药丸共用一张表:两处各写一遍,将来就是"筛出来的是未检测、行上写着未加白名单"。
assert.deepEqual(whitelistStatusOptions(), [
{ value: 'UNKNOWN', label: '未检测' },
{ value: 'ALLOWED', label: '正常' },
{ value: 'BLOCKED', label: '未加白名单' },
])
})
// ---------------------------------------------------------------- 页面接线
test('page_no_longer_filters_rows_in_the_browser', () => {
const source = readSource(PAGE)
assert.doesNotMatch(source, /filteredRows/, '前端二次过滤一旦回来,跨页就又是筛不掉的')
assert.doesNotMatch(source, /rows\.value\.filter\(/, '同上:换写法的前端过滤')
assert.match(source, /<template v-if="rows\.length">[\s\S]{0,120}<tr v-for="\(row, index\) in rows"/,
'表格必须直接画服务端返回的行')
})
test('page_sends_all_three_filters_and_reloads_on_query', () => {
const source = readSource(PAGE)
for (const field of ['keyword:', 'token:', 'whitelistStatus:']) {
assert.match(source, new RegExp(`fetchShopKeyList\\(\\{[\\s\\S]{0,260}${field}`), `${field} 得进请求`)
}
assert.match(source, /function apply\(\) \{\s*\n\s*page\.value = 1/, '改条件必须回第 1 页,否则筛完停在第 3 页看空表')
assert.match(source, /@click="apply"/, '要有显式查询按钮:服务端筛选没有"打字即筛"这回事')
})
test('create_sends_the_tab_as_query_param_while_update_does_not', () => {
const api = readSource('src/pages/shop/shop-key-api.ts')
const page = readSource(PAGE)
// 新增必须把当前 tab 交出去,否则后端只能按操作者会话推导:超管在别家 tab 点新增
// 会"提示已新增、列表照旧空、再点一次撞紫鸟令牌已存在"(2026-10-08 那单报错的正主)。
assert.match(api, /submitCreateShopKey\(form: ShopKeyFormValues, companyId\?: number \| null\)/,
'新增的归属参数得在签名上,不能靠 body')
assert.match(api, /params:\s*\{\s*company_id:\s*companyId\s*\}/, '归属走查询参数 company_id')
assert.match(page, /submitCreateShopKey\(\{ \.\.\.form \}, companyTab\.requestCompanyId\)/,
'页面必须把 tab 的值传下去')
// 反向钉:编辑**不**带归属。行的公司不是可改属性——带过去等于给"把别家的密钥搬进本公司"开门。
const updateCall = /await updateShopKey\([^\n]*\)/.exec(page)
assert.ok(updateCall, '找不到 updateShopKey 的调用点,反向钉无从判定')
assert.equal(/requestCompanyId/.test(updateCall[0]), false,
'编辑一旦也带 tab,跨家挪归属就成了顺手能做的事')
// 归属不进 body:与 Java 侧 requestDtoCarriesNoCompanyField 同一件事的两端。
assert.equal(/companyId/.test(readSource('src/pages/shop/shop-key-form-model.ts')), false,
'请求体构造里出现 companyId=归属变成前端可写字段')
})
test('ops_column_is_wide_enough_for_its_three_buttons', () => {
const source = readSource(PAGE)
// 240 = 真浏览器实测:编辑 53 + 检测白名单 94 + 删除 53 + 两道 gap 16 + td 左右 padding 24。
// 量法是把本文件的 <style> 与 <th> 清单逐字搬进 fixture、字体栈对齐 main.css:12 后取 rect,
// 不是按字数估的(按字数估会把 160px 判成"够宽",那正是这次事故的值)。
const width = /<th style="width: (\d+)px">操作<\/th>/.exec(source)
assert.ok(width, '操作列必须还有一条显式定宽')
assert.ok(Number(width![1]) >= 240, `操作列 ${width![1]}px 装不下实测需要的 240px,第三颗按钮会被裁没`)
// 兜底闸门:宽度是"现在够",换行是"以后加第四颗也不会静默消失"。
// 锚成"独占一行的声明 + 分号"而不是裸词组:块里那段说明注释提到了同一个类,
// 裸词组会被注释里的散文喂饱,判据就恒真了。
// 已知残余口子(2026-10-08 变异实测):注释写成"独占一行 flex-wrap: wrap;"仍能骗过这条;
// 要堵得引 CSS 解析器,不值当——这条防的是"顺手删掉一行声明",不是防蓄意伪装。
assert.match(source, /\.ops-cell \{[^}]*\n\s*flex-wrap: wrap\s*;/,
'缺 flex-wrap 时超宽的那颗按钮会整颗消失而不是换行')
})
@@ -9,6 +9,13 @@
* 实测漏掉 48 处。"分母悄悄变小"对只许减的棘轮是沉默的,所以这里另用一把独立口径对账 * 实测漏掉 48 处。"分母悄悄变小"对只许减的棘轮是沉默的,所以这里另用一把独立口径对账
* (countTestOccurrences),两者不等就红。 * (countTestOccurrences),两者不等就红。
* *
* **第二把尺子(reads,2026-10-08 加)**:`pins` 只认落在用例体内的读盘调用,于是有一条免费的绕过路——
* 把 `readSource(...)` 从用例体挪进模块级 helper,钉子数当场变 0 而守卫一个都没少
* (本仓 `ops-cell-must-wrap.test.ts` 第一天就被记成 `{cases:2, pins:0}`,实测有读盘却"零钉子";
* 全树这样"体内 0 钉而有读点"的文件 21 个)。所以台账每格再加一个 `reads`=**全文读点总数(不分体内体外)**,
* 规则两条:① `reads` 同样只许减;② `pins` 相对基线降了,`reads` 必须至少同步降同样多——
* 降不下来就认定是"搬家"而不是"去掉源码钉子",直接红。
*
* 本机:`node --test tests/source-pin-ratchet.test.ts`(这面原先 0 个 node_modules, * 本机:`node --test tests/source-pin-ratchet.test.ts`(这面原先 0 个 node_modules,
* 纯 node 24 类型剥离就能跑,不依赖 vitest/vue-tsc) * 纯 node 24 类型剥离就能跑,不依赖 vitest/vue-tsc)
* 重生成基线:`UPDATE_SOURCE_PIN_BASELINE=1 node --test tests/source-pin-ratchet.test.ts` * 重生成基线:`UPDATE_SOURCE_PIN_BASELINE=1 node --test tests/source-pin-ratchet.test.ts`
@@ -24,9 +31,13 @@ const BASELINE_PATH = join(HERE, 'baselines', 'source-pin-ledger.json')
/** 这把尺子自己的源码里有 readSource/readFileSync 的字样,不能把自己算成钉子。 */ /** 这把尺子自己的源码里有 readSource/readFileSync 的字样,不能把自己算成钉子。 */
const SELF = 'source-pin-ratchet.test.ts' const SELF = 'source-pin-ratchet.test.ts'
export type FileLedger = { cases: number; pins: number } export type FileLedger = { cases: number; pins: number; reads: number }
export type Ledger = Record<string, FileLedger> export type Ledger = Record<string, FileLedger>
type Baseline = { note: string; totals: { files: number; cases: number; pins: number }; files: Ledger } type Baseline = {
note: string
totals: { files: number; cases: number; pins: number; reads: number }
files: Ledger
}
/** 剥掉块注释、行注释、单/双引号与模板字符串的内容,保留长度与换行以便回指行号。 */ /** 剥掉块注释、行注释、单/双引号与模板字符串的内容,保留长度与换行以便回指行号。 */
export function stripNonCode(src: string): string { export function stripNonCode(src: string): string {
@@ -66,6 +77,12 @@ export function stripNonCode(src: string): string {
const ANCHOR = /^[ \t]{0,4}(?:await[ \t]+)?(?:test|it)[ \t]*\(/gm const ANCHOR = /^[ \t]{0,4}(?:await[ \t]+)?(?:test|it)[ \t]*\(/gm
const PIN = /readSource\s*\(|readFileSync\s*\(|globSync\s*\(/ const PIN = /readSource\s*\(|readFileSync\s*\(|globSync\s*\(/
const READ_SITE = /readSource\s*\(|readFileSync\s*\(|globSync\s*\(/g
/** 全文读点(体内 + 模块级夹具 + helper 都算),注释与字符串里的字样不算。 */
export function countReadSites(src: string): number {
return (stripNonCode(src).match(READ_SITE) || []).length
}
/** 独立口径:出现次数(不做归属),用来给锚点分母对账。 */ /** 独立口径:出现次数(不做归属),用来给锚点分母对账。 */
export function countTestOccurrences(src: string): number { export function countTestOccurrences(src: string): number {
@@ -87,7 +104,11 @@ export function sliceCases(src: string): string[] {
export function ledgerFor(src: string): FileLedger { export function ledgerFor(src: string): FileLedger {
const cases = sliceCases(src) const cases = sliceCases(src)
return { cases: cases.length, pins: cases.filter((r) => PIN.test(r)).length } return {
cases: cases.length,
pins: cases.filter((r) => PIN.test(r)).length,
reads: countReadSites(src),
}
} }
export function collectSources(): Record<string, string> { export function collectSources(): Record<string, string> {
@@ -107,17 +128,31 @@ export function buildLedger(sources: Record<string, string>): Ledger {
return led return led
} }
export type Breach = { file: string; got: FileLedger; cap: FileLedger } export type Breach = { file: string; got: FileLedger; cap: FileLedger; why: string[] }
export function diffAgainstBaseline(got: Ledger, baseline: Ledger): Breach[] { export function diffAgainstBaseline(got: Ledger, baseline: Ledger): Breach[] {
const breaches: Breach[] = [] const breaches: Breach[] = []
const push = (file: string, g: FileLedger, cap: FileLedger, why: string) => {
let hit = breaches.find((b) => b.file === file)
if (!hit) { hit = { file, got: g, cap, why: [] }; breaches.push(hit) }
hit.why.push(why)
}
for (const [file, cap] of Object.entries(baseline)) { for (const [file, cap] of Object.entries(baseline)) {
const g = got[file] ?? { cases: 0, pins: 0 } const g = got[file] ?? { cases: 0, pins: 0, reads: 0 }
if (g.pins > cap.pins || g.cases > cap.cases) breaches.push({ file, got: g, cap }) if (g.pins > cap.pins) push(file, g, cap, `钉子 ${cap.pins}→${g.pins}`)
if (g.cases > cap.cases) push(file, g, cap, `用例 ${cap.cases}→${g.cases}`)
if (g.reads > cap.reads) push(file, g, cap, `读点 ${cap.reads}→${g.reads}`)
// 钉子降了就得问一句"读盘真的少了吗":只降计数不降读点=挪出体内,占比是搬出来的不是修出来的。
const droppedPins = cap.pins - g.pins
const droppedReads = cap.reads - g.reads
if (droppedPins > 0 && droppedReads < droppedPins) {
push(file, g, cap, `钉子降 ${droppedPins} 而读点只降 ${droppedReads}:`
+ '把 readSource 挪出用例体/塞进 helper 不算改进')
}
} }
for (const [file, g] of Object.entries(got)) { for (const [file, g] of Object.entries(got)) {
if (!(file in baseline) && g.pins > 0) { if (!(file in baseline) && (g.pins > 0 || g.reads > 0)) {
breaches.push({ file, got: g, cap: { cases: 0, pins: 0 } }) push(file, g, { cases: 0, pins: 0, reads: 0 }, '台账外新文件带源码钉子或读盘')
} }
} }
return breaches return breaches
@@ -129,9 +164,11 @@ function measure() {
} }
function totals(ledger: Ledger) { function totals(ledger: Ledger) {
let files = 0, cases = 0, pins = 0 let files = 0, cases = 0, pins = 0, reads = 0
for (const v of Object.values(ledger)) { files++; cases += v.cases; pins += v.pins } for (const v of Object.values(ledger)) {
return { files, cases, pins } files++; cases += v.cases; pins += v.pins; reads += v.reads
}
return { files, cases, pins, reads }
} }
function loadBaseline(): Baseline { function loadBaseline(): Baseline {
@@ -149,15 +186,31 @@ test('分母自证:切分器与独立出现次数口径逐文件对平', () =>
} }
assert.deepEqual(bad, [], '切分器漏切用例 ⇒ 分母变小 ⇒ 棘轮变松:\n' + bad.join('\n')) assert.deepEqual(bad, [], '切分器漏切用例 ⇒ 分母变小 ⇒ 棘轮变松:\n' + bad.join('\n'))
assert.ok(totals(ledger).cases > 1500, `分母只有 ${totals(ledger).cases},不像整棵 tests/ 树`) assert.ok(totals(ledger).cases > 1500, `分母只有 ${totals(ledger).cases},不像整棵 tests/ 树`)
// 两把尺子的关系必须站得住:体内钉子是全文读点的子集。reads < pins ⇒ 有一把在说谎。
const liar: string[] = []
for (const [name, v] of Object.entries(ledger)) {
if (v.reads < v.pins) liar.push(`${name} 读点=${v.reads} < 钉子=${v.pins}`)
if (v.pins > 0 && v.reads === 0) liar.push(`${name} 有钉子却读不到读点`)
}
assert.deepEqual(liar, [], '体内口径与全文口径互相矛盾:\n' + liar.join('\n'))
}) })
test('基线自身不许是被清空的壳', () => { test('基线自身不许是被清空的壳', () => {
const b = loadBaseline() const b = loadBaseline()
assert.ok(b.totals.cases > 1500, `基线 cases=${b.totals.cases} 小得可疑`) assert.ok(b.totals.cases > 1500, `基线 cases=${b.totals.cases} 小得可疑`)
assert.ok(Object.keys(b.files).length >= 100, `基线只覆盖 ${Object.keys(b.files).length} 个文件`) assert.ok(Object.keys(b.files).length >= 100, `基线只覆盖 ${Object.keys(b.files).length} 个文件`)
// 第二把尺子的基线缺格就等于那把尺子没装:`reads > undefined` 恒 false,红不出来。
const noReads = Object.entries(b.files)
.filter(([, v]) => typeof (v as FileLedger).reads !== 'number')
.map(([f]) => f)
assert.deepEqual(noReads, [],
`基线里 ${noReads.length} 个文件没有 reads 字段(用 UPDATE_SOURCE_PIN_BASELINE=1 重生成):\n`
+ noReads.slice(0, 8).join('\n'))
assert.ok(b.totals.reads > 0 && Object.values(b.files).reduce((a, v) => a + v.reads, 0) > 0,
'基线 reads 合计为 0 ⇒ 全文口径是个空壳')
}) })
test('逐文件台账只许减:钉子数与用例数都不得高于基线', () => { test('逐文件台账只许减:钉子数、用例数、全文读点都不得高于基线', () => {
const breaches = diffAgainstBaseline(measure().ledger, loadBaseline().files) const breaches = diffAgainstBaseline(measure().ledger, loadBaseline().files)
assert.deepEqual(breaches, [], JSON.stringify(breaches, null, 2)) assert.deepEqual(breaches, [], JSON.stringify(breaches, null, 2))
}) })
@@ -186,6 +239,16 @@ test('行为用例', () => {
}) })
` `
assert.equal(ledgerFor(commented).pins, 0, '注释里的字样不该被算成钉子') assert.equal(ledgerFor(commented).pins, 0, '注释里的字样不该被算成钉子')
// 两把尺子的分工就在这格:helper 里的读盘体内看不见,全文口径必须照样抓到。
const hoisted = `
import { readSource } from './helpers/x.ts'
function src(p) { return readSource(p) }
test('靠 helper 读盘', () => { assert.match(src('a.vue'), /company_id/) })
`
const hoistedLedger = ledgerFor(hoisted)
assert.equal(hoistedLedger.pins, 0, '体内口径对 helper 是瞎的(第二把尺子存在的原因)')
assert.equal(hoistedLedger.reads, 1, '全文口径必须抓到 helper 里那一处读盘')
}) })
test('台账有牙:加钉子、搬进新文件都要红;减钉子不许红', () => { test('台账有牙:加钉子、搬进新文件都要红;减钉子不许红', () => {
@@ -193,24 +256,55 @@ test('台账有牙:加钉子、搬进新文件都要红;减钉子不许红',
const first = Object.keys(base)[0] const first = Object.keys(base)[0]
const bumped: Ledger = JSON.parse(JSON.stringify(base)) const bumped: Ledger = JSON.parse(JSON.stringify(base))
bumped[first] = { cases: bumped[first].cases, pins: bumped[first].pins + 1 } bumped[first] = { ...bumped[first], pins: bumped[first].pins + 1, reads: bumped[first].reads + 1 }
assert.equal(diffAgainstBaseline(bumped, base).length, 1, '同文件加钉子没被抓到 ⇒ 棘轮是摆设') assert.equal(diffAgainstBaseline(bumped, base).length, 1, '同文件加钉子没被抓到 ⇒ 棘轮是摆设')
const moved: Ledger = { ...base, 'brand-new-pin.test.ts': { cases: 3, pins: 3 } } const moved: Ledger = { ...base, 'brand-new-pin.test.ts': { cases: 3, pins: 3, reads: 3 } }
assert.ok(diffAgainstBaseline(moved, base).some((b) => b.file === 'brand-new-pin.test.ts'), assert.ok(diffAgainstBaseline(moved, base).some((b) => b.file === 'brand-new-pin.test.ts'),
'新文件装钉子绕过台账 ⇒ "内部搬家"这条路必须堵住') '新文件装钉子绕过台账 ⇒ "内部搬家"这条路必须堵住')
const improved: Ledger = JSON.parse(JSON.stringify(base)) const improved: Ledger = JSON.parse(JSON.stringify(base))
improved[first] = { cases: improved[first].cases, pins: Math.max(0, improved[first].pins - 1) } improved[first] = { ...improved[first], pins: improved[first].pins, reads: improved[first].reads }
assert.deepEqual(diffAgainstBaseline(improved, base), [], '把改进报成破口等于拦住别人修好它') assert.deepEqual(diffAgainstBaseline(improved, base), [], '基线等于实测时不该有任何破口')
const withPin = Object.entries(base).find(([, v]) => v.pins >= 1)?.[0]
assert.ok(withPin, '实测台账里一个带钉子的文件都没有 ⇒ 下面两条断言无从判定')
const cap = base[withPin]
// 真改进:钉子与读点一起少(把源码钉子换成行为断言,readSource 调用点随之消失)。
const reallyFixed: Ledger = JSON.parse(JSON.stringify(base))
reallyFixed[withPin] = { ...cap, pins: cap.pins - 1, reads: cap.reads - 1 }
assert.deepEqual(diffAgainstBaseline(reallyFixed, base), [], '把改进报成破口等于拦住别人修好它')
// 假改进(2026-10-08 踩到的那条):读点从用例体挪进模块级 helper,钉子数掉了而一个读盘都没少。
const smuggled: Ledger = JSON.parse(JSON.stringify(base))
smuggled[withPin] = { ...cap, pins: cap.pins - 1 }
const smuggledBreach = diffAgainstBaseline(smuggled, base)
assert.equal(smuggledBreach.length, 1, '把读盘挪出体内被记成改进 ⇒ 占比可以凭搬家一路降到 0')
assert.match(smuggledBreach[0].why.join(' '), /不算改进/, '红必须点名是搬家不是修好')
// 只动体外也要红:体内口径看不见的那一半,由 reads 兜住。
const extraRead: Ledger = JSON.parse(JSON.stringify(base))
extraRead[withPin] = { ...cap, reads: cap.reads + 1 }
assert.ok(diffAgainstBaseline(extraRead, base).some((b) => b.file === withPin && b.why.join(' ').includes('读点')),
'体外新增读盘绕开台账 ⇒ 第二把尺子是摆设')
// 台账缺 reads 字段时第二把尺子不能静默失明(`x > undefined` 恒 false)。
const legacy: Ledger = JSON.parse(JSON.stringify(base))
legacy[withPin] = { cases: cap.cases, pins: cap.pins + 1 }
assert.equal(diffAgainstBaseline(legacy, base).length, 1, '基线格子里没有 reads 也要按 pins 抓到破口')
}) })
test('占比读数当场打印,供四面评分尺子取数', () => { test('占比读数当场打印,供四面评分尺子取数', () => {
const t = totals(measure().ledger) const t = totals(measure().ledger)
const b = totals(loadBaseline().files) const b = totals(loadBaseline().files)
const ratio = (100 * t.pins / t.cases).toFixed(2) const ratio = (100 * t.pins / t.cases).toFixed(2)
console.log(`[source-pin] 当前 文件=${t.files} 用例=${t.cases} 钉子=${t.pins} 占比=${ratio}% |基线 用例=${b.cases} 钉子=${b.pins}`) const outside = t.reads - t.pins
console.log(`[source-pin] 当前 文件=${t.files} 用例=${t.cases} 钉子=${t.pins} 占比=${ratio}%`
+ ` |全文读点=${t.reads}(体内 ${t.pins} + 体外 ${outside})`
+ ` |基线 用例=${b.cases} 钉子=${b.pins} 读点=${b.reads}`)
assert.ok(Number(ratio) <= 30, `钉子占比 ${ratio}% 高得不合理`) assert.ok(Number(ratio) <= 30, `钉子占比 ${ratio}% 高得不合理`)
assert.ok(t.reads >= t.pins, '全文读点少于体内钉子 ⇒ 两把尺子有一把坏了')
}) })
if (process.env.UPDATE_SOURCE_PIN_BASELINE === '1') { if (process.env.UPDATE_SOURCE_PIN_BASELINE === '1') {
@@ -218,8 +312,9 @@ if (process.env.UPDATE_SOURCE_PIN_BASELINE === '1') {
const t = totals(ledger) const t = totals(ledger)
mkdirSync(dirname(BASELINE_PATH), { recursive: true }) mkdirSync(dirname(BASELINE_PATH), { recursive: true })
writeFileSync(BASELINE_PATH, JSON.stringify({ writeFileSync(BASELINE_PATH, JSON.stringify({
note: 'readSource 钉子逐文件基线。只许减;台账外新文件带钉子同样算破口。由 tests/source-pin-ratchet.test.ts 生成。', note: 'readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。'
totals: { files: t.files, cases: t.cases, pins: t.pins }, + '都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。',
totals: { files: t.files, cases: t.cases, pins: t.pins, reads: t.reads },
files: ledger, files: ledger,
}, null, 1), 'utf8') }, null, 1), 'utf8')
console.log('[source-pin] 基线已重写 -> ' + BASELINE_PATH) console.log('[source-pin] 基线已重写 -> ' + BASELINE_PATH)
+2 -1
View File
@@ -33,7 +33,8 @@ test('test_task_081_shop_dto_normal_primary_path', () => {
}) })
test('test_task_081_shop_dto_normal_variant_input', () => { test('test_task_081_shop_dto_normal_variant_input', () => {
// 正常变体:店铺密钥列表只允许 page/pageSize,不携带分组/店铺名维度。 // 正常变体:一个筛选词都不给时,店铺密钥列表的下发查询只可能有 page/pageSize
// (三个筛选维度见 shop-key-filter-params.test.ts:给了才下发,空白与非法值都不占参数位)。
const params = normalizeKeyListParams({ page: 3, pageSize: 30 }) const params = normalizeKeyListParams({ page: 3, pageSize: 30 })
const query = toKeyPageQuery(params) const query = toKeyPageQuery(params)
assert.deepEqual(Object.keys(query).sort(), ['page', 'pageSize']) assert.deepEqual(Object.keys(query).sort(), ['page', 'pageSize'])
@@ -51,7 +51,8 @@ public class ShopKeyController {
@GetMapping @GetMapping
@Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。company_id 只收窄可见集、不放大:" @Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。company_id 只收窄可见集、不放大:"
+ "超管按 tab 指定的公司读,非超管一律锁本公司(越界公司为空页)。") + "超管按 tab 指定的公司读,非超管一律锁本公司(越界公司为空页)。"
+ "keyword/token/whitelist_status 三个筛选在同一把公司尺子之内生效,不越过读范围。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopKeyPageVo.class))) @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopKeyPageVo.class)))
}) })
@@ -60,23 +61,33 @@ public class ShopKeyController {
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page, @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
@Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪)") @Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪)")
@RequestParam(name = "company_id", required = false) Long companyId) { @RequestParam(name = "company_id", required = false) Long companyId,
@Parameter(description = "备注名 / 紫鸟账号 模糊词")
@RequestParam(name = "keyword", required = false) String keyword,
@Parameter(description = "紫鸟令牌 模糊词")
@RequestParam(name = "token", required = false) String token,
@Parameter(description = "白名单状态:ALLOWED/BLOCKED/UNKNOWN")
@RequestParam(name = "whitelist_status", required = false) String whitelistStatus) {
AdminUserEntity operator = requireOperator(request); AdminUserEntity operator = requireOperator(request);
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId); Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
return ApiResponse.success(shopKeyService.page(page, pageSize, scopedCompanyId)); return ApiResponse.success(shopKeyService.page(page, pageSize, scopedCompanyId, keyword, token, whitelistStatus));
} }
@PostMapping @PostMapping
@Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。归属由操作者会话推导,请求体不带 company_id。") @Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。归属走与列表同一把门:"
+ "超管按 company_id 指定的那一家落,非超管一律落会话公司(请求体不带归属字段,归属不可由前端直写)。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法")
}) })
public ApiResponse<ShopKeyItemVo> create( public ApiResponse<ShopKeyItemVo> create(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "归属公司(仅超管生效;非超管一律按会话公司落)")
@RequestParam(name = "company_id", required = false) Long companyId,
@Valid @RequestBody ShopKeyCreateRequest body) { @Valid @RequestBody ShopKeyCreateRequest body) {
AdminUserEntity operator = requireOperator(request); AdminUserEntity operator = requireOperator(request);
return ApiResponse.success("创建成功", shopKeyService.create(body, operator.getId())); Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
return ApiResponse.success("创建成功", shopKeyService.create(body, operator.getId(), scopedCompanyId));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@@ -42,12 +42,27 @@ public class ShopKeyService {
/** /**
* @param companyId 读范围公司:由 {@code DataReadScope.readCompanyIdOrOwn} 判定后传下来, * @param companyId 读范围公司:由 {@code DataReadScope.readCompanyIdOrOwn} 判定后传下来,
* {@code null} 只可能来自平台超管「不筛」的判定,调用方不许在这里补默认值。 * {@code null} 只可能来自平台超管「不筛」的判定,调用方不许在这里补默认值。
* @param keyword 备注名 / 紫鸟账号的模糊词,命中其一即保留
* @param token 紫鸟令牌的模糊词
* @param whitelistStatus 白名单状态等值筛,只认 {@code ALLOWED|BLOCKED|UNKNOWN}
*/ */
public ShopKeyPageVo page(long page, long pageSize, Long companyId) { public ShopKeyPageVo page(long page, long pageSize, Long companyId,
String keyword, String token, String whitelistStatus) {
long safePage = Math.max(page, 1); long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100); long safePageSize = Math.min(Math.max(pageSize, 1), 100);
String safeKeyword = normalizeOptional(keyword);
String safeToken = normalizeOptional(token);
String safeStatus = normalizeWhitelistStatusFilter(whitelistStatus);
LambdaQueryWrapper<ShopKeyEntity> query = applyCompanyScope( LambdaQueryWrapper<ShopKeyEntity> query = applyCompanyScope(
new LambdaQueryWrapper<ShopKeyEntity>().orderByDesc(ShopKeyEntity::getId), companyId); new LambdaQueryWrapper<ShopKeyEntity>().orderByDesc(ShopKeyEntity::getId), companyId);
if (!safeKeyword.isEmpty()) {
// 括起来再 OR:不括的话后面任何 AND 条件会被 OR 短路成
// 「备注名命中」或「(账号命中 AND 本公司)」,第 2 家的 tab 就能读到第 1 家的令牌。
query.and(wrapper -> wrapper.like(ShopKeyEntity::getRemarkName, safeKeyword)
.or().like(ShopKeyEntity::getZiniaoAccountName, safeKeyword));
}
query.like(!safeToken.isEmpty(), ShopKeyEntity::getZiniaoToken, safeToken);
query.eq(safeStatus != null, ShopKeyEntity::getIpWhitelistStatus, safeStatus);
Long total = shopKeyMapper.selectCount(query); Long total = shopKeyMapper.selectCount(query);
List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)) List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize))
.stream() .stream()
@@ -62,18 +77,48 @@ public class ShopKeyService {
} }
/** /**
* 归属由<b>操作者会话</b>推导(请求体一律不带 company_id):漏了这一句,新密钥就会被 V150 的 * 白名单状态筛选的取值闸门:空白 = 不筛(返回 {@code null}),非法值 = 抛。
* {@code DEFAULT 1} 静默塞进第 1 家——那是"归属失真且不报错",而 {@code requireCompanyId} *
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载。 * <p>不返回空集也不"原样传下去":这一页的下拉只可能有三个值,能传进第四个的只能是手搓请求,
* 而把它当成"筛一个不存在的状态"返回 0 条,调用方读到的是"这家公司没有未加白名单的密钥"——
* 与"参数没给对"是两种语义,前者会让人停止排查。</p>
*/
private String normalizeWhitelistStatusFilter(String value) {
String normalized = normalizeOptional(value).toUpperCase(java.util.Locale.ROOT);
if (normalized.isEmpty()) {
return null;
}
if (!ZiniaoApiKeyProvider.IP_WHITELIST_STATUS_ALLOWED.equals(normalized)
&& !ZiniaoApiKeyProvider.IP_WHITELIST_STATUS_BLOCKED.equals(normalized)
&& !ZiniaoApiKeyProvider.IP_WHITELIST_STATUS_UNKNOWN.equals(normalized)) {
throw new BusinessException("白名单状态只支持 ALLOWED/BLOCKED/UNKNOWN");
}
return normalized;
}
/**
* 归属走<b>与读侧同一把门</b>:{@code scopedCompanyId} 是 controller 交给
* {@code DataReadScope.readCompanyIdOrOwn} 的判定结果,<b>不是</b>请求里的原值。
*
* <p>改前的形状是"读认 tab、写认会话"两把尺子:超管切到第 2 家的 tab 点新增,界面提示"已新增"、
* 行却落在他自己名下({@code admin} 的 {@code company_id=1}),列表照旧 0 条,
* 再点一次就撞"紫鸟令牌已存在,不能重复维护"。归属与可见集不同家,这一页等于没法用。</p>
*
* <p>{@code null} 只剩一个来源:超管没带 tab(非超管那支门恒返回本公司、不给 null)。
* 这时退回操作者自己那一家,与改前逐字一致;而 {@code requireCompanyId} 取不到公司是<b>抛</b>、
* 不返回 null,所以新密钥不会被 V150 的 {@code DEFAULT 1} 静默塞进第 1 家。
* 这里<b>不保留</b>不带操作者的重载。</p>
*/ */
@Transactional @Transactional
public ShopKeyItemVo create(ShopKeyCreateRequest request, Long operatorId) { public ShopKeyItemVo create(ShopKeyCreateRequest request, Long operatorId, Long scopedCompanyId) {
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空"); String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
String ziniaoToken = normalizeToken(request.getZiniaoToken()); String ziniaoToken = normalizeToken(request.getZiniaoToken());
String ziniaoTokenHash = hashToken(ziniaoToken); String ziniaoTokenHash = hashToken(ziniaoToken);
ensureTokenAvailable(ziniaoTokenHash, null); ensureTokenAvailable(ziniaoTokenHash, null);
ShopKeyEntity entity = new ShopKeyEntity(); ShopKeyEntity entity = new ShopKeyEntity();
entity.setCompanyId(companyScopeSupport.requireCompanyId(operatorId)); entity.setCompanyId(scopedCompanyId != null
? scopedCompanyId
: companyScopeSupport.requireCompanyId(operatorId));
entity.setRemarkName(normalizeOptional(request.getRemarkName())); entity.setRemarkName(normalizeOptional(request.getRemarkName()));
entity.setZiniaoAccountName(ziniaoAccountName); entity.setZiniaoAccountName(ziniaoAccountName);
entity.setZiniaoToken(ziniaoToken); entity.setZiniaoToken(ziniaoToken);
@@ -20,7 +20,6 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
@@ -59,10 +58,10 @@ class ShopKeyControllerCompanyScopeTest {
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user()); when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID); when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
controller().page(request, 1L, 15L, COMPANY_ID); controller().page(request, 1L, 15L, COMPANY_ID, null, null, null);
verify(dataReadScope).readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID)); verify(dataReadScope).readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID));
verify(shopKeyService).page(1L, 15L, COMPANY_ID); verify(shopKeyService).page(1L, 15L, COMPANY_ID, null, null, null);
} }
/** /**
@@ -77,9 +76,9 @@ class ShopKeyControllerCompanyScopeTest {
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user()); when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null); when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null);
controller().page(request, 1L, 15L, COMPANY_ID); controller().page(request, 1L, 15L, COMPANY_ID, null, null, null);
verify(shopKeyService).page(1L, 15L, null); verify(shopKeyService).page(1L, 15L, null, null, null, null);
} }
/** /**
@@ -93,9 +92,25 @@ class ShopKeyControllerCompanyScopeTest {
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user()); when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(99L))).thenReturn(COMPANY_ID); when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(99L))).thenReturn(COMPANY_ID);
controller().page(request, 1L, 15L, 99L); controller().page(request, 1L, 15L, 99L, null, null, null);
verify(shopKeyService).page(1L, 15L, COMPANY_ID); verify(shopKeyService).page(1L, 15L, COMPANY_ID, null, null, null);
}
/**
* 三个筛选词是"只收窄不放大"的读条件:controller 不加工、不补默认值,原样交给 service。
* 这里一旦被"顺手 trim/兜底成第 1 家",前端下拉与后端谓词就会各说一套。
*/
@Test
@DisplayName("列表:keyword/token/whitelist_status 原样透传给 service")
void pageForwardsTheThreeFiltersVerbatim() {
HttpServletRequest request = login();
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
controller().page(request, 1L, 15L, COMPANY_ID, "先锋1", "zn-15-549", "BLOCKED");
verify(shopKeyService).page(1L, 15L, COMPANY_ID, "先锋1", "zn-15-549", "BLOCKED");
} }
@Test @Test
@@ -135,25 +150,55 @@ class ShopKeyControllerCompanyScopeTest {
} }
/** /**
* 写侧口径(一期定案):归属由后端从操作者会话推导,请求体不带 company_id, * 写侧口径(2026-10-08 改,控制方点名"先修那个新增不看 tab 的 bug"):
* 所以 create 这一支<b>不许</b>碰任何读门——碰了就是"建号归谁由前端说了算"。 * 归属走<b>与列表同一把门</b> {@code readCompanyIdOrOwn}。
*
* <p>被推翻的旧定案原文是"create 这一支不许碰任何读门——碰了就是建号归谁由前端说了算"。
* 它不成立的两点:① 列表已经认 tab,写侧认会话=两把尺子,超管在别家 tab 新增会"提示成功但看不见、
* 再点一次撞紫鸟令牌已存在";② "前端说了算"由<b>门</b>兜着,不是由"不读参数"兜着——
* 非超管那支门恒返回本公司,请求里带什么都不算(与本文件 page 那三支同一口径)。</p>
*
* <p>仍然成立的那一半:归属<b>不进请求体</b>,走查询参数,所以 service 侧
* {@code requestDtoCarriesNoCompanyField} 那支钉原样保留。</p>
*/ */
@Test @Test
@DisplayName("新增:只把操作者 id 交给 service,公司由 service 从会话推导") @DisplayName("新增:tab 的公司值过门,service 收到的是门的判定值")
void createPassesOnlyTheOperator() { void createSendsTheTabThroughTheDoor() {
HttpServletRequest request = login(); HttpServletRequest request = login();
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user()); when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
ShopKeyCreateRequest body = new ShopKeyCreateRequest(); ShopKeyCreateRequest body = new ShopKeyCreateRequest();
body.setZiniaoAccountName("ziniao-a"); body.setZiniaoAccountName("ziniao-a");
body.setZiniaoToken("token-a"); body.setZiniaoToken("token-a");
body.setRemarkName("备注"); body.setRemarkName("备注");
controller().create(request, body); controller().create(request, COMPANY_ID, body);
verify(dataReadScope).readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID));
ArgumentCaptor<Long> operatorId = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> operatorId = ArgumentCaptor.forClass(Long.class);
verify(shopKeyService).create(eq(body), operatorId.capture()); ArgumentCaptor<Long> attributed = ArgumentCaptor.forClass(Long.class);
verify(shopKeyService).create(eq(body), operatorId.capture(), attributed.capture());
assertEquals(OPERATOR_ID, operatorId.getValue()); assertEquals(OPERATOR_ID, operatorId.getValue());
verifyNoInteractions(dataReadScope); assertEquals(COMPANY_ID, attributed.getValue(), "门的判定值必须原样交给 service,不许在 controller 再加工");
}
/**
* 反向钉:非超管带别家 tab 时,门返回的是<b>会话那一家</b>,controller 不许拿请求原值往下传——
* 那才是"建号归谁由前端说了算"的真正形状。
*/
@Test
@DisplayName("新增:门按会话收窄后,交给 service 的是收窄值而不是请求里的别家 id")
void createNeverForwardsTheRawRequestedCompany() {
HttpServletRequest request = login();
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(99L))).thenReturn(COMPANY_ID);
ShopKeyCreateRequest body = new ShopKeyCreateRequest();
body.setZiniaoAccountName("ziniao-a");
body.setZiniaoToken("token-a");
controller().create(request, 99L, body);
verify(shopKeyService).create(eq(body), eq(OPERATOR_ID), eq(COMPANY_ID));
} }
private MockHttpServletRequest login() { private MockHttpServletRequest login() {
@@ -107,7 +107,7 @@ class ShopKeyServiceCompanyScopeTest {
void readScopeAddsTheCompanyCondition() { void readScopeAddsTheCompanyCondition() {
stubPageQueries(); stubPageQueries();
service.page(1L, 15L, OWN_COMPANY); service.page(1L, 15L, OWN_COMPANY, null, null, null);
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery(); LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
// 钉成等值而不是 contains("company"):把条件写成 company_id IS NOT NULL 也含 "company", // 钉成等值而不是 contains("company"):把条件写成 company_id IS NOT NULL 也含 "company",
@@ -120,7 +120,7 @@ class ShopKeyServiceCompanyScopeTest {
void readScopeNullMeansUnfilteredAndNothingIsSubstituted() { void readScopeNullMeansUnfilteredAndNothingIsSubstituted() {
stubPageQueries(); stubPageQueries();
service.page(1L, 15L, null); service.page(1L, 15L, null, null, null, null);
// 与上一条对照才有意义:null 是超管「不筛」的判定,这里补一个默认公司就把超管锁死在本公司, // 与上一条对照才有意义:null 是超管「不筛」的判定,这里补一个默认公司就把超管锁死在本公司,
// 而"切 tab 数字不动"的报障会重新出现。 // 而"切 tab 数字不动"的报障会重新出现。
@@ -131,12 +131,18 @@ class ShopKeyServiceCompanyScopeTest {
// -------------------------------------------------------------- 写归属 // -------------------------------------------------------------- 写归属
/**
* 门给 null(超管没带 tab)时才退回操作者自己那一家。这一支与下面 {@code createAttributesToTheTab}
* 是一对:只钉这一支会放行"永远落自己公司"(=2026-10-08 那个 bug),只钉那一支会放行
* "没带 tab 就落空/落 null 被 DEFAULT 1 兜住"。
*/
@Test @Test
void createAttributesTheRowToTheOperatorCompanyNotToTheRequestBody() { @DisplayName("门给 null 时落操作者自己那一家(与改前逐字一致)")
void createFallsBackToTheOperatorCompanyWhenTheDoorGivesNull() {
stubInsertAndReload(ROW_ID, OWN_COMPANY); stubInsertAndReload(ROW_ID, OWN_COMPANY);
when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(OWN_COMPANY)); when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(OWN_COMPANY));
service.create(createRequest(), OPERATOR_ID); service.create(createRequest(), OPERATOR_ID, null);
ArgumentCaptor<ShopKeyEntity> inserted = ArgumentCaptor.forClass(ShopKeyEntity.class); ArgumentCaptor<ShopKeyEntity> inserted = ArgumentCaptor.forClass(ShopKeyEntity.class);
verify(shopKeyMapper).insert(inserted.capture()); verify(shopKeyMapper).insert(inserted.capture());
@@ -144,9 +150,29 @@ class ShopKeyServiceCompanyScopeTest {
} }
/** /**
* 请求体里根本没有 company_id 这个字段(一期定案:归属由后端从会话推导)。 * 本轮修的就是这一支:超管切到第 2 家的 tab 点新增,行必须落第 2 家。
* 这一支钉的是"别给 DTO 加一个 company_id 就完事"——加了之后前端传什么算什么, *
* 而 {@code ShopKeyController.create} 不读任何门,归属就成了可写字段。 * <p>桩<b>故意不给</b> {@code adminUserMapper.selectById}:代码一旦退回"按操作者会话推导",
* 那次未桩的查询返回 null,{@code requireCompanyId} 就抛"归属账号不存在"——
* 红得比断言 companyId 更早,报的还是错原因,所以这里靠"门给什么就用什么"这条正断言钉。</p>
*/
@Test
@DisplayName("归属认 tab:门给第 2 家就落第 2 家,不再按操作者会话推导")
void createAttributesToTheDoorVerdictNotToTheOperatorSession() {
stubInsertAndReload(ROW_ID, OTHER_COMPANY);
service.create(createRequest(), OPERATOR_ID, OTHER_COMPANY);
ArgumentCaptor<ShopKeyEntity> inserted = ArgumentCaptor.forClass(ShopKeyEntity.class);
verify(shopKeyMapper).insert(inserted.capture());
assertThat(inserted.getValue().getCompanyId()).isEqualTo(OTHER_COMPANY);
}
/**
* 归属<b>不进请求体</b>(走查询参数并过 {@code readCompanyIdOrOwn}),这一支钉的是
* "别给 DTO 加一个 company_id 就完事":字段一旦进 body,它就跟着 {@code @Valid} 一起被当成
* 业务输入,而门在 controller 上——绕过门的那条路(直接调 service、或将来有人把
* {@code request.getCompanyId()} 传下去)就从"要改两处"变成"顺手就写了"。
*/ */
@Test @Test
@DisplayName("请求体不许带归属字段:create/update 两个 DTO 都不该有 companyId") @DisplayName("请求体不许带归属字段:create/update 两个 DTO 都不该有 companyId")
@@ -167,7 +193,7 @@ class ShopKeyServiceCompanyScopeTest {
void createRefusesWhenTheOperatorHasNoCompany() { void createRefusesWhenTheOperatorHasNoCompany() {
when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(null)); when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(null));
assertThatThrownBy(() -> service.create(createRequest(), OPERATOR_ID)) assertThatThrownBy(() -> service.create(createRequest(), OPERATOR_ID, null))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.hasMessageContaining("没有所属公司"); .hasMessageContaining("没有所属公司");
@@ -266,7 +292,7 @@ class ShopKeyServiceCompanyScopeTest {
when(shopKeyMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null); when(shopKeyMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
stubInsertAndReload(ROW_ID, OWN_COMPANY); stubInsertAndReload(ROW_ID, OWN_COMPANY);
service.create(createRequest(), OPERATOR_ID); service.create(createRequest(), OPERATOR_ID, null);
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class); ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(shopKeyMapper).selectOne(captor.capture()); verify(shopKeyMapper).selectOne(captor.capture());
@@ -275,6 +301,92 @@ class ShopKeyServiceCompanyScopeTest {
assertThat(query.getSqlSegment()).doesNotContain("company_id"); assertThat(query.getSqlSegment()).doesNotContain("company_id");
} }
// ---------------------------------------------------------------- 筛选
/*
* 下面这些断言里的字面量不是猜的,是把本类同一套桩跑起来、打印 wrapper.getSqlSegment()
* 抄回来的真实形状(MP 会把整段 WHERE 外括一对括号,所以"含 (" 这种判据恒真,一律不用)。
* 实测样本:
* 公司+关键词 → (company_id = #{...MPGENVAL1} AND (remark_name LIKE #{...2} OR ziniao_account_name LIKE #{...3}))
* 令牌 → (ziniao_token LIKE #{...}),参数值 %zn-15%
* 状态 → (ip_whitelist_status = #{...}),参数值 BLOCKED
*/
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void keywordFiltersBothNameColumnsAsOneOrGroup() {
stubPageQueries();
service.page(1L, 15L, OWN_COMPANY, " abc ", null, null);
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
assertThat(query.getSqlSegment())
.as("两个词任命中其一,且必须整体 AND 进公司条件里")
.contains("remark_name LIKE")
.contains("OR ziniao_account_name LIKE")
// 这一串是跨租户的那一刀:去掉 and(...) 包装后 MP 会渲染成
// "company_id = ? AND remark_name LIKE ? OR ziniao_account_name LIKE ?",
// OR 把公司条件短路掉,第 2 家的 tab 就能读到第 1 家的令牌原文。
.contains("AND (remark_name LIKE");
// 参数值带 % 两侧:写成 eq 就不是"模糊搜索"了,而前端 placeholder 承诺的是模糊。
assertThat(query.getParamNameValuePairs().values())
.containsExactlyInAnyOrder(OWN_COMPANY, "%abc%", "%abc%");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void tokenFilterIsALikeOnTheTokenColumn() {
stubPageQueries();
service.page(1L, 15L, OWN_COMPANY, null, "zn-15", null);
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
assertThat(query.getSqlSegment()).contains("ziniao_token LIKE");
assertThat(query.getParamNameValuePairs().values()).containsExactlyInAnyOrder(OWN_COMPANY, "%zn-15%");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void whitelistStatusIsEqualityAndToleratesCase() {
stubPageQueries();
service.page(1L, 15L, OWN_COMPANY, null, null, "blocked");
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
assertThat(query.getSqlSegment()).contains("ip_whitelist_status =");
assertThat(query.getParamNameValuePairs().values()).containsExactlyInAnyOrder(OWN_COMPANY, "BLOCKED");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void blankFiltersAddNoConditionAtAll() {
stubPageQueries();
// 空白串与只给空格都必须等于"没这一维":传成 LIKE '%%' 会把全表放出来,
// 而前端 placeholder 说的是"留空=不筛"。
service.page(1L, 15L, OWN_COMPANY, " ", "", null);
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
assertThat(query.getSqlSegment())
.doesNotContain("remark_name")
.doesNotContain("ziniao_account_name")
.doesNotContain("ziniao_token")
.doesNotContain("ip_whitelist_status");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void illegalWhitelistStatusThrowsBeforeAnyQueryRuns() {
// 反向钉"非法值退化成不筛":那等于把一个打错的状态读成"这一家全部密钥",
// 比报错更糟——它看起来像结果。
assertThatThrownBy(() -> service.page(1L, 15L, OWN_COMPANY, null, null, "NOT_A_STATUS"))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("白名单状态只支持");
verify(shopKeyMapper, never()).selectCount(any(LambdaQueryWrapper.class));
verify(shopKeyMapper, never()).selectList(any(LambdaQueryWrapper.class));
}
// ---------------------------------------------------------------- 桩 // ---------------------------------------------------------------- 桩
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})