feat(jd额度): 上架额度改按在架商品数计+管理员向员工分配额度闸+在架商品面板

客户口径(2026-11-25):「上限=同时在架商品数,下架 10 个就能再上架 10 个换着卖」+
「管理员下的普通员工总和也不能超过这个上限」。

后端
- 计数正本从 biz_jd_product 占有行数迁到 biz_jd_publish_item:发布成功(SUCCESS)
  且未标记下架(delisted_at IS NULL)的去重商品数(DISTINCT product_id,同商品跨任务
  重复发布只占一位)。旧 JdProductMapper#countByUserIds 整条删除——口径源只能一份。
- V216 给发布明细加 delisted_at(NULL=在架);V217 把普通账号存量默认 5000 清 0
  (0=未分配,分配闸上线的前置清账)。
- JdPublishQuotaService:quotaOf 读数换正本;assertWithinQuota 改收勾选商品集,
  批内已在架的不双计(重复上架不重复占位)。
- 新增 JdPublishOnShelfService+/api/jd-publish/on-shelf(团队在架分页+余量,读数与
  建单闸同一正本)与 /api/jd-publish/items/{itemId}/delisted(标记/撤销按商品整组回写,
  跨团队 403;京麦下架执行链自动回流记欠账)。
- AdminUserService 新增分配闸:Σ(直接下属非零额度,被编辑账号取新值) ≤ 锚点额度;
  站超管/锚点 0=不限放行;旧 400「只能为管理员设置额度」废止。新增
  /api/admin/user/{uid}/jd-quota 只读快照(编辑弹窗展示「当前在架 X/上限 Y」)。

后管
- 编辑弹窗额度项改为「京东侧+操作者写权」即出(普通账号也可分配),带当前在架读数
  (读不到只显一句失败话,不挡保存);列表「上架上限」列 0 按档显「不限」/「未分配」;
  普通账号回填缺省 0(避免「打开就保存」凭空分配额度)。展示规则单出口 user-edit-model。

用户端
- 新增在架商品面板(JdOnShelfPanel):余量读数、空态、满额提醒、标记已下架确认与回执
  文案单出口 jd-on-shelf.ts;endpoints 快照同步 onShelf/markDelisted。

判据
- 后端:JdPublishQuotaServiceTest 11、JdPublishOnShelfServiceTest 8、
  JdPublishOnShelfSqlTest 3(三条 SQL 谓词逐字钉:SUCCESS+delisted_at IS NULL+DISTINCT)、
  AdminUserServiceCompanySuperAdminTest +5(Σ 闸四态)、JdSchemaContractTest 钉 V216/V217、
  两条 SQL 台账(XML_SELECT_TOTAL 109→111、XML_STATEMENT_TOTAL 156→158)逐条点名。
- 后管:jd-publish-quota-edit.test.ts 3(含 0 语义分档与「绝不拼/0」)、
  platform-account-pages 源码钉子改钉新形状、source-pin 台账 cases 1867→1868 逐条点名。
