21 Commits

Author SHA1 Message Date
zwork 1524099d3b feat(admin): 分类管理弹窗列表加表头(2026-11-18 用户红框口径)——搜索行与分类列表之间加一行淡色列名「分类名称|商品数|操作」,与数据行同构对齐(同 gap/同左右内边距,商品数吃徽标同宽、操作同 margin-left:auto 靠右);只在列表有数据时渲染,空态/加载中不出;同组普通号只读口径行内无写按钮,操作列表头随之不渲染;表头在滚动列表外,翻页滚动固定。判据:vue-tsc rc0+jd-category-manage-dialog.mount 21/21 绿 2026-11-18 13:41:49 +08:00
zwork bd6f2cdc91 fix(ledger): PageDefaultsLedgerTest 补记 v1.5 Phase 4 三出站点(整量 mvn -o test 抓到,发版前必绿)——917884aa 的 JdPublishController 读侧新增 page=FIRST_PAGE+page_size=JD_PRODUCTS_PAGE_SIZE(products 选品分页)与 limit=DEFAULT_RESULT_LIMIT(history 任务历史)三处出站点,台账没随行:named ledger 59→62、page 口径 26→27、文案与注释同步;单跑 6/6 绿 2026-11-18 13:04:32 +08:00
zwork 84c664c795 feat(platform): 后管菜单平台隔离收窄+列表密度收口(2026-11-18 用户截图口径「密钥管理与密钥用量统计仅亚马逊侧;菜单配置展示树按当前平台先裁剪再展平分页」)——①双侧共用清单四件收窄:AdminMenuPlatformScope.BOTH_MENU_KEYS(后端唯一出处)与 admin platform-scope.ts BOTH_PLATFORM_MENU_KEYS 同源去掉 admin_user_secrets/admin_user_secret_usage,密钥两页京东侧不再下发也不可配;②菜单管理页:全树字典保留(授权数据不动),展示树与父级候选走 filterMenuTreeNodesByPlatform 先裁剪再展平分页,切平台清筛选回页1并关弹窗;③列表密度收口:顶栏 76→56、内容区留白 30/32→12/16、筛选行 flex 换行紧凑、表格行距 6px、按钮/输入 34px 同高,三档响应式断点(1440/820/560,窄屏菜单项不再整体隐藏);task-243 顶栏 56px 断言随行、task-244 新钉六条紧凑断言与「窄屏不许 display:none 菜单项」反向钉。判据:AdminMenuPlatformScopeTest 11+AdminConsoleCurrentUserMenusPlatformTest 3(后端点名绿)+vue-tsc rc0+node --test 35+npx vitest run 全量 188/188 rc0(新增 menu-manage-platform.mount 3 支:京东侧菜单配置页无亚马逊项、保留账号域四件与京东工具、密钥页归亚马逊)+快检 overall=pass 四面绿(2026-11-18 12:5x,Git PATH 前置壳) 2026-11-18 12:47:39 +08:00
zwork 917884aa6d feat(phase-4): 京东商品上架用户端页(v1.5 蓝图 docs/ITERATION_PLAN.md §4 Phase 4)——JdPublishTab(分类 jdCollect.groups 唯一源→选品分页 owner 过滤→跨页勾选→改价三档→建单 queuePayload 直推→useLiveTaskBoard 行级面板+credential-fatal 同形接入)+tool-catalog 占位卡转正式+router 注册;后端面板读侧 JdCollectController 同形五端点(products/dashboard/history/progressBatch/delete)+JdPublishBoardService(无 scope_state,进度真源=明细行级四档)+JdProductQueryService.pageForUser(归属表两步下推不夹原生 SQL);激活 Phase 0 预置 5 支 Pending 契约;判据:JdPublishBoardServiceTest 5+JdProductQueryServiceUserPageTest 4+outlet 分母 138/72(写+2 读+3 随面板端点)、endpoints 冻结快照+progress/batch 清单+1、终态窄集合台账+JdPublishTab 1、catch 块 319→324 全非静默、占位 mount 锁翻转两条断言;vue-tsc rc0、用户端 node --test 1078/1078+vitest mount 90/90、后端点名 6 类 41 例 BUILD SUCCESS、快检四面格(后端 9.5/客户端 10.0/用户端 9.6)绿,唯一红格=后管 mount 组件挂载格,甄别=他窗在飞 admin 件输出含 failed 子串触发 ruler vfail 脆弱判据(实跑 cmd /c npx vitest run RC=0、188/188 全过,本笔零后管文件) 2026-11-18 12:23:27 +08:00
huangzd1997 b5578561df fix(guardrails): 京东上架五守卫格整量补记(24272a91 点名 87 例没跑整量、两处账本与四个分母漏记,2026-11-18 发版前整量 5689 例抓到)——①TaskFailureCategoryGuardrail B51-R1:JdPublishIngestService.summarizeTerminal 文案先落局部变量 message 再配对写列(原来三元里各写各的表达式被「写的列与文案不是同一个来源」判红;CollectDataService failTask 正本形状同源);②ApiGuardCoverageAuditor PENDING_CONVERGENCE 登记 /api/jd-publish(与 /api/jd-collect 逐形状同族:建单等五端点 requireOwnershipUserId fail-closed、chunk 判死口凭据化 isTrustedInternalToken 匿名拒绝判死、JdPublishChunkRequest 不带 userId 不进身份扫描);③RequestSuppliedIdentityOutletTest 写类分母 133→136(建单 DTO 形+activate+heartbeat 三支)、读类 67→69(items+progress 两支),chunk 不计入(留痕注释);④MigratedSqlEquivalenceTest XML_SELECT_TOTAL 103→105+NOT_MIGRATED 点名 JdPublishItemMapper#selectPublishableItems/countByPublishStatus;⑤SqlLayeringConventionTest XML_STATEMENT_TOTAL 147→149。判据:点名 5 类 34/34 绿+整量 5689 例(0 失败/19 skip)BUILD SUCCESS 9:51min——修复 jar 与平台隔离 jar 同窗 2026-11-18 02:56:14 +08:00
huangzd1997 1105320354 fix(admin-shell): 壳层锁视口高——侧边栏固定、菜单区独立滚动条(2026-11-18 用户口径「菜单加个滚动条吧 不然滚动下来 又侧看不见了」)——根因=.admin-shell 用 min-height:100vh 让整条 flex 高度链失去确定性:.admin-menu-scroll(flex:1) 内的 el-scrollbar(内部 height:100% 需父级定高)与 .admin-content(现成 overflow:auto)双双失效、滚动回落整页滚,侧边栏顶部品牌区/平台 tab 被滚出视口;改 height:100vh+overflow:hidden 后侧边栏定视口高、菜单区自出滚动条、内容区独立滚动、顶栏固定(html/body/#app L33 已 height:100% 无需动;不删任何现有声明,task-243 钉的 sidebar 252px/topbar 76px/渐变全兼容)。判据:task-243 首用例新增三条绊线断言(.admin-shell 必须 height:100vh+overflow:hidden、不得回退 min-height:100vh,改回即红;在既有用例内加断言行不新增 test 块/read 点,source-pin 棘轮钉子=460/读点=658 与基线逐字同零台账变化);vue-tsc rc=0;node --test task-243/4/242/棘轮 30/30;快检 overall=pass 四面绿(后端 9.5/后管 8.8/客户端 10.0/用户端 9.6)。纯 CSS 改动随下一窗口后管发版生效,真机目检登录后滚动菜单即见 2026-11-18 02:17:18 +08:00
huangzd1997 8ac9fafb7b feat(jd-database): 分类状态快筛加「全部」档(2026-11-18 用户口径「加个全部选项」,默认仍卡未分类)——三档下拉(全部/已分类/未分类),「全部」value='' 选中即查当前分组全部商品:序列化层对 '' 天然不下发 classified 参数(jd-product-filter toJdProductFilterQuery 单一出口,''/缺省/脏值同走该兜底)=后端 required=false 收 null=JdProductMapper.xml <if test="classified != null"> 跳过谓词,后端零改动;出厂默认与「重置」仍卡「未分类」(11-17 用户口径不动,jdProductFilterActive 对 '' 仍按未激活处理);「全部」选项与「全部分类」下拉的 value='' 全量出口同形。判据:mount jd-database-page 三档断言(['全部','已分类','未分类'] 精确数组,改回两档即红)+新增「选全部→请求不带 classified 键」行为用例+重置仍回未分类;jd-product-group 纯测试形状不变仍绿;vue-tsc rc=0;node --test 14/14;vitest mount 43/43;快检 overall=pass 四面绿(后端 9.5/后管 8.8/客户端 9.8/用户端 9.6)。纯前端改动随下一窗口后管发版生效 2026-11-18 01:56:08 +08:00
huangzd1997 2a8bdd7d29 feat(platform): 后管与桌面端菜单按用户平台隔离(2026-11-18 用户口径「隔离下除 admin 外,京东用户只看京东菜单、亚马逊看不了」)——AdminMenuPlatformScope 成为菜单 key→平台归属唯一出处(京东独占 admin_jd_database+app 三件;双侧六件=账号域基础三页+本笔补侧的菜单权限配置/密钥管理/密钥用量统计;未知 key 默认 amazon 与前端 platform-scope 同形;platform null/空白归一 amazon=列 DEFAULT 同口径,不把「没带」读成京东侧全拦),filterMenuVosByPlatform 扁平过滤保留祖先链保组树完整、分组节点按存活子项去留(与前端 filterMenuTreeNodesByPlatform 同形);裁剪只挂三个下发出口(current-user/menus 非站点超管按 users.platform 收窄+登录 VO adminColumns/appColumns 双树=后管+桌面端一起)与逐页门(requireConsolePageAccess 平台门置于 isAdmin 直通之前,越侧 key 一律 403),红线=不动 getUserColumnPermissions 本体(授权编辑读接口与整树替换保存语义不变、授权行保留);current-user 增 platform 键;前端 allowedPlatformsForUser(超管随菜单树分布、其余锁 users.platform 侧、未知/缺省兜底 amazon、交集空仍锁死本人平台)+AdminLayout watch clamp(localStorage 残留另一侧自动归位、当前页在被禁侧跳回本人平台第一可见页、单侧时 tab 条整个隐藏)+platform-tab.syncToAllowed;app 树 37 key 全集核对无平台无关 key(withdraw=取款挂品牌运营工具、erp/purchase 挂后勤工具)。判据:AdminMenuPlatformScopeTest 11+ConsolePageTest +5 平台门+AdminConsoleCurrentUserMenusPlatformTest 3+AuthServicePlatformMenuTest 3+CompanyTest +1 platform 键=43 例绿;前端 platform-menu-filter 9/9(+2)、mount admin-layout-platform-lock 4/4、授权树过滤对齐扩双侧;vue-tsc rc=0;node --test 1937/1938(唯一红=在册 B116-03 ENOENT);vitest mount 184/184;mvn -o test-compile rc=0;快检后端 2 红格=环境假红(缺 Git 工具链 PATH,前置后 30/30 绿)、四面可读棘轮红=PermissionMenuService 1661→1676 行随本笔点名记账(ops 仓同窗);桌面端界面随 appColumns 下发生效,客户端出包另窗 2026-11-18 01:28:49 +08:00
huangzd1997 24272a910c feat(phase-2): 京东商品上架后端地基(v1.5 蓝图 docs/ITERATION_PLAN.md §4 Phase 2)——V210 发布明细表 biz_jd_publish_item(号段实核:V207~V209 已按序占用)+JdPublishTaskService 建单/配额/归属/生命周期(建单即落快照行,AC-8 配额闸前置、AC-9 他人商品 403、铁律 27a 改价同源、铁律 19 LOCAL 显式写)+items 分批下发(SQL 侧下推只出 PENDING 行=AC-4 断点服务端半边,图片 jd-products 预签名 GET 新开 presignObjectDownload 出口)+JdPublishIngestService chunk 行级回传(isEnd 按行级真源汇总终态,铁律 31 分档判死口凭据化)+JdPublishStaleTaskService 判死(JdStaleTaskService 同形,60 分钟 aiimage.jd.publish.stale-minutes)+派发三件套(SPI jd-product-publish-run+白名单 JD_PUBLISH+建单响应 queuePayload,铁律 32)+JdPublishTaskHeartbeatSpi override ensureOwnership(B98-07 同形债预防:SPI 轻校验+服务层用户域归属闸,LOCAL 客户端心跳实例域不适用)+registry/EXPECTED_MODULES/清理清单/CollectChannel.LOCAL_DEFAULT_MODULES 四清单同步;激活 JdPublishContractPendingTest 7 支 Pending 契约全绿。判据:点名 12 类 87 例 BUILD SUCCESS(契约 8+建单 14+回传 11+判死 3+schema V210 格+coverage/golden/channel/pull-spi/migration 各格);mvn -o test-compile rc=0;可读棘轮 OssStorageService 1161→1176 行随本笔点名更新(presignObjectDownload +15);LockSkipWitness 分母 30→32、覆盖文件 12→13(JdPublishStaleTaskService 两处留痕,ops 仓同窗更新);快检后端 9.5/用户端 9.6 绿、唯一 fail 红格=后管 readSource 属他窗在飞 align-group-editor 用例 10→13(本笔零后管文件);真机带库整链(V210 实跑)随 Phase 5 发版窗口 2026-11-18 00:31:53 +08:00
huangzd1997 f4bde32f83 feat(admin): 新建分组组长可下拉选(2026-11-18 用户口径「组长不能下拉选吗」)——组长原为只读回显当前登录用户(2026-10-07 对齐 admin.js 的有意设计);后端 validateLeaderOperator 对站点超管本就放行任意 createdById(只要求组长与操作者同公司 ensureLeaderSharesOperatorCompany),故纯前端落地:新建+站点超管出 filterable 下拉(候选=本公司账号,公司超管永不领衔、站点超管仅保留操作者本人,管理员/普通账号均可领衔);组长改选联动两件事——组员候选按新组长重算(eligibleGroupMembers 已吃 leaderUserId)+ 把新组长从已选组员里摘掉(后端「组长不能作为组员重复加入分组」);创建提交 createdById=所选组长;编辑与非超管新建保持只读(后端更新载荷不收组长/强制组长=操作者本人);编辑历史行缺 leaderUserId 保持 null 口径不回落当前登录人(组员候选过滤不悄悄变)。判据:align_group_leader_candidates_* 3 支新模型用例+ui_wiring 改钉新形状(v-if=canPickLeader/v-else 只读回显/createdById=leaderId/companyTab 绊线保留)+platform-account-pages 调用形状同步;vue-tsc rc=0;node --test 39/39(align-group-editor 13+task-253 8+platform-account-pages 10+task-268 8) 2026-11-18 00:27:04 +08:00
huangzd1997 885fa813db feat(admin): 侧边栏父菜单默认全展开+mount 断言对齐标题去后缀(2026-11-17 用户口径「父菜单不要默认折叠」)——menu-mapper 的 groupKeysForActive(按激活路由命中展开)换 allGroupKeys(全部分组);AdminLayout 对 entries 变更命令式补开(el-menu 的 default-openeds 只在挂载读一次,平台 tab 切换/菜单树刷新后新分组不会自动展开;watch 里读当下 computed 而非触发快照,快速连切 tab 不补开已离开渲染树的旧分组——el-menu 的 open 对未注册 index 会抛);用户手动收起的组在 entries 不变期间保持收起。判据:task-6 8 例(allGroupKeys 全展开/顶级叶不产键/空菜单空键+壳层绊线:groupKeysForActive 回流即红、watch(openedKeys)+nextTick 缺一即红);mount 京东页「分类管理」断言对齐 ea9dca3f 标题去后缀(那笔漏改的存量红);vue-tsc rc=0;node --test 1932/1933(唯一红=在册 B116-03 ENOENT);vitest mount 180/180;ops fast 闸门后管格绿(overall=fail 甄别=后端巡检格/用户端棘轮格红属 crawler-plugin 34 个在飞件,本笔不触碰后端与用户端) 2026-11-18 00:00:33 +08:00
huangzd1997 ea9dca3faf style(admin): 分类管理弹窗标题去掉「· 分组名」后缀(2026-11-17 用户口径「不要显示周丽娥」)
modal-sub span 与 .modal-sub 样式整段删除;挂载用例改反向钉(.modal-sub 不存在、分组名不进标题),翻组/直建等其余 20 例不受影响。vitest 21 例全绿+vue-tsc rc=0。
2026-11-17 23:02:22 +08:00
huangzd1997 7f76a96264 style(admin): 分类管理弹窗搜索/新建/按钮合回一排(2026-11-17 用户口径「弄成一排呗」)
340px 弹窗里垂直两行显空,三件改回一行。宽度分配先试 flex 1:1.75 实测偏移(搜索 122、新建输入只剩 105,7 字占位 115px 被截),改成搜索定宽 108px+新建行吃剩余(输入 119px),两个占位都完整。挂载用例同步为一排结构,并钉新建行只有输入框+按钮两个子元素(用户旧构建截图里多出的空框=11-15 已下线的排序输入,重新构建即消)。判据:vitest 挂载 21 例全绿+vue-tsc rc=0。
2026-11-17 22:57:23 +08:00
huangzd1997 0c4354fc1e feat(jd): 京东数据库写权限放宽到管理员级+分组筛选收超管档(2026-11-17 用户口径「超管+管理员都可以,只有普通员工不能操作」「超管可以有分组筛选,管理员及以下则没有」)——后端 requirePlatformSuperAdminWrite 改 requireJdProductWrite:平台超管/公司超管/admin 三档放行、普通账号(resolveRole=null)403「仅超级管理员或管理员可以编辑或删除京东数据库数据」(四条商品行写路由同闸;批量归类 V203 requireWritableGroup 不动);前端 canWriteProducts(isAdminRole)管操作列/批量删除/勾选列/只读提示,canFilterGroup(平台+公司超管)管筛选行「分组」控件整块显隐(管理员及以下连单组锁定芯片都不渲染,分类面静默落默认组)。判据:后端 29 例(普通账号四写 403 不触服务+admin 四写放行+公司超管放行+结构钉三档谓词与 403 文案);前端挂载 42 例(普通员工 5 列只读+无分组控件、admin 7 列全写+多组也无下拉、公司超管齐写+多组可切组、超管照旧);vue-tsc rc=0;ops fast 闸门 overall=pass 2026-11-17 22:42:15 +08:00
huangzd1997 8b0cde4a51 feat(admin): 京东数据库动作条上移+文案三刀(2026-11-17 用户截图口径)——「共X条京东商品」汇总删除;原工具栏(批量编辑分类/分类筛选/状态快筛/分类管理/批量删除)整体上移并入筛选行与查询/重置同排(.jd-toolbar 容器摘除,放不下靠 flex-wrap 折行;下拉位宽钉定改 .jd-filter-row 直接子级选择器防误伤「分组」表单下拉);「删除勾选(N)」改「批量删除(N)」、确认弹窗改「确定批量删除选中的 N 个商品吗」。行为零改动(勾选累计/权限分档/筛选语义全不动)。判据:vitest 挂载 jd-database-page 39 例全绿(文案断言同步、汇总条加反向钉)+ jd-category-manage-dialog 21 例+静态扫描 node --test 24 例+vue-tsc rc=0 2026-11-17 22:23:35 +08:00
huangzd1997 c15f0ce229 fix(jd): 采集分类默认口径改「全店采集」——占位符去「不选=」改「全店采集(点击选择分类)」、未选中提示改「默认全店采集。」(2026-11-17 用户口径「默认全店采集,不要写不选=全店采集」;选择行为零改动,空数组=全店采集的三处同键契约不动)。判据:vitest 挂载 jd-collect-progress 10 例全绿(含新占位符 prop 钉与清空恢复断言)+vue-tsc rc=0 2026-11-17 21:17:18 +08:00
huangzd1997 6ccf7f2bb3 feat(admin): 账号域四弹窗撤「所属平台」手选,平台跟随当前 tab(2026-11-17 用户截图「有京东就不需要亚马逊了阿,亚马逊那边也是」)——公司/分组/用户新建编辑弹窗不再出平台单选:新建取当前平台 tab(props.platform),编辑回填行值原样下发(后端契约与 payload 形状零改动);form.platform 仍驱动授权树按平台收窄(UserMenuAuthTree)与京东上架额度可见性(includeQuota),判定出口不动。护栏翻转:platform-account-pages「单选恒在」两处改 doesNotMatch 反向钉(写回单选即红)+ task-48 编辑弹窗按钮钉回只剩角色两枚。判据:node --test 1932/1933(唯一红=B116-03 在册环境红,参考仓 shop-finance-source 已移除)+ vitest mount 177/177 + vue-tsc rc=0 + ops fast 闸门 overall=pass。⚠ 后果登记:记录跨平台挪档的弹窗入口随之消失(B116-01 的「待用户翻档归侧」前置失效),需要时另窗补列表级动作或直改 DB。 2026-11-17 21:16:23 +08:00
huangzd1997 ae250ea182 feat(admin): 分类管理弹窗删三处说明小字(2026-11-17 用户口径「小字不需要」)——弹窗顶部「分类按数据权限分组隔离…」提示、平台超管空态引导语「京东侧还没有数据权限分组…」、组长说明「组长=你…」整段删除,空态只留直建表单本体;对应 CSS(.modal-tip/.bootstrap-lead/.bootstrap-hint)与挂载断言同步(指路句改反向钉、空态改钉表单形状、有组格改钉 .group-bootstrap 不渲染)。判据:vitest 挂载 21 例全绿+vue-tsc rc=0 2026-11-17 21:09:10 +08:00
huangzd1997 d850c46f46 fix(jd): 京东分组作用域两条取组 SQL 补 platform 投影——平台闸读不到平台档把全部组(含 jd 档)判非 jd 清空,平台超管建组建成功京东侧永不显示(2026-11-17 用户截图「咋没显示」实录)。selectAllGroups/selectLedGroups 各补 g.platform AS platform(selectAllGroups 上次 47fc0e08 补 company_id 同一条查询同款病);selectLedGroups 按先例整行摘迁移等价账本点名 NOT_MIGRATED(LEDGER_ROWS 82→81/SELECTS 58→57);ShopManageGroupScopeSqlTest 升级双事故绊线:超管投影钉 company_id+platform 两列、新增组长档投影格。判据:投影缺任一列即红(mock 掉 mapper 的服务用例照旧绿——这正是两连漏的成因);mvn -o test 三类 22 例全绿 2026-11-17 21:08:59 +08:00
huangzd1997 2a0cc86572 fix(jd/account): 用户弹窗选京东桌面端分区整组消失——V209 前台京东菜单(jd_tools/jd-collect/jd-publish)补进平台判定(2026-11-17 用户截图「前台的京东少了」)。新增 JD_APP_MENU_KEYS 与 JD_MENU_KEYS 分列:app 菜单没有 admin 路由,不得混进「与 routes.ts 对撞」的后台清单;platformsOfMenuKey 两份同认,过滤算法与授权树/侧边栏两消费方零改动。判据:user-menu-tree-platform-filter 新增桌面端分区正反两例(jd 留京东工具台整组/amazon 留亚马逊 app)+三 key 判定钉;platform-menu-filter 清单钉死用例同步 JD_APP_MENU_KEYS 形状。node --test 29 例全绿+vue-tsc rc=0 2026-11-17 20:58:54 +08:00
huangzd1997 164b9b83fa feat(jd/account): 授权树按平台过滤+平台超管空态直建京东档分组——用户弹窗选京东只发京东侧菜单(京东数据库+双侧账号域三件,platform-scope 唯一算法出口、侧边栏委托同源),翻档时另一侧勾选自动收敛(pruneCheckedIdsToTree),京东档账号不再整树混发亚马逊授权;分类管理弹窗京东侧零分组时给平台超管开直建口子(POST shop-manages/groups platform 恒 jd、组长=当前登录人),建完 group-created 让父页整条作用域重取翻到新组接着建分类,不再死在「你还不属于任何数据权限分组」(2026-11-17 用户口径「admin 权限最大」)。判据:tests/user-menu-tree-platform-filter.test.ts 钉过滤/收敛/两消费方同形(B79-12 钉法);分类管理弹窗挂载 6 例(直建表单/无登录人/失败不发事件/翻组重取/非超管维持文案/有组不出口子)+京东页挂载 2 例页面级链路;vue-tsc rc=0 2026-11-17 18:59:35 +08:00
111 changed files with 6760 additions and 405 deletions
@@ -19,24 +19,61 @@ export const PLATFORM_TABS: readonly PlatformTabDef[] = [
* 2026-11-17 晚:分类管理子菜单(admin_jd_category_manage,V204)随「京东分类管理并到
* 京东数据库分类编辑里」用户口径整体下线(页/路由/菜单行 V208 删),key 从清单摘除。
* 后续京东新页面上线把 key 加进这里即可,清单外的 key(含店铺管理/生成记录等
* 存量页)一律归亚马逊或双侧清单。 */
* 存量页)一律归亚马逊或双侧清单。
* ⚠ 本清单只收后台(admin)侧 key——护栏用例要求每条都在 routes.ts 登记 menuKey;
* 桌面端(app)京东菜单走 {@link JD_APP_MENU_KEYS}(无 admin 路由,不进侧边栏)。 */
export const JD_MENU_KEYS: readonly string[] = [
'admin_jd_database',
]
/** 双侧共用菜单(2026-11-17 用户口径「这些亚马逊这边也要有」):三个账号域页面在两个
* 平台 tab 下都显示——同一套组件、按当前 tab 给接口传 platform,各自只看/管各自平台的
* 账号、分组、公司(后端 V206 三表加列,存量默认亚马逊,京东侧数据在编辑弹窗里翻档)。 */
/** 桌面端(app)京东菜单的 column_key 清单(V209,2026-11-17 用户口径「前台的京东少了」):
* 组行 jd_tools(京东工具台)+两工具子行 jd-collect(京东店铺数据采集)/jd-publish(京东商品上架),
* 与用户端 permissionKeys 逐字一致。app 菜单不进后管侧边栏与 routes.ts 路由表,故与
* {@link JD_MENU_KEYS} 分列——判定出口 {@link platformsOfMenuKey} 两份同认。
* 后续用户端京东新工具上线把 column_key 加进这里即可。 */
export const JD_APP_MENU_KEYS: readonly string[] = [
'jd_tools',
'jd-collect',
'jd-publish',
]
/** 双侧共用账号管理页面:用户、分组、公司与菜单权限配置。
* 密钥管理/密钥用量统计按 2026-11-18 截图口径收回亚马逊侧。 */
export const BOTH_PLATFORM_MENU_KEYS: readonly string[] = [
'admin_users',
'admin_group_manage',
'admin_companies',
'admin_columns',
]
/** menuKey → 平台归属清单(唯一判定出口):京东独占 → ['jd'];双侧清单 → ['amazon','jd'];
* 其余(未知 key 在内)默认亚马逊。 */
/** menuKey → 平台归属清单(唯一判定出口):京东独占(后台或桌面端清单)→ ['jd'];
* 双侧清单 → ['amazon','jd'];其余(未知 key 在内)默认亚马逊。 */
export function platformsOfMenuKey(key: string): PlatformTabId[] {
if (JD_MENU_KEYS.includes(key)) return ['jd']
if (JD_MENU_KEYS.includes(key) || JD_APP_MENU_KEYS.includes(key)) return ['jd']
if (BOTH_PLATFORM_MENU_KEYS.includes(key)) return ['amazon', 'jd']
return ['amazon']
}
/**
* 通用「按平台过滤菜单树」(唯一算法出口,2026-11-17 用户口径「授权树也按平台收」):
* 叶子按 {@link platformsOfMenuKey} 是否包含当前平台留下;分组节点自身的 key 不参与
* 平台判定,按「有存活的子项」决定去留——否则京东侧「账号与权限」这类混合分组会被整组误剪。
* 两个消费方必须同形:侧边栏(platform-menu-filter.ts)与账号弹窗的授权树
* (UserMenuAuthTree.vue),改判定规则只改这一处。
*/
export function filterMenuTreeNodesByPlatform<T extends { key?: string; children?: T[] }>(
nodes: readonly T[] | null | undefined,
platform: PlatformTabId,
): T[] {
const filtered: T[] = []
for (const node of nodes || []) {
const children = filterMenuTreeNodesByPlatform(node.children, platform)
if (children.length > 0) {
filtered.push({ ...node, children })
continue
}
if ((node.children || []).length > 0) continue
if (platformsOfMenuKey(node.key || '').includes(platform)) filtered.push({ ...node })
}
return filtered
}
+44 -9
View File
@@ -1,12 +1,12 @@
<script setup lang="ts">
import { computed, watch } from 'vue'
import { computed, nextTick, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { useAdminSessionStore } from '@/stores/admin-session'
import { joinAdminPath } from '@/config/app'
import { pageTitleOf, topbarUserOf } from '@/layout/topbar-model'
import { groupKeysForActive, toSidebarEntries } from '@/layout/menu-mapper'
import { filterMenuTreeByPlatform, visiblePlatformsFor } from '@/layout/platform-menu-filter'
import { allGroupKeys, toSidebarEntries } from '@/layout/menu-mapper'
import { filterMenuTreeByPlatform, allowedPlatformsForUser } from '@/layout/platform-menu-filter'
import { PLATFORM_TABS, platformsOfMenuKey } from '@/config/platform-scope'
import { usePlatformTabStore } from '@/stores/platform-tab'
import { firstVisiblePath } from '@/router/helpers'
@@ -41,10 +41,27 @@ const platformTab = usePlatformTabStore()
const menuEntries = computed(() =>
toSidebarEntries(filterMenuTreeByPlatform(session.menuTree, platformTab.active)),
)
const visibleTabIds = computed(() => visiblePlatformsFor(session.menuTree))
const visibleTabDefs = computed(() => PLATFORM_TABS.filter((tab) => visibleTabIds.value.includes(tab.id)))
const showPlatformTabs = computed(() => visibleTabIds.value.length > 1)
const openedKeys = computed(() => groupKeysForActive(menuEntries.value, route.path))
// 平台锁定(2026-11-18 用户口径「隔离下除站点超管外,京东用户只看京东菜单、亚马逊看不了」):
// tab 可见性 = 站点超管随菜单树分布;其余用户锁 users.platform 那一侧(后端下发树已按平台
// 裁剪,这里再把 tab 收敛到本人平台,单侧时 tab 条整个隐藏)。
const allowedTabIds = computed(() => allowedPlatformsForUser(session.menuTree, session.user))
const visibleTabDefs = computed(() => PLATFORM_TABS.filter((tab) => allowedTabIds.value.includes(tab.id)))
const showPlatformTabs = computed(() => allowedTabIds.value.length > 1)
// 父菜单默认全展开(2026-11-17 用户口径「父菜单不要默认折叠」)。el-menu 的 default-openeds
// 只在挂载时读一次,平台 tab 切换/菜单树刷新导致 entries 变化后新分组不会自动展开,
// 这里在 entries 变更渲染完成后按当下值命令式补开;用户手动收起的组在 entries 不变期间
// 保持收起(watch 不重触发)。读当下 computed 而非触发时快照:快速连切 tab 时不补开已
// 离开渲染树的旧分组(el-menu 的 open 对未注册 index 会抛)。
const menuRef = ref<{ open: (index: string) => void } | null>(null)
const openedKeys = computed(() => allGroupKeys(menuEntries.value))
watch(openedKeys, async () => {
await nextTick()
const menu = menuRef.value
if (!menu) return
for (const key of openedKeys.value) {
menu.open(key)
}
}, { immediate: true })
const emptyMenu = computed(() => shouldShowEmptyMenu(menuEntries.value.length > 0, session.loading, session.initialized))
const pageTitle = computed(() => pageTitleOf(route.meta.title))
const userVm = computed(() => topbarUserOf(session.user))
@@ -59,13 +76,14 @@ watch(
// 直达 URL/面包屑跳到另一平台的页面时,tab 指示自动跟过去(与侧边栏保持一致)。
// 双侧清单里的页面(账号域三页)两个 tab 都算归属:当前 tab 已含它就不动。
// 跟随目标只在允许集(allowedTabIds)里找:被平台锁定的侧不会成为落点。
watch(
() => route.meta.menuKey as string | undefined,
(menuKey) => {
if (!menuKey) return
const owners = platformsOfMenuKey(menuKey)
if (owners.includes(platformTab.active)) return
const target = owners.find((platform) => visibleTabIds.value.includes(platform))
const target = owners.find((platform) => allowedTabIds.value.includes(platform))
if (target && target !== platformTab.active) {
platformTab.setActive(target)
}
@@ -73,6 +91,23 @@ watch(
{ immediate: true },
)
// 平台锁定的归位(2026-11-18):会话就位/菜单树刷新后允许集收敛时,把残留的另一侧 tab
// (超管在同一浏览器切过,localStorage 落的值)归位本人平台;当前页若在被禁侧一并跳回
// 该侧第一可见页。切 tab 的跳转复用下面 platformTab.active 的 watch(active 被 syncToAllowed
// 改写后同链路生效)。
watch(
allowedTabIds,
(allowed) => {
if (!session.user) return
platformTab.syncToAllowed(allowed)
const menuKey = route.meta.menuKey as string | undefined
if (!menuKey || platformsOfMenuKey(menuKey).includes(platformTab.active)) return
const first = firstVisiblePath(filterMenuTreeByPlatform(session.menuTree, platformTab.active))
if (first) void router.replace(first)
},
{ immediate: true },
)
// 切到另一侧 tab 时当前页多半不在那边:跳到该侧第一个可见页;该侧为空(tab 不可见)则不动。
// 双侧清单里的页面(账号域三页)切 tab 不跳转——页面自己按当前平台过滤数据。
watch(
@@ -131,7 +166,7 @@ async function signOut() {
</nav>
<el-scrollbar class="admin-menu-scroll">
<el-menu :default-active="activePath" :default-openeds="openedKeys" router class="admin-menu">
<el-menu ref="menuRef" :default-active="activePath" :default-openeds="openedKeys" router class="admin-menu">
<template v-for="entry in menuEntries" :key="entry.key">
<el-sub-menu v-if="entry.kind === 'group'" :index="entry.key">
<template #title>
+3 -3
View File
@@ -34,11 +34,11 @@ export function toSidebarEntries(nodes: AdminMenuNode[] | null | undefined): Sid
return entries
}
/** 计算需默认展开的分组 key:分组下含当前激活路由子项时返回该分组 key。 */
export function groupKeysForActive(entries: SidebarEntry[], activeRoute: string): string[] {
/** 计算需默认展开的分组 key:父菜单默认全展开(2026-11-17 用户口径「父菜单不要默认折叠」)。 */
export function allGroupKeys(entries: SidebarEntry[]): string[] {
const keys: string[] = []
for (const entry of entries) {
if (entry.kind === 'group' && entry.children.some((child) => child.route === activeRoute)) {
if (entry.kind === 'group') {
keys.push(entry.key)
}
}
@@ -1,5 +1,6 @@
import type { AdminMenuNode } from '../types/admin'
import { PLATFORM_TABS, platformsOfMenuKey } from '../config/platform-scope.ts'
import type { AdminMenuNode, AdminUser } from '../types/admin'
import { isSuperAdminRole } from '../types/admin.ts'
import { PLATFORM_TABS, filterMenuTreeNodesByPlatform } from '../config/platform-scope.ts'
import type { PlatformTabId } from '../config/platform-scope.ts'
import { firstVisiblePath } from '../router/helpers.ts'
@@ -7,27 +8,15 @@ import { firstVisiblePath } from '../router/helpers.ts'
* 按平台 tab 过滤后端菜单树(2026-11-16「亚马逊/京东不混」):**只做显示分组,不做鉴权**——
* 准入仍由 session.menuTree(后端按权限裁剪)与路由守卫负责,这里只是把当前用户已被授权的
* 菜单按平台分到两个 tab 下展示。
* 规则:叶子按 platformsOfMenuKey(key) 是否包含当前平台留下(双侧清单里的账号域三页两个
* tab 都显示);分组节点(admin_group_*)自身的 key 不参与平台判定,按「留住的子项数 > 0」
* 决定去留——否则京东 tab 下「账号与权限」这类混合分组会被整组误剪。节点的 key/name/
* route/children 形状原样透传(浅拷贝不改写),toSidebarEntries、groupKeysForActive 与
* 面包屑都不受影响。
* 规则与算法在 {@link filterMenuTreeNodesByPlatform}(2026-11-17 起唯一出口,账号弹窗授权树
* 同用一份);本壳只钉侧边栏专属的两条:节点的 key/name/route/children 形状原样透传(浅拷贝
* 不改写),toSidebarEntries、groupKeysForActive 与面包屑都不受影响。
*/
export function filterMenuTreeByPlatform(
nodes: AdminMenuNode[] | null | undefined,
platform: PlatformTabId,
): AdminMenuNode[] {
const filtered: AdminMenuNode[] = []
for (const node of nodes || []) {
const children = filterMenuTreeByPlatform(node.children, platform)
if (children.length > 0) {
filtered.push({ ...node, children })
continue
}
if ((node.children || []).length > 0) continue
if (platformsOfMenuKey(node.key || '').includes(platform)) filtered.push({ ...node })
}
return filtered
return filterMenuTreeNodesByPlatform(nodes, platform)
}
/** 当前用户在哪些平台下至少有一个可点页面(tab 显示依据);顺序固定随 PLATFORM_TABS。
@@ -37,3 +26,20 @@ export function visiblePlatformsFor(nodes: AdminMenuNode[] | null | undefined):
.filter((tab) => firstVisiblePath(filterMenuTreeByPlatform(nodes, tab.id)) !== '')
.map((tab) => tab.id)
}
/** 登录用户可用的平台 tab(2026-11-18 用户口径「隔离下除站点超管外,京东用户只看京东菜单、
* 亚马逊看不了」):站点超管不限侧、沿用菜单树分布;其余用户锁 users.platform 那一侧
* (未知/缺省按亚马逊存量口径,与后端 AdminMenuPlatformScope.normalize 同形),与「菜单树
* 该侧有可点页面」求交——交集空则仍回落单侧(管理角色必有双侧账号域页,交集实际非空;
* 宁可锁死自己平台也不放开被禁侧)。会话未就位(user 为空)时按可见分布,锁定的收窄
* 由 AdminLayout 的 watch 在 user 就位后再做。 */
export function allowedPlatformsForUser(
nodes: AdminMenuNode[] | null | undefined,
user: Pick<AdminUser, 'role' | 'platform'> | null | undefined,
): PlatformTabId[] {
const visible = visiblePlatformsFor(nodes)
if (!user || isSuperAdminRole(user.role)) return visible
const own: PlatformTabId = user.platform === 'jd' ? 'jd' : 'amazon'
const allowed = visible.filter((id) => id === own)
return allowed.length > 0 ? allowed : [own]
}
@@ -13,7 +13,9 @@ import {
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { actionableErrorText } from '@/components/admin-feedback'
/** 新建/编辑公司(改名 + 启停 + 备注 + 所属平台 V206);写操作仅超管可用,权限由后端把关。 */
/** 新建/编辑公司(改名 + 启停 + 备注);写操作仅超管可用,权限由后端把关。
* 所属平台不设手选(2026-11-17 用户口径「有京东就不需要亚马逊了,亚马逊那边也是」):
* 平台跟随当前平台 tab——新建取当前 tab(props.platform),编辑保持行值原样下发。 */
const props = defineProps<{ modelValue: boolean; company: CompanyItem | null; platform?: PlatformTabId }>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
@@ -77,12 +79,6 @@ async function save() {
placeholder="请输入公司名称(全平台唯一)"
/>
</el-form-item>
<el-form-item label="所属平台">
<el-radio-group v-model="form.platform">
<el-radio-button value="amazon">亚马逊</el-radio-button>
<el-radio-button value="jd">京东</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item label="状态">
<el-select v-model="form.status" style="width: 100%">
<el-option :value="COMPANY_STATUS_ACTIVE" label="启用" />
@@ -29,7 +29,7 @@ const props = defineProps<{
operatorCompanyId?: number | null
/** 当前公司 tab:这次建号落在哪家,就决定能建哪些角色。 */
activeCompanyId?: number | null
/** 当前平台 tab(V206):新号默认落当前平台,单选可改。 */
/** 当前平台 tab(V206):新号落当前平台(跟随所在 tab,弹窗不再手选——2026-11-17 用户口径)。 */
platform?: PlatformTabId
}>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'created'): void }>()
@@ -136,12 +136,6 @@ async function create(): Promise<void> {
<el-option v-for="opt in roleChoices" :key="opt.value" :label="opt.label" :value="opt.value" />
</el-select>
</el-form-item>
<el-form-item label="所属平台">
<el-radio-group v-model="form.platform">
<el-radio-button value="amazon">亚马逊</el-radio-button>
<el-radio-button value="jd">京东</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item
v-if="operatorSuper && form.role === 'company_super_admin'"
label="所属公司"
@@ -184,7 +178,9 @@ async function create(): Promise<void> {
</el-form-item>
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
<div class="auth-tree-box">
<UserMenuAuthTree v-model:checked="form.columnIds" :company-id="form.companyId" />
<!-- 授权树按账号平台收(2026-11-17 用户口径):京东 tab 只给京东侧菜单。
平台不再手选(跟随当前 tab),树收窄的判定出口不变。 -->
<UserMenuAuthTree v-model:checked="form.columnIds" :company-id="form.companyId" :platform="form.platform" />
</div>
</el-form-item>
</el-form>
@@ -128,12 +128,6 @@ async function save(): Promise<void> {
<el-form-item v-if="targetIsCompanySuperAdmin" label="角色">
<el-input model-value="公司超级管理员" readonly />
</el-form-item>
<el-form-item label="所属平台">
<el-radio-group v-model="form.platform">
<el-radio-button value="amazon">亚马逊</el-radio-button>
<el-radio-button value="jd">京东</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item v-if="expiryEditable" label="到期时间(清空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-date-picker
v-model="form.expiresAt"
@@ -152,7 +146,9 @@ async function save(): Promise<void> {
</el-form-item>
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
<div class="auth-tree-box">
<UserMenuAuthTree v-model:checked="form.columnIds" :company-id="props.companyId" />
<!-- 授权树按账号平台收(2026-11-17 用户口径):京东档账号不再整树混发亚马逊菜单。
平台不再手选(跟随当前平台 tab,编辑取行值),树收窄的判定出口不变。 -->
<UserMenuAuthTree v-model:checked="form.columnIds" :company-id="props.companyId" :platform="form.platform" />
<div v-if="loadingAuth" class="auth-loading">菜单权限加载中…</div>
<div v-else-if="!authReady" class="auth-loading auth-loading-error">
菜单权限加载失败,保存已禁用;请关闭后重试
@@ -3,6 +3,7 @@ import { computed, onMounted, ref, watch } from 'vue'
import type { AdminUser } from '@/types/admin'
import type { PlatformTabId } from '@/config/platform-scope'
import {
eligibleGroupLeaders,
eligibleGroupMembers,
groupMemberCandidateHint,
validateShopGroupForm,
@@ -19,22 +20,38 @@ const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'save
const session = useAdminSessionStore()
const groupName = ref('')
/** 所属平台(V206):新建默认当前平台 tab,编辑回填分组原值,单选可翻档。 */
/** 所属平台(V206):不设手选(2026-11-17 用户口径「有京东就不需要亚马逊了,亚马逊那边也是」)——
* 新建取当前平台 tab(props.platform),编辑保持分组原值,值仍随保存下发。 */
const groupPlatform = ref<PlatformTabId>('amazon')
const memberIds = ref<number[]>([])
const errorText = ref('')
const busy = ref(false)
const users = ref<AdminUser[]>([])
/** 组长:新建=当前登录用户;编辑=分组原组长(不可改,只读展示)。 */
const leaderUserId = computed<number | null>(() =>
props.group ? (props.group.leaderUserId ?? null) : (session.user?.id ?? null),
)
const leaderUsername = computed<string>(() =>
props.group ? (props.group.leaderUsername || '') : (session.user?.username || '当前登录用户'),
)
/**
* 组长:新建默认当前登录用户,站点超管可下拉改选(2026-11-18 用户口径,后端 validateLeaderOperator
* 对站点超管放行任意 createdById、只要求组长与操作者同公司);编辑=分组原组长(后端更新载荷不收
* 组长,不可改);非站点超管新建时后端强制组长=操作者本人,同样只读展示。
*/
const leaderUserId = ref<number | null>(null)
/** 只有「新建 + 站点超管」出组长下拉;其余场景只读回显。 */
const canPickLeader = computed(() => !props.group && !!props.operatorSuper)
const operatorRole = computed<string>(() => session.user?.role || '')
const leaderUsername = computed<string>(() => {
const picked = leaderUserId.value != null
? users.value.find((u) => u.id === leaderUserId.value)
: null
if (picked) return picked.username
if (props.group) return props.group.leaderUsername || ''
return session.user?.username || '当前登录用户'
})
/** 组长候选:与组员同池(本公司账号),排除公司超管;站点超管仅保留操作者本人。 */
const leaderCandidates = computed(() =>
eligibleGroupLeaders(users.value, operatorRole.value, session.user?.id ?? null),
)
/** 组员候选:按组长归属过滤(超管全量、非超管仅本组长创建的普通账号)。 */
const memberCandidates = computed(() =>
eligibleGroupMembers(users.value, leaderUserId.value, operatorRole.value),
@@ -52,18 +69,29 @@ watch(
groupName.value = props.group.name
memberIds.value = props.group.memberUserIds ?? []
groupPlatform.value = props.group.platform === 'jd' ? 'jd' : 'amazon'
// 编辑保持原值口径:历史行可能没有 leaderUserId(旧负载),回落 null 而不是当前登录人,
// 否则组员候选过滤会跟着悄悄变。
leaderUserId.value = props.group.leaderUserId ?? null
} else {
groupPlatform.value = props.platform ?? 'amazon'
leaderUserId.value = session.user?.id ?? null
}
},
)
// 组长改选后,若该人已被选为组员要立刻摘掉——后端「组长不能作为组员重复加入分组」会打回。
watch(leaderUserId, (id) => {
if (id == null) return
memberIds.value = memberIds.value.filter((v) => v !== id)
})
async function loadCandidates(): Promise<void> {
try {
// 对齐 admin.js loadUserOptions:page=1&page_size=999 全量拉取,避免归属过滤漏人。
// company_id 必带:不带时后端对站点超管返回全平台账号,别家公司的人就会出现在本公司分组的候选里。
// 取的是**组长自己那家**(当前登录用户),不是公司 tab——新建时组长就是操作者本人,
// 按 tab 取人会在超管停在别家 tab 时列出那家的人,保存时被后端"只能添加组长本公司的账号"打回。
// 取操作者自己那家,不是公司 tab——组长候选与组员候选同池,后端要求组长与操作者同公司
// (ensureLeaderSharesOperatorCompany),按 tab 取人会在超管停在别家 tab 时列出保存必被
// 打回的人("只能添加组长本公司的账号")。
const page = await fetchUserList({ page: 1, pageSize: 999, companyId: session.user?.companyId ?? null })
users.value = page.items
} catch (error) {
@@ -85,13 +113,13 @@ async function save(): Promise<void> {
await updateShopGroup(props.group.id, groupName.value, memberIds.value, groupPlatform.value)
showAdminFeedback('更新成功', 'success')
} else {
// 对齐 admin:组长恒为当前登录用户,提交 createdBy=当前用户 id。
const operatorId = session.user?.id ?? 0
if (!operatorId) {
showAdminFeedback('无法获取当前登录用户,请重新登录', 'error')
// 组长默认当前登录用户;站点超管可改选本公司其他账号(createdById=所选组长)。
const leaderId = leaderUserId.value ?? 0
if (!leaderId) {
showAdminFeedback('无法获取组长账号,请重新登录', 'error')
return
}
await createShopGroup(groupName.value, memberIds.value, operatorId, groupPlatform.value)
await createShopGroup(groupName.value, memberIds.value, leaderId, groupPlatform.value)
showAdminFeedback('创建成功', 'success')
}
emit('saved')
@@ -119,14 +147,17 @@ onMounted(loadCandidates)
<el-form-item label="分组名称" :error="errorText || undefined">
<el-input v-model="groupName" placeholder="请输入分组名称" />
</el-form-item>
<el-form-item label="所属平台">
<el-radio-group v-model="groupPlatform">
<el-radio-button value="amazon">亚马逊</el-radio-button>
<el-radio-button value="jd">京东</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item label="组长">
<el-input :model-value="leaderUsername" readonly placeholder="当前登录用户" />
<el-select
v-if="canPickLeader"
v-model="leaderUserId"
filterable
placeholder="选择组长(默认当前登录用户)"
style="width: 100%"
>
<el-option v-for="u in leaderCandidates" :key="u.id" :label="u.username" :value="u.id" />
</el-select>
<el-input v-else :model-value="leaderUsername" readonly placeholder="当前登录用户" />
</el-form-item>
<el-form-item label="组员">
<el-select
@@ -6,6 +6,8 @@ import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import OldPagination from '@/components/OldPagination.vue'
import { useCompanyTabStore } from '@/stores/company-tab'
import { usePlatformTabStore } from '@/stores/platform-tab'
import { filterMenuTreeNodesByPlatform } from '@/config/platform-scope'
import { createMenu, deleteMenu, loadMenuManageTree, reorderMenus, updateMenu } from './menu-manage-api'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { openAdminConfirm } from '@/components/admin-confirm'
@@ -31,11 +33,22 @@ import {
interface MenuRow extends MenuManageNode {
depth: number
}
interface PlatformMenuNode extends MenuManageNode {
key: string
children?: PlatformMenuNode[]
}
const companyTab = useCompanyTabStore()
const loading = ref(false)
const loadFailure = ref('')
const rows = ref<MenuManageNode[]>([])
const platformTab = usePlatformTabStore()
// 菜单字典保留全树;显示与父级候选先分平台,再展平分页,避免京东项被亚马逊菜单挤到后页。
const visibleMenuTree = computed(() => {
const withKeys = (nodes: MenuManageNode[]): PlatformMenuNode[] =>
nodes.map((node) => ({ ...node, key: node.columnKey, children: withKeys(node.children || []) }))
return filterMenuTreeNodesByPlatform(withKeys(rows.value), platformTab.active)
})
/** 筛选:菜单名称/类型(用户要求账户域子菜单补筛选条件)。 */
const filterName = ref('')
const filterType = ref('')
@@ -63,14 +76,14 @@ const menuRows = computed<MenuRow[]>(() => {
if (node.children?.length) walk(node.children, depth + 1)
}
}
walk(rows.value, 0)
walk(visibleMenuTree.value, 0)
return out
})
const createVisible = ref(false)
const saving = ref(false)
const editingNode = ref<MenuManageNode | null>(null)
const menuForm = reactive<MenuManageForm>(createMenuForm(null, 0))
const parentOptions = computed(() => menuParentCandidates(rows.value, menuForm.menuType))
const parentOptions = computed(() => menuParentCandidates(visibleMenuTree.value, menuForm.menuType))
const dialogTitle = computed(() => (editingNode.value ? '编辑菜单' : '新增菜单'))
/** 节点 id -> 名称,供「上级菜单」列展示。 */
const nameById = computed(() => {
@@ -114,7 +127,7 @@ function openEdit(node: MenuManageNode) {
/** 菜单类型切换时:当前父菜单不属于新类型则重置为根。 */
function onMenuTypeChange(): void {
const candidates = menuParentCandidates(rows.value, menuForm.menuType)
const candidates = menuParentCandidates(visibleMenuTree.value, menuForm.menuType)
if (menuForm.parentId != null && !candidates.some((node) => node.id === menuForm.parentId)) {
menuForm.parentId = null
}
@@ -215,6 +228,7 @@ async function removeMenu(node: MenuManageNode) {
/** 切公司:菜单名称/类型是客户端筛选(在 filteredMenuRows 上筛,不进请求),留着上一家填的值
* 就是拿别家的字符串去筛新一家那一套树 ⇒ 首屏「暂无匹配菜单」而输入框里还显示着它;页码回 1
* 是因为新一家的行数不同。末尾的 void loadMenus() 才是本页唯一的数据出口。 */
watch(() => platformTab.active, () => { filterName.value = ''; filterType.value = ''; page.value = 1; createVisible.value = false })
watch(() => companyTab.activeId, () => { filterName.value = ''; filterType.value = ''; page.value = 1; void loadMenus() })
onMounted(loadMenus)
@@ -1,10 +1,12 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { filterMenuTreeNodesByPlatform } from '../../config/platform-scope.ts'
import type { PlatformTabId } from '../../config/platform-scope.ts'
import type { MenuOptionNode } from './user-menu-auth'
import { compactDirectGrantIds } from './user-menu-auth'
import { compactDirectGrantIds, pruneCheckedIdsToTree } from './user-menu-auth'
import { fetchGrantableMenus } from './user-menu-auth-api'
const props = defineProps<{ checked?: number[]; companyId?: number | null }>()
const props = defineProps<{ checked?: number[]; companyId?: number | null; platform?: PlatformTabId }>()
const emit = defineEmits<{
(e: 'update:checked', ids: number[]): void
(e: 'load', ok: boolean): void
@@ -17,9 +19,16 @@ const appTree = ref<{ setCheckedKeys(keys: unknown[]): void; getCheckedKeys(): u
const data = ref<MenuOptionNode[]>([])
const loaded = ref(false)
/**
* 按平台过滤后的可见树(2026-11-17 用户口径「授权树也按平台收,选京东就去掉亚马逊的」):
* 平台缺省按亚马逊(历史调用形状)。过滤算法与侧边栏同源(platform-scope 唯一出口),
* 叶子按 menuKey 判定——京东侧=「京东数据库+双侧账号域三件+桌面端京东工具台三件」。
*/
const visibleData = computed(() => filterMenuTreeNodesByPlatform(data.value, props.platform ?? 'amazon'))
/** 两种一级分类…(与 API menuType 分区一致):后台(admin) / 桌面端(app)。 */
const adminNodes = computed(() => data.value.filter((node) => node.type === 'admin'))
const appNodes = computed(() => data.value.filter((node) => node.type === 'app'))
const adminNodes = computed(() => visibleData.value.filter((node) => node.type === 'admin'))
const appNodes = computed(() => visibleData.value.filter((node) => node.type === 'app'))
function applyChecked(): void {
const ids = Array.isArray(props.checked) ? props.checked.filter((id) => typeof id === 'number' && id > 0) : []
@@ -37,7 +46,8 @@ function onCheck(): void {
// 提交前压缩为最小直接授权集:父级已勾选时后代不再重复提交(后端按“父级授权
// 展开全部后代”判断权限,与旧 admin.html 勾父清后代语义一致),
// 并剔除置灰的祖先分组(派生勾选,操作者无权授予)。
emit('update:checked', compactDirectGrantIds(ids, data.value))
// 压缩按「可见树」算:另一侧菜单不在树上,其历史勾选天然进不来。
emit('update:checked', compactDirectGrantIds(ids, visibleData.value))
}
async function load(): Promise<void> {
@@ -49,12 +59,26 @@ async function load(): Promise<void> {
// 渲染完成后再应用已勾选 id,否则作用在空 store 上导致已授权不回显。
await nextTick()
applyChecked()
// 首屏就把勾选集收敛进可见树:编辑一个混档账号(既有亚马逊又有京东授权)时,
// 打开弹窗那一刻就该按当前平台剪掉另一侧,而不是等用户点一下树才剪。
pruneChecked()
} catch {
loaded.value = false
emit('load', false)
}
}
/** 平台切换/首屏后把勾选集收敛进可见树:被过滤掉的另一侧勾选不再随表单提交,
* 否则「京东档账号保存后仍带亚马逊授权」会把平台分侧静默架空。集合没变就不发
* update 事件(避免与父级 v-model 循环互刷)。 */
function pruneChecked(): void {
const pruned = pruneCheckedIdsToTree(props.checked, visibleData.value)
const current = Array.isArray(props.checked) ? props.checked : []
if (pruned.length !== current.length || pruned.some((id, index) => id !== current[index])) {
emit('update:checked', pruned)
}
}
onMounted(load)
watch(
() => props.checked,
@@ -62,6 +86,16 @@ watch(
if (loaded.value) applyChecked()
},
)
/** 平台翻档:可见树整棵换,勾选集同步收敛到新树并回显(被剪掉的勾选以 emit 形式
* 落回表单,父级拿到的是纯当前平台的授权集)。 */
watch(
() => props.platform,
() => {
if (!loaded.value) return
pruneChecked()
void nextTick().then(applyChecked)
},
)
/** 公司换了要整棵重取:勾选集里存的是 column id,别家同名菜单是另一份 id(V149 每公司一套树),
* 拿别家的树勾出来的 id 提交会被后端判「无效的菜单权限项」,而已授权项也因为 id 不在这棵树上勾不上。 */
watch(
@@ -155,6 +155,30 @@ export function eligibleGroupMembers(
})
}
/**
* 组长候选(2026-11-18 用户口径「新建分组组长要能下拉选」):
* - 公司超管永不领衔——与组员「超级管理员不属于任何分组」同源,它是本公司最高账号;
* - 站点超管只保留操作者本人(admin 保持「自己领衔建组」的既有能力,其余站点超管不进候选);
* - 管理员与普通账号均可领衔(普通账号当组长有既有文案背书:「当前账号只能作为组长使用」)。
*
* 后端契约:站点超管走 `validateLeaderOperator` 放行通道,可给任意 `createdById` 建组,
* 但组长必须与操作者同公司(`ensureLeaderSharesOperatorCompany`)——候选池天然同公司(按操作者
* companyId 拉取),不会列出后端要打回的人。非超管操作者不出下拉(后端强制组长=操作者本人)。
*/
export function eligibleGroupLeaders(
users: GroupMemberCandidateUser[],
operatorRole: string,
operatorId: number | null,
): GroupMemberCandidateUser[] {
const operatorKey = operatorId != null && operatorId > 0 ? String(operatorId) : ''
const operatorIsSiteSuper = isSuperAdminRole(operatorRole)
return users.filter((u) => {
if (!isGroupIneligibleRole(u.role)) return true
// 两档超管默认不领衔;站点超管只保留操作者本人这一个例外。
return operatorIsSiteSuper && String(u.id) === operatorKey
})
}
/** 组员候选帮助文案(对齐 admin.js:3179-3182)。 */
export function groupMemberCandidateHint(candidateCount: number, operatorRole: string): string {
if (candidateCount > 0) return '可添加当前组长创建的普通员工账号'
@@ -22,7 +22,7 @@ export interface CreateUserForm {
expiresAt: string
/** 所属公司 id:仅 role=company_super_admin 时由站点超管必选(2026-10-05 需求)。 */
companyId?: number | null
/** 所属平台(V206):弹窗打开时预填当前平台 tab,单选可改。 */
/** 所属平台(V206):弹窗打开时预填当前平台 tab(不设手选——2026-11-17 用户口径)。 */
platform: PlatformTabId
}
@@ -46,7 +46,7 @@ export interface CreateUserPayload {
* 反向钉(company-user-create.test.ts)唯一豁免的例外:公司超管必须落指定公司,
* 否则会静默落操作者自己的公司(公司 1),用户需求就是给别家公司开超管。 */
companyId?: number
/** 所属平台(V206):恒下发(弹窗单选默认当前平台 tab),缺省后端落 amazon。 */
/** 所属平台(V206):恒下发(预填当前平台 tab),缺省后端落 amazon。 */
platform: PlatformTabId
}
@@ -20,7 +20,7 @@ export interface EditUserForm {
originalRole: string
/** 到期时间(yyyy-MM-dd HH:mm:ss);空串 = 永不过期。null = 后端本来就无到期。 */
expiresAt: string
/** 所属平台(V206):单选可翻档,未知/缺省归亚马逊(存量默认)。 */
/** 所属平台(V206):编辑回填行值(不设手选——2026-11-17 用户口径),未知/缺省归亚马逊(存量默认)。 */
platform: PlatformTabId
}
@@ -38,7 +38,7 @@ export interface EditUserUpdateRequest {
password?: string
/** 到期时间:空串=清除(恢复永不过期),有值=改期;总是下发(与后端"传了就更新"对齐)。 */
expiresAt: string
/** 所属平台(V206):总是下发(弹窗单选恒渲染),翻档即把记录挪到另一平台的列表。 */
/** 所属平台(V206):总是下发(编辑保持行值原样,后端显式才落)。 */
platform: PlatformTabId
}
@@ -146,3 +146,24 @@ export function compactDirectGrantIds(checkedIds: unknown, tree: MenuOptionNode[
walk(tree, false)
return ids.filter((id) => !ungrantable.has(id) && !coveredByAncestor.has(id))
}
/**
* 把勾选集收敛到「可见树」内(2026-11-17 用户口径「授权树按平台收」的另一半):
* 授权树按平台过滤后,另一侧的已勾 id 在树上不可见、也不再属于这棵树——它们必须
* 从表单勾选集里剔除,否则「京东档账号」保存后仍携带整批亚马逊菜单授权(侧边栏
* 亚马逊 tab 照样全亮,平台分侧被静默架空)。纯函数:入参不动,返回去重升序交集。
*/
export function pruneCheckedIdsToTree(checkedIds: unknown, visibleTree: MenuOptionNode[]): number[] {
const ids = normalizeMenuIds(checkedIds)
if (ids.length === 0) return []
if (visibleTree.length === 0) return []
const visible = new Set<number>()
const walk = (nodes: MenuOptionNode[]): void => {
for (const node of nodes) {
visible.add(node.id)
if (node.children?.length) walk(node.children)
}
}
walk(visibleTree)
return ids.filter((id) => visible.has(id))
}
@@ -5,7 +5,11 @@
* 职责不变:当前数据权限分组的分类建/改名/删除+新增的名称搜索;商品归类不在这里
* (去「批量编辑分类」)。列表状态自管理(写操作后自刷新并 emit changed 让父页刷筛选下拉)。
* 权限口径(V203)不变:本组管理员/公司超管/平台超管可写(editable);同组普通号
* 只读可看(无新建行,改名/删除按钮逐行不渲染),后端同口径 403 兜底。 */
* 只读可看(无新建行,改名/删除按钮逐行不渲染),后端同口径 403 兜底。
* 2026-11-17 晚用户口径「admin 权限最大」:京东侧还没有任何数据权限分组时(平台闸
* 上线后 jd 档组全空),平台超管在本弹窗空态直建第一个京东档分组(组长=自己),
* 建完 emit group-created 让父页重取作用域,当前分组翻到新组后接着就能建分类,
* 不再死在「你还不属于任何数据权限分组」。 */
import { computed, ref, watch } from 'vue'
import {
createJdProductGroup,
@@ -14,6 +18,8 @@ import {
updateJdProductGroup,
type JdProductGroup,
} from './jd-product-api.ts'
import { createShopGroup } from '../account/shop-group-api.ts'
import { useAdminSessionStore } from '@/stores/admin-session'
import { openAdminConfirm } from '@/components/admin-confirm'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { loadFailureMessage } from '@/components/load-failure-model'
@@ -27,9 +33,13 @@ const props = defineProps<{
ownerGroupName: string
/** 当前分组可写(scope 的 editable):建/改名/删除控件全挂它。 */
editable: boolean
/** 操作者是否平台超管(scope 原样透传):只在「还没有分组」的空态开直建口子。 */
platformSuperAdmin?: boolean
}>()
const emit = defineEmits<{ (event: 'close'): void; (event: 'changed'): void }>()
const emit = defineEmits<{ (event: 'close'): void; (event: 'changed'): void; (event: 'group-created'): void }>()
const session = useAdminSessionStore()
const loading = ref(false)
/** 首屏取数失败(可见红条+重试);写操作失败走 errorText 红条(无重试语义)。 */
@@ -73,7 +83,8 @@ const showPager = computed(() => filteredGroups.value.length > PAGE_SIZE)
function goPage(target: number): void {
pageNo.value = Math.min(Math.max(1, target), totalPages.value)
}
/** 空表文案分四种:不属于任何组 / 本组没分类(可管理)/ 本组没分类(只读)/ 搜索无命中。 */
/** 空表文案分四种:不属于任何组 / 本组没分类(可管理)/ 本组没分类(只读)/ 搜索无命中。
* 平台超管的「还没有分组」空态不走这里——模板换成直建分组的表单(canBootstrapGroup)。 */
const emptyListText = computed(() => {
if (props.ownerGroupId <= 0) return '你还不属于任何数据权限分组'
if (!groups.value.length) {
@@ -82,6 +93,40 @@ const emptyListText = computed(() => {
return '没有匹配的分类'
})
/** 空态直建分组的口子(2026-11-17 用户口径「admin 权限最大」):平台超管 + 还没有任何
* 可见分组时才开。组员/翻档等完整分组管理仍归「分组管理」页,这里只解决「从 0 到 1」。 */
const canBootstrapGroup = computed(() => props.platformSuperAdmin === true && props.ownerGroupId <= 0)
/** 直建表单:只收名称;组长=当前操作者,platform 恒 'jd'(京东侧作用域只认 jd 档)。 */
const newGroupName = ref('')
const creatingGroup = ref(false)
const canCreateGroup = computed(() =>
canBootstrapGroup.value && newGroupName.value.trim().length > 0 && !creatingGroup.value)
/** 平台超管空态直建第一个京东档分组:走分组管理同一条 POST(shop-manages/groups),
* 组长=当前操作者、组员先空。成功后 emit group-created 让父页整条作用域重取——
* ownerGroupId 翻到新组后由下方 watch 接手按新组重取分类,操作者接着就能建分类。 */
async function submitCreateGroup(): Promise<void> {
const name = newGroupName.value.trim()
if (!name || creatingGroup.value || !canBootstrapGroup.value) return
const operatorId = session.user?.id ?? 0
if (!operatorId) {
errorText.value = '无法获取当前登录用户,请重新登录'
return
}
creatingGroup.value = true
errorText.value = ''
try {
await createShopGroup(name, [], operatorId, 'jd')
newGroupName.value = ''
showAdminFeedback(`已新建京东档分组「${name}」`, 'success')
emit('group-created')
} catch (error) {
errorText.value = requestErrorMessage(error) || '新建分组失败'
} finally {
creatingGroup.value = false
}
}
async function loadGroups(): Promise<void> {
if (props.ownerGroupId <= 0) {
groups.value = []
@@ -177,6 +222,7 @@ watch(
loadFailure.value = ''
cancelRename()
createName.value = ''
newGroupName.value = ''
pageNo.value = 1
void loadGroups()
}
@@ -185,6 +231,15 @@ watch(
{ immediate: true },
)
/** 建组成功后父页重取作用域会把 ownerGroupId 翻到新组:按新组重取分类列表,
* 操作者不用关弹窗重开就能接着建分类。 */
watch(
() => props.ownerGroupId,
(next, prev) => {
if (next > 0 && next !== prev) void loadGroups()
},
)
/** 改关键字回第一页(命中集变了,停在旧页码会落在空白处)。 */
watch(keyword, () => {
pageNo.value = 1
@@ -199,13 +254,9 @@ watch(totalPages, (pages) => {
<div v-if="visible" class="modal-mask" @click.self="emit('close')">
<div class="manage-modal">
<div class="modal-head">
<h3>分类管理<span v-if="ownerGroupName" class="modal-sub">· {{ ownerGroupName }}</span></h3>
<h3>分类管理</h3>
<button class="modal-close" type="button" aria-label="关闭" @click="emit('close')">×</button>
</div>
<p class="modal-tip">
分类按「数据权限分组」隔离,当前组{{ editable ? '只组长/超管可维护' : '由组长/超管维护' }};
给商品归类:关掉本框,勾选商品后点「批量编辑分类」。
</p>
<div class="manage-bar">
<input v-model="keyword" class="search-input" type="text" placeholder="搜索分类名称" aria-label="搜索分类名称" />
@@ -218,6 +269,14 @@ watch(totalPages, (pages) => {
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" />
<p v-if="errorText" class="group-error">{{ errorText }}</p>
<!-- 表头(2026-11-18 用户红框口径):列表有数据时在搜索行下列出三列名,与行同构对齐;
只读口径下行没有改名/删除按钮,操作列表头随之不渲染。 -->
<div v-if="filteredGroups.length" class="option-head">
<span class="head-name">分类名称</span>
<span class="head-count">商品数</span>
<span v-if="editable" class="head-actions">操作</span>
</div>
<ul class="option-list">
<template v-if="filteredGroups.length">
<li v-for="group in pagedGroups" :key="group.id" class="option-row">
@@ -239,7 +298,22 @@ watch(totalPages, (pages) => {
</li>
</template>
<li v-else-if="loading" class="manage-empty">加载中...</li>
<li v-else class="manage-empty">{{ emptyListText }}</li>
<li v-else class="manage-empty">
<template v-if="canBootstrapGroup">
<div class="group-bootstrap">
<input
v-model="newGroupName"
class="search-input"
type="text"
placeholder="输入分组名称"
aria-label="新分组名称"
@keyup.enter="submitCreateGroup"
/>
<button class="btn" type="button" :disabled="!canCreateGroup" @click="submitCreateGroup">新建分组</button>
</div>
</template>
<template v-else>{{ emptyListText }}</template>
</li>
</ul>
<div v-if="showPager" class="manage-pager">
@@ -293,12 +367,6 @@ watch(totalPages, (pages) => {
font-weight: 650;
color: #24384d;
}
.modal-sub {
margin-left: 6px;
color: #5b6f83;
font-size: 13px;
font-weight: 500;
}
.modal-close {
width: 30px;
height: 30px;
@@ -315,18 +383,16 @@ watch(totalPages, (pages) => {
background: #eef4fa;
color: #24384d;
}
.modal-tip {
margin: 8px 0 10px;
color: #8293a5;
font-size: 12.5px;
line-height: 1.5;
}
/* 2026-11-17 用户口径「垂直排阿,这样好看」「不然留白太多了」:搜索与新建各占整行
(原来两件并排 flex:1 各挤一半宽),弹窗内容变高、列表下方空白收窄,两行输入等宽也更整齐。 */
/* 2026-11-17 用户口径演变:「垂直排阿」→ 弹窗收窄到 340px 后「弄成一排呗」:
搜索框、新分类名输入、新建按钮合回一行。340−42=298px 可用宽度:新建按钮约 56
+两处 gap 16。实测按比例分(flex 1:1.75)会偏移(搜索 122/新建输入只剩 105,
7 字占位 115px 被截),改成搜索定宽 108px(6 字占位 102px 放得下),新建行吃剩余
(298−108−16=174,输入约 118px,占位完整)。 */
.manage-bar {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
gap: 8px;
align-items: center;
margin-bottom: 12px;
}
.search-input,
@@ -353,12 +419,14 @@ watch(totalPages, (pages) => {
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
}
.search-input {
width: 100%;
flex: 0 0 108px;
min-width: 0;
}
.group-create {
display: flex;
flex: 1;
gap: 8px;
width: 100%;
min-width: 0;
}
.group-create input {
flex: 1;
@@ -373,6 +441,33 @@ watch(totalPages, (pages) => {
color: #a04432;
font-size: 13px;
}
/* 表头与行同形(同 gap、同左右内边距),列名只是淡色小字不抢行内容;
商品数列吃与徽标一致的 min-width/内边距,操作列同 rows 的 margin-left:auto 靠右。 */
.option-head {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 8px;
border-bottom: 1px solid #e7eef5;
font-size: 12px;
color: #8293a5;
}
.head-name {
flex: 0 1 auto;
min-width: 0;
}
.head-count {
flex: none;
min-width: 22px;
padding: 0 7px;
text-align: center;
white-space: nowrap;
}
.head-actions {
flex: none;
margin-left: auto;
white-space: nowrap;
}
.option-list {
flex: 1;
min-height: 0;
@@ -427,6 +522,16 @@ watch(totalPages, (pages) => {
font-size: 13px;
list-style: none;
}
/* 平台超管空态直建分组:只有输入行(引导语/组长说明等小字 2026-11-17 用户口径「小字不需要」删除)。 */
.group-bootstrap {
display: flex;
gap: 8px;
}
.group-bootstrap .search-input {
flex: 1;
min-width: 0;
text-align: left;
}
.manage-pager {
display: flex;
align-items: center;
@@ -31,12 +31,19 @@ import { openAdminConfirm } from '@/components/admin-confirm'
import { loadFailureMessage } from '@/components/load-failure-model'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
import { isAdminRole, isCompanySuperAdminRole } from '@/types/admin'
import { formatDateTime, orderedPair } from '@/utils/datetime'
/** 写权限口径(2026-11-16 用户口径):商品行写(编辑/删除/勾选批量删)只对平台超级管理员渲染;
* 分类写(建/改名/删除、归类)由 scope 的每组 editable 决定(本组管理员/公司超管/平台超管)。 */
/** 写权限口径(2026-11-17 用户口径「超管+管理员都可以,只有普通员工不能操作」):
* 商品行写(编辑/删除/批量删除/传图)对管理员级(超级管理员/公司超级管理员/admin 档)渲染,
* 普通账号只读(后端 requireJdProductWrite 同口径兜底);分类写(建/改名/删除、归类)
* 由 scope 的每组 editable 决定(本组管理员/公司超管/平台超管),与本档无关。 */
const session = useAdminSessionStore()
const isSuperAdmin = computed(() => session.isSuperAdmin)
const canWriteProducts = computed(() => isAdminRole(session.user?.role))
/** 分组筛选(同日用户口径「超管可以有分组筛选,管理员及以下则没有」):筛选行「分组」控件
* (下拉+单组锁定芯片)只对超管档(超级管理员/公司超级管理员)渲染;管理员及以下
* 不出现,其分类面固定落在作用域默认分组上。 */
const canFilterGroup = computed(() => session.isSuperAdmin || isCompanySuperAdminRole(session.user?.role))
const loading = ref(false)
const loadFailure = ref('')
@@ -48,6 +55,10 @@ const filter = reactive(createJdProductFilterState())
/** 分类作用域(V203):可见分组 + 每组可写标记。失败静默回空作用域(分类列全空但商品照常)。 */
const categoryScope = ref<JdCategoryGroupOption[]>([])
const scopeDefaultGroupId = ref(0)
/** 操作者是否平台超管(scope 原样透传):京东侧还没有任何分组时,分类管理弹窗
* 靠它给平台超管开「直接新建数据权限分组」的口子(2026-11-17 用户口径「admin 权限最大」),
* 其余角色维持空态指路,不在分类管理里建组。 */
const scopeSuperAdmin = ref(false)
/** 当前分组(数据权限分组 id):分类列/分类筛选/分类管理的共同作用域。 */
const ownerGroupId = ref(0)
/** 当前分组的分类下拉选项(按 ownerGroupId 取,切组即换)。 */
@@ -71,12 +82,12 @@ const currentGroupOption = computed<JdCategoryGroupOption | null>(() =>
const currentGroupName = computed(() => currentGroupOption.value?.name || '')
/** 分类可管理(建/改名/删除/归类):本组管理员、公司超管、平台超管(后端 scope 判)。 */
const canManageCategories = computed(() => currentGroupOption.value?.editable === true)
/** 勾选列服务两类写:批量删除(只超管)+批量编辑分类(本组可写分类的管理员也要勾)。
/** 勾选列服务两类写:批量删除(管理员级)+批量编辑分类(本组可写分类的管理员也要勾)。
* 2026-11-17 弹窗下线后管理员失去弹窗右栏的勾选面 ⇒ 勾选列必须对「本组可写」放开,
* 否则本组管理员没有归类入口。商品行按钮(编辑/删除/删除勾选)仍只归平台超管。 */
const hasSelectionColumn = computed(() => isSuperAdmin.value || canManageCategories.value)
/** 空态行 colspan:勾选列有无决定 5/6/7 列三种形状(超管含操作列)。 */
const emptyColspan = computed(() => (isSuperAdmin.value ? 7 : hasSelectionColumn.value ? 6 : 5))
* 否则本组管理员没有归类入口。 */
const hasSelectionColumn = computed(() => canWriteProducts.value || canManageCategories.value)
/** 空态行 colspan:勾选列有无决定 5/6/7 列三种形状(管理员级含操作列)。 */
const emptyColspan = computed(() => (canWriteProducts.value ? 7 : hasSelectionColumn.value ? 6 : 5))
/** 分组下拉只在能看多组时才渲染;只有一组(含无可见组)时按锁定态展示。 */
const canSwitchGroup = computed(() => categoryScope.value.length > 1)
@@ -110,9 +121,11 @@ async function loadCategoryScope(): Promise<void> {
const scope = await fetchJdCategoryScope()
categoryScope.value = scope.groups
scopeDefaultGroupId.value = scope.defaultGroupId ?? 0
scopeSuperAdmin.value = scope.platformSuperAdmin === true
} catch {
categoryScope.value = []
scopeDefaultGroupId.value = 0
scopeSuperAdmin.value = false
}
// 当前分组:保留用户已选(仍可见时),否则回默认(可见组第一项)。
const keep = categoryScope.value.some((group) => group.id === ownerGroupId.value)
@@ -167,6 +180,15 @@ async function onManaged(): Promise<void> {
await loadGroupOptions()
}
/**
* 分类管理里新建了第一个数据权限分组(平台超管空态直建,2026-11-17 用户口径「admin
* 权限最大」):整条作用域重取——新组会进可见集并把「当前分组」翻过去,分类下拉、
* 弹窗内分类列表随之按新组取,操作者接着就能建分类,不用关弹窗再开一遍。
*/
async function onGroupCreated(): Promise<void> {
await loadCategoryScope()
}
/** 批量归类完成(对话框已关):清勾选+重取列表(行集 groupName 变了)。
* 移出分类 targetName 为 null;updated 是后端实际写入/解挂的归属行数。 */
async function onBatchAssigned(updated: number, targetName: string | null): Promise<void> {
@@ -293,9 +315,9 @@ async function removeOne(row: JdProductItem): Promise<void> {
await removeMany([row.id], `确定删除商品「${row.productCode || row.title}」吗?`)
}
/** 批量删除入口(工具栏按钮):按累计勾选 id 直删(跨页的行也在内),确认弹窗点名总数。 */
/** 批量删除入口(筛选行右侧按钮):按累计勾选 id 直删(跨页的行也在内),确认弹窗点名总数。 */
async function removeSelected(): Promise<void> {
await removeMany([...selectedIds.value], `确定删除勾选的 ${selectedIds.value.size} 个商品吗?`)
await removeMany([...selectedIds.value], `确定批量删除选中的 ${selectedIds.value.size} 个商品吗?`)
}
/** 删除主流程:二次确认 → 先删桶、全成功才删库行(后端保证)→ 刷新列表并清勾选。 */
@@ -355,9 +377,11 @@ onMounted(async () => {
@change="onCategoryPicked"
/>
</div>
<div v-if="categoryScope.length" class="form-group">
<div v-if="canFilterGroup && categoryScope.length" class="form-group">
<label>分组</label>
<!-- 当前分组(V203):能看多组的人(平台超管/公司超管)下拉切换;只有一组时锁定显示组名。
<!-- 当前分组(V203):超管档(平台/公司超管)专属——2026-11-17 用户口径
「超管可以有分组筛选,管理员及以下则没有」,本控件对管理员及以下整块不渲染
(其分类面固定落在作用域默认分组)。能看多组的人下拉切换;只有一组时锁定显示组名。
2026-11-16 用户口径「做成分组」:从工具栏裸下拉上移进筛选行,做成带标签的表单控件
(与其他筛选同壳同圆角)。2026-11-17 用户口径「和亚马逊不统一」:原生 <select> 的
弹层是浏览器直角原生物,换 el-select(同亚马逊面 admin-filter 同壳),组多时可搜索。
@@ -387,14 +411,12 @@ onMounted(async () => {
<button class="btn" type="button" @click="apply">查询</button>
<button class="btn btn-secondary" type="button" @click="reset">重置</button>
</div>
</div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<div class="jd-toolbar">
<span class="jd-summary">共 {{ total }} 条京东商品</span>
<!-- 批量动作条(2026-11-17 用户口径「共X条京东商品删掉,工具栏整体上移」):
原「汇总+工具栏」整行上移并入筛选行,与查询/重置同排;汇总数字删除。
放不下的项随 .jd-filter-row 的 flex-wrap 自然折行。 -->
<!-- 批量编辑分类(2026-11-17 用户口径「店铺分类弹窗删了,加个批量编辑分类」):
只对当前分组可写档(本组管理员/公司超管/平台超管)渲染;勾选 0 时置灰(与
删除勾选同款常显口径),打开后按累计勾选(跨页)提交归入/移出。 -->
批量删除同款常显口径),打开后按累计勾选(跨页)提交归入/移出。 -->
<button
v-if="canManageCategories"
class="btn btn-secondary"
@@ -402,9 +424,10 @@ onMounted(async () => {
:disabled="!selectedCount"
@click="openBatchEdit"
>批量编辑分类</button>
<!-- 商品行写只对平台超管;分类写由当前分组 editable 决定(本组管理员/公司超管/平台超管)。
非超管看到只读提示,分类维护入口=工具栏「分类管理」(只读可看,写控件按 editable 分档)。 -->
<span v-if="!isSuperAdmin" class="jd-readonly-tip">只读:编辑/删除仅超级管理员可用;分类在本页「分类管理」查看与维护</span>
<!-- 商品行写对管理员级(超管+管理员)开放,普通账号看到只读提示;分类写由当前分组
editable 决定(本组管理员/公司超管/平台超管),分类维护入口=「分类管理」
(只读可看,写控件按 editable 分档)。 -->
<span v-if="!canWriteProducts" class="jd-readonly-tip">只读:编辑/删除需超级管理员或管理员;分类在本页「分类管理」查看与维护</span>
<!-- 分类筛选(2026-11-17 与分组同刀换 el-select,弹层圆角与亚马逊统一):保留显式
「全部分类」行(value='',与旧原生下拉同语义——列表里永远有回全量的出口),
选中它/重置回 '' 时闭壳显示同文案占位。 -->
@@ -419,9 +442,11 @@ onMounted(async () => {
<el-option v-for="group in groupOptions" :key="group.id" :label="group.name" :value="String(group.id)" />
</el-select>
<!-- 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」+同日收敛
「不需要全部分类 默认卡在未分类上就行」):已分类=当前分组下有分类
(V203 归属表,与列表分类列同形——筛"未分类"的行分类列必显示未分类);
两档下拉、出厂默认卡「未分类」,选中即查(回第一页);「重置」也回未分类档。 -->
「默认卡在未分类上就行」;2026-11-18 用户口径「加个全部选项」恢复全量档):
已分类=当前分组下有分类(V203 归属表,与列表分类列同形——筛"未分类"的行
分类列必显示未分类);三档下拉、出厂默认仍卡「未分类」(11-17 口径不动),
「全部」(value='')选中即查当前分组全部商品(序列化不下发 classified 参数,
后端 required=false 跳过谓词);选中即查(回第一页);「重置」仍回未分类档。 -->
<el-select
v-model="filter.classified"
class="admin-filter"
@@ -429,6 +454,7 @@ onMounted(async () => {
aria-label="筛选分类状态"
@change="apply"
>
<el-option label="全部" value="" />
<el-option label="已分类" value="classified" />
<el-option label="未分类" value="ungrouped" />
</el-select>
@@ -441,18 +467,20 @@ onMounted(async () => {
@click="openManage"
>分类管理</button>
<!-- 批量删除 2026-11-16 客户口径「不要勾选后才显示」:常显,勾选 0 时置灰。
同日写权限收窄到超管:非超管整颗按钮不渲染(勾选列 2026-11-17 起对本组可写
分类管理员开放,服务批量归类)。 -->
写权限 2026-11-17 口径放宽到管理员级:普通账号整颗按钮不渲染(勾选列 2026-11-17
起对本组可写分类管理员开放,服务批量归类)。文案 2026-11-17 用户口径「删除勾选改成批量删除」。 -->
<button
v-if="isSuperAdmin"
v-if="canWriteProducts"
class="btn btn-danger jd-delete-btn"
type="button"
:disabled="deleting || !selectedCount"
@click="removeSelected"
>
{{ deleting ? '删除中...' : `删除勾选(${selectedCount})` }}
{{ deleting ? '删除中...' : `批量删除(${selectedCount})` }}
</button>
</div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<div class="table-scroll jd-table-scroll">
<table>
<thead>
@@ -463,9 +491,10 @@ onMounted(async () => {
<th style="width: 76px">总库存</th>
<th style="width: 120px">价格</th>
<!-- 同步时间收尾(创建/修改两列 2026-11-16 客户口径「不要」下线,仍收详情抽屉);
操作列 2026-11-16「操作放最后一列」口径置末;同日写权限收窄到超管 ⇒ 非超管不渲染。 -->
操作列 2026-11-16「操作放最后一列」口径置末;写权限 2026-11-17 放宽到
管理员级 ⇒ 普通账号不渲染该列。 -->
<th style="width: 170px">同步时间</th>
<th v-if="isSuperAdmin" style="width: 138px">操作</th>
<th v-if="canWriteProducts" style="width: 138px">操作</th>
</tr>
</thead>
<tbody>
@@ -500,8 +529,8 @@ onMounted(async () => {
<td>{{ formatDateTime(row.syncedAt || '') }}</td>
<!-- 操作列(2026-11-15 用户口径):编辑/删除;@click.stop 防冒泡开详情抽屉。
2026-11-16「操作放最后一列」口径置末;「上架时间 / 商品状态」列同日整列下线;
同日写权限收窄到超管 ⇒ 非超管不渲染该列。 -->
<td v-if="isSuperAdmin" class="jd-ops-cell" @click.stop>
写权限 2026-11-17 口径放宽到管理员级 ⇒ 普通账号不渲染该列。 -->
<td v-if="canWriteProducts" class="jd-ops-cell" @click.stop>
<button class="btn btn-sm" type="button" @click="openEdit(row)">编辑</button>
<button class="btn btn-sm btn-danger" type="button" :disabled="deleting" @click="removeOne(row)">删除</button>
</td>
@@ -534,8 +563,10 @@ onMounted(async () => {
:owner-group-id="ownerGroupId"
:owner-group-name="currentGroupName"
:editable="canManageCategories"
:platform-super-admin="scopeSuperAdmin"
@close="manageVisible = false"
@changed="onManaged"
@group-created="onGroupCreated"
/>
<JdProductDetailDrawer
:item="detailItem"
@@ -122,20 +122,18 @@ h3 {
border-color: #95b1cb;
background: #edf5fb;
}
.jd-toolbar {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 10px;
}
/* 工具栏分类筛选(2026-11-17 用户口径「和亚马逊不统一」起换 el-select):42px 外壳、
/* 批量动作条(2026-11-17 用户口径「汇总删掉、工具栏整体上移」):并入 .jd-filter-row
与查询/重置同排,不再有独立 .jd-toolbar 容器;放不下靠筛选行的 flex-wrap 折行。 */
/* 分类筛选/状态快筛下拉(2026-11-17 用户口径「和亚马逊不统一」起换 el-select):42px 外壳、
9px 圆角、#cbd9e6 描边、#f8fbfd 浅底与 focus ring 都由全局 .el-select.admin-filter
皮肤(main.css)出——与亚马逊面同一套,弹层不再是浏览器原生直角列表。
这里只钉工具栏位宽(admin-filter 出厂 width:100%,进 flex 工具栏会横涨)。 */
.jd-toolbar .el-select.admin-filter {
只钉动作条里的下拉位宽(admin-filter 出厂 width:100%,进 flex 行会横涨);
用直接子级选择器,别误伤「分组」表单组里嵌的同款下拉(那个跟 form-group 走宽)。 */
.jd-filter-row > .el-select.admin-filter {
width: 200px;
flex-shrink: 0;
}
/* 危险动作(删除勾选)推到行尾:留在「批量编辑分类/分类筛选」旁边会被读成同一组动作。 */
/* 危险动作(批量删除)推到行尾:留在「批量编辑分类/分类筛选」旁边会被读成同一组动作。 */
.jd-delete-btn {
margin-left: auto;
}
@@ -143,7 +141,7 @@ h3 {
.jd-manage-btn {
margin-left: 6px;
}
/* 危险动作(删除勾选):与全站 .btn-danger 同形——实心红渐变+白字。
/* 危险动作(批量删除):与全站 .btn-danger 同形——实心红渐变+白字。
旧版是白底红字描边,落在工具栏里看着像「未激活的次要按钮」,与打卡/分组等页不统一。 */
.btn-danger {
background: linear-gradient(135deg, #c06d77, #b35f6a);
@@ -153,12 +151,8 @@ h3 {
.btn-danger:hover:not(:disabled) {
background: linear-gradient(135deg, #cb7c84, #b96570);
}
.jd-summary {
color: #5b6f83;
font-size: 13px;
white-space: nowrap;
}
/* 非超管只读提示(2026-11-16 写权限收窄):紧跟汇总的一句话,不冒充可点按钮。 */
/* 非超管只读提示(2026-11-16 写权限收窄):动作条里的一句话说明,不冒充可点按钮。
(汇总「共 X 条京东商品」2026-11-17 用户口径删除,.jd-summary 样式随之摘除。) */
.jd-readonly-tip {
color: #8293a5;
font-size: 12.5px;
@@ -32,12 +32,13 @@ export interface JdProductFilterState {
category: string
/** 分组 id 文本(分组管理里那一行),空串=全部分组。 */
groupId: string
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」,同日二档收敛
* 「不需要全部分类 默认卡在未分类上就行」):'classified'=已分类(当前分组下有分类),
* 'ungrouped'=未分类,**出厂默认='ungrouped'**(首屏与「重置」都卡未分类档)。
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」,同日定默认卡未分类;
* 2026-11-18 用户口径「加个全部选项」恢复全量档):'classified'=已分类(当前分组下有
* 分类),'ungrouped'=未分类,''=全部(当前分组下全部商品);**出厂默认仍='ungrouped'**
* (11-17 口径不动,首屏与「重置」都卡未分类档)。
* 语义按 V203 归属表(当前数据权限分组)判定,与列表分类列同形;不是 11-16 撤掉的
* 旧 grouped/ungrouped 参数(那两档读已停用的 biz_jd_product.group_id 列,后端仍拒收)。
* ''/缺省=「全部」仍是序列化出口的兜底语义(脏值不冒充档位),但界面不再给这一档。 */
* ''(全部档)序列化时不带 classified 参数=后端跳过谓词查全部;脏值同走该兜底。 */
classified?: '' | 'classified' | 'ungrouped'
/** 同步开始日期(ISO yyyy-MM-dd;空串不限)。 */
syncedFrom: string
@@ -46,8 +47,8 @@ export interface JdProductFilterState {
}
export function createJdProductFilterState(): JdProductFilterState {
// 分类状态出厂卡「未分类」(2026-11-17 用户口径「默认卡在未分类上就行」):
// 首屏与「重置」都带 classified=false 查,用户要全量自己点「已分类」逐档看。
// 分类状态出厂卡「未分类」(2026-11-17 用户口径「默认卡在未分类上就行」,2026-11-18
// 加「全部」档后默认不动):首屏与「重置」都带 classified=false 查,全量走「全部」档。
return { productCode: '', titleKeyword: '', category: '', groupId: '', classified: JD_PRODUCT_DEFAULT_CLASSIFIED, syncedFrom: '', syncedTo: '' }
}
@@ -38,5 +38,13 @@ export const usePlatformTabStore = defineStore('platform-tab', {
this.active = id
writeStoredTab(id)
},
/** 平台锁定(2026-11-18 用户口径「非站点超管只看自己平台侧」):允许集收敛时把 active
* 归位——localStorage 残留的另一侧(超管在同一浏览器切过 tab)自动回落本人平台;
* 允许集为空(会话未就位)不动。 */
syncToAllowed(allowed: readonly PlatformTabId[]) {
if (allowed.length > 0 && !allowed.includes(this.active)) {
this.setActive(allowed[0])
}
},
},
})
+70 -11
View File
@@ -41,7 +41,10 @@ body {
button, input, textarea, select { font: inherit; }
/* ===== 蓝白浅色壳层(对齐 admin.html 末层皮肤) ===== */
.admin-shell { display: flex; min-height: 100vh; background: var(--admin-bg); }
/* 壳层锁视口高(2026-11-18「菜单加个滚动条」):min-height 会让 flex 高度链失去确定性,
* el-scrollbar 与 .admin-content 的 overflow 全部失效、回落整页滚,侧边栏顶部(品牌区/平台
* tab)被滚出视口。height:100vh 定高后侧边栏与 .admin-content 各自独立滚动、顶栏固定。 */
.admin-shell { display: flex; height: 100vh; overflow: hidden; background: var(--admin-bg); }
.admin-sidebar {
display: flex; flex: 0 0 252px; flex-direction: column;
background: linear-gradient(180deg, var(--admin-sidebar) 0%, var(--admin-sidebar-deep) 100%);
@@ -111,7 +114,7 @@ button, input, textarea, select { font: inherit; }
.admin-main { display: flex; min-width: 0; flex: 1; flex-direction: column; }
.admin-topbar {
display: flex; align-items: center; justify-content: space-between; gap: 24px;
min-height: 76px; padding: 0 32px;
min-height: 56px; padding: 0 16px; flex-shrink: 0;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--admin-border);
box-shadow: 0 10px 28px -28px rgba(39, 67, 94, 0.42);
@@ -132,8 +135,8 @@ button, input, textarea, select { font: inherit; }
}
.admin-user-logout.el-button:hover { color: var(--admin-primary-strong); border-color: #95b1cb; background: #edf5fb; }
.admin-content { flex: 1; min-width: 0; padding: 30px 32px 56px; overflow: auto; }
.page-stack { display: flex; flex-direction: column; gap: 18px; }
.admin-content { flex: 1; min-width: 0; min-height: 0; padding: 12px 16px 20px; overflow: auto; }
.page-stack { display: flex; flex-direction: column; gap: 10px; }
/* 表格操作按钮工具栏:置于表格卡片顶部、右对齐(新增/删除/导入/导出等贴近表格行操作)。 */
.table-toolbar { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
.page-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
@@ -224,11 +227,67 @@ button, input, textarea, select { font: inherit; }
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
}
@media (max-width: 820px) {
.admin-sidebar { flex-basis: 64px; }
.admin-brand-copy, .admin-menu .el-sub-menu__title span, .admin-menu .el-menu-item { display: none; }
.admin-topbar { align-items: flex-start; flex-direction: column; padding: 12px 18px; }
.admin-user { width: 100%; justify-content: space-between; }
.admin-user-meta { align-items: flex-start; }
.admin-content { padding: 18px 16px 40px; }
/* 列表密度统一收口;带壳层作用域的选择器覆盖各页 scoped 旧皮肤,不影响弹窗编辑表单。 */
.admin-shell .admin-content :is(.panel-box, .form-box) { padding: 12px 14px; }
.admin-shell .admin-content .el-card { --el-card-padding: 12px; }
.admin-shell .admin-content > [class$="-view"] { gap: 10px; min-width: 0; }
.admin-shell .admin-content :is(.panel-box, .form-box) h3 { margin-bottom: 8px; }
.admin-shell .admin-content :is(.jd-panel-head, .dedupe-panel-head) { margin-bottom: 8px; }
.admin-shell .admin-content :is(.jd-panel-head, .dedupe-panel-head) h3 { margin-bottom: 0; }
.admin-shell .admin-content :is(.users-desc, .page-heading p) { margin-top: 4px; margin-bottom: 8px; }
.admin-shell .admin-content :is(.form-row, .clean-filter-row, .dedupe-filter-row, .dedupe-filter-date-row, .jd-filter-row) {
display: flex; flex-wrap: wrap; align-items: flex-end; gap: 8px; margin-bottom: 10px;
}
.admin-shell .admin-content :is(.clean-filter-row, .dedupe-filter-row, .jd-filter-row) > .form-group {
flex: 1 1 140px; min-width: 0; max-width: 220px;
}
.admin-shell .admin-content :is(.form-row, .clean-filter-row, .dedupe-filter-row, .dedupe-filter-date-row, .jd-filter-row) .form-group { gap: 4px; }
.admin-shell .admin-content :is(.panel-box, .form-box) .form-group input:not([type="checkbox"]):not([type="radio"]),
.admin-shell .admin-content .jd-group-locked { min-height: 34px; padding: 5px 10px; }
.admin-shell .admin-content .el-select.admin-filter .el-select__wrapper { min-height: 34px; padding: 4px 10px; }
.admin-shell .admin-content :is(.panel-box, .form-box) .btn:not(.btn-sm) { min-height: 34px; padding: 5px 12px; }
.admin-shell .admin-content :is(.clean-filter-actions, .dedupe-filter-actions, .jd-filter-actions) { flex-wrap: wrap; gap: 6px; }
.admin-shell .admin-content .jd-filter-row > .el-select.admin-filter { width: 170px; }
.admin-shell .admin-content :is(.table-toolbar, .clean-toolbar) { margin-bottom: 8px; }
.admin-shell .admin-content :is(.table-scroll, .table-wrap) :is(th, td) { padding-top: 6px; padding-bottom: 6px; }
.admin-shell .admin-content :is(.table-scroll, .table-wrap) .btn-sm { min-height: 28px; padding: 3px 6px; font-size: 12.5px; }
.admin-shell .admin-content :is(.table-scroll, .table-wrap) .ops-cell { gap: 4px; }
.admin-shell .admin-content .el-table .el-table__cell { padding: 5px 0; }
.admin-shell .admin-content .old-pagination { gap: 8px; margin-top: 10px; }
.admin-shell .admin-content .table-footer { padding-top: 10px; }
.admin-shell .admin-content .admin-breadcrumb { margin-bottom: 8px; }
.admin-shell .admin-content .company-tabs { margin-bottom: 8px; }
.admin-shell .admin-content .company-tab { padding: 4px 12px; }
.admin-shell .admin-content .operation-guide { margin-bottom: 10px; padding: 8px 12px; }
.admin-shell .admin-content .og-body { margin-top: 4px; }
.admin-shell .admin-content .og-text { line-height: 1.5; }
.admin-shell .admin-content .og-steps { gap: 4px; margin-top: 4px; }
@media (max-width: 1440px) {
.admin-sidebar { flex-basis: 208px; }
.admin-content { padding: 10px 12px 16px; }
}
@media (max-width: 820px) {
.admin-sidebar { flex-basis: 160px; }
.admin-brand { padding: 12px 10px; }
.admin-brand-copy span, .admin-kicker { display: none; }
.admin-topbar { min-height: 56px; gap: 8px; padding: 8px 12px; flex-wrap: wrap; }
.admin-topbar h1 { margin-top: 0; font-size: 16px; }
.admin-user { gap: 8px; flex-wrap: wrap; }
.admin-content { padding: 8px 10px 12px; }
.admin-shell .admin-content :is(.panel-box, .form-box) { padding: 10px; }
.admin-shell .admin-content .form-row > .form-group { flex: 1 1 140px; min-width: 0; max-width: 100%; }
}
@media (max-width: 560px) {
.admin-sidebar { flex-basis: 128px; }
.admin-brand { gap: 6px; }
.admin-brand-logo { width: 28px; height: 28px; }
.admin-brand-copy strong { font-size: 13px; }
.admin-menu-scroll { padding: 8px 4px; }
.admin-menu .el-sub-menu__title, .admin-menu .el-menu-item { padding: 0 8px; font-size: 12px; }
.menu-group-title { font-size: 13px; }
.admin-user-role { display: none; }
.admin-shell .admin-content :is(.clean-filter-row, .dedupe-filter-row, .jd-filter-row) > .form-group { max-width: 100%; }
}
@@ -2,11 +2,12 @@ import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
import {
eligibleGroupLeaders,
eligibleGroupMembers,
groupMemberCandidateHint,
} from '../src/pages/account/shop-group-model.ts'
/** 对齐 admin.js:3020-3028 getEligibleShopManageGroupUsers 与 3179-3182 帮助文案。 */
/** 对齐 admin.js:3020-3028 getEligibleShopManageGroupUsers 与 3179-3182 帮助文案;组长候选为 2026-11-18 新增口径。 */
const USERS = [
{ id: 1, username: '组长A', role: 'admin', createdById: null },
@@ -63,21 +64,47 @@ test('align_group_candidate_hint_empty_for_admin', () => {
})
test('align_group_editor_dialog_ui_wiring', () => {
// UI 接线:候选请求 page_size=999;新建时组长恒为当前登录用户(无改选下拉);候选/提示走新模型。
// UI 接线:候选请求 page_size=999;组长默认当前登录用户,新建+站点超管出改选下拉
// (2026-11-18 用户口径「新建分组组长要能下拉选」),编辑与非超管仍只读;候选/提示走新模型。
const dialog = readSource('src/pages/account/GroupEditorDialog.vue')
assert.match(dialog, /pageSize:\s*999/, '候选列表按参考 page_size=999 拉取')
assert.doesNotMatch(dialog, /组长(创建人)/, '新建弹窗不再提供组长改选下拉')
assert.match(dialog, /当前登录用户/, '新建时组长只读显示当前登录用户')
assert.match(dialog, /canPickLeader/, '组长下拉按「新建+站点超管」条件渲染')
assert.match(dialog, /v-if="canPickLeader"/, '下拉分支挂在 canPickLeader 上')
assert.match(dialog, /eligibleGroupLeaders/, '组长候选走 eligibleGroupLeaders 过滤')
assert.match(dialog, /v-else :model-value="leaderUsername" readonly/, '编辑与非超管新建仍走只读回显')
assert.match(dialog, /当前登录用户/, '只读回显保留当前登录用户兜底')
assert.match(dialog, /memberIds\.value\.filter/, '组长改选后把该人从组员里摘掉(后端拒绝组长重复入组)')
assert.match(dialog, /createShopGroup\(groupName\.value, memberIds\.value, leaderId/,
'创建提交 createdById=所选组长(站点超管改选通道,后端 validateLeaderOperator 放行)')
assert.match(dialog, /eligibleGroupMembers/, '组员候选走归属过滤')
assert.match(dialog, /groupMemberCandidateHint/, '候选提示文案走对齐逻辑')
assert.match(dialog, /companyId:\s*session\.user\?\.companyId \?\? null/,
'候选必须按组长(新建时=当前登录用户)那家取人:不带时后端对站点超管返回全平台账号,别家公司的人会进到这家的候选里')
'候选必须按操作者那家取人:组长必须与操作者同公司(后端 ensureLeaderSharesOperatorCompany),不带时站点超管会拿到全平台账号')
assert.doesNotMatch(dialog, /companyTab/, '分组候选不能按公司 tab 取人——超管停在别家 tab 时会列出那家的人,保存必被后端打回')
const page = readSource('src/pages/account/GroupsPage.vue')
assert.match(page, /创建时间/, '列表补创建时间列')
assert.doesNotMatch(page, /slice\(0,\s*10\)/, '组员 chips 全量渲染不再收 +N')
})
test('align_group_leader_candidates_site_super_keeps_self_drops_company_super', () => {
// 组长候选:公司超管永不领衔;站点超管只保留操作者本人(保持 admin 自建组的既有能力)。
const result = eligibleGroupLeaders(USERS, 'super_admin', 6)
assert.deepEqual(result.map((u) => u.id), [1, 2, 3, 4, 5, 6])
})
test('align_group_leader_candidates_non_super_operator_drops_all_supers', () => {
// 非站点超管操作者:两档超管全部出局(弹窗此时不出下拉,这里是同池复用方的兜底口径)。
const result = eligibleGroupLeaders(USERS, 'admin', 1)
assert.deepEqual(result.map((u) => u.id), [1, 2, 3, 4, 5])
})
test('align_group_leader_candidates_normal_accounts_can_lead', () => {
// 普通账号可领衔(既有文案背书:「当前账号只能作为组长使用」)。
const normals = USERS.filter((u) => u.role === 'normal')
const result = eligibleGroupLeaders(normals, 'super_admin', 6)
assert.deepEqual(result.map((u) => u.id), [2, 3, 4])
})
test('align_group_backend_gate_super_never_joins_and_leader_shares_company', () => {
// 界面收窄只是少踩一次;这两条 403 才是出口。锚在调用点与抛出语句,不锚注释。
const java = readSource(
@@ -84,4 +84,8 @@ test('align_menu_page_drag_and_type_wiring', () => {
assert.match(page, /menuSiblingGroupKey/, '拖拽分组按类型+父级')
assert.match(page, /MENU_TYPE_OPTIONS|菜单类型/, '新建/编辑弹窗含菜单类型下拉')
assert.match(page, /menuParentCandidates/, '父菜单候选按类型过滤')
assert.match(page, /filterMenuTreeNodesByPlatform/, '配置树必须先按当前平台裁剪,再展平分页')
assert.match(page, /platformTab\.active/, '配置树跟随当前平台')
assert.match(page, /walk\(visibleMenuTree\.value, 0\)/, '展平读取当前平台树,京东数据库不能被全量菜单分页挤走')
assert.match(page, /watch\(\(\) => platformTab\.active/, '切平台必须回第一页并清筛选')
})
@@ -2,7 +2,7 @@
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
"totals": {
"files": 262,
"cases": 1832,
"cases": 1837,
"pins": 460,
"reads": 658
},
@@ -58,7 +58,7 @@
"reads": 1
},
"align-group-editor.test.ts": {
"cases": 10,
"cases": 13,
"pins": 2,
"reads": 3
},
@@ -398,7 +398,7 @@
"reads": 7
},
"platform-menu-filter.test.ts": {
"cases": 7,
"cases": 9,
"pins": 0,
"reads": 0
},
@@ -51,7 +51,7 @@ test('请求体:admin/normal 一律不带 companyId;公司超管必须带且
password: 'secret123',
role: 'normal',
columnIds: [3, 1],
// V206:所属平台恒下发(弹窗单选默认当前平台 tab,空表单缺省亚马逊)。
// V206:所属平台恒下发(预填当前平台 tab,空表单缺省亚马逊;弹窗不设手选)。
platform: 'amazon',
})
// 所属管理员仍按原语义携带(仅 normal 角色)
@@ -110,10 +110,10 @@ test('京东列表参数——page 钳制防 (page-1)*page_size 溢出(铁律
assert.equal(offset, 999_900)
})
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」,同日收敛
* 「不需要全部分类 默认卡在未分类上就行」):界面两档,'classified'→true、'ungrouped'→false;
* 出厂默认与「重置」都卡 ungrouped。''/缺省/脏值=「全部」仍是序列化出口的兜底语义
* (不拿脏值冒充档位),但界面不再提供这一档。
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」,同日定默认卡未分类;
* 2026-11-18 用户口径「加个全部选项」恢复全量档):界面三档,'classified'→true、
* 'ungrouped'→false、''(全部)→ 不带 classified 参数;出厂默认与「重置」仍卡 ungrouped。
* ''/缺省/脏值同走「全部」兜底(不拿脏值冒充档位)。
* 参数名是新档 classified——不是后端仍拒收的旧 grouped/ungrouped 查询参数。 */
test('京东列表参数——classified 默认卡未分类:已分类→true、未分类→false、脏值兜底不下发', () => {
const yes = toJdProductListParams({ ...createJdProductFilterState(), classified: 'classified' }, 1, 20, 11)
@@ -0,0 +1,165 @@
/**
* AdminLayout × 平台锁定(2026-11-18 用户口径「隔离下除站点超管外,京东用户只看京东菜单、
* 亚马逊看不了」)的挂载契约:
* - 京东用户(company_super_admin + platform=jd)即使 localStorage 残留另一侧 tab,挂载后
* active 归位本人平台(syncToAllowed),单侧时平台 tab 条整个隐藏;
* - 站点超管不受限:双平台 tab 照画、active 保持残留值(超管切过的侧照记);
* - 京东用户当前路由落在被禁侧(直达 URL):跳回本人平台第一可见页。
* menuTree 模拟后端裁剪后的下发树(京东用户树里本来就没有亚马逊叶子)。
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
*
* 跑法:`npx vitest run tests/mount/admin-layout-platform-lock.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import ElementPlus from 'element-plus'
import { createMemoryHistory, createRouter, type Router } from 'vue-router'
import AdminLayout from '@/layout/AdminLayout.vue'
import { usePlatformTabStore } from '@/stores/platform-tab'
import { useAdminSessionStore } from '@/stores/admin-session'
import { adminPages } from '@/router/routes'
import type { AdminMenuNode } from '@/types/admin'
// AdminLayout 的顶栏/告警子组件各带定时器或远端拉取,与本契约无关,替身化。
vi.mock('@/components/NotificationBell.vue', () => ({ default: { template: '<div class="bell-stub" />' } }))
vi.mock('@/components/ExpiryNotice.vue', () => ({ default: { template: '<div class="expiry-stub" />' } }))
vi.mock('@/layout/OperationGuide.vue', () => ({ default: { template: '<div class="guide-stub" />' } }))
vi.mock('@/layout/CompanyTabs.vue', () => ({ default: { template: '<div class="company-tabs-stub" />' } }))
vi.mock('@/layout/GlobalErrorContainer.vue', () => ({ default: { template: '<div class="error-stub" />' } }))
/** 后端裁剪后下发给京东用户的树形状:双侧账号域六页 + 京东数据库(无任何亚马逊叶子)。 */
const JD_TREE: AdminMenuNode[] = [
{
key: 'admin_group_account',
name: '账号与权限',
children: [
{ key: 'admin_users', name: '用户管理', route: '/account/users' },
{ key: 'admin_group_manage', name: '分组管理', route: '/account/groups' },
{ key: 'admin_columns', name: '菜单权限配置', route: '/account/menus' },
{ key: 'admin_user_secrets', name: '密钥管理', route: '/account/user-secrets' },
{ key: 'admin_user_secret_usage', name: '密钥用量统计', route: '/account/user-secret-usage' },
],
},
{
key: 'admin_group_data',
name: '数据管理',
children: [{ key: 'admin_jd_database', name: '京东数据库', route: '/jd-center/database' }],
},
]
/** 站点超管的树:亚马逊业务页 + 京东页 + 双侧账号域(现状全量形状)。 */
const SUPER_TREE: AdminMenuNode[] = [
{
key: 'admin_group_account',
name: '账号与权限',
children: [{ key: 'admin_users', name: '用户管理', route: '/account/users' }],
},
{
key: 'admin_group_data',
name: '数据管理',
children: [
{ key: 'admin_query_asin', name: '查询ASIN', route: '/asin-center/query' },
{ key: 'admin_jd_database', name: '京东数据库', route: '/jd-center/database' },
],
},
]
let pinia: Pinia
let router: Router
beforeEach(async () => {
vi.clearAllMocks()
window.localStorage.removeItem('admin-platform-tab')
pinia = createPinia()
setActivePinia(pinia)
// adminPages 是相对 /admin-vue/ 的子路径注册表(不带前导斜杠),这里按 memory history
// 补 "/" 建表:路由 meta 带上 menuKey,AdminLayout 的 tab 跟随/replace 判定吃真实 meta。
// component 全部换同步桩——真实页面是懒 import,导航确认会卡在组件 promise 上,
// 而本契约只盯 AdminLayout 的 tab/replace 行为,页面本体无关。
router = createRouter({
history: createMemoryHistory(),
routes: adminPages.map((page) => ({
path: `/${page.path}`,
component: { template: '<div class="page-stub" />' },
meta: { title: page.title, menuKey: page.menuKey },
})),
})
await router.push('/')
await router.isReady()
})
async function mountLayout() {
const wrapper = mount(AdminLayout, { global: { plugins: [pinia, router, ElementPlus] } })
await flushPromises()
return wrapper
}
describe('AdminLayout × 平台锁定(2026-11-18)', () => {
it('京东用户挂载:残留的亚马逊 tab 归位京东侧,tab 条隐藏,侧边栏只画本人平台菜单', async () => {
window.localStorage.setItem('admin-platform-tab', 'amazon')
const session = useAdminSessionStore()
session.user = { id: 10, username: '阿华66', role: 'company_super_admin', platform: 'jd' }
session.menuTree = JD_TREE
session.initialized = true
const wrapper = await mountLayout()
const platformTab = usePlatformTabStore()
expect(platformTab.active).toBe('jd')
expect(wrapper.findAll('.admin-platform-tab').length).toBe(0)
const texts = wrapper.findAll('.admin-menu .el-menu-item').map((item) => item.text())
expect(texts).toContain('京东数据库')
expect(texts).not.toContain('查询ASIN')
// 共用菜单配置保留,两个密钥入口仅亚马逊侧可见。
expect(texts).toContain('菜单权限配置')
expect(texts).not.toContain('密钥管理')
expect(texts).not.toContain('密钥用量统计')
wrapper.unmount()
})
it('站点超管挂载:双平台 tab 照画、残留 active 保持(不受平台锁定影响)', async () => {
window.localStorage.setItem('admin-platform-tab', 'jd')
const session = useAdminSessionStore()
session.user = { id: 1, username: 'admin', role: 'super_admin', platform: 'amazon' }
session.menuTree = SUPER_TREE
session.initialized = true
const wrapper = await mountLayout()
const platformTab = usePlatformTabStore()
expect(platformTab.active).toBe('jd')
const tabs = wrapper.findAll('.admin-platform-tab').map((tab) => tab.text())
expect(tabs).toEqual(['亚马逊', '京东'])
expect(tabs[1]).toBe('京东')
wrapper.unmount()
})
it('京东用户直达被禁侧 URL(/asin-center/query):挂载后跳回本人平台第一可见页', async () => {
const session = useAdminSessionStore()
session.user = { id: 10, username: '阿华66', role: 'company_super_admin', platform: 'jd' }
session.menuTree = JD_TREE
session.initialized = true
await router.push('/asin-center/query')
const wrapper = await mountLayout()
expect(router.currentRoute.value.path).toBe('/account/users')
wrapper.unmount()
})
it('亚马逊存量用户(platform 缺省兜底亚马逊):锁亚马逊侧,京东页不可达', async () => {
const session = useAdminSessionStore()
session.user = { id: 8, username: '存量号', role: 'admin' }
session.menuTree = SUPER_TREE
session.initialized = true
const wrapper = await mountLayout()
const platformTab = usePlatformTabStore()
expect(platformTab.active).toBe('amazon')
expect(wrapper.findAll('.admin-platform-tab').length).toBe(0)
wrapper.unmount()
})
})
@@ -14,6 +14,7 @@ import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import JdCategoryManageDialog from '@/pages/jd/JdCategoryManageDialog.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
const jdApi = vi.hoisted(() => ({
fetchJdProductGroups: vi.fn(),
@@ -22,9 +23,14 @@ const jdApi = vi.hoisted(() => ({
deleteJdProductGroup: vi.fn(),
}))
const groupApi = vi.hoisted(() => ({
createShopGroup: vi.fn(),
}))
const confirmMock = vi.hoisted(() => vi.fn())
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/pages/account/shop-group-api.ts', () => groupApi)
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
/** 分组 id 常量:默认作用域就这一个可见且可写的组(组长档形状)。 */
@@ -40,7 +46,10 @@ beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
// 空态直建分组(2026-11-17 用户口径「admin 权限最大」)需要当前登录人做组长。
useAdminSessionStore().user = { id: 9, username: 'admin', role: 'super_admin' } as never
jdApi.fetchJdProductGroups.mockResolvedValue([])
groupApi.createShopGroup.mockResolvedValue({ id: 21, name: '京东-团队', ownerGroupId: 21, sortOrder: 0, productCount: 0 })
confirmMock.mockResolvedValue(true)
})
@@ -60,12 +69,13 @@ async function mountDialog(editable = true): Promise<VueWrapper<Element>> {
}
describe('京东分类管理对话框(V204 独立页 2026-11-17 并入京东数据库页)', () => {
it('打开即按当前分组取分类(ownerGroupId 必带);标题带当前分组名', async () => {
it('打开即按当前分组取分类(ownerGroupId 必带);标题不带分组名(2026-11-17 用户口径「不要显示周丽娥」)', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(GROUP_A)
expect(wrapper.get('.manage-modal').text()).toContain('分类管理')
expect(wrapper.get('.manage-modal').text()).toContain('甲组', '标题/上下文带当前分组名')
expect(wrapper.find('.modal-sub').exists()).toBe(false, '标题后缀(· 分组名)已删,不得长回来')
expect(wrapper.get('.manage-modal').text()).not.toContain('甲组', '分组名不进标题')
expect(wrapper.findAll('.option-row')).toHaveLength(1)
wrapper.unmount()
})
@@ -142,14 +152,15 @@ describe('京东分类管理对话框(V204 独立页 2026-11-17 并入京东
wrapper.unmount()
})
it('搜索与新建行同属 manage-bar 的两行(搜索在上、新建在下,2026-11-17 改垂直排列)', async () => {
it('搜索与新建行同属 manage-bar 的一排(搜索在左、新建在右,2026-11-17 用户口径「弄成一排呗」)', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
const bar = wrapper.get('.manage-bar')
const children = Array.from(bar.element.children)
expect(children).toHaveLength(2, 'bar 只有两件:搜索框、新建行')
expect(children[0].classList.contains('search-input')).toBe(true, '垂直排列时搜索在上')
expect(children[1].classList.contains('group-create')).toBe(true, '新建行在下')
expect(children).toHaveLength(2, '一排只有两件:搜索框、新建行(新建行内=输入框+新建按钮)')
expect(children[0].classList.contains('search-input')).toBe(true, '搜索框在左')
expect(children[1].classList.contains('group-create')).toBe(true, '新建行在右')
expect(children[1].children).toHaveLength(2, '新建行只有输入框+按钮(排序输入 11-15 已下线,不得长出第三个框)')
wrapper.unmount()
})
@@ -250,8 +261,104 @@ describe('京东分类管理对话框(V204 独立页 2026-11-17 并入京东
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(false, '归类入口在京东数据库页')
expect(wrapper.text()).toContain('批量编辑分类', '但提示要指路(关掉本框去勾选商品归类)')
expect(wrapper.text()).not.toContain('批量编辑分类',
'指路小字已随 2026-11-17 用户口径「小字不需要」删除,弹窗里不该再出现这句')
expect(jdApi.deleteJdProductGroup).not.toHaveBeenCalled()
wrapper.unmount()
})
})
/** 平台超管空态直建分组(2026-11-17 用户口径「admin 权限最大」):京东侧还没有任何
* 数据权限分组时(平台闸上线后 jd 档组全空,B117-02 前置未做),平台超管在弹窗里
* 直接建第一个京东档分组,不再死在「你还不属于任何数据权限分组」。 */
describe('平台超管空态直建京东档分组', () => {
function mountEmpty(platformSuperAdmin: boolean): VueWrapper<Element> {
return mount(JdCategoryManageDialog, {
global: { plugins: [pinia] },
props: { visible: true, ownerGroupId: 0, ownerGroupName: '', editable: false, platformSuperAdmin },
})
}
it('平台超管空态:出直建表单(不是死路文案),提交走分组管理同一条 POST 且 platform 恒 jd、组长=当前登录人', async () => {
const wrapper = mountEmpty(true)
await flushPromises()
await flushPromises()
expect(jdApi.fetchJdProductGroups).not.toHaveBeenCalled()
expect(wrapper.get('.manage-empty').find('[aria-label="新分组名称"]').exists()).toBe(true,
'空态直建表单就在空态区里(引导语小字已删,表单本身还在)')
const input = wrapper.get('[aria-label="新分组名称"]')
await input.setValue('京东-团队')
await wrapper.findAll('button').find((b) => b.text() === '新建分组')!.trigger('click')
await flushPromises()
await flushPromises()
expect(groupApi.createShopGroup).toHaveBeenCalledTimes(1)
expect(groupApi.createShopGroup).toHaveBeenCalledWith('京东-团队', [], 9, 'jd')
expect(wrapper.emitted('group-created'), '建组成功即通知父页重取作用域').toBeTruthy()
expect((input.element as HTMLInputElement).value).toBe('', '成功后清输入')
wrapper.unmount()
})
it('没有当前登录人就不发请求并给可见错误(组长缺了这单没法建)', async () => {
useAdminSessionStore().user = null
const wrapper = mountEmpty(true)
await flushPromises()
await wrapper.get('[aria-label="新分组名称"]').setValue('京东-团队')
await wrapper.findAll('button').find((b) => b.text() === '新建分组')!.trigger('click')
await flushPromises()
expect(groupApi.createShopGroup).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('无法获取当前登录用户')
wrapper.unmount()
})
it('建组失败:错误进红条、不发 group-created(父页作用域不动)', async () => {
groupApi.createShopGroup.mockRejectedValueOnce(new Error('分组名称已存在'))
const wrapper = mountEmpty(true)
await flushPromises()
await wrapper.get('[aria-label="新分组名称"]').setValue('京东-团队')
await wrapper.findAll('button').find((b) => b.text() === '新建分组')!.trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.text()).toContain('分组名称已存在')
expect(wrapper.emitted('group-created')).toBeFalsy()
wrapper.unmount()
})
it('父页把 ownerGroupId 翻到新组后:直建表单消失、按新组重取分类(不用关弹窗重开)', async () => {
const wrapper = mountEmpty(true)
await flushPromises()
await wrapper.get('[aria-label="新分组名称"]').setValue('京东-团队')
await wrapper.findAll('button').find((b) => b.text() === '新建分组')!.trigger('click')
await flushPromises()
const emittedBefore = wrapper.emitted('group-created')?.length ?? 0
await wrapper.setProps({ ownerGroupId: 21, ownerGroupName: '京东-团队', editable: true })
await flushPromises()
await flushPromises()
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(21)
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(21)
expect(wrapper.find('[aria-label="新分组名称"]').exists()).toBe(false, '有组了直建口子就关')
expect(wrapper.emitted('group-created')?.length).toBe(emittedBefore, '翻组重取不再重复通知父页')
wrapper.unmount()
})
it('非平台超管的空态维持原状:死路文案照旧、无直建表单(口子不开给组长/公司超管)', async () => {
const wrapper = mountEmpty(false)
await flushPromises()
expect(wrapper.get('.manage-empty').text()).toBe('你还不属于任何数据权限分组')
expect(wrapper.find('[aria-label="新分组名称"]').exists()).toBe(false)
wrapper.unmount()
})
it('平台超管但已有分组(ownerGroupId>0):直建口子不出现(完整分组管理归「分组管理」页)', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = mount(JdCategoryManageDialog, {
global: { plugins: [pinia] },
props: { visible: true, ownerGroupId: GROUP_A, ownerGroupName: '甲组', editable: true, platformSuperAdmin: true },
})
await flushPromises()
await flushPromises()
expect(wrapper.find('[aria-label="新分组名称"]').exists()).toBe(false)
expect(wrapper.find('.group-bootstrap').exists()).toBe(false, '有组时直建表单整体不渲染')
wrapper.unmount()
})
})
@@ -45,7 +45,12 @@ const jdApi = vi.hoisted(() => ({
const confirmMock = vi.hoisted(() => vi.fn())
const groupApi = vi.hoisted(() => ({
createShopGroup: vi.fn(),
}))
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/pages/account/shop-group-api.ts', () => groupApi)
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
function item(id: number, over: Record<string, unknown> = {}) {
@@ -103,6 +108,7 @@ beforeEach(() => {
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope())
jdApi.fetchJdProductGroups.mockResolvedValue([])
jdApi.fetchJdProductCategories.mockResolvedValue([])
groupApi.createShopGroup.mockResolvedValue({ id: 21, name: '京东-团队', ownerGroupId: 21, sortOrder: 0, productCount: 0 })
confirmMock.mockResolvedValue(true)
})
@@ -160,14 +166,14 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
const deleteBtn = () => wrapper.get('.jd-delete-btn')
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
expect(deleteBtn().text()).toContain('删除勾选(1)')
expect(deleteBtn().text()).toContain('批量删除(1)')
// 翻页:勾选不清(2026-11-17 口径「支持勾选翻页也要记住」)。
await wrapper.findAll('button').find((b) => b.text() === '下一页')!.trigger('click')
await flushPromises()
expect(deleteBtn().text()).toContain('删除勾选(1)', '翻页后第 1 页的勾选仍在累计集里')
expect(deleteBtn().text()).toContain('批量删除(1)', '翻页后第 1 页的勾选仍在累计集里')
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
expect(deleteBtn().text()).toContain('删除勾选(2)', '第 2 页再勾 1 行,累计 2 行')
expect(deleteBtn().text()).toContain('批量删除(2)', '第 2 页再勾 1 行,累计 2 行')
expect(wrapper.findAll('button').some((b) => b.text() === '清除勾选')).toBe(false,
'「清除勾选」按钮 2026-11-17 用户口径删除(显式反悔口没了,勾选只在批量操作成功后自动清)')
@@ -176,10 +182,10 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
await deleteBtn().trigger('click')
await flushPromises()
await flushPromises()
expect(confirmMock.mock.calls.at(-1)![0].message).toContain('确定删除勾选的 2 个商品吗', '确认文案点名累计总数')
expect(confirmMock.mock.calls.at(-1)![0].message).toContain('确定批量删除选中的 2 个商品吗', '确认文案点名累计总数')
// 跨页累计的 id 一起提交。
expect(jdApi.deleteJdProducts).toHaveBeenLastCalledWith([1, 2])
expect(deleteBtn().text()).toContain('删除勾选(0)', '批量删除成功后自动清勾选')
expect(deleteBtn().text()).toContain('批量删除(0)', '批量删除成功后自动清勾选')
wrapper.unmount()
})
@@ -192,7 +198,7 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
const wrapper = await mountWith({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 })
const editBtn = () => wrapper.findAll('button').find((b) => b.text() === '批量编辑分类')!
expect(editBtn().attributes('disabled')).toBeDefined('勾选 0 时置灰(与删除勾选同款常显口径)')
expect(editBtn().attributes('disabled')).toBeDefined('勾选 0 时置灰(与批量删除同款常显口径)')
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
await boxes[0].setValue(true)
await boxes[1].setValue(true)
@@ -216,7 +222,7 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
expect(document.body.textContent).toContain('已把 2 个商品归入「甲组」')
expect(wrapper.find('.batch-modal').exists()).toBe(false, '成功后对话框自动关闭')
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore, '成功后重取列表(groupName 变了)')
expect(wrapper.get('.jd-delete-btn').text()).toContain('删除勾选(0)', '成功后清勾选')
expect(wrapper.get('.jd-delete-btn').text()).toContain('批量删除(0)', '成功后清勾选')
wrapper.unmount()
})
@@ -262,30 +268,42 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
})
})
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」+同日收敛
* 「不需要全部分类 默认卡在未分类上就行」):工具栏「筛选分类状态」下拉只有两档
* (已分类/未分类),出厂默认与「重置」都卡未分类;选中即查重回第一页;
* 页面发的是筛选态字符串(classified/ungrouped),布尔换算收在 jd-product-filter 单一出口
* (纯测试钉形状)。 */
describe('分类状态快筛(两档,默认卡未分类)', () => {
it('下拉只有两档且首屏就卡「未分类」(classified="ungrouped" 随首取下发)', async () => {
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」+同日定默认卡未分类;
* 2026-11-18 用户口径「加个全部选项」恢复全量档):工具栏「筛选分类状态」下拉三档
* (全部/已分类/未分类),出厂默认与「重置」仍卡未分类(11-17 口径不动);
* 「全部」(value='')选中即查当前分组全部商品——序列化不下发 classified 参数;
* 页面发的是筛选态字符串(''/classified/ungrouped),布尔换算收在 jd-product-filter
* 单一出口(纯测试钉形状)。 */
describe('分类状态快筛(三档,默认卡未分类)', () => {
it('下拉三档且首屏就卡「未分类」(classified="ungrouped" 随首取下发)', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(optionLabels(wrapper, '筛选分类状态')).toEqual(['已分类', '未分类'])
expect(optionLabels(wrapper, '筛选分类状态')).toEqual(['全部', '已分类', '未分类'])
expect(jdApi.fetchJdProductList.mock.calls[0][0].classified).toBe('ungrouped',
'首屏默认档=未分类——用户口径「默认卡在未分类上就行」')
wrapper.unmount()
})
it('选「已分类」下发 classified 态;「重置」不放开筛选,而是回默认未分类档', async () => {
it('选「全部」下发不带 classified 键(查当前分组全部商品);选「已分类」下发 classified 态', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await pickSelectOption(wrapper, '筛选分类状态', '全部')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).not.toHaveProperty('classified',
'value=\'\' 序列化不下发 classified 参数=后端跳过谓词查全部')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1 }, '选中即查回第一页')
await pickSelectOption(wrapper, '筛选分类状态', '已分类')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].classified).toBe('classified')
wrapper.unmount()
})
it('「重置」不放开筛选,而是回默认未分类档', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await pickSelectOption(wrapper, '筛选分类状态', '已分类')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].classified).toBe('classified')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1 }, '选中即查回第一页')
await wrapper.findAll('button').find((b) => b.text() === '重置')!.trigger('click')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].classified).toBe('ungrouped',
'重置回出厂默认档(未分类),界面没有「全部」这一档可回')
'重置回出厂默认档(未分类),「全部」只是可选项不接默认')
wrapper.unmount()
})
})
@@ -307,7 +325,7 @@ describe('分类管理入口(V204 独立页并入京东数据库页)', () =>
await flushPromises()
const modal = wrapper.get('.manage-modal')
expect(modal.text()).toContain('分类管理')
expect(modal.text()).toContain('甲组', '标题带当前分组名')
expect(modal.text()).not.toContain('甲组', '标题不带分组名后缀(ea9dca3f 用户口径「不要显示周丽娥」)')
expect(modal.get('.search-input').exists()).toBe(true, '搜索框是本对话框新能力')
expect(modal.text()).toContain('裙装')
expect(jdApi.fetchJdProductGroups.mock.calls.length).toBeGreaterThan(callsBefore,
@@ -343,6 +361,55 @@ describe('分类管理入口(V204 独立页并入京东数据库页)', () =>
})
})
/** 平台超管空态直建分组(2026-11-17 用户口径「admin 权限最大」):京东侧还没有任何
* 数据权限分组时,分类管理弹窗给平台超管开直建口子;建完 group-created ⇒ 父页整条
* 作用域重取,当前分组翻到新组、分类下拉与弹窗列表随新组走——从「死路」到「接着建
* 分类」一气呵成。scope.platformSuperAdmin 是这条链的唯一开关,非超管维持空态文案。 */
describe('平台超管空态直建分组(页面级链路)', () => {
it('超管 + 京东侧零分组:弹窗出直建表单,建组走 POST(jd 档) 且作用域重取翻到新组', async () => {
let scopeFetchCount = 0
jdApi.fetchJdCategoryScope.mockImplementation(() => {
scopeFetchCount += 1
return scopeFetchCount === 1
? Promise.resolve({ platformSuperAdmin: true, defaultGroupId: null, groups: [] })
: Promise.resolve({
platformSuperAdmin: true,
defaultGroupId: 21,
groups: [{ id: 21, name: '京东-团队', label: '京东-团队', editable: true }],
})
})
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('button').find((b) => b.text() === '分类管理')!.trigger('click')
await flushPromises()
const modal = wrapper.get('.manage-modal')
expect(modal.get('[aria-label="新分组名称"]').exists()).toBe(true, '超管空态不是死路文案')
await modal.get('[aria-label="新分组名称"]').setValue('京东-团队')
await modal.findAll('button').find((b) => b.text() === '新建分组')!.trigger('click')
await flushPromises()
await flushPromises()
await flushPromises()
expect(groupApi.createShopGroup).toHaveBeenCalledWith('京东-团队', [], 1, 'jd')
expect(jdApi.fetchJdCategoryScope).toHaveBeenCalledTimes(2, 'group-created ⇒ 父页整条作用域重取')
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(21)
expect(wrapper.find('[aria-label="新分组名称"]').exists()).toBe(false, '有组了直建口子关掉')
expect(wrapper.get('.manage-modal').text()).toContain('本组暂无分类,先新建一个', '接着就能建分类')
wrapper.unmount()
})
it('非超管 + 京东侧零分组:弹窗维持空态文案,无直建表单(口子不开给组长/公司超管)', async () => {
jdApi.fetchJdCategoryScope.mockResolvedValue({ platformSuperAdmin: false, defaultGroupId: null, groups: [] })
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('button').find((b) => b.text() === '分类管理')!.trigger('click')
await flushPromises()
const modal = wrapper.get('.manage-modal')
expect(modal.text()).toContain('你还不属于任何数据权限分组')
expect(modal.find('[aria-label="新分组名称"]').exists()).toBe(false)
expect(groupApi.createShopGroup).not.toHaveBeenCalled()
wrapper.unmount()
})
})
describe('京东数据库页(v1.4 Phase 5)', () => {
it('挂载后按首屏分页参数取列表(pageSize 默认 20、不带公司维度),行数=本页条数', async () => {
const wrapper = await mountWith({ items: [item(1), item(2), item(3)], total: 42, page: 1, pageSize: 20 })
@@ -353,7 +420,8 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
// 公司维度 2026-11-16 整页摘除:入参层不再有 companyId 键(单参 toHaveProperty 才是「键不存在」的真判据)。
expect(firstCall).not.toHaveProperty('companyId')
expect(wrapper.findAll('tbody tr')).toHaveLength(3)
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
// 汇总条(共 X 条京东商品)2026-11-17 用户口径删除:不再渲染(反钉)。
expect(wrapper.find('.jd-summary').exists()).toBe(false, '汇总条已按 2026-11-17 用户口径删除')
})
it('行列字段与顺序(2026-11-15 用户口径;状态列+创建/修改两列 2026-11-16 客户口径「不需要采集/不要」下线仍收详情抽屉;操作置末「操作放最后一列」):勾选/分组/商品信息(图+标题+编码+货号+品牌·类目+SKU/信息分)/总库存/价格/同步/操作(7 列;店铺列 2026-11-15 下线)', async () => {
@@ -744,7 +812,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
const wrapper = await mountWith({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 })
// 批量删除常显(2026-11-16 客户口径「不要勾选后才显示」):未勾选时就在,只是置灰。
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true, '工具栏「删除勾选」常显')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true, '「批量删除」常显')
expect(wrapper.find('.jd-delete-btn').attributes('disabled')).toBeDefined()
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
await boxes[0].setValue(true)
@@ -757,7 +825,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(confirmMock).toHaveBeenCalledTimes(1)
const options = confirmMock.mock.calls[0][0]
expect(options.title).toBe('删除京东商品')
expect(options.message).toContain('确定删除勾选的 2 个商品吗')
expect(options.message).toContain('确定批量删除选中的 2 个商品吗')
expect(options.message).toContain('jd-products 桶内图片文件一并删除', '确认弹窗必须点名「桶文件也会删」')
expect(options.danger).toBe(true)
@@ -811,15 +879,15 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
})
})
/** 写权限分档(2026-11-16 用户口径收窄商品行写;2026-11-17 弹窗下线后更新):
* 商品行写(编辑/删除/勾选批量删)只对平台超管渲染;分类写(批量编辑分类、分类管理)由
* scope 的每组 editable 决定(本组管理员/公司超管/平台超管)——同组普通号在本页只读,
* 分类维护入口=工具栏「分类管理」对话框(V204 独立页 2026-11-17 并入,只读可看)。
* 勾选列 2026-11-17 起对本组可写分类管理员开放(服务批量归类),商品行按钮仍只归平台超管。 */
describe('京东数据库写权限分档(商品行写=平台超管;分类写=本组 editable)', () => {
it('非超管且本组不可写:无勾选列、无操作列、无删除勾选、无批量编辑分类;列表/筛选/详情照常', async () => {
useAdminSessionStore().user = { id: 2, username: 'ops', role: 'admin' }
// 同组普通号:可见但不可写(editable=false)。
/** 写权限分档(2026-11-17 用户口径「超管+管理员都可以,只有普通员工不能操作」,推翻
* 2026-11-16 的平台超管单档):商品行写(编辑/删除/勾选批量删)对管理员级(超管/admin 档)
* 渲染,普通账号只读;分类写(批量编辑分类、分类管理)由 scope 的每组 editable 决定
* (本组管理员/公司超管/平台超管)。同日口径「超管可以有分组筛选,管理员及以下则没有」:
* 筛选行「分组」控件整块只对超管档(超级管理员/公司超级管理员)渲染。 */
describe('京东数据库写权限分档(商品行写=超管+管理员;分组筛选=超管档;分类写=本组 editable)', () => {
it('普通员工且本组不可写:无勾选列、无操作列、无批量删除、无批量编辑分类、无分组控件;列表/筛选/详情照常', async () => {
useAdminSessionStore().user = { id: 2, username: 'ops', role: 'normal' }
// 普通员工:可见但不可写(editable=false)。
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(false))
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
jdApi.fetchJdProductDetail.mockImplementation(() =>
@@ -827,18 +895,21 @@ describe('京东数据库写权限分档(商品行写=平台超管;分类
)
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(0, '不可写分类的普通号没有勾选列')
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(0, '不可写分类的普通员工没有勾选列')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(false, '批量删除按钮不渲染')
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(false, '分类写入口不渲染(本组不可写)')
expect(wrapper.findAll('button').some((b) => b.text() === '分类管理')).toBe(true,
'分类管理入口是读面,普通号也能打开看(写控件由对话框按 editable 分档)')
'分类管理入口是读面,普通员工也能打开看(写控件由对话框按 editable 分档)')
expect(wrapper.find('thead').text()).not.toContain('操作', '操作列(编辑/删除)不渲染')
expect(wrapper.text()).toContain('只读:编辑/删除仅超级管理员可用', '只读提示必须看得见并区分两类写权限')
expect(wrapper.text()).toContain('只读:编辑/删除需超级管理员或管理员', '只读提示必须看得见并区分两类写权限')
expect(wrapper.text()).toContain('分类在本页「分类管理」查看与维护', '提示把分类维护入口指向本页「分类管理」(独立页已并入)')
// 分组筛选=超管档专属(2026-11-17 口径):普通员工连单组锁定芯片都不出。
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false, '普通员工不出分组下拉')
expect(wrapper.find('.jd-group-locked').exists()).toBe(false, '普通员工不出分组锁定芯片')
// 读面不受影响:筛选下拉、列表行、点行开详情都还在。
expect(wrapper.get('[aria-label="筛选店铺分类"]').exists()).toBe(true, '分类筛选是读面,保留')
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(5, '普通号列表 5 列:分类/商品信息/总库存/价格/同步时间')
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(5, '普通员工列表 5 列:分类/商品信息/总库存/价格/同步时间')
await wrapper.findAll('tbody tr')[0].trigger('click')
await flushPromises()
await flushPromises()
@@ -847,7 +918,7 @@ describe('京东数据库写权限分档(商品行写=平台超管;分类
wrapper.unmount()
})
it('超管保留全部写入口(勾选列+操作列+删除勾选+批量编辑分类),且不显示只读提示', async () => {
it('超管保留全部写入口(勾选列+操作列+批量删除+批量编辑分类),且不显示只读提示', async () => {
// beforeEach 默认 super_admin;这里显式再钉一次,防默认值漂移把这条闸门变成恒绿。
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
@@ -857,18 +928,35 @@ describe('京东数据库写权限分档(商品行写=平台超管;分类
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(true)
expect(wrapper.text()).not.toContain('只读:')
expect(wrapper.find('.jd-group-locked').exists()).toBe(true, '超管档保留分组控件(单组=锁定芯片)')
wrapper.unmount()
})
it('本组管理员(非平台超管):商品行按钮仍无,但勾选列随批量编辑分类放开(6 列形状)', async () => {
it('公司超级管理员属超管档:写入口齐+分组控件在(单组=锁定芯片)', async () => {
useAdminSessionStore().user = { id: 4, username: 'company-root', role: 'company_super_admin' }
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(1)
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(7, '公司超管 7 列:含操作列')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true, '批量删除对公司超管渲染')
expect(wrapper.text()).not.toContain('只读:')
expect(wrapper.find('.jd-group-locked').exists()).toBe(true, '公司超管保留分组控件')
wrapper.unmount()
})
it('管理员(admin 档):商品行写全放开(7 列+批量删除),分组控件整块不渲染', async () => {
useAdminSessionStore().user = { id: 3, username: 'leader', role: 'admin' }
// 组长档形状:可见组可写 ⇒ editable=true;商品行写仍按 isSuperAdmin 判(不受 editable 影响)。
// 组长档形状:可见组可写 ⇒ editable=true;商品行写按管理员档判(2026-11-17 口径)。
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(true))
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(6, '管理员 6 列:勾选/分类/商品信息/总库存/价格/同步时间(无操作列)')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(false, '批量删除(商品行写)仍只归平台超管')
expect(wrapper.find('thead').text()).not.toContain('操作')
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(7, '管理员 7 列:勾选/分类/商品信息/总库存/价格/同步/操作')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true, '批量删除(商品行写)对管理员渲染')
expect(wrapper.find('thead').text()).toContain('操作', '操作列(编辑/删除)对管理员渲染')
expect(wrapper.text()).not.toContain('只读:')
// 分组筛选=超管档专属:管理员即使本组可写分类,也不出下拉/锁定芯片。
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false, '管理员不出分组下拉')
expect(wrapper.find('.jd-group-locked').exists()).toBe(false, '管理员不出分组锁定芯片')
const editBtn = wrapper.findAll('button').find((b) => b.text() === '批量编辑分类')
expect(editBtn, '本组管理员有批量编辑分类入口').toBeTruthy()
@@ -886,6 +974,48 @@ describe('京东数据库写权限分档(商品行写=平台超管;分类
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], 7, GROUP_A)
wrapper.unmount()
})
it('管理员多组可见也不出「分组」下拉(超管档专属),写入口与默认组取数照常', async () => {
useAdminSessionStore().user = { id: 3, username: 'leader', role: 'admin' }
jdApi.fetchJdCategoryScope.mockResolvedValue({
platformSuperAdmin: false,
defaultGroupId: 11,
groups: [
{ id: 11, name: 'A组', label: '甲公司 / A组', editable: true },
{ id: 12, name: 'B组', label: '甲公司 / B组', editable: false },
],
})
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
// 多组对管理员也不渲染切换下拉(作用域静默落在默认组)。
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false, '多组也不给管理员出分组下拉')
// 写入口不受影响:操作列+批量删除都在,列表按默认组取。
expect(wrapper.find('thead').text()).toContain('操作')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(11)
expect(jdApi.fetchJdProductList.mock.calls[0][0]).toMatchObject({ ownerGroupId: 11 })
wrapper.unmount()
})
it('公司超级管理员多组可见:分组下拉在(超管档专属),可切组取数', async () => {
useAdminSessionStore().user = { id: 4, username: 'company-root', role: 'company_super_admin' }
jdApi.fetchJdCategoryScope.mockResolvedValue({
platformSuperAdmin: false,
defaultGroupId: 11,
groups: [
{ id: 11, name: 'A组', label: '甲公司 / A组', editable: true },
{ id: 12, name: 'B组', label: '甲公司 / B组', editable: true },
],
})
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(true, '公司超管保留分组下拉')
await pickSelectOption(wrapper, '当前分组', '甲公司 / B组')
await flushPromises()
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(12)
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ownerGroupId: 12, page: 1 })
wrapper.unmount()
})
})
describe('京东数据库分类按数据权限分组隔离(V203)', () => {
@@ -0,0 +1,186 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import MenusPage from '@/pages/account/MenusPage.vue'
import type { MenuManageNode } from '@/pages/account/menu-manage-model'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { usePlatformTabStore } from '@/stores/platform-tab'
const menuApi = vi.hoisted(() => ({
loadMenuManageTree: vi.fn(),
createMenu: vi.fn(),
updateMenu: vi.fn(),
deleteMenu: vi.fn(),
reorderMenus: vi.fn(),
}))
vi.mock('@/pages/account/menu-manage-api', () => menuApi)
/** 同一次加载返回完整字典,平台隔离由真实页面完成。 */
function mixedMenuTree(): MenuManageNode[] {
let nextId = 1
function node(
columnKey: string,
name: string,
menuType: 'admin' | 'app',
children: MenuManageNode[] = [],
): MenuManageNode {
const id = nextId++
return {
id, columnKey, name, menuType, parentId: null, routePath: '', sortOrder: id,
children: children.map((child) => ({ ...child, parentId: id })),
}
}
return [
node('video_image', '视频图片', 'app'),
node('admin_account', '账号与权限管理', 'admin', [
node('admin_columns', '菜单权限管理', 'admin'),
node('admin_users', '用户管理', 'admin'),
node('admin_group_manage', '分组管理', 'admin'),
node('admin_companies', '公司管理', 'admin'),
node('admin_user_secrets', '密钥管理', 'admin'),
node('admin_user_secret_usage', '密钥用量统计', 'admin'),
]),
node('admin_data', '数据管理', 'admin', [
node('admin_shop_manage', '店铺管理', 'admin'),
node('admin_appearance_patent', '外观专利管理', 'admin'),
node('admin_similar_asin', '相似ASIN管理', 'admin'),
node('admin_price_track', '跟价管理', 'admin'),
node('admin_collect_data', '采集数据管理', 'admin'),
node('admin_publish', '发布管理', 'admin'),
node('admin_brand', '品牌管理', 'admin'),
node('admin_records', '生成记录管理', 'admin'),
node('admin_jd_database', '京东数据库', 'admin'),
]),
node('jd_tools', '京东工具台', 'app', [
node('jd-collect', '京东店铺数据采集', 'app'),
node('jd-publish', '京东商品上架', 'app'),
]),
]
}
let pinia: Pinia
let wrapper: VueWrapper<Element> | undefined
let host: HTMLDivElement
beforeEach(() => {
vi.clearAllMocks()
window.localStorage.removeItem('admin-platform-tab')
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
useCompanyTabStore().setActiveId(7)
menuApi.loadMenuManageTree.mockResolvedValue(mixedMenuTree())
host = document.createElement('div')
document.body.appendChild(host)
})
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
host.remove()
window.localStorage.removeItem('admin-platform-tab')
})
async function mountMenus() {
wrapper = mount(MenusPage, { attachTo: host, global: { plugins: [pinia, ElementPlus] } })
await flushPromises()
expect(menuApi.loadMenuManageTree).toHaveBeenCalledWith(7)
return wrapper
}
function visibleNames(page: VueWrapper<Element>) {
return page.findAll('tbody .menu-name-text').map((cell) => cell.text())
}
async function clickNextPage(page: VueWrapper<Element>) {
const next = page.findAll('.old-pagination button').find((button) => button.text() === '下一页')
expect(next).toBeTruthy()
expect(next!.attributes('disabled')).toBeUndefined()
await next!.trigger('click')
await flushPromises()
}
/** 通过真实分页收齐表格行,避免只检查首屏而漏掉后页的跨平台菜单。 */
async function allVisibleNames(page: VueWrapper<Element>) {
const names = visibleNames(page)
while (true) {
const next = page.findAll('.old-pagination button').find((button) => button.text() === '下一页')
if (!next || next.attributes('disabled') !== undefined) return names
await clickNextPage(page)
names.push(...visibleNames(page))
}
}
async function pickMenuType(page: VueWrapper<Element>, label: string) {
const input = page.get('[aria-label="筛选菜单类型"]')
await input.trigger('click')
await flushPromises()
const contentId = input.attributes('aria-controls')
const panel = contentId ? document.getElementById(contentId) : null
expect(panel).toBeTruthy()
const option = [...panel!.querySelectorAll('.el-select-dropdown__item')]
.find((item) => !item.classList.contains('is-hidden') && item.textContent?.trim() === label)
expect(option).toBeTruthy()
await new DOMWrapper(option!).trigger('click')
await flushPromises()
}
describe('菜单权限配置页的平台隔离', () => {
it('京东表格排除视频图片和密钥,保留账号基础菜单、数据管理祖先及京东工具', async () => {
usePlatformTabStore().setActive('jd')
const page = await mountMenus()
expect(await allVisibleNames(page)).toEqual([
'账号与权限管理', '菜单权限管理', '用户管理', '分组管理', '公司管理',
'数据管理', '京东数据库', '京东工具台', '京东店铺数据采集', '京东商品上架',
])
const databaseRow = page.findAll('tbody tr')
.find((row) => row.find('.menu-name-text').text() === '京东数据库')
expect(databaseRow!.findAll('td')[4].text()).toBe('数据管理')
expect(databaseRow!.find('.column-child-mark').exists()).toBe(true)
})
it('从京东切回亚马逊,视频图片和密钥仍在,京东数据库及京东工具均消失', async () => {
usePlatformTabStore().setActive('jd')
const page = await mountMenus()
usePlatformTabStore().setActive('amazon')
await flushPromises()
expect(await allVisibleNames(page)).toEqual([
'视频图片', '账号与权限管理', '菜单权限管理', '用户管理', '分组管理', '公司管理',
'密钥管理', '密钥用量统计', '数据管理', '店铺管理', '外观专利管理',
'相似ASIN管理', '跟价管理', '采集数据管理', '发布管理', '品牌管理', '生成记录管理',
])
expect(menuApi.loadMenuManageTree).toHaveBeenCalledTimes(1)
})
it('带名称和类型筛选进入第二页后切平台,回到第一页并清空两项筛选', async () => {
const page = await mountMenus()
const nameInput = page.get<HTMLInputElement>('input[placeholder="输入菜单名称"]')
await nameInput.setValue('管理')
await pickMenuType(page, '后台')
expect(page.findAll('.menus-filter-row .el-select__selected-item').map((item) => item.text())).toContain('后台')
expect(page.findAll('tbody .menu-type-text').every((cell) => cell.text() === '后台')).toBe(true)
await clickNextPage(page)
expect(page.get('.page-cur').text()).toBe('第 2 / 2 页')
expect(visibleNames(page).length).toBeGreaterThan(0)
expect(visibleNames(page).every((name) => name.includes('管理'))).toBe(true)
usePlatformTabStore().setActive('jd')
await flushPromises()
expect(nameInput.element.value).toBe('')
expect(page.findAll('.menus-filter-row .el-select__selected-item').map((item) => item.text())).toContain('全部')
expect(page.get('.page-cur').text()).toBe('第 1 / 1 页')
expect(page.get('.page-total').text()).toBe('共 10 条')
expect(visibleNames(page)).toEqual([
'账号与权限管理', '菜单权限管理', '用户管理', '分组管理', '公司管理',
'数据管理', '京东数据库', '京东工具台', '京东店铺数据采集', '京东商品上架',
])
expect(menuApi.loadMenuManageTree).toHaveBeenCalledTimes(1)
})
})
@@ -13,20 +13,22 @@ import { toCompanyPayload } from '../src/api/companies-dto.ts'
/**
* 账号域三页按平台 tab 分列(V206,2026-11-17 用户口径「这些亚马逊这边也要有……数据都是新的
* 别把亚马逊的带过来」):users/company/biz_shop_manage_group 三表加 platform 列,存量默认亚马逊;
* 前端同一套组件两 tab 共显,请求带 platform=当前 tab,弹窗单选默认当前平台、可翻档归侧。
* 前端同一套组件两 tab 共显,请求带 platform=当前 tab。
* 平台不设手选(2026-11-17 用户口径「有京东就不需要亚马逊了,亚马逊那边也是」):弹窗不再出
* 「所属平台」单选——新建取当前平台 tab,编辑保持行值;值仍随保存下发(后端契约不变)。
* 上架上限(jd_publish_quota)只属京东口径:编辑弹窗隐藏 + 校验/下发都跳过 + 列表列仅京东侧。
*/
// ---------- 纯函数:payload 的 platform 下发与翻档 ----------
// ---------- 纯函数:payload 的 platform 下发 ----------
test('建号 payload 恒带 platform:京东 tab 建的号默认归京东,单选翻档即改归属', () => {
test('建号 payload 恒带 platform:京东 tab 建的号默认归京东(平台跟随当前 tab,弹窗不手选)', () => {
const jd = toCreateUserRequest({ ...createEmptyCreateUserForm(), username: 'a', password: 'secret123', platform: 'jd' })
assert.equal(jd.platform, 'jd')
const amazon = toCreateUserRequest({ ...createEmptyCreateUserForm(), username: 'a', password: 'secret123' })
assert.equal(amazon.platform, 'amazon', '空表单缺省亚马逊(存量口径),后端 normalizeOrCreate 同口径兜底')
})
test('编辑回填 platform:行值 jd→jd,缺省/未知→amazon;请求体恒下发 platform(翻档即挪列)', () => {
test('编辑回填 platform:行值 jd→jd,缺省/未知→amazon;请求体恒下发 platform(编辑保持行值)', () => {
const jdForm = fillEditUserForm({ id: 7, username: '京东号', role: 'normal', platform: 'jd' })
assert.equal(jdForm.platform, 'jd')
assert.equal(toEditUserUpdateRequest(jdForm).platform, 'jd')
@@ -34,7 +36,7 @@ test('编辑回填 platform:行值 jd→jd,缺省/未知→amazon;请求
const legacy = fillEditUserForm({ id: 8, username: '存量号', role: 'normal' })
assert.equal(legacy.platform, 'amazon', '旧负载没有 platform 时归亚马逊(存量默认),不许渲染成空串')
assert.equal(toEditUserUpdateRequest(legacy).platform, 'amazon', 'platform 恒下发:单选恒渲染,后端显式才落')
assert.equal(toEditUserUpdateRequest(legacy).platform, 'amazon', 'platform 恒下发:编辑保持行值,后端显式才落')
})
test('includeQuota=false(亚马逊侧编辑):不下发 jdPublishQuota,校验也跳过;platform 照常下发', () => {
@@ -97,7 +99,7 @@ test('CompaniesPage:公司列表带平台、切平台重取数、编辑弹窗
assert.match(page, /:platform="platformTab\.active"/, '新建公司弹窗默认落当前平台')
})
test('EditUserDialog:上架上限仅京东侧显示且不参与亚马逊侧提交;所属平台单选恒在', () => {
test('EditUserDialog:上架上限仅京东侧显示且不参与亚马逊侧提交;所属平台不设手选', () => {
const dialog = readSource('src/pages/account/EditUserDialog.vue')
assert.match(dialog, /v-if="includeQuota && \(targetIsCompanySuperAdmin \|\| form\.role === 'admin'\)"/,
'quota 项必须叠上 includeQuota(京东侧)条件——只按角色判断会把该项带进亚马逊侧弹窗')
@@ -105,26 +107,30 @@ test('EditUserDialog:上架上限仅京东侧显示且不参与亚马逊侧提
'提交必须透传 includeQuota:亚马逊侧校验与下发都跳过 quota')
assert.match(dialog, /validateEditUserForm\(form, \{ includeQuota: includeQuota\.value \}\)/,
'校验与下发同口径(校验过了但不下发 = 静默改值)')
assert.match(dialog, /v-model="form\.platform"/, '所属平台单选恒在:翻档是把记录挪到另一平台列表的唯一入口')
assert.doesNotMatch(dialog, /v-model="form\.platform"/,
'所属平台不设手选(2026-11-17 用户口径):平台跟随当前平台 tab,把单选写回来即红')
assert.match(dialog, /props\.platform === 'jd'/, 'includeQuota 取自页面透传的当前平台')
assert.match(dialog, /form\.platform = base\.platform/, '打开弹窗必须回填行值(旧负载缺省归亚马逊)')
assert.match(dialog, /form\.platform = base\.platform/, '打开弹窗必须回填行值(旧负载缺省归亚马逊;保存原样下发)')
})
test('CreateUserDialog/GroupEditorDialog/CompanyEditorDialog:新建默认当前平台、编辑回填行值', () => {
test('CreateUserDialog/GroupEditorDialog/CompanyEditorDialog:平台不设手选,新建默认当前平台、编辑回填行值', () => {
const create = readSource('src/pages/account/CreateUserDialog.vue')
assert.match(create, /form\.platform = props\.platform \?\? 'amazon'/, '建号默认当前平台 tab')
assert.match(create, /v-model="form\.platform"/, '所属平台单选在')
assert.doesNotMatch(create, /v-model="form\.platform"/,
'建号弹窗不设平台手选(2026-11-17 用户口径):把单选写回来即红')
const group = readSource('src/pages/account/GroupEditorDialog.vue')
assert.match(group, /groupPlatform\.value = props\.platform \?\? 'amazon'/, '新建分组默认当前平台 tab')
assert.match(group, /props\.group\.platform === 'jd' \? 'jd' : 'amazon'/, '编辑分组回填行值')
assert.match(group, /createShopGroup\(groupName\.value, memberIds\.value, operatorId, groupPlatform\.value\)/,
'创建分组必须带平台')
assert.doesNotMatch(group, /v-model="groupPlatform"/, '分组弹窗不设平台手选:把单选写回来即红')
assert.match(group, /createShopGroup\(groupName\.value, memberIds\.value, leaderId, groupPlatform\.value\)/,
'创建分组必须带平台(createdById=所选组长,2026-11-18 起超管可改选)')
assert.match(group, /updateShopGroup\(props\.group\.id, groupName\.value, memberIds\.value, groupPlatform\.value\)/,
'更新分组必须带平台(翻档归侧)')
'更新分组必须带平台(编辑保持行值下发)')
assert.doesNotMatch(group, /companyTab/, '分组弹窗不读公司 tab(既有口径:候选按组长公司取人)')
const company = readSource('src/pages/account/CompanyEditorDialog.vue')
assert.match(company, /platform: props\.platform \?\? 'amazon'/, '新建公司默认当前平台 tab')
assert.match(company, /props\.company\.platform === 'jd' \? 'jd' : 'amazon'/, '编辑公司回填行值')
assert.doesNotMatch(company, /v-model="form\.platform"/, '公司弹窗不设平台手选:把单选写回来即红')
})
@@ -3,18 +3,19 @@ import assert from 'node:assert/strict'
import type { AdminMenuNode } from '../src/types/admin.ts'
import {
BOTH_PLATFORM_MENU_KEYS,
JD_APP_MENU_KEYS,
JD_MENU_KEYS,
PLATFORM_TABS,
platformsOfMenuKey,
} from '../src/config/platform-scope.ts'
import { filterMenuTreeByPlatform, visiblePlatformsFor } from '../src/layout/platform-menu-filter.ts'
import { allowedPlatformsForUser, filterMenuTreeByPlatform, visiblePlatformsFor } from '../src/layout/platform-menu-filter.ts'
import { adminPages } from '../src/router/routes.ts'
/** 2026-11-16 用户定案「亚马逊/京东不混一起」:侧边栏顶部加平台 tab,京东侧=截图圈定
* 数据页(京东数据库/分类管理)。2026-11-17 用户口径「这些亚马逊这边也要有」:账号域三页
* (用户管理/分组管理/公司管理)改为双侧显示(BOTH_PLATFORM_MENU_KEYS),同一组件按当前
* tab 传 platform 过滤各自数据。tab 只做显示分组——菜单可见性仍由 session.menuTree(后端
* 按权限裁剪)决定,这里钉的是「分侧归属」与「空侧隐藏」两条形状。
* 按权限裁剪)决定,这里钉的是「分侧归属」「空侧隐藏」与「登录用户平台锁定」三条形状。
* 辅助定义在所有 test 之前:node:test 的用例回调按声明序执行,挪到文件尾会踩 TDZ。 */
const node = (key: string, name: string, route?: string, children?: AdminMenuNode[]): AdminMenuNode => {
@@ -53,17 +54,17 @@ test('menuKey 平台归属:京东独占即 [jd],双侧清单即两侧,其
for (const key of JD_MENU_KEYS) assert.deepEqual(platformsOfMenuKey(key), ['jd'], key)
for (const key of BOTH_PLATFORM_MENU_KEYS) assert.deepEqual(platformsOfMenuKey(key), ['amazon', 'jd'], key)
assert.deepEqual(platformsOfMenuKey('admin_query_asin'), ['amazon'])
assert.deepEqual(platformsOfMenuKey('admin_columns'), ['amazon'])
assert.deepEqual(platformsOfMenuKey('admin_columns'), ['amazon', 'jd'])
assert.deepEqual(platformsOfMenuKey('admin_group_account'), ['amazon'])
assert.deepEqual(platformsOfMenuKey('admin_jd_unknown_future'), ['amazon'])
assert.deepEqual(platformsOfMenuKey(''), ['amazon'])
})
test('京东 tab:账号与权限只余双侧三项,数据管理只余京东独占页(2026-11-17 分类管理并入京东数据库页后只剩数据库一页);顺序与 route 原样透传', () => {
test('京东 tab:账号与权限保留账号管理四项,隐藏密钥管理与用量统计;数据管理保留京东数据库', () => {
const filtered = filterMenuTreeByPlatform(TREE, 'jd')
assert.deepEqual(filtered.map((item) => item.key), ['admin_group_account', 'admin_group_data'])
assert.deepEqual(groupChildKeys(filtered, 'admin_group_account'),
['admin_users', 'admin_group_manage', 'admin_companies'])
['admin_columns', 'admin_users', 'admin_group_manage', 'admin_companies'])
// 2026-11-17 晚用户口径「京东分类管理并到京东数据库分类编辑里」:分类管理子菜单
// (V204)下线,京东侧数据管理组只剩京东数据库一页。
assert.deepEqual(groupChildKeys(filtered, 'admin_group_data'), ['admin_jd_database'])
@@ -115,7 +116,7 @@ test('tab 显示依据:两侧都有可见页才画 tab 条,仅一侧授权
assert.deepEqual(visiblePlatformsFor(null), [])
})
test('平台 tab 定义与两份菜单清单钉死(防清单漂移):京东独占仅数据库一页、双侧共用账号域三页', () => {
test('平台 tab 定义与菜单清单钉死(防清单漂移):京东独占后台仅数据库一页、双侧共用账号域三页、桌面端京东工具台三件(V209)', () => {
assert.deepEqual(PLATFORM_TABS, [
{ id: 'amazon', label: '亚马逊' },
{ id: 'jd', label: '京东' },
@@ -123,7 +124,12 @@ test('平台 tab 定义与两份菜单清单钉死(防清单漂移):京东
// 2026-11-17 晚分类管理(admin_jd_category_manage)并入京东数据库页后从清单摘除。
assert.deepEqual([...JD_MENU_KEYS], ['admin_jd_database'])
assert.deepEqual([...BOTH_PLATFORM_MENU_KEYS].sort(),
['admin_companies', 'admin_group_manage', 'admin_users'])
['admin_columns', 'admin_companies', 'admin_group_manage', 'admin_users'])
assert.deepEqual(platformsOfMenuKey('admin_user_secrets'), ['amazon'])
assert.deepEqual(platformsOfMenuKey('admin_user_secret_usage'), ['amazon'])
// 桌面端(app)清单与 JD_MENU_KEYS 分列:app 菜单没有 admin 路由,不得混进
// 「与 routes.ts 对撞」的那份(下方护栏用例只扫 JD_MENU_KEYS/BOTH 两份是刻意的)。
assert.deepEqual([...JD_APP_MENU_KEYS].sort(), ['jd-collect', 'jd-publish', 'jd_tools'])
})
test('两份清单的每一条都必须在路由注册表登记(同 company-menu-route 护栏形状:少登记=看得见点进去404)', () => {
@@ -132,3 +138,34 @@ test('两份清单的每一条都必须在路由注册表登记(同 company-me
assert.ok(registered.has(key), `平台侧菜单 key "${key}" 未在 src/router/routes.ts 登记 menuKey`)
}
})
test('allowedPlatformsForUser:站点超管随菜单树分布;其余用户锁 users.platform 一侧(未知/缺省按亚马逊)', () => {
assert.deepEqual(allowedPlatformsForUser(TREE, { role: 'super_admin', platform: 'jd' }), ['amazon', 'jd'],
'站点超管不限侧:双平台 tab 照画')
assert.deepEqual(allowedPlatformsForUser(TREE, { role: 'company_super_admin', platform: 'jd' }), ['jd'],
'京东用户锁京东侧:亚马逊 tab 消失(单侧时 tab 条整个隐藏)')
assert.deepEqual(allowedPlatformsForUser(TREE, { role: 'admin', platform: 'amazon' }), ['amazon'])
assert.deepEqual(allowedPlatformsForUser(TREE, { role: 'normal', platform: undefined }), ['amazon'],
'platform 缺省按亚马逊存量口径(与后端 AdminMenuPlatformScope.normalize 同形)')
assert.deepEqual(allowedPlatformsForUser(TREE, { role: 'company_super_admin', platform: 'weird' }), ['amazon'],
'未知平台值同样兜底亚马逊,不得读成京东侧')
assert.deepEqual(allowedPlatformsForUser(TREE, null), ['amazon', 'jd'],
'会话未就位(user 为空)按可见分布:锁定的收窄由 AdminLayout 在 user 就位后再做')
})
test('allowedPlatformsForUser:菜单树缺本平台页时仍锁死本人平台(宁空侧不放开被禁侧)', () => {
const amazonOnlyTree: AdminMenuNode[] = [
node('admin_group_data', '数据管理', undefined, [
node('admin_dedupe_total_data', '去重数据汇总', '/asin-center/registry'),
]),
]
assert.deepEqual(
allowedPlatformsForUser(amazonOnlyTree, { role: 'company_super_admin', platform: 'amazon' }),
['amazon'],
)
assert.deepEqual(
allowedPlatformsForUser(amazonOnlyTree, { role: 'company_super_admin', platform: 'jd' }),
['jd'],
'交集空回落单侧:管理角色必有双侧账号域页所以实际非空,异常形状下宁可空侧也不放开被禁侧',
)
})
+10 -4
View File
@@ -2,14 +2,20 @@ import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
// module 13 task 243:壳层换皮成 admin.html 蓝白浅色 —— 侧栏 252px 浅底、顶栏 76px、
// module 13 task 243:壳层换皮成 admin.html 蓝白浅色 —— 侧栏 252px 浅底、顶栏 56px、
// 角色胶囊 + 次级退出按钮、去掉顶栏重复 logo、菜单激活态浅蓝渐变+左蓝条。
test('test_task_243_shell_normal_primary_path', () => {
const css = readSource('src/styles/main.css')
assert.match(css, /\.admin-sidebar\s*\{[^}]*flex:\s*0\s*0\s*252px/, '侧栏宽度应为 252px')
assert.match(css, /\.admin-topbar\s*\{[^}]*min-height:\s*76px/, '顶栏高度应为 76px')
assert.match(css, /\.admin-topbar\s*\{[^}]*min-height:\s*56px/, '顶栏高度应为 56px')
assert.match(css, /linear-gradient\(180deg,\s*var\(--admin-sidebar\)\s*0%,/, '侧栏应为浅色渐变底')
// 壳层锁视口高(2026-11-18「菜单加个滚动条」绊线):.admin-shell 必须 height:100vh +
// overflow:hidden——侧边栏固定、菜单区 el-scrollbar 与内容区 overflow:auto 才能各自独立滚动;
// 改回 min-height 会把整条 flex 高度链放软、回落整页滚(侧边栏顶部被滚出视口)。
assert.match(css, /\.admin-shell\s*\{[^}]*height:\s*100vh/, '.admin-shell 必须锁视口高')
assert.match(css, /\.admin-shell\s*\{[^}]*overflow:\s*hidden/, '.admin-shell 必须 overflow:hidden')
assert.equal(/\.admin-shell\s*\{[^}]*min-height:\s*100vh/.test(css), false, '.admin-shell 不得回退 min-height:100vh')
})
test('test_task_243_shell_normal_variant_input', () => {
@@ -22,8 +28,8 @@ test('test_task_243_shell_normal_variant_input', () => {
test('test_task_243_shell_normal_repeated_operation_is_idempotent', () => {
const css = readSource('src/styles/main.css')
const first = /\.admin-topbar\s*\{[^}]*min-height:\s*76px/.test(css)
const second = /\.admin-topbar\s*\{[^}]*min-height:\s*76px/.test(css)
const first = /\.admin-topbar\s*\{[^}]*min-height:\s*56px/.test(css)
const second = /\.admin-topbar\s*\{[^}]*min-height:\s*56px/.test(css)
assert.equal(first, true)
assert.equal(first, second)
})
@@ -10,6 +10,12 @@ test('test_task_244_component_normal_primary_path', () => {
assert.match(css, /--el-table-header-bg-color:\s*#edf4fa/, '表头底色应对齐 admin #edf4fa')
assert.match(css, /--el-table-header-text-color:\s*#4e6479/, '表头文字色应对齐 admin')
assert.match(css, /--el-table-row-hover-bg-color:\s*#f1f7fb/, '行 hover 应对齐 admin')
assert.match(css, /\.admin-content\s*\{[^}]*padding:\s*12px 16px 20px/, '内容区应减少留白')
assert.match(css, /\.admin-content :is\(\.panel-box, \.form-box\)\s*\{[^}]*padding:\s*12px 14px/, '列表卡片应紧凑')
assert.match(css, /\.admin-content :is\(\.table-scroll, \.table-wrap\) :is\(th, td\)\s*\{[^}]*padding-top:\s*6px;\s*padding-bottom:\s*6px/, '普通列表应缩小行间距')
assert.match(css, /\.admin-content \.el-select\.admin-filter \.el-select__wrapper\s*\{[^}]*min-height:\s*34px/, '筛选下拉应与紧凑输入同高')
assert.match(css, /\.admin-content :is\(\.form-row, \.clean-filter-row, \.dedupe-filter-row, \.dedupe-filter-date-row, \.jd-filter-row\)\s*\{[^}]*display:\s*flex;\s*flex-wrap:\s*wrap/, '筛选栏必须随可用宽度换行')
assert.equal(/\.admin-menu \.el-menu-item\s*\{\s*display:\s*none/.test(css), false, '窄屏菜单项不能被直接隐藏')
})
test('test_task_244_component_normal_variant_input', () => {
+1 -1
View File
@@ -20,7 +20,7 @@ test('test_task_253_group_list_normal_variant_input', () => {
assert.match(page, /leaderUserId/, '判定依赖组长 leaderUserId')
const editor = readSource('src/pages/account/GroupEditorDialog.vue')
assert.match(editor, /组长/, '编辑弹窗含组长展示')
assert.match(editor, /当前登录用户/, '新建时组长只读为当前登录用户')
assert.match(editor, /当前登录用户/, '组长默认当前登录用户(超管新建可改选,编辑/非超管只读回显)')
})
test('test_task_253_group_list_normal_repeated_operation_is_idempotent', () => {
+3 -4
View File
@@ -88,10 +88,9 @@ test('test_task_048_normal_role_wording_agrees_across_all_exits', () => {
const buttons = [...dialog.matchAll(/<el-radio-button\s+value="([a-z_]+)">([^<]*)</g)].map(
(m) => [m[1], m[2]] as const,
)
// 2026-11-17 V206:弹窗新增「所属平台」单选(amazon/jd 两档)——角色按钮仍是前两枚,
// 平台按钮单独钉,四出口文案对平的意图不变。
assert.deepEqual(buttons.slice(0, 2), [['normal', word], ['admin', '管理员']], '编辑用户弹窗的角色按钮文案')
assert.deepEqual(buttons.slice(2), [['amazon', '亚马逊'], ['jd', '京东']], '所属平台单选两档(V206 翻档归侧的唯一入口)')
// 2026-11-17 V206 曾加「所属平台」单选;同日晚按用户口径「有京东就不需要亚马逊了」撤掉——
// 平台跟随当前平台 tab,弹窗回到只剩角色两枚按钮(平台手选回流会在这里红)。
assert.deepEqual(buttons, [['normal', word], ['admin', '管理员']], '编辑用户弹窗的角色按钮文案(且平台单选不得回流)')
})
/**
+16 -6
View File
@@ -1,7 +1,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
import { groupKeysForActive, toSidebarEntries } from '../src/layout/menu-mapper.ts'
import { allGroupKeys, toSidebarEntries } from '../src/layout/menu-mapper.ts'
import type { AdminMenuNode } from '../src/types/admin.ts'
function node(partial: Partial<AdminMenuNode> & { key: string; name: string }): AdminMenuNode {
@@ -89,11 +89,21 @@ test('test_task_006_menu_sidebar_mapping_invalid_input_rejected', () => {
})
test('test_task_006_menu_sidebar_mapping_dependency_failure_returns_actionable_message', () => {
// 依赖失败:壳层消费映射模块;激活分组展开按当前路由命中。
// 依赖失败:壳层消费映射模块;父菜单默认全展开(2026-11-17 用户口径「父菜单不要默认折叠」),
// 不再按激活路由命中展开;entries 变化后必须命令式补开(el-menu 的 default-openeds 只在挂载读一次)。
const layout = readSource('src/layout/AdminLayout.vue')
assert.match(layout, /toSidebarEntries/)
assert.match(layout, /groupKeysForActive/)
const active = toSidebarEntries(TREE)
assert.deepEqual(groupKeysForActive(active, '/account/menus'), ['account'])
assert.deepEqual(groupKeysForActive(active, '/account/nope'), [], '未命中路由不展开任何分组')
assert.match(layout, /allGroupKeys/)
assert.doesNotMatch(layout, /groupKeysForActive/, '按激活路由展开的旧行为不得回流')
assert.match(layout, /watch\(openedKeys/, 'entries 变化后必须命令式补开,否则切平台 tab 新组收起')
assert.match(layout, /nextTick/)
const entries = toSidebarEntries(TREE)
assert.deepEqual(allGroupKeys(entries), ['account'])
const mix = toSidebarEntries([
node({ key: 'g1', name: '分组一', children: [node({ key: 'c1', name: '子一', route: '/x/c' })] }),
node({ key: 'leaf', name: '顶级页', route: '/top' }),
node({ key: 'g2', name: '分组二', children: [node({ key: 'c2', name: '子二', route: '/y/c' })] }),
])
assert.deepEqual(allGroupKeys(mix), ['g1', 'g2'], '分组全部展开、顶级叶项不产生展开键')
assert.deepEqual(allGroupKeys(toSidebarEntries([])), [], '空菜单不产生展开键')
})
@@ -0,0 +1,110 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
filterMenuTreeNodesByPlatform,
JD_APP_MENU_KEYS,
platformsOfMenuKey,
} from '../src/config/platform-scope.ts'
import { filterMenuTreeByPlatform } from '../src/layout/platform-menu-filter.ts'
import type { MenuOptionNode } from '../src/pages/account/user-menu-auth.ts'
import { pruneCheckedIdsToTree } from '../src/pages/account/user-menu-auth.ts'
/**
* 授权树按平台过滤(2026-11-17 用户口径「这边也没有去掉亚马逊的」):建号/编辑弹窗的
* 菜单权限树在选「京东」时只留京东侧菜单(京东数据库+双侧账号域件),亚马逊菜单整枝
* 隐藏;切平台时勾选集收敛进可见树(pruneCheckedIdsToTree),否则京东档账号保存后仍带
* 亚马逊授权,平台分侧被静默架空。
*
* 算法与侧边栏同源(platform-scope.filterMenuTreeNodesByPlatform 唯一出口)——本文件
* 同时钉「两个消费方同形」:同一夹具喂侧边栏版与授权树版,逐层 key 序列必须一致
* (B79-12 同款钉法:一句判据在册有多份正本时,同形性本身要有人钉)。
*/
const node = (id: number, key: string, children?: MenuOptionNode[]): MenuOptionNode => {
const out: MenuOptionNode = { id, key, name: `菜单${id}`, sort: id, parentId: null, type: 'admin' }
if (children) out.children = children
return out
}
/** 授权树实测形状缩影:混编分组(京东库+亚马逊页混在一个分组下)+两侧叶子。 */
const TREE: MenuOptionNode[] = [
node(1, 'admin_group_account', [
node(11, 'admin_users'),
node(12, 'admin_group_manage'),
node(13, 'admin_companies'),
node(14, 'admin_columns'),
]),
node(2, 'admin_jd_database'),
node(3, 'admin_group_shop', [
node(31, 'admin_shop_keys'),
node(32, 'admin_shop_manage'),
]),
]
const keysOf = (nodes: MenuOptionNode[]): string[] =>
nodes.map((n) => (n.children?.length ? `${n.key}(${keysOf(n.children).join(',')})` : n.key))
test('京东侧:只剩京东数据库+双侧账号域件(2026-11-18 扩双侧后菜单权限配置也归京东侧),亚马逊分组整枝消失', () => {
const jd = filterMenuTreeNodesByPlatform(TREE, 'jd')
assert.deepEqual(keysOf(jd), [
'admin_group_account(admin_users,admin_group_manage,admin_companies,admin_columns)',
'admin_jd_database',
])
})
test('亚马逊侧:京东独占菜单消失,亚马逊菜单与账号域分组原样', () => {
const amazon = filterMenuTreeNodesByPlatform(TREE, 'amazon')
assert.deepEqual(keysOf(amazon), [
'admin_group_account(admin_users,admin_group_manage,admin_companies,admin_columns)',
'admin_group_shop(admin_shop_keys,admin_shop_manage)',
])
})
test('与侧边栏过滤同形:同一夹具两个消费方逐层 key 一致(B79-12 钉法)', () => {
for (const platform of ['amazon', 'jd'] as const) {
const viaSidebar = keysOf(filterMenuTreeByPlatform(TREE as never, platform) as never)
const viaAuthTree = keysOf(filterMenuTreeNodesByPlatform(TREE, platform))
assert.deepEqual(viaAuthTree, viaSidebar, `platform=${platform} 两处消费方必须同形`)
}
})
test('判定出口不变:京东独占/双侧/默认亚马逊三个档位原样(改档位先改这里再改清单)', () => {
assert.deepEqual(platformsOfMenuKey('admin_jd_database'), ['jd'])
assert.deepEqual(platformsOfMenuKey('admin_users'), ['amazon', 'jd'])
assert.deepEqual(platformsOfMenuKey('admin_shop_keys'), ['amazon'])
})
/** 桌面端(app)分区缩影:V209 京东工具台组+两工具子行,旁置亚马逊侧 app 菜单。 */
const APP_TREE: MenuOptionNode[] = [
node(51, 'jd_tools', [node(511, 'jd-collect'), node(512, 'jd-publish')]),
node(52, 'app_variant_collection'),
]
test('桌面端京东侧不再整组消失:jd_tools 组+两工具保留,亚马逊 app 菜单剪掉(2026-11-17「前台的京东少了」回归钉)', () => {
for (const key of JD_APP_MENU_KEYS) {
assert.deepEqual(platformsOfMenuKey(key), ['jd'], `V209 app 菜单 ${key} 必须判京东侧`)
}
const jd = filterMenuTreeNodesByPlatform(APP_TREE, 'jd')
assert.deepEqual(keysOf(jd), ['jd_tools(jd-collect,jd-publish)'],
'选京东时桌面端分区必须保留京东工具台整组(叶子 key 认京东,组按存活子项去留)')
})
test('桌面端亚马逊侧:京东工具台消失,亚马逊 app 菜单原样', () => {
const amazon = filterMenuTreeNodesByPlatform(APP_TREE, 'amazon')
assert.deepEqual(keysOf(amazon), ['app_variant_collection'])
})
test('pruneCheckedIdsToTree:勾选集收敛进可见树,隐藏侧 id 被剔除且原数组不动', () => {
const jd = filterMenuTreeNodesByPlatform(TREE, 'jd')
const checked = [11, 12, 2, 31, 99]
const snapshot = checked.slice()
const pruned = pruneCheckedIdsToTree(checked, jd)
assert.deepEqual(pruned, [2, 11, 12], '只留可见树内的 id(31=亚马逊店务、99=不存在)')
assert.deepEqual(checked, snapshot, '入参数组不被改写')
})
test('pruneCheckedIdsToTree:空树全剪、空勾选原样空、非法 id 不复活', () => {
assert.deepEqual(pruneCheckedIdsToTree([1, 2], []), [], '可见树为空=无可保留')
assert.deepEqual(pruneCheckedIdsToTree([], TREE), [])
assert.deepEqual(pruneCheckedIdsToTree([0, -3, 'x', 11.7], TREE), [11], '非法 id 按 normalizeMenuIds 口径收敛(丢弃/取整),不会原样漏进提交集')
})
@@ -73,7 +73,14 @@ public final class TaskModuleRegistry {
// 照常按天清理(商品行在 biz_jd_product 独立保留,不被清);Phase 2 判死登记定型:
// JdStaleTaskService 自带 @Scheduled(60 分钟超时线,selfScheduledStaleCheck=true,
// 同 publish/collect-data 先例),京麦登录态失效判死由回传侧经它落终态。
new Module("JD_SHOP_COLLECT", "京东店铺采集", false, true, false, true, Optional.empty())
new Module("JD_SHOP_COLLECT", "京东店铺采集", false, true, false, true, Optional.empty()),
// v1.5 京东商品上架(蓝图 docs/ITERATION_PLAN.md §4 Phase 2):resultFileJob=false——
// 不出 Excel 结果文件,行级结果落 biz_jd_publish_item(V210),行状态由客户端 chunk
// 回传推进;ageCleanup=true——任务行照常按天清理(发布明细行独立保留不随清,溯源);
// selfScheduledStaleCheck=true——JdPublishStaleTaskService 自带 @Scheduled(发布逐商品
// 页面自动化节奏慢,60 分钟超时线自管,同 JD_SHOP_COLLECT 先例);submitSecret=empty——
// 发布由桌面机已登录京麦的 Chrome 直连执行,无代理无 LLM(铁律 27c 登记结论)。
new Module("JD_PUBLISH", "京东上架", false, true, false, true, Optional.empty())
);
private TaskModuleRegistry() {
@@ -0,0 +1,152 @@
package com.nanri.aiimage.common.service;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 后台/桌面端菜单 key → 平台归属的唯一出处(2026-11-18 用户口径「隔离下除站点超管外,
* 京东用户只看京东菜单、亚马逊看不了」)。字面量与 admin-frontend-vue
* {@code src/config/platform-scope.ts} 同源同值:京东独占、双侧共用、其余(未知 key 在内)
* 默认亚马逊——前端对未知 key 也是默认亚马逊,两端口径必须同形。
*
* <p>语义边界:平台裁剪只挂在「菜单下发出口」({@code /api/admin/current-user/menus} 与登录 VO
* 的 adminColumns/appColumns)与逐页门 {@code requireConsolePageAccess};授权管理读/写接口
* (/permission-users/{uid}/column-permissions 与整树替换保存)**不裁**——授权行保留,
* 用户日后翻档(platform 改回另一侧)授权仍在,不因「打开编辑弹窗又保存」被静默清掉。</p>
*
* <p>过滤算法与前端 {@code filterMenuTreeNodesByPlatform} 同形:叶子按 key 归属保留;
* 分组节点自身的 key 不参与平台判定,按「有存活的子项」去留——否则京东侧「账号与权限」
* 这类混合分组(双侧页面 + 亚马逊页混编)会被整组误剪。扁平 VO 过滤会保留被保留节点的
* 祖先链,保证下游 {@code AdminMenuTreeBuilder.build} 组树完整。</p>
*/
public final class AdminMenuPlatformScope {
/** 京东后台独占菜单 key(与前端 JD_MENU_KEYS 逐字一致,用例钉住)。 */
public static final Set<String> JD_MENU_KEYS = Set.of("admin_jd_database");
/** 桌面端(app 树)京东菜单 key(与前端 JD_APP_MENU_KEYS 逐字一致,V209:组行 + 两工具子行)。 */
public static final Set<String> JD_APP_MENU_KEYS = Set.of("jd_tools", "jd-collect", "jd-publish");
/** 双侧共用账号管理页面;密钥管理与用量统计按 2026-11-18 截图口径收回亚马逊侧。 */
public static final Set<String> BOTH_MENU_KEYS = Set.of(
"admin_users", "admin_group_manage", "admin_companies", "admin_columns");
private AdminMenuPlatformScope() {
}
/**
* 平台归一:null/空白按 {@code amazon}(与 users.platform 列 DEFAULT 'amazon' 同口径,
* 也与前端 {@code user.platform === 'jd' ? 'jd' : 'amazon'} 同形)——实体没带平台值的
* 账号一律按亚马逊侧放行,不得把「没带」读成「京东侧全拦」。
*/
public static String normalize(String platform) {
return platform == null || platform.isBlank() ? AdminPlatformScope.AMAZON : platform;
}
/**
* menuKey → 平台归属:京东独占(后台或桌面端清单)→ {jd};双侧清单 → {amazon,jd};
* 其余(未知 key 在内)默认 {amazon}。key 缺省(null/空白)同样默认亚马逊,与前端
* {@code platformsOfMenuKey(node.key || '')} 对齐。
*/
public static Set<String> platformsOfMenuKey(String key) {
if (key == null || key.isBlank()) {
return Set.of(AdminPlatformScope.AMAZON);
}
if (JD_MENU_KEYS.contains(key) || JD_APP_MENU_KEYS.contains(key)) {
return Set.of(AdminPlatformScope.JD);
}
if (BOTH_MENU_KEYS.contains(key)) {
return Set.of(AdminPlatformScope.AMAZON, AdminPlatformScope.JD);
}
return Set.of(AdminPlatformScope.AMAZON);
}
/**
* 逐页门用:columnKeys 里是否存在「不归属该平台」的 key。双侧 key 两个平台都放行;
* 空 keys 返回 false(不构成越侧证据,交给原有授权判定处理)。
*/
public static boolean hasCrossPlatformKey(List<String> columnKeys, String platform) {
if (columnKeys == null || columnKeys.isEmpty()) {
return false;
}
String own = normalize(platform);
for (String key : columnKeys) {
if (!platformsOfMenuKey(key).contains(own)) {
return true;
}
}
return false;
}
/**
* 扁平菜单 VO 按平台过滤(下发出口专用):叶子按 key 归属保留;分组节点(有子项者)
* 按存活子项去留;被保留节点的祖先链一并保留,保证组树完整。null/空回空列表。
* 入参不被修改。
*/
public static List<PermissionMenuItemVo> filterMenuVosByPlatform(List<PermissionMenuItemVo> menus,
String platform) {
if (menus == null || menus.isEmpty()) {
return List.of();
}
String own = normalize(platform);
Map<Long, PermissionMenuItemVo> byId = new HashMap<>();
Map<Long, List<PermissionMenuItemVo>> childrenOf = new HashMap<>();
for (PermissionMenuItemVo menu : menus) {
if (menu == null || menu.getId() == null) {
continue;
}
byId.put(menu.getId(), menu);
if (menu.getParentId() != null) {
childrenOf.computeIfAbsent(menu.getParentId(), k -> new ArrayList<>()).add(menu);
}
}
Set<Long> keepIds = new LinkedHashSet<>();
for (PermissionMenuItemVo menu : byId.values()) {
if (subtreeHasPlatformLeaf(menu, childrenOf, own)) {
keepWithAncestors(menu, byId, keepIds);
}
}
if (keepIds.isEmpty()) {
return List.of();
}
List<PermissionMenuItemVo> out = new ArrayList<>();
for (PermissionMenuItemVo menu : menus) {
if (menu != null && menu.getId() != null && keepIds.contains(menu.getId())) {
out.add(menu);
}
}
return List.copyOf(out);
}
/** 叶子:key 归属判定;分组节点:任一子树存活即存活(孤儿/空分组随之被裁)。 */
private static boolean subtreeHasPlatformLeaf(PermissionMenuItemVo menu,
Map<Long, List<PermissionMenuItemVo>> childrenOf,
String platform) {
List<PermissionMenuItemVo> children = childrenOf.get(menu.getId());
if (children == null || children.isEmpty()) {
return platformsOfMenuKey(menu.getColumnKey()).contains(platform);
}
for (PermissionMenuItemVo child : children) {
if (child != null && subtreeHasPlatformLeaf(child, childrenOf, platform)) {
return true;
}
}
return false;
}
private static void keepWithAncestors(PermissionMenuItemVo menu,
Map<Long, PermissionMenuItemVo> byId,
Set<Long> keepIds) {
PermissionMenuItemVo current = menu;
while (current != null && current.getId() != null && keepIds.add(current.getId())) {
Long parent = current.getParentId();
current = parent == null ? null : byId.get(parent);
}
}
}
@@ -118,6 +118,13 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
* requireOwnershipUserId(fail-closed 401),chunk 与 heartbeat 和 collect-data/delete-brand
* 同形状(本机桌面执行器不带凭据,行归属以任务 owner 投影);chunk 的 error 上报已接整单
* 判死,其 owner 对撞收口随 v1.4 Phase 6.1 落,判死口凭据化后随统一批进名单</li>
* <li>{@code /api/jd-publish} —— v1.5 京东商品上架任务面(建单/products/activate/items/progress/
* dashboard/history/progress-batch/delete/chunk/heartbeat):与 /api/jd-collect 逐形状同族——建单等
* 写类端点方法体已有 requireOwnershipUserId
* (fail-closed 401,B98-07 同形债预防),products/dashboard/history/delete 走 resolveOwnershipUserId
* (Phase 4 面板读侧),progressBatch 走 require+filterOwnedTaskIds,chunk 判死口凭据化
* (isTrustedInternalToken,匿名一律拒绝判死),行级落库与 jd-collect 同形状(本机桌面执行器不带凭据,
* 行归属以任务 owner 投影);判死口凭据化后随统一批进名单</li>
* </ul>
*/
static final Set<String> PENDING_CONVERGENCE = Set.of(
@@ -127,7 +134,8 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
"/api/delete-brand",
"/api/module-templates",
"/api/split",
"/api/jd-collect");
"/api/jd-collect",
"/api/jd-publish");
private final RequestMappingHandlerMapping handlerMapping;
@@ -28,6 +28,9 @@ public class CollectRoutingProperties {
/** 京东店铺采集模块名(v1.4;紫鸟只在本机 Windows,默认通道必须 LOCAL,铁律 19 同形)。 */
public static final String MODULE_JD_SHOP_COLLECT = "JD_SHOP_COLLECT";
/** 京东商品上架模块名(v1.5;京麦登录态在用户桌面机 19899 Chrome profile,默认通道必须 LOCAL,铁律 19 同形)。 */
public static final String MODULE_JD_PUBLISH = "JD_PUBLISH";
/** LOCAL 通道的任务在 PENDING 超过多少分钟后允许 Linux 兜底认领。 */
private long linuxFallbackMinutes = 30L;
@@ -3,7 +3,9 @@ package com.nanri.aiimage.modules.admin.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.AdminMenuPlatformScope;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
@@ -76,6 +78,9 @@ public class AdminConsoleController {
// 所以这些键要与既有 companyId/companyName 的形状一致(前端 || '' 兜底)
item.put("companyId", operator.getCompanyId());
item.put("companyName", companyService.nameOrEmpty(operator.getCompanyId()));
// 所属平台(V206):前端据它把平台 tab 锁到本人一侧(2026-11-18 用户口径「隔离下
// 非站点超管只看自己平台侧」);站点超管前端不限侧,此值对它只是标记。
item.put("platform", operator.getPlatform());
// 到期续费提醒(V146):只反映自身 expires_at,不级联——续费是账号自己的事。
// expiresAt 为 yyyy-MM-dd HH:mm 或 null;daysToExpire 为剩余整天数或 null。
item.put("expiresAt", operator.getExpiresAt() == null ? null
@@ -93,6 +98,13 @@ public class AdminConsoleController {
List<PermissionMenuItemVo> menus = permissionMenuService.getUserColumnPermissions(
operator, operator.getId(), PermissionMenuService.MENU_TYPE_ADMIN, true);
menus = AdminMenuTreeBuilder.filterByMenuType(menus, PermissionMenuService.MENU_TYPE_ADMIN);
// 平台隔离(2026-11-18 用户口径「除站点超管外,京东用户只看京东菜单、亚马逊看不了」):
// 非站点超管按自身 users.platform 收窄下发树(京东用户只留京东侧+双侧账号域,其余
// 默认亚马逊侧裁掉;路由守卫随树拦截直达 URL)。只裁下发出口——授权管理读/写接口不裁,
// 整树替换保存语义不变,授权行保留(AdminMenuPlatformScope 类注释)。
if (!DeviceSessionPolicy.isSuperAdmin(operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())) {
menus = AdminMenuPlatformScope.filterMenuVosByPlatform(menus, operator.getPlatform());
}
List<Map<String, Object>> items = AdminMenuTreeBuilder.toMapList(AdminMenuTreeBuilder.build(menus));
return ApiResponse.success(Map.of("items", items));
}
@@ -10,8 +10,10 @@ import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.AdminMenuPlatformScope;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
@@ -23,6 +25,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.nanri.aiimage.common.security.JwtService;
@@ -279,8 +282,19 @@ public class AuthService {
vo.setDeviceId(deviceId);
vo.setToken(token);
vo.setExpiresIn(jwtService.ttlSeconds());
vo.setAppColumns(permissionMenuService.getUserColumnPermissions(user.getId(), PermissionMenuService.MENU_TYPE_APP));
vo.setAdminColumns(permissionMenuService.getUserColumnPermissions(user.getId(), PermissionMenuService.MENU_TYPE_ADMIN));
// 平台隔离(2026-11-18 用户口径「后管+桌面端一起」):非站点超管按 users.platform 收窄
// 登录下发菜单——adminColumns(后管)与 appColumns(桌面端)一并裁,京东用户的桌面端
// 只见京东工具;站点超管不限侧全量。只裁下发出口,授权行不动(AdminMenuPlatformScope 类注释)。
List<PermissionMenuItemVo> appColumns = permissionMenuService.getUserColumnPermissions(
user.getId(), PermissionMenuService.MENU_TYPE_APP);
List<PermissionMenuItemVo> adminColumns = permissionMenuService.getUserColumnPermissions(
user.getId(), PermissionMenuService.MENU_TYPE_ADMIN);
if (!DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById())) {
appColumns = AdminMenuPlatformScope.filterMenuVosByPlatform(appColumns, user.getPlatform());
adminColumns = AdminMenuPlatformScope.filterMenuVosByPlatform(adminColumns, user.getPlatform());
}
vo.setAppColumns(appColumns);
vo.setAdminColumns(adminColumns);
return vo;
}
@@ -803,6 +803,21 @@ public class OssStorageService {
return buildDownloadPublicUrl(location.objectKey(), location.bucket());
}
/**
* 指定桶对象的下载预签名 GET URL(公开出口):内网写入、公网签名({@link #applyDownloadHost}
* 换 download-endpoint,SigV4 只对服务端收到的 host 验签、签名保持不变)。
*
* <p>调用方(v1.5 京东发布明细下发)持有的是对象 key 与桶名——jd-products 是私有桶,
* {@code generateFreshDownloadUrl} 的公开直链不适用,必须走签名;上传侧对应
* {@link #presignObjectUpload}(presign PUT 直传),读写两向对称。</p>
*/
public String presignObjectDownload(String bucket, String objectKey, int expirySeconds) {
if (bucket == null || bucket.isBlank() || objectKey == null || objectKey.isBlank()) {
throw new IllegalArgumentException("presign download requires bucket and objectKey");
}
return applyDownloadHost(presignDownloadUrl(objectKey, bucket, expirySeconds));
}
private void uploadFile(File file, String bucket, String objectKey) {
if (file == null || !file.isFile()) {
throw new IllegalArgumentException("upload file must exist");
@@ -61,16 +61,18 @@ import java.util.List;
* <p>鉴权照外观专利只读页私有 {@code requireXxxAccess} 形状:JWT → 内部令牌回退 → 超管放行 →
* 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权
* ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。
* <b>2026-11-16 起读/写分档</b>:读(列表/类目/详情)按上面的菜单口径放行;写(编辑/上传图片/
* 删除/批量删除/批量归类)在菜单口径之上再要求平台超管,非超管一律 403(前端同窗隐藏写入口)。</p>
* <b>2026-11-16 起读/写分档(2026-11-17 口径放宽)</b>:读(列表/类目/详情)按上面的菜单
* 口径放行;商品行写(编辑/上传图片/删除/批量删除)在菜单口径之上再走管理员级写闸
* (平台超管+公司超管+admin 档放行,普通账号 403,见 {@code requireJdProductWrite});
* 批量归类走 V203 的按组判(requireWritableGroup)。</p>
*
* <p><b>公司口径(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」)</b>:读侧零公司
* 维度——company_id 请求参数与 {@code superAdminScopedCompanyId} 谓词已随公共化收尾整批
* 摘除(2026-11-15 定案「京东数据库不区分公司、属于公共的」的最后一截),行上的 company_id
* 只剩「哪家公司客户端同步的」来源标记,不构成可见性边界;每个拿到本页菜单权限的管理员
* (含站点超管)看到同一份全量公共库。详情与写侧(编辑/删除)同样没有公司维度:
* 对全部公共行可编辑可删除,但<b>写动作只对平台超管开放</b>(2026-11-16 用户口径
* 「京东数据库只有超管有编辑删除权限」,见 {@code requirePlatformSuperAdminWrite}),
* 对全部公共行可编辑可删除,但<b>写动作只对管理员级开放</b>(2026-11-17 用户口径
* 「超管+管理员都可以,只有普通员工不能」,见 {@code requireJdProductWrite}),
* 写侧端点的 company_id 传参已随 2026-11-15 公共化摘除。</p>
*
* <p>导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删);
@@ -172,7 +174,7 @@ public class AdminJdProductController {
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
@Valid @RequestBody JdProductUpdateRequest body,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
RequestOperator operator = requireJdProductWrite(request);
Long updatedId = jdProductUpdateService.update(id, body);
log.info("[jd-product] 编辑商品 operatorId={} id={} title={}",
operator.id(), updatedId, body.getTitle());
@@ -196,7 +198,7 @@ public class AdminJdProductController {
@Parameter(description = "替换目标图片登记行 id(缺省=新增)")
@RequestParam(value = "replace_image_id", required = false) Long replaceImageId,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
RequestOperator operator = requireJdProductWrite(request);
Long updatedId = jdProductUpdateService.uploadImage(id, file, imageType, attrName, replaceImageId);
log.info("[jd-product] 上传图片 operatorId={} id={} replaceImageId={} imageType={}",
operator.id(), updatedId, replaceImageId, imageType);
@@ -211,7 +213,7 @@ public class AdminJdProductController {
public ApiResponse<JdProductDeleteVo> delete(
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
RequestOperator operator = requireJdProductWrite(request);
JdProductDeleteVo vo = jdProductDeleteService.delete(List.of(id));
// 管理端破坏性动作必须留痕:谁、删了哪些行、桶里清了几个对象(同分组删除口径)。
log.info("[jd-product] 删除商品 operatorId={} id={} deleted={} objectsDeleted={}",
@@ -246,7 +248,7 @@ public class AdminJdProductController {
public ApiResponse<JdProductDeleteVo> batchDelete(
@Valid @RequestBody JdProductBatchDeleteRequest body,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
RequestOperator operator = requireJdProductWrite(request);
JdProductDeleteVo vo = jdProductDeleteService.delete(body.getIds());
log.info("[jd-product] 批量删除商品 operatorId={} requested={} deleted={} objectsDeleted={} kept={}",
operator.id(), body.getIds().size(), vo.getDeleted(),
@@ -267,23 +269,27 @@ public class AdminJdProductController {
}
/**
* 写端点的越权闸(2026-11-16 用户口径「京东数据库只有超管有编辑删除权限」)。
* 写端点的越权闸(2026-11-17 用户口径「超管+管理员都可以,只有普通员工不能操作」,
* 推翻 2026-11-16「只有超管有编辑删除权限」的单档)。
*
* <p>读保持菜单权限口径(拿到 {@code admin_jd_database} 列权限的管理员可见同一份公共库),
* 写(编辑 / 上传图片 / 单行删除 / 批量删除 / 批量归类)收窄到<b>平台超级管理员</b>:
* 与 {@code BrandGatingController#requirePlatformSuperAdmin}、
* {@code AdminDeviceLogController#requireSuperAdmin} 同一判据(
* {@code DeviceSessionPolicy#isSuper} 只认站点 super_admin,公司超管不在内)。</p>
* <p>读保持菜单权限口径(拿到 {@code admin_jd_database} 列权限的管理员可见同一份公共库);
* 商品行写(编辑 / 上传图片 / 单行删除 / 批量删除)放宽到<b>管理员级</b>:平台超级管理员、
* 公司超级管理员、admin 角色三档放行,普通账号(role 归不出档)403。分类写不在此闸——
* {@code batch-assign-group} 沿用 V203 的 {@code requireWritableGroup}(本组管理员/
* 公司超管/平台超管,按组判)。</p>
*
* <p>写动作会置人工编辑锁({@code manual_locked=1})并物理删除桶内图片,属影响全平台公共
* 数据的动作,故不随读权限下放;非超管拿到 403 时前端已不渲染这些入口,本闸是兜底。</p>
* <p>写动作会置人工编辑锁({@code manual_locked=1})并物理删除桶内图片;普通账号拿到 403
* 时前端已不渲染这些入口,本闸是兜底。</p>
*/
private RequestOperator requirePlatformSuperAdminWrite(HttpServletRequest request) {
private RequestOperator requireJdProductWrite(HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
if (!operator.superAdmin()) {
log.warn("[jd-product] 非平台超管写操作被拒 operatorId={} role={}",
operator.id(), adminAuthSupport.currentRole(operator.user()));
throw new BusinessException(403, "仅平台超级管理员可以编辑或删除京东数据库数据");
String role = adminAuthSupport.currentRole(operator.user());
boolean adminTier = operator.superAdmin()
|| DeviceSessionPolicy.isCompanySuperAdmin(role)
|| "admin".equals(role);
if (!adminTier) {
log.warn("[jd-product] 普通账号写操作被拒 operatorId={} role={}", operator.id(), role);
throw new BusinessException(403, "仅超级管理员或管理员可以编辑或删除京东数据库数据");
}
return operator;
}
@@ -0,0 +1,221 @@
package com.nanri.aiimage.modules.jd.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskBatchRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
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.JdPublishProgressVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
import com.nanri.aiimage.modules.jd.service.JdPublishBoardService;
import com.nanri.aiimage.modules.jd.service.JdPublishIngestService;
import com.nanri.aiimage.modules.jd.service.JdPublishTaskService;
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo;
import com.nanri.aiimage.modules.task.service.TaskProgressOwnershipSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 京东商品上架任务面(v1.5 Phase 2,蓝图 docs/ITERATION_PLAN.md §3)。
*
* <p>五个入口:建单(用户端登录用户,uid 按会话身份回填;响应体带 queuePayload 供页面
* {@code api.enqueue_json} 推送,DELETE_BRAND 同形)、激活(页面推送前 PENDING→RUNNING)、
* 明细分批下发(客户端按游标拉 PENDING 行)、行级回传(本机执行器直调,判死口凭据化)、
* 心跳(归属校验前置——B98-07 同形债预防:用户域校验在闸门处按可信 uid 对比任务 owner)。
* 全局 {@code /api/tasks/{taskId}/heartbeat} 同时可用,本端点只是给执行器一个模块内聚的 URL。</p>
*/
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/jd-publish")
@Tag(name = "京东商品上架", description = "京东数据库存量商品 → 京麦店铺发布:建单 → 本机已登录京麦的 Chrome 逐商品发布 → 行级回传落明细。")
public class JdPublishController {
private final JdPublishTaskService publishTaskService;
private final JdPublishIngestService ingestService;
private final JdPublishBoardService boardService;
private final JdProductQueryService jdProductQueryService;
private final TaskProgressOwnershipSupport progressOwnershipSupport;
private final AdminAuthSupport adminAuthSupport;
@PostMapping("/tasks")
@Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;"
+ "任务落 PENDING、执行通道显式 LOCAL(本机已登录京麦的 Chrome 执行)、明细快照行随建单落库。"
+ "响应体带 queuePayload(type=jd-product-publish-run),页面原样投 api.enqueue_json。")
public ApiResponse<JdPublishTaskVo> createTask(@Valid @RequestBody JdPublishTaskCreateRequest request,
HttpServletRequest httpRequest) {
// uid 不由请求体说了算:解析不出会话身份就 401(fail-closed,与采集建单同口径)。
request.setUserId(adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()));
return ApiResponse.success(publishTaskService.createTask(request,
adminAuthSupport.currentDeviceId(httpRequest)));
}
@PostMapping("/tasks/{taskId}/activate")
@Operation(summary = "激活京东上架任务", description = "页面把 jd-product-publish-run 载荷推给本机客户端前调用:"
+ "PENDING→RUNNING 条件更新。漏掉这一步,客户端第一个回传会被「任务不在运行中(PENDING)」拒收"
+ "(2026-11-14 采集链真机实录同形)。")
public ApiResponse<Void> activate(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) {
publishTaskService.activateTask(taskId,
adminAuthSupport.requireOwnershipUserId(httpRequest, userId));
return ApiResponse.success(null);
}
@GetMapping("/tasks/{taskId}/items")
@Operation(summary = "分批下发发布明细", description = "按游标分批返回未发布(PENDING)行的发布数据"
+ "(标题/最终价/库存/SKU/属性/图片预签名 GET URL/categoryPath)——派发载荷只带 taskId+改价规则,"
+ "明细按需拉取(载荷尺寸可控、断点友好)。已回传行被状态谓词跳过,断点重连不重发。")
public ApiResponse<JdPublishItemsPageVo> items(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@Parameter(description = "游标(上一页最后一行 id;首页传 0 或省略)", required = false, example = "0")
@RequestParam(value = "cursor", required = false) Long cursor,
@Parameter(description = "批大小(默认 20,上限 100)", required = false, example = "20")
@RequestParam(value = "limit", required = false) Integer limit,
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) {
return ApiResponse.success(publishTaskService.pullItems(taskId,
adminAuthSupport.requireOwnershipUserId(httpRequest, userId), cursor, limit));
}
@GetMapping("/tasks/{taskId}/progress")
@Operation(summary = "查询京东上架进度", description = "任务状态 + 行级分组计数(待发布/发布中/成功/失败)。"
+ "归属校验与建单同口径:uid 按会话身份回填,任务 owner 与 uid 不一致即 403。")
public ApiResponse<JdPublishProgressVo> progress(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) {
return ApiResponse.success(publishTaskService.queryProgress(taskId,
adminAuthSupport.requireOwnershipUserId(httpRequest, userId)));
}
@PostMapping("/tasks/{taskId}/chunk")
@Operation(summary = "提交行级发布结果回传", description = "执行器按批次回传行级状态(PUBLISHING/SUCCESS/FAILED"
+ " +真实失败原因 + wareId);isEnd=true 任务按行级状态汇总落终态。error 字段按铁律 31 分档"
+ "(京麦登录态失效整单 FAILED;非致命只记录)——判定只信 X-Internal-Token,匿名一律拒绝判死。")
public ApiResponse<JdPublishChunkVo> submitChunk(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@RequestBody JdPublishChunkRequest request,
HttpServletRequest httpRequest) {
// 判死口凭据化(JdCollectController.submitChunk 同口径):error 上报是唯一能触发整单
// 判死的入口,匿名一律拒绝判死;行级结果落库不要求内部令牌(采集端按任务拉单)。
boolean trustedErrorReporter = adminAuthSupport.isTrustedInternalToken(httpRequest);
return ApiResponse.success(ingestService.submitChunk(taskId, request, trustedErrorReporter));
}
@PostMapping("/tasks/{taskId}/heartbeat")
@Operation(summary = "上报发布心跳", description = "沿用全局任务心跳语义:任务终态时回 alive=false,"
+ "执行端下一跳收手。归属校验前置:uid 与任务 owner 不一致即 403(B98-07 同形债预防——"
+ "任意用户不可给任意任务刷心跳续命)。处理位置一并记入心跳位置表供判死文案使用。")
public ApiResponse<TaskHeartbeatVo> heartbeat(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId,
@RequestBody(required = false) TaskHeartbeatRequest request,
HttpServletRequest httpRequest) {
return ApiResponse.success(publishTaskService.heartbeat(taskId,
adminAuthSupport.requireOwnershipUserId(httpRequest, userId), request));
}
// ------------------------------------------------------------------
// v1.5 Phase 4:用户端「商品上架」页读侧(选品分页+任务面板四端点)。
// 形状照 JdCollectController 面板段同族:dashboard/history/delete 走 resolve,
// progressBatch 走 requireOwnershipUserId+filterOwnedTaskIds;products 按会话
// 身份只回归属当前用户的商品行(AC-9 owner 过滤,跨用户商品 0 返回)。
// ------------------------------------------------------------------
@GetMapping("/products")
@Operation(summary = "用户端选品分页(归属过滤)", description = "「商品上架」页选品列表:只回归属当前"
+ "登录用户的京东数据库商品行(AC-9 owner 过滤,跨用户商品 0 返回),可按自定义分类过滤"
+ "(分类 id 经 V203 归属表两步下推:先取 product_id 集,再 in 主键)。")
public ApiResponse<JdProductPageVo> products(
@Parameter(description = "自定义分类 id(不传=全部归属商品)")
@RequestParam(name = "category_id", required = false) Long categoryId,
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.JD_PRODUCTS_PAGE_SIZE) Long pageSize,
@Parameter(description = "当前用户 ID;省略时取当前登录身份", required = false)
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
return ApiResponse.success(jdProductQueryService.pageForUser(userId, categoryId, page, pageSize));
}
@GetMapping("/dashboard")
@Operation(summary = "查询京东上架任务总览", description = "当前用户的运行中、成功、失败任务数。"
+ "任务面板统计卡数据源,页面进入时请求一次即可,不需要持续轮询。")
public ApiResponse<JdPublishDashboardVo> dashboard(
@Parameter(description = "当前用户 ID", required = true, example = "1")
@RequestParam("user_id") Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
return ApiResponse.success(boardService.dashboard(userId));
}
@GetMapping("/history")
@Operation(summary = "查询京东上架任务历史", description = "当前用户最近的上架任务历史(活跃任务排前),"
+ "含行级四档计数(待发布/发布中/成功/失败)与建单载荷带回(分类 id/改价规则,重试重建推送载荷用)。")
public ApiResponse<JdPublishHistoryVo> history(
@Parameter(description = "当前用户 ID", required = true, example = "1")
@RequestParam("user_id") Long userId,
@Parameter(description = "历史记录条数,默认 50,最大 100", example = "50")
@RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
return ApiResponse.success(boardService.history(userId, limit));
}
@PostMapping("/tasks/progress/batch")
@Operation(summary = "批量查询上架任务进度", description = "任务面板只对活跃任务调用该接口,建议 6 秒一次。"
+ "归属先由公共出口按会话身份过滤,返回任务头 + 行级四档计数。")
public ApiResponse<JdPublishTaskBatchVo> progressBatch(@Valid @RequestBody JdPublishTaskBatchRequest request,
HttpServletRequest httpRequest) {
return ApiResponse.success(boardService.progressBatch(progressOwnershipSupport
.filterOwnedTaskIds(request.getTaskIds(),
adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()))));
}
@DeleteMapping("/tasks/{taskId}")
@Operation(summary = "删除上架任务", description = "删除当前用户的一条京东商品上架任务,"
+ "连带清理该任务的发布明细快照行(发布不落商品行,无京东数据库清理语义)。")
public ApiResponse<Void> deleteTask(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@Parameter(description = "当前用户 ID,必须与创建任务的用户一致", required = true, example = "1")
@RequestParam("user_id") Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
boardService.deleteTask(taskId, userId);
return ApiResponse.success(null);
}
}
@@ -0,0 +1,35 @@
package com.nanri.aiimage.modules.jd.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 京东商品上架发布明细(biz_jd_publish_item,V210)数据访问口。
*
* <p>行级状态推进({@code updateById}/条件更新)走 MyBatis-Plus 既有通道;分批下发与
* 状态聚合两条具名 SQL 落 {@code mapper/jd/JdPublishItemMapper.xml}(铁律 1)。</p>
*/
@Mapper
public interface JdPublishItemMapper extends BaseMapper<JdPublishItemEntity> {
/**
* 明细分批下发页(断点友好,铁律 20 SQL 侧下推):只出<b>未发布</b>(PENDING)行,
* 按 id 升序、{@code id > cursor} 之后取 {@code limit} 行——已回传的行(SUCCESS/FAILED/
* PUBLISHING)被状态谓词天然跳过,客户端断点重连时把 cursor 置 0 也不会重发已发布商品
* (AC-4 服务端半边)。{@code cursor}/{@code limit} 必须是服务侧钳制后的值。
*/
List<JdPublishItemEntity> selectPublishableItems(@Param("taskId") Long taskId,
@Param("cursor") long cursor,
@Param("limit") int limit);
/**
* 行级状态聚合(进度与终态汇总共用):按 publish_status 分组计数。
* 行数上界=该任务商品行数(建单口钳 500),无分页问题。
*/
List<Map<String, Object>> countByPublishStatus(@Param("taskId") Long taskId);
}
@@ -0,0 +1,56 @@
package com.nanri.aiimage.modules.jd.model.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.List;
/**
* 京东发布行级回传请求(v1.5 蓝图 §3:POST /api/jd-publish/tasks/{taskId}/chunk)。
*
* <p>顶层键集 {@code batchId / items / isEnd}(外加 {@code error} 失败上报);行内键集
* {@code itemId / productId / publishStatus / publishError / jdWareId}。行状态是唯一
* 行级真源({@code biz_jd_publish_item.publish_status});{@code error} 按铁律 31 分档
* (京麦登录态失效→整单 FAILED,代理/LLM 凭据致命词→{@code CredentialFatalClassifier},
* 其余技术性故障只记录不判死)——判定只信 X-Internal-Token(匿名 error 一律拒绝判死,
* 照 JdCollectController.submitChunk 同口径)。</p>
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class JdPublishChunkRequest {
/** 批次号(客户端生成,溯源用)。 */
private String batchId;
/** 本批行级结果。 */
private List<ItemResult> items;
/** true=本任务全部行已回传,任务按行级状态汇总落终态。 */
private Boolean isEnd;
/**
* 客户端失败上报(非空时按铁律 31 分档;可信判定单一出口 X-Internal-Token)。
*/
private String error;
/** 单行回传结果。 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ItemResult {
/** 明细行 id(items 下发时的 itemId;productId 作为对撞锚点)。 */
private Long itemId;
/** 商品行 id(uk_task_product 定位锚点)。 */
private Long productId;
/** 行级状态:PUBLISHING / SUCCESS / FAILED。 */
private String publishStatus;
/** 行级失败真实原因(FAILED 行必填,R6 单行失败隔离)。 */
private String publishError;
/** 京麦发布成功回执的商品 id(SUCCESS 行回传)。 */
private String jdWareId;
}
}
@@ -0,0 +1,24 @@
package com.nanri.aiimage.modules.jd.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 京东商品上架批量进度请求(形状照 {@code JdCollectTaskBatchRequest} 同族)。
* {@code userId} 可省略:归属过滤主体是 {@code TaskProgressOwnershipSupport.filterOwnedTaskIds}
* 按会话身份判定,请求体里的 userId 只作 admin 代客的归属提示。
*/
@Data
@Schema(description = "京东商品上架批量进度请求")
public class JdPublishTaskBatchRequest {
@Schema(description = "要查询的任务 ID 列表(只查活跃任务,建议 6 秒一批)", required = true)
@NotEmpty(message = "taskIds 不能为空")
private List<Long> taskIds;
@Schema(description = "当前用户 ID(归属过滤用,可省略)")
private Long userId;
}
@@ -0,0 +1,40 @@
package com.nanri.aiimage.modules.jd.model.dto;
import lombok.Data;
import java.util.List;
/**
* 京东商品上架建单请求(v1.5 蓝图 §3 建单契约)。
*
* <p>用户在用户端「京东工具台 → 商品上架」页选自定义分类(消费 {@code GET /api/jd-collect/groups},
* B113-01 分类口唯一,AC-9)→ 分页拉该分类下归属自己的商品 → 勾选 → 可选统一改价规则 → 提交建单。
* 服务端按 productIds 落 {@code biz_jd_publish_item} 快照行;{@code request_json} 整体进
* {@code biz_file_task} 供兜底拉取回读({@code readCreateRequest} 同形)。</p>
*/
@Data
public class JdPublishTaskCreateRequest {
/** 提交人 uid(Controller 侧按会话身份回填,请求体自带值不采信)。 */
private Long userId;
/** 自定义分类 id(biz_jd_product_group.id,记录与展示用;商品勾选集才是发布范围)。 */
private Long categoryId;
/** 要上架的商品行 id 集(biz_jd_product.id,必填非空;全部必须归属当前用户,AC-9 归属半边)。 */
private List<Long> productIds;
/** 统一改价规则(可选;null=按原价,mode=none)。 */
private PriceRule priceRule;
/** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */
@Data
public static class PriceRule {
/** none / percent / fixed(空缺省按 none 处理)。 */
private String mode;
/** percent 的百分数或 fixed 的加价金额;mode=none 时忽略。 */
private java.math.BigDecimal value;
}
}
@@ -0,0 +1,58 @@
package com.nanri.aiimage.modules.jd.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 京东商品上架发布明细行({@code biz_jd_publish_item},V210,v1.5 蓝图 §3)。
*
* <p>每任务每商品一行(唯一键 {@code uk_task_product}):建单即按 {@code biz_jd_product}
* 快照落行(商品库有 ageCleanup 清理语义,发布记录不随商品删除丢失溯源);行级状态机
* {@code PENDING → PUBLISHING → SUCCESS/FAILED} 由客户端 chunk 回传逐行推进——服务端
* 不预测发布结果,行状态的唯一写入口是 {@code JdPublishIngestService}(单客户端串行
* 回传,无并发竞争)。任务级行为复用 {@code biz_file_task}(module_type=JD_PUBLISH),
* 本表只承载行级明细与快照。</p>
*/
@Data
@TableName("biz_jd_publish_item")
public class JdPublishItemEntity {
@TableId(type = IdType.AUTO)
private Long id;
/** 任务行 id(biz_file_task.id,module_type=JD_PUBLISH)。 */
private Long taskId;
/** 物化归属分公司(owner 的 users.company_id;读不出落 NULL 不回填,铁律 30)。 */
private Long companyId;
/** 任务 owner uid(biz_file_task.user_id 投影)。 */
private Long userId;
/** 商品行 id(biz_jd_product.id)。 */
private Long productId;
/** 京东商品编码快照。 */
private String productCode;
/** 来源店铺名快照。 */
private String shopName;
/** 商品标题快照。 */
private String title;
/** 京麦类目路径快照(A &gt; B &gt; C)。 */
private String categoryPath;
/** 改价快照 JSON({"mode","value","sourcePrice","finalPrice"},finalPrice=主档价按规则折算)。 */
private String priceRuleJson;
/** 库存快照 JSON({"total":n})。 */
private String stockJson;
/** 行级状态机:PENDING/PUBLISHING/SUCCESS/FAILED(客户端 chunk 回传推进)。 */
private String publishStatus;
/** 行级失败真实原因(客户端回传原文,R6 单行失败隔离)。 */
private String publishError;
/** 京麦发布成功回执的商品 id(wareId,AC-3 真机核对锚点)。 */
private String jdWareId;
/** 主图 objectKey 快照(biz_jd_product_image MAIN 档 sortNo 最小行)。 */
private String mainImageObjectKey;
/** 建单落行时刻。 */
private LocalDateTime createdAt;
/** 最近回传/复位时刻。 */
private LocalDateTime updatedAt;
}
@@ -0,0 +1,19 @@
package com.nanri.aiimage.modules.jd.model.vo;
import lombok.Data;
/**
* 京东发布行级回传响应(v1.5):已接受行数 + 未发布余量;任务落终态时带终态状态。
*/
@Data
public class JdPublishChunkVo {
/** 本批接受行数。 */
private int acceptedCount;
/** 该任务剩余未发布(PENDING)行数。 */
private long pendingCount;
/** 任务终态状态(isEnd=true 且落了终态时回填;非终态回 null)。 */
private String taskStatus;
}
@@ -0,0 +1,27 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 京东商品上架任务面板总览(v1.5 Phase 4,用户端「商品上架」统计卡数据源)。
*
* <p>形状照 {@code JdCollectDashboardVo} 同族:当前用户的运行中/成功/失败任务数,
* 已结束=成功+失败。页面进入时请求一次,不参与轮询。</p>
*/
@Data
@Schema(description = "京东商品上架任务总览")
public class JdPublishDashboardVo {
@Schema(description = "运行中任务数(含排队)")
private long pendingTaskCount;
@Schema(description = "已结束任务数(成功+失败)")
private long processedTaskCount;
@Schema(description = "成功任务数")
private long successTaskCount;
@Schema(description = "失败任务数")
private long failedTaskCount;
}
@@ -0,0 +1,67 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Map;
/**
* 京东商品上架任务历史行(v1.5 Phase 4,任务面板历史层数据源)。
*
* <p>行级计数(待发布/发布中/成功/失败)来自 {@code biz_jd_publish_item} 按任务聚合;
* 建单载荷(分类 id + 改价规则)随行带回——失败任务「重试」时页面用它重建推送载荷
* (铁律 26 原任务复位 + 铁律 32 第三件同键:重建的载荷与建单响应 queuePayload 同形状)。</p>
*/
@Data
@Schema(description = "京东商品上架任务历史行")
public class JdPublishHistoryItemVo {
@Schema(description = "任务 ID")
private Long taskId;
@Schema(description = "任务编号")
private String taskNo;
@Schema(description = "biz_file_task.status 原值:PENDING/RUNNING/SUCCESS/FAILED")
private String taskStatus;
@Schema(description = "任务是否成功")
private boolean success;
@Schema(description = "终态原因(非终态为 null)")
private String errorMessage;
@Schema(description = "建单所选自定义分类 id(biz_jd_product_group.id)")
private Long categoryId;
@Schema(description = "建单统一改价规则(原样带回,重试重建推送载荷用;空=原价)")
private Map<String, Object> priceRule;
@Schema(description = "商品明细总行数")
private long productTotal;
@Schema(description = "待发布行数")
private long pendingCount;
@Schema(description = "发布中行数")
private long publishingCount;
@Schema(description = "成功行数")
private long successCount;
@Schema(description = "失败行数")
private long failedCount;
@Schema(description = "任务创建时刻")
private String createdAt;
@Schema(description = "任务结束时刻")
private String finishedAt;
@Schema(description = "最近更新时刻")
private String updatedAt;
@Schema(description = "改价规则里的加价值(percent 百分数 / fixed 金额;仅展示用)")
private BigDecimal priceRuleValue;
}
@@ -0,0 +1,16 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 京东商品上架任务历史(活跃任务排前,形状照 {@code JdCollectHistoryVo} 同族)。 */
@Data
@Schema(description = "京东商品上架任务历史")
public class JdPublishHistoryVo {
@Schema(description = "历史行")
private List<JdPublishHistoryItemVo> items = new ArrayList<>();
}
@@ -0,0 +1,93 @@
package com.nanri.aiimage.modules.jd.model.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 明细分批下发的单商品发布载荷(v1.5 蓝图 §3:标题/最终价/库存/SKU/属性/图片/categoryPath)。
*
* <p>图片按 objectKey 发预签名 GET URL(jd-products 桶既有 presign 模式复用,蓝图 §3);
* 属性 {@code attrs} 是采集链原样透传的 key/label/value 三元组 JSON(服务端不裁剪不转写);
* SKU 行价已按统一改价规则折算({@code finalPrice}),执行器直接填表不再二次计算。</p>
*/
@Data
public class JdPublishItemPayloadVo {
/** 明细行 id(biz_jd_publish_item.id,客户端回传 chunk 时定位行)。 */
private Long itemId;
/** 商品行 id(biz_jd_product.id)。 */
private Long productId;
private String productCode;
/** 商品标题快照(发布页标题栏)。 */
private String title;
/** 京麦类目路径快照(A &gt; B &gt; C,授权树内定位节点)。 */
private String categoryPath;
/** 主档源价(biz_jd_product.priceMin 快照)。 */
private BigDecimal sourcePrice;
/** 主档最终价(源价 ± 改价规则折算)。 */
private BigDecimal finalPrice;
/** 库存总数快照。 */
private Integer stockTotal;
/** 商品属性全集(原始 key/label/value 三元组 JSON 原样透传)。 */
private String attrs;
/** SKU 矩阵(销售属性组合行,价已按规则折算)。 */
private List<SkuVo> skus;
/** 主图(预签名 GET URL,sortNo 升序)。 */
private List<ImageView> mainImages;
/** 销售属性图(attrName 维度,预签名 GET URL)。 */
private List<ImageView> attrImages;
/** 详情长图(预签名 GET URL,sortNo 升序,直铺详情编辑器)。 */
private List<ImageView> detailImages;
/** SKU 矩阵行。 */
@Data
public static class SkuVo {
private String skuId;
private String skuName;
/** SKU 源价(采集快照)。 */
private BigDecimal sourcePrice;
/** SKU 最终价(源价 ± 改价规则折算)。 */
private BigDecimal finalPrice;
private Integer stock;
/** 销售属性组合 JSON([{"name":"颜色","value":"上衣"},…])。 */
private String saleAttrsJson;
private Integer sortNo;
}
/** 图片下发视图(objectKey 留档 + 预签名 GET URL 直取)。 */
@Data
public static class ImageView {
/** 自有桶对象 key(留档;URL 过期时可凭它重签)。 */
private String objectKey;
/** 预签名 GET URL(客户端执行器直接下载/上传京麦)。 */
private String url;
/** 销售属性名(ATTR 档专用)。 */
private String attrName;
private Integer sortNo;
}
}
@@ -0,0 +1,30 @@
package com.nanri.aiimage.modules.jd.model.vo;
import lombok.Data;
import java.util.List;
/**
* 明细分批下发页(v1.5 蓝图 §3:GET /api/jd-publish/tasks/{taskId}/items)。
*
* <p>游标语义:{@code nextCursor}=本页最后一行 id,客户端带它取下一页;{@code hasMore}
* 由「本页取满批大小」判定(SQL 侧 {@code id > cursor AND publish_status='PENDING'}
* 下推,铁律 20——已回传行被状态谓词跳过,断点重连 cursor 归零也不会重发)。</p>
*/
@Data
public class JdPublishItemsPageVo {
private Long taskId;
/** 本页明细行。 */
private List<JdPublishItemPayloadVo> items;
/** 下一页游标(本页最后一行 id;空页时保持请求 cursor)。 */
private Long nextCursor;
/** true=可能还有下一页(本页取满批大小)。 */
private boolean hasMore;
/** 该任务剩余未发布行数(PENDING 计数,进度参考)。 */
private long pendingCount;
}
@@ -0,0 +1,41 @@
package com.nanri.aiimage.modules.jd.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 京东发布任务进度(v1.5 用户端实时面板数据源,R7)。
*
* <p>行级分组计数(PENDING/PUBLISHING/SUCCESS/FAILED)来自 {@code biz_jd_publish_item}
* 聚合 SQL;任务级状态/终态原因来自 {@code biz_file_task}。归属校验按 {@code (taskId, userId)}
* (铁律 11):管理员代客时 userId 与任务 owner 不一致一律拒。</p>
*/
@Data
public class JdPublishProgressVo {
private Long taskId;
/** 任务状态(biz_file_task.status)。 */
private String status;
/** 终态原因(error_message;非终态为 null)。 */
private String message;
/** 总行数(该任务商品明细行数)。 */
private long totalCount;
/** 待发布行数。 */
private long pendingCount;
/** 发布中行数。 */
private long publishingCount;
/** 成功行数。 */
private long successCount;
/** 失败行数。 */
private long failedCount;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,19 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 批量进度响应(形状照 {@code JdCollectTaskBatchVo} 同族;查不到的任务进 missingTaskIds)。 */
@Data
@Schema(description = "京东商品上架批量进度")
public class JdPublishTaskBatchVo {
@Schema(description = "命中的任务条目")
private List<JdPublishTaskDetailVo> items = new ArrayList<>();
@Schema(description = "没查到的任务 ID(已删除/非本模块,前端停止轮询)")
private List<Long> missingTaskIds = new ArrayList<>();
}
@@ -0,0 +1,19 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 批量进度条目:任务头 + 最新历史行(形状照 {@code JdCollectTaskDetailVo} 同族)。 */
@Data
@Schema(description = "京东商品上架任务进度条目")
public class JdPublishTaskDetailVo {
@Schema(description = "任务头")
private JdPublishTaskItemVo task;
@Schema(description = "最新进度行(单元素)")
private List<JdPublishHistoryItemVo> items = new ArrayList<>();
}
@@ -0,0 +1,25 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/** 批量进度条目里的任务头(形状照 {@code JdCollectTaskItemVo} 同族)。 */
@Data
@Schema(description = "京东商品上架任务头")
public class JdPublishTaskItemVo {
@Schema(description = "任务 ID")
private Long id;
@Schema(description = "任务编号")
private String taskNo;
@Schema(description = "任务状态")
private String status;
@Schema(description = "终态原因")
private String errorMessage;
@Schema(description = "最近更新时刻")
private String updatedAt;
}
@@ -0,0 +1,27 @@
package com.nanri.aiimage.modules.jd.model.vo;
import lombok.Data;
import java.util.Map;
/**
* 京东商品上架建单响应(v1.5 蓝图 §3)。
*
* <p>{@code queuePayload} 是页面推送载体(DELETE_BRAND {@code delete-brand-run} 同形先例):
* 建单成功后用户端页面 JS 把它原样投进 {@code api.enqueue_json}——载荷 type 与
* {@code JdPublishTaskPullSpiImpl.QUEUE_TYPE} 逐字同值(铁律 32 第三件:enqueue 页面推送;
* 兜底拉取线由 SPI 组装同形载荷,两处漂移任务永不执行)。</p>
*/
@Data
public class JdPublishTaskVo {
private Long taskId;
private String taskNo;
/** 执行通道(建单显式写 LOCAL,铁律 19:京麦登录态只在用户桌面机)。 */
private String collectChannel;
/** 页面推送载荷:{"type":"jd-product-publish-run","data":{"taskId":n,"priceRule":{...}}}。 */
private Map<String, Object> queuePayload;
}
@@ -117,6 +117,53 @@ public class JdProductQueryService {
return vo;
}
/**
* 用户端「商品上架」选品分页(v1.5 Phase 4,AC-9 owner 过滤):只回归属当前用户的行,
* 可按自定义分类过滤。分类过滤不走 wrapper 原生 EXISTS(SqlLayeringConventionTest
* rawSqlInsideWrappersDoesNotGrow 钉死不涨):先从 V203 归属表取该分类的 product_id 集,
* 再 in 主键——分类规模=组内商品数,量级可控;分类空集直接回空页不查主表。
* 页码钳制与 {@link #page} 同出口(MAX_PAGE/MAX_PAGE_SIZE,铁律 15)。
*/
public JdProductPageVo pageForUser(Long userId, Long categoryId, Long page, Long pageSize) {
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
LambdaQueryWrapper<JdProductEntity> query = new LambdaQueryWrapper<JdProductEntity>()
.eq(JdProductEntity::getUserId, userId);
if (categoryId != null && categoryId > 0) {
List<Long> productIds = jdProductGroupAssignMapper.selectList(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.select(JdProductGroupAssignEntity::getProductId)
.eq(JdProductGroupAssignEntity::getCategoryId, categoryId))
.stream().map(JdProductGroupAssignEntity::getProductId).distinct().toList();
if (productIds.isEmpty()) {
return emptyPage(safePage, safeSize);
}
query.in(JdProductEntity::getId, productIds);
}
long total = jdProductMapper.selectCount(query);
List<JdProductListItemVo> items = total <= 0 ? List.of()
: jdProductMapper.selectList(query
.orderByDesc(JdProductEntity::getSyncedAt, JdProductEntity::getId)
.last("limit " + (safePage - 1) * safeSize + ", " + safeSize))
.stream().map(this::toListItem).toList();
JdProductPageVo vo = new JdProductPageVo();
vo.setItems(items);
vo.setTotal(total);
vo.setPage(safePage);
vo.setPageSize(safeSize);
return vo;
}
private static JdProductPageVo emptyPage(long page, long pageSize) {
JdProductPageVo vo = new JdProductPageVo();
vo.setItems(List.of());
vo.setTotal(0L);
vo.setPage(page);
vo.setPageSize(pageSize);
return vo;
}
/**
* 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
* 已落库行 distinct 的 {@code category_path}(=京麦末级类目名,契约 §2.3 E3)
@@ -0,0 +1,254 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryItemVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskItemVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* 京东商品上架任务面板服务(v1.5 Phase 4,用户端「商品上架」实时任务面板四端点)。
*
* <p>形状照 {@code JdCollectBoardService} 同族裁剪:京东发布<b>没有</b>
* {@code biz_task_scope_state} 游标(进度真源是 {@code biz_jd_publish_item} 的行级状态,
* {@code JdPublishTaskService#queryProgress} 同口径),历史行的「行级计数」改从明细表
* GROUP BY 聚合;删除面只清明细行+任务主行(发布不落商品行,无京东数据库清理语义)。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JdPublishBoardService {
private static final int MAX_HISTORY_LIMIT = 100;
private final FileTaskMapper fileTaskMapper;
private final JdPublishItemMapper jdPublishItemMapper;
private final ObjectMapper objectMapper;
/** 查询当前用户的面板总览(运行中/成功/失败三档计数,已结束=成功+失败)。 */
public JdPublishDashboardVo dashboard(Long userId) {
JdPublishDashboardVo vo = new JdPublishDashboardVo();
long running = countTask(userId, TaskStatuses.FileTask.RUNNING);
long success = countTask(userId, TaskStatuses.FileTask.SUCCESS);
long failed = countTask(userId, TaskStatuses.FileTask.FAILED);
vo.setPendingTaskCount(running);
vo.setSuccessTaskCount(success);
vo.setFailedTaskCount(failed);
vo.setProcessedTaskCount(success + failed);
return vo;
}
private long countTask(Long userId, String status) {
return fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, JdPublishTaskService.MODULE_TYPE)
.eq(FileTaskEntity::getUserId, userId)
.eq(FileTaskEntity::getStatus, status));
}
/**
* 查询当前用户最近的任务历史(活跃任务排前,其余按最近更新时间倒序)。
* 行级计数批量回查:一条 GROUP BY(task_id, publish_status)出全部任务的四档计数,
* 不逐任务一条聚合查询(100 行上限打爆面板的同族教训)。
*/
public JdPublishHistoryVo history(Long userId, Integer limit) {
int safeLimit = Math.max(1, Math.min(limit == null ? 50 : limit, MAX_HISTORY_LIMIT));
List<FileTaskEntity> tasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, JdPublishTaskService.MODULE_TYPE)
.eq(FileTaskEntity::getUserId, userId)
.orderByDesc(FileTaskEntity::getCreatedAt)
.last("limit " + safeLimit));
tasks.sort(Comparator
.comparing((FileTaskEntity task) -> !isActive(task))
.thenComparing(FileTaskEntity::getUpdatedAt,
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(FileTaskEntity::getId, Comparator.reverseOrder()));
Map<Long, Map<String, Long>> countsByTask = countItemsByTask(
tasks.stream().map(FileTaskEntity::getId).toList());
JdPublishHistoryVo vo = new JdPublishHistoryVo();
for (FileTaskEntity task : tasks) {
vo.getItems().add(toHistoryItem(task,
countsByTask.getOrDefault(task.getId(), Map.of())));
}
return vo;
}
private static boolean isActive(FileTaskEntity task) {
return TaskStatuses.FileTask.ACTIVE.contains(task.getStatus());
}
/** 批量行级计数:一条 GROUP BY 出全部任务的 PENDING/PUBLISHING/SUCCESS/FAILED 行数。 */
private Map<Long, Map<String, Long>> countItemsByTask(List<Long> taskIds) {
Map<Long, Map<String, Long>> counts = new HashMap<>();
if (taskIds.isEmpty()) {
return counts;
}
List<Map<String, Object>> rows = jdPublishItemMapper.selectMaps(new QueryWrapper<JdPublishItemEntity>()
.select("task_id", "publish_status", "count(*) as cnt")
.in("task_id", taskIds)
.groupBy("task_id", "publish_status"));
for (Map<String, Object> row : rows) {
Long taskId = row.get("task_id") == null ? null : Long.valueOf(String.valueOf(row.get("task_id")));
Object status = row.get("publish_status");
Object cnt = row.get("cnt");
if (taskId == null || status == null || !(cnt instanceof Number number)) {
continue;
}
counts.computeIfAbsent(taskId, key -> new LinkedHashMap<>())
.put(String.valueOf(status), number.longValue());
}
return counts;
}
/** 组装历史行:任务头 + 建单载荷(分类 id/改价规则,宽松读) + 行级四档计数。 */
private JdPublishHistoryItemVo toHistoryItem(FileTaskEntity task, Map<String, Long> counts) {
JdPublishHistoryItemVo item = new JdPublishHistoryItemVo();
item.setTaskId(task.getId());
item.setTaskNo(task.getTaskNo());
item.setTaskStatus(task.getStatus());
item.setSuccess(TaskStatuses.FileTask.SUCCESS.equals(task.getStatus()));
item.setErrorMessage(task.getErrorMessage());
JdPublishTaskCreateRequest request = readCreateRequestQuiet(task);
if (request != null) {
item.setCategoryId(request.getCategoryId());
if (request.getPriceRule() != null) {
Map<String, Object> rule = new LinkedHashMap<>();
rule.put("mode", request.getPriceRule().getMode());
rule.put("value", request.getPriceRule().getValue());
item.setPriceRule(rule);
item.setPriceRuleValue(request.getPriceRule().getValue());
}
}
item.setProductTotal(counts.values().stream().mapToLong(Long::longValue).sum());
item.setPendingCount(counts.getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L));
item.setPublishingCount(counts.getOrDefault(JdPublishTaskService.ITEM_PUBLISHING, 0L));
item.setSuccessCount(counts.getOrDefault(JdPublishTaskService.ITEM_SUCCESS, 0L));
item.setFailedCount(counts.getOrDefault(JdPublishTaskService.ITEM_FAILED, 0L));
if (task.getCreatedAt() != null) {
item.setCreatedAt(task.getCreatedAt().toString());
}
if (task.getFinishedAt() != null) {
item.setFinishedAt(task.getFinishedAt().toString());
}
if (task.getUpdatedAt() != null) {
item.setUpdatedAt(task.getUpdatedAt().toString());
}
return item;
}
/** 历史行宽松读建单载荷:载荷缺失/损坏时只少分类 id 与改价规则,不把历史面板打成红条。 */
private JdPublishTaskCreateRequest readCreateRequestQuiet(FileTaskEntity task) {
if (task.getRequestJson() == null || task.getRequestJson().isBlank()) {
return null;
}
try {
return objectMapper.readValue(task.getRequestJson(), JdPublishTaskCreateRequest.class);
} catch (Exception ex) {
log.warn("[jd-publish] 建单载荷解析失败,历史行少分类/改价 taskId={} err={}",
task.getId(), ex.getMessage());
return null;
}
}
/**
* 批量查任务进度(前端轮询专用,归属已由 {@code TaskProgressOwnershipSupport} 过滤)。
* 形状照采集面板:每任务一条 {@code {task, items:[最新进度行]}},查不到的进 missingTaskIds。
*/
public JdPublishTaskBatchVo progressBatch(List<Long> taskIds) {
Set<Long> normalized = new LinkedHashSet<>();
if (taskIds != null) {
for (Long id : taskIds) {
if (id != null && id > 0) {
normalized.add(id);
}
}
}
JdPublishTaskBatchVo vo = new JdPublishTaskBatchVo();
if (normalized.isEmpty()) {
return vo;
}
List<FileTaskEntity> tasks = fileTaskMapper.selectList(
new LambdaQueryWrapper<FileTaskEntity>().in(FileTaskEntity::getId, normalized));
List<Long> hitIds = new ArrayList<>();
Map<Long, Map<String, Long>> countsByTask = countItemsByTask(
tasks.stream().map(FileTaskEntity::getId).toList());
for (FileTaskEntity task : tasks) {
if (!JdPublishTaskService.MODULE_TYPE.equals(task.getModuleType())) {
continue;
}
hitIds.add(task.getId());
JdPublishTaskItemVo taskItem = new JdPublishTaskItemVo();
taskItem.setId(task.getId());
taskItem.setTaskNo(task.getTaskNo());
taskItem.setStatus(task.getStatus());
taskItem.setErrorMessage(task.getErrorMessage());
taskItem.setUpdatedAt(task.getUpdatedAt() == null ? null : task.getUpdatedAt().toString());
JdPublishTaskDetailVo detail = new JdPublishTaskDetailVo();
detail.setTask(taskItem);
detail.getItems().add(toHistoryItem(task,
countsByTask.getOrDefault(task.getId(), Map.of())));
vo.getItems().add(detail);
}
for (Long id : normalized) {
if (!hitIds.contains(id)) {
vo.getMissingTaskIds().add(id);
}
}
return vo;
}
/**
* 删除任务:明细快照行按 {@code task_id} 清 + 任务主行。事务内只做 DB 删除——
* 发布不落商品行/图片行(京东数据库是采集面的数据),没有额外清理语义。
*/
@Transactional
public void deleteTask(Long taskId, Long userId) {
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !JdPublishTaskService.MODULE_TYPE.equals(task.getModuleType())
|| (userId != null && task.getUserId() != null && !Objects.equals(userId, task.getUserId()))) {
throw new BusinessException("任务不存在");
}
int items = jdPublishItemMapper.delete(new LambdaQueryWrapper<JdPublishItemEntity>()
.eq(JdPublishItemEntity::getTaskId, taskId));
fileTaskMapper.deleteById(taskId);
log.info("[jd-publish] 删除任务 taskId={} userId={} 明细行={}", taskId, userId, items);
}
/** 供测试确认行级计数口径(BigDecimal 展示值从 priceRule 原样带回)。 */
static BigDecimal priceRuleValueOf(JdPublishTaskCreateRequest request) {
return request.getPriceRule() == null ? null : request.getPriceRule().getValue();
}
/** 时间列统一字符串(LocalDateTime.toString;空值原样 null,与采集面板同口径)。 */
static String timeText(LocalDateTime value) {
return value == null ? null : value.toString();
}
}
@@ -0,0 +1,229 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.ItemResult;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.CredentialFatalTaskCloser;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 京东发布行级回传(v1.5 蓝图 §3 chunk 通道:POST /api/jd-publish/tasks/{taskId}/chunk)。
*
* <p>行状态是唯一行级真源({@code biz_jd_publish_item.publish_status},uk_task_product 定位);
* {@code isEnd=true} 时按行级状态汇总任务终态(失败行 &gt; 0 ⇒ 任务 FAILED、其余 SUCCESS,
* successFileCount/failedFileCount 落真实行数——R6 单行失败隔离、任务终态汇总成败数)。
* CAS 只认 RUNNING(铁律 14:已终态的任务不改写;可重入)。</p>
*
* <p>{@code error} 上报按铁律 31 分档(判死口凭据化,匿名一律拒绝判死——照
* {@code JdCollectController#submitChunk} 同口径):京麦登录态失效 →
* {@link JdPublishStaleTaskService#terminalizeOnJdLoginFatal}(词表复用
* {@code JdStaleTaskService#isJdLoginStateFailure},京东域两链同一族);代理/LLM 凭据
* 致命词 → {@code CredentialFatalTaskCloser};其余技术性故障只记录不判死。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JdPublishIngestService {
private static final String LOG_TAG = "jd-publish";
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
/** chunk 可写回的行级状态(PENDING 是建单初值,不接受回传写回)。 */
private static final Set<String> WRITABLE_STATUSES =
Set.of(JdPublishTaskService.ITEM_PUBLISHING, JdPublishTaskService.ITEM_SUCCESS,
JdPublishTaskService.ITEM_FAILED);
/** publish_error 列宽(V210 VARCHAR(1024)),超长截断不炸批。 */
private static final int MAX_ERROR_LENGTH = 1024;
private final FileTaskMapper fileTaskMapper;
private final JdPublishItemMapper jdPublishItemMapper;
private final JdPublishStaleTaskService staleTaskService;
private final TaskProgressSnapshotService taskProgressSnapshotService;
public JdPublishChunkVo submitChunk(Long taskId, JdPublishChunkRequest request, boolean trustedErrorReporter) {
if (taskId == null || taskId <= 0) {
throw new BusinessException("任务 ID 不合法");
}
if (request == null) {
throw new BusinessException("回传体为空");
}
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !TaskFinalizeSupport.belongsToModule(JdPublishTaskService.MODULE_TYPE, task.getModuleType())) {
throw new BusinessException("任务不存在: " + taskId);
}
if (TaskStatuses.FileTask.TERMINAL.contains(task.getStatus())) {
throw new BusinessException("任务已结束(" + task.getStatus() + "),不再接受回传");
}
if (request.getError() != null && !request.getError().isBlank()) {
return handleErrorReport(task, request.getError(), trustedErrorReporter);
}
if (!STATUS_RUNNING.equals(task.getStatus())) {
// PENDING 拒收(页面推送漏 activate 时客户端第一个回传在此被拒,2026-11-14 同形实录)。
throw new BusinessException("任务不在运行中(" + task.getStatus() + "),请先激活任务再回传");
}
int accepted = 0;
if (request.getItems() != null) {
for (ItemResult item : request.getItems()) {
accepted += applyRowResult(taskId, item);
}
}
JdPublishChunkVo vo = new JdPublishChunkVo();
vo.setAcceptedCount(accepted);
vo.setPendingCount(statusCounts(taskId).getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L));
if (Boolean.TRUE.equals(request.getIsEnd())) {
vo.setTaskStatus(summarizeTerminal(taskId));
}
log.info("[{}] chunk 回传 taskId={} batchId={} accepted={} pending={} isEnd={}",
LOG_TAG, taskId, request.getBatchId(), accepted, vo.getPendingCount(),
Boolean.TRUE.equals(request.getIsEnd()));
return vo;
}
/** 行级结果落库:按 uk_task_product(task_id + product_id)定位,单行失败不炸批。 */
private int applyRowResult(Long taskId, ItemResult item) {
if (item == null || item.getProductId() == null) {
return 0;
}
String status = item.getPublishStatus() == null ? null : item.getPublishStatus().trim().toUpperCase();
if (status == null || !WRITABLE_STATUSES.contains(status)) {
log.warn("[{}] 回传行状态不识别,跳过 taskId={} productId={} status={}",
LOG_TAG, taskId, item.getProductId(), item.getPublishStatus());
return 0;
}
LambdaUpdateWrapper<JdPublishItemEntity> wrapper = new LambdaUpdateWrapper<JdPublishItemEntity>()
.eq(JdPublishItemEntity::getTaskId, taskId)
.eq(JdPublishItemEntity::getProductId, item.getProductId())
.set(JdPublishItemEntity::getPublishStatus, status)
.set(JdPublishItemEntity::getPublishError,
JdPublishTaskService.ITEM_FAILED.equals(status)
? truncate(item.getPublishError()) : null)
.set(JdPublishItemEntity::getJdWareId, item.getJdWareId())
.set(JdPublishItemEntity::getUpdatedAt, LocalDateTime.now());
int updated = jdPublishItemMapper.update(null, wrapper);
if (updated == 0) {
log.warn("[{}] 回传行未命中明细行(商品不在本任务?)taskId={} productId={}",
LOG_TAG, taskId, item.getProductId());
}
return updated;
}
/** 铁律 31 分档判死口:只信 X-Internal-Token,匿名 error 一律拒绝判死(不碰状态)。 */
private JdPublishChunkVo handleErrorReport(FileTaskEntity task, String error, boolean trustedErrorReporter) {
JdPublishChunkVo vo = new JdPublishChunkVo();
vo.setAcceptedCount(0);
vo.setPendingCount(statusCounts(task.getId()).getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L));
if (!trustedErrorReporter) {
log.warn("[{}] 匿名 error 上报拒绝判死 taskId={} err={}", LOG_TAG, task.getId(), abbreviate(error));
return vo;
}
// 京东域凭据词(京麦登录态)先判——采集/发布共用 19899 同一 profile,同一族同一判据。
if (JdStaleTaskService.isJdLoginStateFailure(error)) {
staleTaskService.terminalizeOnJdLoginFatal(task, error);
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
return vo;
}
// 代理/LLM 凭据致命词 → 公共判定档(发布面无代理无 LLM 消费,客户端报什么分什么档)。
boolean closed = new CredentialFatalTaskCloser(LOG_TAG, fileTaskMapper, null)
.closeIfFatal(task, error);
if (closed) {
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
return vo;
}
log.warn("[{}] 非致命失败上报,只记录不判死 taskId={} err={}", LOG_TAG, task.getId(), abbreviate(error));
return vo;
}
/** isEnd 终态汇总:按行级真源聚合落任务终态(R6),CAS 只认 RUNNING(铁律 14)。 */
private String summarizeTerminal(Long taskId) {
Map<String, Long> counts = statusCounts(taskId);
long success = counts.getOrDefault(JdPublishTaskService.ITEM_SUCCESS, 0L);
long failed = counts.getOrDefault(JdPublishTaskService.ITEM_FAILED, 0L);
long unpublished = counts.getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L)
+ counts.getOrDefault(JdPublishTaskService.ITEM_PUBLISHING, 0L);
boolean anyFailed = failed > 0;
String status = anyFailed ? TaskStatuses.FileTask.FAILED : TaskStatuses.FileTask.SUCCESS;
StringBuilder reason = new StringBuilder("发布完成:成功 ").append(success).append(" 行,失败 ")
.append(failed).append(" 行");
if (unpublished > 0) {
reason.append(",未发布 ").append(unpublished).append(" 行");
}
LocalDateTime now = LocalDateTime.now();
// 文案先落局部变量再配对写列(B51-R1 守卫「写的列与文案同一个来源」:列由同一句文案派生,
// 三元里各写各的表达式会被 TaskFailureCategoryGuardrailTest 判为不同源即红)。
String message = anyFailed ? reason.toString() : null;
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId)
.eq(FileTaskEntity::getModuleType, JdPublishTaskService.MODULE_TYPE)
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
.set(FileTaskEntity::getStatus, status)
.set(FileTaskEntity::getSuccessFileCount, success)
.set(FileTaskEntity::getFailedFileCount, failed)
.set(FileTaskEntity::getErrorMessage, message)
.set(FileTaskEntity::getFailureCategory, message == null ? null : TaskFailureLedger.categoryOf(message))
.set(FileTaskEntity::getUpdatedAt, now)
.set(FileTaskEntity::getFinishedAt, now));
if (updated > 0) {
taskProgressSnapshotService.markTerminal(taskId, JdPublishTaskService.MODULE_TYPE, status,
anyFailed ? reason.toString() : null);
log.info("[{}] 任务落终态 {} taskId={}", LOG_TAG, status, taskId);
}
return status;
}
/** 行级状态聚合(XML 具名 SQL):status → 行数。 */
private Map<String, Long> statusCounts(Long taskId) {
Map<String, Long> counts = new LinkedHashMap<>();
for (Map<String, Object> row : jdPublishItemMapper.countByPublishStatus(taskId)) {
Object status = row.get("publishStatus");
Object cnt = row.get("cnt");
if (status != null && cnt instanceof Number number) {
counts.put(String.valueOf(status), number.longValue());
}
}
return counts;
}
private String truncate(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.length() <= MAX_ERROR_LENGTH ? trimmed : trimmed.substring(0, MAX_ERROR_LENGTH);
}
private String abbreviate(String value) {
if (value == null) {
return "";
}
return value.length() <= 200 ? value : value.substring(0, 200) + "…";
}
/** 供测试确认行级形状(按任务取全部明细行)。 */
public java.util.List<JdPublishItemEntity> findItemRows(Long taskId) {
return jdPublishItemMapper.selectList(new LambdaQueryWrapper<JdPublishItemEntity>()
.eq(JdPublishItemEntity::getTaskId, taskId)
.orderByAsc(JdPublishItemEntity::getId));
}
}
@@ -0,0 +1,156 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.common.task.LockSkipWitness;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.StaleTaskHeartbeatPolicy;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/**
* 京东商品上架判活(v1.5 蓝图 §4 Phase 2,形状照 {@code JdStaleTaskService} 同形)。
*
* <p>两件事,登记形态不同:① <b>心跳超时兜底判死</b>——自带 {@code @Scheduled} 巡检
* (注册表 {@code selfScheduledStaleCheck=true},同 JD_SHOP_COLLECT 先例:发布是逐商品页面
* 自动化,节奏比采集还慢,60 分钟超时线({@code aiimage.jd.publish.stale-minutes},按发布
* 时长重估)并入 2 分钟集中巡检线没有额外收益,自管判死时延即可);② <b>京麦登录态失效
* 判死</b>——客户端在回传 {@code error} 里报「京麦未登录 / 登录态失效」时由回传侧
* ({@code JdPublishIngestService})调 {@link #terminalizeOnJdLoginFatal} 整单落终态
* (铁律 31:凭据不可自愈 ⇒ 行失败 + 整单终态,让心跳对采集端回 {@code alive=false} 收手),
* 判死出口集中在本类。</p>
*
* <p>「京麦登录态」词表是京东域两链共用的同一族凭据词(采集/发布共用 19899 同一 profile,
* 登录态失效的形状相同)——判据直接复用 {@code JdStaleTaskService#isJdLoginStateFailure},
* 不另抄一份词表(两份词表各改各的就是分叉判据);代理/LLM 凭据致命词的分档不在本类——
* 那是 {@code CredentialFatalClassifier} 的公共词表,回传侧直接用。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JdPublishStaleTaskService {
public static final String MODULE_TYPE = JdPublishTaskService.MODULE_TYPE;
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
private static final String STATUS_FAILED = TaskStatuses.FileTask.FAILED;
private static final String LOG_TAG = "jd-publish";
private final FileTaskMapper fileTaskMapper;
private final TaskDistributedLockService taskDistributedLockService;
private final DistributedJobLockService distributedJobLockService;
private final StaleTaskHeartbeatPolicy staleTaskHeartbeatPolicy;
private final TaskProgressSnapshotService taskProgressSnapshotService;
/** 心跳超时线(分钟),按发布时长重估(蓝图 §3);下限钳 1。 */
@Value("${aiimage.jd.publish.stale-minutes:60}")
private long staleMinutes;
/** 心跳超时兜底判死(自带调度;分布式锁保证 A/B 双实例单跑;秒位 45 与采集面 40 错开)。 */
@Scheduled(cron = "${aiimage.jd.publish.stale-check-cron:45 */2 * * * *}")
public void finalizeStaleTasks() {
DistributedJobLockService.LockHandle lock =
distributedJobLockService.tryLock("jd-publish:stale-check", java.time.Duration.ofMinutes(10));
if (lock == null) {
LockSkipWitness.abandoned("jd-publish:stale-check");
return;
}
try (lock) {
long minutes = Math.max(1L, staleMinutes);
LocalDateTime threshold = LocalDateTime.now().minusMinutes(minutes);
List<FileTaskEntity> candidates = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
.lt(FileTaskEntity::getUpdatedAt, threshold)
.last("limit 200"));
for (FileTaskEntity task : candidates) {
if (staleTaskHeartbeatPolicy.isStillQueuedBeforeFirstHeartbeat(
task.getId(), 0L, task.getUpdatedAt(), LocalDateTime.now())) {
// 首次心跳之前不判死:任务还在客户端队列排队,updated_at 停在认领时刻不是卡死证据。
log.info("[{}] 未收到首次心跳、排队宽限内暂不判死 taskId={} updatedAt={} timeoutMinutes={}",
LOG_TAG, task.getId(), task.getUpdatedAt(), minutes);
continue;
}
TaskDistributedLockService.LockHandle taskLock =
taskDistributedLockService.acquire(MODULE_TYPE, task.getId(), 0L);
if (taskLock == null) {
LockSkipWitness.recordAbandoned("jd-publish:stale-finalize", MODULE_TYPE, task.getId());
continue;
}
try (taskLock) {
failStale(task, minutes);
}
}
}
}
private void failStale(FileTaskEntity task, long minutes) {
String reason = "京东上架心跳超时超过 " + minutes + " 分钟,任务已自动失败";
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
.set(FileTaskEntity::getStatus, STATUS_FAILED)
.set(FileTaskEntity::getErrorMessage, reason)
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(reason))
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
if (updated > 0) {
taskProgressSnapshotService.markTerminal(task.getId(), MODULE_TYPE, STATUS_FAILED, reason);
log.warn("[{}] 心跳超时改判死 taskId={} updatedAt={} timeoutMinutes={}",
LOG_TAG, task.getId(), task.getUpdatedAt(), minutes);
}
}
/**
* 京麦登录态失效整单判死(铁律 31):CAS RUNNING→FAILED,终态文案点名「京麦未登录」与
* 「登录态失效」并给动作句(不写「稍后重试」)。已终态的任务 CAS 自然不命中,可重入。
*
* @return true=本次真的把任务写成了终态
*/
public boolean terminalizeOnJdLoginFatal(FileTaskEntity task, String rawError) {
if (task == null || task.getId() == null) {
return false;
}
String message = terminalLoginMessage(rawError);
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
.set(FileTaskEntity::getStatus, STATUS_FAILED)
.set(FileTaskEntity::getSuccessFileCount, 0)
.set(FileTaskEntity::getFailedFileCount, 1)
.set(FileTaskEntity::getErrorMessage, message)
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(message))
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
if (updated > 0) {
taskProgressSnapshotService.markTerminal(task.getId(), MODULE_TYPE, STATUS_FAILED, message);
log.warn("[{}] 京麦登录态失效,任务落终态 FAILED taskId={} err={}", LOG_TAG, task.getId(), message);
}
return updated > 0;
}
/** 终态文案:生产者原文 + 点名两句判据词(「京麦未登录」「登录态失效」都在,AC-5 口径)+ 动作句。 */
static String terminalLoginMessage(String rawError) {
String raw = rawError == null ? "" : rawError.trim();
StringBuilder message = new StringBuilder();
if (!raw.isEmpty()) {
message.append(raw).append(";");
}
message.append("京麦未登录(登录态失效),请在客户端重新登录京麦后重试");
return message.toString();
}
}
@@ -0,0 +1,59 @@
package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.TaskModuleHeartbeatSpi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 京东商品上架的心跳 SPI 接线(v1.5,形状照 {@code JdCollectTaskHeartbeatSpi} 同形)。
*
* <p>京东模块没有独立的任务缓存(进度由全局心跳位置表、{@code biz_jd_publish_item}
* 行级真源与 {@code biz_task_progress_snapshot} 承载),所以 {@link #touchHeartbeat} 是
* 语义上的空实现——挂这个 Bean 的目的:① 心跳契约测试按注册表校验每个 moduleType 都有
* SPI,缺了会红;② 显式声明 {@code heartbeatNeedsFullTaskEntity()=false},心跳热路径不捞
* {@code request_json}/{@code result_json} 整行(AC-19 同款省钱口径);③ <b>override
* {@link #ensureOwnership}</b>——B98-07 同形债预防(采集面 JdCollectTaskHeartbeatSpi 未
* override,任意用户可给任意京东任务刷心跳续命,在册 P3)。</p>
*
* <p><b>为什么不在 SPI 里做实例域拒绝</b>:publish/shop-data-crawl 的任务由服务端 worker
* 执行、心跳来自执行线程自身(认领实例),按 {@code owner_instance_id} 拒绝安全;京东发布
* 是 LOCAL 单机任务、心跳来自用户桌面机客户端——公网入口可能落到 A/B 任一实例,按实例域
* 拒绝会把「心跳落到非认领实例」误杀成断连。用户域归属校验落在
* {@code JdPublishController#heartbeat}(可信 uid 只在会话层拿得到),本 override 做
* 任务在飞的轻校验并留审核痕迹。</p>
*/
@Slf4j
@Component
public class JdPublishTaskHeartbeatSpi implements TaskModuleHeartbeatSpi {
@Override
public String moduleType() {
return JdPublishTaskService.MODULE_TYPE;
}
@Override
public void touchHeartbeat(Long taskId, TaskHeartbeatRequest request) {
// 京东发布无模块缓存可刷:行级进度由 chunk 回传侧写,心跳只走 task 侧的通用通道。
}
/**
* B98-07 同形债预防(override=债已接,不是漏接):任务为空或模块不归属即拒绝;
* 实例域判据刻意不做(LOCAL 客户端心跳会落任一实例,见类注释)——用户域归属校验
* 在控制器层按可信 uid 执行。
*/
@Override
public void ensureOwnership(FileTaskEntity task, String operation) {
if (task == null || task.getId() == null
|| !JdPublishTaskService.MODULE_TYPE.equals(task.getModuleType())) {
throw new IllegalArgumentException("心跳目标不是京东上架任务 taskId="
+ (task == null ? null : task.getId()) + " operation=" + operation);
}
}
@Override
public boolean heartbeatNeedsFullTaskEntity() {
return false;
}
}
@@ -0,0 +1,46 @@
package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.ClientTaskPullSpi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* 京东商品上架的客户端兜底拉取实现(v1.5,铁律 32 派发三件套第一件)。
*
* <p>页面推送缺失(只建单没推送 / 推送前关页面 / 纯浏览器打开)时任务会停在 PENDING,
* {@code TaskClientPullService} 认领后由本实现组装可直接入队的载荷。载荷组装单一出处=
* {@link JdPublishTaskService#buildQueuePayload}(建单响应体与兜底拉取共用),type 与
* 客户端分发键逐字同值 <b>jd-product-publish-run</b>({@code QUEUE_TYPE})——
* 两处漂移任务客户端不识别(铁律 32:领了任务却「未知任务类型」)。</p>
*
* <p>明细(标题/价格/SKU/图片预签名)不在派发载荷里——载荷只带 taskId+改价规则
* (蓝图 §3:载荷尺寸可控、断点友好),客户端拿到后按游标分批拉
* {@code GET /api/jd-publish/tasks/{taskId}/items}。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class JdPublishTaskPullSpiImpl implements ClientTaskPullSpi {
/** 与客户端 amazon/jd/publish 的 QUEUE_TYPE 逐字同值(改这里必须同轮改客户端)。 */
public static final String QUEUE_TYPE = "jd-product-publish-run";
private final JdPublishTaskService publishTaskService;
@Override
public String moduleType() {
return JdPublishTaskService.MODULE_TYPE;
}
@Override
public Map<String, Object> buildQueuePayload(FileTaskEntity task) {
// 载荷组装单一出处:与建单响应的 queuePayload 同源(铁律 32 三件同值判据)。
Map<String, Object> payload = publishTaskService.buildQueuePayload(task);
log.info("[jd-publish] 兜底载荷已组装 taskId={}", task.getId());
return payload;
}
}
@@ -0,0 +1,537 @@
package com.nanri.aiimage.modules.jd.service;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
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.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.config.CollectRoutingProperties;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest.PriceRule;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishItemPayloadVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishItemsPageVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishProgressVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.CollectChannel;
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 京东商品上架建单(v1.5 蓝图 docs/ITERATION_PLAN.md §4 Phase 2:建单/配额/归属/生命周期/明细下发)。
*
* <p>形状照 {@code JdCollectTaskService} 同形:Mapper {@code insert} +
* taskNo={@code MODULE_TYPE-Snowflake} + 载荷整体进 {@code request_json}。京东发布特有:
* ① 执行通道恒 {@code LOCAL} 且<b>建单显式写库</b>(铁律 19:京麦登录态只在用户桌面机
* 19899 Chrome profile,执行方没有"界面选 ONLINE"的自由度);② 建单口<b>不接</b>
* {@code requireSubmitSecret}——发布由桌面机已登录京麦的 Chrome 直连执行,无代理无 LLM
* ({@code TaskModuleRegistry} 登记 {@code Optional.empty()},铁律 27c 登记结论);
* ③ 建单前置闸门按铁律 27b 排在一切昂贵动作前:未选商品 / 选了他人商品(AC-9 归属,
* 业务码 403)/ 超配额(AC-8,{@code JdPublishQuotaService#assertWithinQuota} 原语接线)
* 逐条点名拒绝;④ 建单即按商品快照落 {@code biz_jd_publish_item} 行(V210,商品库有
* 清理语义,发布记录不随商品删除丢失溯源)。</p>
*
* <p>建单成功页面推送与兜底拉取共用同一份载荷组装 {@link #buildQueuePayload}:
* type=<b>jd-product-publish-run</b>(与 {@link JdPublishTaskPullSpiImpl#QUEUE_TYPE}
* 逐字同值,铁律 32 第三件——两处漂移任务永不执行)。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JdPublishTaskService {
public static final String MODULE_TYPE = CollectRoutingProperties.MODULE_JD_PUBLISH;
private static final String STATUS_PENDING = TaskStatuses.FileTask.PENDING;
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
/** 行级状态词表(V210 publish_status 列,与客户端 chunk 回传同词表)。 */
public static final String ITEM_PENDING = "PENDING";
public static final String ITEM_PUBLISHING = "PUBLISHING";
public static final String ITEM_SUCCESS = "SUCCESS";
public static final String ITEM_FAILED = "FAILED";
/** 单任务商品勾选上限(防 request_json/明细行膨胀;建单口拦注定失败的输入)。 */
private static final int MAX_PRODUCT_IDS = 500;
/** items 下发批大小上限(服务侧钳制,防一次拉满 500 行把载荷撑爆)。 */
private static final int MAX_ITEMS_BATCH = 100;
/** 图片预签名 GET 有效期(秒):发布一批跑得久,24h 同 InternalAudio 先例。 */
private static final int IMAGE_PRESIGN_EXPIRY_SECONDS = 86_400;
private final FileTaskMapper fileTaskMapper;
private final JdProductMapper jdProductMapper;
private final JdProductImageMapper jdProductImageMapper;
private final JdProductSkuMapper jdProductSkuMapper;
private final JdPublishItemMapper jdPublishItemMapper;
private final JdPublishQuotaService jdPublishQuotaService;
private final AdminUserMapper adminUserMapper;
private final OssStorageService ossStorageService;
private final ObjectMapper objectMapper;
private final TaskHeartbeatService taskHeartbeatService;
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
/** 下发批大小出厂值(aiimage.jd.publish.items-batch-size,服务侧钳制上限 100)。 */
@Value("${aiimage.jd.publish.items-batch-size:20}")
private int itemsBatchSize = 20;
/** jd-products 独立桶(V194 同源配置,商品图/详情长图都在这里,铁律 17)。 */
@Value("${aiimage.jd.oss.bucket:jd-products}")
private String bucket;
public JdPublishTaskVo createTask(JdPublishTaskCreateRequest request, String deviceId) {
validate(request);
// AC-8 配额闸:前置在一切昂贵动作前(铁律 27b),超配额当场业务码拒绝并点名额度文案。
AdminUserEntity operator = adminUserMapper.selectById(request.getUserId());
jdPublishQuotaService.assertWithinQuota(operator, request.getProductIds().size());
// AC-9 归属半边:按主键批量取商品行(建单勾选集上界 500,非取页分页),存在性
// 与归属一起 fail-closed——缺行与选了他人商品都当场拒,不让一半商品静默混进任务。
List<JdProductEntity> products = jdProductMapper.selectBatchIds(request.getProductIds());
if (products.size() != request.getProductIds().size()) {
throw new BusinessException("部分商品不存在或已从京东数据库清理,请刷新后重新勾选");
}
for (JdProductEntity product : products) {
if (!Objects.equals(product.getUserId(), request.getUserId())) {
throw new BusinessException(403, "勾选的商品不属于当前账号,不能上架他人数据库的商品");
}
}
LocalDateTime now = LocalDateTime.now();
FileTaskEntity task = new FileTaskEntity();
task.setTaskNo(MODULE_TYPE + "-" + IdUtil.getSnowflakeNextIdStr());
task.setModuleType(MODULE_TYPE);
task.setTaskMode("PYTHON_QUEUE");
// 铁律 19:建单入口显式写通道。京东发布只能在本机已登录京麦的 Chrome 执行。
task.setCollectChannel(CollectChannel.LOCAL.name());
task.setStatus(STATUS_PENDING);
task.setSourceFileCount(request.getProductIds().size());
task.setSuccessFileCount(0);
task.setFailedFileCount(0);
task.setCreatedBy("user:" + request.getUserId());
task.setUserId(request.getUserId());
task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
task.setCreatedAt(now);
task.setUpdatedAt(now);
try {
task.setRequestJson(objectMapper.writeValueAsString(request));
task.setResultJson("{}");
} catch (Exception ex) {
throw new BusinessException("序列化建单载荷失败", ex);
}
fileTaskMapper.insert(task);
// 建单即落明细快照行(蓝图 §3):标题/类目/价格折算/库存/店铺/编码随行固化,
// 商品行被清理后发布记录仍可溯源;uk_task_product 防同任务重复勾选落两行。
Map<Long, String> mainImageByProduct = loadMainImageObjectKeys(products);
for (JdProductEntity product : products) {
jdPublishItemMapper.insert(buildSnapshotItem(task, product, request,
mainImageByProduct.get(product.getId()), now));
}
JdPublishTaskVo vo = new JdPublishTaskVo();
vo.setTaskId(task.getId());
vo.setTaskNo(task.getTaskNo());
vo.setCollectChannel(task.getCollectChannel());
vo.setQueuePayload(buildQueuePayload(task));
log.info("[jd-publish] 建单成功 taskId={} taskNo={} products={} userId={} channel={}",
task.getId(), task.getTaskNo(), request.getProductIds().size(),
request.getUserId(), task.getCollectChannel());
return vo;
}
/**
* 激活任务(PENDING→RUNNING)——页面把载荷推给本机客户端<b>之前</b>调用。
*
* <p>形状照 {@code JdCollectTaskService#activateTask} 同形(2026-11-14 真机实录:漏掉
* 这一步,客户端第一个回传会被「任务不在运行中(PENDING)」拒收)。只允许
* PENDING→RUNNING 条件更新:与客户端兜底拉取的原子认领互斥,谁先翻转谁执行。
*/
public void activateTask(Long taskId, Long userId) {
FileTaskEntity task = fileTaskMapper.selectById(taskId);
// 归属谓词走公共出口(TaskLifecycleDebtRatchetTest 棘轮只许降:新增手写遍数即红)。
if (task == null || !TaskFinalizeSupport.belongsToModule(MODULE_TYPE, task.getModuleType())
|| (userId != null && task.getUserId() != null && !Objects.equals(userId, task.getUserId()))) {
throw new BusinessException("任务不存在");
}
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId)
.eq(FileTaskEntity::getStatus, STATUS_PENDING)
.set(FileTaskEntity::getStatus, STATUS_RUNNING)
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
if (updated == 0) {
FileTaskEntity latest = fileTaskMapper.selectById(taskId);
if (latest != null && STATUS_RUNNING.equals(latest.getStatus())) {
throw new BusinessException("任务已在执行中(可能已由客户端自动接管),无需重复启动");
}
throw new BusinessException("任务已结束");
}
log.info("[jd-publish] 已激活(PENDING→RUNNING) taskId={} userId={}", taskId, task.getUserId());
}
/**
* 明细分批下发(GET /items):只出 PENDING 行(已回传行被 SQL 状态谓词跳过,断点
* 重连 cursor 归零也不会重发已发布商品,AC-4 服务端半边);SKU 价按改价规则折算;
* 图片发 jd-products 桶预签名 GET URL(蓝图 §3)。
*/
public JdPublishItemsPageVo pullItems(Long taskId, Long userId, Long cursor, Integer limit) {
requireOwnedTask(taskId, userId);
int safeLimit = Math.min(Math.max(limit == null ? itemsBatchSize : limit, 1), MAX_ITEMS_BATCH);
long safeCursor = cursor == null ? 0L : Math.max(0L, cursor);
List<JdPublishItemEntity> rows = jdPublishItemMapper.selectPublishableItems(taskId, safeCursor, safeLimit);
// 页内商品行批量取(attrs 原样透传),不逐行 selectById。
Map<Long, JdProductEntity> productsByPid = rows.isEmpty() ? Map.of()
: jdProductMapper.selectBatchIds(rows.stream().map(JdPublishItemEntity::getProductId).toList())
.stream().collect(Collectors.toMap(JdProductEntity::getId, Function.identity(), (a, b) -> a));
JdPublishItemsPageVo vo = new JdPublishItemsPageVo();
vo.setTaskId(taskId);
vo.setItems(rows.isEmpty() ? List.of() : rows.stream()
.map(row -> buildItemPayload(row, productsByPid.get(row.getProductId())))
.toList());
vo.setNextCursor(rows.isEmpty() ? safeCursor : rows.get(rows.size() - 1).getId());
vo.setHasMore(rows.size() == safeLimit);
vo.setPendingCount(aggregateStatusCounts(taskId).getOrDefault(ITEM_PENDING, 0L));
return vo;
}
/** 行级进度(R7 实时面板):任务级状态/终态原因 + 行级分组计数。 */
public JdPublishProgressVo queryProgress(Long taskId, Long userId) {
FileTaskEntity task = requireOwnedTask(taskId, userId);
JdPublishProgressVo vo = new JdPublishProgressVo();
vo.setTaskId(task.getId());
vo.setStatus(task.getStatus());
vo.setMessage(task.getErrorMessage());
vo.setUpdatedAt(task.getUpdatedAt());
Map<String, Long> counts = aggregateStatusCounts(taskId);
vo.setPendingCount(counts.getOrDefault(ITEM_PENDING, 0L));
vo.setPublishingCount(counts.getOrDefault(ITEM_PUBLISHING, 0L));
vo.setSuccessCount(counts.getOrDefault(ITEM_SUCCESS, 0L));
vo.setFailedCount(counts.getOrDefault(ITEM_FAILED, 0L));
vo.setTotalCount(vo.getPendingCount() + vo.getPublishingCount() + vo.getSuccessCount() + vo.getFailedCount());
return vo;
}
/** 回传/兜底拉取侧读建单载荷(request_json 整体);缺失/损坏按异常拒绝,不静默兜。 */
public JdPublishTaskCreateRequest readCreateRequest(FileTaskEntity task) {
try {
JdPublishTaskCreateRequest request = objectMapper.readValue(task.getRequestJson(),
JdPublishTaskCreateRequest.class);
if (request == null || request.getProductIds() == null || request.getProductIds().isEmpty()) {
throw new BusinessException("任务载荷缺少 productIds,无法下发发布明细");
}
return request;
} catch (BusinessException ex) {
throw ex;
} catch (Exception ex) {
throw new BusinessException("任务载荷解析失败 taskId=" + task.getId(), ex);
}
}
/** 建单成功页面推送载荷(铁律 32 第三件;type 与 JdPublishTaskPullSpiImpl.QUEUE_TYPE 同值)。 */
public Map<String, Object> buildQueuePayload(FileTaskEntity task) {
JdPublishTaskCreateRequest create = readCreateRequest(task);
Map<String, Object> data = new LinkedHashMap<>();
data.put("taskId", task.getId());
data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule());
return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data);
}
/**
* 心跳上报(B98-07 同形债预防,用户域半边):归属校验在调全局心跳通道<b>之前</b>——
* 可信 uid 按 (taskId, userId) 对比任务 owner,不一致一律拒;比对放服务层让全局
* {@code /api/tasks/{taskId}/heartbeat} 与本模块内聚端点共用同一闸(B98-07 的债是
* 「任意用户可给任意任务刷心跳续命」,实例域判据对 LOCAL 客户端心跳不适用,
* 见 {@code JdPublishTaskHeartbeatSpi} 类注释)。
*/
public TaskHeartbeatVo heartbeat(Long taskId, Long userId, TaskHeartbeatRequest request) {
requireOwnedTask(taskId, userId);
taskHeartbeatPositionService.record(taskId, request);
return taskHeartbeatService.heartbeat(taskId, request);
}
/** 供测试确认快照行形状。 */
public List<JdPublishItemEntity> findItemRows(Long taskId) {
return jdPublishItemMapper.selectList(new LambdaQueryWrapper<JdPublishItemEntity>()
.eq(JdPublishItemEntity::getTaskId, taskId)
.orderByAsc(JdPublishItemEntity::getId));
}
/** 归属校验唯一出口:模块归属谓词走公共出口 + (taskId, userId) 归属对比(铁律 11)。 */
private FileTaskEntity requireOwnedTask(Long taskId, Long userId) {
if (taskId == null || taskId <= 0) {
throw new BusinessException("任务 ID 不合法");
}
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !TaskFinalizeSupport.belongsToModule(MODULE_TYPE, task.getModuleType())) {
throw new BusinessException("任务不存在: " + taskId);
}
if (userId != null && task.getUserId() != null && !Objects.equals(userId, task.getUserId())) {
throw new BusinessException(403, "无权查看该任务");
}
return task;
}
private void validate(JdPublishTaskCreateRequest request) {
if (request.getUserId() == null || request.getUserId() <= 0) {
throw new BusinessException("user_id 不合法");
}
if (request.getProductIds() == null || request.getProductIds().isEmpty()) {
throw new BusinessException("请勾选要上架的商品");
}
// 保序去重:同一次提交里重复勾选同一商品,落一行而不是两行(uk_task_product 同义)。
request.setProductIds(request.getProductIds().stream()
.filter(Objects::nonNull)
.filter(id -> id > 0)
.distinct()
.toList());
if (request.getProductIds().isEmpty()) {
throw new BusinessException("请勾选要上架的商品");
}
if (request.getProductIds().size() > MAX_PRODUCT_IDS) {
throw new BusinessException("单次上架最多选 " + MAX_PRODUCT_IDS + " 个商品,当前 "
+ request.getProductIds().size() + " 个");
}
normalizePriceRule(request);
}
/** 改价规则归一化写回请求体:request_json 里的值必须就是闸门认可的值(铁律 27a 同源)。 */
private void normalizePriceRule(JdPublishTaskCreateRequest request) {
PriceRule rule = request.getPriceRule();
if (rule == null || rule.getMode() == null || rule.getMode().isBlank()) {
request.setPriceRule(null);
return;
}
String mode = rule.getMode().trim().toLowerCase(Locale.ROOT);
if (!Set.of("none", "percent", "fixed").contains(mode)) {
throw new BusinessException("改价规则不识别: " + rule.getMode() + "(只支持 none/percent/fixed)");
}
if (!"none".equals(mode)) {
if (rule.getValue() == null) {
throw new BusinessException("改价规则 mode=" + mode + " 时必须填写加价值");
}
if (rule.getValue().compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException("加价值不能为负数");
}
}
rule.setMode(mode);
request.setPriceRule(rule);
}
/** 最终价:none 原值;percent 按百分比上浮;fixed 固定加价。2 位小数 HALF_UP。 */
static BigDecimal finalPriceOf(BigDecimal source, PriceRule rule) {
if (source == null) {
return null;
}
if (rule == null || rule.getValue() == null || "none".equals(rule.getMode())) {
return source.setScale(2, RoundingMode.HALF_UP);
}
if ("percent".equals(rule.getMode())) {
BigDecimal uplifted = source.add(source.multiply(rule.getValue()).movePointLeft(2));
return uplifted.setScale(2, RoundingMode.HALF_UP);
}
return source.add(rule.getValue()).setScale(2, RoundingMode.HALF_UP);
}
/** 快照明细行:商品主档列随行固化,改价折算进 price_rule_json(蓝图 §3)。 */
private JdPublishItemEntity buildSnapshotItem(FileTaskEntity task, JdProductEntity product,
JdPublishTaskCreateRequest request,
String mainImageObjectKey, LocalDateTime now) {
JdPublishItemEntity item = new JdPublishItemEntity();
item.setTaskId(task.getId());
item.setCompanyId(product.getCompanyId());
item.setUserId(task.getUserId());
item.setProductId(product.getId());
item.setProductCode(product.getProductCode());
item.setShopName(product.getShopName());
item.setTitle(product.getTitle());
item.setCategoryPath(product.getCategoryPath());
PriceRule rule = request.getPriceRule();
BigDecimal sourcePrice = product.getPriceMin();
Map<String, Object> priceJson = new LinkedHashMap<>();
priceJson.put("mode", rule == null ? "none" : rule.getMode());
priceJson.put("value", rule == null ? null : rule.getValue());
priceJson.put("sourcePrice", sourcePrice);
priceJson.put("finalPrice", finalPriceOf(sourcePrice, rule));
item.setPriceRuleJson(toJson(priceJson));
Map<String, Object> stockJson = new LinkedHashMap<>();
stockJson.put("total", product.getStockTotal());
item.setStockJson(toJson(stockJson));
item.setPublishStatus(ITEM_PENDING);
item.setMainImageObjectKey(mainImageObjectKey);
item.setCreatedAt(now);
item.setUpdatedAt(now);
return item;
}
private String toJson(Map<String, Object> value) {
try {
return objectMapper.writeValueAsString(value);
} catch (Exception ex) {
throw new BusinessException("序列化快照列失败", ex);
}
}
/** MAIN 档主图 objectKey(每商品取 sortNo 最小行);图片行缺失/无 key 的商品不落主图列。 */
private Map<Long, String> loadMainImageObjectKeys(List<JdProductEntity> products) {
List<Long> productIds = products.stream().map(JdProductEntity::getId).toList();
List<JdProductImageEntity> images = jdProductImageMapper.selectList(
new LambdaQueryWrapper<JdProductImageEntity>()
.in(JdProductImageEntity::getProductId, productIds)
.eq(JdProductImageEntity::getImageType, "MAIN")
.orderByAsc(JdProductImageEntity::getSortNo, JdProductImageEntity::getId));
Map<Long, String> result = new LinkedHashMap<>();
for (JdProductImageEntity image : images) {
if (image.getObjectKey() != null && !image.getObjectKey().isBlank()) {
result.putIfAbsent(image.getProductId(), image.getObjectKey());
}
}
return result;
}
/** 行级状态聚合(XML 具名 SQL):status → 行数。 */
private Map<String, Long> aggregateStatusCounts(Long taskId) {
Map<String, Long> counts = new LinkedHashMap<>();
for (Map<String, Object> row : jdPublishItemMapper.countByPublishStatus(taskId)) {
Object status = row.get("publishStatus");
Object cnt = row.get("cnt");
if (status != null && cnt instanceof Number number) {
counts.put(String.valueOf(status), number.longValue());
}
}
return counts;
}
/** 单行下发载荷:SKU 折算价 + 图片预签名 GET(商品行由页内批量预取传入)。 */
private JdPublishItemPayloadVo buildItemPayload(JdPublishItemEntity row, JdProductEntity product) {
JdPublishItemPayloadVo vo = new JdPublishItemPayloadVo();
vo.setItemId(row.getId());
vo.setProductId(row.getProductId());
vo.setProductCode(row.getProductCode());
vo.setTitle(row.getTitle());
vo.setCategoryPath(row.getCategoryPath());
vo.setSourcePrice(sourcePriceOf(row));
vo.setFinalPrice(finalPriceOf(row));
vo.setStockTotal(stockTotalOf(row));
vo.setAttrs(product == null ? null : product.getAttrJson());
PriceRule rule = priceRuleOf(row);
vo.setSkus(loadSkuPayloads(row.getProductId(), rule));
vo.setMainImages(loadImagePayloads(row.getProductId(), "MAIN"));
vo.setAttrImages(loadImagePayloads(row.getProductId(), "ATTR"));
vo.setDetailImages(loadImagePayloads(row.getProductId(), "DETAIL"));
return vo;
}
private PriceRule priceRuleOf(JdPublishItemEntity row) {
Map<String, Object> json = readJson(row.getPriceRuleJson());
PriceRule rule = new PriceRule();
Object mode = json.get("mode");
Object value = json.get("value");
rule.setMode(mode == null ? "none" : String.valueOf(mode));
rule.setValue(decimalOf(value));
return rule;
}
private BigDecimal sourcePriceOf(JdPublishItemEntity row) {
return decimalOf(readJson(row.getPriceRuleJson()).get("sourcePrice"));
}
private BigDecimal finalPriceOf(JdPublishItemEntity row) {
return decimalOf(readJson(row.getPriceRuleJson()).get("finalPrice"));
}
private Integer stockTotalOf(JdPublishItemEntity row) {
Object total = readJson(row.getStockJson()).get("total");
return total instanceof Number number ? number.intValue() : null;
}
private Map<String, Object> readJson(String value) {
if (value == null || value.isBlank()) {
return Map.of();
}
try {
return objectMapper.readValue(value,
objectMapper.getTypeFactory().constructMapType(LinkedHashMap.class, String.class, Object.class));
} catch (Exception ex) {
log.warn("[jd-publish] 快照 JSON 解析失败,按空快照下发 err={}", ex.getMessage());
return Map.of();
}
}
private BigDecimal decimalOf(Object value) {
return value instanceof Number number ? BigDecimal.valueOf(number.doubleValue()) : null;
}
/** SKU 矩阵按 sortNo 升序下发,价按改价规则从 SKU 源价折算(与主档价同一规则同一函数)。 */
private List<JdPublishItemPayloadVo.SkuVo> loadSkuPayloads(Long productId, PriceRule rule) {
List<JdProductSkuEntity> skus = jdProductSkuMapper.selectList(
new LambdaQueryWrapper<JdProductSkuEntity>()
.eq(JdProductSkuEntity::getProductId, productId)
.orderByAsc(JdProductSkuEntity::getSortNo, JdProductSkuEntity::getId));
return skus.stream().map(sku -> {
JdPublishItemPayloadVo.SkuVo vo = new JdPublishItemPayloadVo.SkuVo();
vo.setSkuId(sku.getSkuId());
vo.setSkuName(sku.getSkuName());
vo.setSourcePrice(sku.getPrice());
vo.setFinalPrice(finalPriceOf(sku.getPrice(), rule));
vo.setStock(sku.getStock());
vo.setSaleAttrsJson(sku.getSaleAttrsJson());
vo.setSortNo(sku.getSortNo());
return vo;
}).toList();
}
/** 指定档图片按 sortNo 升序发预签名 GET URL(objectKey 留档可重签)。 */
private List<JdPublishItemPayloadVo.ImageView> loadImagePayloads(Long productId, String imageType) {
List<JdProductImageEntity> images = jdProductImageMapper.selectList(
new LambdaQueryWrapper<JdProductImageEntity>()
.eq(JdProductImageEntity::getProductId, productId)
.eq(JdProductImageEntity::getImageType, imageType)
.orderByAsc(JdProductImageEntity::getSortNo, JdProductImageEntity::getId));
return images.stream().map(image -> {
JdPublishItemPayloadVo.ImageView view = new JdPublishItemPayloadVo.ImageView();
view.setObjectKey(image.getObjectKey());
view.setUrl(ossStorageService.presignObjectDownload(bucket, image.getObjectKey(),
IMAGE_PRESIGN_EXPIRY_SECONDS));
view.setAttrName(image.getAttrName());
view.setSortNo(image.getSortNo());
return view;
}).toList();
}
}
@@ -11,6 +11,7 @@ import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuCreateReques
import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuUpdateRequest;
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.AdminMenuPlatformScope;
import com.nanri.aiimage.modules.permission.model.entity.PermissionMenuEntity;
import com.nanri.aiimage.modules.permission.model.entity.UserColumnPermissionEntity;
import com.nanri.aiimage.modules.permission.model.vo.ImageVideoDataPermissionUserVo;
@@ -777,9 +778,23 @@ public class PermissionMenuService {
* <p>入口放开不等于逐页放开。现网 46 个普通账号持有后台菜单授权(只读实查 2026-10-06),若逐页门只看入口,它们顺手就能读到同公司的密钥页与扣次数的 ASIN 查询页——勾菜单的人本意是给一页,不是给全部。
* 判据与 {@link #hasAnyAdminMenu} 同一套(本公司树 + 直接授权递归展开),所以勾父分组
* 覆盖后代的语义在这里照样成立。</p>
*
* <p>2026-11-18 平台隔离:管理员角色链的「恒可进」收窄为「恒可进<b>本人平台侧</b>」——
* 非站点超管传入越侧 key 一律 403(见方法体平台门),下发树裁剪之外的第二道防线。</p>
*/
public void requireConsolePageAccess(AdminUserEntity operator, String denialMessage, String... columnKeys) {
if (operator == null || isAdmin(operator)) {
if (operator == null) {
return;
}
// 平台门(2026-11-18 用户口径「隔离下非站点超管只看自己平台侧」):与下发树裁剪同口径——
// 站点超管直通之外,其余角色(含公司超管/管理员,故须放在 isAdmin 直通之前)传入的页面
// key 必须归属自身 users.platform;双侧 key 两平台都放行,越侧直调一律 403。
if (!DeviceSessionPolicy.isSuperAdmin(operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())
&& columnKeys != null && columnKeys.length > 0
&& AdminMenuPlatformScope.hasCrossPlatformKey(List.of(columnKeys), operator.getPlatform())) {
throw new BusinessException(403, denialMessage);
}
if (isAdmin(operator)) {
return;
}
if (columnKeys != null && columnKeys.length > 0
@@ -13,7 +13,7 @@ import java.util.Locale;
* 只剩兜底窗口,不再决定执行方。
*
* <p>列可空,且**不回填**:空值按模块默认解释,外观专利/相似ASIN/京东店铺采集
* (v1.4 起)读作 {@link #LOCAL}、其余模块读作 {@link #ONLINE},与 V183 之前
* (v1.4 起)/京东商品上架(v1.5 起)读作 {@link #LOCAL}、其余模块读作 {@link #ONLINE},与 V183 之前
* {@code AIIMAGE_COLLECT_LOCAL_*} 的出厂值 {@code true} 逐字等价。未升级的客户端与
* 全部历史任务因此行为不变。京东采集只能在本机 Windows + 紫鸟窗口执行,不加进本清单
* 就会默认 ONLINE ⇒ 任务被推给无紫鸟的 Linux worker,永不执行(铁律 19 同形)。
@@ -29,7 +29,8 @@ public enum CollectChannel {
private static final List<String> LOCAL_DEFAULT_MODULES = List.of(
CollectRoutingProperties.MODULE_APPEARANCE_PATENT,
CollectRoutingProperties.MODULE_SIMILAR_ASIN,
CollectRoutingProperties.MODULE_JD_SHOP_COLLECT);
CollectRoutingProperties.MODULE_JD_SHOP_COLLECT,
CollectRoutingProperties.MODULE_JD_PUBLISH);
/**
* 未登记通道时读作 {@link #LOCAL} 的模块清单。
@@ -43,7 +43,10 @@ AIIMAGE_JD_COLLECT_IMAGE_MAX_PER_PRODUCT=200
AIIMAGE_JD_COLLECT_STALE_MINUTES=60
# SKU 矩阵单商品上限(V198 详情面):真机一个商品 12 行,超限截断并 WARN。
AIIMAGE_JD_SKU_MAX_PER_PRODUCT=200
# 京东采集的客户端兜底拉取白名单(v1.4 P0-1):默认值已含 JD_SHOP_COLLECT(见 application.yml)。
# 京东商品上架(v1.5):对应 application.yml 的 aiimage.jd: publish 段。
AIIMAGE_JD_PUBLISH_STALE_MINUTES=60
AIIMAGE_JD_PUBLISH_ITEMS_BATCH_SIZE=20
# 京东采集/上架的客户端兜底拉取白名单(v1.4 P0-1 / v1.5):默认值已含 JD_SHOP_COLLECT、JD_PUBLISH(见 application.yml)。
# ⚠ 只有真的要覆盖整个白名单时才设 AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES——env 变量存在即生效,
# 设成空串会把白名单清空(兜底拉取对 JD 形同关闭)。打开 AIIMAGE_CLIENT_TASK_PULL_ENABLED
# 前先确认客户端版本带兜底拉取线程。
@@ -177,6 +177,11 @@ aiimage:
# SKU 矩阵单商品上限(V198 详情面):真机一个商品 12 行,超限截断并 WARN,
# 防脏回传把整批撑爆。显式写在这里,不许只活在代码默认值里。
sku-max-per-product: ${AIIMAGE_JD_SKU_MAX_PER_PRODUCT:200}
# 京东商品上架(v1.5):发布是逐商品页面自动化,节奏比采集慢——判死窗口独立可调
# (按发布时长重估,蓝图 §3);items 下发批大小钳制在服务侧(上限 100)。
publish:
stale-minutes: ${AIIMAGE_JD_PUBLISH_STALE_MINUTES:60}
items-batch-size: ${AIIMAGE_JD_PUBLISH_ITEMS_BATCH_SIZE:20}
# 设备日志对象存储:主机B 独立 MinIO(与业务 OSS 隔离,日志只保留 7 天)。
# endpoint 未配置时日志上报/管理接口不可用(宁可失败也不静默落到业务桶)。
# 桶的 7 天过期规则由运维用 mc 配置(与 retention-days 口径一致)。
@@ -300,7 +305,7 @@ aiimage:
enabled: ${AIIMAGE_MODULE_CLEANUP_ENABLED:true}
cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *}
retention-days: ${AIIMAGE_MODULE_CLEANUP_RETENTION_DAYS:7}
module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND,PRODUCT_RISK_RESOLVE,PRICE_TRACK,SHOP_MATCH,PATROL_DELETE,QUERY_ASIN,WITHDRAW,APPEARANCE_PATENT,SIMILAR_ASIN,COLLECT_DATA,JD_SHOP_COLLECT}
module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND,PRODUCT_RISK_RESOLVE,PRICE_TRACK,SHOP_MATCH,PATROL_DELETE,QUERY_ASIN,WITHDRAW,APPEARANCE_PATENT,SIMILAR_ASIN,COLLECT_DATA,JD_SHOP_COLLECT,JD_PUBLISH}
# 以下为各业务表的保留期清理(2026-09-16 统一补齐):这些表此前只增不删,
# 或只有"读的时候顺手删一行"这类碰运气的清理。全部按天分批删除、带分布式锁单实例执行。
device-log:
@@ -405,7 +410,9 @@ aiimage:
# 2026-11-14 v1.4 加 JD_SHOP_COLLECT(P0-1):京东采集只能在本机客户端执行(紫鸟/京麦
# 登录态在桌面机),页面推送缺失时任务会永久停在 PENDING——兜底拉取是它的唯一出路;
# queuePayload 由 JdTaskPullSpiImpl 组装(type=jd-shop-collect-run,与客户端同值)。
module-types: ${AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES:SIMILAR_ASIN,COLLECT_DATA,JD_SHOP_COLLECT}
# 2026-11-17 v1.5 加 JD_PUBLISH:京麦登录态在用户桌面机 19899 Chrome profile,发布同样
# 只能由客户端执行;queuePayload 由 JdPublishTaskPullSpiImpl 组装(type=jd-product-publish-run)。
module-types: ${AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES:SIMILAR_ASIN,COLLECT_DATA,JD_SHOP_COLLECT,JD_PUBLISH}
min-pending-minutes: ${AIIMAGE_CLIENT_TASK_PULL_MIN_PENDING_MINUTES:5}
limit: ${AIIMAGE_CLIENT_TASK_PULL_LIMIT:5}
# 服务端内部认领(/api/internal/tasks/pull-pending,Linux 后台 worker 专用),
@@ -0,0 +1,47 @@
-- 迁移 V210:京东商品上架发布明细表 biz_jd_publish_item(v1.5 蓝图 docs/ITERATION_PLAN.md §3)。
-- =============================================================
-- 1. 号段协调(2026-11-17 当窗实核):V207=users_jd_publish_quota(5c7a310e)、
-- V208=drop_jd_category_manage_menu、V209=jd_app_menu 已按序占用(蓝图 Phase 0 登记的
-- V208 在飞件已转正),发布明细表取 V210;契约正则放宽到 V208~V229(JdPublishContractPendingTest)。
--
-- 2. 形状口径:每任务每商品一行(uk_task_product)——建单即按 biz_jd_product 快照落行
-- (商品库有 ageCleanup 清理语义,发布记录不随商品删除丢失溯源,蓝图 §3);行级状态机
-- PENDING → PUBLISHING → SUCCESS/FAILED 由客户端 chunk 回传逐行推进,服务端不预测
-- (行状态唯一写入口 = JdPublishIngestService,单客户端串行回传无并发竞争)。
-- 任务级行为复用 biz_file_task(module_type=JD_PUBLISH),本表只承载行级明细。
-- user_id 是任务 owner 投影(biz_file_task.user_id),company_id 物化归属分公司
-- (owner 用户的 users.company_id;读不出显式落 NULL 不回填默认,铁律 30)。
--
-- 3. 影响表与数据量:新表零存量行;行数 = 上架任务商品勾选数(单任务上限 500,建单口钳制)。
--
-- 4. 可重跑性:CREATE TABLE IF NOT EXISTS——中途失败重跑整条 no-op(V193/V198 先例)。
-- 应用侧:MigrationInventoryTest 自动清点;JdSchemaContractTest#V210 钉形状。
--
-- 5. 回滚(patch,不当期执行):
-- DROP TABLE biz_jd_publish_item;
-- DELETE FROM flyway_schema_history WHERE version='210';
-- =============================================================
CREATE TABLE IF NOT EXISTS `biz_jd_publish_item` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
`task_id` BIGINT NOT NULL COMMENT 'biz_file_task.id(module_type=JD_PUBLISH)',
`company_id` BIGINT NULL COMMENT '物化归属分公司(owner 的 users.company_id;读不出落 NULL 不回填,铁律 30)',
`user_id` BIGINT NOT NULL COMMENT '任务 owner uid(biz_file_task.user_id 投影)',
`product_id` BIGINT NOT NULL COMMENT '商品行 id(biz_jd_product.id)',
`product_code` VARCHAR(64) NULL COMMENT '京东商品编码快照',
`shop_name` VARCHAR(255) NULL COMMENT '来源店铺名快照',
`title` VARCHAR(600) NULL COMMENT '商品标题快照(京麦标题上限 60 字,留余量)',
`category_path` VARCHAR(512) NULL COMMENT '京麦类目路径快照(A > B > C)',
`price_rule_json` JSON NULL COMMENT '改价快照 {"mode":"none|percent|fixed","value":n,"sourcePrice":x,"finalPrice":y}(finalPrice=主档价按规则折算)',
`stock_json` JSON NULL COMMENT '库存快照 {"total":n}',
`publish_status` VARCHAR(32) NOT NULL DEFAULT 'PENDING' COMMENT '行级状态机:PENDING/PUBLISHING/SUCCESS/FAILED',
`publish_error` VARCHAR(1024) NULL COMMENT '行级失败真实原因(客户端回传原文,R6 单行失败隔离)',
`jd_ware_id` VARCHAR(64) NULL COMMENT '京麦发布成功回执的商品 id(wareId,AC-3 真机核对锚点)',
`main_image_object_key` VARCHAR(512) NULL COMMENT '主图 objectKey 快照(biz_jd_product_image MAIN 档 sortNo 最小行)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建单落行时刻',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近回传/复位时刻',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_task_product` (`task_id`, `product_id`),
KEY `idx_task_status` (`task_id`, `publish_status`),
KEY `idx_user_created` (`user_id`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='京东商品上架发布明细(v1.5,行级状态与快照,任务行在 biz_file_task)';
@@ -56,8 +56,11 @@
WHERE accessible_group_id IS NOT NULL
ORDER BY accessible_group_id ASC
</select>
<!-- platform 列(2026-11-17):JdCategoryScopeService.retainJdPlatformGroups 只认本投影读出的
platform,少了这列每行都是 null ⇒ 平台闸把全部分组(含 jd 档)判成非 jd 清空——
与下面 selectLedGroups 同病,投影契约由 ShopManageGroupScopeSqlTest 钉。 -->
<select id="selectAllGroups" resultType="com.nanri.aiimage.common.model.entity.ShopManageGroupEntity">
SELECT g.id AS id, g.group_name AS groupName, g.company_id AS companyId
SELECT g.id AS id, g.group_name AS groupName, g.company_id AS companyId, g.platform AS platform
FROM biz_shop_manage_group g
ORDER BY g.id ASC
</select>
@@ -81,7 +84,7 @@
AND COALESCE(g.created_by_id, g.user_id) IS NOT NULL
</select>
<select id="selectLedGroups" resultType="com.nanri.aiimage.common.model.entity.ShopManageGroupEntity">
SELECT g.id AS id, g.group_name AS groupName
SELECT g.id AS id, g.group_name AS groupName, g.platform AS platform
FROM biz_shop_manage_group g
WHERE g.created_by_id = #{operatorId} OR g.user_id = #{operatorId}
ORDER BY g.id ASC
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper">
<!-- 京东商品上架发布明细(V210,v1.5):SQL 全部落 XML(铁律 1)。
行级状态推进(chunk 回传)走 MyBatis-Plus 条件更新(Mapper 层),本文件只承载
分批下发与状态聚合两条读侧具名 SQL。 -->
<!-- 明细分批下发页(断点友好,铁律 20 SQL 侧下推):过滤谓词必须在 SQL 段——
按 task_id 等值 + publish_status='PENDING' + id > cursor 下推后 LIMIT,
不得把已取页拉回 Java 再 filter(先 limit 后过滤会饿死另一批,铁律 20 同形)。
状态谓词同时是断点真源:已回传行(SUCCESS/FAILED/PUBLISHING)天然不进下一页,
客户端断点重连 cursor 归零也不会重发已发布商品(AC-4 服务端半边)。 -->
<select id="selectPublishableItems" resultType="com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity">
SELECT *
FROM biz_jd_publish_item
WHERE task_id = #{taskId}
AND publish_status = 'PENDING'
AND id &gt; #{cursor}
ORDER BY id ASC
LIMIT #{limit}
</select>
<!-- 行级状态聚合(进度展示与 isEnd 终态汇总共用):按 publish_status 分组计数。
行数上界=该任务商品行数(建单口钳 500),无分页问题。 -->
<select id="countByPublishStatus" resultType="java.util.Map">
SELECT publish_status AS publishStatus, COUNT(*) AS cnt
FROM biz_jd_publish_item
WHERE task_id = #{taskId}
GROUP BY publish_status
</select>
</mapper>
@@ -59,9 +59,15 @@ class MigratedSqlEquivalenceTest {
// 补 g.company_id AS companyId(注解时代原文没有这列)——改动是有意的,按 selectTaskPage/V188
// 同款处理整行摘出、点名 NOT_MIGRATED;新形状由 47fc0e08 那单的守卫钉。该笔走 fast 档发版
// 没点本支,2026-11-17 京东分类管理发版窗 full 闸门抓到补记。
private static final int LEDGER_ROWS = 82;
// 60 → 59:摘出去那行是一条 select。(59 → 58:摘 ShopManageGroupMapper#selectAllGroups 同上。)
private static final int LEDGER_SELECTS = 58;
// 82 → 81:2026-11-17 京东分组作用域平台闸(retainJdPlatformGroups)上线当窗事故——
// selectAllGroups 与 selectLedGroups 都没补 g.platform AS platform 投影,每行 getPlatform()
// 恒 null ⇒ 平台闸把全部分组(含刚建的 jd 档)判成非 jd 清空(「建组建成功、京东侧永远
// 不显示」)。selectLedGroups 同批补列,按同款先例整行摘账本点名 NOT_MIGRATED;新形状由
// ShopManageGroupScopeSqlTest 两条投影钉。
private static final int LEDGER_ROWS = 81;
// 60 → 59:摘出去那行是一条 select。(59 → 58:摘 ShopManageGroupMapper#selectAllGroups 同上。
// 58 → 57:摘 ShopManageGroupMapper#selectLedGroups 同上(2026-11-17 platform 补列)。)
private static final int LEDGER_SELECTS = 57;
/** 全部 mapper XML 里的 select 总数:账本 60 + TaskImageCache 5 + AsinResultCache 1。 */
/** 66 → 67:会话容忍新增的 {@code AdminUserMapper#countLiveWorkFor} 也是一条 select。 */
// 67 → 78:keywordshare 模块新写 11 条 select,逐条登记进下方 NOT_MIGRATED。
@@ -100,7 +106,10 @@ class MigratedSqlEquivalenceTest {
// 该笔当时只点编译没跑整量、两处账本都漏记,2026-11-15 发版前整量抓到补记。
// 114 → 103:keywordshare 模块整体下线(Project-Slimming 第三轮:6.4 天访问日志零流量、
// 四树零引用、V165 已撤菜单),随删 11 条 select 与下方 NOT_MIGRATED 的 12 条点名。
private static final int XML_SELECT_TOTAL = 103;
// 103 → 105:2026-11-18 整量补记 v1.5 Phase 2(24272a91)JdPublishItemMapper 新写 2 条
// 只读 select(selectPublishableItems + countByPublishStatus),逐条点名进 NOT_MIGRATED
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。
private static final int XML_SELECT_TOTAL = 105;
/**
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
@@ -206,7 +215,19 @@ class MigratedSqlEquivalenceTest {
// g.company_id AS companyId:注解时代原文没有这列,等价性这支对撞即红。
// 有意改动按先例整行摘账本点名留痕(LEDGER_ROWS 83 → 82 / SELECTS 59 → 58);
// 该笔 fast 档发版漏记,2026-11-17 京东分类管理发版窗 full 闸门抓到补记。
"ShopManageGroupMapper#selectAllGroups");
"ShopManageGroupMapper#selectAllGroups",
// 2026-11-17 京东分组作用域平台闸给 selectLedGroups 补 g.platform AS platform:
// 注解时代原文没有这列(同批 selectAllGroups 也漏了 platform 投影,那已在
// 上面豁免),平台闸读不到平台档把全部组清空。按同款先例整行摘账本点名留痕
// (LEDGER_ROWS 82 → 81 / SELECTS 58 → 57);新形状由 ShopManageGroupScopeSqlTest 钉。
"ShopManageGroupMapper#selectLedGroups",
// 2026-11-18 整量补记:v1.5 Phase 2 京东商品上架(24272a91)JdPublishItemMapper
// 新写 2 条只读 select(selectPublishableItems 明细分批下发页 PENDING 谓词+id 游标、
// countByPublishStatus 行级状态聚合),从来没有注解原文可对撞,逐条点名留痕。
// 该笔点名 12 类 87 例没跑整量、两处账本漏记,2026-11-18 发版前整量抓到补记
//(XML_SELECT_TOTAL 103 → 105,SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。
"JdPublishItemMapper#selectPublishableItems",
"JdPublishItemMapper#countByPublishStatus");
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
private static final int LEDGER_COLUMNS = 5;
@@ -131,7 +131,11 @@ class SqlLayeringConventionTest {
// 164 → 147:keywordshare 模块整体下线(Project-Slimming 第三轮:6.4 天访问日志零流量、
// 四树零引用、V165 已撤菜单),4 份 XML 17 条语句(11 select + 4 insert + 1 delete)随删;
// 同轮 MigratedSqlEquivalenceTest.XML_SELECT_TOTAL 114 → 103、NOT_MIGRATED 摘掉 12 条点名。
private static final int XML_STATEMENT_TOTAL = 147;
// 147 → 149:2026-11-18 整量补记 v1.5 Phase 2(24272a91)京东商品上架在 JdPublishItemMapper
// 落 2 条只读 select(selectPublishableItems 明细分批下发页 + countByPublishStatus 行级聚合),
// 全部新写,非迁移语句;同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED
//(该文件 XML_SELECT_TOTAL 同轮 103 → 105)。
private static final int XML_STATEMENT_TOTAL = 149;
/**
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
@@ -39,7 +39,7 @@ class PageDefaultsLedgerTest {
/**
* 出站点台账:{@code 文件#参数 -> 该页当前默认值的具名出处}。
* 54 条,逐条对应一次真实翻页行为;加页要登记,改值要表态。
* 62 条,逐条对应一次真实翻页行为;加页要登记,改值要表态。
*/
private static final List<String> LEDGER = List.of(
"AdminUserController.java#page=FIRST_PAGE",
@@ -79,6 +79,12 @@ class PageDefaultsLedgerTest {
// 2026-11-15 京东任务面板改版(45d0989a):历史层 GET /api/jd-collect/history 的 limit 出站点
// (默认 50,服务端钳制 1..100;与 CollectDataController#limit 同常量同形状)
"JdCollectController.java#limit=DEFAULT_RESULT_LIMIT",
// v1.5 Phase 4(2026-11-18,917884aa):用户端「商品上架」读侧三出站点——
// products 选品分页(page/page_size 默认 JD_PRODUCTS_PAGE_SIZE,与后管只读页同常量)
// + history 任务历史 limit(默认 50,服务端钳制 1..100,同 DEFAULT_RESULT_LIMIT)
"JdPublishController.java#page=FIRST_PAGE",
"JdPublishController.java#page_size=JD_PRODUCTS_PAGE_SIZE",
"JdPublishController.java#limit=DEFAULT_RESULT_LIMIT",
"NotificationController.java#page=FIRST_PAGE",
"NotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
// (本批 /groups 端点:参数名与默认值和列表端点同,台账按出站点计数、不去重)
@@ -120,14 +126,17 @@ class PageDefaultsLedgerTest {
assertThat(constants)
.as("分页/条数出站点的具名默认值必须与台账一一对应"
+ "(58→60:v1.4 Phase 5 京东数据库后管只读页 AdminJdProductController 的"
+ "(59→62:v1.5 Phase 4 用户端「商品上架」读侧 JdPublishController "
+ "products 的 page/page_size 与 history 的 limit 三处出站点;"
+ "58→60:v1.4 Phase 5 京东数据库后管只读页 AdminJdProductController 的"
+ " page/page_size 两处出站点;60→59:2026-11-17 任务证据特性下线,"
+ " AdminTaskEvidenceController 两处出站点随控制器删除)")
.isEqualTo(LEDGER.stream().sorted().toList());
// 同口径非零对照:台账不是空的,扫描器也确实数得出 59 处
// 同口径非零对照:台账不是空的,扫描器也确实数得出 62 处
// (61 而不是 60:2026-11-15 京东任务面板改版(45d0989a)新增 GET /api/jd-collect/history
// 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处)
assertThat(constants).hasSize(59);
// 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处;
// 59→62:v1.5 Phase 4 用户端「商品上架」读侧三出站点随 917884aa 登记同窗)
assertThat(constants).hasSize(62);
}
@Test
@@ -142,9 +151,10 @@ class PageDefaultsLedgerTest {
void oneSemanticCannotGrowASecondDefault() {
List<String> actual = sites();
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;"
.as("页码口径只有一套:全部从 1 起(26→27:v1.5 Phase 4 用户端「商品上架」products 选品分页也是分页出站点;"
+ "26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;"
+ "27→26:2026-11-17 任务证据特性下线随删一处)")
.isEqualTo(26);
.isEqualTo(27);
assertThat(distinctConstants(actual, "page_size"))
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
@@ -23,7 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* NullPointerException。平台超管是唯一走这条投影的档位,所以只有超管整页炸,非超管一切正常,
* mock 掉 mapper 的单元用例也全都绿。
*
* <p>判据:投影里少了 {@code company_id},本格直接红——那条查询是「组归属公司」的唯一来源。
* <p>2026-11-17 同一条查询再缺一次列:平台闸({@code retainJdPlatformGroups})上线时
* {@code selectAllGroups}/{@code selectLedGroups} 都没补 {@code platform} 投影,每行
* {@code getPlatform()} 都是 {@code null} ⇒ 平台闸把<b>全部分组(含刚建的 jd 档)判成非 jd
* 清空</b>——平台超管在京东侧永远空作用域、空态直建口永远在、建完的组永远不显示
* (「建组建成功、界面永远不显示」的生产实录)。两条投影的判据一并钉进本格:
* 少 {@code company_id} 或少 {@code platform} 都直接红。
*/
class ShopManageGroupScopeSqlTest {
@@ -31,13 +36,25 @@ class ShopManageGroupScopeSqlTest {
private static final String NS = "com.nanri.aiimage.common.mapper.ShopManageGroupMapper";
@Test
void 平台超管的组清单必须投影归属公司() throws Exception {
void 平台超管的组清单必须投影归属公司与平台档() throws Exception {
String sql = render("selectAllGroups");
assertEquals("SELECT g.id AS id, g.group_name AS groupName, g.company_id AS companyId"
+ " FROM biz_shop_manage_group g ORDER BY g.id ASC", sql,
"投影变了:少了 company_id 就是 2026-11-16 那次线上 500(公司名映射为空、"
+ "组标签前缀失效);多了列则要把 assemble 的跨公司前缀判据一起复核");
assertEquals("SELECT g.id AS id, g.group_name AS groupName, g.company_id AS companyId,"
+ " g.platform AS platform FROM biz_shop_manage_group g ORDER BY g.id ASC", sql,
"投影变了:少 company_id 就是 2026-11-16 那次线上 500(公司名映射为空、"
+ "组标签前缀失效);少 platform 就是 2026-11-17 那次平台闸清空全部分组"
+ "(jd 档组建了也不显示);多了列则要把 assemble 的跨公司前缀判据一起复核");
}
@Test
void 管理员档的组清单必须投影平台档() throws Exception {
String sql = render("selectLedGroups");
assertEquals("SELECT g.id AS id, g.group_name AS groupName, g.platform AS platform"
+ " FROM biz_shop_manage_group g WHERE g.created_by_id = ? OR g.user_id = ?"
+ " ORDER BY g.id ASC", sql,
"组长/普通号档走这条投影过平台闸:少 platform 则 jd 档组对非超管永远不可见"
+ "(与 selectAllGroups 同一批病灶,2026-11-17 实录)");
}
private static String render(String id) throws Exception {
@@ -107,7 +107,17 @@ class RequestSuppliedIdentityOutletTest {
// POST /api/jd-collect/tasks/progress/batch(批量进度:request.userId 先过 requireOwnershipUserId
// 再 filterOwnedTaskIds 过滤归属)+ DELETE /api/jd-collect/tasks/{taskId}(@RequestParam("user_id")
// 先过 resolveOwnershipUserId,删除任务行连带 jd 三表)——覆盖面变大,不是放宽分母。
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(133);
// 136 而不是 133:2026-11-18 v1.5 Phase 2 京东商品上架(24272a91)新增三支写类端点——
// POST /api/jd-publish/tasks(建单:JdPublishTaskCreateRequest 带 userId DTO 形,先过
// requireOwnershipUserId fail-closed、请求体自带值不采信)+ POST /api/jd-publish/tasks/{taskId}/activate
// + POST /api/jd-publish/tasks/{taskId}/heartbeat(都是 @RequestParam("user_id") 先过
// requireOwnershipUserId);chunk 回传不走身份出口(判死口凭据化 isTrustedInternalToken,
// JdPublishChunkRequest 不带 userId 字段),不计入——覆盖面变大,不是放宽分母。
// 138 而不是 136:2026-11-18 v1.5 Phase 4 京东上架用户端读侧新增两支写类端点——
// POST /api/jd-publish/tasks/progress/batch(request.userId 先过 requireOwnershipUserId 再
// filterOwnedTaskIds 过滤归属)+ DELETE /api/jd-publish/tasks/{taskId}(@RequestParam("user_id")
// 先过 resolveOwnershipUserId,删除任务行连带发布明细快照行)——覆盖面变大,不是放宽分母。
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(138);
// 64 而不是 63:2026-10-29 随本地采集开关恢复 GET /tasks/{taskId}/queue-payload,
// 该 handler 同时接上 resolveOwnershipUserId(不是放宽分母)。
// 65 而不是 64:2026-11-14 v1.4 新增 JdCollectController GET /api/jd-collect/tasks/{taskId}/progress
@@ -116,7 +126,14 @@ class RequestSuppliedIdentityOutletTest {
// 67 而不是 65:2026-11-15 京东任务面板改版(45d0989a)新增两支读类端点——
// GET /api/jd-collect/dashboard(统计卡)+ GET /api/jd-collect/history(历史层,limit 钳制 1..100),
// 都是 @RequestParam("user_id") 先过 resolveOwnershipUserId——覆盖面变大,不是放宽分母。
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(67);
// 69 而不是 67:2026-11-18 v1.5 Phase 2 新增两支读类端点——GET /api/jd-publish/tasks/{taskId}/items
// + GET /api/jd-publish/tasks/{taskId}/progress,都是 @RequestParam("user_id") 先过
// requireOwnershipUserId——覆盖面变大,不是放宽分母。
// 72 而不是 69:2026-11-18 v1.5 Phase 4 京东上架用户端读侧新增三支读类端点——
// 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);
assertThat(scan.unbound()).as("取请求身份但未接出口的 handler:只剩豁免那一条")
.containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET);
}
@@ -0,0 +1,178 @@
package com.nanri.aiimage.common.service;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 菜单 key → 平台归属唯一出处(2026-11-18 用户口径「隔离下除站点超管外,京东用户只看京东
* 菜单、亚马逊看不了」)。三份清单必须与 admin-frontend-vue {@code src/config/platform-scope.ts}
* 逐字同值:{@code JD_MENU_KEYS} / {@code JD_APP_MENU_KEYS} / {@code BOTH_PLATFORM_MENU_KEYS}。
* 把任一清单改回旧形状(双侧少三页、京东缺 key)、把「未知 key 默认亚马逊」改掉、或把
* 平台裁剪挂回 {@code PermissionMenuService.getUserColumnPermissions} 本体(授权编辑读接口
* 会被误裁,整树替换保存即丢授权行)都必须变红。
*/
class AdminMenuPlatformScopeTest {
// ------------------------------------------------------------ 清单字面量
@Test
@DisplayName("京东独占(后台)清单逐字:admin_jd_database")
void jdAdminMenuKeysArePinnedVerbatim() {
assertThat(AdminMenuPlatformScope.JD_MENU_KEYS).containsExactly("admin_jd_database");
}
@Test
@DisplayName("桌面端京东清单逐字:jd_tools 组行 + jd-collect / jd-publish")
void jdAppMenuKeysArePinnedVerbatim() {
assertThat(AdminMenuPlatformScope.JD_APP_MENU_KEYS)
.containsExactlyInAnyOrder("jd_tools", "jd-collect", "jd-publish");
}
@Test
@DisplayName("双侧清单逐字:用户、分组、公司与菜单权限配置;密钥相关页面仅亚马逊")
void bothPlatformMenuKeysArePinnedVerbatim() {
assertThat(AdminMenuPlatformScope.BOTH_MENU_KEYS).containsExactlyInAnyOrder(
"admin_users", "admin_group_manage", "admin_companies",
"admin_columns");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("admin_user_secrets")).containsExactly("amazon");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("admin_user_secret_usage")).containsExactly("amazon");
}
// ------------------------------------------------------------ key 归属判定
@Test
@DisplayName("key 归属判定:京东清单 → jd;双侧 → 双平台;未知/缺省 → amazon")
void platformsOfMenuKeyFollowsTheThreeLists() {
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("admin_jd_database")).containsExactly("jd");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("jd_tools")).containsExactly("jd");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("admin_users"))
.containsExactlyInAnyOrder("amazon", "jd");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("admin_columns"))
.containsExactlyInAnyOrder("amazon", "jd");
// 未知 key 与缺省 key 一律默认亚马逊——与前端 platformsOfMenuKey(node.key || '') 同形
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("admin_brand_gating")).containsExactly("amazon");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey(null)).containsExactly("amazon");
assertThat(AdminMenuPlatformScope.platformsOfMenuKey("")).containsExactly("amazon");
}
@Test
@DisplayName("平台归一:null/空白按 amazon(列 DEFAULT 同口径),不得把「没带」读成京东侧全拦")
void nullPlatformNormalizesToAmazon() {
assertThat(AdminMenuPlatformScope.normalize(null)).isEqualTo("amazon");
assertThat(AdminMenuPlatformScope.normalize(" ")).isEqualTo("amazon");
assertThat(AdminMenuPlatformScope.normalize("jd")).isEqualTo("jd");
}
// ------------------------------------------------------------ 逐页门越侧判定
@Test
@DisplayName("越侧判定:jd 用户传亚马逊 key 判越侧;amazon 用户传亚马逊 key 不判")
void crossPlatformKeyFollowsOperatorPlatform() {
assertThat(AdminMenuPlatformScope.hasCrossPlatformKey(
List.of("admin_shop_manage", "admin_query_asin"), "jd")).isTrue();
assertThat(AdminMenuPlatformScope.hasCrossPlatformKey(
List.of("admin_shop_manage"), "amazon")).isFalse();
// 双侧 key 与京东 key 对 jd 用户都放行
assertThat(AdminMenuPlatformScope.hasCrossPlatformKey(
List.of("admin_jd_database", "admin_users"), "jd")).isFalse();
// null 平台按 amazon:亚马逊 key 不越侧
assertThat(AdminMenuPlatformScope.hasCrossPlatformKey(
List.of("admin_shop_manage"), (String) null)).isFalse();
}
// ------------------------------------------------------------ 扁平 VO 过滤
@Test
@DisplayName("jd 平台过滤:京东叶子+双侧叶子保留,亚马逊叶子与无存活子项的分组裁掉")
void jdPlatformKeepsJdAndBothLeavesWithAncestorChain() {
List<PermissionMenuItemVo> menus = List.of(
vo(1L, "group-account", null), // 账号与权限分组(双侧叶子挂它下面)
vo(2L, "admin_users", 1L), // 双侧叶子
vo(3L, "admin_columns", 1L), // 双侧叶子(2026-11-18 补双侧)
vo(4L, "group-brand", null), // 亚马逊侧分组(子叶全亚马逊 → 整组裁掉)
vo(5L, "admin_brand_gating", 4L), // 亚马逊叶子
vo(6L, "admin_jd_database", null), // 京东叶子(根级)
vo(7L, "group-unknown", null), // 只挂未知 key 的分组
vo(8L, "admin_unknown_menu", 7L)); // 未知 key 默认亚马逊 → group-unknown 整组裁掉
List<PermissionMenuItemVo> kept = AdminMenuPlatformScope.filterMenuVosByPlatform(menus, "jd");
assertThat(ids(kept)).containsExactlyInAnyOrder(1L, 2L, 3L, 6L);
}
@Test
@DisplayName("amazon 平台过滤:亚马逊叶子+双侧叶子保留,京东叶子裁掉")
void amazonPlatformKeepsAmazonAndBothLeaves() {
List<PermissionMenuItemVo> menus = List.of(
vo(1L, "group-account", null),
vo(2L, "admin_users", 1L),
vo(5L, "admin_brand_gating", null),
vo(6L, "admin_jd_database", null));
List<PermissionMenuItemVo> kept = AdminMenuPlatformScope.filterMenuVosByPlatform(menus, "amazon");
assertThat(ids(kept)).containsExactlyInAnyOrder(1L, 2L, 5L);
}
@Test
@DisplayName("过滤保留祖先链:京东叶子挂亚马逊分组下时,分组随存活子项保留")
void ancestorChainSurvivesForKeptLeafUnderMixedGroup() {
List<PermissionMenuItemVo> menus = List.of(
vo(1L, "group-mixed", null),
vo(5L, "admin_brand_gating", 1L),
vo(6L, "admin_jd_database", 1L));
List<PermissionMenuItemVo> kept = AdminMenuPlatformScope.filterMenuVosByPlatform(menus, "jd");
// 叶子 6 存活 → 分组 1 必须保留(否则 AdminMenuTreeBuilder.build 组树丢父)
assertThat(ids(kept)).containsExactlyInAnyOrder(1L, 6L);
}
@Test
@DisplayName("null 平台按 amazon 过滤;null/空输入回空列表;入参不被修改")
void nullPlatformFiltersAsAmazonAndInputsUntouched() {
List<PermissionMenuItemVo> menus = List.of(
vo(5L, "admin_brand_gating", null),
vo(6L, "admin_jd_database", null));
List<PermissionMenuItemVo> kept = AdminMenuPlatformScope.filterMenuVosByPlatform(menus, null);
assertThat(ids(kept)).containsExactly(5L);
assertThat(AdminMenuPlatformScope.filterMenuVosByPlatform(null, "jd")).isEmpty();
assertThat(AdminMenuPlatformScope.filterMenuVosByPlatform(List.of(), "jd")).isEmpty();
}
@Test
@DisplayName("全被裁光时回空列表(下游组树即空,前端该侧无可点页面)")
void fullyFilteredPlatformReturnsEmptyList() {
List<PermissionMenuItemVo> menus = List.of(
vo(5L, "admin_brand_gating", null),
vo(6L, "admin_jd_database", null));
// amazon 平台下把京东叶子也喂进过滤场景不存在(下发树按用户授权来),
// 这里钉纯函数语义:没有任何存活叶子的输入回空。
List<PermissionMenuItemVo> jdOnly = List.of(vo(6L, "admin_jd_database", null));
assertThat(ids(AdminMenuPlatformScope.filterMenuVosByPlatform(jdOnly, "amazon"))).isEmpty();
assertThat(menus).hasSize(2);
}
private List<Long> ids(List<PermissionMenuItemVo> menus) {
return menus.stream().map(PermissionMenuItemVo::getId).toList();
}
private PermissionMenuItemVo vo(Long id, String columnKey, Long parentId) {
PermissionMenuItemVo item = new PermissionMenuItemVo();
item.setId(id);
item.setColumnKey(columnKey);
item.setName(columnKey);
item.setParentId(parentId);
item.setMenuType("admin");
return item;
}
}
@@ -128,4 +128,23 @@ class AdminConsoleCurrentUserCompanyTest {
.containsEntry("expiresAt", null)
.containsEntry("daysToExpire", null);
}
/**
* 平台隔离(2026-11-18 用户口径):前端 {@code allowedPlatformsForUser} 直接读
* {@code session.user.platform} 把平台 tab 锁到本人一侧,没有映射层——键名拼错的表现是
* 「京东用户照样切到亚马逊 tab」(值 undefined 走 'amazon' 兜底),只能由用例盯着。
*/
@Test
@DisplayName("current-user 带 platform 键(V206 字面量 amazon|jd 原样透传)")
void currentUserCarriesPlatformKeyVerbatim() {
operator.setPlatform("jd");
assertThat(item()).containsEntry("platform", "jd");
operator.setPlatform("amazon");
assertThat(item()).containsEntry("platform", "amazon");
operator.setPlatform(null);
assertThat(item()).containsEntry("platform", null);
}
}
@@ -0,0 +1,144 @@
package com.nanri.aiimage.modules.admin.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* {@code GET /api/admin/current-user/menus} 的平台裁剪(2026-11-18 用户口径「隔离下除站点
* 超管外,京东用户只看京东菜单、亚马逊看不了」):非站点超管按 users.platform 收窄下发树
* ——jd 用户只留京东叶子与双侧账号域叶子(及其祖先分组),亚马逊业务页不再下发,前端
* 路由守卫随树拦截直达 URL。把裁剪挪走(非超管重新下发全量)或挪进
* {@code PermissionMenuService.getUserColumnPermissions} 本体(授权编辑读接口被误裁)都即红。
*/
class AdminConsoleCurrentUserMenusPlatformTest {
private AdminAuthSupport adminAuthSupport;
private PermissionMenuService permissionMenuService;
private AdminConsoleController controller;
private HttpServletRequest request;
private AdminUserEntity operator;
@BeforeEach
void setUp() {
adminAuthSupport = mock(AdminAuthSupport.class);
permissionMenuService = mock(PermissionMenuService.class);
controller = new AdminConsoleController(adminAuthSupport, permissionMenuService,
mock(CompanyService.class));
request = mock(HttpServletRequest.class);
operator = new AdminUserEntity();
operator.setId(10L);
operator.setCompanyId(5L);
when(adminAuthSupport.requireConsoleOperatorOrInternal(request)).thenReturn(operator);
when(permissionMenuService.getUserColumnPermissions(any(), anyLong(), eq("admin"), eq(true)))
.thenReturn(fullCatalog());
when(permissionMenuService.getUserColumnPermissions(any(), anyLong(), eq("admin"), eq(false)))
.thenReturn(fullCatalog());
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> items() {
ApiResponse<Map<String, Object>> response = controller.currentUserMenus(request);
return (List<Map<String, Object>>) response.getData().get("items");
}
/** 扁平 VO 收集整棵响应树里出现过的 key(含分组)。 */
private void collectKeys(List<Map<String, Object>> nodes, List<String> out) {
for (Map<String, Object> node : nodes) {
out.add((String) node.get("key"));
Object children = node.get("children");
if (children instanceof List<?> list) {
@SuppressWarnings("unchecked")
List<Map<String, Object>> subs = (List<Map<String, Object>>) (List<?>) list;
collectKeys(subs, out);
}
}
}
@Test
@DisplayName("jd 公司超管:下发树无亚马逊叶子,京东叶子与双侧账号域照发(含祖先分组)")
void jdOperatorGetsJdAndBothMenusOnly() {
operator.setRole("company_super_admin");
operator.setIsAdmin(1);
operator.setPlatform("jd");
List<String> keys = new java.util.ArrayList<>();
collectKeys(items(), keys);
assertThat(keys).contains("admin_jd_database", "admin_users", "admin_group_manage", "admin_columns");
assertThat(keys).doesNotContain("admin_brand_gating", "admin_query_asin",
"admin_user_secrets", "admin_user_secret_usage");
assertThat(keys).contains("group-account");
}
@Test
@DisplayName("amazon 存量用户(platform=null 按 amazon 兜底):亚马逊叶子照发,京东叶子裁掉")
void amazonOperatorKeepsAmazonMenus() {
operator.setRole("admin");
operator.setIsAdmin(1);
operator.setPlatform(null);
List<String> keys = new java.util.ArrayList<>();
collectKeys(items(), keys);
assertThat(keys).contains("admin_brand_gating", "admin_users");
assertThat(keys).doesNotContain("admin_jd_database");
}
@Test
@DisplayName("站点超管:不裁剪,双平台全量原样下发")
void superAdminGetsEverything() {
operator.setRole("super_admin");
operator.setIsAdmin(1);
operator.setPlatform("jd");
List<String> keys = new java.util.ArrayList<>();
collectKeys(items(), keys);
assertThat(keys).contains("admin_jd_database", "admin_brand_gating", "admin_query_asin",
"admin_users");
}
/** 夹具:分组 + 亚马逊两页 + 京东一页 + 双侧账号域全份(含 2026-11-18 补双侧的三页)。 */
private List<PermissionMenuItemVo> fullCatalog() {
return List.of(
vo(100L, "group-account", null),
vo(101L, "admin_users", 100L),
vo(102L, "admin_group_manage", 100L),
vo(103L, "admin_columns", 100L),
vo(104L, "admin_user_secrets", 100L),
vo(105L, "admin_user_secret_usage", 100L),
vo(106L, "group-brand", null),
vo(107L, "admin_brand_gating", 106L),
vo(108L, "admin_query_asin", null),
vo(109L, "admin_jd_database", null));
}
private PermissionMenuItemVo vo(Long id, String columnKey, Long parentId) {
PermissionMenuItemVo item = new PermissionMenuItemVo();
item.setId(id);
item.setColumnKey(columnKey);
item.setName(columnKey);
item.setParentId(parentId);
item.setMenuType("admin");
item.setSortOrder(id.intValue());
return item;
}
}
@@ -0,0 +1,170 @@
package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.common.security.JwtService;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 登录 VO 的平台裁剪(2026-11-18 用户口径「后管+桌面端一起」):非站点超管登录返回的
* adminColumns(后管菜单树)与 appColumns(桌面端工具菜单)按 users.platform 收窄——
* 京东用户的桌面端只见京东工具(jd_tools 组),亚马逊工具不再下发;站点超管双平台全量。
* 裁剪只挂登录下发出口,授权行不动;把它挪进 getUserColumnPermissions 本体(授权编辑读
* 接口被误裁)或去掉(登录响应重新带全量)都即红。
*/
class AuthServicePlatformMenuTest {
private LoginUserMapper loginUserMapper;
private PermissionMenuService permissionMenuService;
private AuthService service;
/** 惰性 answer 引用:login() 求值时才读,测试体里先设置再登录。 */
private LoginUserEntity currentUser;
@BeforeAll
static void initMybatisPlusTableInfo() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
LoginUserEntity.class);
}
@BeforeEach
void setUp() {
loginUserMapper = mock(LoginUserMapper.class);
WerkzeugPasswordEncoder passwordEncoder = mock(WerkzeugPasswordEncoder.class);
JwtService jwtService = mock(JwtService.class);
permissionMenuService = mock(PermissionMenuService.class);
AuthProperties authProperties = mock(AuthProperties.class);
when(authProperties.isSingleDeviceEnabled()).thenReturn(true);
when(jwtService.ttlSeconds()).thenReturn(604800L);
when(jwtService.issue(anyLong(), anyString(), anyString(), anyLong())).thenReturn("jwt-token");
when(loginUserMapper.selectOne(any())).thenAnswer(invocation -> currentUser);
when(passwordEncoder.matches("pwd", "hash")).thenReturn(true);
when(permissionMenuService.getUserColumnPermissions(anyLong(), eq("admin")))
.thenReturn(adminCatalog());
when(permissionMenuService.getUserColumnPermissions(anyLong(), eq("app")))
.thenReturn(appCatalog());
service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
permissionMenuService, authProperties, mock(CompanyService.class),
mock(AccountExpiryService.class));
}
private LoginResultVo login() {
LoginRequest request = new LoginRequest();
request.setUsername("u7");
request.setPassword("pwd");
request.setDeviceId("devA");
return service.login(request);
}
@Test
@DisplayName("jd 用户登录:adminColumns 只剩京东+双侧叶子,appColumns 只剩京东工具")
void jdUserLoginGetsJdSidedColumnsOnly() {
currentUser = user("company_super_admin", "jd");
LoginResultVo vo = login();
assertThat(vo.getAdminColumns())
.extracting(PermissionMenuItemVo::getColumnKey)
.contains("admin_jd_database", "admin_users", "admin_columns")
.doesNotContain("admin_brand_gating");
assertThat(vo.getAppColumns())
.extracting(PermissionMenuItemVo::getColumnKey)
.contains("jd_tools", "jd-collect", "jd-publish")
.doesNotContain("pricing", "query-asin", "wb");
}
@Test
@DisplayName("amazon 存量用户(platform=null 兜底):亚马逊列照发,京东列裁掉")
void amazonUserLoginKeepsAmazonColumns() {
currentUser = user("admin", null);
LoginResultVo vo = login();
assertThat(vo.getAdminColumns())
.extracting(PermissionMenuItemVo::getColumnKey)
.contains("admin_brand_gating", "admin_users")
.doesNotContain("admin_jd_database");
assertThat(vo.getAppColumns())
.extracting(PermissionMenuItemVo::getColumnKey)
.contains("pricing", "query-asin")
.doesNotContain("jd_tools");
}
@Test
@DisplayName("站点超管登录:双平台全量,不裁剪")
void superAdminLoginGetsEverything() {
currentUser = user("super_admin", "jd");
LoginResultVo vo = login();
assertThat(vo.getAdminColumns()).extracting(PermissionMenuItemVo::getColumnKey)
.contains("admin_jd_database", "admin_brand_gating");
assertThat(vo.getAppColumns()).extracting(PermissionMenuItemVo::getColumnKey)
.contains("jd_tools", "pricing");
}
private LoginUserEntity user(String role, String platform) {
LoginUserEntity user = new LoginUserEntity();
user.setId(7L);
user.setUsername("u7");
user.setPasswordHash("hash");
user.setIsAdmin("super_admin".equals(role) || "admin".equals(role)
|| "company_super_admin".equals(role) ? 1 : 0);
user.setRole(role);
user.setPlatform(platform);
user.setMachine("devA");
return user;
}
private List<PermissionMenuItemVo> adminCatalog() {
return List.of(
vo(101L, "admin_users", null, "admin"),
vo(102L, "admin_columns", null, "admin"),
vo(107L, "admin_brand_gating", null, "admin"),
vo(109L, "admin_jd_database", null, "admin"));
}
private List<PermissionMenuItemVo> appCatalog() {
return List.of(
vo(201L, "jd_tools", null, "app"),
vo(202L, "jd-collect", 201L, "app"),
vo(203L, "jd-publish", 201L, "app"),
vo(210L, "pricing", null, "app"),
vo(211L, "query-asin", null, "app"),
vo(212L, "wb", null, "app"));
}
private PermissionMenuItemVo vo(Long id, String columnKey, Long parentId, String menuType) {
PermissionMenuItemVo item = new PermissionMenuItemVo();
item.setId(id);
item.setColumnKey(columnKey);
item.setName(columnKey);
item.setParentId(parentId);
item.setMenuType(menuType);
item.setSortOrder(id.intValue());
return item;
}
}
@@ -44,7 +44,7 @@ class TaskModuleCoverageTest {
"PUBLISH", "DEDUPE", "SPLIT", "CONVERT", "DELETE_BRAND", "PRODUCT_RISK_RESOLVE",
"PRICE_TRACK", "SHOP_MATCH", "PATROL_DELETE", "QUERY_ASIN", "WITHDRAW",
"APPEARANCE_PATENT", "SIMILAR_ASIN", "COLLECT_DATA", "SHOP_DATA_CRAWL", "BRAND",
"JD_SHOP_COLLECT");
"JD_SHOP_COLLECT", "JD_PUBLISH");
@Test
void registryCoversEveryKnownModuleWithLabel() {
@@ -27,13 +27,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*/
class JdCollectChannelGoldenTest {
/** Phase 1 起注册表 17 个模块且含京东:再增删模块必须同轮更新本清单。 */
/** Phase 1 起注册表 17 个模块且含京东;Phase 2(v1.5)加 JD_PUBLISH 后 18 个:再增删模块必须同轮更新本清单。 */
@Test
void 京东模块已注册进任务模块注册表() {
Set<String> types = TaskModuleRegistry.moduleTypes();
assertEquals(17, types.size(), "再增删模块时同轮更新本数(Phase 1 定格 17)");
assertEquals(18, types.size(), "再增删模块时同轮更新本数(Phase 1 定格 17,v1.5 Phase 2 定格 18)");
assertTrue(types.containsAll(List.of("APPEARANCE_PATENT", "SIMILAR_ASIN", "SHOP_DATA_CRAWL",
"COLLECT_DATA", "PRICE_TRACK", "PUBLISH", "BRAND", "JD_SHOP_COLLECT")), "既有清单形状漂移,先查别人改动");
"COLLECT_DATA", "PRICE_TRACK", "PUBLISH", "BRAND", "JD_SHOP_COLLECT", "JD_PUBLISH")),
"既有清单形状漂移,先查别人改动");
}
/** 京东模块默认 LOCAL(紫鸟只在本机):谁把它翻回 ONLINE 这里先红。 */
@@ -2,7 +2,6 @@ package com.nanri.aiimage.modules.jd;
import com.nanri.aiimage.modules.task.model.CollectChannel;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -18,12 +17,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* v1.5 京东商品上架到京麦(Phase 0 预置的验收契约,蓝图 docs/ITERATION_PLAN.md §1 AC / §4)。
*
* <p><b>Pending-to-Active 机制</b>:标 {@code @Disabled("Pending Phase 2")} 的方法是 Phase 2
* (后端地基:V208+ 迁移 / JdPublishController / JdPublishTaskService / 派发三件套)落地后才
* 能跑绿的契约,实现合入的同一个 Phase 里必须移除注解跑绿——蓝图对应 Phase 的【待激活验收
* 测试】栏登记了这份清单。唯一不 skip 的方法 {@link #京东分类读取口全仓唯一_B11301绊线()} 是
* <b>立即生效</b>的存量绊线:B113-01 拍板「分类选项唯一来源 GET /api/jd-collect/groups」,
* 任何面(含本迭代新增的发布面)都不许开第二个京东分类读取口。
* <p><b>Pending-to-Active 机制</b>:Phase 0 预置时标 {@code @Disabled("Pending Phase 2")} 的
* 7 支已在 Phase 2(后端地基:V210 迁移 / JdPublishController / JdPublishTaskService /
* 派发三件套)落地时移除注解正式激活(蓝图 Phase 2【待激活验收测试】清单)。
* {@link #京东分类读取口全仓唯一_B11301绊线()} 是<b>立即生效</b>的存量绊线:B113-01 拍板
* 「分类选项唯一来源 GET /api/jd-collect/groups」,任何面(含本迭代新增的发布面)都不许开
* 第二个京东分类读取口。
*
* <p>Pending 方法全部写成<b>源码绊线</b>(读源文件断言关键形状),不 import 尚不存在的新类,
* Phase 0 落盘即可编译;判据形状照 {@code JdTaskPullSpiImplTest}(白名单段绊线)与
@@ -75,7 +74,6 @@ class JdPublishContractPendingTest {
// ---------------------------------------------------------------- AC-2(Pending Phase 2:派发三件套)
@Test
@Disabled("Pending Phase 2: AC-2 派发三件套——client-task-pull 白名单加 JD_PUBLISH 后移除本注解")
void client_task_pull白名单默认值含JD_PUBLISH_源码绊线() throws IOException {
// 照 JdTaskPullSpiImplTest 同判据:白名单不含模块名时 SPI 装载了也不会被走到。
// 逐行定位 AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES 那一行再断言,比全文 contains 精确。
@@ -88,7 +86,6 @@ class JdPublishContractPendingTest {
}
@Test
@Disabled("Pending Phase 2: AC-2 LOCAL_DEFAULT_MODULES——JD_PUBLISH 进清单后移除本注解")
void JD_PUBLISH默认通道必须是LOCAL_铁律19同形() {
// 京东发布必须由客户端已登录京麦的 Chrome 执行,Linux worker 永远跑不了:
// 不进 LOCAL_DEFAULT_MODULES 就会默认 ONLINE ⇒ 任务被推给无京麦登录态的机器(铁律 19)。
@@ -98,7 +95,6 @@ class JdPublishContractPendingTest {
}
@Test
@Disabled("Pending Phase 2: AC-2 SPI 实现——JdPublishTaskPullSpiImpl 落地后移除本注解")
void 派发SPI实现存在且队列类型为jd_product_publish_run() throws IOException {
assertTrue(Files.exists(PUBLISH_SPI), "缺 ClientTaskPullSpi 实现:JdPublishTaskPullSpiImpl(铁律 32 第一件)");
assertTrue(Files.readString(PUBLISH_SPI).contains(PUBLISH_QUEUE_TYPE),
@@ -110,7 +106,6 @@ class JdPublishContractPendingTest {
}
@Test
@Disabled("Pending Phase 2: AC-2 registry 登记——TaskModuleRegistry 加 JD_PUBLISH 后移除本注解")
void TaskModuleRegistry登记JD_PUBLISH模块_源码绊线() throws IOException {
assertTrue(Files.exists(MODULE_REGISTRY), "TaskModuleRegistry 缺失");
assertTrue(Files.readString(MODULE_REGISTRY).contains(PUBLISH_MODULE),
@@ -120,11 +115,12 @@ class JdPublishContractPendingTest {
// ---------------------------------------------------------------- AC-1(Pending Phase 2:建单端点)
@Test
@Disabled("Pending Phase 2: AC-1 建单端点——JdPublishController 落地后移除本注解")
void 建单端点形状与归属校验_源码绊线() throws IOException {
assertTrue(Files.exists(PUBLISH_CONTROLLER), "缺 JdPublishController(蓝图 §3:POST /api/jd-publish/tasks)");
String source = Files.readString(PUBLISH_CONTROLLER);
assertTrue(source.contains("jd-publish/tasks"), "缺建单端点路径 /api/jd-publish/tasks");
// 类级 @RequestMapping 与方法级 @PostMapping 分开写,拼接串搜不到(照 AC-9 格同一口径)。
assertTrue(source.contains("/api/jd-publish"), "缺类级 @RequestMapping /api/jd-publish");
assertTrue(source.contains("@PostMapping(\"/tasks\")"), "缺建单端点 POST /tasks");
assertTrue(source.contains("@PostMapping"), "建单必须是 POST 端点");
// AC-9 归属半边:选了他人商品要业务码拒绝(照 JdCollectController 的 fail-closed 鉴权形状)
assertTrue(source.contains("requireOwnershipUserId"),
@@ -132,7 +128,6 @@ class JdPublishContractPendingTest {
}
@Test
@Disabled("Pending Phase 2: AC-1 发布明细表——V208+ 迁移落地后移除本注解")
void 发布明细表迁移存在且表名为biz_jd_publish_item() throws IOException {
// 蓝图 §3:V207 已被 users_jd_publish_quota 占用(5c7a310e),发布明细表从 V208 起号。
// 号段断言放宽到 V208~V229:开工时仍须按 MigrationInventoryTest 复核当窗可用号(铁律 33)。
@@ -147,7 +142,6 @@ class JdPublishContractPendingTest {
// ---------------------------------------------------------------- AC-8(Pending Phase 2:配额闸)
@Test
@Disabled("Pending Phase 2: AC-8 配额闸——建单入口接 assertWithinQuota 后移除本注解")
void 建单入口必须接JdPublishQuotaService配额闸_源码绊线() throws IOException {
assertTrue(Files.exists(PUBLISH_SERVICE), "缺 JdPublishTaskService");
String source = Files.readString(PUBLISH_SERVICE);
@@ -135,6 +135,27 @@ class JdSchemaContractTest {
assertTrue(sql.contains("flyway_schema_history WHERE version='209'"), "缺回滚注释");
}
@Test
void V210_发布明细表_任务内商品唯一键与行级状态形状() {
String sql = read(DB_DIR.resolve("V210__jd_publish_item.sql"));
assertTrue(sql.contains("biz_jd_publish_item"), "缺发布明细表");
for (String column : List.of("task_id", "user_id", "product_id", "product_code", "shop_name",
"title", "category_path", "price_rule_json", "stock_json", "publish_status",
"publish_error", "jd_ware_id", "main_image_object_key", "created_at", "updated_at")) {
assertFalse(linesContaining(sql, "`" + column + "`").isEmpty(), "V210 缺列: " + column);
}
// 每任务每商品一行:重试/重复勾选不落两行(断点续跑的行级锚点)。
assertTrue(sql.contains("uk_task_product"), "任务内商品唯一键缺失");
assertTrue(linesContaining(sql, "uk_task_product").stream()
.anyMatch(line -> line.contains("task_id") && line.contains("product_id")),
"唯一键必须是 (task_id, product_id)");
// 行级状态机词表(chunk 回传推进的唯一真源)。
assertTrue(linesContaining(sql, "`publish_status`").stream()
.anyMatch(line -> line.contains("NOT NULL") && line.contains("DEFAULT 'PENDING'")),
"publish_status 必须 NOT NULL DEFAULT 'PENDING'(建单即落行,行状态由回传推进)");
assertTrue(sql.contains("迁移 V210"), "头注释必须是 `-- 迁移 V210…`(MigrationInventoryTest 口径)");
}
@Test
void 配置_独立图片桶不落默认桶() {
String appYml = read(RESOURCES.resolve("application.yml"));
@@ -77,7 +77,8 @@ import static org.mockito.Mockito.when;
* <p><b>V203 分类按数据权限分组隔离(2026-11-16 用户口径)</b>:分类归属存
* {@code biz_jd_product_group_assign} 的 (product_id, owner_group_id) 一行,读面靠
* {@code owner_group_id} 取「当前分组」的分类(缺省=作用域默认分组),归类的写权限
* 由 {@link JdCategoryScopeService} 判「该组可写」——商品行编辑/删除仍只平台超管。
* 由 {@link JdCategoryScopeService} 判「该组可写」——商品行编辑/删除走管理员级写闸
* (2026-11-17 用户口径「超管+管理员都可以,只有普通员工不能」)。
* 本类把作用域服务整体 mock 掉(四档角色矩阵在 {@code JdCategoryScopeServiceTest} 里钉),
* 只钉控制器怎么用它、以及拒绝语义不被吞。</p>
*/
@@ -235,25 +236,29 @@ class AdminJdProductControllerTest {
assertTrue(source.contains("\"owner_group_id\""), "列表必须收 owner_group_id(当前分组)");
}
// ===================== 写权限分档(2026-11-16 / V203) =====================
// ===================== 写权限分档(2026-11-17:超管级+管理员可写,普通账号只读) =====================
/** 写端点越权闸的结构判据:商品行四条写路由走超管闸,读三条走菜单正门。 */
/** 写端点越权闸的结构判据:商品行四条写路由走管理员级写闸,读三条走菜单正门。 */
@Test
void 商品页读写权限分档_商品行写端点逐条走超管闸() throws IOException {
void 商品页读写权限分档_商品行写端点逐条走管理员级写闸() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
assertEquals(4, count(source, "requirePlatformSuperAdminWrite(request)"),
"编辑/上传图片/单行删除/批量删除四条商品行写路由必须逐条走超管写闸"
assertEquals(4, count(source, "requireJdProductWrite(request)"),
"编辑/上传图片/单行删除/批量删除四条商品行写路由必须逐条走管理员级写闸"
+ "(归类不在此列:V203 起归本组管理员可做)");
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/类目/详情/归类四条读+组内写路由,与超管写闸内部一处,共五处菜单权限正门");
assertTrue(source.contains("仅平台超级管理员可以编辑或删除京东数据库数据"),
"非超管写商品的 403 文案必须点名平台超管");
"列表/类目/详情/归类四条读+组内写路由,与写闸内部一处,共五处菜单权限正门");
assertTrue(source.contains("仅超级管理员或管理员可以编辑或删除京东数据库数据"),
"普通账号写商品的 403 文案必须点名超管与管理员(2026-11-17 口径)");
assertTrue(source.contains("operator.superAdmin()"),
"写闸必须在菜单口径之上再判 superAdmin(只放行站点超管,公司超管不在内)");
"写闸必须在菜单口径之上再判 superAdmin(平台超管直放)");
assertTrue(source.contains("DeviceSessionPolicy.isCompanySuperAdmin(role)"),
"写闸必须放行公司超级管理员(超管档,2026-11-17 口径「只有普通员工不能」)");
assertTrue(source.contains("\"admin\".equals(role)"),
"写闸必须放行 admin 角色(管理员档,2026-11-17 口径「超管+管理员都可以」)");
}
@Test
void 非超管有菜单权限时读放行_商品行写一律403且不触服务() {
void 普通账号有菜单权限时读放行_商品行写一律403且不触服务() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
@@ -267,11 +272,12 @@ class AdminJdProductControllerTest {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
operator.setUsername("company-admin");
operator.setUsername("member");
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
// 非超管(管理员 / 公司超管同形):拿到 admin_jd_database 菜单权限后读可进、商品行写仍拒。
when(authSupport.currentRole(operator)).thenReturn("admin");
// 普通账号:resolveRole 归不出档返回 null(AdminAuthSupport.currentRole 真实形状);
// 拿到 admin_jd_database 菜单权限后读可进、商品行写仍拒(2026-11-17 口径「只有普通员工不能」)。
when(authSupport.currentRole(operator)).thenReturn(null);
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
grant.setRoutePath(ROUTE_PATH);
@@ -285,28 +291,28 @@ class AdminJdProductControllerTest {
pageVo.setItems(List.of());
when(queryService.page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, null, request)
.isSuccess(), "非超管有菜单权限时读必须放行(读写分档只收窄写)");
.isSuccess(), "普通账号有菜单权限时读必须放行(读写分档只收窄写)");
// 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
JdProductUpdateRequest updateBody = new JdProductUpdateRequest();
updateBody.setTitle("标题");
BusinessException updateEx = assertThrows(BusinessException.class,
() -> controller.update(11L, updateBody, request));
assertTrue(updateEx.getMessage().contains("仅平台超级管理员"), "编辑被拒文案点名平台超管");
assertTrue(updateEx.getMessage().contains("仅超级管理员或管理员"), "编辑被拒文案点名超管与管理员");
BusinessException deleteEx = assertThrows(BusinessException.class,
() -> controller.delete(11L, request));
assertTrue(deleteEx.getMessage().contains("仅平台超级管理员"));
assertTrue(deleteEx.getMessage().contains("仅超级管理员或管理员"));
JdProductBatchDeleteRequest batchBody = new JdProductBatchDeleteRequest();
batchBody.setIds(List.of(11L, 12L));
BusinessException batchEx = assertThrows(BusinessException.class,
() -> controller.batchDelete(batchBody, request));
assertTrue(batchEx.getMessage().contains("仅平台超级管理员"));
assertTrue(batchEx.getMessage().contains("仅超级管理员或管理员"));
BusinessException uploadEx = assertThrows(BusinessException.class,
() -> controller.uploadImage(11L, mock(MultipartFile.class), "MAIN", null, null, request));
assertTrue(uploadEx.getMessage().contains("仅平台超级管理员"),
assertTrue(uploadEx.getMessage().contains("仅超级管理员或管理员"),
"上传/替换图片改桶内对象=写动作,必须同闸");
verify(updateService, never()).update(any(), any());
@@ -315,6 +321,69 @@ class AdminJdProductControllerTest {
verify(deleteService, never()).delete(any());
}
/** 2026-11-17 口径「超管+管理员都可以」:admin 档四条写入口全放行、公司超管(超管档)同闸放行。 */
@Test
void 管理员与公司超管有菜单权限即可写商品_写入口放行且触服务() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, updateService, mock(JdProductGroupService.class),
mock(JdCategoryScopeService.class), authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
// 管理员(admin 档,非任何超管):菜单权限命中后商品行写全放行。
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
grant.setRoutePath(ROUTE_PATH);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
JdProductUpdateRequest updateBody = new JdProductUpdateRequest();
updateBody.setTitle("标题");
JdProductDetailVo detailVo = new JdProductDetailVo();
detailVo.setId(11L);
when(updateService.update(11L, updateBody)).thenReturn(11L);
when(queryService.detail(11L, null)).thenReturn(detailVo);
assertEquals(Boolean.TRUE, controller.update(11L, updateBody, request).isSuccess(),
"admin 档编辑放行必须是 success 信封(B80-03)");
verify(updateService).update(11L, updateBody);
when(updateService.uploadImage(11L, null, "MAIN", null, null)).thenReturn(11L);
assertEquals(Boolean.TRUE,
controller.uploadImage(11L, null, "MAIN", null, null, request).isSuccess(),
"admin 档上传图片同闸放行");
verify(updateService).uploadImage(11L, null, "MAIN", null, null);
JdProductDeleteVo receipt = new JdProductDeleteVo();
receipt.setDeleted(1);
when(deleteService.delete(List.of(11L))).thenReturn(receipt);
assertEquals(Boolean.TRUE, controller.delete(11L, request).isSuccess(), "admin 档单行删除放行");
JdProductBatchDeleteRequest batchBody = new JdProductBatchDeleteRequest();
batchBody.setIds(List.of(11L, 12L));
when(deleteService.delete(List.of(11L, 12L))).thenReturn(receipt);
assertEquals(Boolean.TRUE, controller.batchDelete(batchBody, request).isSuccess(), "admin 档批量删除放行");
verify(deleteService).delete(List.of(11L));
verify(deleteService).delete(List.of(11L, 12L));
// 公司超管=超管档:同一道闸放行(单条删除代表性钉住,防「只放平台超管」回潜)。
AdminUserEntity companySuper = new AdminUserEntity();
companySuper.setId(8L);
HttpServletRequest companyRequest = mock(HttpServletRequest.class);
when(authSupport.requireUser(companyRequest)).thenReturn(companySuper);
when(authSupport.currentRole(companySuper)).thenReturn("company_super_admin");
when(permissionMenuService.getUserColumnPermissions(8L, "admin")).thenReturn(List.of(grant));
when(deleteService.delete(List.of(21L))).thenReturn(receipt);
assertEquals(Boolean.TRUE, controller.delete(21L, companyRequest).isSuccess(),
"公司超级管理员属超管档,商品行写同闸放行(2026-11-17 口径)");
verify(deleteService).delete(List.of(21L));
}
@Test
void 不可写组的分组写一律403且不触服务() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
@@ -0,0 +1,150 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 用户端「商品上架」选品分页(v1.5 Phase 4,AC-9 owner 过滤的服务端半边)。
*
* <p>判据四件:① 归属条件恒带(user_id 来自会话出口,跨用户商品 0 返回);② 分类过滤走
* V203 归属表两步下推(先取 product_id 集再 in 主键,不往 wrapper 夹原生 SQL);③ 分类空集
* 直接回空页不查主表;④ 页码/页宽钳制照管理面同出口(MAX_PAGE/MAX_PAGE_SIZE,铁律 15)。</p>
*/
@ExtendWith(MockitoExtension.class)
class JdProductQueryServiceUserPageTest {
@Mock
private JdProductMapper jdProductMapper;
@Mock
private JdProductImageMapper jdProductImageMapper;
@Mock
private JdProductSkuMapper jdProductSkuMapper;
@Mock
private JdProductGroupMapper jdProductGroupMapper;
@Mock
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
@InjectMocks
private JdProductQueryService service;
@BeforeAll
static void initMybatisPlusTableInfo() {
// LambdaQueryWrapper 需要 MP 的 lambda cache(ProgressQueryOwnershipOutletTest 同款初始化)。
com.baomidou.mybatisplus.core.MybatisConfiguration configuration =
new com.baomidou.mybatisplus.core.MybatisConfiguration();
org.apache.ibatis.builder.MapperBuilderAssistant assistant =
new org.apache.ibatis.builder.MapperBuilderAssistant(configuration, "");
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
JdProductEntity.class);
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity.class);
}
private JdProductEntity product(long id) {
JdProductEntity row = new JdProductEntity();
row.setId(id);
row.setUserId(7L);
row.setTitle("测试商品 " + id);
row.setProductCode("P" + id);
row.setPriceMin(new BigDecimal("10.50"));
row.setStockTotal(3);
return row;
}
private com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity assign(long productId) {
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity row =
new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity();
row.setProductId(productId);
row.setCategoryId(3L);
row.setOwnerGroupId(2L);
return row;
}
@Test
void 选品分页只回归属当前用户的行() {
when(jdProductMapper.selectCount(any())).thenReturn(1L);
when(jdProductMapper.selectList(any())).thenReturn(List.of(product(11L)));
JdProductPageVo vo = service.pageForUser(7L, null, 1L, 20L);
ArgumentCaptor<LambdaQueryWrapper<JdProductEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(jdProductMapper).selectCount(captor.capture());
captor.getValue().getSqlSegment(); // MP 惯例:先求值一次才铺出参数
assertThat(captor.getValue().getSqlSegment()).as("归属条件恒在主查询里").contains("user_id");
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(7L);
assertThat(vo.getTotal()).isEqualTo(1L);
assertThat(vo.getItems()).hasSize(1);
assertThat(vo.getItems().get(0).getTitle()).isEqualTo("测试商品 11");
// 没选分类不查归属表
verify(jdProductGroupAssignMapper, never()).selectList(any());
}
@Test
void 分类过滤_先取归属表产品集再进主查询() {
when(jdProductGroupAssignMapper.selectList(any()))
.thenReturn(List.of(assign(11L), assign(12L), assign(11L)));
when(jdProductMapper.selectCount(any())).thenReturn(1L);
when(jdProductMapper.selectList(any())).thenReturn(List.of(product(12L)));
JdProductPageVo vo = service.pageForUser(7L, 3L, 1L, 20L);
ArgumentCaptor<LambdaQueryWrapper<JdProductEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(jdProductMapper).selectCount(captor.capture());
captor.getValue().getSqlSegment();
assertThat(captor.getValue().getSqlSegment())
.as("分类集以 IN 下推进主查询(owner 条件仍然恒在)")
.contains("user_id").contains("IN");
assertThat(captor.getValue().getParamNameValuePairs().values())
.contains(7L, 11L, 12L);
assertThat(vo.getItems()).hasSize(1);
}
@Test
void 分类空集直接回空页不查主表() {
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of());
JdProductPageVo vo = service.pageForUser(7L, 3L, 1L, 20L);
assertThat(vo.getTotal()).isZero();
assertThat(vo.getItems()).isEmpty();
verify(jdProductMapper, never()).selectCount(any());
verify(jdProductMapper, never()).selectList(any());
}
@Test
void 页码页宽钳制_离谱页码不喂负下标() {
when(jdProductMapper.selectCount(any())).thenReturn(0L);
JdProductPageVo zero = service.pageForUser(7L, null, 0L, 5000L);
assertThat(zero.getPage()).as("页码下限钳到 1").isEqualTo(1L);
assertThat(zero.getPageSize()).as("页宽上限钳到 100").isEqualTo(100L);
JdProductPageVo huge = service.pageForUser(7L, null, Long.MAX_VALUE, 20L);
assertThat(huge.getPage()).as("页码上限钳到 10000(乘积不溢出,铁律 15 同形)").isEqualTo(10000L);
verify(jdProductMapper, never()).selectList(any());
}
}
@@ -0,0 +1,167 @@
package com.nanri.aiimage.modules.jd.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 京东商品上架任务面板服务(v1.5 Phase 4 面板四端点)。
*
* <p>判据四件:① 总览三档计数(已结束=成功+失败);② 历史行读真源(行级四档计数来自
* {@code biz_jd_publish_item} GROUP BY 聚合,分类 id/改价规则从建单载荷带回);③ 批量进度
* 按模块过滤,非本模块任务进 missingTaskIds 不冒充面板条目;④ 删除面校验归属后才清明细行
* +任务主行(发布不落商品行,无京东数据库清理语义)。</p>
*/
@ExtendWith(MockitoExtension.class)
class JdPublishBoardServiceTest {
@Mock
private FileTaskMapper fileTaskMapper;
@Mock
private JdPublishItemMapper jdPublishItemMapper;
@Spy
private ObjectMapper objectMapper = new ObjectMapper();
@InjectMocks
private JdPublishBoardService service;
@BeforeEach
void setUp() {
// LambdaQueryWrapper 需要 MP 的 lambda cache(JdCollectBoardServiceTest 同款初始化)。
com.baomidou.mybatisplus.core.MybatisConfiguration configuration =
new com.baomidou.mybatisplus.core.MybatisConfiguration();
org.apache.ibatis.builder.MapperBuilderAssistant assistant =
new org.apache.ibatis.builder.MapperBuilderAssistant(configuration, "");
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity.class);
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.task.model.entity.FileTaskEntity.class);
}
private FileTaskEntity task(long id, long userId, String status) {
FileTaskEntity task = new FileTaskEntity();
task.setId(id);
task.setModuleType(JdPublishTaskService.MODULE_TYPE);
task.setUserId(userId);
task.setTaskNo("JD_PUBLISH-" + id);
task.setStatus(status);
task.setRequestJson("{\"userId\":" + userId + ",\"categoryId\":3,\"productIds\":[11,12],"
+ "\"priceRule\":{\"mode\":\"percent\",\"value\":10}}");
task.setCreatedAt(LocalDateTime.of(2026, 11, 18, 10, 0));
task.setUpdatedAt(LocalDateTime.of(2026, 11, 18, 10, 1));
return task;
}
@Test
void 总览三档计数与已结束数() {
when(fileTaskMapper.selectCount(any())).thenReturn(2L, 3L, 1L);
var vo = service.dashboard(7L);
assertThat(vo.getPendingTaskCount()).isEqualTo(2L);
assertThat(vo.getSuccessTaskCount()).isEqualTo(3L);
assertThat(vo.getFailedTaskCount()).isEqualTo(1L);
assertThat(vo.getProcessedTaskCount()).as("已结束=成功+失败").isEqualTo(4L);
}
@Test
void 历史行读真源_行级四档计数与建单载荷带回() {
FileTaskEntity running = task(34400L, 7L, "RUNNING");
FileTaskEntity failed = task(34399L, 7L, "FAILED");
// selectList 先出 history 主查询(按 createdAt 倒序 limit),乱序返回验证排序
when(fileTaskMapper.selectList(any())).thenReturn(new ArrayList<>(List.of(failed, running)));
// 一条 GROUP BY(task_id, publish_status)出全部任务的四档计数
when(jdPublishItemMapper.selectMaps(any())).thenReturn(List.of(
Map.of("task_id", 34400L, "publish_status", "SUCCESS", "cnt", 5L),
Map.of("task_id", 34400L, "publish_status", "PUBLISHING", "cnt", 2L),
Map.of("task_id", 34399L, "publish_status", "SUCCESS", "cnt", 3L),
Map.of("task_id", 34399L, "publish_status", "FAILED", "cnt", 1L)));
var vo = service.history(7L, 50);
assertThat(vo.getItems()).hasSize(2);
// 活跃(RUNNING)排前:失败任务往后靠
assertThat(vo.getItems().get(0).getTaskId()).isEqualTo(34400L);
var first = vo.getItems().get(0);
assertThat(first.getCategoryId()).as("分类 id 随建单载荷带回").isEqualTo(3L);
assertThat(first.getPriceRule())
.as("改价规则随建单载荷带回(重试重建推送载荷与建单响应 queuePayload 同键)")
.containsEntry("mode", "percent").containsEntry("value", java.math.BigDecimal.TEN);
assertThat(first.getProductTotal()).as("总行数=四档计数之和(SUCCESS5+PUBLISHING2)").isEqualTo(7L);
assertThat(first.getSuccessCount()).isEqualTo(5L);
assertThat(first.getPublishingCount()).isEqualTo(2L);
assertThat(first.getPendingCount()).isEqualTo(0L);
assertThat(first.getFailedCount()).isEqualTo(0L);
var second = vo.getItems().get(1);
assertThat(second.getTaskStatus()).isEqualTo("FAILED");
assertThat(second.getFailedCount()).as("失败行单独计数").isEqualTo(1L);
assertThat(second.getSuccessCount()).isEqualTo(3L);
}
@Test
void 批量进度按模块过滤_非本模块任务进missingTaskIds() {
FileTaskEntity publish = task(88L, 7L, "RUNNING");
FileTaskEntity collect = task(89L, 7L, "RUNNING");
collect.setModuleType("JD_SHOP_COLLECT");
when(fileTaskMapper.selectList(any())).thenReturn(List.of(publish, collect));
when(jdPublishItemMapper.selectMaps(any())).thenReturn(
List.of(Map.of("task_id", 88L, "publish_status", "SUCCESS", "cnt", 2L)));
var vo = service.progressBatch(List.of(88L, 89L, 0L, 88L));
assertThat(vo.getItems()).hasSize(1);
assertThat(vo.getItems().get(0).getTask().getId()).isEqualTo(88L);
assertThat(vo.getItems().get(0).getItems().get(0).getSuccessCount()).isEqualTo(2L);
assertThat(vo.getMissingTaskIds())
.as("非本模块任务不冒充面板条目;非法/重复 id 归一化后不影响")
.containsExactly(89L);
}
@Test
void 删除任务_归属不符一律拒_不碰明细表() {
FileTaskEntity other = task(88L, 9L, "FAILED");
when(fileTaskMapper.selectById(88L)).thenReturn(other);
assertThatThrownBy(() -> service.deleteTask(88L, 7L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("任务不存在");
verify(jdPublishItemMapper, never()).delete(any());
verify(fileTaskMapper, never()).deleteById(any(java.io.Serializable.class));
}
@Test
void 删除任务_先清明细快照行再清任务行() {
FileTaskEntity mine = task(88L, 7L, "FAILED");
when(fileTaskMapper.selectById(88L)).thenReturn(mine);
when(jdPublishItemMapper.delete(any())).thenReturn(2);
service.deleteTask(88L, 7L);
InOrder order = inOrder(jdPublishItemMapper, fileTaskMapper);
order.verify(jdPublishItemMapper).delete(any());
order.verify(fileTaskMapper).deleteById(any(java.io.Serializable.class));
}
}
@@ -0,0 +1,266 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.ItemResult;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* v1.5 Phase 2 行级回传测试:R6 单行失败隔离/终态汇总、铁律 31 判死分档(京麦登录态致命、
* 匿名拒判死、非致命只记录)、PENDING/终态任务拒收回传。
*/
@ExtendWith(MockitoExtension.class)
class JdPublishIngestServiceTest {
@Mock
private FileTaskMapper fileTaskMapper;
@Mock
private JdPublishItemMapper jdPublishItemMapper;
@Mock
private JdPublishStaleTaskService staleTaskService;
@Mock
private TaskProgressSnapshotService taskProgressSnapshotService;
@InjectMocks
private JdPublishIngestService service;
/** Mockito 纯单测无 Spring 环境:LambdaUpdateWrapper 解析 SFunction 需要 TableInfo 缓存(先例 ProgressQueryOwnershipOutletTest)。 */
@BeforeAll
static void initMybatisPlusTableInfo() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, FileTaskEntity.class);
TableInfoHelper.initTableInfo(assistant, JdPublishItemEntity.class);
}
private FileTaskEntity runningTask(long taskId) {
FileTaskEntity task = new FileTaskEntity();
task.setId(taskId);
task.setModuleType("JD_PUBLISH");
task.setStatus("RUNNING");
return task;
}
private ItemResult row(long productId, String status, String error, String wareId) {
ItemResult item = new ItemResult();
item.setProductId(productId);
item.setPublishStatus(status);
item.setPublishError(error);
item.setJdWareId(wareId);
return item;
}
private void stubCounts(long success, long failed, long pending, long publishing) {
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of(
Map.of("publishStatus", "SUCCESS", "cnt", success),
Map.of("publishStatus", "FAILED", "cnt", failed),
Map.of("publishStatus", "PENDING", "cnt", pending),
Map.of("publishStatus", "PUBLISHING", "cnt", publishing)));
}
@Test
void 行级回传SUCCESS落库并带wareId() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(0, 0, 1, 0);
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setBatchId("PUB-0001");
request.setItems(List.of(row(101L, "SUCCESS", null, "10036498117800")));
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getAcceptedCount()).isEqualTo(1);
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(jdPublishItemMapper).update(any(), captor.capture());
String sqlSet = captor.getValue().getSqlSet();
assertThat(sqlSet).as("行级状态与 wareId 两列一起落库")
.contains("publish_status").contains("jd_ware_id");
assertThat(captor.getValue().getParamNameValuePairs().values())
.extracting(String::valueOf)
.as("行级值:状态 + wareId").contains("SUCCESS", "10036498117800");
assertThat(vo.getTaskStatus()).as("未带 isEnd 不落终态").isNull();
}
@Test
void 行级FAILED带真实原因落库() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(0, 0, 1, 0);
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setItems(List.of(row(101L, "FAILED", "类目不在授权树内", null)));
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getAcceptedCount()).isEqualTo(1);
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(jdPublishItemMapper).update(any(), captor.capture());
assertThat(captor.getValue().getParamNameValuePairs().values())
.extracting(String::valueOf)
.as("R6:失败行落真实原因,不伪造成功").contains("FAILED", "类目不在授权树内");
}
@Test
void 不识别的行状态跳过不炸批() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(0, 0, 2, 0);
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setItems(List.of(row(101L, "PENDING", null, null), row(102L, "SUCCESS", null, "w1")));
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getAcceptedCount()).as("PENDING 不可回传写回,只有 SUCCESS 行被接受").isEqualTo(1);
}
@Test
void isEnd全成功任务落SUCCESS() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(3, 0, 0, 0);
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setIsEnd(true);
request.setItems(List.of(row(103L, "SUCCESS", null, "w3")));
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getTaskStatus()).isEqualTo("SUCCESS");
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(fileTaskMapper).update(any(), captor.capture());
String sqlSet = captor.getValue().getSqlSet();
assertThat(sqlSet).as("任务终态列:状态 + 真实行数两列")
.contains("status").contains("success_file_count");
assertThat(captor.getValue().getParamNameValuePairs().values())
.extracting(String::valueOf)
.as("AC-6:任务终态汇总真实行数").contains("SUCCESS");
verify(taskProgressSnapshotService).markTerminal(eq(34400L), eq("JD_PUBLISH"), eq("SUCCESS"), any());
}
@Test
void isEnd有失败行任务落FAILED并汇总() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(2, 1, 0, 0);
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setIsEnd(true);
request.setItems(List.of());
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getTaskStatus()).isEqualTo("FAILED");
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(fileTaskMapper).update(any(), captor.capture());
assertThat(captor.getValue().getParamNameValuePairs().values())
.extracting(String::valueOf)
.as("R6:任务终态汇总成败数(文案带真实行数)")
.contains("FAILED", "发布完成:成功 2 行,失败 1 行");
}
@Test
void PENDING任务拒收回传点名激活() {
FileTaskEntity task = runningTask(34400L);
task.setStatus("PENDING");
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
assertThatThrownBy(() -> service.submitChunk(34400L, new JdPublishChunkRequest(), true))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("任务不在运行中");
verify(jdPublishItemMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
}
@Test
void 终态任务拒收回传() {
FileTaskEntity task = runningTask(34400L);
task.setStatus("SUCCESS");
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
assertThatThrownBy(() -> service.submitChunk(34400L, new JdPublishChunkRequest(), true))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("任务已结束");
}
@Test
void 京麦登录态致命可信上报判死() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(0, 0, 1, 0);
when(staleTaskService.terminalizeOnJdLoginFatal(any(), anyString())).thenReturn(true);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setError("发布页跳回登录页,京麦未登录");
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getTaskStatus()).as("铁律 31:凭据不可自愈 ⇒ 整单 FAILED").isEqualTo("FAILED");
verify(staleTaskService).terminalizeOnJdLoginFatal(any(), eq("发布页跳回登录页,京麦未登录"));
verify(jdPublishItemMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
}
@Test
void 匿名error上报拒绝判死() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(0, 0, 1, 0);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setError("京麦未登录");
JdPublishChunkVo vo = service.submitChunk(34400L, request, false);
assertThat(vo.getTaskStatus()).as("判死口凭据化:匿名一律拒绝判死").isNull();
verify(staleTaskService, never()).terminalizeOnJdLoginFatal(any(), anyString());
verify(fileTaskMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
}
@Test
void 非致命技术故障只记录不判死() {
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
stubCounts(0, 0, 1, 0);
JdPublishChunkRequest request = new JdPublishChunkRequest();
request.setError("页面结构变更,发布按钮定位失败");
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
assertThat(vo.getTaskStatus()).as("技术性故障只补测不判死(R5 分档)").isNull();
verify(staleTaskService, never()).terminalizeOnJdLoginFatal(any(), anyString());
verify(fileTaskMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
}
@Test
void 任务不存在拒收回传() {
when(fileTaskMapper.selectById(99999L)).thenReturn(null);
assertThatThrownBy(() -> service.submitChunk(99999L, new JdPublishChunkRequest(), true))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("任务不存在");
}
}
@@ -0,0 +1,106 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.StaleTaskHeartbeatPolicy;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* v1.5 Phase 2 判死测试:铁律 31 CAS 语义(RUNNING→FAILED、已终态可重入不改写)、
* AC-5 终态文案点名「京麦未登录」「登录态失效」并给动作句(不写「稍后重试」)。
*/
@ExtendWith(MockitoExtension.class)
class JdPublishStaleTaskServiceTest {
@Mock
private FileTaskMapper fileTaskMapper;
@Mock
private TaskDistributedLockService taskDistributedLockService;
@Mock
private DistributedJobLockService distributedJobLockService;
@Mock
private StaleTaskHeartbeatPolicy staleTaskHeartbeatPolicy;
@Mock
private TaskProgressSnapshotService taskProgressSnapshotService;
@InjectMocks
private JdPublishStaleTaskService service;
/** Mockito 纯单测无 Spring 环境:LambdaUpdateWrapper 解析 SFunction 需要 TableInfo 缓存(先例 ProgressQueryOwnershipOutletTest)。 */
@BeforeAll
static void initMybatisPlusTableInfo() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
FileTaskEntity.class);
}
private FileTaskEntity task(long id) {
FileTaskEntity task = new FileTaskEntity();
task.setId(id);
task.setModuleType("JD_PUBLISH");
task.setStatus("RUNNING");
return task;
}
@Test
void 登录态失效判死CAS成功() {
FileTaskEntity task = task(34400L);
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
boolean terminalized = service.terminalizeOnJdLoginFatal(task, "发布页跳回登录页");
assertThat(terminalized).isTrue();
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(fileTaskMapper).update(any(), captor.capture());
// paramNameValuePairs 的值里有整句文案;子串断言拼成一串再判(元素级 contains 是全等)。
String joined = java.util.Arrays.toString(captor.getValue().getParamNameValuePairs().values().toArray());
assertThat(joined)
.as("AC-5 文案:生产者原文+两判据词+动作句")
.contains("发布页跳回登录页")
.contains("京麦未登录")
.contains("登录态失效")
.contains("重新登录京麦")
.as("铁律 31:不得说「稍后重试」").doesNotContain("稍后重试");
verify(taskProgressSnapshotService).markTerminal(eq(34400L), eq("JD_PUBLISH"), eq("FAILED"), any());
}
@Test
void 已终态任务CAS不命中可重入() {
FileTaskEntity task = task(34401L);
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(0);
boolean terminalized = service.terminalizeOnJdLoginFatal(task, "京麦未登录");
assertThat(terminalized).as("铁律 14:已终态不改写,可重入").isFalse();
verify(taskProgressSnapshotService, org.mockito.Mockito.never())
.markTerminal(any(), any(), any(), any());
}
@Test
void 文案判据词复用采集面同一族词表() {
// 判词表单一出处=JdStaleTaskService.isJdLoginStateFailure(京东域两链共用 19899 profile),
// 发布侧只消费不另抄一份词表(两份词表各改各的就是分叉判据)。
assertThat(JdStaleTaskService.isJdLoginStateFailure("发布页要求登录,京麦未登录")).isTrue();
assertThat(JdStaleTaskService.isJdLoginStateFailure("登录态失效")).isTrue();
assertThat(JdStaleTaskService.isJdLoginStateFailure("页面结构变更")).isFalse();
assertThat(JdStaleTaskService.isJdLoginStateFailure(" ")).isFalse();
}
}
@@ -0,0 +1,345 @@
package com.nanri.aiimage.modules.jd.service;
import com.fasterxml.jackson.databind.ObjectMapper;
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.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest.PriceRule;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
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.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;
/**
* v1.5 Phase 2 建单行为测试:AC-1 建单快照/LOCAL 显式写、AC-8 配额闸前置、AC-9 归属
* fail-closed、铁律 27a 改价规则同源、铁律 32 载荷 type 同值判据。
*/
@ExtendWith(MockitoExtension.class)
class JdPublishTaskServiceTest {
@Mock
private FileTaskMapper fileTaskMapper;
@Mock
private JdProductMapper jdProductMapper;
@Mock
private JdProductImageMapper jdProductImageMapper;
@Mock
private JdProductSkuMapper jdProductSkuMapper;
@Mock
private JdPublishItemMapper jdPublishItemMapper;
@Mock
private JdPublishQuotaService jdPublishQuotaService;
@Mock
private AdminUserMapper adminUserMapper;
@Mock
private OssStorageService ossStorageService;
@Spy
private ObjectMapper objectMapper = new ObjectMapper();
@Mock
private TaskHeartbeatService taskHeartbeatService;
@Mock
private TaskHeartbeatPositionService taskHeartbeatPositionService;
@InjectMocks
private JdPublishTaskService service;
private JdProductEntity product(long id, long userId, String title) {
JdProductEntity product = new JdProductEntity();
product.setId(id);
product.setUserId(userId);
product.setCompanyId(2L);
product.setShopName("测试旗舰店");
product.setProductCode("JD" + id);
product.setTitle(title);
product.setCategoryPath("女装 > 连衣裙");
product.setPriceMin(new BigDecimal("100.00"));
product.setStockTotal(50);
return product;
}
private JdPublishTaskCreateRequest validRequest(long userId) {
JdPublishTaskCreateRequest request = new JdPublishTaskCreateRequest();
request.setUserId(userId);
request.setCategoryId(11L);
request.setProductIds(List.of(101L, 102L));
return request;
}
@Test
void 建单成功且通道显式写LOCAL并落快照行() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
when(jdProductMapper.selectBatchIds(List.of(101L, 102L)))
.thenReturn(List.of(product(101L, 7L, "连衣裙A"), product(102L, 7L, "连衣裙B")));
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34400L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
JdPublishTaskVo vo = service.createTask(validRequest(7L), "device-abc");
assertThat(vo.getTaskId()).isEqualTo(34400L);
assertThat(vo.getTaskNo()).startsWith("JD_PUBLISH-");
assertThat(vo.getCollectChannel()).as("铁律 19:建单入口显式写通道,不依赖 defaultFor 兜底")
.isEqualTo("LOCAL");
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
verify(fileTaskMapper).insert(taskCaptor.capture());
FileTaskEntity task = taskCaptor.getValue();
assertThat(task.getModuleType()).isEqualTo("JD_PUBLISH");
assertThat(task.getStatus()).isEqualTo("PENDING");
assertThat(task.getUserId()).isEqualTo(7L);
assertThat(task.getSourceFileCount()).isEqualTo(2);
assertThat(task.getRequestJson()).contains("101").contains("102");
// AC-1 明细快照行:每勾选商品一行
verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(any(JdPublishItemEntity.class));
// AC-8 配额闸:前置且按勾选数计
verify(jdPublishQuotaService).assertWithinQuota(any(AdminUserEntity.class), eq(2));
// 铁律 32 第三件:建单响应带页面推送载荷,type 与 SPI QUEUE_TYPE 同值
assertThat(vo.getQueuePayload())
.containsEntry("type", "jd-product-publish-run");
assertThat(String.valueOf(vo.getQueuePayload().get("data")))
.as("data 段带 taskId(派发载荷键集)").contains("taskId").contains("34400");
}
@Test
void 快照行带改价折算与库存() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
when(jdProductMapper.selectBatchIds(List.of(101L))).thenReturn(List.of(product(101L, 7L, "连衣裙A")));
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34401L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
JdPublishTaskCreateRequest request = validRequest(7L);
request.setProductIds(List.of(101L));
PriceRule rule = new PriceRule();
rule.setMode("percent");
rule.setValue(new BigDecimal("10"));
request.setPriceRule(rule);
service.createTask(request, null);
ArgumentCaptor<JdPublishItemEntity> itemCaptor = ArgumentCaptor.forClass(JdPublishItemEntity.class);
verify(jdPublishItemMapper).insert(itemCaptor.capture());
JdPublishItemEntity item = itemCaptor.getValue();
assertThat(item.getPriceRuleJson()).as("铁律 27a:闸门认可的改价规则随快照固化").contains("percent");
assertThat(item.getPriceRuleJson()).contains("110.00");
assertThat(item.getStockJson()).contains("50");
assertThat(item.getTitle()).isEqualTo("连衣裙A");
assertThat(item.getPublishStatus()).isEqualTo("PENDING");
}
@Test
void 未选商品建单被拒并点名() {
JdPublishTaskCreateRequest request = validRequest(7L);
request.setProductIds(List.of());
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请勾选要上架的商品");
verify(jdPublishQuotaService, never()).assertWithinQuota(any(), anyInt());
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
}
@Test
void 超过商品上限建单被拒并点名() {
JdPublishTaskCreateRequest request = validRequest(7L);
request.setProductIds(java.util.stream.LongStream.rangeClosed(1, 501)
.boxed().toList());
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("单次上架最多选 500 个");
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
}
@Test
void 选了他人商品建单被拒并点名() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
when(jdProductMapper.selectBatchIds(List.of(101L)))
.thenReturn(List.of(product(101L, 8L, "别人的连衣裙")));
JdPublishTaskCreateRequest request = validRequest(7L);
request.setProductIds(List.of(101L));
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class)
.as("AC-9 归属半边:选他人商品业务码拒绝")
.extracting("code")
.isEqualTo(403);
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
verify(jdPublishItemMapper, never()).insert(any(JdPublishItemEntity.class));
}
@Test
void 商品缺行建单被拒() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
when(jdProductMapper.selectBatchIds(List.of(101L, 102L))).thenReturn(List.of(product(101L, 7L, "连衣裙A")));
assertThatThrownBy(() -> service.createTask(validRequest(7L), null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("部分商品不存在");
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
}
@Test
void 超配额建单被拒且不落任何行() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
org.mockito.Mockito.doThrow(new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前已占用 "
+ "5000/上限 5000,请清理京东数据库商品或联系管理员调整配额后重试"))
.when(jdPublishQuotaService).assertWithinQuota(any(), eq(2));
assertThatThrownBy(() -> service.createTask(validRequest(7L), null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("商品上架数量已达上限");
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
verify(jdPublishItemMapper, never()).insert(any(JdPublishItemEntity.class));
}
@Test
void 改价规则不识别建单被拒() {
JdPublishTaskCreateRequest request = validRequest(7L);
PriceRule rule = new PriceRule();
rule.setMode("double");
rule.setValue(BigDecimal.TEN);
request.setPriceRule(rule);
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("none/percent/fixed");
}
@Test
void 改价规则缺加价值建单被拒() {
JdPublishTaskCreateRequest request = validRequest(7L);
PriceRule rule = new PriceRule();
rule.setMode("fixed");
request.setPriceRule(rule);
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("必须填写加价值");
}
@Test
void 统一改价折算口径() {
PriceRule percent = new PriceRule();
percent.setMode("percent");
percent.setValue(new BigDecimal("10"));
assertThat(JdPublishTaskService.finalPriceOf(new BigDecimal("100"), percent))
.isEqualByComparingTo("110.00");
PriceRule fixed = new PriceRule();
fixed.setMode("fixed");
fixed.setValue(new BigDecimal("5.5"));
assertThat(JdPublishTaskService.finalPriceOf(new BigDecimal("100"), fixed))
.isEqualByComparingTo("105.50");
assertThat(JdPublishTaskService.finalPriceOf(new BigDecimal("100"), null))
.isEqualByComparingTo("100.00");
assertThat(JdPublishTaskService.finalPriceOf(null, percent)).isNull();
}
@Test
void 明细分批下发只出PENDING行并发预签名URL() {
FileTaskEntity task = new FileTaskEntity();
task.setId(34400L);
task.setModuleType("JD_PUBLISH");
task.setUserId(7L);
task.setStatus("RUNNING");
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
JdPublishItemEntity row = new JdPublishItemEntity();
row.setId(1L);
row.setTaskId(34400L);
row.setProductId(101L);
row.setTitle("连衣裙A");
row.setCategoryPath("女装 > 连衣裙");
row.setPriceRuleJson("{\"mode\":\"percent\",\"value\":10,\"sourcePrice\":100.00,\"finalPrice\":110.00}");
row.setStockJson("{\"total\":50}");
row.setPublishStatus("PENDING");
when(jdPublishItemMapper.selectPublishableItems(34400L, 0L, 20)).thenReturn(List.of(row));
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of());
JdProductEntity product = product(101L, 7L, "连衣裙A");
product.setAttrJson("{\"key\":\"color\"}");
when(jdProductMapper.selectBatchIds(List.of(101L))).thenReturn(List.of(product));
when(jdProductSkuMapper.selectList(any())).thenReturn(List.of());
when(jdProductImageMapper.selectList(any())).thenReturn(List.of());
var vo = service.pullItems(34400L, 7L, 0L, null);
assertThat(vo.getTaskId()).isEqualTo(34400L);
assertThat(vo.getItems()).hasSize(1);
assertThat(vo.getItems().get(0).getFinalPrice()).isEqualByComparingTo("110.00");
assertThat(vo.getItems().get(0).getAttrs()).contains("color");
assertThat(vo.isHasMore()).as("默认批大小 20 > 本页 1 行").isFalse();
assertThat(vo.getPendingCount()).isZero();
}
@Test
void 下发归属校验他人任务403() {
FileTaskEntity task = new FileTaskEntity();
task.setId(34400L);
task.setModuleType("JD_PUBLISH");
task.setUserId(8L);
task.setStatus("RUNNING");
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
assertThatThrownBy(() -> service.pullItems(34400L, 7L, 0L, null))
.isInstanceOf(BusinessException.class)
.extracting("code")
.isEqualTo(403);
}
@Test
void 心跳归属校验不通过不放行全局通道() {
FileTaskEntity task = new FileTaskEntity();
task.setId(34400L);
task.setModuleType("JD_PUBLISH");
task.setUserId(8L);
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
assertThatThrownBy(() -> service.heartbeat(34400L, 7L, null))
.as("B98-07 同形债预防:任意用户不可给任意任务刷心跳")
.isInstanceOf(BusinessException.class)
.extracting("code")
.isEqualTo(403);
verify(taskHeartbeatService, never()).heartbeat(anyLong(), any());
}
@Test
void 心跳归属校验通过走全局通道() {
FileTaskEntity task = new FileTaskEntity();
task.setId(34400L);
task.setModuleType("JD_PUBLISH");
task.setUserId(7L);
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo heartbeatVo =
new com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo();
heartbeatVo.setAlive(true);
when(taskHeartbeatService.heartbeat(eq(34400L), any())).thenReturn(heartbeatVo);
var vo = service.heartbeat(34400L, 7L, null);
assertThat(vo.isAlive()).isTrue();
verify(taskHeartbeatPositionService).record(eq(34400L), any());
}
}
@@ -158,6 +158,64 @@ class PermissionMenuServiceConsolePageTest {
.doesNotThrowAnyException();
}
// ---------------------------------------------------------- 平台门(2026-11-18)
/**
* 平台隔离(2026-11-18 用户口径「隔离下非站点超管只看自己平台侧」):管理员角色链的
* 「恒可进」收窄为「恒可进本人平台侧」——jd 用户直调亚马逊页面门一律 403,即便角色链
* 本可直通。把平台门挪回 isAdmin 直通之后(公司超管/管理员重新越侧)即红。
*/
@Test
void jdCompanySuperAdminIsDeniedAmazonPageDoor() {
AdminUserEntity operator = user(9L, "company_super_admin");
operator.setPlatform("jd");
BusinessException ex = catchThrowableOfType(() -> service.requireConsolePageAccess(
operator, "无权访问店铺管理", "admin_shop_manage"), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(403);
}
@Test
void jdCompanySuperAdminPassesJdPageDoor() {
AdminUserEntity operator = user(9L, "company_super_admin");
operator.setPlatform("jd");
assertThatCode(() -> service.requireConsolePageAccess(
operator, "无权访问京东数据库", "admin_jd_database")).doesNotThrowAnyException();
}
/** 普通账号同理:授权解决「有没有这一页」,平台门解决「这一页归不归我的平台」。 */
@Test
void jdNormalAccountHoldingAmazonGrantIsStillDenied() {
grants(7L, SHOP_PAGE_ID);
AdminUserEntity operator = user(7L, "normal");
operator.setPlatform("jd");
BusinessException ex = catchThrowableOfType(() -> service.requireConsolePageAccess(
operator, "无权访问店铺管理", "admin_shop_manage"), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(403);
}
/** 站点超管不受平台约束:双平台全通。 */
@Test
void superAdminIsNotPlatformConfined() {
AdminUserEntity operator = user(1L, "super_admin");
operator.setPlatform("jd");
assertThatCode(() -> service.requireConsolePageAccess(
operator, "无权访问店铺管理", "admin_shop_manage")).doesNotThrowAnyException();
}
/** 存量回归:platform 缺省(null→amazon)的账号调亚马逊页面门照旧放行。 */
@Test
void amazonPlatformOperatorKeepsExistingPageDoorBehavior() {
assertThatCode(() -> service.requireConsolePageAccess(
user(9L, "company_super_admin"), "无权访问店铺管理", "admin_shop_manage"))
.doesNotThrowAnyException();
}
// ---------------------------------------------------------------- 下发侧剪枝
@Test
@@ -39,9 +39,11 @@ class CollectChannelTest {
*/
@Test
void 本机默认模块清单与defaultFor同源() {
// v1.5 起含 JD_PUBLISH(京麦登录态只在用户桌面机 19899 Chrome,铁律 19 同形)。
assertEquals(List.of(CollectRoutingProperties.MODULE_APPEARANCE_PATENT,
CollectRoutingProperties.MODULE_SIMILAR_ASIN,
CollectRoutingProperties.MODULE_JD_SHOP_COLLECT), CollectChannel.localDefaultModuleTypes());
CollectRoutingProperties.MODULE_JD_SHOP_COLLECT,
CollectRoutingProperties.MODULE_JD_PUBLISH), CollectChannel.localDefaultModuleTypes());
for (String module : CollectChannel.localDefaultModuleTypes()) {
assertTrue(CollectChannel.defaultFor(module).isLocal(), module + " 在清单里却不被判本机");
}
@@ -44,7 +44,6 @@ ShopManageGroupMapper selectAccessibleCreatorUserIds Select PURE SELECT DISTINCT
ShopManageGroupMapper selectAccessibleGroupIds Select PURE SELECT DISTINCT accessible_group_id\nFROM (\n SELECT g.id AS accessible_group_id\n FROM biz_shop_manage_group g\n WHERE g.created_by_id = #{operatorId}\n OR g.user_id = #{operatorId}\n UNION\n SELECT gm.group_id AS accessible_group_id\n FROM biz_shop_manage_group_member gm\n WHERE gm.user_id = #{operatorId}\n UNION\n SELECT g2.id AS accessible_group_id\n FROM biz_shop_manage_group_member gm\n INNER JOIN biz_shop_manage_group g1 ON g1.id = gm.group_id\n INNER JOIN biz_shop_manage_group g2\n ON g2.created_by_id = COALESCE(g1.created_by_id, g1.user_id)\n OR g2.user_id = COALESCE(g1.created_by_id, g1.user_id)\n WHERE gm.user_id = #{operatorId}\n AND COALESCE(g1.created_by_id, g1.user_id) IS NOT NULL\n UNION\n SELECT member_groups.id AS accessible_group_id\n FROM biz_shop_manage_group leader_group\n INNER JOIN biz_shop_manage_group_member direct_member ON direct_member.group_id = leader_group.id\n INNER JOIN biz_shop_manage_group member_groups\n ON member_groups.created_by_id = direct_member.user_id\n OR member_groups.user_id = direct_member.user_id\n WHERE leader_group.created_by_id = #{operatorId}\n OR leader_group.user_id = #{operatorId}\n) accessible_groups\nWHERE accessible_group_id IS NOT NULL\nORDER BY accessible_group_id ASC
ShopManageGroupMapper selectGroupNamesByUserIds Select PURE <script>\nSELECT u.id AS userId, g.group_name AS groupName\nFROM users u\nINNER JOIN biz_shop_manage_group g\n ON g.created_by_id = u.created_by_id OR g.user_id = u.created_by_id\nWHERE u.created_by_id IS NOT NULL\n AND u.id IN\n<foreach collection='userIds' item='userId' open='(' separator=',' close=')'>\n #{userId}\n</foreach>\nORDER BY g.id ASC\n</script>
ShopManageGroupMapper selectLeaderIdsByMemberUserId Select PURE SELECT DISTINCT COALESCE(g.created_by_id, g.user_id) AS leader_id\nFROM biz_shop_manage_group_member gm\nINNER JOIN biz_shop_manage_group g ON g.id = gm.group_id\nWHERE gm.user_id = #{userId}\n AND COALESCE(g.created_by_id, g.user_id) IS NOT NULL
ShopManageGroupMapper selectLedGroups Select PURE SELECT g.id AS id, g.group_name AS groupName\nFROM biz_shop_manage_group g\nWHERE g.created_by_id = #{operatorId} OR g.user_id = #{operatorId}\nORDER BY g.id ASC
ShopManageGroupMapper selectManagedMemberUserIds Select PURE SELECT DISTINCT gm.user_id\nFROM biz_shop_manage_group g\nINNER JOIN biz_shop_manage_group_member gm ON gm.group_id = g.id\nINNER JOIN users u ON u.id = gm.user_id\nWHERE g.created_by_id = #{operatorId}\n OR g.user_id = #{operatorId}\nORDER BY gm.user_id ASC
ShopManageGroupMapper selectUserIdsByGroupId Select PURE SELECT u.id AS userId\nFROM users u\nINNER JOIN biz_shop_manage_group g ON g.id = #{groupId}\nWHERE u.id = COALESCE(g.created_by_id, g.user_id)\n OR u.created_by_id = COALESCE(g.created_by_id, g.user_id)\nORDER BY u.id ASC
ShopManageGroupMapper selectUserIdsByGroupIds Select PURE <script>\nSELECT DISTINCT visible_user_id\nFROM (\n SELECT COALESCE(g.created_by_id, g.user_id) AS visible_user_id\n FROM biz_shop_manage_group g\n WHERE g.id IN\n <foreach collection='groupIds' item='groupId' open='(' separator=',' close=')'>\n #{groupId}\n </foreach>\n UNION\n SELECT gm.user_id AS visible_user_id\n FROM biz_shop_manage_group_member gm\n WHERE gm.group_id IN\n <foreach collection='groupIds' item='groupId' open='(' separator=',' close=')'>\n #{groupId}\n </foreach>\n) visible_users\nWHERE visible_user_id IS NOT NULL\nORDER BY visible_user_id ASC\n</script>
Can't render this file because it contains an unexpected character in line 1 and column 222.
+2 -2
View File
@@ -414,14 +414,14 @@ onUnmounted(() => {
<div class="category-block">
<span class="category-label">采集分类(可选,多选)</span>
<el-select v-model="selectedShopCategoryValues" multiple collapse-tags collapse-tags-tooltip
:max-collapse-tags="1" placeholder="不选=全店采集(点击选择分类)" class="shop-cat-select">
:max-collapse-tags="1" placeholder="全店采集(点击选择分类)" class="shop-cat-select">
<el-option v-for="category in shopCategoryOptions" :key="category.value"
:label="category.label" :value="category.value" />
</el-select>
<p class="category-hint">
{{ selectedShopCategoryValues.length
? `只采选中 ${selectedShopCategoryValues.length} 个分类的商品;`
: '不选=全店采集。' }}
: '默认全店采集。' }}
分类是京麦后台「店内分类」(2026-11-16 快照);商品要先在京麦挂上分类才会被选中。
<button v-if="selectedShopCategoryValues.length" class="shop-cat-clear" type="button"
@click="clearShopCategories">清空</button>
+615
View File
@@ -0,0 +1,615 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import {
fetchJdCollectGroups,
type JdCollectGroupVo,
} from '@/shared/api/types/modules/jd-collect'
import {
activateJdPublishTask,
createJdPublishTask,
deleteJdPublishTask,
fetchJdPublishDashboard,
fetchJdPublishHistory,
fetchJdPublishProducts,
fetchJdPublishTaskProgressBatch,
interruptJdPublishTask,
type JdPublishHistoryItemVo,
type JdPublishProductVo,
} from '@/shared/api/types/modules/jd-publish'
import { retryClientTask } from '@/shared/api/task-retry'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { resolvePageHref } from '@/shared/page-prefix'
import { userNotice } from '@/shared/utils/user-notice'
import { formatDateTime } from '@/shared/utils/datetime'
import { useLiveTaskBoard } from '@/shared/composables/useLiveTaskBoard'
import NotificationBell from '@/shared/components/NotificationBell.vue'
/** 京东「商品上架」(v1.5 蓝图 §4 Phase 4):选分类 → 勾商品 → 改价规则 → 建单 → 右侧任务面板实时行级进度。
*
* 六条边界(照 v1.4/v1.5 已落地的采集契约与外观专利任务面板骨架,不另造流程):
* 1. 分类选项唯一来源=jdCollect.groups 既有出口(B113-01,AC-9 源码绊线钉死:本页不得自拼
* 分类 URL);分组下的商品列表走 jdPublish.products(AC-9 owner 过滤:服务端只回归属
* 当前登录用户的行),页内翻页、勾选跨页累计;
* 2. 改价规则三档(none/percent/fixed,蓝图 §3 死契约),与勾选集一起进建单体;服务端按
* 同一规则折算 SKU 价(铁律 27a 改价同源);
* 3. 建单成功把服务端下发的 queuePayload(type=jd-product-publish-run,铁律 32 第三件)原样
* 推进本机客户端队列;激活(PENDING→RUNNING)必须在推队列之前(2026-11-14 采集链真机
* 实录同因);推送失败不回滚建单(兜底拉取认领);
* 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比;
* 5. 失败/中断「重试/继续」走通用原位复位(铁律 26,不克隆),推送载荷从历史行的建单载荷
* (分类 id+改价规则)同源重建——与建单响应 queuePayload 同键同形状;
* 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经
* reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件
* 挂 App.vue,本页无需重复挂)。
*/
const homeHref = resolvePageHref('/new_web_source/home.html')
const backHref = resolvePageHref('/new_web_source/jd-console.html')
const username = ref('admin')
const submitting = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
// ---- 分类选择(AC-9:唯一来源是 jdCollect 组的既有 fetch 函数,不自拼 URL)----
const jdCollectGroupLoader = fetchJdCollectGroups
const groupOptions = ref<JdCollectGroupVo[]>([])
const groupsLoading = ref(false)
const selectedGroupId = ref<number | null>(null)
async function loadGroups() {
groupsLoading.value = true
try {
const vo = await jdCollectGroupLoader()
groupOptions.value = vo ?? []
// 默认选中第一个分类:分类是建单的展示维度,缺省选中省一次点击;商品列表随之拉取。
if (!selectedGroupId.value && groupOptions.value.length) {
selectedGroupId.value = groupOptions.value[0].id
}
} finally {
groupsLoading.value = false
}
}
// ---- 选品分页(owner 过滤在服务端;勾选跨页累计在本地 Map,翻页不清空)----
const PRODUCT_PAGE_SIZE = 12
const products = ref<JdPublishProductVo[]>([])
const productTotal = ref(0)
const productPage = ref(1)
const productsLoading = ref(false)
const selectedProducts = ref(new Map<number, JdPublishProductVo>())
const selectedProductIds = computed(() => Array.from(selectedProducts.value.keys()))
function toggleProduct(row: JdPublishProductVo, checked: boolean) {
const next = new Map(selectedProducts.value)
if (checked) next.set(row.id, row)
else next.delete(row.id)
selectedProducts.value = next
}
function clearSelection() {
selectedProducts.value = new Map()
}
async function loadProducts() {
productsLoading.value = true
try {
const vo = await fetchJdPublishProducts(selectedGroupId.value, productPage.value, PRODUCT_PAGE_SIZE)
products.value = vo.items ?? []
productTotal.value = vo.total ?? 0
} catch (err) {
errorMessage.value = err instanceof Error ? err.message : '商品列表拉取失败,请稍后重试'
} finally {
productsLoading.value = false
}
}
function changePage(page: number) {
productPage.value = page
void loadProducts()
}
// ---- 改价规则(蓝图 §3:none/percent/fixed 三档;percent=百分数,fixed=加价金额)----
const PRICE_RULE_MODES = [
{ value: 'none', label: '按原价上架' },
{ value: 'percent', label: '按比例加价(%)' },
{ value: 'fixed', label: '固定加价(元)' },
] as const
const priceMode = ref<'none' | 'percent' | 'fixed'>('none')
const priceValue = ref<number | null>(null)
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
const submitDisabled = computed(() =>
submitting.value
|| !selectedGroupId.value
|| !selectedProducts.value.size
|| priceValueMissing.value)
// ---- 实时任务面板(照 JdCollectTab 的 useLiveTaskBoard 形状;京东发布无结果文件,无下载层)----
const board = useLiveTaskBoard<JdPublishHistoryItemVo>({
scope: 'jd-publish',
pollingStorageKey: () => `jd-publish:tasks:${uidForStorage()}`,
fetchHistory: fetchJdPublishHistory,
fetchProgressBatch: fetchJdPublishTaskProgressBatch,
fetchDashboard: fetchJdPublishDashboard,
normalizeTaskStatus,
// 京东发布没有结果文件:状态到终态即结束,没有「等文件」那一层
isResultPreparing: () => false,
addPendingAfterFinalStatus: () => false,
keepPendingFileTask: () => false,
// CANCELLED 也是终态:中断的任务出「继续」按钮并停止轮询
settleOnTaskStatuses: ['SUCCESS', 'FAILED', 'CANCELLED'],
deleteTask: {
shouldDeleteTask: (item) => item.taskId != null,
deleteTask: (taskId) => deleteJdPublishTask(taskId),
deleteHistory: async () => undefined,
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
},
})
const { batchDeleteHistory, deleteTaskRecord } = board
const jdCards = computed<TaskStatCard[]>(() => [
{ label: '运行中任务', value: board.dashboard.value.pendingTaskCount },
{ label: '已结束任务', value: board.dashboard.value.processedTaskCount },
{ label: '成功任务', value: board.dashboard.value.successTaskCount },
{ label: '失败任务', value: board.dashboard.value.failedTaskCount },
])
const currentTaskViews = computed<TaskItemView[]>(() =>
board.currentItems.value.map(toJdPublishTaskView),
)
const historyTaskViews = computed<TaskItemView[]>(() =>
board.historyOnlyItems.value.map(toJdPublishTaskView),
)
function itemSource(item: TaskItemView) {
return item.source as JdPublishHistoryItemVo
}
function toJdPublishTaskView(item: JdPublishHistoryItemVo): TaskItemView {
const showProgress = isActiveTask(item)
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
return {
key: `jd-publish-${item.taskId ?? item.taskNo ?? item.updatedAt ?? ''}`,
title: `商品上架 · ${total ?? '—'} 个商品`,
taskId: item.taskId ?? '-',
startedAt: formatDateTime(item.createdAt),
finishedAt: formatDateTime(item.finishedAt),
statusText: statusText(item),
statusClass: statusClass(item),
extraLines: [
`成功 ${item.successCount ?? 0} / 失败 ${item.failedCount ?? 0}`
+ (item.publishingCount ? ` / 发布中 ${item.publishingCount}` : ''),
...(showProgress && total ? [`已发布 ${Math.min(published, total)}/${total} 个商品`] : []),
...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
],
progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null,
source: item,
}
}
// ---- 本模块的状态语义(京东发布:无结果文件,状态即终态)----
function normalizeTaskStatus(item: JdPublishHistoryItemVo | null | undefined) {
return (item?.taskStatus || '').toUpperCase()
}
function isActiveTask(item: JdPublishHistoryItemVo) {
const status = normalizeTaskStatus(item)
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
}
function statusText(item: JdPublishHistoryItemVo) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return '正在发布到京麦…'
if (status === 'PENDING') return '等待本机客户端领取任务…'
if (status === 'SCHEDULED') return '已排队,等待执行'
if (status === 'CANCELLED') return '已中断'
if (status === 'FAILED') return '发布失败'
if (status === 'SUCCESS' || item.success) return '发布完成'
return '等待中'
}
function statusClass(item: JdPublishHistoryItemVo) {
const status = normalizeTaskStatus(item)
if (status === 'FAILED') return 'failed'
if (status === 'RUNNING' || status === 'SCHEDULED') return 'running'
if (status === 'CANCELLED') return 'pending'
if (status === 'SUCCESS' || item.success) return 'success'
return 'pending'
}
/** 百分比:有 total 按已发布行数算(封顶 99 直到服务端落 SUCCESS);没有 total 不编造分母。 */
function progressPercent(item: JdPublishHistoryItemVo) {
const status = normalizeTaskStatus(item)
if (status === 'SUCCESS') return 100
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
if (!total) return 0
const done = Math.min((item.successCount ?? 0) + (item.failedCount ?? 0), total)
return Math.max(0, Math.min(99, Math.round((done * 100) / total)))
}
/** 计数文案:有 total 带分母和百分比;没有 total 只报行数,不编造分母。 */
function progressCountLabel(item: JdPublishHistoryItemVo) {
const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
if (!total) return `已发布 ${published} 个商品`
return `已发布 ${published}/${total} 个商品(${progressPercent(item)}%)`
}
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务)。 */
function canRetryTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
if (!item?.taskId) return false
const status = normalizeTaskStatus(item)
return status === 'FAILED' || status === 'CANCELLED'
}
/** 按钮文案:已中断的任务显示「继续」(从断点接着跑),失败任务仍是「重试」。 */
function retryLabel(item: JdPublishHistoryItemVo | null | undefined): string {
return normalizeTaskStatus(item) === 'CANCELLED' ? '继续' : '重试'
}
/** 在跑/待跑的任务可中断:PENDING/RUNNING/SCHEDULED 是服务端 CAS 的同一 ACTIVE 集合。 */
function canInterruptTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
if (!item?.taskId) return false
const status = normalizeTaskStatus(item)
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
}
async function interruptTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
const taskId = item?.taskId
if (!taskId) return
// 确认框取消走 reject 两臂(与采集页同口径,不新增 catch 块)
const confirmed = await ElMessageBox.confirm(
'中断后:本机客户端会停止发布,已发布的商品保留在京麦与发布明细里。确定中断吗?',
'中断任务',
{ type: 'warning', confirmButtonText: '中断', cancelButtonText: '先不中断' },
).then(
() => true,
() => false,
)
if (!confirmed) return
try {
await interruptJdPublishTask(taskId)
ElMessage.success('已中断:客户端下一跳心跳后收手,之后可点「继续」接着跑')
await refreshBoard()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '中断失败')
}
}
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
const taskId = item?.taskId
if (!taskId) return
const isResume = normalizeTaskStatus(item) === 'CANCELLED'
try {
await retryClientTask(taskId)
ElMessage.success(isResume
? '已继续:在这条任务上接着跑(已成功的商品不会重复发布)'
: '已提交重试:在这条任务上继续跑(不新建任务)')
// 复位是 PENDING:与建单同一条激活+推队列链路,客户端才会立刻领到这一单。
const activateError = await activateTask(taskId)
if (!activateError) {
const priceRule = item?.priceRule && item.priceRule.mode ? item.priceRule : { mode: 'none' }
// 推送载荷从历史行的建单载荷同源重建(与建单响应 queuePayload 同键:type/taskId/priceRule)。
await pushToClientQueue({ type: 'jd-product-publish-run', data: { taskId, priceRule } })
}
board.addPollingTask(taskId)
await refreshBoard()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '重试失败')
}
}
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度 */
async function refreshBoard() {
await Promise.all([
board.loadDashboard(),
board.loadHistory({ force: true }),
board.refreshTaskProgress(),
])
}
/** 激活任务(PENDING→RUNNING),返回 null 表示可推队列,返回 string 表示失败原因。
* 漏掉这一步,客户端第一个回传会被「任务不在运行中(PENDING)」拒收(采集链真机实录同因)。 */
async function activateTask(id: number): Promise<string | null> {
try {
await activateJdPublishTask(id)
return null
} catch (err) {
const text = err instanceof Error ? err.message : ''
// 客户端兜底拉取已原子认领(PENDING→RUNNING)时后端回这句:等同激活成功,不当失败展示。
if (text.includes('已在执行中')) {
return null
}
console.error('[jd-publish] 激活任务失败', err)
return '任务激活失败,本机客户端领不到这一单,请稍后重试'
}
}
/** 推送本机队列:建单路径传服务端下发的 queuePayload(页面不拼载荷),重试路径按同键形状重建后传入。 */
async function pushToClientQueue(payload: Record<string, unknown>): Promise<string | null> {
const api = getPywebviewApi()
if (!api?.enqueue_json) {
return '当前环境未启用任务队列能力(浏览器预览环境不会启动),请在本机客户端中打开本页'
}
const pushResult = await api.enqueue_json(payload)
if (pushResult?.success) {
return null
}
// 桥返回的 error 原文(系统/英文)不透传进界面:console 留链,界面固定中文动作句
if (pushResult?.error) {
console.error('[jd-publish] enqueue_json 被拒', pushResult.error)
}
return '推送本机队列失败,任务将由客户端兜底拉取认领'
}
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
const priceRuleHint = computed(() => {
if (priceMode.value === 'none') return '按京东数据库里的采集原价上架。'
if (priceMode.value === 'percent') return '按采集价上浮 N%(填 10 表示加价 10%)。'
return '每个商品统一加固定金额(填 5 表示加 5 元)。'
})
async function startPublish() {
if (submitDisabled.value) return
errorMessage.value = ''
successMessage.value = ''
submitting.value = true
try {
const priceRule = priceMode.value === 'none'
? { mode: 'none' as const }
: { mode: priceMode.value, value: priceValue.value as number }
// 勾选集即建单 productIds;selectedGroupId 即建单体 categoryId
// (服务端按 owner 校验,选了他人商品当场拒,AC-9)。
const categoryId = selectedGroupId.value
const productIds = selectedProductIds.value
const vo = await createJdPublishTask(categoryId, productIds, priceRule)
board.addPollingTask(vo.taskId)
let pushNote = ''
const activateError = await activateTask(vo.taskId)
if (activateError) {
// 没激活成功就不推队列:推了也是白跑一轮。任务留在 PENDING,
// 由服务端兜底拉取认领后照样会跑,所以这里只提示、不回滚建单。
pushNote = activateError
} else {
try {
// 建单响应自带 queuePayload(服务端组装,铁律 32 第三件),页面原样投递。
const pushError = await pushToClientQueue(vo.queuePayload
?? { type: 'jd-product-publish-run', data: { taskId: vo.taskId, priceRule } })
if (pushError) pushNote = pushError
} catch (pushErr) {
pushNote = '推送本机队列失败,任务将由服务端兜底派发给本机客户端执行'
console.error('[jd-publish] 推送本机队列失败', pushErr)
}
}
if (pushNote) {
errorMessage.value = pushNote
} else {
successMessage.value = `任务已创建(${productIds.length} 个商品)并推送给本机客户端,进度显示在右侧任务区`
}
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
} catch (err) {
errorMessage.value = err instanceof Error ? err.message : '建单失败,请稍后重试'
} finally {
submitting.value = false
}
}
onMounted(async () => {
const localName = (window.localStorage.getItem('username') || '').trim()
if (localName) username.value = localName
board.loadPollingIds()
await Promise.all([
loadGroups().catch(() => undefined),
board.loadDashboard().catch(() => undefined),
board.loadHistory().catch(() => undefined),
])
board.seedRunningTasksFromHistory()
board.seedPendingFileTasksFromHistory()
board.ensurePollingIfAny()
void loadProducts()
})
onUnmounted(() => {
board.dispose()
})
</script>
<template>
<div class="page-shell module-page jd-publish-page">
<header class="jd-top">
<router-link class="home-back" :to="homeHref" title="返回首页">← 返回首页</router-link>
<div class="brand">
<span class="brand-logo">富</span>
<span class="brand-text">
<span class="brand-name">数富AI</span>
<span class="brand-sub">京东运营工具台</span>
</span>
</div>
<div class="top-right">
<NotificationBell />
<span class="admin-name">{{ username }}</span>
</div>
</header>
<div class="tool-head">
<router-link class="tool-head__back" :to="backHref">← 返回京东工具台</router-link>
<span class="tool-head__title">商品上架</span>
<span class="tool-head__desc">
把京东数据库里你自己的商品批量上架到京麦店铺:选分类、勾商品、可选统一改价,本机已登录京麦的客户端逐个发布。
</span>
</div>
<main class="jd-body">
<aside class="left-panel">
<div class="category-block">
<span class="category-label">自定义分类</span>
<el-select v-model="selectedGroupId" placeholder="选择分类" class="shop-cat-select"
:loading="groupsLoading" @change="() => { productPage = 1; clearSelection(); void loadProducts() }">
<el-option v-for="group in groupOptions" :key="group.id"
:label="`${group.name}(${group.productCount ?? 0} 个商品)`" :value="group.id" />
</el-select>
<p class="category-hint">分类由管理员在后台「京东数据库」维护;列表只显示归属你账号的商品。</p>
</div>
<div class="product-block" v-loading="productsLoading">
<div class="product-head">
<span class="category-label">选择商品(已选 {{ selectedProducts.size }} 个,跨页累计)</span>
<button v-if="selectedProducts.size" class="shop-cat-clear" type="button"
@click="clearSelection">清空勾选</button>
</div>
<div v-if="!products.length && !productsLoading" class="product-empty">
{{ selectedGroupId ? '该分类下暂无归属你账号的商品' : '请先选择分类' }}
</div>
<label v-for="product in products" :key="product.id" class="product-row">
<input type="checkbox" class="product-check"
:checked="selectedProducts.has(product.id)"
@change="toggleProduct(product, ($event.target as HTMLInputElement).checked)" />
<img v-if="product.mainImageUrl" class="product-thumb" :src="product.mainImageUrl" alt="" loading="lazy" />
<span v-else class="product-thumb product-thumb--empty">无图</span>
<span class="product-info">
<span class="product-title">{{ product.title }}</span>
<span class="product-meta">
¥{{ 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>
</span>
</label>
<el-pagination v-if="productTotal > PRODUCT_PAGE_SIZE" class="product-pager" layout="prev, pager, next"
:total="productTotal" :page-size="PRODUCT_PAGE_SIZE" :current-page="productPage"
@current-change="changePage" />
</div>
<div class="category-block">
<span class="category-label">改价规则(可选)</span>
<el-select v-model="priceMode" class="shop-cat-select">
<el-option v-for="mode in PRICE_RULE_MODES" :key="mode.value" :label="mode.label" :value="mode.value" />
</el-select>
<el-input-number v-if="priceMode !== 'none'" v-model="priceValue" :min="0" :precision="2"
:step="priceMode === 'percent' ? 1 : 0.5" class="price-input" controls-position="right"
:placeholder="priceMode === 'percent' ? '加价百分比' : '加价金额'" />
<p class="category-hint">{{ priceRuleHint }}</p>
</div>
<button class="collect-btn" type="button" :disabled="submitDisabled" @click="startPublish">
{{ submitting ? '创建中…' : `上架已选 ${selectedProducts.size} 个商品` }}
</button>
<p class="collect-hint">
点击后本机客户端会逐个把商品发布到已登录的京麦店铺,请保持客户端在线且京麦已登录;发布进度逐行显示在右侧任务区。
</p>
<p v-if="successMessage" class="feedback success">{{ successMessage }}</p>
<p v-if="errorMessage" class="feedback error">{{ errorMessage }}</p>
</aside>
<section class="right-panel">
<TaskCenterPanel
:on-batch-delete="batchDeleteHistory"
:on-refresh="refreshBoard"
title="商品上架"
:cards="jdCards"
:current-items="currentTaskViews"
:history-items="historyTaskViews"
current-title="当前任务"
current-empty-text="暂无当前任务"
history-empty-text="暂无历史记录"
>
<template #item-actions="{ item }">
<button v-if="canInterruptTask(itemSource(item))" type="button" class="btn-interrupt"
@click="interruptTaskRecord(itemSource(item))">中断</button>
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
@click="retryTaskRecord(itemSource(item))">{{ retryLabel(itemSource(item)) }}</button>
<button type="button" class="btn-delete" @click="deleteTaskRecord(itemSource(item))">删除</button>
</template>
<template #history-item-actions="{ item }">
<button v-if="canInterruptTask(itemSource(item))" type="button" class="btn-interrupt"
@click="interruptTaskRecord(itemSource(item))">中断</button>
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
@click="retryTaskRecord(itemSource(item))">{{ retryLabel(itemSource(item)) }}</button>
<button v-if="itemSource(item).taskId" type="button" class="btn-delete"
@click="deleteTaskRecord(itemSource(item))">删除</button>
</template>
</TaskCenterPanel>
</section>
</main>
</div>
</template>
<!-- 样式与采集页同族暗色主题(header/brand/工具头为两页共通形状,各自 scoped 不共享);
逐规则单行压缩只为过可读棘轮 800 行线,不改任何选择器与声明。 -->
<style scoped>
.jd-publish-page { display: flex; flex-direction: column; min-height: 100vh; background-color: #1a1f2e; background-image: radial-gradient(rgba(45, 212, 191, 0.08) 1px, transparent 1px); background-size: 48px 48px; font-family: "PingFang SC", "Microsoft YaHei UI", "Microsoft YaHei", "微软雅黑", sans-serif; }
.jd-top { flex: 0 0 auto; min-height: 64px; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 0 28px; background: #1a1f2e; border-bottom: 1px solid #3e4a62; }
.home-back, .tool-head__back { flex-shrink: 0; display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border: 1px solid #3e4a62; border-radius: 6px; color: #c8d2e2; font-size: 13px; text-decoration: none; white-space: nowrap; transition: all 0.2s; }
.home-back:hover, .tool-head__back:hover { background: #2b3447; color: #f5f8fc; }
.brand { display: flex; align-items: center; gap: 12px; flex-shrink: 0; }
.brand-logo { display: flex; align-items: center; justify-content: center; width: 38px; height: 38px; border-radius: 8px; background: #e1251b; color: #fff; font-size: 20px; font-weight: 700; box-shadow: 0 2px 8px rgba(225, 37, 27, 0.32); }
.brand-text { display: flex; flex-direction: column; line-height: 1.35; }
.brand-name { color: #f5f8fc; font-size: 17px; font-weight: 700; white-space: nowrap; }
.brand-sub { color: #a0acbe; font-size: 10px; white-space: nowrap; }
.top-right { display: flex; align-items: center; gap: 14px; flex-shrink: 0; }
.admin-name { color: #c8d2e2; font-size: 13px; font-weight: 700; white-space: nowrap; }
.tool-head { flex: 0 0 auto; display: flex; align-items: center; flex-wrap: wrap; gap: 20px; min-height: 62px; padding: 10px 34px; background: #1a1f2e; }
.tool-head__title { flex-shrink: 0; color: #f5f8fc; font-size: 22px; font-weight: 700; white-space: nowrap; }
.tool-head__desc { min-width: 0; max-width: 760px; color: #a0acbe; font-size: 14px; line-height: 1.5; }
.jd-body { flex: 1 1 auto; min-height: 0; display: flex; align-items: stretch; overflow: hidden; }
.left-panel { width: 440px; flex-shrink: 0; padding: 20px; overflow-y: auto; border-right: 1px solid #3e4a62; }
.right-panel { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow-y: auto; padding: 20px; }
.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-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; }
.shop-cat-clear { margin-left: 6px; padding: 0; border: none; background: none; color: #6ea8ff; font-size: 12px; cursor: pointer; font-family: inherit; }
.shop-cat-clear:hover { text-decoration: underline; }
.product-block { margin-bottom: 16px; }
.product-head { display: flex; align-items: center; justify-content: space-between; }
.product-head .category-label { margin-bottom: 8px; }
.product-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; margin-bottom: 6px; border: 1px solid #2c3547; border-radius: 8px; background: #20283a; cursor: pointer; }
.product-row:hover { border-color: #3e4a62; }
.product-check { flex-shrink: 0; width: 15px; height: 15px; accent-color: #e1251b; cursor: pointer; }
.product-thumb { flex-shrink: 0; width: 44px; height: 44px; border-radius: 6px; object-fit: cover; background: #232b3d; }
.product-thumb--empty { display: inline-flex; align-items: center; justify-content: center; color: #5f6c85; font-size: 11px; }
.product-info { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.product-title { color: #d9e1ef; font-size: 12px; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.product-meta { color: #8a97ad; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.product-empty { padding: 18px 0; color: #5f6c85; font-size: 12px; text-align: center; }
.product-pager { margin-top: 8px; justify-content: center; }
.product-pager :deep(.el-pager li), .product-pager :deep(.btn-prev), .product-pager :deep(.btn-next) { background: transparent; color: #c8d2e2; }
.product-pager :deep(.el-pager li.is-active) { color: #6ea8ff; }
.price-input { width: 100%; margin-top: 8px; }
.price-input :deep(.el-input__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
.price-input :deep(.el-input__inner) { color: #c8d2e2; }
.collect-btn { width: 100%; padding: 13px 0; border: none; border-radius: 8px; background: linear-gradient(135deg, #ff5a4f, #e1251b); color: #ffffff; font-size: 16px; font-weight: 700; font-family: inherit; cursor: pointer; box-shadow: 0 4px 16px rgba(225, 37, 27, 0.32); transition: all 0.2s; }
.collect-btn:hover:not(:disabled) { filter: brightness(1.1); transform: translateY(-1px); }
.collect-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.collect-hint { margin: 12px 0 0; color: #a0acbe; font-size: 12px; line-height: 1.7; }
.feedback { margin: 16px 0 0; padding: 10px 12px; border-radius: 8px; font-size: 13px; line-height: 1.6; }
.feedback.success { background: rgba(16, 185, 129, 0.12); color: #6ee7b7; }
.feedback.error { background: rgba(248, 113, 113, 0.12); color: #fca5a5; }
.btn-delete, .btn-retry, .btn-interrupt { border: none; cursor: pointer; border-radius: 6px; font-size: 12px; }
.btn-delete { padding: 6px 10px; color: #ff8f8f; background: rgba(231, 76, 60, .12); }
.btn-retry { padding: 6px 10px; color: #7fd1a0; background: rgba(39, 174, 96, .14); }
.btn-interrupt { padding: 6px 10px; color: #f0b35e; background: rgba(240, 179, 94, .12); }
@media (max-width: 1100px) {
.tool-head { padding: 10px 16px; gap: 10px; }
.jd-body { flex-direction: column; overflow-y: auto; }
.left-panel { width: 100%; border-right: none; border-bottom: 1px solid #3e4a62; }
.right-panel { padding: 16px; }
}
</style>

Some files were not shown because too many files have changed in this diff Show More