feat(jd): 上架按账号授权 + 建单钉来源店铺 + 店铺不匹配整单判死

2026-11-24 客户(心向大海)两条口径:
「如果没有店铺登入情况 软件怎么知道我们要上架是哪一个店铺?」
「上架的账户 我是这个权限不开给他的」

后端半边(用户端页头与会话核对见 frontend-vue 同笔;客户端发布前核对见 app_client 0f8bcdf)。

一、按账号授权(拒绝型能力,quiet fail 全靠本类判据)
- JdPublishPermissionSupport:V209 app 菜单组键 jd_tools 或子键 jd-publish 命中即放行,
  超管直放;有效键集按 AdminMenuPlatformScope 过滤到账号平台(与登录分发同源)。
  无权限抛 403 + 中文动作句(告诉管理员去哪儿勾)。
- JdPublishController:建单/改品牌重试/选品/面板/历史/批量进度六个用户面入口一律先判;
  客户端执行面(items/chunk/activate/heartbeat/补值/删除)不判——执行器本来就只跑
  已建的任务,判在这里会让进行中的任务断在半路。

二、建单钉来源店铺(一次上架只发一家店)
- resolveSingleShop:按勾选商品快照判店铺,跨店勾选建单即拒并点名两家店;
  同店两种形状(有 id / 只有店名)归一到 id 再比。
- JdPublishTaskCreateRequest 落 shopId/shopName → 队列载荷两键 → 明细页
  JdPublishItemsPageVo.shopId/shopName 下发;旧任务载荷没这两键时回落明细行
  shop_name(V210 就有),保证老任务至少能按店名核对。

三、店铺不匹配整单判死
- JdPublishStaleTaskService.SHOP_MISMATCH_MARK/terminalizeOnJdShopMismatch:
  CAS RUNNING→FAILED、0/1 计数、原文追加动作句;不按累计行数收窄(确定性失败)。
- JdPublishIngestService.fail:命中标记排在凭据致命档之后、页面结构变更之前接线,
  回 accept=true 让客户端收口。

