feat(京东上架): 京麦品牌候选上报+用户端联想输入(V220)

- 后端:biz_jd_shop_brand(V220)+JdShopBrandService 增量 upsert/list/recordUsedTarget
  +POST/GET /api/jd-shop-brands(requireUserOrInternal,ApiGuard 覆盖登记)
- 用户端:endpoints.jdPublish.shopBrands+jd-brand-options 纯函数+JdPublishTab 目标品牌
  改 el-autocomplete(手输永远生效)
- 台账:TaskFailureCategoryGuardrailTest updateById 写点 164→165(JdShopBrandService.report,
  实体无 ALWAYS 列、row 为读回新鲜行,审过登记)

来源:2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」
未发版:V220 随 jar 迁移、app-web 需重发、客户端候选上报随 5.1.4
This commit is contained in:
2026-11-28 17:29:46 +08:00
parent d8a85e6ff5
commit 3de3e2e0ca
17 changed files with 1005 additions and 16 deletions
@@ -107,7 +107,12 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
// token(与分片回传同形)。路径不是 /api/admin/**,不进 AdminApiGuardFilter;
// 也不进 USER_TOOL_PREFIXES(那批挂 user-tool-guard-enabled,按 user_id/JWT 语义
// 收紧,采集器上报不带 user 参数,套进去会误伤),所以按方法级设防登记这一格。
"/api/jd-shop-category-tree");
"/api/jd-shop-category-tree",
// 2026-11-28 京麦店铺品牌候选(V220):两条入口(POST 上报 / GET 读取)的方法体第一行
// 同样是 adminAuthSupport.requireUserOrInternal——用户端目标品牌下拉走登录 JWT、
// 客户端发布流程上报走可信内部 token;不进 /api/admin/** 也不进 USER_TOOL_PREFIXES
// 的理由与上一行同源(那批按 user_id/JWT 收紧,会误伤不带 user 参数的客户端上报)。
"/api/jd-shop-brands");
/**
* 待收欠账:数据按 user_id 归属、却既不进守卫名单也没有 require* 的前缀。
@@ -0,0 +1,70 @@
package com.nanri.aiimage.modules.jd.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.model.dto.JdShopBrandReportRequest;
import com.nanri.aiimage.modules.jd.model.vo.JdShopBrandVo;
import com.nanri.aiimage.modules.jd.service.JdShopBrandService;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
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;
import java.util.Map;
/**
* 京麦店铺品牌候选(2026-11-28):客户端上报 + 用户端目标品牌下拉读取。
*
* <p>客户口径「品牌看看能不能获取下来,也可以支持自己输入」:京麦品牌是远程搜索、
* 没有可离线拉取的全量清单,因此由客户端在发布流程的品牌面板里抓真实候选上报,
* 前端下拉展示真名候选并保留手输。</p>
*
* <p>鉴权:{@code requireUserOrInternal}——用户端读走登录 JWT,客户端上报走可信内部
* token(与授权类目树 / 分片回传同形),两者任一通过;都不通过按 401。</p>
*/
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/jd-shop-brands")
@Tag(name = "京麦店铺品牌候选", description = "客户端发布流程抓取上报,用户端目标品牌下拉读取。")
public class JdShopBrandController {
private final JdShopBrandService brandService;
private final AdminAuthSupport adminAuthSupport;
@PostMapping
@Operation(summary = "上报店铺品牌候选(客户端调用)",
description = "增量幂等 upsert(按 shop_id+brand_id 刷新文本与时间):候选是京麦远程搜索"
+ "碎片,整替换会把以前抓到的品牌清空。缺店铺 ID、空候选一律拒。")
public ApiResponse<Map<String, Object>> report(
@RequestBody JdShopBrandReportRequest body,
@Parameter(hidden = true) HttpServletRequest request) {
adminAuthSupport.requireUserOrInternal(request);
int saved = brandService.report(body);
return ApiResponse.success(Map.of("saved", saved));
}
@GetMapping
@Operation(summary = "读取店铺品牌候选(用户端目标品牌下拉)",
description = "按最近一次抓到的时间倒序;keyword 为品牌名模糊过滤。空列表只表示"
+ "这家店还没抓到过候选,页面仍须允许手输品牌名。")
public ApiResponse<JdShopBrandVo> list(
@Parameter(description = "京麦 venderId", required = true)
@RequestParam("shopId") String shopId,
@Parameter(description = "品牌名模糊过滤")
@RequestParam(value = "keyword", required = false) String keyword,
@Parameter(description = "返回条数上限(默认 50,最大 200)")
@RequestParam(value = "limit", required = false) Integer limit,
@Parameter(hidden = true) HttpServletRequest request) {
adminAuthSupport.requireUserOrInternal(request);
return ApiResponse.success(brandService.list(shopId, keyword, limit));
}
}
@@ -0,0 +1,16 @@
package com.nanri.aiimage.modules.jd.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdShopBrandEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 京麦店铺品牌候选({@code biz_jd_shop_brand},V220,2026-11-28)数据访问口。
*
* <p>上报是增量幂等(按 shop_id+brand_id upsert)、读取是按店过滤,全部可由
* {@link BaseMapper} + lambda wrapper 表达,不需要自定义 SQL。品牌候选是几十到几百行
* 的小表,service 侧「先按店查出已有 → 内存分拣 insert/update」比逐条 select 更省连接。</p>
*/
@Mapper
public interface JdShopBrandMapper extends BaseMapper<JdShopBrandEntity> {
}
@@ -0,0 +1,44 @@
package com.nanri.aiimage.modules.jd.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 客户端上报「京麦店铺品牌候选」的请求体({@code POST /api/jd-shop-brands},2026-11-28)。
*
* <p>上报是**增量幂等**的(按 shop_id+brand_id upsert),不是整店替换——品牌候选是京麦
* 按关键词远程搜出来的碎片,客户端每次只看到一页结果,整替换会把以前抓到的品牌清掉。</p>
*/
@Data
@Schema(description = "京麦店铺品牌候选上报")
public class JdShopBrandReportRequest {
@Schema(description = "京麦 venderId(店铺 ID);取不到时上报被拒(候选无法归属到店铺)")
private String shopId;
@Schema(description = "店铺展示名(仅供排查)")
private String shopName;
@Schema(description = "本次抓到的品牌候选(1~500 条)")
private List<Brand> brands;
@Schema(description = "来源:publish=发布流程抓到的面板候选(缺省);"
+ "target=成功上架时实际使用的目标品牌(客户手输的品牌也可以进候选)")
private String source;
@Data
@Schema(description = "品牌候选")
public static class Brand {
@Schema(description = "京麦品牌 id(字符串,可为负,如「无品牌」=-1)")
private String brandId;
@Schema(description = "品牌名(候选文本 ``[`` 之前的部分)")
private String brandName;
@Schema(description = "候选文本 ``[id]-`` 之后的公司名(可空,仅区分同名品牌)")
private String companySuffix;
}
}
@@ -0,0 +1,43 @@
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_shop_brand},V220,2026-11-28)。
*
* <p>一行=「店铺 × 品牌 id」。京麦品牌是**远程搜索**(输入关键词才出候选),没有可离线
* 拉取的全量清单;客户端在发布流程的品牌面板里每次都能抓到真机候选(文本形状
* ``品牌名[品牌id]-公司名``),上报落本表,前端目标品牌下拉用这些真名候选,
* 手输保留。唯一键 {@code uk_jd_shop_brand(shop_id, brand_id)} 保证重复抓取幂等。</p>
*
* <p>{@code brandId} 存字符串:真机里「无品牌」是负数 id(-1),「无」是 1343010,
* 不按数字大小排序、也不做数值转换。</p>
*/
@Data
@TableName("biz_jd_shop_brand")
public class JdShopBrandEntity {
@TableId(type = IdType.AUTO)
private Long id;
/** 京麦 venderId(店铺 ID)。 */
private String shopId;
/** 抓取时的店铺展示名(仅供排查)。 */
private String shopName;
/** 京麦品牌 id(字符串;可为负)。 */
private String brandId;
/** 品牌名(候选文本 ``[`` 之前的部分)。 */
private String brandName;
/** 候选文本 ``[id]-`` 之后的公司名(仅用于区分同名品牌)。 */
private String companySuffix;
/** 来源:publish=发布流程抓到;target=成功上架的目标品牌。 */
private String source;
/** 最近一次在真机候选里看到的时间。 */
private LocalDateTime lastSeenAt;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,41 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 京麦店铺品牌候选读取回执({@code GET /api/jd-shop-brands},2026-11-28)。
*
* <p>用户端上架页「目标品牌」下拉的数据源。{@code items} 为空只表示「这家店还没抓到过
* 候选」,不表示店铺没有品牌——京麦品牌是远程搜索,候选靠发布流程逐步积累,
* 所以下拉必须同时允许手输(客户口径「也可以支持自己输入」)。</p>
*/
@Data
@Schema(description = "京麦店铺品牌候选")
public class JdShopBrandVo {
@Schema(description = "品牌候选(按最近一次看到的时间倒序)")
private List<Item> items;
@Schema(description = "该店铺已缓存的候选总数")
private Integer total;
@Data
@Schema(description = "品牌候选")
public static class Item {
@Schema(description = "京麦品牌 id(可为负)")
private String brandId;
@Schema(description = "品牌名")
private String brandName;
@Schema(description = "公司名后缀(可空)")
private String companySuffix;
@Schema(description = "最近一次看到的时间")
private String lastSeenAt;
}
}
@@ -0,0 +1,172 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdShopBrandMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdShopBrandReportRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdShopBrandEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdShopBrandVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 京麦店铺品牌候选:客户端发布流程上报 + 用户端目标品牌下拉读取(2026-11-28)。
*
* <p>为什么这么做:京麦品牌是**按关键词远程搜索**的(输入才出候选),没有可离线拉取的
* 全量清单,所以「获取品牌列表」只能靠客户端在真实发布流程里把看到的候选攒起来。
* 上游客户口径是「品牌看看能不能获取下来,也可以支持自己输入」——下拉给真名候选,
* 手输始终保留,候选为空不影响建单。</p>
*
* <p>与授权类目树(V215)的关键差异:那边的树是整店快照(整店替换),这边的候选是
* **搜索碎片**(一次只看到一页),因此只能是增量 upsert——整替换会把以前抓到的品牌清空。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class JdShopBrandService {
/** 单次上报条数上限:候选面板一页几十条,给 10 倍余量,超了按脏数据拒。 */
static final int MAX_REPORT_BRANDS = 500;
/** 读取默认/最大条数(下拉一次展示够用即可)。 */
static final int DEFAULT_LIMIT = 50;
static final int MAX_LIMIT = 200;
/** 文本长度上限(与 DDL 对齐)。 */
static final int MAX_SHOP_ID = 64;
static final int MAX_SHOP_NAME = 128;
static final int MAX_BRAND_ID = 32;
static final int MAX_BRAND_NAME = 128;
static final int MAX_COMPANY = 255;
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final String SOURCE_PUBLISH = "publish";
private static final String SOURCE_TARGET = "target";
private final JdShopBrandMapper mapper;
/**
* 增量上报一家店铺的品牌候选(幂等):同 {@code shop_id + brand_id} 只刷新文本与时间。
*
* <p>缺店铺 ID / 空候选一律拒:没有店铺归属的候选落库后永远读不出来,属于脏数据;
* 空候选也不该被当成「这家店没有品牌」去清空已有记录。</p>
*/
@Transactional
public int report(JdShopBrandReportRequest request) {
if (request == null || isBlank(request.getShopId())) {
throw new BusinessException("缺少店铺 ID,品牌候选无法归属");
}
String shopId = clip(request.getShopId(), MAX_SHOP_ID);
String shopName = clip(request.getShopName(), MAX_SHOP_NAME);
List<JdShopBrandReportRequest.Brand> brands = request.getBrands();
if (brands == null || brands.isEmpty()) {
throw new BusinessException("品牌候选为空,未写入");
}
if (brands.size() > MAX_REPORT_BRANDS) {
throw new BusinessException("单次品牌候选超过上限 " + MAX_REPORT_BRANDS + " 条");
}
Map<String, JdShopBrandEntity> existing = new HashMap<>();
for (JdShopBrandEntity row : mapper.selectList(new LambdaQueryWrapper<JdShopBrandEntity>()
.eq(JdShopBrandEntity::getShopId, shopId))) {
existing.put(row.getBrandId(), row);
}
LocalDateTime now = LocalDateTime.now();
// 来源只认两档:target=成功上架实际用过的目标品牌(可来自客户手输,比搜索碎片更可信);
// 其余一律按 publish(面板候选)。脏值不许凭空扩容词表。
String source = SOURCE_TARGET.equalsIgnoreCase(clip(request.getSource(), 16))
? SOURCE_TARGET : SOURCE_PUBLISH;
List<JdShopBrandEntity> inserts = new ArrayList<>();
List<JdShopBrandEntity> updates = new ArrayList<>();
for (JdShopBrandReportRequest.Brand brand : brands) {
if (brand == null || isBlank(brand.getBrandId())) {
continue;
}
String brandId = clip(brand.getBrandId(), MAX_BRAND_ID);
String brandName = clip(brand.getBrandName(), MAX_BRAND_NAME);
String company = clip(brand.getCompanySuffix(), MAX_COMPANY);
JdShopBrandEntity known = existing.get(brandId);
if (known == null) {
JdShopBrandEntity row = new JdShopBrandEntity();
row.setShopId(shopId);
row.setShopName(shopName);
row.setBrandId(brandId);
row.setBrandName(brandName);
row.setCompanySuffix(company);
row.setSource(source);
row.setLastSeenAt(now);
inserts.add(row);
} else {
known.setShopName(shopName);
known.setBrandName(brandName);
known.setCompanySuffix(company);
known.setLastSeenAt(now);
if (SOURCE_TARGET.equals(source)) {
// 成功上架用过的品牌把来源升级为 target(只在升级方向,不往回降级)。
known.setSource(SOURCE_TARGET);
}
updates.add(known);
}
}
for (JdShopBrandEntity row : inserts) {
mapper.insert(row);
existing.put(row.getBrandId(), row);
}
for (JdShopBrandEntity row : updates) {
mapper.updateById(row);
}
log.info("[jd-shop-brand] 上报落库 shopId={} shopName={} 新增={} 刷新={}",
shopId, shopName, inserts.size(), updates.size());
return inserts.size() + updates.size();
}
/** 读取该店铺缓存的品牌候选(按最近看到时间倒序;keyword 为名称模糊过滤)。 */
public JdShopBrandVo list(String shopId, String keyword, Integer limit) {
if (isBlank(shopId)) {
throw new BusinessException("缺少店铺 ID,无法读取品牌候选");
}
String sid = clip(shopId, MAX_SHOP_ID);
int size = limit == null || limit <= 0 ? DEFAULT_LIMIT : Math.min(limit, MAX_LIMIT);
LambdaQueryWrapper<JdShopBrandEntity> query = new LambdaQueryWrapper<JdShopBrandEntity>()
.eq(JdShopBrandEntity::getShopId, sid)
.orderByDesc(JdShopBrandEntity::getLastSeenAt)
.orderByDesc(JdShopBrandEntity::getId)
.last("limit " + size);
if (!isBlank(keyword)) {
query.like(JdShopBrandEntity::getBrandName, keyword.trim());
}
List<JdShopBrandVo.Item> items = new ArrayList<>();
for (JdShopBrandEntity row : mapper.selectList(query)) {
JdShopBrandVo.Item item = new JdShopBrandVo.Item();
item.setBrandId(row.getBrandId());
item.setBrandName(row.getBrandName());
item.setCompanySuffix(row.getCompanySuffix());
item.setLastSeenAt(row.getLastSeenAt() == null ? null : row.getLastSeenAt().format(TS));
items.add(item);
}
JdShopBrandVo vo = new JdShopBrandVo();
vo.setItems(items);
vo.setTotal(items.size());
return vo;
}
private static boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
private static String clip(String value, int max) {
if (value == null) {
return null;
}
String text = value.trim();
return text.length() <= max ? text : text.substring(0, max);
}
}
@@ -0,0 +1,28 @@
-- 京麦店铺品牌候选(客户端发布流程抓取上报,2026-11-28)
--
-- 背景:客户口径「品牌列表看看能不能获取下来,也可以支持自己输入」——
-- 目标店上架必须选该店授权品牌,而京麦品牌是**远程搜索**(输入关键词才出候选),
-- 没有可以离线拉取的全量清单。客户端在克隆页/新增页的品牌面板里每次都能抓到
-- 真实候选(文本形状「品牌名[品牌id]-公司名」),顺手回报落本表,前端目标品牌
-- 下拉即用真名候选(手输保留,不受候选为空影响)。
--
-- 口径:
-- * 一行=「店铺 × 品牌 id」;uk(shop_id, brand_id) 保证幂等,重复抓到只刷新时间与文本;
-- * brand_id 存字符串:真机里「无品牌」是负数 id(-1),「无」是 1343010,不按数字排序;
-- * company_suffix 存候选里「-」之后的公司名,仅为区分同名不同公司的品牌,不参与判定;
-- * 只存京麦平台公共品牌名,不含商品/公司业务数据 ⇒ 不做公司维隔离。
CREATE TABLE IF NOT EXISTS `biz_jd_shop_brand` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
`shop_id` VARCHAR(64) NOT NULL COMMENT '京麦 venderId(店铺 ID)',
`shop_name` VARCHAR(128) DEFAULT NULL COMMENT '抓取时店铺展示名(仅供排查)',
`brand_id` VARCHAR(32) NOT NULL COMMENT '京麦品牌 id(可为负,如「无品牌」=-1)',
`brand_name` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '品牌名(候选文本 [id] 之前的部分)',
`company_suffix` VARCHAR(255) DEFAULT NULL COMMENT '候选文本 [id]- 之后的公司名(仅区分同名品牌)',
`source` VARCHAR(16) NOT NULL DEFAULT 'publish' COMMENT '来源:publish=发布流程抓到;target=成功上架的目标品牌',
`last_seen_at` DATETIME NOT NULL COMMENT '最近一次在真机候选里看到的时间',
`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_jd_shop_brand` (`shop_id`, `brand_id`),
KEY `idx_jd_shop_brand_name` (`shop_id`, `brand_name`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '京麦店铺品牌候选(客户端发布流程上报)';
@@ -0,0 +1,170 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdShopBrandMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdShopBrandReportRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdShopBrandEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdShopBrandVo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 京麦店铺品牌候选(V220,2026-11-28):增量幂等上报 + 目标品牌下拉读取。
*
* <p>判据:缺店铺 ID/空候选一律拒且**不碰库**(空候选不许被当成「这家店没品牌」去清空);
* 同 shop_id+brand_id 二次上报只刷新文本与时间、不新增行(京麦候选是搜索碎片,整替换会
* 丢以前抓到的品牌);缺 brand_id 的条目跳过但其余照写;负 id(「无品牌」=-1)按字符串
* 原样存;读取按最近时间倒序、keyword 走品牌名模糊。</p>
*/
class JdShopBrandServiceTest {
private final JdShopBrandMapper mapper = mock(JdShopBrandMapper.class);
private final JdShopBrandService service = new JdShopBrandService(mapper);
@BeforeAll
static void initTableInfo() {
// 读侧与 upsert 前查重都用 lambda 列引用,裸单测 JVM 里不初始化就解析不了。
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, JdShopBrandEntity.class);
}
private static JdShopBrandReportRequest request(String shopId, String... brandPairs) {
JdShopBrandReportRequest body = new JdShopBrandReportRequest();
body.setShopId(shopId);
body.setShopName("家居日用数据库店");
List<JdShopBrandReportRequest.Brand> brands = new java.util.ArrayList<>();
for (int i = 0; i + 1 < brandPairs.length; i += 2) {
JdShopBrandReportRequest.Brand brand = new JdShopBrandReportRequest.Brand();
brand.setBrandId(brandPairs[i]);
brand.setBrandName(brandPairs[i + 1]);
brands.add(brand);
}
body.setBrands(brands);
return body;
}
@Test
void 缺店铺ID直接拒且不碰库() {
JdShopBrandReportRequest body = request(" ");
assertThrows(BusinessException.class, () -> service.report(body));
assertThrows(BusinessException.class, () -> service.report(null));
verifyNoInteractions(mapper);
}
@Test
void 空候选不许清空已有记录() {
JdShopBrandReportRequest body = new JdShopBrandReportRequest();
body.setShopId("228346061");
body.setBrands(List.of());
assertThrows(BusinessException.class, () -> service.report(body));
verifyNoInteractions(mapper);
}
@Test
void 首次上报全部新增且负id原样存() {
when(mapper.selectList(any())).thenReturn(List.of());
int saved = service.report(request("228346061", "1343010", "无", "-1", "无品牌"));
ArgumentCaptor<JdShopBrandEntity> captor = ArgumentCaptor.forClass(JdShopBrandEntity.class);
verify(mapper, times(2)).insert(captor.capture());
verify(mapper, never()).updateById(any(JdShopBrandEntity.class));
List<JdShopBrandEntity> rows = captor.getAllValues();
assertEquals(2, saved);
assertEquals("1343010", rows.get(0).getBrandId());
assertEquals("无", rows.get(0).getBrandName());
assertEquals("-1", rows.get(1).getBrandId(), "「无品牌」的负 id 必须原样保留,不许转数字");
assertEquals("publish", rows.get(0).getSource());
}
@Test
void 二次上报同品牌只刷新不新增行() {
JdShopBrandEntity known = new JdShopBrandEntity();
known.setId(7L);
known.setShopId("228346061");
known.setBrandId("1343010");
known.setBrandName("旧名");
when(mapper.selectList(any())).thenReturn(List.of(known));
int saved = service.report(request("228346061", "1343010", "无"));
ArgumentCaptor<JdShopBrandEntity> captor = ArgumentCaptor.forClass(JdShopBrandEntity.class);
verify(mapper, times(1)).updateById(captor.capture());
verify(mapper, never()).insert(any(JdShopBrandEntity.class));
assertEquals(1, saved);
assertEquals("无", captor.getValue().getBrandName());
assertEquals(7L, captor.getValue().getId());
assertTrue(captor.getValue().getLastSeenAt() != null);
}
@Test
void 缺品牌id的条目跳过其余照写() {
when(mapper.selectList(any())).thenReturn(List.of());
JdShopBrandReportRequest body = new JdShopBrandReportRequest();
body.setShopId("228346061");
JdShopBrandReportRequest.Brand empty = new JdShopBrandReportRequest.Brand();
empty.setBrandId(" ");
JdShopBrandReportRequest.Brand ok = new JdShopBrandReportRequest.Brand();
ok.setBrandId("88");
ok.setBrandName("某某牌");
body.setBrands(List.of(empty, ok));
assertEquals(1, service.report(body));
verify(mapper, times(1)).insert(any(JdShopBrandEntity.class));
}
@Test
void 超上限拒绝() {
JdShopBrandReportRequest body = new JdShopBrandReportRequest();
body.setShopId("228346061");
List<JdShopBrandReportRequest.Brand> brands = new java.util.ArrayList<>();
for (int i = 0; i < JdShopBrandService.MAX_REPORT_BRANDS + 1; i++) {
JdShopBrandReportRequest.Brand brand = new JdShopBrandReportRequest.Brand();
brand.setBrandId(String.valueOf(i));
brands.add(brand);
}
body.setBrands(brands);
assertThrows(BusinessException.class, () -> service.report(body));
verifyNoInteractions(mapper);
}
@Test
void 读取按店铺过滤并回填字段() {
JdShopBrandEntity row = new JdShopBrandEntity();
row.setBrandId("1343010");
row.setBrandName("无");
row.setCompanySuffix("某某贸易有限公司");
row.setLastSeenAt(java.time.LocalDateTime.of(2026, 11, 28, 14, 0));
when(mapper.selectList(any())).thenReturn(List.of(row));
JdShopBrandVo vo = service.list("228346061", null, 10);
assertEquals(1, vo.getTotal());
assertEquals("无", vo.getItems().get(0).getBrandName());
assertEquals("1343010", vo.getItems().get(0).getBrandId());
assertEquals("2026-11-28 14:00:00", vo.getItems().get(0).getLastSeenAt());
}
@Test
void 读取缺店铺ID拒绝() {
assertThrows(BusinessException.class, () -> service.list("", null, 10));
verifyNoInteractions(mapper);
}
}
@@ -102,8 +102,13 @@ class TaskFailureCategoryGuardrailTest {
* 一处({@code jdGroupShopMapper.updateById(row)},JdGroupShopEntity 无 ALWAYS 字段;
* row 是 selectOne 读回的新鲜行,只覆写 shop_name 一列,不涉抹列风险)。审过后登记基线。
* 该笔当时只点 jd 点名包没跑整仓整量、账本漏记,发版前整量抓到补记。
*
* <p>164 → 165:2026-11-28 京麦品牌候选 {@code JdShopBrandService.report} 增量 upsert
* 一处({@code mapper.updateById(row)},JdShopBrandEntity 无 @TableField/ALWAYS 列;
* row 是 selectByShop 读回的新鲜实体,只覆写 shopName/brandName/companySuffix/lastSeenAt
* 与 source 单向升级,不涉抹列风险)。审过后登记基线。
*/
private static final int REGISTERED_UPDATE_BY_ID_SITES = 164;
private static final int REGISTERED_UPDATE_BY_ID_SITES = 165;
@Test
void 任务失败文案写点必须同笔写分类列() {
+82 -6
View File
@@ -16,11 +16,18 @@ import {
fetchJdPublishHistory,
fetchJdPublishProducts,
fetchJdPublishTaskProgressBatch,
fetchJdShopBrands,
interruptJdPublishTask,
retryJdPublishBrand,
type JdPublishHistoryItemVo,
type JdPublishProductVo,
} from '@/shared/api/types/modules/jd-publish'
import {
brandOptionsFromRows,
brandOptionsHint,
filterBrandOptions,
type JdShopBrandOption,
} from '@/pages/jd/jd-brand-options'
import { retryClientTask } from '@/shared/api/task-retry'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { ensureJdLogin, markJdLoginExpired } from '@/shared/stores/jd-login-autoflow'
@@ -170,6 +177,56 @@ function isValidBrand(name: string) {
return name.length > 0 && name.length <= TARGET_BRAND_MAX
}
// ---- 目标品牌候选(2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」)----
/** 候选来自客户端在发布表单里抓到的真名品牌(服务端 `biz_jd_shop_brand` 增量积累)。
* 京麦品牌只能按关键词远程搜索,没有全量清单,所以这里展示的是「本店见过的」那批;
* **手输始终保留**——列表空、读取失败都不拦建单(品牌是否可用由客户端回读校验兜底)。 */
const BRAND_OPTIONS_LIMIT = 200
const brandOptions = ref<JdShopBrandOption[]>([])
const brandOptionsLoading = ref(false)
const brandOptionsFailed = ref(false)
/** 候选归属店铺:优先京麦当前登录店(真正的发布目标),其次来源店(单店克隆的上架目标)。 */
const brandShopId = computed(() => {
const guard = shopGuard.value
const target = guard.state === 'cross' || guard.state === 'multi' ? guard.target : null
const fromGuard = guard.state === 'undetected' || guard.state === 'match' ? guard.expected.shopId : ''
return currentShop.value?.shopId || target?.shopId || fromGuard || ''
})
const brandHint = computed(() => brandOptionsHint({
loading: brandOptionsLoading.value,
failed: brandOptionsFailed.value,
count: brandOptions.value.length,
}))
async function loadBrandOptions(shopId: string) {
if (!shopId) {
brandOptions.value = []
brandOptionsFailed.value = false
return
}
brandOptionsLoading.value = true
brandOptionsFailed.value = false
try {
const vo = await fetchJdShopBrands(shopId, undefined, BRAND_OPTIONS_LIMIT)
brandOptions.value = brandOptionsFromRows(vo?.items)
} catch (error) {
// 候选只是输入便利:读不到就落一句灰字让客户直接手输,绝不拦建单。
brandOptions.value = []
brandOptionsFailed.value = true
console.warn('[jd-publish] 读取本店品牌候选失败:%s',
error instanceof Error ? error.message : String(error))
} finally {
brandOptionsLoading.value = false
}
}
/** 联想候选:本地过滤(候选是本店已积累的小集合,逐字符发请求只会让列表抖动)。 */
function queryBrandOptions(query: string, callback: (items: JdShopBrandOption[]) => void) {
callback(filterBrandOptions(brandOptions.value, query))
}
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
// ---- 本次上架到哪家店(2026-11-24 客户口径「软件怎么知道要上架哪一家店铺」)----
@@ -789,6 +846,10 @@ async function startPublish() {
}
}
// 目标品牌候选随「发布到哪家店」变:选分类/检测到京麦店后按店铺 id 拉一次本店历史品牌
// (挂载时可能还不知道店,watch 一拿到 id 就补拉;换店铺重新拉,旧店候选不许留在下拉里)。
watch(brandShopId, (shopId) => { void loadBrandOptions(shopId) }, { immediate: true })
onMounted(async () => {
const localName = (window.localStorage.getItem('username') || '').trim()
if (localName) username.value = localName
@@ -910,10 +971,19 @@ onUnmounted(() => {
<div class="category-block">
<label class="category-label" for="jd-publish-target-brand">目标品牌名称(必填)</label>
<input id="jd-publish-target-brand" v-model="targetBrandInput" class="target-brand-input" type="text"
required :aria-invalid="Boolean(targetBrandInput && !isValidBrand(targetBrandName))"
aria-describedby="jd-publish-brand-hint" placeholder="输入当前京麦店铺可用的品牌名称" />
<p id="jd-publish-brand-hint" class="category-hint">本次选中的商品统一使用此品牌。</p>
<!-- 2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」:联想列表给
客户端抓到过的本店真名品牌,**输入框照样能手输**(autocomplete 不拦自由文本)。 -->
<el-autocomplete id="jd-publish-target-brand" v-model="targetBrandInput"
:class="['target-brand-input', { 'target-brand-invalid': Boolean(targetBrandInput && !isValidBrand(targetBrandName)) }]"
:fetch-suggestions="queryBrandOptions" :trigger-on-focus="true" :debounce="0" value-key="brandName"
clearable required :aria-invalid="Boolean(targetBrandInput && !isValidBrand(targetBrandName))"
aria-describedby="jd-publish-brand-hint" placeholder="输入或选择当前京麦店铺可用的品牌名称">
<template #default="{ item }">
<span class="brand-option-name">{{ item.brandName }}</span>
<span v-if="item.companySuffix" class="brand-option-company">{{ item.companySuffix }}</span>
</template>
</el-autocomplete>
<p id="jd-publish-brand-hint" class="category-hint">本次选中的商品统一使用此品牌。{{ brandHint }}</p>
</div>
<button class="collect-btn" type="button" :disabled="submitDisabled" @click="startPublish">
@@ -1015,8 +1085,14 @@ onUnmounted(() => {
.product-head { display: flex; align-items: center; justify-content: space-between; }
.product-head .category-label { margin-bottom: 8px; }
.product-empty { padding: 18px 0; color: #5f6c85; font-size: 12px; text-align: center; }
.target-brand-input { box-sizing: border-box; width: 100%; padding: 8px 10px; border: 1px solid #3e4a62; border-radius: 6px; background: #232b3d; color: #c8d2e2; font: inherit; }
.target-brand-input[aria-invalid="true"] { border-color: #fca5a5; }
/* 目标品牌改成 el-autocomplete(2026-11-28):底色/边框落在 el-input 外壳上,
沿用改价输入框的深色口径;无效品牌名只在有输入时标红(空值是另一句错误)。 */
.target-brand-input { display: block; width: 100%; }
.target-brand-input :deep(.el-input__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
.target-brand-input :deep(.el-input__inner) { color: #c8d2e2; }
.target-brand-invalid :deep(.el-input__wrapper) { box-shadow: 0 0 0 1px #fca5a5 inset; }
.brand-option-name { margin-right: 8px; }
.brand-option-company { color: #8b97a9; font-size: 12px; }
.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; }
@@ -0,0 +1,99 @@
/**
* 目标品牌候选(2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」)。
*
* 京麦品牌是**按关键词远程搜索**的(输入才出候选),没有可离线拉取的全量清单:客户端每次
* 在发布表单的品牌面板里看到真实候选(文本形状 `品牌名[品牌id]-公司名`)就增量上报
* `/api/jd-shop-brands`,本页把这些真名候选做成目标品牌输入的联想列表。
*
* 三条边界:
* 1. **手输始终保留**:候选只是便利通道,列表空/读不到都不影响建单(品牌是否可用最终由
* 客户端在京麦表单里回读校验,不是靠这份缓存);
* 2. **只展示品牌名**:京麦 id(可为负,「无品牌」=-1)只用于服务端去重,不上屏、不进建单
* 载荷(建单要的是 `targetBrandName`);
* 3. 同名不同公司靠 `companySuffix` 区分,展示成副标题而不是品牌名的一部分。
*
* 本文件是纯函数(node --test 直测):只产选项与中文文案,取数/渲染由页面做。
*/
/** 下拉选项(服务端 `JdShopBrandVo.items` 裁剪后的形状)。 */
export interface JdShopBrandOption {
brandId: string;
brandName: string;
companySuffix: string;
lastSeenAt: string;
}
/** 服务端候选行的最小子集(页面直接传 VO 进 normalized 即可)。 */
export interface JdShopBrandSource {
brandId?: string;
brandName?: string;
companySuffix?: string;
lastSeenAt?: string;
}
/** 候选读取的状态文案:加载中 / 有候选 / 还没抓到过 / 读取失败。 */
export const BRAND_OPTIONS_LOADING_HINT = '正在读取本店历史品牌…';
export const BRAND_OPTIONS_READY_HINT = '可直接从本店历史品牌里选,也可以手动输入品牌名。';
export const BRAND_OPTIONS_EMPTY_HINT =
'本店还没有历史品牌记录(客户端成功发布过一次后会自动积累),请直接手动输入京麦里的品牌名称。';
export const BRAND_OPTIONS_UNAVAILABLE_HINT = '暂时读不到本店历史品牌,请直接手动输入京麦里的品牌名称。';
function text(value: unknown): string {
return String(value ?? '').trim();
}
/**
* 服务端行 → 选项:丢掉没有品牌名的行(名字是唯一可展示、可手输对齐的字段),
* 按 `brandId`(缺 id 时按品牌名)去重,保留服务端给的顺序(=最近看到时间倒序)。
*/
export function brandOptionsFromRows(rows: JdShopBrandSource[] | null | undefined): JdShopBrandOption[] {
const seen = new Set<string>();
const options: JdShopBrandOption[] = [];
for (const raw of rows ?? []) {
const brandName = text(raw?.brandName);
if (!brandName) continue;
const brandId = text(raw?.brandId);
const key = brandId || `name:${brandName}`;
if (seen.has(key)) continue;
seen.add(key);
options.push({
brandId,
brandName,
companySuffix: text(raw?.companySuffix),
lastSeenAt: text(raw?.lastSeenAt),
});
}
return options;
}
/**
* 关键词过滤(空关键词=全量):品牌名与公司名都参与匹配,大小写不敏感。
* 本地过滤而不是远程搜索——候选是本店已积累的小集合(服务端上限 200 条),
* 输入时逐字符发请求只会让联想列表抖动。
*/
export function filterBrandOptions(
options: JdShopBrandOption[] | null | undefined,
keyword: string | null | undefined,
): JdShopBrandOption[] {
const rows = options ?? [];
const needle = text(keyword).toLowerCase();
if (!needle) return rows;
return rows.filter((option) => option.brandName.toLowerCase().includes(needle)
|| option.companySuffix.toLowerCase().includes(needle));
}
/** 下拉行主文案:品牌名;有公司名时补一行副标题(同名不同公司靠它区分)。 */
export function brandOptionLabel(option: JdShopBrandOption): string {
return option.companySuffix ? `${option.brandName} · ${option.companySuffix}` : option.brandName;
}
/** 输入框下方那句灰字:四种状态各一句,切状态不出现空串(空串会让客户以为功能没做)。 */
export function brandOptionsHint(input: {
loading?: boolean;
failed?: boolean;
count?: number;
}): string {
if (input.failed) return BRAND_OPTIONS_UNAVAILABLE_HINT;
if (input.loading) return BRAND_OPTIONS_LOADING_HINT;
return (input.count ?? 0) > 0 ? BRAND_OPTIONS_READY_HINT : BRAND_OPTIONS_EMPTY_HINT;
}
+4
View File
@@ -250,6 +250,10 @@ export const API_ENDPOINTS = {
onShelf: '/api/jd-publish/on-shelf',
/** 标记/取消标记已下架(按商品整组腾额度) */
markDelisted: '/api/jd-publish/items/{itemId}/delisted',
/** 京麦店铺品牌候选(2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」):
* 客户端在发布表单的品牌面板里抓到真名候选就增量上报,用户端目标品牌输入框读它做联想;
* 京麦品牌只能按关键词远程搜索,没有可离线拉取的全量清单。 */
shopBrands: '/api/jd-shop-brands',
},
userSecret: {
bundle: '/api/user-secrets',
@@ -73,6 +73,41 @@ export function retryJdPublishBrand(taskId: number, targetBrandName: string, res
))
}
// ---------------------------------------------------------------------------
// 目标品牌候选(2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」):
// 京麦品牌只能按关键词远程搜索、没有全量清单,所以候选由客户端在发布表单里抓到后增量上报
// (`POST /api/jd-shop-brands`,shop_id+brand_id 幂等 upsert);本页只读它做输入联想,
// 手输始终保留——列表空/读不到都不影响建单。
// ---------------------------------------------------------------------------
/** 候选行:`brandId` 是京麦 id(可为负,「无品牌」=-1;手输品牌记作 `name:<品牌名>`),只用于去重。 */
export interface JdShopBrandItemVo {
brandId?: string;
brandName?: string;
companySuffix?: string;
lastSeenAt?: string;
}
export interface JdShopBrandListVo {
items?: JdShopBrandItemVo[];
total?: number;
}
/**
* 读取某店铺已积累的品牌候选(按最近看到时间倒序;keyword 走品牌名模糊)。
* 空列表只表示「这家店还没抓到过候选」,调用方必须仍允许手输。
*/
export function fetchJdShopBrands(shopId: string, keyword?: string, limit = 200) {
const params: Record<string, unknown> = { shopId, limit };
if (keyword) params.keyword = keyword;
return unwrapJavaResponse(
get<JavaApiResponse<JdShopBrandListVo>>(
buildJavaUrl(API_ENDPOINTS.jdPublish.shopBrands),
{ params },
),
);
}
// ---------------------------------------------------------------------------
// 选品分页(2026-11-25 作用域):服务端回归本账号可见数据权限分组下的分类归属商品行
// (同组同事采集的也在内;跨公司/跨组不可见——与分类下拉/徽标同源)。
+3 -1
View File
@@ -352,7 +352,9 @@ test('test_endpoints_frozen_snapshot', () => {
"deleteTask": "/api/jd-publish/tasks/{taskId}",
// 2026-11-25 额度改口径:在架清单+标记已下架腾额度(JdOnShelfPanel 唯一落点)。
"onShelf": "/api/jd-publish/on-shelf",
"markDelisted": "/api/jd-publish/items/{itemId}/delisted"
"markDelisted": "/api/jd-publish/items/{itemId}/delisted",
// 2026-11-28 目标品牌候选:客户端发布流程抓到真名候选增量上报,用户端下拉联想读它。
"shopBrands": "/api/jd-shop-brands"
},
"userSecret": {
"bundle": "/api/user-secrets",
+118
View File
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import {
BRAND_OPTIONS_EMPTY_HINT,
BRAND_OPTIONS_LOADING_HINT,
BRAND_OPTIONS_READY_HINT,
BRAND_OPTIONS_UNAVAILABLE_HINT,
brandOptionLabel,
brandOptionsFromRows,
brandOptionsHint,
filterBrandOptions,
} from '../src/pages/jd/jd-brand-options.ts'
/** 目标品牌候选(2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」):
*
* 京麦品牌只能按关键词远程搜索、没有全量清单,候选是客户端在发布表单里抓到的本店真名品牌
* (服务端 `biz_jd_shop_brand` 增量积累)。本文件钉三件事:
* 1. 服务端行 → 下拉选项的裁剪(空名丢弃、按 id 去重、id 与公司名分字段);
* 2. 本地过滤只影响「联想列表」,不影响输入框里的自由文本(手输始终可用);
* 3. 四种状态的灰字文案都不为空(空串会让客户以为功能没做)。
*/
test('服务端行转选项:空品牌名丢弃,同 id 只留第一条', () => {
const options = brandOptionsFromRows([
{ brandId: '1343010', brandName: ' 无 ', companySuffix: ' 某某贸易有限公司 ', lastSeenAt: '2026-11-28 14:00:00' },
{ brandId: '1343010', brandName: '无(重复页签)' },
{ brandId: '-1', brandName: '无品牌' },
{ brandId: '9', brandName: ' ' },
{ brandName: '没有 id 但有名' },
])
assert.deepEqual(options.map((row) => row.brandName), ['无', '无品牌', '没有 id 但有名'])
assert.equal(options[0].brandId, '1343010')
assert.equal(options[0].companySuffix, '某某贸易有限公司')
assert.equal(options[0].lastSeenAt, '2026-11-28 14:00:00')
// 「无品牌」的负 id 必须原样保留(只用于去重,不参与上屏)。
assert.equal(options[1].brandId, '-1')
assert.equal(options[1].companySuffix, '')
})
test('没有 id 的行按名字去重,不会整批丢', () => {
const options = brandOptionsFromRows([
{ brandName: '手输品牌' }, { brandName: '手输品牌' }, { brandName: 'name:前缀形状' },
])
assert.deepEqual(options.map((row) => row.brandName), ['手输品牌', 'name:前缀形状'])
})
test('空输入与 null 安全:没有候选就是空列表,不抛', () => {
assert.deepEqual(brandOptionsFromRows(null), [])
assert.deepEqual(brandOptionsFromRows(undefined), [])
assert.deepEqual(brandOptionsFromRows([]), [])
assert.deepEqual(filterBrandOptions(undefined, '无'), [])
})
test('过滤:空关键词出全量,品牌名与公司名都参与匹配且大小写不敏感', () => {
const options = brandOptionsFromRows([
{ brandId: '1', brandName: 'OTHER/其他', companySuffix: '甲公司' },
{ brandId: '2', brandName: '铜精灵', companySuffix: '某某铜业' },
{ brandId: '3', brandName: '无' },
])
assert.equal(filterBrandOptions(options, '').length, 3)
assert.equal(filterBrandOptions(options, ' ').length, 3)
assert.deepEqual(filterBrandOptions(options, 'other').map((row) => row.brandName), ['OTHER/其他'])
assert.deepEqual(filterBrandOptions(options, '铜').map((row) => row.brandName), ['铜精灵'])
assert.deepEqual(filterBrandOptions(options, '铜业').map((row) => row.brandName), ['铜精灵'])
assert.deepEqual(filterBrandOptions(options, '不存在'), [])
})
test('下拉行文案:有公司名时补副标题,没有就只出品牌名', () => {
const [withCompany, withoutCompany] = brandOptionsFromRows([
{ brandId: '1', brandName: '无', companySuffix: '某某贸易有限公司' },
{ brandId: '2', brandName: '无品牌' },
])
assert.equal(brandOptionLabel(withCompany), '无 · 某某贸易有限公司')
assert.equal(brandOptionLabel(withoutCompany), '无品牌')
})
test('四种状态各有非空灰字:加载中/有候选/还没抓到/读取失败', () => {
assert.equal(brandOptionsHint({ loading: true, count: 3 }), BRAND_OPTIONS_LOADING_HINT)
assert.equal(brandOptionsHint({ count: 3 }), BRAND_OPTIONS_READY_HINT)
assert.equal(brandOptionsHint({ count: 0 }), BRAND_OPTIONS_EMPTY_HINT)
assert.equal(brandOptionsHint({ failed: true }), BRAND_OPTIONS_UNAVAILABLE_HINT)
// 失败优先于计数(读失败时候选被清空,不能再报「有候选」)。
assert.equal(brandOptionsHint({ failed: true, count: 5 }), BRAND_OPTIONS_UNAVAILABLE_HINT)
for (const hint of [BRAND_OPTIONS_LOADING_HINT, BRAND_OPTIONS_READY_HINT,
BRAND_OPTIONS_EMPTY_HINT, BRAND_OPTIONS_UNAVAILABLE_HINT]) {
assert.ok(hint.trim().length > 0)
}
// 空候选那句必须点明「还能手输」,否则客户会以为必须先有候选才能建单。
assert.ok(BRAND_OPTIONS_EMPTY_HINT.includes('手动输入'))
})
// ---------------------------------------------------------------------------
// 源码绊线(B113-01 同族):本页的目标品牌必须是**联想输入框**而不是只读下拉——
// el-select 的 filterable 在「打字但没回车」时 modelValue 仍是空,客户会以为填了品牌却
// 建不了单;el-autocomplete 的输入框值就是 modelValue,手输永远生效。
// ---------------------------------------------------------------------------
const TAB = join(process.cwd(), 'src/pages/jd/JdPublishTab.vue')
test('目标品牌用 el-autocomplete 联想+手输,不是 el-select 纯下拉', () => {
assert.ok(existsSync(TAB), `商品上架页尚未落地:${TAB}`)
const source = readFileSync(TAB, 'utf8')
assert.ok(source.includes('<el-autocomplete'), '目标品牌输入框必须是 el-autocomplete(联想+自由文本)')
assert.ok(source.includes(':fetch-suggestions="queryBrandOptions"'), '联想候选必须走 queryBrandOptions(本地过滤)')
assert.ok(source.includes('value-key="brandName"'), '选中候选时只能回填品牌名——京麦 id 不进建单载荷')
assert.ok(!source.includes('<el-select v-model="targetBrandInput"'),
'不许改成 el-select:filterable 在未回车时 modelValue 为空,手输会静默丢失')
})
test('候选按店铺拉取:watch 店铺 id,换店铺不留旧候选', () => {
const source = readFileSync(TAB, 'utf8')
assert.ok(source.includes('watch(brandShopId'), '品牌候选必须随发布目标店铺变化重拉(immediate,挂载即拉)')
assert.ok(source.includes('fetchJdShopBrands'), '候选唯一来源是 /api/jd-shop-brands(不许自拼 URL)')
assert.ok(source.includes('brandOptions = ref'), '候选落页面 ref,联想只在本地过滤')
})
@@ -10,13 +10,14 @@ import {
const api = vi.hoisted(() => ({
create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(),
history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(),
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(), shop: vi.fn(),
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(), shop: vi.fn(), brands: vi.fn(),
}))
vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups }))
vi.mock('@/shared/api/types/modules/jd-publish', () => ({
createJdPublishTask: api.create,
retryJdPublishBrand: api.retryBrand,
fetchJdShopBrands: api.brands,
activateJdPublishTask: api.activate,
fetchJdPublishDashboard: api.dashboard,
fetchJdPublishHistory: api.history,
@@ -66,6 +67,13 @@ async function mountPage() {
ElSelect: { props: ['modelValue'], emits: ['update:modelValue', 'change'], template: '<div><slot /></div>' },
ElPagination: { emits: ['current-change'], template: '<div />' }, ElInputNumber: true,
ElDrawer: { props: ['modelValue'], template: '<div v-if="modelValue"><slot /></div>' },
// 目标品牌输入框是 el-autocomplete(2026-11-28 品牌候选联想):替身只要「真 input+
// v-model 双向」,联想列表本身由 jd-brand-options 纯函数用例与源码绊线覆盖。
ElAutocomplete: {
props: ['modelValue', 'fetchSuggestions', 'valueKey', 'triggerOnFocus', 'debounce', 'clearable'],
emits: ['update:modelValue'],
template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />',
},
},
directives: { loading: () => undefined },
},
@@ -76,7 +84,7 @@ async function mountPage() {
async function startPublish(page: VueWrapper, brand = ' 示例品牌 ') {
// 2026-11-26 晚客户口径「商品信息不要显示,选分类上架就行」:选中分类即整分类上架,无逐行勾选步骤。
await page.get('.target-brand-input').setValue(brand)
await page.get('#jd-publish-target-brand').setValue(brand)
await page.get('.collect-btn').trigger('click')
await flushPromises()
}
@@ -92,6 +100,7 @@ beforeEach(() => {
api.progress.mockResolvedValue(batch(row('PENDING', 0)))
api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol, enqueue_json: api.enqueue })
api.protocol.mockResolvedValue(3)
api.brands.mockResolvedValue({ items: [], total: 0 })
api.alert.mockResolvedValue(undefined)
api.enqueue.mockResolvedValue({ success: true })
api.retry.mockResolvedValue(null)
@@ -184,7 +193,7 @@ it('选分类=自动分页拉全本分类全部商品并整批建单,商品
expect(page.find('.product-pager').exists()).toBe(false)
expect(page.find('.product-select-all').exists()).toBe(false)
expect(page.get('.collect-btn').text()).toContain('上架本分类 3 个商品')
await page.get('.target-brand-input').setValue('示例品牌')
await page.get('#jd-publish-target-brand').setValue('示例品牌')
await page.get('.collect-btn').trigger('click')
await flushPromises()
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23, 24, 25], { mode: 'none' }, '示例品牌')
@@ -389,7 +398,7 @@ it('协议 3 的本机遇跨店只给升级提示,一条都不建单', async (
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
api.protocol.mockResolvedValue(3)
const page = await mountPage()
await page.get('.target-brand-input').setValue('示例品牌')
await page.get('#jd-publish-target-brand').setValue('示例品牌')
// 挂载即自动检测(2026-11-28 口径):检测到异店=跨店档,协议 <4 按钮直接禁用+升级提示
await flushPromises()
expect(api.shop).toHaveBeenCalledOnce()
@@ -406,7 +415,7 @@ it('协议 4 跨店:挂载自动检测显形目标店与琥珀说明,直接
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
api.protocol.mockResolvedValue(4)
const page = await mountPage()
await page.get('.target-brand-input').setValue('示例品牌')
await page.get('#jd-publish-target-brand').setValue('示例品牌')
await flushPromises()
expect(page.text()).toContain('跨店上架')
@@ -436,7 +445,7 @@ it('多店未检测京麦:不拦建单,带 targetFromLogin 且不带目标
api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol, enqueue_json: api.enqueue })
api.protocol.mockResolvedValue(4)
const page = await mountPage()
await page.get('.target-brand-input').setValue('示例品牌')
await page.get('#jd-publish-target-brand').setValue('示例品牌')
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(false)
// 2026-11-28 客户口径「不存在发错店的情况」:未检测档不再出琥珀警告小字(含「发错店判死」句)
expect(page.text()).not.toContain('将按京麦当前登录店铺新建上架')
@@ -456,7 +465,7 @@ it('多店未检测且协议 3:仍拦(NEW 任务只投给 v4+ 客户端,
api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol, enqueue_json: api.enqueue })
api.protocol.mockResolvedValue(3)
const page = await mountPage()
await page.get('.target-brand-input').setValue('示例品牌')
await page.get('#jd-publish-target-brand').setValue('示例品牌')
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(true)
expect(page.text()).toContain('升级')
await startPublish(page)
@@ -522,3 +531,55 @@ it('分类非空时不出空态告警(v-if 不成立),常驻解释句已
expect(page.text()).not.toContain('分类由管理员在后台「京东数据库」维护')
})
// ---- 目标品牌候选(2026-11-28 客户口径「品牌看看能不能获取下来,也可以支持自己输入」)----
// 候选=客户端在发布表单里抓到的本店真名品牌(服务端 biz_jd_shop_brand 增量积累);
// 输入框是联想(el-autocomplete),**手输始终保留**——候选空/读取失败都不拦建单。
it('检测到京麦店后按店铺 id 拉本店品牌候选,灰字点名可以选也可以手输', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
api.brands.mockResolvedValue({ items: [
{ brandId: '1343010', brandName: '无', companySuffix: '某某贸易有限公司', lastSeenAt: '2026-11-28 14:00:00' },
{ brandId: '-1', brandName: '无品牌', lastSeenAt: '2026-11-27 09:00:00' },
], total: 2 })
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await flushPromises()
expect(api.brands).toHaveBeenCalledExactlyOnceWith('228346061', undefined, 200)
const hint = page.get('#jd-publish-brand-hint').text()
expect(hint).toContain('本次选中的商品统一使用此品牌')
expect(hint).toContain('可直接从本店历史品牌里选,也可以手动输入品牌名')
// 品牌 id 只用于服务端去重,不上屏(客户口径「shopId 啥的不要搞复杂」同款)。
expect(hint).not.toContain('1343010')
})
it('品牌候选读不到不拦建单:灰字点名手输,手输品牌原样进建单', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
api.brands.mockRejectedValue(new Error('网络断了'))
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await flushPromises()
expect(page.get('#jd-publish-brand-hint').text()).toContain('请直接手动输入京麦里的品牌名称')
await startPublish(page, ' 无品牌 ')
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '无品牌')
})
it('本店还没有候选时灰字点名「成功发布过一次后会自动积累」,手输照样可用', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await flushPromises()
expect(page.get('#jd-publish-brand-hint').text())
.toContain('客户端成功发布过一次后会自动积累')
await startPublish(page, '无')
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '无')
})