From 934091b3d5ef07ea3d20f2899f180616f3d18476 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com>
Date: Wed, 25 Nov 2026 22:35:43 +0800
Subject: [PATCH] =?UTF-8?q?feat(jd=E9=A2=9D=E5=BA=A6):=20=E4=B8=8A?=
=?UTF-8?q?=E6=9E=B6=E9=A2=9D=E5=BA=A6=E6=94=B9=E6=8C=89=E5=9C=A8=E6=9E=B6?=
=?UTF-8?q?=E5=95=86=E5=93=81=E6=95=B0=E8=AE=A1=EF=BC=8B=E7=AE=A1=E7=90=86?=
=?UTF-8?q?=E5=91=98=E5=90=91=E5=91=98=E5=B7=A5=E5=88=86=E9=85=8D=E9=A2=9D?=
=?UTF-8?q?=E5=BA=A6=E9=97=B8=EF=BC=8B=E5=9C=A8=E6=9E=B6=E5=95=86=E5=93=81?=
=?UTF-8?q?=E9=9D=A2=E6=9D=BF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
客户口径(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 点名。
---
admin-frontend-vue/src/api/user-jd-quota.ts | 26 +++
.../src/pages/account/EditUserDialog.vue | 46 +++-
.../src/pages/account/UsersPage.vue | 9 +-
.../src/pages/account/user-edit-model.ts | 44 +++-
.../tests/baselines/source-pin-ledger.json | 4 +-
.../tests/jd-publish-quota-edit.test.ts | 39 +++-
.../tests/platform-account-pages.test.ts | 6 +-
.../admin/controller/AdminUserController.java | 12 +
.../admin/model/vo/AdminJdQuotaVo.java | 22 ++
.../service/AdminJdQuotaViewService.java | 51 +++++
.../admin/service/AdminUserService.java | 60 ++++-
.../jd/controller/JdPublishController.java | 39 ++++
.../modules/jd/mapper/JdProductMapper.java | 9 +-
.../jd/mapper/JdPublishItemMapper.java | 20 ++
.../jd/model/entity/JdPublishItemEntity.java | 2 +
.../jd/model/vo/JdPublishOnShelfVo.java | 64 ++++++
.../jd/service/JdPublishOnShelfService.java | 122 ++++++++++
.../jd/service/JdPublishQuotaService.java | 80 ++++---
.../jd/service/JdPublishTaskService.java | 6 +-
.../db/V216__jd_publish_item_delisted.sql | 23 ++
.../db/V217__users_normal_quota_reset.sql | 28 +++
.../resources/mapper/jd/JdProductMapper.xml | 13 +-
.../mapper/jd/JdPublishItemMapper.xml | 46 ++++
.../aiimage/MigratedSqlEquivalenceTest.java | 18 +-
.../aiimage/SqlLayeringConventionTest.java | 7 +-
.../common/api/PageDefaultsLedgerTest.java | 16 +-
.../RequestSuppliedIdentityOutletTest.java | 4 +-
...AdminUserServiceCompanySuperAdminTest.java | 102 ++++++++-
.../modules/jd/JdSchemaContractTest.java | 22 ++
.../jd/mapper/JdPublishOnShelfSqlTest.java | 80 +++++++
.../service/JdPublishOnShelfServiceTest.java | 213 ++++++++++++++++++
.../jd/service/JdPublishQuotaServiceTest.java | 102 ++++++---
.../jd/service/JdPublishTaskServiceTest.java | 14 +-
frontend-vue/src/pages/jd/JdOnShelfPanel.vue | 129 +++++++++++
frontend-vue/src/pages/jd/JdPublishTab.vue | 2 +
frontend-vue/src/pages/jd/jd-on-shelf.ts | 48 ++++
frontend-vue/src/shared/api/endpoints.ts | 4 +
.../shared/api/types/modules/jd-publish.ts | 46 ++++
.../tests/catch-silence-ratchet.test.ts | 6 +-
frontend-vue/tests/endpoints.test.ts | 5 +-
frontend-vue/tests/jd-on-shelf.test.ts | 99 ++++++++
.../mount/jd-on-shelf-panel.mount.test.ts | 140 ++++++++++++
42 files changed, 1709 insertions(+), 119 deletions(-)
create mode 100644 admin-frontend-vue/src/api/user-jd-quota.ts
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/admin/model/vo/AdminJdQuotaVo.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminJdQuotaViewService.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdPublishOnShelfVo.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdPublishOnShelfService.java
create mode 100644 backend-java/src/main/resources/db/V216__jd_publish_item_delisted.sql
create mode 100644 backend-java/src/main/resources/db/V217__users_normal_quota_reset.sql
create mode 100644 backend-java/src/test/java/com/nanri/aiimage/modules/jd/mapper/JdPublishOnShelfSqlTest.java
create mode 100644 backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishOnShelfServiceTest.java
create mode 100644 frontend-vue/src/pages/jd/JdOnShelfPanel.vue
create mode 100644 frontend-vue/src/pages/jd/jd-on-shelf.ts
create mode 100644 frontend-vue/tests/jd-on-shelf.test.ts
create mode 100644 frontend-vue/tests/mount/jd-on-shelf-panel.mount.test.ts
diff --git a/admin-frontend-vue/src/api/user-jd-quota.ts b/admin-frontend-vue/src/api/user-jd-quota.ts
new file mode 100644
index 000000000..d4e0a51fe
--- /dev/null
+++ b/admin-frontend-vue/src/api/user-jd-quota.ts
@@ -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 {
+ const { data } = await http.get(`${USER_JD_QUOTA_ENDPOINT}/${uid}/jd-quota`)
+ const raw = unwrap | null>(data) ?? {}
+ return {
+ used: Number(raw.used ?? 0),
+ limit: Number(raw.limit ?? 0),
+ unlimited: raw.unlimited === true,
+ }
+}
\ No newline at end of file
diff --git a/admin-frontend-vue/src/pages/account/EditUserDialog.vue b/admin-frontend-vue/src/pages/account/EditUserDialog.vue
index 4dda14ecf..d8479852e 100644
--- a/admin-frontend-vue/src/pages/account/EditUserDialog.vue
+++ b/admin-frontend-vue/src/pages/account/EditUserDialog.vue
@@ -3,8 +3,9 @@ import { computed, reactive, ref, watch } from 'vue'
import type { AdminUser } from '@/types/admin'
import type { PlatformTabId } from '@/config/platform-scope'
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 { fetchUserJdQuota, type UserJdQuotaSnapshot } from '@/api/user-jd-quota'
import { loadUserMenuAuth } from './user-menu-auth-api'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { actionableErrorText } from '@/components/admin-feedback'
@@ -33,6 +34,12 @@ const includeQuota = computed(() => props.platform === 'jd')
* 与后端 AdminUserService「无权修改京东上架额度」403 闸同口径,前端不再给出改了必被拒的输入框)。
*/
const quotaWritable = computed(() => includeQuota.value && props.operatorCanWriteQuota === true)
+/** 额度 0 的语义按「改完之后」的目标档给标签(2026-11-25):公司超管目标的角色单选隐藏,
+ * 取原角色;其余跟单选当前值。 */
+const quotaRoleForLabel = computed(() => (targetIsCompanySuperAdmin.value ? form.originalRole : form.role))
+/** 弹窗里的「当前已用」快照:与建单配额闸同一正本(团队在架商品数)。读不到不阻塞保存(只显示失败句)。 */
+const quotaUsed = ref(null)
+const quotaUsedFailed = ref(false)
/** 公司超管目标的角色单选是隐藏的(改完仍是 company_super_admin),到期时间照旧可改;
* 管理员改成普通账号时这一项消失,保存按「清空」下发(见 user-edit-model 的 roleAfter)。 */
const expiryEditable = computed(() =>
@@ -56,10 +63,24 @@ watch(
errors.jdPublishQuota = undefined
errors.password = undefined
authReady.value = false
+ quotaUsed.value = null
+ quotaUsedFailed.value = false
void refreshAuth()
+ if (quotaWritable.value) void refreshQuota()
},
)
+/** 拉「当前在架 X/上限 Y」:失败只在本行显示一句失败话,不挡保存(读数非保存前提)。 */
+async function refreshQuota(): Promise {
+ if (!props.user) return
+ try {
+ quotaUsed.value = await fetchUserJdQuota(props.user.id)
+ } catch {
+ // 读不到不等于改不了:额度编辑仍照常,界面给一句「读取失败」即可(不静默——用户在行下看得见)。
+ quotaUsedFailed.value = true
+ }
+}
+
async function refreshAuth(): Promise {
if (!props.user) return
loadingAuth.value = true
@@ -145,8 +166,14 @@ async function save(): Promise {
style="width: 240px"
/>
-
-
+
+
+
+
+ {{ quotaUsageText(quotaUsed.used, quotaUsed.limit, quotaUsed.unlimited) }}
+
+
当前已用读取失败(不影响额度编辑)
+
@@ -186,4 +213,17 @@ async function save(): Promise {
.auth-loading-error {
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);
+}
diff --git a/admin-frontend-vue/src/pages/account/UsersPage.vue b/admin-frontend-vue/src/pages/account/UsersPage.vue
index 825044bac..b16397fa7 100644
--- a/admin-frontend-vue/src/pages/account/UsersPage.vue
+++ b/admin-frontend-vue/src/pages/account/UsersPage.vue
@@ -19,7 +19,7 @@ import { totalPageCount } from './user-pagination'
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
import { disableBlockReason, disableConfirmMessage, disabledBadgeText } from './user-disable-model'
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 CreateUserDialog from './CreateUserDialog.vue'
import EditUserDialog from './EditUserDialog.vue'
@@ -78,10 +78,11 @@ function editableOf(row: AdminUser): boolean {
return editableBy(row.role, operatorRole.value)
}
-/** 上架上限列文案(仅京东侧渲染该列):null=旧数据未配('-'),0=不限,其余为具体条数。 */
+/** 上架上限列文案(仅京东侧渲染):null=旧数据未配('-'),0=按档「不限」/「未分配」,其余为具体条数。
+ * 2026-11-25 口径:普通账号的 0 是「未分配」(只作管理员分配账,不单独拦人),管理员档的 0 才是「不限」。
+ * 展示规则单出口在 user-edit-model(判据与界面读同一份)。 */
function quotaCellText(row: AdminUser): string {
- if (row.jdPublishQuota == null) return '-'
- return row.jdPublishQuota === 0 ? '不限' : String(row.jdPublishQuota)
+ return quotaCellTextOf(row)
}
/** 列表请求参数 = 用户填的筛选态 + 当前公司 + 当前平台。公司/平台值每次现取、不写进 filters:
diff --git a/admin-frontend-vue/src/pages/account/user-edit-model.ts b/admin-frontend-vue/src/pages/account/user-edit-model.ts
index ec69bfb72..0286b502e 100644
--- a/admin-frontend-vue/src/pages/account/user-edit-model.ts
+++ b/admin-frontend-vue/src/pages/account/user-edit-model.ts
@@ -3,6 +3,9 @@ import type { AdminUser } from '../../types/admin'
import type { PlatformTabId } from '../../config/platform-scope.ts'
import { CREATE_PASSWORD_MIN_LEN, mayCarryOwnExpiry } from './user-create-model.ts'
+/** 管理员档缺省额度(与后端 AdminUserService.JD_QUOTA_DEFAULT 同值)。 */
+const JD_QUOTA_DEFAULT = 5000
+
/** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */
export type EditUserRole = 'normal' | 'admin'
@@ -47,6 +50,36 @@ export function editRoleOf(role: string | null | undefined): EditUserRole {
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 {
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
}
-/** 从用户行回填编辑表单:用户名只读、密码留空、columnIds 待授权加载填充。 */
+/** 从用户行回填编辑表单:用户名只读、密码留空、columnIds 待授权加载填充。
+ * 额度缺省按目标档(2026-11-25):管理员档缺省给默认上限 5000,普通账号缺省 0=未分配
+ * (V217 已把存量的普通账号 5000 清成 0;这里再给 5000 会让「打开就保存」凭空分配额度)。 */
export function fillEditUserForm(user: AdminUser): EditUserForm {
const role = typeof user.role === 'string' ? user.role.trim() : ''
return {
uid: user.id,
- jdPublishQuota: user.jdPublishQuota ?? 5000,
+ jdPublishQuota: user.jdPublishQuota ?? (quotaUnlimitedRole(role) ? JD_QUOTA_DEFAULT : 0),
username: user.username || '',
password: '',
role: editRoleOf(role),
@@ -113,7 +148,6 @@ export function validateEditUserForm(
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符,留空则不修改`
}
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)) {
errors.jdPublishQuota = '请输入 0 至 2147483647 的整数'
}
@@ -153,8 +187,8 @@ export function toEditUserUpdateRequest(form: EditUserForm, options: EditUserFor
if (keepsRole) {
request.role = nextRole
}
- if (options.includeQuota !== false && options.canWriteQuota !== false &&
- (roleAfter === 'admin' || roleAfter === 'company_super_admin')) {
+ if (options.includeQuota !== false && options.canWriteQuota !== false) {
+ // 2026-11-25 口径:普通账号也可设额度(员工额度=管理员向员工的分配账),不再按目标档收口。
request.jdPublishQuota = form.jdPublishQuota
}
const password = form.password || ''
diff --git a/admin-frontend-vue/tests/baselines/source-pin-ledger.json b/admin-frontend-vue/tests/baselines/source-pin-ledger.json
index f2b799941..a59b4bf2b 100644
--- a/admin-frontend-vue/tests/baselines/source-pin-ledger.json
+++ b/admin-frontend-vue/tests/baselines/source-pin-ledger.json
@@ -2,7 +2,7 @@
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
"totals": {
"files": 265,
- "cases": 1867,
+ "cases": 1868,
"pins": 463,
"reads": 665
},
@@ -333,7 +333,7 @@
"reads": 0
},
"jd-publish-quota-edit.test.ts": {
- "cases": 2,
+ "cases": 3,
"pins": 0,
"reads": 0
},
diff --git a/admin-frontend-vue/tests/jd-publish-quota-edit.test.ts b/admin-frontend-vue/tests/jd-publish-quota-edit.test.ts
index 7039b827f..a95035f1c 100644
--- a/admin-frontend-vue/tests/jd-publish-quota-edit.test.ts
+++ b/admin-frontend-vue/tests/jd-publish-quota-edit.test.ts
@@ -1,8 +1,15 @@
import test from 'node:test'
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 })
assert.equal(form.jdPublishQuota, 0)
assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, 0)
@@ -10,8 +17,34 @@ test('京东上架额度回填、校验和按管理员提交', () => {
assert.equal(validateEditUserForm(form).valid, false)
form.jdPublishQuota = 1.5
assert.equal(validateEditUserForm(form).valid, false)
+ form.jdPublishQuota = 1200
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 客户口径「配额只有公司管理员才可以改,管理员能配合就大家都乱改了」:
diff --git a/admin-frontend-vue/tests/platform-account-pages.test.ts b/admin-frontend-vue/tests/platform-account-pages.test.ts
index 08bca93a8..121d2ea79 100644
--- a/admin-frontend-vue/tests/platform-account-pages.test.ts
+++ b/admin-frontend-vue/tests/platform-account-pages.test.ts
@@ -101,8 +101,10 @@ test('CompaniesPage:公司列表带平台、切平台重取数、编辑弹窗
test('EditUserDialog:上架上限仅京东侧且操作者有额度写权才显示/提交;所属平台不设手选', () => {
const dialog = readSource('src/pages/account/EditUserDialog.vue')
- assert.match(dialog, /v-if="quotaWritable && \(targetIsCompanySuperAdmin \|\| form\.role === 'admin'\)"/,
- 'quota 项必须走 quotaWritable(京东侧+操作者额度写权)——只按目标角色判断,普通管理员会对着改了必被后端 403 的输入框(2026-11-24 客户口径)')
+ assert.match(dialog, /v-if="quotaWritable"/,
+ 'quota 项必须走 quotaWritable(京东侧+操作者额度写权)——2026-11-25 口径:普通账号也可分配额度'
+ + '(员工额度=管理员向员工的分配账,Σ 分配账的输入),不再按目标档收口;operatorCanWriteQuota 一档'
+ + '仍不可省(普通管理员对着改了必被后端 403 的输入框是 2026-11-24 客户口径)')
assert.match(dialog, /const quotaWritable = computed\(\(\) => includeQuota\.value && props\.operatorCanWriteQuota === true\)/,
'quotaWritable 必须同时要求京东侧与操作者写权档;prop 缺省按无权重(fail-closed,镜像后端「无权修改京东上架额度」闸)')
assert.match(dialog, /submitEditUser\(form, options\)/,
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/admin/controller/AdminUserController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/controller/AdminUserController.java
index c12f0445c..4c6d8417a 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/admin/controller/AdminUserController.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/controller/AdminUserController.java
@@ -4,7 +4,9 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
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.vo.AdminJdQuotaVo;
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.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
@@ -30,6 +32,7 @@ public class AdminUserController {
private final AdminAuthSupport adminAuthSupport;
private final AdminUserService adminUserService;
+ private final AdminJdQuotaViewService jdQuotaViewService;
@GetMapping("/users")
@Operation(summary = "分页查询用户列表")
@@ -78,4 +81,13 @@ public class AdminUserController {
adminUserService.deleteUser(currentUser, uid);
return ApiResponse.success("删除成功", null);
}
+
+ @GetMapping("/user/{uid}/jd-quota")
+ @Operation(summary = "京东上架额度快照", description = "2026-11-25 口径改造:编辑弹窗展示「当前在架 X/上限 Y」,"
+ + "读数与建单配额闸同一正本(JdPublishQuotaService.quotaOf)。权限照额度编辑同档。")
+ public ApiResponse jdQuota(HttpServletRequest request,
+ @PathVariable Long uid) {
+ AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
+ return ApiResponse.success(jdQuotaViewService.snapshot(currentUser, uid));
+ }
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/admin/model/vo/AdminJdQuotaVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/model/vo/AdminJdQuotaVo.java
new file mode 100644
index 000000000..512076b11
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/model/vo/AdminJdQuotaVo.java
@@ -0,0 +1,22 @@
+package com.nanri.aiimage.modules.admin.model.vo;
+
+import lombok.Data;
+
+/**
+ * 京东上架额度快照(2026-11-25 客户口径改造):后管编辑弹窗展示「当前在架 X/上限 Y」。
+ *
+ * 读数与建单配额闸同一正本({@code JdPublishQuotaService.quotaOf})——弹窗看到的
+ * 和建单被拦的是同一个数,杜绝「界面说没满、建单说满了」的两套账。
+ */
+@Data
+public class AdminJdQuotaVo {
+
+ /** 团队在架商品数(发布成功且未标记下架,去重商品口径)。 */
+ private long used;
+
+ /** 配额上限(≤0=不限)。 */
+ private long limit;
+
+ /** 上限是否不限。 */
+ private boolean unlimited;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminJdQuotaViewService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminJdQuotaViewService.java
new file mode 100644
index 000000000..9179d710a
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminJdQuotaViewService.java
@@ -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」。
+ *
+ * 独立小服务而不是塞进 {@link AdminUserService}:后者被十几支测试手工 new,
+ * 加一个构造参会涟漪一片;本视图只依赖 AdminUserMapper+配额原语,读侧单点。
+ * 读数与建单配额闸同一正本({@code JdPublishQuotaService.quotaOf}),弹窗看到的
+ * 和建单被拦的是同一个数。
+ */
+@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;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java
index 92f93abfd..e75801fca 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java
@@ -41,6 +41,9 @@ public class AdminUserService {
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 定案):它的停用一律由上级账号级联决定。 */
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)) {
throw new BusinessException(403, "无权修改京东上架额度");
}
- if (!"admin".equals(roleAfter) && !"company_super_admin".equals(roleAfter)) {
- throw new BusinessException(400, "只能为管理员设置京东上架额度");
- }
if (request.getJdPublishQuota() < 0) {
throw new BusinessException(400, "京东上架额度不能为负数");
}
+ // 2026-11-25 分配闸:普通账号也可设额度(额度=管理员向员工的分配账,
+ // 0=未分配:不计入 Σ、不单独拦人,实际拦截仍看团队在架总和 ≤ 主管额度)。
+ // 旧 400「只能为管理员设置京东上架额度」随客户口径「管理员下的普通员工
+ // 总和也不能超过这个上限」废止——没有员工额度数字,总和账无从算起。
+ assertQuotaAllocation(target, roleAfter, request.getJdPublishQuota());
}
// 移人先于写库:先确认目标公司可用,再确认 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 subordinates = adminUserMapper.selectList(
+ new LambdaQueryWrapper()
+ .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) 菜单:
* 把勾选 id 按类型拆分后分区整树替换(internal 类型不在树里,出现即按无效处理)。
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java
index 3291b4e17..044fa9eec 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java
@@ -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.JdPublishHistoryVo;
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.JdPublishTaskBatchVo;
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.JdPublishFillAiService;
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.JdPublishTaskService;
import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService;
@@ -71,6 +73,7 @@ public class JdPublishController {
private final JdSizeChartAiService sizeChartAiService;
private final JdPublishFillAiService fillAiService;
private final JdPublishPermissionSupport publishPermissionSupport;
+ private final JdPublishOnShelfService onShelfService;
private final JdCategoryScopeService jdCategoryScopeService;
@PostMapping({"/tasks", "/tasks/target-brand"})
@@ -266,4 +269,40 @@ public class JdPublishController {
boardService.deleteTask(taskId, userId);
return ApiResponse.success(null);
}
+
+ // ------------------------------------------------------------------
+ // 2026-11-25 客户口径「上限=同时在架商品数,下架腾额度」:在架面板+人工标记下架。
+ // 京麦人工下架系统感知不到,标记通道按商品整组回写 delisted_at(V216);
+ // 读数与建单配额闸同一正本(JdPublishQuotaService),面板与拦截永远对得上。
+ // ------------------------------------------------------------------
+
+ @GetMapping("/on-shelf")
+ @Operation(summary = "在架商品分页+额度余量", description = "团队(管理员+名下员工)当前在架商品"
+ + "(发布成功且未标记下架,同商品只出最新一行)分页,附 used/limit 余量读数。")
+ public ApiResponse 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 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) {}
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java
index e958c32a4..70968e17f 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java
@@ -87,13 +87,8 @@ public interface JdProductMapper extends BaseMapper {
@Param("companyId") Long companyId,
@Param("visibleGroupIds") List visibleGroupIds);
- /**
- * 商品上架配额计数({@code JdPublishQuotaService}):按 owner uid 集(管理员本人+
- * 名下员工,公司超管=全公司成员)计 {@code biz_jd_product} 行数。归属列
- * {@code user_id}=任务 owner(V193 物化列)。调用方保证列表非空——空集在服务侧
- * 直接按 0 处理,不进 SQL。
- */
- long countByUserIds(@Param("userIds") List userIds);
+ // 2026-11-25 口径改造:旧「商品上架配额计数 countByUserIds(按 biz_jd_product 行数)」已删——
+ // 额度正本迁到 JdPublishItemMapper.countOnShelfByUserIds(在架商品数)。口径源只能一份。
/**
* 后管只读页分页查询(synced_at 倒序)。
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdPublishItemMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdPublishItemMapper.java
index 7f9119ba8..7f4358111 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdPublishItemMapper.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdPublishItemMapper.java
@@ -32,4 +32,24 @@ public interface JdPublishItemMapper extends BaseMapper {
* 行数上界=该任务商品行数(建单口钳 500),无分页问题。
*/
List
*
* 建单成功页面推送与兜底拉取共用同一份载荷组装 {@link #buildQueuePayload}:
@@ -128,8 +127,9 @@ public class JdPublishTaskService {
public JdPublishTaskVo createTask(JdPublishTaskCreateRequest request, String deviceId) {
validate(request);
// AC-8 配额闸:前置在一切昂贵动作前(铁律 27b),超配额当场业务码拒绝并点名额度文案。
+ // 2026-11-25 口径改在架商品数:传勾选商品集而非个数——批内已在架的不双计(重复上架不重复占位)。
AdminUserEntity operator = adminUserMapper.selectById(request.getUserId());
- jdPublishQuotaService.assertWithinQuota(operator, request.getProductIds().size());
+ jdPublishQuotaService.assertWithinQuota(operator, request.getProductIds());
// 归属闸(2026-11-25 作用域改口径:选中商品必须在「本账号可见数据权限分组」的分类
// 归属行里,与选品列表/分类下拉同源同口径)。旧形状按 biz_jd_product.user_id 严格
diff --git a/backend-java/src/main/resources/db/V216__jd_publish_item_delisted.sql b/backend-java/src/main/resources/db/V216__jd_publish_item_delisted.sql
new file mode 100644
index 000000000..5a47a797b
--- /dev/null
+++ b/backend-java/src/main/resources/db/V216__jd_publish_item_delisted.sql
@@ -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`;
diff --git a/backend-java/src/main/resources/db/V217__users_normal_quota_reset.sql b/backend-java/src/main/resources/db/V217__users_normal_quota_reset.sql
new file mode 100644
index 000000000..cc195aef6
--- /dev/null
+++ b/backend-java/src/main/resources/db/V217__users_normal_quota_reset.sql
@@ -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;
diff --git a/backend-java/src/main/resources/mapper/jd/JdProductMapper.xml b/backend-java/src/main/resources/mapper/jd/JdProductMapper.xml
index 02c1daf3e..723f265c9 100644
--- a/backend-java/src/main/resources/mapper/jd/JdProductMapper.xml
+++ b/backend-java/src/main/resources/mapper/jd/JdProductMapper.xml
@@ -145,7 +145,7 @@
AND p.price_max <= #{maxPrice}
-
+
diff --git a/backend-java/src/main/resources/mapper/jd/JdPublishItemMapper.xml b/backend-java/src/main/resources/mapper/jd/JdPublishItemMapper.xml
index f491bea93..32fe585f9 100644
--- a/backend-java/src/main/resources/mapper/jd/JdPublishItemMapper.xml
+++ b/backend-java/src/main/resources/mapper/jd/JdPublishItemMapper.xml
@@ -28,4 +28,50 @@
WHERE task_id = #{taskId}
GROUP BY publish_status
+
+
+
+
+
+
+
+
+
diff --git a/backend-java/src/test/java/com/nanri/aiimage/MigratedSqlEquivalenceTest.java b/backend-java/src/test/java/com/nanri/aiimage/MigratedSqlEquivalenceTest.java
index 5ec6556a6..c25885d0f 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/MigratedSqlEquivalenceTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/MigratedSqlEquivalenceTest.java
@@ -118,7 +118,13 @@ class MigratedSqlEquivalenceTest {
// mapper/company/CompanyMapper.xml(SqlLayeringConventionTest 抓到 898e8a5e 走了注解
// 通道),SQL 文本未改写;非注解迁移件,逐条点名进下方 NOT_MIGRATED
//(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,
// SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 163 → 164)。
- "JdProductMapper#countByUserIds",
+ // 2026-11-25 额度改口径随旧计数源整条删除(口径源只能一份),点名一并摘除。
// 47fc0e08(2026-11-16 平台超管 500 热修)给 selectAllGroups 的 XML 补
// g.company_id AS companyId:注解时代原文没有这列,等价性这支对撞即红。
// 有意改动按先例整行摘账本点名留痕(LEDGER_ROWS 83 → 82 / SELECTS 59 → 58);
@@ -242,6 +248,14 @@ class MigratedSqlEquivalenceTest {
//(XML_SELECT_TOTAL 103 → 105,SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。
"JdPublishItemMapper#selectPublishableItems",
"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 行锁,不存在注解时代原文。
"FileTaskMapper#selectByIdForUpdate",
// 2026-11-21 v1.7 店铺名单:JdProductMapper 新写 1 条只读 select
diff --git a/backend-java/src/test/java/com/nanri/aiimage/SqlLayeringConventionTest.java b/backend-java/src/test/java/com/nanri/aiimage/SqlLayeringConventionTest.java
index 9ad500550..0d00bbdf8 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/SqlLayeringConventionTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/SqlLayeringConventionTest.java
@@ -149,7 +149,12 @@ class SqlLayeringConventionTest {
// 154 → 156:2026-11-23 京麦授权类目树(V215)新落 mapper/jd/JdShopCategoryTreeMapper.xml
// 2 条写语句——deleteByShopId(整店快照替换第一步,1 delete)+ insertBatch(500 行一批,
// 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 的现状("这不是简单单表"的证据),文件名 → 条数:
diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/api/PageDefaultsLedgerTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/api/PageDefaultsLedgerTest.java
index 7b2f592ff..f4852b980 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/common/api/PageDefaultsLedgerTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/common/api/PageDefaultsLedgerTest.java
@@ -85,6 +85,10 @@ class PageDefaultsLedgerTest {
"JdPublishController.java#page=FIRST_PAGE",
"JdPublishController.java#page_size=JD_PRODUCTS_PAGE_SIZE",
"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#pageSize=ADMIN_LIST_PAGE_SIZE",
// (本批 /groups 端点:参数名与默认值和列表端点同,台账按出站点计数、不去重)
@@ -132,11 +136,12 @@ class PageDefaultsLedgerTest {
+ " page/page_size 两处出站点;60→59:2026-11-17 任务证据特性下线,"
+ " AdminTaskEvidenceController 两处出站点随控制器删除)")
.isEqualTo(LEDGER.stream().sorted().toList());
- // 同口径非零对照:台账不是空的,扫描器也确实数得出 62 处
+ // 同口径非零对照:台账不是空的,扫描器也确实数得出 64 处
// (61 而不是 60:2026-11-15 京东任务面板改版(45d0989a)新增 GET /api/jd-collect/history
// 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处;
- // 59→62:v1.5 Phase 4 用户端「商品上架」读侧三出站点随 917884aa 登记同窗)
- assertThat(constants).hasSize(62);
+ // 59→62:v1.5 Phase 4 用户端「商品上架」读侧三出站点随 917884aa 登记同窗;
+ // 62→64:2026-11-25 上架额度改口径新增 GET /api/jd-publish/on-shelf 的 page/page_size 两处)
+ assertThat(constants).hasSize(64);
}
@Test
@@ -153,8 +158,9 @@ class PageDefaultsLedgerTest {
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
.as("页码口径只有一套:全部从 1 起(26→27:v1.5 Phase 4 用户端「商品上架」products 选品分页也是分页出站点;"
+ "26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;"
- + "27→26:2026-11-17 任务证据特性下线随删一处)")
- .isEqualTo(27);
+ + "27→26:2026-11-17 任务证据特性下线随删一处;"
+ + "27→28:2026-11-25 上架额度改口径新增 GET /api/jd-publish/on-shelf 分页)")
+ .isEqualTo(28);
assertThat(distinctConstants(actual, "page_size"))
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/security/RequestSuppliedIdentityOutletTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/security/RequestSuppliedIdentityOutletTest.java
index 751d7a88b..e2eafab32 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/common/security/RequestSuppliedIdentityOutletTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/common/security/RequestSuppliedIdentityOutletTest.java
@@ -134,7 +134,9 @@ class RequestSuppliedIdentityOutletTest {
// GET /api/jd-publish/products(选品分页,AC-9 owner 过滤)+ GET /api/jd-publish/dashboard
// + GET /api/jd-publish/history(面板统计卡+历史层),都是 @RequestParam("user_id") 先过
// 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:只剩豁免那一条")
.containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET);
}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/admin/service/AdminUserServiceCompanySuperAdminTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/admin/service/AdminUserServiceCompanySuperAdminTest.java
index 992da0974..e1f0d580c 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/admin/service/AdminUserServiceCompanySuperAdminTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/admin/service/AdminUserServiceCompanySuperAdminTest.java
@@ -61,7 +61,7 @@ class AdminUserServiceCompanySuperAdminTest {
}
@Test
- void 京东额度允许零并拒绝负数和普通账号() {
+ void 京东额度允许零并拒绝负数_普通账号也可分配() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(10L, "admin", 1L, 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
@@ -73,10 +73,106 @@ class AdminUserServiceCompanySuperAdminTest {
request.setJdPublishQuota(-1);
assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
.isInstanceOf(BusinessException.class).hasMessageContaining("不能为负数");
+ // 2026-11-25 分配闸上线:普通账号也可设额度(=主管向员工的分配账,0=未分配),
+ // 旧 400「只能为管理员设置京东上架额度」废止——没有员工额度数字,Σ 总和账无从算起。
request.setJdPublishQuota(1);
target.setRole("normal");
- assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
- .isInstanceOf(BusinessException.class).hasMessageContaining("只能为管理员");
+ service.updateUser(operator, 10L, request);
+ 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());
}
/**
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/JdSchemaContractTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/JdSchemaContractTest.java
index b53839517..e9f2fe575 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/JdSchemaContractTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/JdSchemaContractTest.java
@@ -156,6 +156,28 @@ class JdSchemaContractTest {
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
void V214_分类店铺名单_同分类唯一键形状() {
String sql = read(DB_DIR.resolve("V214__jd_group_shop.sql"));
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/mapper/JdPublishOnShelfSqlTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/mapper/JdPublishOnShelfSqlTest.java
new file mode 100644
index 000000000..e35e7e6e0
--- /dev/null
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/mapper/JdPublishOnShelfSqlTest.java
@@ -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 客户口径改造)。
+ *
+ *
为什么钉 SQL:额度 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 三连缺列的同款教训)。
+ */
+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 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;
+ }
+}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishOnShelfServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishOnShelfServiceTest.java
new file mode 100644
index 000000000..a3f344d1e
--- /dev/null
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishOnShelfServiceTest.java
@@ -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 额度改口径)。
+ *
+ * 核心判据:标记按商品整组生效——同商品跨任务的多条 SUCCESS 行必须一起落
+ * delisted_at,只标面板展示那一行,旧行仍被 {@code COUNT(DISTINCT product_id)} 计为在架、
+ * 额度腾不出去(客户「下架 10 再上 10」当场误拦)。权限=团队口径;面板余量读数与
+ * 配额闸同一正本(quotaOf)。
+ */
+@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> captor =
+ ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
+ verify(jdPublishItemMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
+ LambdaUpdateWrapper 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> 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());
+ }
+}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishQuotaServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishQuotaServiceTest.java
index 1e5e40fef..e3e000d4b 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishQuotaServiceTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishQuotaServiceTest.java
@@ -3,7 +3,7 @@ package com.nanri.aiimage.modules.jd.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.jd.mapper.JdProductMapper;
+import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -23,7 +23,10 @@ import static org.mockito.Mockito.when;
/**
* 商品上架配额(JdPublishQuotaService)行为测试:默认 5000、0=不限、普通账号锚定到
* created_by_id 管理员并按其团队 uid 集计数、站点超管豁免、恰好等于上限的边界放行、
- * 空集按 used=0 不进 SQL。判限口径=「管理员+名下员工合计」(2026-11-15 用户口径)。
+ * 空集按 used=0 不进 SQL。判限口径=「管理员+名下员工合计」(2026-11-15 用户口径);
+ * 计数口径=团队在架商品数(发布成功且未标记下架,去重商品,2026-11-25 客户口径
+ * 「上限=同时在架商品数,下架 10 个就能再上架 10 个」)——旧「采集库占有行数」
+ * 口径判据随正本迁移替换。
*/
@ExtendWith(MockitoExtension.class)
class JdPublishQuotaServiceTest {
@@ -33,10 +36,10 @@ class JdPublishQuotaServiceTest {
@Mock
private UserDataScopeSupport userDataScopeSupport;
@Mock
- private JdProductMapper jdProductMapper;
+ private JdPublishItemMapper jdPublishItemMapper;
private JdPublishQuotaService newService() {
- return new JdPublishQuotaService(adminUserMapper, userDataScopeSupport, jdProductMapper);
+ return new JdPublishQuotaService(adminUserMapper, userDataScopeSupport, jdPublishItemMapper);
}
private AdminUserEntity admin(long id) {
@@ -54,21 +57,29 @@ class JdPublishQuotaServiceTest {
return user;
}
+ /** 批量商品 id(n 个不重复)。 */
+ private static List products(int n) {
+ return java.util.stream.LongStream.rangeClosed(1, n).boxed().toList();
+ }
+
/** 双重载(Long/实体)消歧:lambda 参数显式标注实体形状(argThat(...))。 */
@Test
- void 默认上限5000_超限拒绝且文案含占用与上限() {
+ void 默认上限5000_超限拒绝且文案含在架与上限() {
JdPublishQuotaService service = newService();
AdminUserEntity employee = employee(9L, 5L);
when(adminUserMapper.selectById(5L)).thenReturn(admin(5L));
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.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)
.hasMessageContaining("4990")
.hasMessageContaining("5000")
+ .hasMessageContaining("在架")
+ .hasMessageContaining("标记已下架")
.hasMessageContaining("管理员");
// 普通账号必须锚定到所属管理员(uid=5)的团队集,而不是只数自己
verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L));
@@ -80,9 +91,38 @@ class JdPublishQuotaServiceTest {
AdminUserEntity operator = admin(5L);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.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
@@ -90,10 +130,8 @@ class JdPublishQuotaServiceTest {
JdPublishQuotaService service = newService();
AdminUserEntity operator = admin(5L);
operator.setJdPublishQuota(0);
- when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
- .thenReturn(List.of());
- assertThatCode(() -> service.assertWithinQuota(operator, 999_999)).doesNotThrowAnyException();
- verifyNoInteractions(jdProductMapper, adminUserMapper);
+ assertThatCode(() -> service.assertWithinQuota(operator, products(999_999))).doesNotThrowAnyException();
+ verifyNoInteractions(jdPublishItemMapper, adminUserMapper);
}
@Test
@@ -103,8 +141,8 @@ class JdPublishQuotaServiceTest {
siteSuperAdmin.setId(1L);
siteSuperAdmin.setRole("super_admin");
- assertThatCode(() -> service.assertWithinQuota(siteSuperAdmin, 999_999)).doesNotThrowAnyException();
- verifyNoInteractions(jdProductMapper, userDataScopeSupport, adminUserMapper);
+ assertThatCode(() -> service.assertWithinQuota(siteSuperAdmin, products(999_999))).doesNotThrowAnyException();
+ verifyNoInteractions(jdPublishItemMapper, userDataScopeSupport, adminUserMapper);
}
@Test
@@ -114,22 +152,22 @@ class JdPublishQuotaServiceTest {
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of());
- // used=0:additional=5000 恰好等于上限,放行
- assertThatCode(() -> service.assertWithinQuota(operator, 5000)).doesNotThrowAnyException();
- // additional=5001 超限,但空集不查库
- assertThatThrownBy(() -> service.assertWithinQuota(operator, 5001))
+ // used=0:本批净新增 5000 恰好等于上限,放行
+ assertThatCode(() -> service.assertWithinQuota(operator, products(5000))).doesNotThrowAnyException();
+ // 5001 超限,但空集不查库
+ assertThatThrownBy(() -> service.assertWithinQuota(operator, products(5001)))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("0");
- verifyNoInteractions(jdProductMapper);
+ verifyNoInteractions(jdPublishItemMapper);
}
@Test
- void 快照返回占用与上限() {
+ 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(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(1234L);
+ when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(1234L);
JdPublishQuotaService.QuotaSnapshot snapshot = service.quotaOf(operator);
assertThat(snapshot.used()).isEqualTo(1234L);
@@ -145,8 +183,9 @@ class JdPublishQuotaServiceTest {
when(adminUserMapper.selectById(5L)).thenReturn(manager);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L));
- when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(12L);
- assertThatThrownBy(() -> service.assertWithinQuota(employee(9L, 5L), 1))
+ when(jdPublishItemMapper.countOnShelfByUserIds(List.of(5L, 9L))).thenReturn(12L);
+ when(jdPublishItemMapper.countOnShelfInProductIds(List.of(5L, 9L), products(1))).thenReturn(0L);
+ assertThatThrownBy(() -> service.assertWithinQuota(employee(9L, 5L), products(1)))
.isInstanceOf(BusinessException.class).hasMessageContaining("12");
}
@@ -157,11 +196,22 @@ class JdPublishQuotaServiceTest {
when(adminUserMapper.selectById(5L)).thenReturn(null);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 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)
.hasMessageContaining("5000");
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);
+ }
}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishTaskServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishTaskServiceTest.java
index fe63fda5e..4a098194a 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishTaskServiceTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdPublishTaskServiceTest.java
@@ -34,7 +34,7 @@ import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
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;
@@ -168,8 +168,8 @@ class JdPublishTaskServiceTest {
.contains("\"targetBrandName\":\"目标品牌B\"");
// AC-1 明细快照行:每勾选商品一行
verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(any(JdPublishItemEntity.class));
- // AC-8 配额闸:前置且按勾选数计
- verify(jdPublishQuotaService).assertWithinQuota(any(AdminUserEntity.class), eq(2));
+ // AC-8 配额闸:前置且按勾选商品集计(2026-11-25 改在架口径:传集不传数,批内已在架不双计)
+ verify(jdPublishQuotaService).assertWithinQuota(any(AdminUserEntity.class), eq(List.of(101L, 102L)));
// 铁律 32 第三件:建单响应带页面推送载荷,type 与 SPI QUEUE_TYPE 同值
assertThat(vo.getQueuePayload())
.containsEntry("type", "jd-product-publish-run");
@@ -214,7 +214,7 @@ class JdPublishTaskServiceTest {
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请勾选要上架的商品");
- verify(jdPublishQuotaService, never()).assertWithinQuota(any(), anyInt());
+ verify(jdPublishQuotaService, never()).assertWithinQuota(any(), anyList());
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
}
@@ -302,9 +302,9 @@ class JdPublishTaskServiceTest {
@Test
void 超配额建单被拒且不落任何行() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
- org.mockito.Mockito.doThrow(new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前已占用 "
- + "5000/上限 5000,请清理京东数据库商品或联系管理员调整配额后重试"))
- .when(jdPublishQuotaService).assertWithinQuota(any(), eq(2));
+ org.mockito.Mockito.doThrow(new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前在架 "
+ + "5000/上限 5000,请先在京麦下架商品并在「在架商品」里标记已下架,或联系管理员调整额度后重试"))
+ .when(jdPublishQuotaService).assertWithinQuota(any(), eq(List.of(101L, 102L)));
assertThatThrownBy(() -> service.createTask(validRequest(7L), null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("商品上架数量已达上限");
diff --git a/frontend-vue/src/pages/jd/JdOnShelfPanel.vue b/frontend-vue/src/pages/jd/JdOnShelfPanel.vue
new file mode 100644
index 000000000..62da390a3
--- /dev/null
+++ b/frontend-vue/src/pages/jd/JdOnShelfPanel.vue
@@ -0,0 +1,129 @@
+
+
+
+
+
+
+ {{ vo ? quotaReadoutText(vo.used, vo.limit, vo.unlimited) : '余量读取中…' }}
+
+
+
+ 额度已满:请先在京麦下架商品,并到本列表「标记已下架」腾出额度后再建单。
+
+
+
{{ onShelfEmptyText(vo.unlimited, vo.used) }}
+
+
![]()
+
无图
+
+ {{ item.title || '(无标题快照)' }}
+
+ 编码 {{ item.productCode }} ·
+ 来源 {{ item.shopName }} ·
+ 上架 {{ item.listedAt ? formatDateTime(item.listedAt) : '-' }}
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend-vue/src/pages/jd/JdPublishTab.vue b/frontend-vue/src/pages/jd/JdPublishTab.vue
index 95e3fa145..9d97caee3 100644
--- a/frontend-vue/src/pages/jd/JdPublishTab.vue
+++ b/frontend-vue/src/pages/jd/JdPublishTab.vue
@@ -2,6 +2,7 @@
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
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 jdLogo from '@/pages/home/assets/jd-logo.png'
import {
@@ -899,6 +900,7 @@ onUnmounted(() => {
+
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}下架,额度已腾出;请确认该商品确已在京麦下架`;
+}
diff --git a/frontend-vue/src/shared/api/endpoints.ts b/frontend-vue/src/shared/api/endpoints.ts
index 651a4c3ce..7f7e09141 100644
--- a/frontend-vue/src/shared/api/endpoints.ts
+++ b/frontend-vue/src/shared/api/endpoints.ts
@@ -246,6 +246,10 @@ export const API_ENDPOINTS = {
progress: '/api/jd-publish/tasks/{taskId}/progress',
/** 删除任务(连带清理该任务的发布明细快照行) */
deleteTask: '/api/jd-publish/tasks/{taskId}',
+ /** 在架商品分页+额度余量(2026-11-25 客户口径「上限=同时在架商品数」) */
+ onShelf: '/api/jd-publish/on-shelf',
+ /** 标记/取消标记已下架(按商品整组腾额度) */
+ markDelisted: '/api/jd-publish/items/{itemId}/delisted',
},
userSecret: {
bundle: '/api/user-secrets',
diff --git a/frontend-vue/src/shared/api/types/modules/jd-publish.ts b/frontend-vue/src/shared/api/types/modules/jd-publish.ts
index b4096bcae..691e993de 100644
--- a/frontend-vue/src/shared/api/types/modules/jd-publish.ts
+++ b/frontend-vue/src/shared/api/types/modules/jd-publish.ts
@@ -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>(
+ buildJavaUrl(API_ENDPOINTS.jdPublish.onShelf),
+ { params: { user_id: getCurrentUserId(), page, page_size: pageSize } },
+ ),
+ );
+}
+
+/** 标记/取消标记已下架:服务端按商品整组回写(同商品跨任务成功行一起落/一起回拨)。 */
+export function markJdItemDelisted(itemId: number, delisted: boolean) {
+ return unwrapJavaResponse(
+ post, { delisted: boolean }>(
+ buildJavaUrl(API_ENDPOINTS.jdPublish.markDelisted.replace('{itemId}', String(itemId))),
+ { delisted },
+ ),
+ );
+}
diff --git a/frontend-vue/tests/catch-silence-ratchet.test.ts b/frontend-vue/tests/catch-silence-ratchet.test.ts
index 10af427b3..df963023c 100644
--- a/frontend-vue/tests/catch-silence-ratchet.test.ts
+++ b/frontend-vue/tests/catch-silence-ratchet.test.ts
@@ -118,7 +118,11 @@ const BASELINE = {
// 原文只进 console;「读不到权限」不等于「没权限」,把有权限的人锁在门外比放进去后被
// 服务端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。非静默:
// 首条语句是状态写入、不是 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 行,面板里那处
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
diff --git a/frontend-vue/tests/endpoints.test.ts b/frontend-vue/tests/endpoints.test.ts
index 8b7159ae1..ae694bfbe 100644
--- a/frontend-vue/tests/endpoints.test.ts
+++ b/frontend-vue/tests/endpoints.test.ts
@@ -349,7 +349,10 @@ test('test_endpoints_frozen_snapshot', () => {
"history": "/api/jd-publish/history",
"progressBatch": "/api/jd-publish/tasks/progress/batch",
"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": {
"bundle": "/api/user-secrets",
diff --git a/frontend-vue/tests/jd-on-shelf.test.ts b/frontend-vue/tests/jd-on-shelf.test.ts
new file mode 100644
index 000000000..f6c62d52f
--- /dev/null
+++ b/frontend-vue/tests/jd-on-shelf.test.ts
@@ -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, //)
+})
diff --git a/frontend-vue/tests/mount/jd-on-shelf-panel.mount.test.ts b/frontend-vue/tests/mount/jd-on-shelf-panel.mount.test.ts
new file mode 100644
index 000000000..a7dfc9532
--- /dev/null
+++ b/frontend-vue/tests/mount/jd-on-shelf-panel.mount.test.ts
@@ -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(),
+ ElMessage: { success: api.success, error: api.error },
+ ElMessageBox: { confirm: api.confirm },
+}))
+
+function pageVo(overrides: Record = {}) {
+ 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: '' } },
+ 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('本团队')
+})