- 用户端:jd-on-shelf.test.ts 纯函数+mount 面板判据;catch-silence 台账 blocks 336→338 点名。
This commit is contained in:
2026-11-25 22:35:43 +08:00
parent fce4c7322c
commit 934091b3d5
42 changed files with 1709 additions and 119 deletions
@@ -0,0 +1,26 @@
/** 京东上架额度只读快照适配(2026-11-25 额度改口径):编辑弹窗展示「当前在架 X/上限 Y」。 */
import { http } from './http'
import { unwrap } from './envelope'
/** Java AdminUserController.jdQuota 端点前缀(/api/admin/user/{uid}/jd-quota)。 */
export const USER_JD_QUOTA_ENDPOINT = '/api/admin/user'
export interface UserJdQuotaSnapshot {
/** 团队在架商品数(发布成功且未标记下架,去重商品口径)。 */
used: number
/** 配额上限(≤0=不限;普通账号 0=未分配)。 */
limit: number
/** 上限是否不限。 */
unlimited: boolean
}
/** 拉取某账号的额度快照:读数与建单配额闸同一正本(JdPublishQuotaService.quotaOf)。 */
export async function fetchUserJdQuota(uid: number): Promise<UserJdQuotaSnapshot> {
const { data } = await http.get<unknown>(`${USER_JD_QUOTA_ENDPOINT}/${uid}/jd-quota`)
const raw = unwrap<Record<string, unknown> | null>(data) ?? {}
return {
used: Number(raw.used ?? 0),
limit: Number(raw.limit ?? 0),
unlimited: raw.unlimited === true,
}
}
@@ -3,8 +3,9 @@ import { computed, reactive, ref, watch } from 'vue'
import type { AdminUser } from '@/types/admin' import type { AdminUser } from '@/types/admin'
import type { PlatformTabId } from '@/config/platform-scope' import type { PlatformTabId } from '@/config/platform-scope'
import { mayCarryOwnExpiry } from './user-create-model' import { mayCarryOwnExpiry } from './user-create-model'
import { fillEditUserForm, validateEditUserForm, type EditUserForm, type EditUserFormErrors } from './user-edit-model' import { fillEditUserForm, quotaFieldLabel, quotaUsageText, validateEditUserForm, type EditUserForm, type EditUserFormErrors } from './user-edit-model'
import { submitEditUser } from './user-edit-adapter' import { submitEditUser } from './user-edit-adapter'
import { fetchUserJdQuota, type UserJdQuotaSnapshot } from '@/api/user-jd-quota'
import { loadUserMenuAuth } from './user-menu-auth-api' import { loadUserMenuAuth } from './user-menu-auth-api'
import { showAdminFeedback } from '@/components/admin-feedback-ui' import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { actionableErrorText } from '@/components/admin-feedback' import { actionableErrorText } from '@/components/admin-feedback'
@@ -33,6 +34,12 @@ const includeQuota = computed(() => props.platform === 'jd')
* 与后端 AdminUserService「无权修改京东上架额度」403 闸同口径,前端不再给出改了必被拒的输入框)。 * 与后端 AdminUserService「无权修改京东上架额度」403 闸同口径,前端不再给出改了必被拒的输入框)。
*/ */
const quotaWritable = computed(() => includeQuota.value && props.operatorCanWriteQuota === true) const quotaWritable = computed(() => includeQuota.value && props.operatorCanWriteQuota === true)
/** 额度 0 的语义按「改完之后」的目标档给标签(2026-11-25):公司超管目标的角色单选隐藏,
* 取原角色;其余跟单选当前值。 */
const quotaRoleForLabel = computed(() => (targetIsCompanySuperAdmin.value ? form.originalRole : form.role))
/** 弹窗里的「当前已用」快照:与建单配额闸同一正本(团队在架商品数)。读不到不阻塞保存(只显示失败句)。 */
const quotaUsed = ref<UserJdQuotaSnapshot | null>(null)
const quotaUsedFailed = ref(false)
/** 公司超管目标的角色单选是隐藏的(改完仍是 company_super_admin),到期时间照旧可改; /** 公司超管目标的角色单选是隐藏的(改完仍是 company_super_admin),到期时间照旧可改;
* 管理员改成普通账号时这一项消失,保存按「清空」下发(见 user-edit-model 的 roleAfter)。 */ * 管理员改成普通账号时这一项消失,保存按「清空」下发(见 user-edit-model 的 roleAfter)。 */
const expiryEditable = computed(() => const expiryEditable = computed(() =>
@@ -56,10 +63,24 @@ watch(
errors.jdPublishQuota = undefined errors.jdPublishQuota = undefined
errors.password = undefined errors.password = undefined
authReady.value = false authReady.value = false
quotaUsed.value = null
quotaUsedFailed.value = false
void refreshAuth() void refreshAuth()
if (quotaWritable.value) void refreshQuota()
}, },
) )
/** 拉「当前在架 X/上限 Y」:失败只在本行显示一句失败话,不挡保存(读数非保存前提)。 */
async function refreshQuota(): Promise<void> {
if (!props.user) return
try {
quotaUsed.value = await fetchUserJdQuota(props.user.id)
} catch {
// 读不到不等于改不了:额度编辑仍照常,界面给一句「读取失败」即可(不静默——用户在行下看得见)。
quotaUsedFailed.value = true
}
}
async function refreshAuth(): Promise<void> { async function refreshAuth(): Promise<void> {
if (!props.user) return if (!props.user) return
loadingAuth.value = true loadingAuth.value = true
@@ -145,8 +166,14 @@ async function save(): Promise<void> {
style="width: 240px" style="width: 240px"
/> />
</el-form-item> </el-form-item>
<el-form-item v-if="quotaWritable && (targetIsCompanySuperAdmin || form.role === 'admin')" label="京东上架额度(0 表示不限)" :error="errors.jdPublishQuota"> <el-form-item v-if="quotaWritable" :label="quotaFieldLabel(quotaRoleForLabel)" :error="errors.jdPublishQuota">
<el-input-number v-model="form.jdPublishQuota" :min="0" :max="2147483647" :precision="0" /> <div class="quota-edit-box">
<el-input-number v-model="form.jdPublishQuota" :min="0" :max="2147483647" :precision="0" />
<div v-if="quotaUsed" class="quota-used">
{{ quotaUsageText(quotaUsed.used, quotaUsed.limit, quotaUsed.unlimited) }}
</div>
<div v-else-if="quotaUsedFailed" class="quota-used quota-used-error">当前已用读取失败(不影响额度编辑)</div>
</div>
</el-form-item> </el-form-item>
<el-form-item v-if="props.user && props.user.creatorUsername" label="所属管理员"> <el-form-item v-if="props.user && props.user.creatorUsername" label="所属管理员">
<el-input :model-value="props.user.creatorUsername" readonly /> <el-input :model-value="props.user.creatorUsername" readonly />
@@ -186,4 +213,17 @@ async function save(): Promise<void> {
.auth-loading-error { .auth-loading-error {
color: var(--el-color-danger); color: var(--el-color-danger);
} }
.quota-edit-box {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.quota-used {
font-size: 12px;
color: var(--admin-muted);
}
.quota-used-error {
color: var(--el-color-warning);
}
</style> </style>
@@ -19,7 +19,7 @@ import { totalPageCount } from './user-pagination'
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model' import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
import { disableBlockReason, disableConfirmMessage, disabledBadgeText } from './user-disable-model' import { disableBlockReason, disableConfirmMessage, disabledBadgeText } from './user-disable-model'
import { listPhaseOf, userListEmptyHint } from './user-list-state' import { listPhaseOf, userListEmptyHint } from './user-list-state'
import { editableBy } from './user-edit-model' import { editableBy, quotaCellTextOf } from './user-edit-model'
import { formatExpiryCell } from './user-expiry' import { formatExpiryCell } from './user-expiry'
import CreateUserDialog from './CreateUserDialog.vue' import CreateUserDialog from './CreateUserDialog.vue'
import EditUserDialog from './EditUserDialog.vue' import EditUserDialog from './EditUserDialog.vue'
@@ -78,10 +78,11 @@ function editableOf(row: AdminUser): boolean {
return editableBy(row.role, operatorRole.value) return editableBy(row.role, operatorRole.value)
} }
/** 上架上限列文案(仅京东侧渲染该列):null=旧数据未配('-'),0=不限,其余为具体条数。 */ /** 上架上限列文案(仅京东侧渲染):null=旧数据未配('-'),0=按档「不限」/「未分配」,其余为具体条数。
* 2026-11-25 口径:普通账号的 0 是「未分配」(只作管理员分配账,不单独拦人),管理员档的 0 才是「不限」。
* 展示规则单出口在 user-edit-model(判据与界面读同一份)。 */
function quotaCellText(row: AdminUser): string { function quotaCellText(row: AdminUser): string {
if (row.jdPublishQuota == null) return '-' return quotaCellTextOf(row)
return row.jdPublishQuota === 0 ? '不限' : String(row.jdPublishQuota)
} }
/** 列表请求参数 = 用户填的筛选态 + 当前公司 + 当前平台。公司/平台值每次现取、不写进 filters: /** 列表请求参数 = 用户填的筛选态 + 当前公司 + 当前平台。公司/平台值每次现取、不写进 filters:
@@ -3,6 +3,9 @@ import type { AdminUser } from '../../types/admin'
import type { PlatformTabId } from '../../config/platform-scope.ts' import type { PlatformTabId } from '../../config/platform-scope.ts'
import { CREATE_PASSWORD_MIN_LEN, mayCarryOwnExpiry } from './user-create-model.ts' import { CREATE_PASSWORD_MIN_LEN, mayCarryOwnExpiry } from './user-create-model.ts'
/** 管理员档缺省额度(与后端 AdminUserService.JD_QUOTA_DEFAULT 同值)。 */
const JD_QUOTA_DEFAULT = 5000
/** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */ /** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */
export type EditUserRole = 'normal' | 'admin' export type EditUserRole = 'normal' | 'admin'
@@ -47,6 +50,36 @@ export function editRoleOf(role: string | null | undefined): EditUserRole {
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal' return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
} }
/**
* 额度 0 是否等于「不限」(2026-11-25 额度改口径):管理员档/公司超管/站点超管是;普通账号的 0
* 是「未分配」——员工额度只作管理员分配账(Σ 员工额度 ≤ 主管额度),不单独拦员工本人。
*/
export function quotaUnlimitedRole(role: string | null | undefined): boolean {
const value = (role || '').trim().toLowerCase()
return value === 'admin' || value === 'company_super_admin' || value === 'super_admin'
}
/** 上架上限列文案(UsersPage,京东侧):null=未配('-')、0=按档「不限」/「未分配」、其余=条数。 */
export function quotaCellTextOf(row: { role?: string | null; jdPublishQuota?: number | null }): string {
if (row.jdPublishQuota == null) return '-'
if (row.jdPublishQuota === 0) return quotaUnlimitedRole(row.role) ? '不限' : '未分配'
return String(row.jdPublishQuota)
}
/** 编辑弹窗额度字段标签:0 的语义按目标档不同(普通账号=未分配,管理员档=不限)。 */
export function quotaFieldLabel(role: string | null | undefined): string {
return quotaUnlimitedRole(role)
? '京东上架额度(0 表示不限)'
: '京东上架额度(0 表示未分配;员工额度只作分配账,不单独拦)'
}
/** 弹窗「当前已用」读数:与建单配额闸同一正本(在架商品数),0 上限显「不限」不出「/0」坏数。 */
export function quotaUsageText(used: number, limit: number, unlimited: boolean): string {
const safeUsed = Number.isFinite(used) && used > 0 ? Math.floor(used) : 0
if (unlimited || !Number.isFinite(limit) || limit <= 0) return `当前在架 ${safeUsed}/不限`
return `当前在架 ${safeUsed}/${Math.floor(limit)}`
}
/** 该角色是否允许被编辑:站点/公司超级管理员不可经普通编辑入口修改(镜像后端闸门)。 */ /** 该角色是否允许被编辑:站点/公司超级管理员不可经普通编辑入口修改(镜像后端闸门)。 */
export function isEditableUser(role: string | null | undefined): boolean { export function isEditableUser(role: string | null | undefined): boolean {
const value = (role || '').trim().toLowerCase() const value = (role || '').trim().toLowerCase()
@@ -74,12 +107,14 @@ export function normalizeExpiryForPicker(raw: string | null | undefined): string
return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(value) ? `${value}:00` : value return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(value) ? `${value}:00` : value
} }
/** 从用户行回填编辑表单:用户名只读、密码留空、columnIds 待授权加载填充。 */ /** 从用户行回填编辑表单:用户名只读、密码留空、columnIds 待授权加载填充。
* 额度缺省按目标档(2026-11-25):管理员档缺省给默认上限 5000,普通账号缺省 0=未分配
* (V217 已把存量的普通账号 5000 清成 0;这里再给 5000 会让「打开就保存」凭空分配额度)。 */
export function fillEditUserForm(user: AdminUser): EditUserForm { export function fillEditUserForm(user: AdminUser): EditUserForm {
const role = typeof user.role === 'string' ? user.role.trim() : '' const role = typeof user.role === 'string' ? user.role.trim() : ''
return { return {
uid: user.id, uid: user.id,
jdPublishQuota: user.jdPublishQuota ?? 5000, jdPublishQuota: user.jdPublishQuota ?? (quotaUnlimitedRole(role) ? JD_QUOTA_DEFAULT : 0),
username: user.username || '', username: user.username || '',
password: '', password: '',
role: editRoleOf(role), role: editRoleOf(role),
@@ -113,7 +148,6 @@ export function validateEditUserForm(
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符,留空则不修改` errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符,留空则不修改`
} }
if (options.includeQuota !== false && options.canWriteQuota !== false && if (options.includeQuota !== false && options.canWriteQuota !== false &&
(form.role === 'admin' || form.originalRole === 'company_super_admin') &&
(!Number.isInteger(form.jdPublishQuota) || form.jdPublishQuota < 0 || form.jdPublishQuota > 2147483647)) { (!Number.isInteger(form.jdPublishQuota) || form.jdPublishQuota < 0 || form.jdPublishQuota > 2147483647)) {
errors.jdPublishQuota = '请输入 0 至 2147483647 的整数' errors.jdPublishQuota = '请输入 0 至 2147483647 的整数'
} }
@@ -153,8 +187,8 @@ export function toEditUserUpdateRequest(form: EditUserForm, options: EditUserFor
if (keepsRole) { if (keepsRole) {
request.role = nextRole request.role = nextRole
} }
if (options.includeQuota !== false && options.canWriteQuota !== false && if (options.includeQuota !== false && options.canWriteQuota !== false) {
(roleAfter === 'admin' || roleAfter === 'company_super_admin')) { // 2026-11-25 口径:普通账号也可设额度(员工额度=管理员向员工的分配账),不再按目标档收口。
request.jdPublishQuota = form.jdPublishQuota request.jdPublishQuota = form.jdPublishQuota
} }
const password = form.password || '' const password = form.password || ''
@@ -2,7 +2,7 @@
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。", "note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
"totals": { "totals": {
"files": 265, "files": 265,
"cases": 1867, "cases": 1868,
"pins": 463, "pins": 463,
"reads": 665 "reads": 665
}, },
@@ -333,7 +333,7 @@
"reads": 0 "reads": 0
}, },
"jd-publish-quota-edit.test.ts": { "jd-publish-quota-edit.test.ts": {
"cases": 2, "cases": 3,
"pins": 0, "pins": 0,
"reads": 0 "reads": 0
}, },
@@ -1,8 +1,15 @@
import test from 'node:test' import test from 'node:test'
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { fillEditUserForm, toEditUserUpdateRequest, validateEditUserForm } from '../src/pages/account/user-edit-model.ts' import {
fillEditUserForm,
quotaCellTextOf,
quotaFieldLabel,
quotaUsageText,
toEditUserUpdateRequest,
validateEditUserForm,
} from '../src/pages/account/user-edit-model.ts'
test('京东上架额度回填、校验和按管理员提交', () => { test('京东上架额度回填、校验和提交(普通账号也下发,2026-11-25 口径)', () => {
const form = fillEditUserForm({ id: 3, username: '管理员', role: 'admin', jdPublishQuota: 0 }) const form = fillEditUserForm({ id: 3, username: '管理员', role: 'admin', jdPublishQuota: 0 })
assert.equal(form.jdPublishQuota, 0) assert.equal(form.jdPublishQuota, 0)
assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, 0) assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, 0)
@@ -10,8 +17,34 @@ test('京东上架额度回填、校验和按管理员提交', () => {
assert.equal(validateEditUserForm(form).valid, false) assert.equal(validateEditUserForm(form).valid, false)
form.jdPublishQuota = 1.5 form.jdPublishQuota = 1.5
assert.equal(validateEditUserForm(form).valid, false) assert.equal(validateEditUserForm(form).valid, false)
form.jdPublishQuota = 1200
form.role = 'normal' form.role = 'normal'
assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, undefined) // 2026-11-25 客户口径「管理员下的普通员工总和也不能超过这个上限」:员工额度数字是
// Σ 分配账的输入,普通账号必须下发(旧断言「改成普通档即 undefined」随口径废止)。
assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, 1200,
'普通账号额度必须下发——不发的话后端 Σ 分配账无从算起')
})
// 2026-11-25 额度改口径的展示判据:0 的语义按档不同(管理员档=不限、普通账号=未分配),
// 余量读数不许拼出「/0」。纯函数单出口,界面与判据读同一份。
test('额度缺省与 0 语义按目标档分档', () => {
assert.equal(fillEditUserForm({ id: 9, username: '员工', role: 'normal', jdPublishQuota: null }).jdPublishQuota, 0,
'普通账号缺省 0=未分配(V217 已把存量 5000 清了,这里再给 5000 会「打开就保存」凭空分配)')
assert.equal(fillEditUserForm({ id: 9, username: '管理员', role: 'admin', jdPublishQuota: null }).jdPublishQuota, 5000,
'管理员档缺省给默认上限 5000(与后端 JD_QUOTA_DEFAULT 同值)')
assert.equal(quotaCellTextOf({ role: 'normal', jdPublishQuota: 0 }), '未分配')
assert.equal(quotaCellTextOf({ role: 'admin', jdPublishQuota: 0 }), '不限')
assert.equal(quotaCellTextOf({ role: 'company_super_admin', jdPublishQuota: 0 }), '不限')
assert.equal(quotaCellTextOf({ role: 'normal', jdPublishQuota: 800 }), '800')
assert.equal(quotaCellTextOf({ role: 'admin', jdPublishQuota: null }), '-')
assert.match(quotaFieldLabel('admin'), /0 表示不限/)
assert.match(quotaFieldLabel('normal'), /0 表示未分配/)
assert.equal(quotaUsageText(12, 5000, false), '当前在架 12/5000')
assert.equal(quotaUsageText(12, 0, true), '当前在架 12/不限')
assert.equal(quotaUsageText(0, 0, false), '当前在架 0/不限', 'limit≤0 一律「不限」,绝不拼「/0」')
}) })
// 2026-11-24 客户口径「配额只有公司管理员才可以改,管理员能配合就大家都乱改了」: // 2026-11-24 客户口径「配额只有公司管理员才可以改,管理员能配合就大家都乱改了」:
@@ -101,8 +101,10 @@ test('CompaniesPage:公司列表带平台、切平台重取数、编辑弹窗
test('EditUserDialog:上架上限仅京东侧且操作者有额度写权才显示/提交;所属平台不设手选', () => { test('EditUserDialog:上架上限仅京东侧且操作者有额度写权才显示/提交;所属平台不设手选', () => {
const dialog = readSource('src/pages/account/EditUserDialog.vue') const dialog = readSource('src/pages/account/EditUserDialog.vue')
assert.match(dialog, /v-if="quotaWritable && \(targetIsCompanySuperAdmin \|\| form\.role === 'admin'\)"/, assert.match(dialog, /v-if="quotaWritable"/,
'quota 项必须走 quotaWritable(京东侧+操作者额度写权)——只按目标角色判断,普通管理员会对着改了必被后端 403 的输入框(2026-11-24 客户口径)') 'quota 项必须走 quotaWritable(京东侧+操作者额度写权)——2026-11-25 口径:普通账号也可分配额度'
+ '(员工额度=管理员向员工的分配账,Σ 分配账的输入),不再按目标档收口;operatorCanWriteQuota 一档'
+ '仍不可省(普通管理员对着改了必被后端 403 的输入框是 2026-11-24 客户口径)')
assert.match(dialog, /const quotaWritable = computed\(\(\) => includeQuota\.value && props\.operatorCanWriteQuota === true\)/, assert.match(dialog, /const quotaWritable = computed\(\(\) => includeQuota\.value && props\.operatorCanWriteQuota === true\)/,
'quotaWritable 必须同时要求京东侧与操作者写权档;prop 缺省按无权重(fail-closed,镜像后端「无权修改京东上架额度」闸)') 'quotaWritable 必须同时要求京东侧与操作者写权档;prop 缺省按无权重(fail-closed,镜像后端「无权修改京东上架额度」闸)')
assert.match(dialog, /submitEditUser\(form, options\)/, assert.match(dialog, /submitEditUser\(form, options\)/,
@@ -4,7 +4,9 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults; import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest; import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest; import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
import com.nanri.aiimage.modules.admin.model.vo.AdminJdQuotaVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo; import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
import com.nanri.aiimage.modules.admin.service.AdminJdQuotaViewService;
import com.nanri.aiimage.modules.admin.service.AdminUserService; import com.nanri.aiimage.modules.admin.service.AdminUserService;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
@@ -30,6 +32,7 @@ public class AdminUserController {
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final AdminUserService adminUserService; private final AdminUserService adminUserService;
private final AdminJdQuotaViewService jdQuotaViewService;
@GetMapping("/users") @GetMapping("/users")
@Operation(summary = "分页查询用户列表") @Operation(summary = "分页查询用户列表")
@@ -78,4 +81,13 @@ public class AdminUserController {
adminUserService.deleteUser(currentUser, uid); adminUserService.deleteUser(currentUser, uid);
return ApiResponse.success("删除成功", null); return ApiResponse.success("删除成功", null);
} }
@GetMapping("/user/{uid}/jd-quota")
@Operation(summary = "京东上架额度快照", description = "2026-11-25 口径改造:编辑弹窗展示「当前在架 X/上限 Y」,"
+ "读数与建单配额闸同一正本(JdPublishQuotaService.quotaOf)。权限照额度编辑同档。")
public ApiResponse<AdminJdQuotaVo> jdQuota(HttpServletRequest request,
@PathVariable Long uid) {
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success(jdQuotaViewService.snapshot(currentUser, uid));
}
} }
@@ -0,0 +1,22 @@
package com.nanri.aiimage.modules.admin.model.vo;
import lombok.Data;
/**
* 京东上架额度快照(2026-11-25 客户口径改造):后管编辑弹窗展示「当前在架 X/上限 Y」。
*
* <p>读数与建单配额闸同一正本({@code JdPublishQuotaService.quotaOf})——弹窗看到的
* 和建单被拦的是同一个数,杜绝「界面说没满、建单说满了」的两套账。</p>
*/
@Data
public class AdminJdQuotaVo {
/** 团队在架商品数(发布成功且未标记下架,去重商品口径)。 */
private long used;
/** 配额上限(≤0=不限)。 */
private long limit;
/** 上限是否不限。 */
private boolean unlimited;
}
@@ -0,0 +1,51 @@
package com.nanri.aiimage.modules.admin.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.admin.model.vo.AdminJdQuotaVo;
import com.nanri.aiimage.modules.jd.service.JdPublishQuotaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
/**
* 后管「京东上架额度」只读视图(2026-11-25 口径改造):编辑弹窗展示「当前在架 X/上限 Y」。
*
* <p>独立小服务而不是塞进 {@link AdminUserService}:后者被十几支测试手工 new,
* 加一个构造参会涟漪一片;本视图只依赖 AdminUserMapper+配额原语,读侧单点。
* 读数与建单配额闸同一正本({@code JdPublishQuotaService.quotaOf}),弹窗看到的
* 和建单被拦的是同一个数。</p>
*/
@Service
@RequiredArgsConstructor
public class AdminJdQuotaViewService {
private final AdminUserMapper adminUserMapper;
private final JdPublishQuotaService jdPublishQuotaService;
/**
* 额度快照。权限照额度编辑同档:站点超管/公司超管可查;公司超管限查自己本人
* 或直接创建在自己名下的账号(与写侧「只能编辑自己名下创建的账号」闸同形)。
*/
public AdminJdQuotaVo snapshot(AdminUserEntity currentUser, Long uid) {
String role = currentUser.getRole() == null ? "" : currentUser.getRole();
if (!"super_admin".equals(role) && !"company_super_admin".equals(role)) {
throw new BusinessException(403, "无权查看京东上架额度");
}
AdminUserEntity target = adminUserMapper.selectById(uid);
if (target == null) {
throw new BusinessException("用户不存在");
}
if ("company_super_admin".equals(role)
&& !currentUser.getId().equals(target.getId())
&& !currentUser.getId().equals(target.getCreatedById())) {
throw new BusinessException(403, "只能查看自己名下创建的账号");
}
JdPublishQuotaService.QuotaSnapshot quota = jdPublishQuotaService.quotaOf(target);
AdminJdQuotaVo vo = new AdminJdQuotaVo();
vo.setUsed(quota.used());
vo.setLimit(quota.limit());
vo.setUnlimited(quota.unlimited());
return vo;
}
}
@@ -41,6 +41,9 @@ public class AdminUserService {
private static final DateTimeFormatter CREATED_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); private static final DateTimeFormatter CREATED_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
/** 京东上架额度缺省值(V207 列默认,与 {@code JdPublishQuotaService.DEFAULT_QUOTA} 同源口径)。 */
private static final long JD_QUOTA_DEFAULT = 5000L;
/** 普通账号不该带自己的到期时间(2026-10-05 定案):它的停用一律由上级账号级联决定。 */ /** 普通账号不该带自己的到期时间(2026-10-05 定案):它的停用一律由上级账号级联决定。 */
private static final String NORMAL_ACCOUNT_EXPIRY_MESSAGE = private static final String NORMAL_ACCOUNT_EXPIRY_MESSAGE =
"普通账号不需要设置到期时间,其停用跟随上级账号(组长/公司超管)级联"; "普通账号不需要设置到期时间,其停用跟随上级账号(组长/公司超管)级联";
@@ -478,12 +481,14 @@ public class AdminUserService {
if (!"super_admin".equals(role) && !"company_super_admin".equals(role)) { if (!"super_admin".equals(role) && !"company_super_admin".equals(role)) {
throw new BusinessException(403, "无权修改京东上架额度"); throw new BusinessException(403, "无权修改京东上架额度");
} }
if (!"admin".equals(roleAfter) && !"company_super_admin".equals(roleAfter)) {
throw new BusinessException(400, "只能为管理员设置京东上架额度");
}
if (request.getJdPublishQuota() < 0) { if (request.getJdPublishQuota() < 0) {
throw new BusinessException(400, "京东上架额度不能为负数"); throw new BusinessException(400, "京东上架额度不能为负数");
} }
// 2026-11-25 分配闸:普通账号也可设额度(额度=管理员向员工的分配账,
// 0=未分配:不计入 Σ、不单独拦人,实际拦截仍看团队在架总和 ≤ 主管额度)。
// 旧 400「只能为管理员设置京东上架额度」随客户口径「管理员下的普通员工
// 总和也不能超过这个上限」废止——没有员工额度数字,总和账无从算起。
assertQuotaAllocation(target, roleAfter, request.getJdPublishQuota());
} }
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏 // 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
@@ -553,6 +558,55 @@ public class AdminUserService {
} }
} }
/**
* 分配闸(2026-11-25 客户口径「管理员下的普通员工总和也不能超过这个上限」):
* Σ(直接下属非零额度,被编辑账号取新值) ≤ 锚点管理员额度。锚点=目标本身为
* 管理员/公司超管档时取目标,普通账号取 {@code created_by_id} 指向的上级
* (无上级或读不到=没有分配账,放行);锚点是站点超管(额度豁免)或锚点
* 额度 ≤0(0=不限)整体放行。员工额度 0=未分配:不计入 Σ、不单独拦上架,
* 实际拦截仍看团队在架总和 ≤ 主管额度({@code JdPublishQuotaService})。
*/
private void assertQuotaAllocation(AdminUserEntity target, String roleAfter, Integer newQuota) {
AdminUserEntity anchor;
if ("admin".equals(roleAfter) || "company_super_admin".equals(roleAfter)) {
anchor = target;
} else if (target.getCreatedById() != null) {
anchor = adminUserMapper.selectById(target.getCreatedById());
} else {
return;
}
if (anchor == null || anchor.getId() == null) {
return;
}
if (DeviceSessionPolicy.isSuperAdmin(anchor.getRole(), anchor.getIsAdmin(), anchor.getCreatedById())) {
return;
}
// 锚点额度取「改完之后」的值:正在编辑主管本人额度时用新值判(下调同样被 Σ 拦),
// 编辑员工时用主管库存值判。null=列缺省(V207 默认 5000)。
long anchorQuota = anchor.getId().equals(target.getId())
? newQuota
: (anchor.getJdPublishQuota() == null ? JD_QUOTA_DEFAULT : anchor.getJdPublishQuota());
if (anchorQuota <= 0) {
return;
}
List<AdminUserEntity> subordinates = adminUserMapper.selectList(
new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getCreatedById, anchor.getId())
.last("limit 2000"));
long sum = 0L;
for (AdminUserEntity subordinate : subordinates) {
if (subordinate.getId() != null && subordinate.getId().equals(target.getId())) {
sum += newQuota;
} else if (subordinate.getJdPublishQuota() != null) {
sum += subordinate.getJdPublishQuota();
}
}
if (sum > anchorQuota) {
throw new BusinessException(400, "名下员工额度总和 " + sum
+ " 已超过管理员额度 " + anchorQuota + ",请先下调员工额度");
}
}
/** /**
* 用户管理授权树现在同时展示并勾选 后台(admin) + 前端客户端(app) 菜单: * 用户管理授权树现在同时展示并勾选 后台(admin) + 前端客户端(app) 菜单:
* 把勾选 id 按类型拆分后分区整树替换(internal 类型不在树里,出现即按无效处理)。 * 把勾选 id 按类型拆分后分区整树替换(internal 类型不在树里,出现即按无效处理)。
@@ -13,6 +13,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishItemsPageVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishItemsPageVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishOnShelfVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishProgressVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishProgressVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo;
@@ -21,6 +22,7 @@ import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
import com.nanri.aiimage.modules.jd.service.JdPublishBoardService; import com.nanri.aiimage.modules.jd.service.JdPublishBoardService;
import com.nanri.aiimage.modules.jd.service.JdPublishFillAiService; import com.nanri.aiimage.modules.jd.service.JdPublishFillAiService;
import com.nanri.aiimage.modules.jd.service.JdPublishIngestService; import com.nanri.aiimage.modules.jd.service.JdPublishIngestService;
import com.nanri.aiimage.modules.jd.service.JdPublishOnShelfService;
import com.nanri.aiimage.modules.jd.service.JdPublishPermissionSupport; import com.nanri.aiimage.modules.jd.service.JdPublishPermissionSupport;
import com.nanri.aiimage.modules.jd.service.JdPublishTaskService; import com.nanri.aiimage.modules.jd.service.JdPublishTaskService;
import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService; import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService;
@@ -71,6 +73,7 @@ public class JdPublishController {
private final JdSizeChartAiService sizeChartAiService; private final JdSizeChartAiService sizeChartAiService;
private final JdPublishFillAiService fillAiService; private final JdPublishFillAiService fillAiService;
private final JdPublishPermissionSupport publishPermissionSupport; private final JdPublishPermissionSupport publishPermissionSupport;
private final JdPublishOnShelfService onShelfService;
private final JdCategoryScopeService jdCategoryScopeService; private final JdCategoryScopeService jdCategoryScopeService;
@PostMapping({"/tasks", "/tasks/target-brand"}) @PostMapping({"/tasks", "/tasks/target-brand"})
@@ -266,4 +269,40 @@ public class JdPublishController {
boardService.deleteTask(taskId, userId); boardService.deleteTask(taskId, userId);
return ApiResponse.success(null); return ApiResponse.success(null);
} }
// ------------------------------------------------------------------
// 2026-11-25 客户口径「上限=同时在架商品数,下架腾额度」:在架面板+人工标记下架。
// 京麦人工下架系统感知不到,标记通道按商品整组回写 delisted_at(V216);
// 读数与建单配额闸同一正本(JdPublishQuotaService),面板与拦截永远对得上。
// ------------------------------------------------------------------
@GetMapping("/on-shelf")
@Operation(summary = "在架商品分页+额度余量", description = "团队(管理员+名下员工)当前在架商品"
+ "(发布成功且未标记下架,同商品只出最新一行)分页,附 used/limit 余量读数。")
public ApiResponse<JdPublishOnShelfVo> onShelf(
@Parameter(description = "页码", required = false, example = "1")
@RequestParam(name = "page", required = false, defaultValue = PageDefaults.FIRST_PAGE) Long page,
@Parameter(description = "每页数量(默认 20,上限 100)", required = false, example = "20")
@RequestParam(name = "page_size", required = false, defaultValue = PageDefaults.JD_PRODUCTS_PAGE_SIZE) Long pageSize,
@Parameter(description = "当前用户 ID;省略时取当前登录身份", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
publishPermissionSupport.assertCanPublish(userId);
return ApiResponse.success(onShelfService.page(userId, page, pageSize));
}
@PostMapping("/items/{itemId}/delisted")
@Operation(summary = "标记/取消标记已下架", description = "按商品整组回写 delisted_at(同商品跨任务的"
+ "成功明细一起落/一起回拨)——标记即腾额度;权限=团队口径,管理员可替名下员工标记。")
public ApiResponse<Void> markDelisted(@PathVariable Long itemId,
@Valid @RequestBody DelistedRequest request,
HttpServletRequest httpRequest) {
Long userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, null);
publishPermissionSupport.assertCanPublish(userId);
onShelfService.markDelisted(itemId, userId, Boolean.TRUE.equals(request.delisted()));
return ApiResponse.success(null);
}
public record DelistedRequest(@jakarta.validation.constraints.NotNull Boolean delisted) {}
} }
@@ -87,13 +87,8 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
@Param("companyId") Long companyId, @Param("companyId") Long companyId,
@Param("visibleGroupIds") List<Long> visibleGroupIds); @Param("visibleGroupIds") List<Long> visibleGroupIds);
/** // 2026-11-25 口径改造:旧「商品上架配额计数 countByUserIds(按 biz_jd_product 行数)」已删——
* 商品上架配额计数({@code JdPublishQuotaService}):按 owner uid 集(管理员本人+ // 额度正本迁到 JdPublishItemMapper.countOnShelfByUserIds(在架商品数)。口径源只能一份。
* 名下员工,公司超管=全公司成员)计 {@code biz_jd_product} 行数。归属列
* {@code user_id}=任务 owner(V193 物化列)。调用方保证列表非空——空集在服务侧
* 直接按 0 处理,不进 SQL。
*/
long countByUserIds(@Param("userIds") List<Long> userIds);
/** /**
* 后管只读页分页查询(synced_at 倒序)。 * 后管只读页分页查询(synced_at 倒序)。
@@ -32,4 +32,24 @@ public interface JdPublishItemMapper extends BaseMapper<JdPublishItemEntity> {
* 行数上界=该任务商品行数(建单口钳 500),无分页问题。 * 行数上界=该任务商品行数(建单口钳 500),无分页问题。
*/ */
List<Map<String, Object>> countByPublishStatus(@Param("taskId") Long taskId); List<Map<String, Object>> countByPublishStatus(@Param("taskId") Long taskId);
/**
* 在架商品数(上架额度计数正本,2026-11-25 口径):uid 集内发布成功且未标记下架的
* <b>去重商品数</b>——同商品跨任务重复发布只算一个(uk_task_product 只防同任务重勾)。
*/
long countOnShelfByUserIds(@Param("userIds") List<Long> userIds);
/**
* 本批勾选商品里「当前已在架」的去重商品数(建单闸用:重复上架不双计额度)。
*/
long countOnShelfInProductIds(@Param("userIds") List<Long> userIds,
@Param("productIds") List<Long> productIds);
/**
* 在架商品分页(用户端「在架商品」面板):同商品取最新一行(MAX(id)),
* 按 id 倒序分页——谓词全部 SQL 侧下推(铁律 20),不在 Java 里 filter。
*/
List<JdPublishItemEntity> selectOnShelfItems(@Param("userIds") List<Long> userIds,
@Param("offset") long offset,
@Param("limit") int limit);
} }
@@ -51,6 +51,8 @@ public class JdPublishItemEntity {
private String publishError; private String publishError;
/** 京麦发布成功回执的商品 id(wareId,AC-3 真机核对锚点)。 */ /** 京麦发布成功回执的商品 id(wareId,AC-3 真机核对锚点)。 */
private String jdWareId; private String jdWareId;
/** 标记已下架时刻(V216,NULL=在架):上架额度按在架商品数计,标记即腾额度。 */
private LocalDateTime delistedAt;
/** 主图 objectKey 快照(biz_jd_product_image MAIN 档 sortNo 最小行)。 */ /** 主图 objectKey 快照(biz_jd_product_image MAIN 档 sortNo 最小行)。 */
private String mainImageObjectKey; private String mainImageObjectKey;
/** 建单落行时刻。 */ /** 建单落行时刻。 */
@@ -0,0 +1,64 @@
package com.nanri.aiimage.modules.jd.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 在架商品面板(2026-11-25 客户口径「上限=同时在架商品数」的界面出口)。
*
* <p>used/limit 与 {@code JdPublishQuotaService.quotaOf} 同一读数(面板行数与额度账
* 对得上是这条链的验收项);items 为团队在架商品分页(发布成功且未标记下架,
* 同商品只出最新一行)。标记已下架/撤销走 {@code POST /api/jd-publish/items/{id}/delisted}。</p>
*/
@Data
public class JdPublishOnShelfVo {
/** 团队在架商品数(去重商品口径,即额度 used)。 */
private long used;
/** 配额上限(≤0=不限,界面显「不限」)。 */
private long limit;
/** 上限是否不限(limit ≤0)。 */
private boolean unlimited;
/** 在架商品总数(分页分母,=used)。 */
private long total;
/** 当前页在架商品行。 */
private List<OnShelfItem> items;
/** 在架商品行:面板展示+标记下架所需的最新成功明细行。 */
@Data
public static class OnShelfItem {
/** 明细行 id(面板展示行=该商品最新成功行;标记/撤销按商品整组生效)。 */
private Long itemId;
/** 商品行 id(biz_jd_product.id,额度去重键)。 */
private Long productId;
/** 京东商品编码快照。 */
private String productCode;
/** 商品标题快照。 */
private String title;
/** 来源店铺名快照。 */
private String shopName;
/** 京麦发布成功回执商品 id。 */
private String jdWareId;
/** 主图预签名 GET URL(可能为 null:快照缺主图)。 */
private String imageUrl;
/** 上架成功时刻(该明细行最近更新时间)。 */
private LocalDateTime listedAt;
/** 上架操作人 uid(团队内谁上的架)。 */
private Long operatorUserId;
}
}
@@ -0,0 +1,122 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishOnShelfVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import static com.nanri.aiimage.modules.jd.service.JdPublishTaskService.ITEM_SUCCESS;
/**
* 在架商品面板与「标记已下架」(2026-11-25 客户口径:上限=同时在架商品数,
* 下架 10 个就能再上架 10 个换着卖)。
*
* <p>在架口径与 {@link JdPublishQuotaService} 同一正本:发布成功(SUCCESS)且未标记
* 下架(delisted_at IS NULL,V216)的去重商品数。京麦人工下架系统感知不到,本服务
* 先开人工标记通道——<b>标记按商品整组生效</b>(同商品跨任务的多条成功行全部落
* delisted_at,否则旧行仍被 DISTINCT 计为在架、额度腾不出去);撤销同样按商品整组
* 回拨。权限=团队口径(管理员可替名下员工标记,跨团队 403)。</p>
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class JdPublishOnShelfService {
private final AdminUserMapper adminUserMapper;
private final JdPublishItemMapper jdPublishItemMapper;
private final JdPublishQuotaService jdPublishQuotaService;
private final OssStorageService ossStorageService;
/** jd-products 独立桶(与发布明细主图快照同源,铁律 17)。 */
@Value("${aiimage.jd.oss.bucket:jd-products}")
private String bucket;
private static final int MAX_PAGE_SIZE = 100;
private static final int IMAGE_PRESIGN_EXPIRY_SECONDS = 86_400;
// 成功词表不新造:biz_jd_publish_item.publish_status 的正本常量在 JdPublishTaskService.ITEM_SUCCESS
// (静态导入)——TaskStatusVocabularyRatchetTest 钉的就是「词表只有一套,别新增内联集合/标量」。
/** 团队在架商品分页+额度余量(used/limit 与配额闸同一读数,面板与拦截对得上)。 */
public JdPublishOnShelfVo page(Long operatorUid, long page, long pageSize) {
AdminUserEntity operator = adminUserMapper.selectById(operatorUid);
JdPublishQuotaService.QuotaSnapshot snapshot = jdPublishQuotaService.quotaOf(operator);
List<Long> userIds = jdPublishQuotaService.teamUserIds(operator);
JdPublishOnShelfVo vo = new JdPublishOnShelfVo();
vo.setUsed(snapshot.used());
vo.setLimit(snapshot.limit());
vo.setUnlimited(snapshot.unlimited());
vo.setTotal(snapshot.used());
long size = Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
long offset = Math.max(page - 1, 0) * size;
if (userIds.isEmpty() || snapshot.used() == 0 || offset >= snapshot.used()) {
vo.setItems(List.of());
return vo;
}
vo.setItems(jdPublishItemMapper.selectOnShelfItems(userIds, offset, (int) size).stream()
.map(this::toItem).toList());
return vo;
}
/**
* 标记/取消标记已下架:按 (product_id, 团队 uid 集, SUCCESS) 整组回写 delisted_at。
* 幂等(重复标记/重复撤销 affected=0 静默通过);非成功行与跨团队行响亮拒绝。
*/
@Transactional
public void markDelisted(Long itemId, Long operatorUid, boolean delisted) {
JdPublishItemEntity item = jdPublishItemMapper.selectById(itemId);
if (item == null) {
throw new BusinessException("发布明细不存在,请刷新后重试");
}
if (!ITEM_SUCCESS.equals(item.getPublishStatus())) {
throw new BusinessException("只有发布成功的商品才能标记或取消下架");
}
AdminUserEntity operator = adminUserMapper.selectById(operatorUid);
List<Long> userIds = jdPublishQuotaService.teamUserIds(operator);
if (item.getUserId() == null || !userIds.contains(item.getUserId())) {
throw new BusinessException(403, "只能标记本团队(管理员及其名下员工)的上架商品");
}
LambdaUpdateWrapper<JdPublishItemEntity> update = new LambdaUpdateWrapper<JdPublishItemEntity>()
.eq(JdPublishItemEntity::getProductId, item.getProductId())
.eq(JdPublishItemEntity::getPublishStatus, ITEM_SUCCESS)
.in(JdPublishItemEntity::getUserId, userIds);
if (delisted) {
update.isNull(JdPublishItemEntity::getDelistedAt)
.set(JdPublishItemEntity::getDelistedAt, LocalDateTime.now());
} else {
update.isNotNull(JdPublishItemEntity::getDelistedAt)
.set(JdPublishItemEntity::getDelistedAt, null);
}
int rows = jdPublishItemMapper.update(null, update);
log.info("[jd-publish] 在架标记 operatorId={} itemId={} productId={} delisted={} rows={}",
operatorUid, itemId, item.getProductId(), delisted, rows);
}
private JdPublishOnShelfVo.OnShelfItem toItem(JdPublishItemEntity row) {
JdPublishOnShelfVo.OnShelfItem item = new JdPublishOnShelfVo.OnShelfItem();
item.setItemId(row.getId());
item.setProductId(row.getProductId());
item.setProductCode(row.getProductCode());
item.setTitle(row.getTitle());
item.setShopName(row.getShopName());
item.setJdWareId(row.getJdWareId());
item.setListedAt(row.getUpdatedAt());
item.setOperatorUserId(row.getUserId());
if (row.getMainImageObjectKey() != null && !row.getMainImageObjectKey().isBlank()) {
item.setImageUrl(ossStorageService.presignObjectDownload(bucket,
row.getMainImageObjectKey(), IMAGE_PRESIGN_EXPIRY_SECONDS));
}
return item;
}
}
@@ -4,7 +4,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper; import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.DeviceSessionPolicy; import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper; import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport; import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -14,19 +14,22 @@ import java.util.List;
/** /**
* 商品上架配额(2026-11-15 用户口径「限制管理员上架的商品数量,包括管理员下的员工 * 商品上架配额(2026-11-15 用户口径「限制管理员上架的商品数量,包括管理员下的员工
* 总和不能超过管理员账号设置的最大值」,默认 5000。 * 总和不能超过管理员账号设置的最大值」,默认 5000;2026-11-25 客户口径改计数:
* 「上限=同时在架商品数,下架 10 个就能再上架 10 个换着卖」)。
* *
* <p>计数口径=团队在京东数据库({@code biz_jd_product})占有的行数:上架功能的数据源 * <p>计数口径=团队<b>在架商品数</b>:发布明细({@code biz_jd_publish_item})里
* 就是京东数据库,团队占有量即「可上架量」的上游闸。归属列 {@code user_id}=任务 owner * 发布成功(SUCCESS)且未标记下架({@code delisted_at IS NULL},V216)的去重商品数
* (V193 物化列),uid 集由 {@link UserDataScopeSupport#resolveVisibleUserIds} 统一解析—— * (DISTINCT product_id——同商品跨任务重复发布只占一个额度位)。旧口径「京东数据库
* 管理员=本人+名下员工(数据权限分组成员,无分组回退 {@code created_by_id} 兜底); * 占有行数」已废弃:采集入库不占额度、上架成功才占、在京麦下架后到「在架商品」面板
* 公司超管=全公司成员;普通账号先锚定到 {@code created_by_id} 指向的管理员再取团队集, * 标记下架即腾出额度(京麦下架执行链自动回流记 BACKLOG 欠账)。归属 uid 集仍由
* 读不到主管回退按自己计。站点超管不限额。</p> * {@link UserDataScopeSupport#resolveVisibleUserIds} 统一解析——管理员=本人+名下员工
* (数据权限分组成员,无分组回退 {@code created_by_id} 兜底);公司超管=全公司成员;
* 普通账号先锚定到 {@code created_by_id} 指向的管理员再取团队集,读不到主管回退按自己
* 计。站点超管不限额。</p>
* *
* <p>两个出口:{@link #quotaOf} 只读快照(供上架界面展示余量);{@link #assertWithinQuota} * <p>两个出口:{@link #quotaOf} 只读快照(后管编辑弹窗与用户端「在架商品」面板展示余量);
* 建上架单前的配额闸,超限抛 {@link BusinessException}。上限 ≤0(0=不限)整体放行。 * {@link #assertWithinQuota} 建上架单前的配额闸,超限抛 {@link BusinessException}。
* 商品上架建单入口落地时调用 {@link #assertWithinQuota}——本服务是配额原语, * 上限 ≤0(0=不限)整体放行。本批勾选里已在架的商品不双计(重复上架不重复占位)。</p>
* 不自行改变任何现有链路行为。</p>
*/ */
@Service @Service
@Slf4j @Slf4j
@@ -35,52 +38,69 @@ public class JdPublishQuotaService {
private final AdminUserMapper adminUserMapper; private final AdminUserMapper adminUserMapper;
private final UserDataScopeSupport userDataScopeSupport; private final UserDataScopeSupport userDataScopeSupport;
private final JdProductMapper jdProductMapper; private final JdPublishItemMapper jdPublishItemMapper;
private static final long DEFAULT_QUOTA = 5000L; private static final long DEFAULT_QUOTA = 5000L;
/** 配额只读快照:used=团队已占有行数,limit=配置上限(≤0=不限)。 */ /** 配额只读快照:used=团队在架商品数(去重),limit=配置上限(≤0=不限)。 */
public record QuotaSnapshot(long used, long limit) { public record QuotaSnapshot(long used, long limit) {
public boolean unlimited() { public boolean unlimited() {
return limit <= 0; return limit <= 0;
} }
} }
/** 团队已占用与上限的只读快照;uid 集为空(无主管且无 id)按 used=0 处理,不进 SQL。 */ /** 团队已上架在架与上限的只读快照;uid 集为空(无主管且无 id)按 used=0 处理,不进 SQL。 */
public QuotaSnapshot quotaOf(AdminUserEntity operator) { public QuotaSnapshot quotaOf(AdminUserEntity operator) {
AdminUserEntity anchor = operator == null ? null : anchorOf(operator); AdminUserEntity anchor = operator == null ? null : anchorOf(operator);
List<Long> userIds = anchor == null || anchor.getId() == null ? List.of() List<Long> userIds = teamUserIdsOf(anchor);
: userDataScopeSupport.resolveVisibleUserIds(anchor); long used = userIds.isEmpty() ? 0L : jdPublishItemMapper.countOnShelfByUserIds(userIds);
long used = userIds.isEmpty() ? 0L : jdProductMapper.countByUserIds(userIds);
long limit = anchor == null || anchor.getJdPublishQuota() == null long limit = anchor == null || anchor.getJdPublishQuota() == null
? DEFAULT_QUOTA : anchor.getJdPublishQuota(); ? DEFAULT_QUOTA : anchor.getJdPublishQuota();
return new QuotaSnapshot(used, limit); return new QuotaSnapshot(used, limit);
} }
/** /**
* 建上架单前的配额闸:按「管理员+名下员工合计」口径判限。站点超管不限额; * 建上架单前的配额闸:按「管理员+名下员工合计在架数」口径判限。站点超管不限额;
* 上限 ≤0(0=不限)放行;{@code additionalCount} 为负按 0 处理(本闸只判限不预占)。 * 上限 ≤0(0=不限)放行;本批 {@code productIds} 里已在架的商品不双计
* (重复上架不重复占位);本闸只判限不预占(并发建单同刻双双过闸的窗口维持现状,
* 执行期不复查)。
*/ */
public void assertWithinQuota(AdminUserEntity operator, int additionalCount) { public void assertWithinQuota(AdminUserEntity operator, List<Long> productIds) {
if (operator != null && DeviceSessionPolicy.isSuperAdmin( if (operator != null && DeviceSessionPolicy.isSuperAdmin(
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())) { operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())) {
return; return;
} }
QuotaSnapshot snapshot = quotaOf(operator); AdminUserEntity anchor = operator == null ? null : anchorOf(operator);
if (snapshot.unlimited()) { List<Long> userIds = teamUserIdsOf(anchor);
long limit = anchor == null || anchor.getJdPublishQuota() == null
? DEFAULT_QUOTA : anchor.getJdPublishQuota();
if (limit <= 0) {
return; return;
} }
long requested = Math.max(0, additionalCount); List<Long> batch = productIds == null ? List.of() : productIds.stream().distinct().toList();
if (snapshot.used() + requested > snapshot.limit()) { long used = userIds.isEmpty() ? 0L : jdPublishItemMapper.countOnShelfByUserIds(userIds);
long alreadyOnShelf = userIds.isEmpty() || batch.isEmpty() ? 0L
: jdPublishItemMapper.countOnShelfInProductIds(userIds, batch);
long requested = Math.max(0L, batch.size() - alreadyOnShelf);
if (used + requested > limit) {
log.warn("[jd-publish] 商品上架配额不足 operatorId={} used={} requested={} limit={}", log.warn("[jd-publish] 商品上架配额不足 operatorId={} used={} requested={} limit={}",
operator == null ? null : operator.getId(), operator == null ? null : operator.getId(), used, requested, limit);
snapshot.used(), requested, snapshot.limit()); throw new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前在架 "
throw new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前已占用 " + used + "/上限 " + limit
+ snapshot.used() + "/上限 " + snapshot.limit() + ",请先在京麦下架商品并在「在架商品」里标记已下架,或联系管理员调整额度后重试");
+ ",请清理京东数据库商品或联系管理员调整配额后重试");
} }
} }
/** 配额归属锚点解析后的团队 uid 集(在架清单与标记下架的权限口径共用,2026-11-25)。 */
public List<Long> teamUserIds(AdminUserEntity operator) {
return teamUserIdsOf(operator == null ? null : anchorOf(operator));
}
private List<Long> teamUserIdsOf(AdminUserEntity anchor) {
return anchor == null || anchor.getId() == null ? List.of()
: userDataScopeSupport.resolveVisibleUserIds(anchor);
}
private AdminUserEntity anchorOf(AdminUserEntity operator) { private AdminUserEntity anchorOf(AdminUserEntity operator) {
// resolveRole 对普通账号返回 null(角色域只有 super_admin/company_super_admin/admin/null) // resolveRole 对普通账号返回 null(角色域只有 super_admin/company_super_admin/admin/null)
if (DeviceSessionPolicy.resolveRole( if (DeviceSessionPolicy.resolveRole(
@@ -68,8 +68,7 @@ import java.util.stream.Collectors;
* ③ 建单前置闸门按铁律 27b 排在一切昂贵动作前:未选商品 / 勾选商品不在可上架作用域 * ③ 建单前置闸门按铁律 27b 排在一切昂贵动作前:未选商品 / 勾选商品不在可上架作用域
* (2026-11-25 起=本账号可见数据权限分组下的分类归属行,跨公司/跨组业务码 403;旧口径 * (2026-11-25 起=本账号可见数据权限分组下的分类归属行,跨公司/跨组业务码 403;旧口径
* 「只认建单人」把同组同事采的商品全拒在门外,客户实况「分类里有 3 个、列表 0 个」)/ * 「只认建单人」把同组同事采的商品全拒在门外,客户实况「分类里有 3 个、列表 0 个」)/
* 超配额(AC-8,{@code JdPublishQuotaService#assertWithinQuota} 原语接线)逐条点名拒绝; * 超配额(AC-8,{@code JdPublishQuotaService#assertWithinQuota} 原语接线)逐条点名拒绝;④ 建单即按商品快照落 {@code biz_jd_publish_item} 行(V210,商品库有
* ④ 建单即按商品快照落 {@code biz_jd_publish_item} 行(V210,商品库有
* 清理语义,发布记录不随商品删除丢失溯源)。</p> * 清理语义,发布记录不随商品删除丢失溯源)。</p>
* *
* <p>建单成功页面推送与兜底拉取共用同一份载荷组装 {@link #buildQueuePayload}: * <p>建单成功页面推送与兜底拉取共用同一份载荷组装 {@link #buildQueuePayload}:
@@ -128,8 +127,9 @@ public class JdPublishTaskService {
public JdPublishTaskVo createTask(JdPublishTaskCreateRequest request, String deviceId) { public JdPublishTaskVo createTask(JdPublishTaskCreateRequest request, String deviceId) {
validate(request); validate(request);
// AC-8 配额闸:前置在一切昂贵动作前(铁律 27b),超配额当场业务码拒绝并点名额度文案。 // AC-8 配额闸:前置在一切昂贵动作前(铁律 27b),超配额当场业务码拒绝并点名额度文案。
// 2026-11-25 口径改在架商品数:传勾选商品集而非个数——批内已在架的不双计(重复上架不重复占位)。
AdminUserEntity operator = adminUserMapper.selectById(request.getUserId()); AdminUserEntity operator = adminUserMapper.selectById(request.getUserId());
jdPublishQuotaService.assertWithinQuota(operator, request.getProductIds().size()); jdPublishQuotaService.assertWithinQuota(operator, request.getProductIds());
// 归属闸(2026-11-25 作用域改口径:选中商品必须在「本账号可见数据权限分组」的分类 // 归属闸(2026-11-25 作用域改口径:选中商品必须在「本账号可见数据权限分组」的分类
// 归属行里,与选品列表/分类下拉同源同口径)。旧形状按 biz_jd_product.user_id 严格 // 归属行里,与选品列表/分类下拉同源同口径)。旧形状按 biz_jd_product.user_id 严格
@@ -0,0 +1,23 @@
-- 迁移 V216:发布明细表加「标记已下架」列 delisted_at(2026-11-25 客户口径改额度计数)。
-- =============================================================
-- 1. 号段协调:V215=jd_shop_category_tree(9538c1c6)已占用,本窗取 V216;
-- 契约正则 V208~V229(JdPublishContractPendingTest)天然覆盖。
--
-- 2. 口径背景:上架上限从「京东数据库占有行数」改为「当前在架商品数」——
-- 在架=发布成功(publish_status='SUCCESS')且未标记下架(delisted_at IS NULL)。
-- 客户在京麦人工下架,系统感知不到,本窗先开「标记已下架」人工腾额度通道
-- (写入口 JdPublishOnShelfService.markDelisted);京麦下架执行链自动回流记欠账。
--
-- 3. 影响表与数据量:biz_jd_publish_item 全量行加列,存量行 delisted_at=NULL
-- (=视为在架,与上线前「成功上架即占用」的初始账一致,不猜历史下架)。
--
-- 4. 可重跑性:plain ALTER(V207/V34 同形先例),Flyway 按版本记账只执行一次。
-- 应用侧:MigrationInventoryTest 自动清点;JdSchemaContractTest 钉 V216 列。
--
-- 5. 回滚(patch,不当期执行):
-- ALTER TABLE biz_jd_publish_item DROP COLUMN delisted_at;
-- DELETE FROM flyway_schema_history WHERE version='216';
-- =============================================================
ALTER TABLE `biz_jd_publish_item`
ADD COLUMN `delisted_at` DATETIME NULL COMMENT '标记已下架时刻(NULL=在架):上架额度按在架商品数计,标记即腾额度' AFTER `jd_ware_id`;
@@ -0,0 +1,28 @@
-- 迁移 V217:普通账号京东上架额度清 0(2026-11-25 分配闸上线的前置清账)。
-- =============================================================
-- 1. 背景:额度语义扩展——普通账号的 jd_publish_quota 从「无人使用的默认 5000」
-- 变为「管理员向员工的额度分配账」,分配闸按 Σ(直接下属非零额度) ≤ 主管额度
-- 校验(AdminUserService 额度编辑块)。存量普通账号全是 V207 的 NOT NULL
-- DEFAULT 5000(历史上后端拒绝为非管理员档写额度,值从未被编辑过),
-- 不清零则分配闸上线即把每个多员工管理员炸红。
--
-- 2. 口径:0=未分配(不计入 Σ、不单独拦人,实际拦截仍看团队在架总和 ≤ 主管额度)。
-- 只动普通档:排除 role ∈ {super_admin, company_super_admin, admin} 与
-- is_admin=1 的行(DeviceSessionPolicy.resolveRole 对「role 空 + is_admin=1」
-- 推断为管理员档,这类行不是普通账号,额度留原值)。
-- 再钉 jd_publish_quota=5000(只清默认值,若未来有人改过别的数字不误伤)。
--
-- 3. 影响表与数据量:users 表普通账号行;管理员档行零触碰。
--
-- 4. 可重跑性:UPDATE 幂等(清过再跑 no-op)。应用侧:MigrationInventoryTest 自动清点。
--
-- 5. 回滚(patch,不当期执行):无法逐行还原默认值来源,按需
-- UPDATE users SET jd_publish_quota=5000 WHERE <同谓词>;
-- DELETE FROM flyway_schema_history WHERE version='217';
-- =============================================================
UPDATE `users`
SET `jd_publish_quota` = 0
WHERE COALESCE(`is_admin`, 0) <> 1
AND (`role` IS NULL OR `role` NOT IN ('super_admin', 'company_super_admin', 'admin'))
AND `jd_publish_quota` = 5000;
@@ -145,7 +145,7 @@
<if test="maxPrice != null">AND p.price_max &lt;= #{maxPrice}</if> <if test="maxPrice != null">AND p.price_max &lt;= #{maxPrice}</if>
<!-- 选品作用域(2026-11-25 客户实况「自定义分类写着 3 个商品、选品列表却是 0 条」): <!-- 选品作用域(2026-11-25 客户实况「自定义分类写着 3 个商品、选品列表却是 0 条」):
用户端「商品上架」的可见面=当前账号可见数据权限分组(JdCategoryScope#visibleGroupIds, 用户端「商品上架」的可见面=当前账号可见数据权限分组(JdCategoryScope#visibleGroupIds,
与分类下拉同一份解析结果)下的分类归属行。与 groupId 合成<b>同一条</b> EXISTS—— 与分类下拉同一份解析结果)下的分类归属行。与上方 groupId 合成<b>同一条</b> EXISTS——
「这个分类」与「我可见的组」必须是同一行归属(不许拿别组分类名凑数); 「这个分类」与「我可见的组」必须是同一行归属(不许拿别组分类名凑数);
visibleGroupIds 为 null/空时退回原来只按 category_id 的等值形状(后管只读页 visibleGroupIds 为 null/空时退回原来只按 category_id 的等值形状(后管只读页
groupId 档行为逐字不变)。徽标计数(JdProductGroupService.listForGroups)读的也是 groupId 档行为逐字不变)。徽标计数(JdProductGroupService.listForGroups)读的也是
@@ -255,13 +255,6 @@
LIMIT #{limit} LIMIT #{limit}
</select> </select>
<!-- 商品上架配额计数(JdPublishQuotaService):按 owner uid 集计 biz_jd_product 行数; <!-- 2026-11-25 口径改造:旧「商品上架配额计数 countByUserIds(按 biz_jd_product 行数)」已删,
uid 集=管理员本人+名下员工(公司超管=全公司成员),由服务侧保证非空 额度正本迁到 mapper/jd/JdPublishItemMapper.xml 的 countOnShelfByUserIds(在架商品数)。 -->
(空集按 0 处理,不进 SQL)。user_id=任务 owner(V193 物化归属列)。 -->
<select id="countByUserIds" resultType="long">
SELECT COUNT(*)
FROM biz_jd_product
WHERE user_id IN
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
</select>
</mapper> </mapper>
@@ -28,4 +28,50 @@
WHERE task_id = #{taskId} WHERE task_id = #{taskId}
GROUP BY publish_status GROUP BY publish_status
</select> </select>
<!-- 在架商品数(上架额度计数正本,2026-11-25 客户口径「上限=同时在架商品数,
下架腾额度」):发布成功(SUCCESS)且未标记下架(delisted_at IS NULL,V216)
的去重商品数。去重口径=DISTINCT product_id——同商品跨任务重复发布只占一个额度位。
⚠ 计数源已从 biz_jd_product 行数(旧「采集库占有量」口径)迁到本表:
采集入库不占额度、上架成功才占、标记下架即腾出。 -->
<select id="countOnShelfByUserIds" resultType="long">
SELECT COUNT(DISTINCT product_id)
FROM biz_jd_publish_item
WHERE publish_status = 'SUCCESS'
AND delisted_at IS NULL
AND user_id IN
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
</select>
<!-- 本批勾选商品里已在架的去重商品数(建单闸「重复上架不双计」):
productIds=建单勾选的 biz_jd_product.id 集(服务侧钳制非空去重后传入)。 -->
<select id="countOnShelfInProductIds" resultType="long">
SELECT COUNT(DISTINCT product_id)
FROM biz_jd_publish_item
WHERE publish_status = 'SUCCESS'
AND delisted_at IS NULL
AND user_id IN
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
AND product_id IN
<foreach collection="productIds" item="pid" open="(" separator="," close=")">#{pid}</foreach>
</select>
<!-- 在架商品分页(用户端「在架商品」面板):同商品取最新一行(GROUP BY product_id
的 MAX(id)),外层按 id 倒序分页。谓词与 countOnShelfByUserIds 同口径,
面板行数与额度读数对得上是这条链的验收项。 -->
<select id="selectOnShelfItems" resultType="com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity">
SELECT i.*
FROM biz_jd_publish_item i
JOIN (
SELECT MAX(id) AS max_id
FROM biz_jd_publish_item
WHERE publish_status = 'SUCCESS'
AND delisted_at IS NULL
AND user_id IN
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
GROUP BY product_id
) t ON t.max_id = i.id
ORDER BY i.id DESC
LIMIT #{limit} OFFSET #{offset}
</select>
</mapper> </mapper>
@@ -118,7 +118,13 @@ class MigratedSqlEquivalenceTest {
// mapper/company/CompanyMapper.xml(SqlLayeringConventionTest 抓到 898e8a5e 走了注解 // mapper/company/CompanyMapper.xml(SqlLayeringConventionTest 抓到 898e8a5e 走了注解
// 通道),SQL 文本未改写;非注解迁移件,逐条点名进下方 NOT_MIGRATED // 通道),SQL 文本未改写;非注解迁移件,逐条点名进下方 NOT_MIGRATED
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 152 → 154)。 //(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 152 → 154)。
private static final int XML_SELECT_TOTAL = 109; // 109 → 111:2026-11-25 上架额度改口径(客户「上限=同时在架商品数,下架腾额度」)——
// JdPublishItemMapper 新写 3 条只读 select(countOnShelfByUserIds 在架去重计数/
// countOnShelfInProductIds 批内已在架不双计/selectOnShelfItems 在架分页面板),+3;
// 旧「采集库占有量」计数口 JdProductMapper#countByUserIds 随口径源迁移整条删除,−1。
// 净 +2。全部新写非迁移语句,逐条点名进下方 NOT_MIGRATED(旧点名一并摘除);
// SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 156 → 158。
private static final int XML_SELECT_TOTAL = 111;
/** /**
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。 * 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
@@ -224,7 +230,7 @@ class MigratedSqlEquivalenceTest {
// 配额原语),没有注解原文可对撞,点名留痕。该笔当时只点编译没跑整量、漏记两处 // 配额原语),没有注解原文可对撞,点名留痕。该笔当时只点编译没跑整量、漏记两处
// 账本,2026-11-15 发版前整量抓到补记(XML_SELECT_TOTAL 113 → 114, // 账本,2026-11-15 发版前整量抓到补记(XML_SELECT_TOTAL 113 → 114,
// SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 163 → 164)。 // SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 163 → 164)。
"JdProductMapper#countByUserIds", // 2026-11-25 额度改口径随旧计数源整条删除(口径源只能一份),点名一并摘除。
// 47fc0e08(2026-11-16 平台超管 500 热修)给 selectAllGroups 的 XML 补 // 47fc0e08(2026-11-16 平台超管 500 热修)给 selectAllGroups 的 XML 补
// g.company_id AS companyId:注解时代原文没有这列,等价性这支对撞即红。 // g.company_id AS companyId:注解时代原文没有这列,等价性这支对撞即红。
// 有意改动按先例整行摘账本点名留痕(LEDGER_ROWS 83 → 82 / SELECTS 59 → 58); // 有意改动按先例整行摘账本点名留痕(LEDGER_ROWS 83 → 82 / SELECTS 59 → 58);
@@ -242,6 +248,14 @@ class MigratedSqlEquivalenceTest {
//(XML_SELECT_TOTAL 103 → 105,SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。 //(XML_SELECT_TOTAL 103 → 105,SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。
"JdPublishItemMapper#selectPublishableItems", "JdPublishItemMapper#selectPublishableItems",
"JdPublishItemMapper#countByPublishStatus", "JdPublishItemMapper#countByPublishStatus",
// 2026-11-25 上架额度改口径:JdPublishItemMapper 新写 3 条只读 select
//(countOnShelfByUserIds 在架去重计数=额度正本、countOnShelfInProductIds
// 批内已在架不双计、selectOnShelfItems 在架面板分页 MAX(id) 去重),
// 从来没有注解原文可对撞,逐条点名留痕(同轮 JdProductMapper#countByUserIds
// 随旧口径删除摘除本点名;XML_SELECT_TOTAL 109 → 111)。
"JdPublishItemMapper#countOnShelfByUserIds",
"JdPublishItemMapper#countOnShelfInProductIds",
"JdPublishItemMapper#selectOnShelfItems",
// Phase 5 原生 XML 行锁,不存在注解时代原文。 // Phase 5 原生 XML 行锁,不存在注解时代原文。
"FileTaskMapper#selectByIdForUpdate", "FileTaskMapper#selectByIdForUpdate",
// 2026-11-21 v1.7 店铺名单:JdProductMapper 新写 1 条只读 select // 2026-11-21 v1.7 店铺名单:JdProductMapper 新写 1 条只读 select
@@ -149,7 +149,12 @@ class SqlLayeringConventionTest {
// 154 → 156:2026-11-23 京麦授权类目树(V215)新落 mapper/jd/JdShopCategoryTreeMapper.xml // 154 → 156:2026-11-23 京麦授权类目树(V215)新落 mapper/jd/JdShopCategoryTreeMapper.xml
// 2 条写语句——deleteByShopId(整店快照替换第一步,1 delete)+ insertBatch(500 行一批, // 2 条写语句——deleteByShopId(整店快照替换第一步,1 delete)+ insertBatch(500 行一批,
// 1 insert);全部新写非迁移语句,该文件 XML_SELECT_TOTAL 不动(无 select)。 // 1 insert);全部新写非迁移语句,该文件 XML_SELECT_TOTAL 不动(无 select)。
private static final int XML_STATEMENT_TOTAL = 156; // 156 → 158:2026-11-25 上架额度改口径(客户「上限=同时在架商品数,下架腾额度」)——
// JdPublishItemMapper 新写 3 条只读 select(countOnShelfByUserIds/countOnShelfInProductIds/
// selectOnShelfItems),+3;旧「采集库占有量」计数口 JdProductMapper#countByUserIds 整条
// 删除(口径源只能一份),−1。净 +2。标记下架写侧走 MyBatis-Plus wrapper 不落 XML,
// 语句数不动;逐条点名进 MigratedSqlEquivalenceTest.NOT_MIGRATED(同轮 109 → 111)。
private static final int XML_STATEMENT_TOTAL = 158;
/** /**
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数: * wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
@@ -85,6 +85,10 @@ class PageDefaultsLedgerTest {
"JdPublishController.java#page=FIRST_PAGE", "JdPublishController.java#page=FIRST_PAGE",
"JdPublishController.java#page_size=JD_PRODUCTS_PAGE_SIZE", "JdPublishController.java#page_size=JD_PRODUCTS_PAGE_SIZE",
"JdPublishController.java#limit=DEFAULT_RESULT_LIMIT", "JdPublishController.java#limit=DEFAULT_RESULT_LIMIT",
// 2026-11-25 上架额度改口径:GET /api/jd-publish/on-shelf(团队在架分页)两处出站点,
// 默认值与选品分页同常量(page=FIRST_PAGE、page_size=JD_PRODUCTS_PAGE_SIZE,上限钳制在服务侧)
"JdPublishController.java#page=FIRST_PAGE",
"JdPublishController.java#page_size=JD_PRODUCTS_PAGE_SIZE",
"NotificationController.java#page=FIRST_PAGE", "NotificationController.java#page=FIRST_PAGE",
"NotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE", "NotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
// (本批 /groups 端点:参数名与默认值和列表端点同,台账按出站点计数、不去重) // (本批 /groups 端点:参数名与默认值和列表端点同,台账按出站点计数、不去重)
@@ -132,11 +136,12 @@ class PageDefaultsLedgerTest {
+ " page/page_size 两处出站点;60→59:2026-11-17 任务证据特性下线," + " page/page_size 两处出站点;60→59:2026-11-17 任务证据特性下线,"
+ " AdminTaskEvidenceController 两处出站点随控制器删除)") + " AdminTaskEvidenceController 两处出站点随控制器删除)")
.isEqualTo(LEDGER.stream().sorted().toList()); .isEqualTo(LEDGER.stream().sorted().toList());
// 同口径非零对照:台账不是空的,扫描器也确实数得出 62 处 // 同口径非零对照:台账不是空的,扫描器也确实数得出 64 处
// (61 而不是 60:2026-11-15 京东任务面板改版(45d0989a)新增 GET /api/jd-collect/history // (61 而不是 60:2026-11-15 京东任务面板改版(45d0989a)新增 GET /api/jd-collect/history
// 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处; // 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处;
// 59→62:v1.5 Phase 4 用户端「商品上架」读侧三出站点随 917884aa 登记同窗) // 59→62:v1.5 Phase 4 用户端「商品上架」读侧三出站点随 917884aa 登记同窗;
assertThat(constants).hasSize(62); // 62→64:2026-11-25 上架额度改口径新增 GET /api/jd-publish/on-shelf 的 page/page_size 两处)
assertThat(constants).hasSize(64);
} }
@Test @Test
@@ -153,8 +158,9 @@ class PageDefaultsLedgerTest {
assertThat(kindsUsing(actual, "page", "FIRST_PAGE")) assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
.as("页码口径只有一套:全部从 1 起(26→27:v1.5 Phase 4 用户端「商品上架」products 选品分页也是分页出站点;" .as("页码口径只有一套:全部从 1 起(26→27:v1.5 Phase 4 用户端「商品上架」products 选品分页也是分页出站点;"
+ "26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;" + "26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;"
+ "27→26:2026-11-17 任务证据特性下线随删一处)") + "27→26:2026-11-17 任务证据特性下线随删一处;"
.isEqualTo(27); + "27→28:2026-11-25 上架额度改口径新增 GET /api/jd-publish/on-shelf 分页)")
.isEqualTo(28);
assertThat(distinctConstants(actual, "page_size")) assertThat(distinctConstants(actual, "page_size"))
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 " .as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红") + "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
@@ -134,7 +134,9 @@ class RequestSuppliedIdentityOutletTest {
// GET /api/jd-publish/products(选品分页,AC-9 owner 过滤)+ GET /api/jd-publish/dashboard // GET /api/jd-publish/products(选品分页,AC-9 owner 过滤)+ GET /api/jd-publish/dashboard
// + GET /api/jd-publish/history(面板统计卡+历史层),都是 @RequestParam("user_id") 先过 // + GET /api/jd-publish/history(面板统计卡+历史层),都是 @RequestParam("user_id") 先过
// resolveOwnershipUserId——覆盖面变大,不是放宽分母。 // resolveOwnershipUserId——覆盖面变大,不是放宽分母。
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(72); // 73 而不是 72:2026-11-25 上架额度改口径新增 GET /api/jd-publish/on-shelf(团队在架分页
// +额度余量),@RequestParam("user_id") 先过 requireSessionOwnerUserId——覆盖面变大,不是放宽分母。
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(73);
assertThat(scan.unbound()).as("取请求身份但未接出口的 handler:只剩豁免那一条") assertThat(scan.unbound()).as("取请求身份但未接出口的 handler:只剩豁免那一条")
.containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET); .containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET);
} }
@@ -61,7 +61,7 @@ class AdminUserServiceCompanySuperAdminTest {
} }
@Test @Test
void 京东额度允许零并拒绝负数和普通账号() { void 京东额度允许零并拒绝负数_普通账号也可分配() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null); AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(10L, "admin", 1L, 1L); AdminUserEntity target = user(10L, "admin", 1L, 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin"); when(authSupport.currentRole(operator)).thenReturn("super_admin");
@@ -73,10 +73,106 @@ class AdminUserServiceCompanySuperAdminTest {
request.setJdPublishQuota(-1); request.setJdPublishQuota(-1);
assertThatThrownBy(() -> service.updateUser(operator, 10L, request)) assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
.isInstanceOf(BusinessException.class).hasMessageContaining("不能为负数"); .isInstanceOf(BusinessException.class).hasMessageContaining("不能为负数");
// 2026-11-25 分配闸上线:普通账号也可设额度(=主管向员工的分配账,0=未分配),
// 旧 400「只能为管理员设置京东上架额度」废止——没有员工额度数字,Σ 总和账无从算起。
request.setJdPublishQuota(1); request.setJdPublishQuota(1);
target.setRole("normal"); target.setRole("normal");
assertThatThrownBy(() -> service.updateUser(operator, 10L, request)) service.updateUser(operator, 10L, request);
.isInstanceOf(BusinessException.class).hasMessageContaining("只能为管理员"); verify(userMapper, org.mockito.Mockito.atLeast(2)).update(any(), any());
}
/**
* 2026-11-25 客户口径「管理员下的普通员工总和也不能超过这个上限」——分配闸:
* Σ(直接下属非零额度,被编辑账号取新值) ≤ 锚点管理员额度;0=未分配不计入;
* 锚点额度 0=不限放行;锚点为站点超管(额度豁免)放行。
*/
@Test
void 员工额度总和超过主管额度_保存被拒并点名两边数字() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity manager = user(5L, "admin", 1L, 1L);
manager.setJdPublishQuota(5000);
AdminUserEntity target = user(11L, "normal", 1L, 5L);
AdminUserEntity sibling = user(12L, "normal", 1L, 5L);
sibling.setJdPublishQuota(2500);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
when(userMapper.selectById(5L)).thenReturn(manager);
when(userMapper.selectList(any())).thenReturn(List.of(target, sibling));
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setJdPublishQuota(2600);
assertThatThrownBy(() -> service.updateUser(operator, 11L, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("已超过管理员额度")
.hasMessageContaining("5100")
.hasMessageContaining("5000");
verify(userMapper, never()).update(any(), any());
}
@Test
void 员工额度清零_未分配不计入总和_放行() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity manager = user(5L, "admin", 1L, 1L);
manager.setJdPublishQuota(5000);
AdminUserEntity target = user(11L, "normal", 1L, 5L);
target.setJdPublishQuota(3000);
AdminUserEntity sibling = user(12L, "normal", 1L, 5L);
sibling.setJdPublishQuota(2500);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
when(userMapper.selectById(5L)).thenReturn(manager);
when(userMapper.selectList(any())).thenReturn(List.of(target, sibling));
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setJdPublishQuota(0);
service.updateUser(operator, 11L, request);
verify(userMapper).update(any(), any());
}
@Test
void 下调主管额度低于员工总和_同样被拒() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity manager = user(5L, "admin", 1L, 1L);
manager.setJdPublishQuota(5000);
AdminUserEntity subordinate = user(11L, "normal", 1L, 5L);
subordinate.setJdPublishQuota(3000);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(5L)).thenReturn(manager);
when(userMapper.selectList(any())).thenReturn(List.of(subordinate));
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setJdPublishQuota(2000);
assertThatThrownBy(() -> service.updateUser(operator, 5L, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("已超过管理员额度");
}
@Test
void 主管额度设为不限_分配闸放行() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity manager = user(5L, "admin", 1L, 1L);
manager.setJdPublishQuota(5000);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(5L)).thenReturn(manager);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setJdPublishQuota(0);
service.updateUser(operator, 5L, request);
verify(userMapper).update(any(), any());
}
@Test
void 主管是站点超管_额度豁免不进分配账() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(11L, "normal", 1L, 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
when(userMapper.selectById(1L)).thenReturn(operator);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setJdPublishQuota(9999);
service.updateUser(operator, 11L, request);
verify(userMapper).update(any(), any());
} }
/** /**
@@ -156,6 +156,28 @@ class JdSchemaContractTest {
assertTrue(sql.contains("迁移 V210"), "头注释必须是 `-- 迁移 V210…`(MigrationInventoryTest 口径)"); assertTrue(sql.contains("迁移 V210"), "头注释必须是 `-- 迁移 V210…`(MigrationInventoryTest 口径)");
} }
@Test
void V216_V217_在架标记列与普通账号额度清零() {
// 2026-11-25 额度改口径两笔:V216 在架标记列(下架腾额度的落点)+ V217 分配闸前置清账。
String sql = read(DB_DIR.resolve("V216__jd_publish_item_delisted.sql"));
assertTrue(sql.contains("迁移 V216"), "头注释必须是 `-- 迁移 V216…`(MigrationInventoryTest 口径)");
assertTrue(sql.contains("biz_jd_publish_item"), "必须落在发布明细表");
assertTrue(linesContaining(sql, "`delisted_at`").stream()
.anyMatch(line -> line.contains("DATETIME NULL")),
"delisted_at 必须 DATETIME NULL——NULL=在架,标记即腾额度(JdPublishOnShelfService)");
String reset = read(DB_DIR.resolve("V217__users_normal_quota_reset.sql"));
assertTrue(reset.contains("迁移 V217"), "头注释必须是 `-- 迁移 V217…`(MigrationInventoryTest 口径)");
assertTrue(reset.contains("UPDATE `users`") && reset.contains("`jd_publish_quota` = 0"),
"普通账号额度必须清 0(0=未分配,不计入 Σ;分配闸上线的前置清账,否则存量默认 5000 当场炸红)");
// 谓词三件套:is_admin=1 的管理员推断档不碰、管理员三档不碰、只清默认值 5000(重跑 no-op 幂等)。
assertTrue(reset.contains("is_admin"), "必须排除 is_admin=1 的管理员推断档(DeviceSessionPolicy.resolveRole 口径)");
assertTrue(reset.contains("'admin'") && reset.contains("'company_super_admin'")
&& reset.contains("'super_admin'"),
"必须点名排除管理员三档");
assertTrue(reset.contains("`jd_publish_quota` = 5000"), "只清默认值 5000,重跑幂等");
}
@Test @Test
void V214_分类店铺名单_同分类唯一键形状() { void V214_分类店铺名单_同分类唯一键形状() {
String sql = read(DB_DIR.resolve("V214__jd_group_shop.sql")); String sql = read(DB_DIR.resolve("V214__jd_group_shop.sql"));
@@ -0,0 +1,80 @@
package com.nanri.aiimage.modules.jd.mapper;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 上架额度「在架商品数」计数 SQL 契约格(2026-11-25 客户口径改造)。
*
* <p><b>为什么钉 SQL</b>:额度 used 从 {@code biz_jd_product} 行数迁到
* {@code biz_jd_publish_item} 后,三个谓词一个都不能静默丢——丢 {@code delisted_at IS NULL}
* 则「下架腾额度」当场失效(标记了仍占位,客户换产品卖被误拦);丢
* {@code publish_status='SUCCESS'} 则 PENDING/FAILED 行也占额度;丢 {@code DISTINCT product_id}
* 则同商品跨任务重复发布双计额度。服务层单测全走 mock,回退只有本格拦得住
* (ShopManageGroupScopeSqlTest 三连缺列的同款教训)。</p>
*/
class JdPublishOnShelfSqlTest {
private static final String XML = "mapper/jd/JdPublishItemMapper.xml";
private static final String NS = "com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper";
@Test
void 在架计数必须同时带成功态与未下架两个谓词并按商品去重() throws Exception {
String sql = render("countOnShelfByUserIds", Map.of("userIds", List.of(1L, 2L)));
assertEquals("SELECT COUNT(DISTINCT product_id) FROM biz_jd_publish_item"
+ " WHERE publish_status = 'SUCCESS' AND delisted_at IS NULL AND user_id IN ( ? , ? )", sql,
"额度 used 正本谓词变了:少 delisted_at IS NULL=标记下架不腾额度(客户「下架 10 再上 10」被误拦);"
+ "少 publish_status='SUCCESS'=未发布/失败行也占额度;少 DISTINCT=同商品重复发布双计");
}
@Test
void 批内已在架不双计的谓词与计数口径同源() throws Exception {
String sql = render("countOnShelfInProductIds",
Map.of("userIds", List.of(1L, 2L), "productIds", List.of(7L)));
assertEquals("SELECT COUNT(DISTINCT product_id) FROM biz_jd_publish_item"
+ " WHERE publish_status = 'SUCCESS' AND delisted_at IS NULL"
+ " AND user_id IN ( ? , ? ) AND product_id IN ( ? )", sql,
"两条计数谓词必须逐字同源(除批集收窄),否则面板余量与建单净新增两套账");
}
@Test
void 在架面板分页按商品去重取最新行且谓词与计数同源() throws Exception {
String sql = render("selectOnShelfItems",
Map.of("userIds", List.of(1L, 2L), "offset", 0L, "limit", 20));
// 外层投影与排序逐字钉;内层子查询谓词用包含判据(同一组谓词在两条计数里已逐字钉过)。
assertTrue(sql.startsWith("SELECT i.* FROM biz_jd_publish_item i JOIN ("
+ " SELECT MAX(id) AS max_id FROM biz_jd_publish_item"
+ " WHERE publish_status = 'SUCCESS' AND delisted_at IS NULL"
+ " AND user_id IN ( ? , ? ) GROUP BY product_id ) t ON t.max_id = i.id"),
"面板必须与计数同口径去重(GROUP BY product_id 取 MAX(id) 最新行),否则面板行数≠额度读数");
assertTrue(sql.endsWith("ORDER BY i.id DESC LIMIT ? OFFSET ?"),
"分页排序必须 id 倒序游标稳定(正序会让翻页看到重复/漏行)");
}
private static String render(String id, Map<String, Object> params) throws Exception {
MappedStatement statement = parse().getMappedStatement(NS + "." + id);
return statement.getBoundSql(params).getSql().replaceAll("\\s+", " ").trim();
}
private static Configuration parse() throws Exception {
MybatisConfiguration configuration = new MybatisConfiguration();
try (InputStream in = Resources.getResourceAsStream(XML)) {
new XMLMapperBuilder(in, configuration, XML, configuration.getSqlFragments()).parse();
}
return configuration;
}
}
@@ -0,0 +1,213 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishOnShelfVo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 在架商品面板与「标记已下架」(JdPublishOnShelfService)行为测试(2026-11-25 额度改口径)。
*
* <p>核心判据:<b>标记按商品整组生效</b>——同商品跨任务的多条 SUCCESS 行必须一起落
* delisted_at,只标面板展示那一行,旧行仍被 {@code COUNT(DISTINCT product_id)} 计为在架、
* 额度腾不出去(客户「下架 10 再上 10」当场误拦)。权限=团队口径;面板余量读数与
* 配额闸同一正本(quotaOf)。</p>
*/
@ExtendWith(MockitoExtension.class)
class JdPublishOnShelfServiceTest {
@Mock
private AdminUserMapper adminUserMapper;
@Mock
private JdPublishItemMapper jdPublishItemMapper;
@Mock
private JdPublishQuotaService jdPublishQuotaService;
@Mock
private OssStorageService ossStorageService;
private JdPublishOnShelfService service;
@BeforeEach
void setUp() {
service = new JdPublishOnShelfService(adminUserMapper, jdPublishItemMapper,
jdPublishQuotaService, ossStorageService);
ReflectionTestUtils.setField(service, "bucket", "jd-products");
}
private JdPublishItemEntity item(long id, long productId, long userId, String status, LocalDateTime delistedAt) {
JdPublishItemEntity row = new JdPublishItemEntity();
row.setId(id);
row.setProductId(productId);
row.setUserId(userId);
row.setPublishStatus(status);
row.setDelistedAt(delistedAt);
row.setTitle("收纳盒A");
row.setProductCode("100365361600");
row.setShopName("家居日用数据库店");
row.setJdWareId("999");
row.setUpdatedAt(LocalDateTime.of(2026, 11, 23, 20, 30));
return row;
}
@Test
void 标记下架按商品整组回写_不是只标面板那一行() {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
when(adminUserMapper.selectById(9L)).thenReturn(operator);
when(jdPublishItemMapper.selectById(100L)).thenReturn(item(100L, 7L, 9L, "SUCCESS", null));
when(jdPublishQuotaService.teamUserIds(operator)).thenReturn(List.of(5L, 9L));
service.markDelisted(100L, 9L, true);
ArgumentCaptor<LambdaUpdateWrapper<JdPublishItemEntity>> captor =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(jdPublishItemMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
LambdaUpdateWrapper<JdPublishItemEntity> wrapper = captor.getValue();
wrapper.getSqlSegment(); // MP 3.5.7 惯例:先求值一次才把条件参数铺进 paramNameValuePairs
assertThat(wrapper.getSqlSet()).contains("delisted_at");
// 谓词按商品整组:product_id+SUCCESS+团队 uid 集,绝不按单行 id
assertThat(wrapper.getSqlSegment()).contains("product_id").contains("publish_status").contains("user_id");
assertThat(wrapper.getParamNameValuePairs().values()).contains(7L, "SUCCESS", 5L, 9L);
assertThat(wrapper.getParamNameValuePairs().values()).doesNotContain(100L);
}
@Test
void 撤销标记同样整组回拨_delisted_at置空() {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
when(adminUserMapper.selectById(9L)).thenReturn(operator);
when(jdPublishItemMapper.selectById(100L))
.thenReturn(item(100L, 7L, 9L, "SUCCESS", LocalDateTime.now()));
when(jdPublishQuotaService.teamUserIds(operator)).thenReturn(List.of(5L, 9L));
service.markDelisted(100L, 9L, false);
ArgumentCaptor<LambdaUpdateWrapper<JdPublishItemEntity>> captor =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(jdPublishItemMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
captor.getValue().getSqlSegment(); // 同前:铺参数
assertThat(captor.getValue().getSqlSet()).contains("delisted_at");
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(7L, "SUCCESS");
}
@Test
void 非成功行不许标记() {
when(jdPublishItemMapper.selectById(101L)).thenReturn(item(101L, 7L, 9L, "PUBLISHING", null));
assertThatThrownBy(() -> service.markDelisted(101L, 9L, true))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有发布成功的商品");
}
@Test
void 明细行不存在响亮拒绝() {
when(jdPublishItemMapper.selectById(404L)).thenReturn(null);
assertThatThrownBy(() -> service.markDelisted(404L, 9L, true))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("发布明细不存在");
}
@Test
void 跨团队标记被403拒_管理员可替名下员工标记() {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
when(adminUserMapper.selectById(9L)).thenReturn(operator);
when(jdPublishItemMapper.selectById(102L)).thenReturn(item(102L, 7L, 77L, "SUCCESS", null));
when(jdPublishQuotaService.teamUserIds(operator)).thenReturn(List.of(5L, 9L));
BusinessException ex = org.assertj.core.api.Assertions.catchThrowableOfType(
() -> service.markDelisted(102L, 9L, true), BusinessException.class);
assertThat(ex).isNotNull();
assertThat(ex.getCode()).isEqualTo(403);
assertThat(ex.getMessage()).contains("本团队");
// 员工 9 的行在团队集 [5,9] 内 → 放行(上面第一支已钉正向)
org.mockito.Mockito.clearInvocations(jdPublishItemMapper);
when(jdPublishItemMapper.selectById(100L)).thenReturn(item(100L, 7L, 9L, "SUCCESS", null));
assertThatCode(() -> service.markDelisted(100L, 9L, true)).doesNotThrowAnyException();
}
@Test
void 面板余量读数与配额闸同源_分页钳制() {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
when(adminUserMapper.selectById(9L)).thenReturn(operator);
when(jdPublishQuotaService.quotaOf(operator)).thenReturn(new JdPublishQuotaService.QuotaSnapshot(25L, 5000L));
when(jdPublishQuotaService.teamUserIds(operator)).thenReturn(List.of(5L, 9L));
JdPublishItemEntity row = item(100L, 7L, 9L, "SUCCESS", null);
row.setMainImageObjectKey("images/main.jpg");
when(jdPublishItemMapper.selectOnShelfItems(List.of(5L, 9L), 20L, 10))
.thenReturn(List.of(row));
when(ossStorageService.presignObjectDownload(eq("jd-products"), eq("images/main.jpg"), anyInt()))
.thenReturn("https://oss/signed");
JdPublishOnShelfVo vo = service.page(9L, 3, 10);
assertThat(vo.getUsed()).isEqualTo(25L);
assertThat(vo.getLimit()).isEqualTo(5000L);
assertThat(vo.isUnlimited()).isFalse();
assertThat(vo.getTotal()).isEqualTo(25L);
assertThat(vo.getItems()).hasSize(1);
assertThat(vo.getItems().get(0).getImageUrl()).isEqualTo("https://oss/signed");
assertThat(vo.getItems().get(0).getTitle()).isEqualTo("收纳盒A");
}
@Test
void 页大小超上限钳到100_越界页不查SQL() {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
when(adminUserMapper.selectById(9L)).thenReturn(operator);
when(jdPublishQuotaService.quotaOf(operator)).thenReturn(new JdPublishQuotaService.QuotaSnapshot(25L, 5000L));
when(jdPublishQuotaService.teamUserIds(operator)).thenReturn(List.of(5L, 9L));
when(jdPublishItemMapper.selectOnShelfItems(anyList(), anyLong(), eq(100))).thenReturn(List.of());
service.page(9L, 1, 9999);
// offset 20 ≥ used 25? 不——page=1 先钉钳制;再打越界页
JdPublishOnShelfVo beyond = service.page(9L, 4, 10); // offset=30 ≥ 25
assertThat(beyond.getItems()).isEmpty();
verify(jdPublishItemMapper, never()).selectOnShelfItems(anyList(), eq(30L), anyInt());
}
@Test
void 不限额度面板照常出数_unlimited显形() {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
when(adminUserMapper.selectById(9L)).thenReturn(operator);
when(jdPublishQuotaService.quotaOf(operator)).thenReturn(new JdPublishQuotaService.QuotaSnapshot(3L, 0L));
when(jdPublishQuotaService.teamUserIds(operator)).thenReturn(List.of(5L, 9L));
when(jdPublishItemMapper.selectOnShelfItems(List.of(5L, 9L), 0L, 20))
.thenReturn(List.of(item(100L, 7L, 9L, "SUCCESS", null)));
JdPublishOnShelfVo vo = service.page(9L, 1, 20);
assertThat(vo.isUnlimited()).isTrue();
assertThat(vo.getItems()).hasSize(1);
assertThat(vo.getItems().get(0).getImageUrl()).isNull(); // 无主图快照不签 URL
verify(ossStorageService, never()).presignObjectDownload(anyString(), anyString(), anyInt());
}
}
@@ -3,7 +3,7 @@ package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper; import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper; import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport; import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@@ -23,7 +23,10 @@ import static org.mockito.Mockito.when;
/** /**
* 商品上架配额(JdPublishQuotaService)行为测试:默认 5000、0=不限、普通账号锚定到 * 商品上架配额(JdPublishQuotaService)行为测试:默认 5000、0=不限、普通账号锚定到
* created_by_id 管理员并按其团队 uid 集计数、站点超管豁免、恰好等于上限的边界放行、 * created_by_id 管理员并按其团队 uid 集计数、站点超管豁免、恰好等于上限的边界放行、
* 空集按 used=0 不进 SQL。判限口径=「管理员+名下员工合计」(2026-11-15 用户口径)。 * 空集按 used=0 不进 SQL。判限口径=「管理员+名下员工合计」(2026-11-15 用户口径);
* 计数口径=团队在架商品数(发布成功且未标记下架,去重商品,2026-11-25 客户口径
* 「上限=同时在架商品数,下架 10 个就能再上架 10 个」)——旧「采集库占有行数」
* 口径判据随正本迁移替换。
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class JdPublishQuotaServiceTest { class JdPublishQuotaServiceTest {
@@ -33,10 +36,10 @@ class JdPublishQuotaServiceTest {
@Mock @Mock
private UserDataScopeSupport userDataScopeSupport; private UserDataScopeSupport userDataScopeSupport;
@Mock @Mock
private JdProductMapper jdProductMapper; private JdPublishItemMapper jdPublishItemMapper;
private JdPublishQuotaService newService() { private JdPublishQuotaService newService() {
return new JdPublishQuotaService(adminUserMapper, userDataScopeSupport, jdProductMapper); return new JdPublishQuotaService(adminUserMapper, userDataScopeSupport, jdPublishItemMapper);
} }
private AdminUserEntity admin(long id) { private AdminUserEntity admin(long id) {
@@ -54,21 +57,29 @@ class JdPublishQuotaServiceTest {
return user; return user;
} }
/** 批量商品 id(n 个不重复)。 */
private static List<Long> products(int n) {
return java.util.stream.LongStream.rangeClosed(1, n).boxed().toList();
}
/** 双重载(Long/实体)消歧:lambda 参数显式标注实体形状(argThat(...))。 */ /** 双重载(Long/实体)消歧:lambda 参数显式标注实体形状(argThat(...))。 */
@Test @Test
void 默认上限5000_超限拒绝且文案含占用与上限() { void 默认上限5000_超限拒绝且文案含在架与上限() {
JdPublishQuotaService service = newService(); JdPublishQuotaService service = newService();
AdminUserEntity employee = employee(9L, 5L); AdminUserEntity employee = employee(9L, 5L);
when(adminUserMapper.selectById(5L)).thenReturn(admin(5L)); when(adminUserMapper.selectById(5L)).thenReturn(admin(5L));
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L))) when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L, 10L)); .thenReturn(List.of(5L, 9L, 10L));
when(jdProductMapper.countByUserIds(List.of(5L, 9L, 10L))).thenReturn(4990L); when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L, 10L))).thenReturn(4990L);
when(jdPublishItemMapper.countOnShelfInProductIds(List.of(5L, 9L, 10L), products(20))).thenReturn(0L);
assertThatThrownBy(() -> service.assertWithinQuota(employee, 20)) assertThatThrownBy(() -> service.assertWithinQuota(employee, products(20)))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.hasMessageContaining("4990") .hasMessageContaining("4990")
.hasMessageContaining("5000") .hasMessageContaining("5000")
.hasMessageContaining("在架")
.hasMessageContaining("标记已下架")
.hasMessageContaining("管理员"); .hasMessageContaining("管理员");
// 普通账号必须锚定到所属管理员(uid=5)的团队集,而不是只数自己 // 普通账号必须锚定到所属管理员(uid=5)的团队集,而不是只数自己
verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)); verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L));
@@ -80,9 +91,38 @@ class JdPublishQuotaServiceTest {
AdminUserEntity operator = admin(5L); AdminUserEntity operator = admin(5L);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L))) when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L)); .thenReturn(List.of(5L, 9L));
when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(4990L); when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(4990L);
when(jdPublishItemMapper.countOnShelfInProductIds(List.of(5L, 9L), products(10))).thenReturn(0L);
assertThatCode(() -> service.assertWithinQuota(operator, 10)).doesNotThrowAnyException(); assertThatCode(() -> service.assertWithinQuota(operator, products(10))).doesNotThrowAnyException();
}
@Test
void 批内已在架商品不双计_重复上架不重复占位() {
JdPublishQuotaService service = newService();
AdminUserEntity operator = admin(5L);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L));
when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(4995L);
// 勾选 10 个里 5 个当前已在架(下架没标记/重发场景):净新增只有 5,4995+5=5000 恰好放行
when(jdPublishItemMapper.countOnShelfInProductIds(List.of(5L, 9L), products(10))).thenReturn(5L);
assertThatCode(() -> service.assertWithinQuota(operator, products(10))).doesNotThrowAnyException();
}
@Test
void 批内已在架不足抵消费_仍拒() {
JdPublishQuotaService service = newService();
AdminUserEntity operator = admin(5L);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L));
when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(4995L);
when(jdPublishItemMapper.countOnShelfInProductIds(List.of(5L, 9L), products(10))).thenReturn(4L);
assertThatThrownBy(() -> service.assertWithinQuota(operator, products(10)))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("4995")
.hasMessageContaining("5000");
} }
@Test @Test
@@ -90,10 +130,8 @@ class JdPublishQuotaServiceTest {
JdPublishQuotaService service = newService(); JdPublishQuotaService service = newService();
AdminUserEntity operator = admin(5L); AdminUserEntity operator = admin(5L);
operator.setJdPublishQuota(0); operator.setJdPublishQuota(0);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L))) assertThatCode(() -> service.assertWithinQuota(operator, products(999_999))).doesNotThrowAnyException();
.thenReturn(List.of()); verifyNoInteractions(jdPublishItemMapper, adminUserMapper);
assertThatCode(() -> service.assertWithinQuota(operator, 999_999)).doesNotThrowAnyException();
verifyNoInteractions(jdProductMapper, adminUserMapper);
} }
@Test @Test
@@ -103,8 +141,8 @@ class JdPublishQuotaServiceTest {
siteSuperAdmin.setId(1L); siteSuperAdmin.setId(1L);
siteSuperAdmin.setRole("super_admin"); siteSuperAdmin.setRole("super_admin");
assertThatCode(() -> service.assertWithinQuota(siteSuperAdmin, 999_999)).doesNotThrowAnyException(); assertThatCode(() -> service.assertWithinQuota(siteSuperAdmin, products(999_999))).doesNotThrowAnyException();
verifyNoInteractions(jdProductMapper, userDataScopeSupport, adminUserMapper); verifyNoInteractions(jdPublishItemMapper, userDataScopeSupport, adminUserMapper);
} }
@Test @Test
@@ -114,22 +152,22 @@ class JdPublishQuotaServiceTest {
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L))) when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of()); .thenReturn(List.of());
// used=0:additional=5000 恰好等于上限,放行 // used=0:本批净新增 5000 恰好等于上限,放行
assertThatCode(() -> service.assertWithinQuota(operator, 5000)).doesNotThrowAnyException(); assertThatCode(() -> service.assertWithinQuota(operator, products(5000))).doesNotThrowAnyException();
// additional=5001 超限,但空集不查库 // 5001 超限,但空集不查库
assertThatThrownBy(() -> service.assertWithinQuota(operator, 5001)) assertThatThrownBy(() -> service.assertWithinQuota(operator, products(5001)))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.hasMessageContaining("0"); .hasMessageContaining("0");
verifyNoInteractions(jdProductMapper); verifyNoInteractions(jdPublishItemMapper);
} }
@Test @Test
void 快照返回占用与上限() { void 快照返回在架数与上限() {
JdPublishQuotaService service = newService(); JdPublishQuotaService service = newService();
AdminUserEntity operator = admin(5L); AdminUserEntity operator = admin(5L);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L))) when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L)); .thenReturn(List.of(5L, 9L));
when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(1234L); when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(1234L);
JdPublishQuotaService.QuotaSnapshot snapshot = service.quotaOf(operator); JdPublishQuotaService.QuotaSnapshot snapshot = service.quotaOf(operator);
assertThat(snapshot.used()).isEqualTo(1234L); assertThat(snapshot.used()).isEqualTo(1234L);
@@ -145,8 +183,9 @@ class JdPublishQuotaServiceTest {
when(adminUserMapper.selectById(5L)).thenReturn(manager); when(adminUserMapper.selectById(5L)).thenReturn(manager);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L))) when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L)); .thenReturn(List.of(5L, 9L));
when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(12L); when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(12L);
assertThatThrownBy(() -> service.assertWithinQuota(employee(9L, 5L), 1)) when(jdPublishItemMapper.countOnShelfInProductIds(List.of(5L, 9L), products(1))).thenReturn(0L);
assertThatThrownBy(() -> service.assertWithinQuota(employee(9L, 5L), products(1)))
.isInstanceOf(BusinessException.class).hasMessageContaining("12"); .isInstanceOf(BusinessException.class).hasMessageContaining("12");
} }
@@ -157,11 +196,22 @@ class JdPublishQuotaServiceTest {
when(adminUserMapper.selectById(5L)).thenReturn(null); when(adminUserMapper.selectById(5L)).thenReturn(null);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 9L))) when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 9L)))
.thenReturn(List.of(9L)); .thenReturn(List.of(9L));
when(jdProductMapper.countByUserIds(List.of(9L))).thenReturn(5000L); when(jdPublishItemMapper.countOnShelfByUserIds(List.of(9L))).thenReturn(5000L);
when(jdPublishItemMapper.countOnShelfInProductIds(List.of(9L), products(1))).thenReturn(0L);
assertThatThrownBy(() -> service.assertWithinQuota(employee, 1)) assertThatThrownBy(() -> service.assertWithinQuota(employee, products(1)))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.hasMessageContaining("5000"); .hasMessageContaining("5000");
verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 9L)); verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 9L));
} }
@Test
void teamUserIds按锚点团队解析_在架面板与标记权限共用() {
JdPublishQuotaService service = newService();
when(adminUserMapper.selectById(5L)).thenReturn(admin(5L));
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L, 10L));
assertThat(service.teamUserIds(employee(9L, 5L))).containsExactly(5L, 9L, 10L);
}
} }
@@ -34,7 +34,7 @@ import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@@ -168,8 +168,8 @@ class JdPublishTaskServiceTest {
.contains("\"targetBrandName\":\"目标品牌B\""); .contains("\"targetBrandName\":\"目标品牌B\"");
// AC-1 明细快照行:每勾选商品一行 // AC-1 明细快照行:每勾选商品一行
verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(any(JdPublishItemEntity.class)); verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(any(JdPublishItemEntity.class));
// AC-8 配额闸:前置且按勾选数计 // AC-8 配额闸:前置且按勾选商品集计(2026-11-25 改在架口径:传集不传数,批内已在架不双计)
verify(jdPublishQuotaService).assertWithinQuota(any(AdminUserEntity.class), eq(2)); verify(jdPublishQuotaService).assertWithinQuota(any(AdminUserEntity.class), eq(List.of(101L, 102L)));
// 铁律 32 第三件:建单响应带页面推送载荷,type 与 SPI QUEUE_TYPE 同值 // 铁律 32 第三件:建单响应带页面推送载荷,type 与 SPI QUEUE_TYPE 同值
assertThat(vo.getQueuePayload()) assertThat(vo.getQueuePayload())
.containsEntry("type", "jd-product-publish-run"); .containsEntry("type", "jd-product-publish-run");
@@ -214,7 +214,7 @@ class JdPublishTaskServiceTest {
assertThatThrownBy(() -> service.createTask(request, null)) assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.hasMessageContaining("请勾选要上架的商品"); .hasMessageContaining("请勾选要上架的商品");
verify(jdPublishQuotaService, never()).assertWithinQuota(any(), anyInt()); verify(jdPublishQuotaService, never()).assertWithinQuota(any(), anyList());
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class)); verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
} }
@@ -302,9 +302,9 @@ class JdPublishTaskServiceTest {
@Test @Test
void 超配额建单被拒且不落任何行() { void 超配额建单被拒且不落任何行() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity()); when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
org.mockito.Mockito.doThrow(new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前已占用 " org.mockito.Mockito.doThrow(new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前在架 "
+ "5000/上限 5000,请清理京东数据库商品或联系管理员调整配额后重试")) + "5000/上限 5000,请先在京麦下架商品并在「在架商品」里标记已下架,或联系管理员调整额度后重试"))
.when(jdPublishQuotaService).assertWithinQuota(any(), eq(2)); .when(jdPublishQuotaService).assertWithinQuota(any(), eq(List.of(101L, 102L)));
assertThatThrownBy(() -> service.createTask(validRequest(7L), null)) assertThatThrownBy(() -> service.createTask(validRequest(7L), null))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.hasMessageContaining("商品上架数量已达上限"); .hasMessageContaining("商品上架数量已达上限");
@@ -0,0 +1,129 @@
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
fetchJdOnShelf,
markJdItemDelisted,
type JdOnShelfItemVo,
type JdOnShelfPageVo,
} from '@/shared/api/types/modules/jd-publish'
import {
clampPageSize,
markButtonLabel,
markDelistedNotice,
onShelfEmptyText,
quotaNearLimit,
quotaReadoutText,
} from './jd-on-shelf'
import { formatDateTime } from '@/shared/utils/datetime'
/**
* 在架商品面板(2026-11-25 客户口径「上限=同时在架商品数,下架 10 个就能再上 10 个」)。
*
* 京麦人工下架系统感知不到,本面板是「标记已下架腾额度」的唯一界面出口;
* 余量读数 used/limit 与建单配额闸同一正本(服务端 JdPublishQuotaService),
* 这里看到的和建单被拦的是同一个数。文案单出口在 jd-on-shelf.ts(判据同读)。
* 团队口径:管理员=本人+名下员工(管理员可替员工标记),员工=所属管理员团队。
*/
const PAGE_SIZE = 20
const open = ref(false)
const loading = ref(false)
const page = ref(1)
const vo = ref<JdOnShelfPageVo | null>(null)
async function load() {
loading.value = true
try {
vo.value = await fetchJdOnShelf(page.value, clampPageSize(PAGE_SIZE))
} catch (error) {
vo.value = null
ElMessage.error(error instanceof Error ? error.message : '在架商品读取失败')
} finally {
loading.value = false
}
}
function togglePanel() {
open.value = !open.value
if (open.value && !vo.value) void load()
}
async function changePage(next: number) {
page.value = next
await load()
}
async function markDelisted(item: JdOnShelfItemVo) {
// 确认框取消走 reject 两臂(与中断任务同口径,不新增 catch 块)
const confirmed = await ElMessageBox.confirm(
`确认把「${item.title || item.productCode || item.productId}」标记为已下架?`
+ '标记后该商品不再占用上架额度;请确认它确已在京麦下架。',
'标记已下架',
{ type: 'warning', confirmButtonText: '标记已下架', cancelButtonText: '先不标记' },
).then(
() => true,
() => false,
)
if (!confirmed) return
try {
await markJdItemDelisted(item.itemId, true)
ElMessage.success(markDelistedNotice(item.productCode))
await load()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '标记失败,请稍后重试')
}
}
</script>
<template>
<section class="on-shelf" v-loading="loading">
<div class="on-shelf-head">
<button class="on-shelf-toggle" type="button" :aria-expanded="open" @click="togglePanel">
{{ open ? '收起在架商品' : '展开在架商品' }}
</button>
<span class="on-shelf-quota">{{ vo ? quotaReadoutText(vo.used, vo.limit, vo.unlimited) : '余量读取中…' }}</span>
<button class="on-shelf-refresh" type="button" :disabled="loading" @click="load()">刷新</button>
</div>
<p v-if="vo && quotaNearLimit(vo.used, vo.limit, vo.unlimited)" class="on-shelf-warn">
额度已满:请先在京麦下架商品,并到本列表「标记已下架」腾出额度后再建单。
</p>
<div v-if="open" class="on-shelf-body">
<div v-if="vo && !vo.items.length" class="on-shelf-empty">{{ onShelfEmptyText(vo.unlimited, vo.used) }}</div>
<div v-for="item in vo?.items ?? []" :key="item.itemId" class="on-shelf-row">
<img v-if="item.imageUrl" class="on-shelf-thumb" :src="item.imageUrl" alt="" loading="lazy" />
<span v-else class="on-shelf-thumb on-shelf-thumb--empty">无图</span>
<span class="on-shelf-info">
<span class="on-shelf-title">{{ item.title || '(无标题快照)' }}</span>
<span class="on-shelf-meta">
<template v-if="item.productCode">编码 {{ item.productCode }} · </template>
<template v-if="item.shopName">来源 {{ item.shopName }} · </template>
上架 {{ item.listedAt ? formatDateTime(item.listedAt) : '-' }}
</span>
</span>
<button class="on-shelf-mark" type="button" @click="markDelisted(item)">{{ markButtonLabel() }}</button>
</div>
<el-pagination v-if="vo && vo.total > PAGE_SIZE" class="on-shelf-pager" layout="prev, pager, next"
:total="vo.total" :page-size="PAGE_SIZE" :current-page="page" @current-change="changePage" />
</div>
</section>
</template>
<style scoped>
.on-shelf { flex-shrink: 0; margin: 0 0 12px; padding: 10px 14px; border: 1px solid #2c3547; border-radius: 8px; background: #20283a; }
.on-shelf-head { display: flex; align-items: center; gap: 12px; }
.on-shelf-toggle, .on-shelf-refresh { padding: 4px 12px; border: 1px solid #3e4a62; border-radius: 6px; background: transparent; color: #c8d2e2; font-size: 12px; cursor: pointer; }
.on-shelf-quota { color: #e6edf7; font-size: 13px; }
.on-shelf-warn { margin: 8px 0 0; color: #e6a23c; font-size: 12px; }
.on-shelf-body { margin-top: 10px; }
.on-shelf-empty { padding: 12px; color: #8b98af; font-size: 12px; text-align: center; }
.on-shelf-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; margin-bottom: 6px; border: 1px solid #2c3547; border-radius: 8px; background: #1a2130; }
.on-shelf-thumb { width: 44px; height: 44px; object-fit: cover; border-radius: 6px; flex-shrink: 0; }
.on-shelf-thumb--empty { display: inline-flex; align-items: center; justify-content: center; color: #5f6c85; font-size: 11px; background: #232c3e; }
.on-shelf-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.on-shelf-title { color: #e6edf7; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.on-shelf-meta { color: #8b98af; font-size: 11px; }
.on-shelf-mark { padding: 4px 12px; border: 1px solid #b45454; border-radius: 6px; background: transparent; color: #e08a8a; font-size: 12px; cursor: pointer; flex-shrink: 0; }
.on-shelf-pager { justify-content: center; margin-top: 8px; }
</style>
@@ -2,6 +2,7 @@
import { computed, onMounted, onUnmounted, ref, watch } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue' import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import JdOnShelfPanel from '@/pages/jd/JdOnShelfPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types' import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import jdLogo from '@/pages/home/assets/jd-logo.png' import jdLogo from '@/pages/home/assets/jd-logo.png'
import { import {
@@ -899,6 +900,7 @@ onUnmounted(() => {
</aside> </aside>
<section class="right-panel"> <section class="right-panel">
<JdOnShelfPanel />
<TaskCenterPanel <TaskCenterPanel
:on-batch-delete="batchDeleteHistory" :on-batch-delete="batchDeleteHistory"
:on-refresh="refreshBoard" :on-refresh="refreshBoard"
+48
View File
@@ -0,0 +1,48 @@
/**
* 在架商品面板的纯函数层(2026-11-25 客户口径「上限=同时在架商品数,下架腾额度」)。
*
* 文案单出口纪律:余量读数、空态、标记按钮文案只在这里拼——面板与判据读同一份,
* 回退(比如把「不限」拼成「0」)当场红。服务端 used/limit 与建单配额闸同一正本,
* 本层只做展示换算,不做任何二次判定。
*/
/** 余量读数:limit≤0(0=不限)显「不限」,绝不显「/0」这种像坏数的数字。 */
export function quotaReadoutText(used: number, limit: number, unlimited: boolean): string {
const safeUsed = Number.isFinite(used) && used > 0 ? Math.floor(used) : 0;
if (unlimited || !Number.isFinite(limit) || limit <= 0) {
return `当前在架 ${safeUsed}/不限`;
}
return `当前在架 ${safeUsed}/${Math.floor(limit)}`;
}
/** 余量是否已到顶(到顶给琥珀提醒句,不硬拦——硬闸在服务端建单口)。 */
export function quotaNearLimit(used: number, limit: number, unlimited: boolean): boolean {
if (unlimited || !Number.isFinite(limit) || limit <= 0) return false;
return used >= limit;
}
/** 面板空态:额度未用满与用满两种口径分开说,别让人以为面板坏了。 */
export function onShelfEmptyText(unlimited: boolean, used: number): string {
if (used > 0) return '本页暂无更多在架商品,可翻页查看';
return unlimited
? '当前没有已上架商品;上架成功后的商品会出现在这里,并计入额度'
: '当前没有已上架商品;额度只在商品上架成功后占用,采集入库不占';
}
/** 标记按钮文案:delisted 态在面板里恒为「未下架」(已下架的行不进在架列表),撤销口用此文案。 */
export function markButtonLabel(): string {
return '标记已下架';
}
/** 分页大小钳制:与后端 MAX_PAGE_SIZE=100 同口径,超了按 100 请求。 */
export function clampPageSize(pageSize: number): number {
if (!Number.isFinite(pageSize) || pageSize <= 0) return 20;
return Math.min(Math.floor(pageSize), 100);
}
/** 标记成功后的回执文案(点名动作与后果,不写「操作成功」这种没有信息量的话)。
* ⚠ 本窗不承诺「撤销标记」入口——已下架行不进在架列表,误标撤销口记 BACKLOG 欠账。 */
export function markDelistedNotice(productCode?: string): string {
const who = productCode ? `商品 ${productCode} ` : '';
return `已标记${who}下架,额度已腾出;请确认该商品确已在京麦下架`;
}
+4
View File
@@ -246,6 +246,10 @@ export const API_ENDPOINTS = {
progress: '/api/jd-publish/tasks/{taskId}/progress', progress: '/api/jd-publish/tasks/{taskId}/progress',
/** 删除任务(连带清理该任务的发布明细快照行) */ /** 删除任务(连带清理该任务的发布明细快照行) */
deleteTask: '/api/jd-publish/tasks/{taskId}', deleteTask: '/api/jd-publish/tasks/{taskId}',
/** 在架商品分页+额度余量(2026-11-25 客户口径「上限=同时在架商品数」) */
onShelf: '/api/jd-publish/on-shelf',
/** 标记/取消标记已下架(按商品整组腾额度) */
markDelisted: '/api/jd-publish/items/{itemId}/delisted',
}, },
userSecret: { userSecret: {
bundle: '/api/user-secrets', bundle: '/api/user-secrets',
@@ -291,3 +291,49 @@ export function interruptJdPublishTask(taskId: number) {
), ),
); );
} }
// ---------------------------------------------------------------------------
// 在架商品面板(2026-11-25 客户口径「上限=同时在架商品数,下架 10 个就能再上 10 个」)。
// 余量读数 used/limit 与建单配额闸同一正本(服务端 JdPublishQuotaService),
// 面板看到的和建单被拦的是同一个数;京麦人工下架后在本面板「标记已下架」即腾额度。
// ---------------------------------------------------------------------------
export interface JdOnShelfItemVo {
itemId: number;
productId: number;
productCode?: string;
title?: string;
shopName?: string;
jdWareId?: string;
imageUrl?: string;
listedAt?: string;
operatorUserId?: number;
}
export interface JdOnShelfPageVo {
used: number;
limit: number;
unlimited: boolean;
total: number;
items: JdOnShelfItemVo[];
}
/** 在架商品分页(团队口径:管理员含名下员工,员工=所属管理员团队)。 */
export function fetchJdOnShelf(page: number, pageSize: number) {
return unwrapJavaResponse(
get<JavaApiResponse<JdOnShelfPageVo>>(
buildJavaUrl(API_ENDPOINTS.jdPublish.onShelf),
{ params: { user_id: getCurrentUserId(), page, page_size: pageSize } },
),
);
}
/** 标记/取消标记已下架:服务端按商品整组回写(同商品跨任务成功行一起落/一起回拨)。 */
export function markJdItemDelisted(itemId: number, delisted: boolean) {
return unwrapJavaResponse(
post<JavaApiResponse<null>, { delisted: boolean }>(
buildJavaUrl(API_ENDPOINTS.jdPublish.markDelisted.replace('{itemId}', String(itemId))),
{ delisted },
),
);
}
@@ -118,7 +118,11 @@ const BASELINE = {
// 原文只进 console;「读不到权限」不等于「没权限」,把有权限的人锁在门外比放进去后被 // 原文只进 console;「读不到权限」不等于「没权限」,把有权限的人锁在门外比放进去后被
// 服务端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。非静默: // 服务端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。非静默:
// 首条语句是状态写入、不是 console.*,silent 一格没涨、perFile 无新增条目,只进 blocks。 // 首条语句是状态写入、不是 console.*,silent 一格没涨、perFile 无新增条目,只进 blocks。
blocks: 336, // 338 = 336 + 2(2026-11-25 京东上架额度改口径「在架商品面板」):JdOnShelfPanel.vue 的
// load(在架清单读取失败 → ElMessage.error 报原文,面板清空不显旧数)与 markDelisted
// (标记失败 → ElMessage.error 透出服务端原文,跨团队 403 等;确认框取消走 reject 两臂
// 不新增 catch)各一支,都有用户可见出口,silent 一格没涨、perFile 无新增条目,只进 blocks。
blocks: 338,
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处 // 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进 // 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动, // useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
+4 -1
View File
@@ -349,7 +349,10 @@ test('test_endpoints_frozen_snapshot', () => {
"history": "/api/jd-publish/history", "history": "/api/jd-publish/history",
"progressBatch": "/api/jd-publish/tasks/progress/batch", "progressBatch": "/api/jd-publish/tasks/progress/batch",
"progress": "/api/jd-publish/tasks/{taskId}/progress", "progress": "/api/jd-publish/tasks/{taskId}/progress",
"deleteTask": "/api/jd-publish/tasks/{taskId}" "deleteTask": "/api/jd-publish/tasks/{taskId}",
// 2026-11-25 额度改口径:在架清单+标记已下架腾额度(JdOnShelfPanel 唯一落点)。
"onShelf": "/api/jd-publish/on-shelf",
"markDelisted": "/api/jd-publish/items/{itemId}/delisted"
}, },
"userSecret": { "userSecret": {
"bundle": "/api/user-secrets", "bundle": "/api/user-secrets",
+99
View File
@@ -0,0 +1,99 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import {
clampPageSize,
markButtonLabel,
markDelistedNotice,
onShelfEmptyText,
quotaNearLimit,
quotaReadoutText,
} from '../src/pages/jd/jd-on-shelf.ts'
/**
* 在架商品面板纯函数与接线绊线(2026-11-25 客户口径「上限=同时在架商品数,
* 下架 10 个就能再上 10 个换着卖」)。
*
* 绊线盯的是「安静地不做」类回退:面板绕过 api 模块裸拼 URL(落点台账失效)、
* 文案在组件里硬拼(单出口失效)、JdPublishTab 不挂面板(功能整面失踪)——
* 行为测试全绿也拦不住,只有源码绊线拦得住。
*/
const ROOT = process.cwd()
function read(relativePath: string, what: string): string {
const path = join(ROOT, relativePath)
assert.ok(existsSync(path), `${what} 尚未落地:${path}`)
return readFileSync(path, 'utf8')
}
// ---------------------------------------------------------- 纯函数:余量文案
test('余量读数:正常档显「在架 X/Y」,不限档绝不显「/0」', () => {
assert.equal(quotaReadoutText(120, 5000, false), '当前在架 120/5000')
assert.equal(quotaReadoutText(120, 0, true), '当前在架 120/不限')
// limit≤0 但 unlimited 没带(防御:服务端两键同值,坏一个也不出「/0」坏数)
assert.equal(quotaReadoutText(3, 0, false), '当前在架 3/不限')
assert.equal(quotaReadoutText(Number.NaN, 5000, false), '当前在架 0/5000')
assert.equal(quotaReadoutText(12.7, 5000.9, false), '当前在架 12/5000')
})
test('到顶判据:used≥limit 才提醒;不限档永不提醒', () => {
assert.equal(quotaNearLimit(5000, 5000, false), true)
assert.equal(quotaNearLimit(5001, 5000, false), true)
assert.equal(quotaNearLimit(4999, 5000, false), false)
assert.equal(quotaNearLimit(999999, 0, true), false)
})
test('空态文案:未占用点名「采集入库不占额度」,翻页态不冒充空账', () => {
assert.match(onShelfEmptyText(false, 0), /采集入库不占/)
assert.match(onShelfEmptyText(true, 0), /上架成功后.*计入额度/s)
assert.equal(onShelfEmptyText(false, 25), '本页暂无更多在架商品,可翻页查看')
})
test('分页钳制与服务端 MAX_PAGE_SIZE=100 同口径', () => {
assert.equal(clampPageSize(9999), 100)
assert.equal(clampPageSize(20), 20)
assert.equal(clampPageSize(0), 20)
assert.equal(clampPageSize(-1), 20)
})
test('标记回执点名商品编码与确认义务,不写「操作成功」空话', () => {
assert.match(markDelistedNotice('100365361600'), /商品 100365361600/)
assert.match(markDelistedNotice('100365361600'), /额度已腾出/)
assert.match(markDelistedNotice(), /已标记下架,额度已腾出/)
assert.equal(markButtonLabel(), '标记已下架')
})
// ---------------------------------------------------------- 源码绊线:接线与单出口
test('绊线:在架端点只在 endpoints.ts 登记一处,面板必须走 api 模块出口', () => {
const endpoints = read('src/shared/api/endpoints.ts', '端点表')
assert.match(endpoints, /onShelf: '\/api\/jd-publish\/on-shelf'/)
assert.match(endpoints, /markDelisted: '\/api\/jd-publish\/items\/\{itemId\}\/delisted'/)
const apiModule = read('src/shared/api/types/modules/jd-publish.ts', '上架 api 模块')
assert.match(apiModule, /API_ENDPOINTS\.jdPublish\.onShelf/)
assert.match(apiModule, /API_ENDPOINTS\.jdPublish\.markDelisted/)
const panel = read('src/pages/jd/JdOnShelfPanel.vue', '在架面板')
assert.doesNotMatch(panel, /\/api\/jd-publish/, '面板不得裸拼后端 URL(落点必须走 api 模块)')
assert.match(panel, /fetchJdOnShelf/)
assert.match(panel, /markJdItemDelisted/)
})
test('绊线:面板文案单出口——组件不硬拼「当前在架」,判据与界面读同一份', () => {
const panel = read('src/pages/jd/JdOnShelfPanel.vue', '在架面板')
assert.doesNotMatch(panel, /当前在架/, '余量文案必须经 quotaReadoutText 单出口')
assert.match(panel, /quotaReadoutText/)
assert.match(panel, /onShelfEmptyText/)
assert.match(panel, /markDelistedNotice/)
})
test('绊线:JdPublishTab 必须挂上在架面板(功能整面失踪类回退)', () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '上架页')
assert.match(tab, /import JdOnShelfPanel from '@\/pages\/jd\/JdOnShelfPanel\.vue'/)
assert.match(tab, /<JdOnShelfPanel \/>/)
})
@@ -0,0 +1,140 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import JdOnShelfPanel from '@/pages/jd/JdOnShelfPanel.vue'
/**
* 在架商品面板 mount 判据(2026-11-25 额度改口径):余量读数、展开取数、
* 标记已下架走确认框两臂+成功回执+重取列表。api 模块整体 mock——
* 面板必须经 fetchJdOnShelf/markJdItemDelisted 出口(裸 URL 回退当场红)。
*/
const api = vi.hoisted(() => ({
onShelf: vi.fn(),
markDelisted: vi.fn(),
confirm: vi.fn(),
success: vi.fn(),
error: vi.fn(),
}))
vi.mock('@/shared/api/types/modules/jd-publish', () => ({
fetchJdOnShelf: api.onShelf,
markJdItemDelisted: api.markDelisted,
}))
vi.mock('element-plus', async (importOriginal) => ({
...await importOriginal<typeof import('element-plus')>(),
ElMessage: { success: api.success, error: api.error },
ElMessageBox: { confirm: api.confirm },
}))
function pageVo(overrides: Record<string, unknown> = {}) {
return {
used: 2, limit: 5000, unlimited: false, total: 2,
items: [
{ itemId: 100, productId: 7, productCode: '100365361600', title: '收纳盒A', shopName: '家居日用数据库店', listedAt: '2026-11-23 20:30:04' },
{ itemId: 101, productId: 8, productCode: '100365355826', title: '纸巾盒B', shopName: '家居日用数据库店', listedAt: '2026-11-23 20:21:29' },
],
...overrides,
}
}
let wrapper: VueWrapper | undefined
beforeEach(() => {
vi.clearAllMocks()
wrapper?.unmount()
wrapper = undefined
})
async function mountPanel() {
// 替身注册法与 jd-publish-dispatch.mount.test.ts 同族:分页替身+loading 指令空实现
wrapper = mount(JdOnShelfPanel, {
global: {
stubs: { ElPagination: { emits: ['current-change'], template: '<div />' } },
directives: { loading: () => undefined },
},
})
await flushPromises()
return wrapper
}
it('默认收起不取数;展开后拉第一页并显余量读数', async () => {
api.onShelf.mockResolvedValue(pageVo())
const w = await mountPanel()
expect(api.onShelf).not.toHaveBeenCalled()
await w.get('.on-shelf-toggle').trigger('click')
await flushPromises()
expect(api.onShelf).toHaveBeenCalledTimes(1)
expect(api.onShelf.mock.calls[0][0]).toBe(1)
expect(api.onShelf.mock.calls[0][1]).toBe(20)
expect(w.text()).toContain('当前在架 2/5000')
expect(w.findAll('.on-shelf-row')).toHaveLength(2)
expect(w.text()).toContain('收纳盒A')
})
it('不限档显「不限」,绝不显「/0」坏数', async () => {
api.onShelf.mockResolvedValue(pageVo({ used: 0, limit: 0, unlimited: true, total: 0, items: [] }))
const w = await mountPanel()
await w.get('.on-shelf-toggle').trigger('click')
await flushPromises()
expect(w.text()).toContain('当前在架 0/不限')
expect(w.text()).not.toContain('/0')
expect(w.text()).toContain('上架成功后的商品会出现在这里')
})
it('额度到顶出琥珀提醒句', async () => {
api.onShelf.mockResolvedValue(pageVo({ used: 5000, total: 5000 }))
const w = await mountPanel()
await w.get('.on-shelf-toggle').trigger('click')
await flushPromises()
expect(w.find('.on-shelf-warn').text()).toContain('额度已满')
expect(w.find('.on-shelf-warn').text()).toContain('标记已下架')
})
it('标记已下架:确认→调 api(itemId,true)→回执点名编码→重取列表', async () => {
api.onShelf.mockResolvedValue(pageVo())
api.confirm.mockResolvedValue(true)
api.markDelisted.mockResolvedValue(null)
const w = await mountPanel()
await w.get('.on-shelf-toggle').trigger('click')
await flushPromises()
await w.findAll('.on-shelf-mark')[0].trigger('click')
await flushPromises()
expect(api.markDelisted).toHaveBeenCalledWith(100, true)
expect(api.success).toHaveBeenCalledTimes(1)
expect(String(api.success.mock.calls[0][0])).toContain('100365361600')
// 标记成功后重取(腾额度读数当场回跳)
expect(api.onShelf).toHaveBeenCalledTimes(2)
})
it('确认框取消(reject 臂)不发起标记', async () => {
api.onShelf.mockResolvedValue(pageVo())
api.confirm.mockRejectedValue('cancel')
const w = await mountPanel()
await w.get('.on-shelf-toggle').trigger('click')
await flushPromises()
await w.findAll('.on-shelf-mark')[1].trigger('click')
await flushPromises()
expect(api.markDelisted).not.toHaveBeenCalled()
expect(api.onShelf).toHaveBeenCalledTimes(1)
})
it('标记失败透出服务端原文(跨团队 403 等)', async () => {
api.onShelf.mockResolvedValue(pageVo())
api.confirm.mockResolvedValue(true)
api.markDelisted.mockRejectedValue(new Error('只能标记本团队(管理员及其名下员工)的上架商品'))
const w = await mountPanel()
await w.get('.on-shelf-toggle').trigger('click')
await flushPromises()
await w.findAll('.on-shelf-mark')[0].trigger('click')
await flushPromises()
expect(api.error).toHaveBeenCalledTimes(1)
expect(String(api.error.mock.calls[0][0])).toContain('本团队')
})