判据:JdPublishPermissionSupportTest 5 支(新)+TaskService +3/Stale +2/Ingest +2,
后端 JdPublish 九类 77 支全绿;四支既有护栏(catch 静默/请求身份/超管单出口/SQL 分层)绿。
This commit is contained in:
2026-11-24 15:21:27 +08:00
parent cf06872cb6
commit 1b10db4bf9
20 changed files with 1156 additions and 6 deletions
+155
View File
@@ -22,6 +22,13 @@ import {
} from '@/shared/api/types/modules/jd-publish'
import { retryClientTask } from '@/shared/api/task-retry'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { ensureJdLogin, markJdLoginExpired } from '@/shared/stores/jd-login-autoflow'
import {
evaluateShopGuard,
shopGuardBlocks,
shopLabel,
type JdShopRef,
} from '@/pages/jd/jd-publish-shop'
import { resolvePageHref } from '@/shared/page-prefix'
import { userNotice } from '@/shared/utils/user-notice'
import { formatDateTime } from '@/shared/utils/datetime'
@@ -166,8 +173,109 @@ function isValidBrand(name: string) {
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
// ---- 本次上架到哪家店(2026-11-24 客户口径「软件怎么知道要上架哪一家店铺」)----
/** 来源店铺=勾选商品行的快照店铺;京麦当前店铺=桥现拉(不缓存、不猜、不自动探测)。 */
const selectedProductRows = computed(() => Array.from(selectedProducts.value.values()))
const currentShop = ref<JdShopRef | null>(null)
const detectingShop = ref(false)
const canDetectShop = ref(false)
const shopNote = ref('')
const shopError = ref('')
const SHOP_DETECT_UNAVAILABLE =
'当前在本机客户端之外打开或客户端版本较旧,无法检测京麦店铺。请在本机客户端中打开本页;'
+ '本机客户端发布前仍会核对任务记录的店铺,不一致整单拦下、一条都不发'
const shopGuard = computed(() => evaluateShopGuard(selectedProductRows.value, currentShop.value))
/** 来源店铺文案:没取到/多家店/单店三档(多店由 shopGuard 直接拦)。 */
const sourceShopText = computed(() => {
const guard = shopGuard.value
if (guard.state === 'unknown') return '未取到(旧商品数据没有店铺信息)'
if (guard.state === 'multi') return guard.shops.map((shop) => shopLabel(shop)).join('、')
return shopLabel(guard.expected)
})
const currentShopText = computed(() => (currentShop.value ? shopLabel(currentShop.value) : '未检测'))
/** 挂载时判可用性:老客户端没有 get_jd_shop_info ⇒ 检测按钮置灰(同「同步分类」口径)。 */
function refreshShopDetectability() {
canDetectShop.value = typeof getPywebviewApi()?.get_jd_shop_info === 'function'
}
/**
* 点「检测当前京麦店铺」:桥现拉京麦首屏(会起客户端专用浏览器,秒级)。
* 失败按 code 分档——jd_busy 走 amber 说明、jd_login 走自动登录链路(登录成功后自动重测一次)、
* jd_page/未知走红色错误。返回值只作 `startPublish` 的判断输入,展示通道由本函数自理。
*/
async function detectShop(options?: { fromAutoLogin?: boolean }) {
if (detectingShop.value && !options?.fromAutoLogin) return
shopError.value = ''
shopNote.value = ''
const api = getPywebviewApi()
const bridge = api?.get_jd_shop_info
if (typeof bridge !== 'function') {
canDetectShop.value = false
shopNote.value = SHOP_DETECT_UNAVAILABLE
return
}
detectingShop.value = true
try {
const result = await bridge()
if (result?.success && (result.shopName || result.shopId)) {
currentShop.value = { shopId: result.shopId, shopName: result.shopName }
return
}
if (result?.code === 'jd_busy') {
shopNote.value = result.error || '京东任务正在运行,等任务结束后再检测京麦店铺'
return
}
if (result?.code === 'jd_login') {
if (options?.fromAutoLogin) {
shopError.value = result.error || '京麦未登录(登录态失效)'
return
}
markJdLoginExpired()
shopNote.value = '检测到京麦未登录,已自动打开京麦登录窗口,请在弹出的浏览器里完成登录'
const gate = await ensureJdLogin(api)
if (gate.status === 'ok') {
shopNote.value = ''
detectingShop.value = false
await detectShop({ fromAutoLogin: true })
return
}
if (gate.severity === 'error') {
shopNote.value = ''
shopError.value = gate.hint || result.error || '打开京麦登录窗口失败,请稍后重试'
} else {
shopNote.value = gate.hint || shopNote.value
}
return
}
shopError.value = result?.error || '检测京麦店铺失败,请稍后重试'
} finally {
detectingShop.value = false
}
}
/**
* 建单前把店铺核一次:已检测且一致就不再开浏览器;命中不匹配/跨店直接给拦截文案。
* 检测失败(页面结构变更、老客户端、京麦任务在跑)**不**拦创建——最终强拦截在客户端
* 执行器(先上报标记再中止)与服务端(命中即整单判死),页面这层只负责提前告知。
*/
async function ensureShopChecked(): Promise<string> {
const guard = shopGuard.value
if (shopGuardBlocks(guard)) return guard.message
if (guard.state !== 'undetected') return ''
await detectShop()
const next = shopGuard.value
return shopGuardBlocks(next) ? next.message : ''
}
const submitDisabled = computed(() =>
submitting.value
|| detectingShop.value
|| shopGuardBlocks(shopGuard.value)
|| !selectedGroupId.value
|| !selectedProducts.value.size
|| !isValidBrand(targetBrandName.value)
@@ -603,6 +711,12 @@ async function startPublish() {
errorMessage.value = JD_UPGRADE_NOTICE
return
}
// 店铺核对在建单之前:京麦登录的不是勾选商品那家店时一条都不发(客户口径「强拦截」)。
const shopIssue = await ensureShopChecked()
if (shopIssue) {
errorMessage.value = shopIssue
return
}
const vo = await createJdPublishTask(categoryId, productIds, priceRule, brand)
board.addPollingTask(vo.taskId)
const pushNote = await pushToClientQueue(vo.queuePayload)
@@ -620,6 +734,7 @@ async function startPublish() {
onMounted(async () => {
const localName = (window.localStorage.getItem('username') || '').trim()
if (localName) username.value = localName
refreshShopDetectability()
board.loadPollingIds()
await Promise.all([
loadGroups().catch(() => undefined),
@@ -666,6 +781,35 @@ onUnmounted(() => {
<main class="jd-body">
<aside class="left-panel">
<!-- 本次上架到哪家店:来源店铺(勾选商品快照)vs 京麦当前登录店铺(现检测) -->
<div class="category-block shop-guard">
<span class="category-label">本次上架到哪家店</span>
<p class="shop-line">
<span class="shop-line__key">商品来源店铺</span>
<span class="shop-line__value">{{ sourceShopText }}</span>
</p>
<p class="shop-line">
<span class="shop-line__key">京麦当前登录</span>
<span class="shop-line__value" :class="{ 'shop-line__value--muted': !currentShop }">{{ currentShopText }}</span>
<button class="shop-detect-btn" type="button" :disabled="detectingShop || !canDetectShop" @click="detectShop()">
{{ detectingShop ? '检测中…' : (currentShop ? '重新检测' : '检测京麦店铺') }}
</button>
</p>
<p v-if="shopError" class="shop-alert">{{ shopError }}</p>
<p v-else-if="shopGuard.state === 'mismatch' || shopGuard.state === 'multi'" class="shop-alert">
{{ shopGuard.message }}
</p>
<p v-else-if="shopGuard.state === 'match'" class="shop-ok">
店铺一致:商品会发布到「{{ shopLabel(shopGuard.expected) }}」。
</p>
<p v-else-if="shopNote" class="category-hint">{{ shopNote }}</p>
<p v-else-if="!canDetectShop" class="category-hint">{{ SHOP_DETECT_UNAVAILABLE }}</p>
<p v-else class="category-hint">
勾选商品后点「检测京麦店铺」可确认京麦当前登录的是不是同一家店;不一致时本页不让建单,
客户端发布前还会再核对一次,一条都不会发出去。
</p>
</div>
<div class="category-block">
<span class="category-label">自定义分类</span>
<el-select v-model="selectedGroupId" placeholder="选择分类" class="shop-cat-select"
@@ -700,6 +844,7 @@ onUnmounted(() => {
<span class="product-info">
<span class="product-title">{{ product.title }}</span>
<span class="product-meta">
<template v-if="product.shopName">店铺 {{ product.shopName }} · </template>
¥{{ product.priceMin ?? '-' }}<template v-if="product.priceMax && product.priceMax !== product.priceMin">~{{ product.priceMax }}</template>
· 库存 {{ product.stockTotal ?? '-' }}<template v-if="product.skuCount"> · {{ product.skuCount }}个SKU</template>
</span>
@@ -797,6 +942,16 @@ onUnmounted(() => {
.category-block { margin-bottom: 16px; }
.category-label { display: block; margin-bottom: 8px; color: #c8d2e2; font-size: 13px; font-weight: 600; }
.category-hint { margin: 8px 0 0; color: #7f8ca3; font-size: 12px; line-height: 1.6; }
.shop-guard { padding: 10px 12px; border: 1px solid #2c3547; border-radius: 8px; background: #20283a; }
.shop-line { display: flex; align-items: center; gap: 8px; margin: 0 0 6px; font-size: 12px; line-height: 1.5; }
.shop-line__key { flex-shrink: 0; color: #7f8ca3; }
.shop-line__value { min-width: 0; overflow: hidden; color: #d9e1ef; text-overflow: ellipsis; white-space: nowrap; }
.shop-line__value--muted { color: #7f8ca3; }
.shop-detect-btn { flex-shrink: 0; margin-left: auto; padding: 3px 10px; border: 1px solid #3e4a62; border-radius: 6px; background: #232b3d; color: #c8d2e2; font-family: inherit; font-size: 12px; cursor: pointer; }
.shop-detect-btn:hover:not(:disabled) { border-color: #6ea8ff; color: #f5f8fc; }
.shop-detect-btn:disabled { opacity: 0.55; cursor: not-allowed; }
.shop-alert { margin: 6px 0 0; padding: 8px 10px; border-radius: 6px; background: rgba(248, 113, 113, 0.12); color: #fca5a5; font-size: 12px; line-height: 1.6; }
.shop-ok { margin: 6px 0 0; color: #6ee7b7; font-size: 12px; }
.shop-cat-select { width: 100%; }
.shop-cat-select :deep(.el-select__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
.shop-cat-select :deep(.el-select__placeholder), .shop-cat-select :deep(.el-select__selected-item) { color: #c8d2e2; }
@@ -0,0 +1,44 @@
/**
* 「商品上架」按账号授权(2026-11-24 客户口径:「上架的账户 我是这个权限不开给他的」)。
*
* 三层,口径同一份、判据逐字相同:
* 1. **入口**:京东工作台的卡片由 `filterJdToolsByPermission` 过滤(V209 app 菜单:
* 组键 `jd_tools` 或子键 `jd-publish`);
* 2. **直达路由**:`/jd-publish` 的 `beforeEnter` 用本文件的 `resolveJdPublishAccess`,
* 没权限的用户手敲地址也进不来(正常入口被隐藏后,直达是唯一绕过口);
* 3. **服务端**:`JdPublishPermissionSupport.assertCanPublish`(建单/选品/面板一律 403),
* 这是唯一权威判据——前端两层只为用户体验,不承担安全职责。
*
* 收回权限的实操(后管「用户管理 → 菜单权限 → 桌面端」):把「商品上架」子项取消勾选后
* 保存,直接授权集合只剩 `{jd-collect}`,读侧不再展开 `jd_tools` 组 ⇒ 本文件判为无权限。
*
* 权限接口异常(`null`)按「未知」放行:后管账号体系里「读不到权限」与「没有权限」必须分开,
* 抖一下把有权限的人锁在门外比放进去后被 403 更难解释;后端 403 仍是硬边界。
*/
/** app 菜单组键(V209 columns.column_key='jd_tools') */
export const JD_PUBLISH_GROUP_KEY = 'jd_tools'
/** 商品上架子键(V209 columns.column_key='jd-publish') */
export const JD_PUBLISH_COLUMN_KEY = 'jd-publish'
export const JD_PUBLISH_DENIED_TEXT =
'当前账号没有「商品上架」权限,请联系管理员在后台「用户管理 → 菜单权限 → 桌面端」里勾上「商品上架」'
export type JdPublishAccess = 'allowed' | 'denied' | 'unknown'
/** 权限键是否覆盖「商品上架」:组键命中(预授权授的是组行)或子键命中都算。 */
export function canUseJdPublish(keys: ReadonlyArray<string> | null | undefined): boolean {
const allowed = new Set(
(keys ?? []).map((key) => String(key ?? '').trim().toLowerCase()).filter(Boolean),
)
return allowed.has(JD_PUBLISH_GROUP_KEY) || allowed.has(JD_PUBLISH_COLUMN_KEY)
}
/**
* 路由判据:拿到键集(可能为空数组=真没权限)⇒ allowed/denied;
* 拿不到键集(接口失败/超时,调用方传 null)⇒ unknown(放行,服务端 403 兜底)。
*/
export function resolveJdPublishAccess(keys: ReadonlyArray<string> | null): JdPublishAccess {
if (keys === null) return 'unknown'
return canUseJdPublish(keys) ? 'allowed' : 'denied'
}
@@ -0,0 +1,127 @@
/**
* 京东上架「发到哪一家店」(2026-11-24 客户口径:「如果没有店铺登入情况 软件怎么知道我们要上架
* 是哪一个店铺?」)。
*
* 三份身份,各有唯一出处,三层同一标记:
* 1. **来源店铺**=所勾商品行的 `shopName/shopId`(京东数据库快照)。服务端建单时按它做
* 「一单只能发到一家店」校验(`JdPublishTaskService.resolveSingleShop`),并把它钉进
* 任务载荷与明细下发(`JdPublishItemsPageVo.shopId/shopName`);
* 2. **京麦当前登录店铺**=桥 `get_jd_shop_info` 现拉(客户端起有头浏览器读京麦首屏),
* 不是页面缓存、也不是上次「同步分类」的残留;本页只拿它做提前告知;
* 3. **最终强拦截**=客户端发布前用任务记录的店铺再核一次(`JdPublishPage.verify_shop`),
* 不一致先上报标记再中止,服务端 `JdPublishStaleTaskService` 命中即整单判死——一条都不发。
*
* 本文件是纯函数(node --test 直测):只产状态与中文文案,复选框禁用/错误条/提示色由调用方选。
*/
/** 判据标记:客户端 `SHOP_MISMATCH_MARK`、服务端 `JdPublishStaleTaskService.SHOP_MISMATCH_MARK` 同值。 */
export const SHOP_MISMATCH_MARK = '京东店铺不匹配'
export interface JdShopRef {
shopId?: string
shopName?: string
}
/** 来源店铺的最小子集(只要这两个字段,页面传 `JdPublishProductVo[]` 进来即可)。 */
export interface JdShopSource {
shopId?: string
shopName?: string
}
export type JdShopGuard =
/** 勾选的商品没带店铺信息(旧数据/未勾选)⇒ 页面不拦,交给客户端与服务端兜底 */
| { state: 'unknown' }
/** 有来源店铺、还没检测京麦 ⇒ 提示可检测(不拦) */
| { state: 'undetected'; expected: JdShopRef }
| { state: 'match'; expected: JdShopRef; actual: JdShopRef }
| { state: 'mismatch'; expected: JdShopRef; actual: JdShopRef; message: string }
/** 勾选的商品来自多家店 ⇒ 服务端也会拒(按店分开勾) */
| { state: 'multi'; shops: JdShopRef[]; message: string }
function text(value: unknown): string {
return String(value ?? '').trim()
}
/** 归一化店铺身份:两名皆空返回 null(把「没记录」和「记录了空串」当同一件事)。 */
export function normalizeShopRef(raw: JdShopRef | null | undefined): JdShopRef | null {
const shopId = text(raw?.shopId)
const shopName = text(raw?.shopName)
if (!shopId && !shopName) return null
return { ...(shopId ? { shopId } : {}), ...(shopName ? { shopName } : {}) }
}
/** 人读标签:`家居日用数据库店(shopId=228346061)`,缺一半只报有的那半。 */
export function shopLabel(raw: JdShopRef | null | undefined): string {
const shop = normalizeShopRef(raw)
if (!shop) return '未记录店铺'
if (shop.shopName && shop.shopId) return `${shop.shopName}(shopId=${shop.shopId})`
if (shop.shopName) return shop.shopName
return `shopId=${shop.shopId}`
}
/**
* 勾选商品的来源店铺去重(id 优先、回退店名):同一家店的不同行只算一家,
* 顺序按勾选先后稳定输出(页面文案不会因 Map 重排跳字)。
*
* 跨形状归一:库存里有行带 id、有行只带店名(快照字段缺失),both 指同一家店时
* 必须并成一条并补齐缺的字段——否则页面对同店勾选误报「来自多个店铺」。
*/
export function sourceShopRefs(products: ReadonlyArray<JdShopSource> | null | undefined): JdShopRef[] {
const refs: JdShopRef[] = []
for (const product of products ?? []) {
const shop = normalizeShopRef(product)
if (!shop) continue
const existing = refs.find((ref) => (shop.shopId && ref.shopId === shop.shopId)
|| (shop.shopName && ref.shopName === shop.shopName))
if (existing) {
if (shop.shopId && !existing.shopId) existing.shopId = shop.shopId
if (shop.shopName && !existing.shopName) existing.shopName = shop.shopName
continue
}
refs.push({ ...shop })
}
return refs
}
/** 不匹配整句:开头即标记,点名「勾选的店」与「京麦现在登的店」,给动作句(不写「稍后重试」)。 */
export function shopMismatchMessage(expected: JdShopRef | null | undefined, actual: JdShopRef | null | undefined): string {
const expectedLabel = shopLabel(expected)
return (`${SHOP_MISMATCH_MARK}:本次勾选的商品来自「${expectedLabel}」,`
+ `当前京麦登录「${shopLabel(actual)}」;请先在京麦切换到「${expectedLabel}」再上架。`)
}
/** 跨店勾选整句(与服务端建单拒绝文案同口径:按店分开勾)。 */
export function multiShopMessage(shops: ReadonlyArray<JdShopRef>): string {
const labels = shops.map((shop) => shopLabel(shop)).join('、')
return `本次勾选的商品来自多个店铺(${labels}),一次上架只能发到一家店,请按店铺分开勾选。`
}
/** true/false=能比;null=两边都缺可比字段(只认同一维度:id 对 id、名对名)。 */
function sameShop(expected: JdShopRef, actual: JdShopRef): boolean | null {
if (expected.shopId && actual.shopId) return expected.shopId === actual.shopId
if (expected.shopName && actual.shopName) return expected.shopName === actual.shopName
return null
}
/** 页面判据:来源店铺(勾选集) vs 京麦当前登录店铺(检测结果,null=没检测/没读到)。 */
export function evaluateShopGuard(
products: ReadonlyArray<JdShopSource> | null | undefined,
detected: JdShopRef | null | undefined,
): JdShopGuard {
const refs = sourceShopRefs(products)
if (refs.length > 1) return { state: 'multi', shops: refs, message: multiShopMessage(refs) }
const expected = refs[0]
if (!expected) return { state: 'unknown' }
const actual = normalizeShopRef(detected)
if (!actual) return { state: 'undetected', expected }
const same = sameShop(expected, actual)
// 比不了(一边只有店名、另一边只有 id)不判不匹配:宁可留给客户端强拦截,也不误拦真实任务。
if (same === null) return { state: 'undetected', expected }
if (same) return { state: 'match', expected, actual }
return { state: 'mismatch', expected, actual, message: shopMismatchMessage(expected, actual) }
}
/** UI 唯一处断:命中这两档才禁「上架」按钮(unknown/undetected 不拦)。 */
export function shopGuardBlocks(guard: JdShopGuard): guard is Extract<JdShopGuard, { state: 'mismatch' | 'multi' }> {
return guard.state === 'mismatch' || guard.state === 'multi'
}
+30
View File
@@ -1,4 +1,32 @@
import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
import { JD_PUBLISH_DENIED_TEXT, resolveJdPublishAccess } from '@/pages/jd/jd-publish-access'
/**
* `/jd-publish` 直达守卫(2026-11-24 客户口径「上架的账户 我是这个权限不开给他的」)。
*
* 正常入口(京东工作台卡片)已由 filterJdToolsByPermission 隐藏,手敲地址是唯一绕过口;
* 服务端 `JdPublishPermissionSupport` 仍是一律 403 的硬边界,这里只把「进得去但处处报错」
* 换成一句可执行的中文提示 + 回工作台。
*
* 权限接口失败(拿不到键集)⇒ unknown 放行:后管账号体系里「读不到」不等于「没权限」,
* 抖一下把人锁住比让它落到后端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。
*/
export async function guardJdPublishRoute(): Promise<true | { path: string }> {
let keys: string[] | null = null
try {
keys = await getCurrentUserAppColumnKeys()
} catch (error) {
keys = null
console.error('[router] 读取菜单权限失败,/jd-publish 按放行处理:%s',
error instanceof Error ? error.message : String(error))
}
if (resolveJdPublishAccess(keys) !== 'denied') return true
ElMessage.warning(JD_PUBLISH_DENIED_TEXT)
return { path: '/jd-console' }
}
/**
* 数富AI 桌面前端 SPA 路由(无 .html 后缀)
@@ -82,6 +110,8 @@ const routes = [
path: '/jd-publish',
name: 'jd-publish',
component: () => import('@/pages/jd/JdPublishTab.vue'),
// 菜单权限未开通「商品上架」的账号手敲地址也进不来(详见 guardJdPublishRoute)
beforeEnter: guardJdPublishRoute,
},
{
path: '/split',
@@ -221,6 +221,22 @@ export interface PywebviewApi {
code?: string;
error?: string;
}>;
/**
* 京麦当前登录店铺(2026-11-24 客户口径「软件怎么知道我们要上架是哪一个店铺?」):
* 执行体 `amazon/jd/shop_categories.py::fetch_shop_info` 与「同步分类」共用同一个首屏
* 窗口,但**不等分类包**——店名/ID 到手即返回(分类档才等分类)。成功带
* `shopName/shopId`;失败 code 分档 jd_busy(京东任务在跑)/ jd_login(京麦未登录)/
* jd_page(读不到店铺信息:页面结构变更或落登录页)。
* 老客户端没有这个方法 ⇒ 页面置灰检测按钮并提示升级(发布前的强拦截在客户端执行器里,
* 不依赖本页检测)。
*/
get_jd_shop_info?: () => Promise<{
success: boolean;
shopName?: string;
shopId?: string;
code?: string;
error?: string;
}>;
/**
* 京麦登录窗自动触发链路(2026-11-23「登录京麦」按钮退役,原 2026-11-20 独立登录
* 入口):起本机京东采集专用浏览器、停在京麦登录页等人工登录(执行体在客户端
@@ -113,7 +113,12 @@ const BASELINE = {
// resubmitTask 包住重新提交请求——失败 ElMessage.error 当场把服务端文案报给用户、
// 成功 ElMessage.success 并刷新看板;确认框的取消走 `error === 'cancel'` 直接 return。
// 非静默(块内有用户可见出口),silent 一格没涨、perFile 无新增条目,只进 blocks。
blocks: 335,
// 336 = 335 + 1(2026-11-24 京东上架「发到哪一家店」+按账号授权):router/index.ts 的
// guardJdPublishRoute 包住 app 菜单权限读取——接口失败/超时按 unknown 放行(keys=null),
// 原文只进 console;「读不到权限」不等于「没权限」,把有权限的人锁在门外比放进去后被
// 服务端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。非静默:
// 首条语句是状态写入、不是 console.*,silent 一格没涨、perFile 无新增条目,只进 blocks。
blocks: 336,
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
+162
View File
@@ -0,0 +1,162 @@
import assert from 'node:assert/strict'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import test from 'node:test'
import {
canUseJdPublish,
JD_PUBLISH_DENIED_TEXT,
resolveJdPublishAccess,
} from '../src/pages/jd/jd-publish-access.ts'
import {
evaluateShopGuard,
normalizeShopRef,
shopGuardBlocks,
shopLabel,
shopMismatchMessage,
SHOP_MISMATCH_MARK,
sourceShopRefs,
} from '../src/pages/jd/jd-publish-shop.ts'
/**
* 2026-11-24 客户口径两件(京东「商品上架」):
* 1. 「如果没有店铺登入情况 软件怎么知道我们要上架是哪一个店铺?」——页面必须显形
* 来源店铺与京麦当前登录店铺,不一致强拦截;
* 2. 「上架的账户 我是这个权限不开给他的」——按账号授权:入口隐藏(卡片过滤)+
* 直达路由守卫+服务端 403 三层。
*
* 本文件管纯判据与源码绊线;页面接线由 tests/mount/jd-publish-dispatch.mount.test.ts 覆盖。
*/
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('来源店铺按 id 去重、同名单店归一、空值全部丢弃', () => {
const refs = sourceShopRefs([
{ shopId: ' 228346061 ', shopName: ' 家居日用数据库店 ' },
{ shopId: '228346061', shopName: '家居日用数据库店' },
{ shopId: '', shopName: '家居日用数据库店' },
{ shopName: '花屿巷旗舰店' },
{ shopId: null, shopName: ' ' },
{},
])
assert.deepEqual(refs, [
{ shopId: '228346061', shopName: '家居日用数据库店' },
{ shopName: '花屿巷旗舰店' },
], '同一家店不同行只算一家;店名回退 id 时不能把空 id 当身份')
})
test('同一家店两种形状(只有 id / 只有店名)在来源集里能归一', () => {
// id 口径优先:一行有 id 一行只有名字时,页面无法确定同店,按两家报出来让用户分开勾
const refs = sourceShopRefs([{ shopId: '1' }, { shopName: '某店' }])
assert.equal(refs.length, 2)
})
test('店铺标签:名+id 全显示,缺一半只报有的那半,全空=未记录店铺', () => {
assert.equal(shopLabel({ shopId: '1', shopName: '某店' }), '某店(shopId=1)')
assert.equal(shopLabel({ shopName: '某店' }), '某店')
assert.equal(shopLabel({ shopId: '1' }), 'shopId=1')
assert.equal(shopLabel(null), '未记录店铺')
assert.equal(normalizeShopRef({ shopId: ' ' }), null)
})
test('不匹配文案:标记开头、点名两家店、给动作句且不写「稍后重试」', () => {
const message = shopMismatchMessage(
{ shopId: '228346061', shopName: '家居日用数据库店' },
{ shopId: '165515933', shopName: '花屿巷旗舰店' },
)
assert.ok(message.startsWith(SHOP_MISMATCH_MARK))
assert.ok(message.includes('家居日用数据库店') && message.includes('228346061'))
assert.ok(message.includes('花屿巷旗舰店') && message.includes('165515933'))
assert.ok(message.includes('切换'))
assert.ok(!message.includes('稍后重试'), '确定性失败不允许写「稍后重试」')
})
test('判据四态:未勾选 unknown / 未检测 undetected / 同店 match / 异店 mismatch', () => {
assert.equal(evaluateShopGuard([], { shopId: '1' }).state, 'unknown')
assert.equal(evaluateShopGuard([{ shopId: '1' }], null).state, 'undetected')
const match = evaluateShopGuard([{ shopId: '1', shopName: '某店' }], { shopId: '1', shopName: '某店' })
assert.equal(match.state, 'match')
const mismatch = evaluateShopGuard([{ shopId: '1', shopName: '某店' }], { shopId: '2', shopName: '别店' })
assert.equal(mismatch.state, 'mismatch')
assert.ok(shopGuardBlocks(mismatch))
assert.ok(!shopGuardBlocks(match) && !shopGuardBlocks(evaluateShopGuard([], null)))
})
test('id 优先于店名:id 不同但同名也不放行', () => {
const guard = evaluateShopGuard([{ shopId: '1', shopName: '同名店' }], { shopId: '2', shopName: '同名店' })
assert.equal(guard.state, 'mismatch')
})
test('只有店名时按店名比对;比不了(一边只有 id)按未检测处理,不误拦', () => {
assert.equal(evaluateShopGuard([{ shopName: '某店' }], { shopName: '某店' }).state, 'match')
assert.equal(evaluateShopGuard([{ shopName: '某店' }], { shopName: '别店' }).state, 'mismatch')
assert.equal(evaluateShopGuard([{ shopId: '1' }], { shopName: '某店' }).state, 'undetected')
})
test('跨店勾选直接拦,文案与服务端建单拒绝同口径(按店分开勾)', () => {
const guard = evaluateShopGuard([{ shopId: '1', shopName: '甲店' }, { shopId: '2', shopName: '乙店' }], null)
assert.equal(guard.state, 'multi')
assert.ok(shopGuardBlocks(guard))
if (guard.state === 'multi') {
assert.ok(guard.message.includes('甲店') && guard.message.includes('乙店'))
assert.ok(guard.message.includes('分开勾选'))
}
})
// ---------------------------------------------------------------- 菜单权限判据
test('权限判据:组键 jd_tools 或子键 jd-publish 命中即放行(大小写/空白归一)', () => {
assert.ok(canUseJdPublish(['jd_tools']))
assert.ok(canUseJdPublish([' JD-PUBLISH ']))
assert.ok(!canUseJdPublish(['jd-collect']), '只授「获取店铺数据」不包含「商品上架」')
assert.ok(!canUseJdPublish([]))
assert.ok(!canUseJdPublish(['jd_tools_extra']), '前缀相近不算命中')
})
test('路由判据三态:拿到空键集=denied,拿不到键集(接口失败)=unknown 放行', () => {
assert.equal(resolveJdPublishAccess(['jd-collect']), 'denied')
assert.equal(resolveJdPublishAccess(null), 'unknown')
assert.equal(resolveJdPublishAccess(['jd-publish']), 'allowed')
assert.ok(JD_PUBLISH_DENIED_TEXT.includes('菜单权限'))
assert.ok(JD_PUBLISH_DENIED_TEXT.includes('商品上架'))
})
// ---------------------------------------------------------------- 源码绊线(接线不许漏)
test('上架页显形来源店铺与京麦当前店铺,并在建单前核对', () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
assert.ok(tab.includes('get_jd_shop_info'), '页面必须调桥 get_jd_shop_info 现拉京麦当前店铺')
assert.ok(tab.includes('ensureShopChecked'), '建单前必须走店铺核对(strong block)')
assert.ok(tab.includes('shopGuardBlocks'), '不匹配/跨店必须禁掉上架按钮')
assert.ok(tab.includes('product.shopName'), '商品行要显形自己的来源店铺')
const createAt = tab.indexOf('createJdPublishTask(')
const checkAt = tab.indexOf('await ensureShopChecked()')
assert.ok(checkAt > 0 && createAt > checkAt, '核对必须早于建单')
})
test('上架页不得自己拼店铺身份(只用勾选商品快照 + 桥结果)', () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
assert.ok(!/shopId\s*=\s*['"]\d+/.test(tab), '页面不得写死任何 shopId')
assert.ok(!tab.includes('jd-shop-info'), '页面不得自拼店铺读取 URL(唯一口是桥)')
})
test('/jd-publish 直达路由挂权限守卫,权限接口失败按放行处理', () => {
const router = read('src/router/index.ts', 'router/index.ts')
assert.ok(router.includes('resolveJdPublishAccess'), '路由必须用统一判据模块')
assert.ok(/path: '\/jd-publish'[\s\S]{0,200}?beforeEnter:/.test(router), '/jd-publish 缺 beforeEnter 守卫')
assert.ok(router.includes('getCurrentUserAppColumnKeys'), '守卫必须读当前用户 app 列权限')
assert.ok(router.includes("path: '/jd-console'"), '没权限时回工作台(那里只显示有权限的卡片)')
})
test('桥类型声明 get_jd_shop_info(老客户端按缺方法置灰)', () => {
const bridge = read('src/shared/bridges/pywebview.ts', 'pywebview.ts')
assert.ok(bridge.includes('get_jd_shop_info?:'), 'PywebviewApi 缺 get_jd_shop_info 声明')
})
@@ -10,7 +10,7 @@ import {
const api = vi.hoisted(() => ({
create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(),
history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(),
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(),
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(), shop: vi.fn(),
}))
vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups }))
@@ -357,3 +357,78 @@ it('源商品身份缺失形状已被客户端放行,提示维持换店或重
await page.get('.history-btn').trigger('click')
expect(page.text()).not.toContain('非在售商品')
})
// ---- 店铺核对(2026-11-24 客户口径「软件怎么知道要上架哪一家店铺」)----
// 桥 get_jd_shop_info 现拉京麦当前登录店铺;与勾选商品的来源店铺不一致 ⇒ 页面强拦截,一条都不建单。
// 老客户端没有这个方法(默认替身就不带)⇒ 不拦,最终拦截由客户端执行器与服务端完成。
type ShopBridgeResult = {
success: boolean; shopId?: string; shopName?: string; code?: string; error?: string
}
function withShopBridge(result: ShopBridgeResult) {
api.bridge.mockReturnValue({
jd_publish_protocol: api.protocol, enqueue_json: api.enqueue, get_jd_shop_info: api.shop,
})
api.shop.mockResolvedValue(result)
}
it('京麦登录的不是勾选商品的店铺时不建单,并点名两家店', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '165515933', shopName: '花屿巷旗舰店' })
const page = await mountPage()
await page.get('.target-brand-input').setValue('示例品牌')
await page.get<HTMLInputElement>('.product-check').setValue(true)
// 勾选后不检测:按钮仍可点(未检测不拦),点下去才开始核对
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(false)
await page.get('.collect-btn').trigger('click')
await flushPromises()
expect(api.shop).toHaveBeenCalledOnce()
expect(api.create).not.toHaveBeenCalled()
expect(api.enqueue).not.toHaveBeenCalled()
expect(page.text()).toContain('京东店铺不匹配')
expect(page.text()).toContain('家居日用数据库店')
expect(page.text()).toContain('花屿巷旗舰店')
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(true)
})
it('京麦与来源店铺一致时照常建单', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await startPublish(page)
expect(api.shop).toHaveBeenCalledOnce()
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '示例品牌')
expect(page.text()).toContain('店铺一致')
})
it('检测过且一致后不再重复起浏览器', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await page.get<HTMLInputElement>('.product-check').setValue(true)
await page.get('.shop-detect-btn').trigger('click')
await flushPromises()
expect(api.shop).toHaveBeenCalledOnce()
await startPublish(page)
expect(api.shop).toHaveBeenCalledOnce()
expect(api.create).toHaveBeenCalledOnce()
})
it('京麦未登录时给登录指引,不静默建单', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: false, code: 'jd_busy', error: '京东任务正在运行,请稍后再试' })
const page = await mountPage()
await startPublish(page)
// jd_busy 档:不硬拦(任务可能在收尾),页面给 amber 说明;建单继续,最终拦截在客户端
expect(api.create).toHaveBeenCalledOnce()
expect(page.text()).toContain('京东任务正在运行')
})
@@ -0,0 +1,47 @@
import { beforeEach, expect, it, vi } from 'vitest'
/**
* `/jd-publish` 直达权限守卫(2026-11-24 客户口径「上架的账户 我是这个权限不开给他的」)。
*
* 正常入口(京东工作台卡片)已被 `filterJdToolsByPermission` 隐藏,手敲地址是唯一绕过口;
* 这里直测守卫本体,不导航(导航会顺带拉起页面组件、发一堆真实请求)。
* 三层口径:入口隐藏 + 本守卫 + 服务端 `JdPublishPermissionSupport` 403(唯一权威判据)。
*/
const api = vi.hoisted(() => ({ columnKeys: vi.fn() }))
vi.mock('@/shared/api/permission', () => ({ getCurrentUserAppColumnKeys: api.columnKeys }))
vi.mock('element-plus', async (importOriginal) => ({
...await importOriginal<typeof import('element-plus')>(),
ElMessage: { warning: vi.fn(), error: vi.fn(), success: vi.fn() },
}))
const { guardJdPublishRoute } = await import('@/router/index')
const { ElMessage } = await import('element-plus')
beforeEach(() => {
api.columnKeys.mockReset()
vi.mocked(ElMessage.warning).mockClear()
vi.spyOn(console, 'error').mockImplementation(() => undefined)
})
it('没开通「商品上架」的账号手敲 /jd-publish 被挡回京东工作台并给中文提示', async () => {
api.columnKeys.mockResolvedValue(['jd-collect'])
expect(await guardJdPublishRoute()).toEqual({ path: '/jd-console' })
expect(ElMessage.warning).toHaveBeenCalledOnce()
expect(String(vi.mocked(ElMessage.warning).mock.calls[0][0])).toContain('商品上架')
})
it('组键 jd_tools 或子键 jd-publish 命中都放行', async () => {
api.columnKeys.mockResolvedValue(['jd_tools'])
expect(await guardJdPublishRoute()).toBe(true)
api.columnKeys.mockResolvedValue(['jd-collect', 'jd-publish'])
expect(await guardJdPublishRoute()).toBe(true)
expect(ElMessage.warning).not.toHaveBeenCalled()
})
it('权限接口失败按放行处理(读不到 ≠ 没权限,后端 403 仍是硬边界)', async () => {
api.columnKeys.mockRejectedValue(new Error('timeout'))
expect(await guardJdPublishRoute()).toBe(true)
expect(ElMessage.warning).not.toHaveBeenCalled()
})