feat(keywordshare): 五国关键词共享后端模块(桌面工具网页化)
词本体直接读写主库既有 keyword_share 表(已是全量词库),使用状态 keyword_usage,留痕 keyword_add_log/keyword_delete_log;不建新表、无 SQLite。 九个端点挂 /api/keyword-share,权限键 keyword-share,companyId 服务端取。 列表排序对齐桌面版:已使用在前、按 used_time 升序;添加查重跳过+留痕+ 自动标记已使用;随机抽词从未使用池。 SQL 账本 99→115(16 条新写语句)、select 账本 67→78(11 条),逐条点入 NOT_MIGRATED;ApiGuardCoverageAuditor METHOD_GUARDED_PATHS 登记 /api/keyword-share(9 端点全部 handler 内 requireConsolePageAccess 把门)。 FILTER_* 命名避开任务状态词表棘轮。
This commit is contained in:
@@ -101,7 +101,12 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
* 往里塞一条没设防的路径会红。
|
||||
*/
|
||||
static final Set<String> METHOD_GUARDED_PATHS = Set.of(
|
||||
"/api/client/credentials");
|
||||
"/api/client/credentials",
|
||||
// 五国关键词共享(2026-10-23 keywordshare 模块):9 个端点全部在 handler 体内经
|
||||
// requireKeywordShareAccess → adminAuthSupport.requireUser + PermissionMenuService
|
||||
// .requireConsolePageAccess(operator, …, "keyword-share") 逐请求把门,且 company_id
|
||||
// 一律服务端取、不收请求参数——第二道门已到位,只欠进 USER_TOOL_PREFIXES 第一道门。
|
||||
"/api/keyword-share");
|
||||
|
||||
/**
|
||||
* 待收欠账:数据按 user_id 归属、却既不进守卫名单也没有 require* 的前缀。
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.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.keywordshare.model.dto.KeywordShareAddRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareDeleteRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordUsageBatchRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareAddResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareDeleteResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareFiltersVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareLogPageVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareMarkResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordSharePageVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareStatsGroupedVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareUnmarkResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.service.KeywordShareService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
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 org.springframework.web.bind.annotation.DeleteMapping;
|
||||
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.List;
|
||||
|
||||
/**
|
||||
* 五国关键词共享(桌面 Tkinter 工具的 web 化)。
|
||||
*
|
||||
* <p>company_id 一律服务端从当前登录人取,前端不传、也不接受传参;
|
||||
* 页面权限键 {@code keyword-share}(后台菜单 column_key,经 requireConsolePageAccess 把门)。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/keyword-share")
|
||||
@Tag(name = "五国关键词共享", description = "五国关键词共享词库的查询、增删、使用标记与团队共享记录。数据按公司隔离。")
|
||||
public class KeywordShareController {
|
||||
|
||||
/** 后台菜单权限键(column_key)。 */
|
||||
private static final String PERMISSION_KEY = "keyword-share";
|
||||
private static final String DENIAL_MESSAGE = "无权访问五国关键词共享";
|
||||
|
||||
private final KeywordShareService keywordShareService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
|
||||
@GetMapping("/keywords")
|
||||
@Operation(summary = "分页查询关键词", description = "按国家/类目/搜索/使用状态筛选,未使用在前、已使用按使用时间升序。")
|
||||
public ApiResponse<KeywordSharePageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "一级类目") @RequestParam(name = "category", required = false) String category,
|
||||
@Parameter(description = "二级类目") @RequestParam(name = "subCategory", required = false) String subCategory,
|
||||
@Parameter(description = "三级类目") @RequestParam(name = "categoryL3", required = false) String categoryL3,
|
||||
@Parameter(description = "四级类目") @RequestParam(name = "categoryL4", required = false) String categoryL4,
|
||||
@Parameter(description = "关键词/中文模糊搜索") @RequestParam(name = "search", required = false) String search,
|
||||
@Parameter(description = "使用状态:all|used|unused") @RequestParam(name = "status", required = false) String status,
|
||||
@Parameter(description = "已使用时间范围(天):1=今天,7/30/90/180/360;0或不传=全部")
|
||||
@RequestParam(name = "usedDays", required = false) Integer usedDays,
|
||||
@Parameter(description = "仅看我使用") @RequestParam(name = "onlyMine", required = false) Boolean onlyMine,
|
||||
@Parameter(description = "页码(1 起)") @RequestParam(name = "page", required = false) Long page,
|
||||
@Parameter(description = "每页数量(默认 200,上限 500)") @RequestParam(name = "size", required = false) Long size) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.page(operator.companyId(), operator.userName(),
|
||||
country, category, subCategory, categoryL3, categoryL4, search,
|
||||
status, usedDays, Boolean.TRUE.equals(onlyMine), page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/filters")
|
||||
@Operation(summary = "查询筛选名册", description = "国家列表与一级→二级→三级→四级类目树,按当前公司 DISTINCT。")
|
||||
public ApiResponse<KeywordShareFiltersVo> filters(HttpServletRequest request) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.filters(operator.companyId()));
|
||||
}
|
||||
|
||||
@GetMapping("/stats-grouped")
|
||||
@Operation(summary = "词库统计", description = "国家与一级/二级/三级类目的分布计数(统计弹窗)。")
|
||||
public ApiResponse<KeywordShareStatsGroupedVo> statsGrouped(HttpServletRequest request) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.statsGrouped(operator.companyId()));
|
||||
}
|
||||
|
||||
@PostMapping("/keywords")
|
||||
@Operation(summary = "批量添加关键词", description = "trim 规范化;已存在/为空跳过;成功行写词本体、添加留痕并自动标记已使用。")
|
||||
public ApiResponse<KeywordShareAddResultVo> add(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody KeywordShareAddRequest body) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success("添加成功", keywordShareService.add(body, operator.companyId(), operator.userName()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/keywords")
|
||||
@Operation(summary = "批量删除关键词", description = "删除本公司词行并写删除留痕。")
|
||||
public ApiResponse<KeywordShareDeleteResultVo> delete(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody KeywordShareDeleteRequest body) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success("删除成功", keywordShareService.delete(body, operator.companyId(), operator.userName()));
|
||||
}
|
||||
|
||||
@PostMapping("/usage/mark")
|
||||
@Operation(summary = "批量标记已使用", description = "写 keyword_usage,唯一键冲突按 UPSERT 刷新,幂等。")
|
||||
public ApiResponse<KeywordShareMarkResultVo> mark(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody KeywordUsageBatchRequest body) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.mark(body, operator.companyId(), operator.userName()));
|
||||
}
|
||||
|
||||
@PostMapping("/usage/unmark")
|
||||
@Operation(summary = "批量取消使用", description = "删除 keyword_usage 行。")
|
||||
public ApiResponse<KeywordShareUnmarkResultVo> unmark(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody KeywordUsageBatchRequest body) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.unmark(body, operator.companyId()));
|
||||
}
|
||||
|
||||
@GetMapping("/logs")
|
||||
@Operation(summary = "团队共享记录", description = "使用/添加/删除三类留痕的分页只读展示。")
|
||||
public ApiResponse<KeywordShareLogPageVo> logs(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "记录类型:usage|add|delete", required = true)
|
||||
@RequestParam(name = "type") String type,
|
||||
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "页码(1 起)") @RequestParam(name = "page", required = false) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "size", required = false) Long size) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.logs(operator.companyId(), type, country, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/random")
|
||||
@Operation(summary = "随机抽词", description = "从当前筛选的未使用池随机抽取(默认 10 条)。")
|
||||
public ApiResponse<List<KeywordShareRowVo>> random(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "抽取条数(默认 10)") @RequestParam(name = "count", required = false) Long count,
|
||||
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "一级类目") @RequestParam(name = "category", required = false) String category,
|
||||
@Parameter(description = "二级类目") @RequestParam(name = "subCategory", required = false) String subCategory,
|
||||
@Parameter(description = "三级类目") @RequestParam(name = "categoryL3", required = false) String categoryL3,
|
||||
@Parameter(description = "四级类目") @RequestParam(name = "categoryL4", required = false) String categoryL4,
|
||||
@Parameter(description = "关键词/中文模糊搜索") @RequestParam(name = "search", required = false) String search) {
|
||||
Operator operator = requireKeywordShareAccess(request);
|
||||
return ApiResponse.success(keywordShareService.random(operator.companyId(), operator.userName(),
|
||||
country, category, subCategory, categoryL3, categoryL4, search, count));
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐端点把门:登录态 + 后台菜单权限;公司 id 与用户名都从登录人实体取,前端传参不参与归属判定。
|
||||
*/
|
||||
private Operator requireKeywordShareAccess(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireUser(request);
|
||||
permissionMenuService.requireConsolePageAccess(operator, DENIAL_MESSAGE, PERMISSION_KEY);
|
||||
return new Operator(operator.getCompanyId(), operator.getUsername());
|
||||
}
|
||||
|
||||
private record Operator(Long companyId, String userName) {
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordAddLogEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——添加留痕(keyword_add_log)数据访问。
|
||||
*/
|
||||
@Mapper
|
||||
public interface KeywordAddLogMapper extends BaseMapper<KeywordAddLogEntity> {
|
||||
|
||||
/** 批量写添加留痕(对齐桌面版 ShareSync.log_add_batch 的单次往返)。 */
|
||||
int insertBatch(@Param("rows") List<KeywordAddLogEntity> rows);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordDeleteLogEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——删除留痕(keyword_delete_log)数据访问。
|
||||
*/
|
||||
@Mapper
|
||||
public interface KeywordDeleteLogMapper extends BaseMapper<KeywordDeleteLogEntity> {
|
||||
|
||||
/** 批量写删除留痕。 */
|
||||
int insertBatch(@Param("rows") List<KeywordDeleteLogEntity> rows);
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryTreeRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareFilterQuery;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordShareEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——词本体(keyword_share)数据访问。
|
||||
*
|
||||
* <p>列表/统计/随机这类带 JOIN 与动态筛选的 SQL 全部收口在本 Mapper 的 XML 里
|
||||
* ({@code mapper/keywordshare/KeywordShareMapper.xml}),筛选值一律 {@code #{}} 占位符。</p>
|
||||
*/
|
||||
@Mapper
|
||||
public interface KeywordShareMapper extends BaseMapper<KeywordShareEntity> {
|
||||
|
||||
/** 筛选命中总数(含状态/时间/仅看我条件)。 */
|
||||
long countHit(@Param("f") KeywordShareFilterQuery filter);
|
||||
|
||||
/** 当前页行:未使用在前,已使用按 used_time 升序(对齐桌面版 _filtered_rows_conn 的口径)。 */
|
||||
List<KeywordShareRowVo> selectRows(@Param("f") KeywordShareFilterQuery filter);
|
||||
|
||||
/** 未使用池随机抽词。 */
|
||||
List<KeywordShareRowVo> selectRandomUnused(@Param("f") KeywordShareFilterQuery filter);
|
||||
|
||||
/** 本公司跨国重复词数:同词出现在 2 个及以上国家。 */
|
||||
long countDupKeywords(@Param("companyId") Long companyId);
|
||||
|
||||
/** 类目筛选名册:国家平铺。 */
|
||||
List<String> selectFilterCountries(@Param("companyId") Long companyId);
|
||||
|
||||
/** 类目筛选名册:类目树的去重行(category/sub_category/category_l3/category_l4)。 */
|
||||
List<KeywordCategoryTreeRow> selectFilterTreeRows(@Param("companyId") Long companyId);
|
||||
|
||||
/** 词库统计:按国家分布。 */
|
||||
List<KeywordNameCountRow> selectCountryCounts(@Param("companyId") Long companyId);
|
||||
|
||||
/** 词库统计:按一级类目分布。 */
|
||||
List<KeywordNameCountRow> selectCategoryCounts(@Param("companyId") Long companyId);
|
||||
|
||||
/** 词库统计:按二级类目分布(挂一级类目下)。 */
|
||||
List<KeywordCategoryCountRow> selectSubCategoryCounts(@Param("companyId") Long companyId);
|
||||
|
||||
/** 词库统计:按三级类目分布(挂一级+二级下)。 */
|
||||
List<KeywordCategoryL3CountRow> selectCategoryL3Counts(@Param("companyId") Long companyId);
|
||||
|
||||
/** 批量查 (country, keyword) 已存在的键(添加防重预检)。 */
|
||||
List<KeywordShareKey> selectExistingKeywords(@Param("companyId") Long companyId,
|
||||
@Param("keys") List<KeywordShareKey> keys);
|
||||
|
||||
/** 批量 INSERT IGNORE:命中唯一键 uk_comp_cw 的重复行静默跳过,兜底与预检双保险。 */
|
||||
int insertBatchIgnore(@Param("rows") List<KeywordShareEntity> rows);
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordUsageEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——使用状态(keyword_usage)数据访问。
|
||||
* 批量标记走 UPSERT(对齐桌面版 ShareSync.mark 的 ON DUPLICATE KEY UPDATE 语义,天然幂等),
|
||||
* SQL 收口在 {@code mapper/keywordshare/KeywordUsageMapper.xml}。
|
||||
*/
|
||||
@Mapper
|
||||
public interface KeywordUsageMapper extends BaseMapper<KeywordUsageEntity> {
|
||||
|
||||
/** 批量 UPSERT:唯一键冲突时刷新 user_name/used_time,幂等。 */
|
||||
int upsertBatch(@Param("rows") List<KeywordUsageEntity> rows);
|
||||
|
||||
/** 批量取消使用:按 (company_id, country, keyword) 删行,返回实际删除条数。 */
|
||||
int deleteBatch(@Param("companyId") Long companyId, @Param("keys") List<KeywordShareKey> keys);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 词库统计的「一级类目 + 二级类目 + 计数」行。
|
||||
*/
|
||||
@Data
|
||||
public class KeywordCategoryCountRow {
|
||||
|
||||
private String category;
|
||||
private String name;
|
||||
private Long count;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 词库统计的「一级 + 二级 + 三级类目 + 计数」行。
|
||||
*/
|
||||
@Data
|
||||
public class KeywordCategoryL3CountRow {
|
||||
|
||||
private String category;
|
||||
private String subCategory;
|
||||
private String name;
|
||||
private Long count;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 类目筛选名册的树行(DISTINCT category/sub_category/category_l3/category_l4),Service 内组装成树。
|
||||
*/
|
||||
@Data
|
||||
public class KeywordCategoryTreeRow {
|
||||
|
||||
private String category;
|
||||
private String subCategory;
|
||||
private String categoryL3;
|
||||
private String categoryL4;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 词库统计的「名称 + 计数」行(按国家 / 按一级类目)。
|
||||
*/
|
||||
@Data
|
||||
public class KeywordNameCountRow {
|
||||
|
||||
private String name;
|
||||
private Long count;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量添加关键词请求。词的一级~四级类目由词库既有口径维护,web 端添加不携带类目字段
|
||||
* (落库取列默认值 ''),与桌面版从纯文本行解析出 country/keyword/chinese 的输入面一致。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量添加请求")
|
||||
public class KeywordShareAddRequest {
|
||||
|
||||
@Valid
|
||||
@NotEmpty(message = "items 不能为空")
|
||||
@Schema(description = "待添加的词列表", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private List<Item> items;
|
||||
|
||||
@Data
|
||||
@Schema(description = "单个待添加词")
|
||||
public static class Item {
|
||||
|
||||
@Schema(description = "国家", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String country;
|
||||
|
||||
@Schema(description = "关键词", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String keyword;
|
||||
|
||||
@Schema(description = "中文翻译")
|
||||
private String chinese;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量删除关键词请求(按列表行的主键 id)。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量删除请求")
|
||||
public class KeywordShareDeleteRequest {
|
||||
|
||||
@NotEmpty(message = "ids 不能为空")
|
||||
@Schema(description = "待删除的行主键列表", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private List<Long> ids;
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* keyword_share 列表/随机抽词的筛选条件与分页参数——Mapper XML 的唯一入参载体({@code @Param("f")})。
|
||||
*
|
||||
* <p>筛选值全部走 {@code #{}} 占位符,SQL 侧不做任何字符串拼接。</p>
|
||||
*/
|
||||
@Data
|
||||
public class KeywordShareFilterQuery {
|
||||
|
||||
/** 归属公司,服务端从当前登录人取,永远不为空。 */
|
||||
private Long companyId;
|
||||
private String country;
|
||||
private String category;
|
||||
private String subCategory;
|
||||
private String categoryL3;
|
||||
private String categoryL4;
|
||||
/** keyword/chinese 双列 LIKE 的搜索词,服务端已 trim;空串表示不筛。 */
|
||||
private String search;
|
||||
/** all | used | unused;空/未知按 all 处理。 */
|
||||
private String status;
|
||||
/** 已使用时间下限;null 表示不筛时间。 */
|
||||
private LocalDateTime usedSince;
|
||||
/** true = 仅看当前用户名标记的使用记录。 */
|
||||
private Boolean onlyMine;
|
||||
/** 仅看我的判定基准用户名。 */
|
||||
private String userName;
|
||||
private long offset;
|
||||
private long limit;
|
||||
|
||||
/** 复制一份基础筛选,只换状态口径(命中总数与「命中内已使用数」要按不同 status 各数一遍)。 */
|
||||
public KeywordShareFilterQuery copyWithStatus(String newStatus) {
|
||||
KeywordShareFilterQuery copy = new KeywordShareFilterQuery();
|
||||
copy.setCompanyId(companyId);
|
||||
copy.setCountry(country);
|
||||
copy.setCategory(category);
|
||||
copy.setSubCategory(subCategory);
|
||||
copy.setCategoryL3(categoryL3);
|
||||
copy.setCategoryL4(categoryL4);
|
||||
copy.setSearch(search);
|
||||
copy.setStatus(newStatus);
|
||||
copy.setUsedSince(usedSince);
|
||||
copy.setOnlyMine(onlyMine);
|
||||
copy.setUserName(userName);
|
||||
copy.setOffset(offset);
|
||||
copy.setLimit(limit);
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* (country, keyword) 业务键——查重、标记/取消使用的批量键载体。
|
||||
*/
|
||||
@Data
|
||||
public class KeywordShareKey {
|
||||
|
||||
private String country;
|
||||
private String keyword;
|
||||
|
||||
public static KeywordShareKey of(String country, String keyword) {
|
||||
KeywordShareKey key = new KeywordShareKey();
|
||||
key.setCountry(country);
|
||||
key.setKeyword(keyword);
|
||||
return key;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量标记/取消使用请求。接口语义由路径区分(/usage/mark 与 /usage/unmark),body 同形。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量标记/取消使用请求")
|
||||
public class KeywordUsageBatchRequest {
|
||||
|
||||
@Valid
|
||||
@NotEmpty(message = "items 不能为空")
|
||||
@Schema(description = "待操作的词键列表", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private List<Item> items;
|
||||
|
||||
@Data
|
||||
@Schema(description = "单个词键")
|
||||
public static class Item {
|
||||
|
||||
@Schema(description = "国家", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String country;
|
||||
|
||||
@Schema(description = "关键词", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String keyword;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.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;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——添加留痕(谁添加了哪个词,可追溯源头)。
|
||||
*
|
||||
* <p>列结构按桌面版 {@code ShareSync.log_add} 的 {@code CREATE TABLE IF NOT EXISTS keyword_add_log}
|
||||
* 逐列核对(keyword_share_app.py L2058-2066):id 自增主键、country NOT NULL、keyword NOT NULL、
|
||||
* user_name DEFAULT ''、add_time 可空、company_id NOT NULL DEFAULT 1。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("keyword_add_log")
|
||||
public class KeywordAddLogEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String country;
|
||||
private String keyword;
|
||||
private String userName;
|
||||
private LocalDateTime addTime;
|
||||
private Long companyId;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.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;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——删除留痕(谁删了哪个词,可追溯源头)。
|
||||
*
|
||||
* <p>列结构按桌面版 {@code ShareSync.log_delete} 的 {@code CREATE TABLE IF NOT EXISTS keyword_delete_log}
|
||||
* 逐列核对(keyword_share_app.py L2019-2026):id 自增主键、country NOT NULL、keyword NOT NULL、
|
||||
* user_name DEFAULT ''、delete_time 可空、company_id NOT NULL DEFAULT 1。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("keyword_delete_log")
|
||||
public class KeywordDeleteLogEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String country;
|
||||
private String keyword;
|
||||
private String userName;
|
||||
private LocalDateTime deleteTime;
|
||||
private Long companyId;
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.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;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——词本体(含四级类目)。
|
||||
*
|
||||
* <p>表在主库(aiimage)早已存在且已是全量词库,桌面 Tkinter 工具与 web 版共用同一份,
|
||||
* 每公司一份、按 {@code company_id} 隔离;唯一键 {@code uk_comp_cw(company_id, country, keyword)}。
|
||||
* <b>不建表、不走 Flyway</b>:本模块只做实体/Mapper 映射既有表。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("keyword_share")
|
||||
public class KeywordShareEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String country;
|
||||
private String keyword;
|
||||
private String chinese;
|
||||
private String ktype;
|
||||
private String source;
|
||||
private String category;
|
||||
private String subCategory;
|
||||
private String categoryL3;
|
||||
private String categoryL4;
|
||||
private String userName;
|
||||
private LocalDateTime addTime;
|
||||
private Long companyId;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.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;
|
||||
|
||||
/**
|
||||
* 五国关键词共享——使用状态(谁在什么时候标记了哪个词)。
|
||||
*
|
||||
* <p>每公司一份,唯一键 {@code uk_comp_cw(company_id, country, keyword)};
|
||||
* 「仅看我使用」按 {@code user_name = 当前用户名} 过滤。词的删除不走这里(删词写 keyword_delete_log)。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("keyword_usage")
|
||||
public class KeywordUsageEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String country;
|
||||
private String keyword;
|
||||
private String userName;
|
||||
private LocalDateTime usedTime;
|
||||
private Long companyId;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 批量添加结果:成功条数 + 跳过条数(已存在/为空/批内重复)。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量添加结果")
|
||||
public class KeywordShareAddResultVo {
|
||||
|
||||
@Schema(description = "成功添加条数")
|
||||
private int added;
|
||||
|
||||
@Schema(description = "跳过条数(已存在、关键词为空或批内重复)")
|
||||
private int skipped;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 批量删除结果。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量删除结果")
|
||||
public class KeywordShareDeleteResultVo {
|
||||
|
||||
@Schema(description = "实际删除条数(仅计本公司存在的行)")
|
||||
private int deleted;
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 类目筛选名册:国家平铺 + 一级→二级→三级→四级类目树(按当前公司 DISTINCT)。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词筛选名册")
|
||||
public class KeywordShareFiltersVo {
|
||||
|
||||
@Schema(description = "国家列表")
|
||||
private List<String> countries;
|
||||
|
||||
@Schema(description = "类目树")
|
||||
private List<CategoryNode> categories;
|
||||
|
||||
@Data
|
||||
@Schema(description = "一级类目节点")
|
||||
public static class CategoryNode {
|
||||
|
||||
@Schema(description = "一级类目名")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "二级类目列表")
|
||||
private List<SubCategoryNode> subs;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Schema(description = "二级类目节点")
|
||||
public static class SubCategoryNode {
|
||||
|
||||
@Schema(description = "二级类目名")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "三级类目列表")
|
||||
private List<L3Node> l3;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Schema(description = "三级类目节点")
|
||||
public static class L3Node {
|
||||
|
||||
@Schema(description = "三级类目名")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "四级类目列表")
|
||||
private List<String> l4;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 团队共享记录分页。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词共享记录分页")
|
||||
public class KeywordShareLogPageVo {
|
||||
|
||||
@Schema(description = "总条数")
|
||||
private long total;
|
||||
|
||||
@Schema(description = "当前页行")
|
||||
private List<KeywordShareLogVo> rows;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 团队共享记录单行(使用 / 添加 / 删除三类留痕同形展示,只读)。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词共享记录行")
|
||||
public class KeywordShareLogVo {
|
||||
|
||||
@Schema(description = "操作人")
|
||||
private String userName;
|
||||
|
||||
@Schema(description = "国家")
|
||||
private String country;
|
||||
|
||||
@Schema(description = "关键词")
|
||||
private String keyword;
|
||||
|
||||
@Schema(description = "操作时间(使用时间/添加时间/删除时间)")
|
||||
private LocalDateTime time;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 批量标记使用结果。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量标记使用结果")
|
||||
public class KeywordShareMarkResultVo {
|
||||
|
||||
@Schema(description = "成功标记条数(唯一键冲突按幂等处理,仍计入)")
|
||||
private int marked;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 关键词分页列表:总命中数 + 当前行 + 统计条。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词分页列表")
|
||||
public class KeywordSharePageVo {
|
||||
|
||||
@Schema(description = "筛选命中总数")
|
||||
private long total;
|
||||
|
||||
@Schema(description = "当前页行")
|
||||
private List<KeywordShareRowVo> rows;
|
||||
|
||||
@Schema(description = "统计条")
|
||||
private KeywordShareStatsVo stats;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 关键词列表/随机抽词的单行。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词行")
|
||||
public class KeywordShareRowVo {
|
||||
|
||||
@Schema(description = "行主键")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "国家")
|
||||
private String country;
|
||||
|
||||
@Schema(description = "关键词")
|
||||
private String keyword;
|
||||
|
||||
@Schema(description = "中文翻译")
|
||||
private String chinese;
|
||||
|
||||
@Schema(description = "一级类目")
|
||||
private String category;
|
||||
|
||||
@Schema(description = "二级类目")
|
||||
private String subCategory;
|
||||
|
||||
@Schema(description = "三级类目")
|
||||
private String categoryL3;
|
||||
|
||||
@Schema(description = "四级类目")
|
||||
private String categoryL4;
|
||||
|
||||
@Schema(description = "是否已使用")
|
||||
private boolean used;
|
||||
|
||||
@Schema(description = "使用时间(未使用为 null)")
|
||||
private LocalDateTime usedTime;
|
||||
|
||||
@Schema(description = "使用者(未使用为空串)")
|
||||
private String usedUser;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 词库统计弹窗:国家、一级/二级/三级类目的分布计数(对齐桌面版统计窗的四段展示)。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词词库统计")
|
||||
public class KeywordShareStatsGroupedVo {
|
||||
|
||||
@Schema(description = "按国家分布")
|
||||
private List<KeywordNameCountRow> byCountry;
|
||||
|
||||
@Schema(description = "按一级类目分布")
|
||||
private List<KeywordNameCountRow> byCategory;
|
||||
|
||||
@Schema(description = "按二级类目分布(挂一级类目下)")
|
||||
private List<KeywordCategoryCountRow> bySubCategory;
|
||||
|
||||
@Schema(description = "按三级类目分布(挂一级+二级下)")
|
||||
private List<KeywordCategoryL3CountRow> byCategoryL3;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 列表页统计条:命中数、命中内已/未使用数、本公司跨国重复词数。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词列表统计")
|
||||
public class KeywordShareStatsVo {
|
||||
|
||||
@Schema(description = "筛选命中总数")
|
||||
private long hit;
|
||||
|
||||
@Schema(description = "命中内已使用数")
|
||||
private long used;
|
||||
|
||||
@Schema(description = "命中内未使用数")
|
||||
private long unused;
|
||||
|
||||
@Schema(description = "本公司跨国重复词数")
|
||||
private long dup;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 批量取消使用结果。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "五国关键词批量取消使用结果")
|
||||
public class KeywordShareUnmarkResultVo {
|
||||
|
||||
@Schema(description = "实际删除的使用记录条数")
|
||||
private int unmarked;
|
||||
}
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordAddLogMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordDeleteLogMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordShareMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordUsageMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryTreeRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareAddRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareDeleteRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareFilterQuery;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordUsageBatchRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordAddLogEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordDeleteLogEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordShareEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordUsageEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareAddResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareDeleteResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareFiltersVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareLogPageVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareLogVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareMarkResultVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordSharePageVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareStatsGroupedVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareStatsVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareUnmarkResultVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 五国关键词共享(桌面 Tkinter 工具的 web 化)。
|
||||
*
|
||||
* <p>词本体 = 主库 keyword_share(每公司一份、company_id 隔离),web 版没有 SQLite;
|
||||
* 所有查询/写入都以服务端取到的 companyId 收口,杜绝跨公司读写。
|
||||
* 行为口径对齐桌面版 keyword_share_app.py:列表「未使用在前、已使用按 used_time 升序」,
|
||||
* 添加即自动标记已使用(使用者=当前用户、时间=添加时刻),删词写 keyword_delete_log 留痕,
|
||||
* 标记走 UPSERT 天然幂等。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class KeywordShareService {
|
||||
|
||||
/** 列表默认页容量(API 契约定值;不走 PageDefaults 以免挤进它的逐点台账)。 */
|
||||
public static final long DEFAULT_PAGE_SIZE = 200;
|
||||
/** 列表页容量上限。 */
|
||||
public static final long MAX_PAGE_SIZE = 500;
|
||||
/** 随机抽词默认条数。 */
|
||||
public static final long DEFAULT_RANDOM_COUNT = 10;
|
||||
/** 随机抽词单次上限。 */
|
||||
public static final long MAX_RANDOM_COUNT = 100;
|
||||
/** 共享记录单页上限(留痕查询非无限拉取)。 */
|
||||
public static final long MAX_LOG_PAGE_SIZE = 500;
|
||||
|
||||
public static final String FILTER_ALL = "all";
|
||||
public static final String FILTER_USED = "used";
|
||||
public static final String FILTER_UNUSED = "unused";
|
||||
|
||||
/** 添加词的固定口径,与桌面版 insert_keyword 一致。 */
|
||||
private static final String KTYPE_MANUAL = "主关键词";
|
||||
private static final String SOURCE_MANUAL = "手动添加";
|
||||
|
||||
private final KeywordShareMapper keywordShareMapper;
|
||||
private final KeywordUsageMapper keywordUsageMapper;
|
||||
private final KeywordAddLogMapper keywordAddLogMapper;
|
||||
private final KeywordDeleteLogMapper keywordDeleteLogMapper;
|
||||
|
||||
// ---------------------------------------------------------------- 列表与统计
|
||||
|
||||
public KeywordSharePageVo page(Long companyId, String viewerUserName,
|
||||
String country, String category, String subCategory,
|
||||
String categoryL3, String categoryL4, String search,
|
||||
String status, Integer usedDays, boolean onlyMine,
|
||||
Long page, Long size) {
|
||||
KeywordShareFilterQuery filter = buildFilter(companyId, viewerUserName, country, category, subCategory,
|
||||
categoryL3, categoryL4, search, status, usedDays, onlyMine);
|
||||
filter.setOffset((safePage(page) - 1) * safePageSize(size));
|
||||
filter.setLimit(safePageSize(size));
|
||||
|
||||
long hit = keywordShareMapper.countHit(filter);
|
||||
// 命中内已使用数:状态过滤生效时命中即答案;否则按同条件单独数一遍 used
|
||||
long used = switch (filter.getStatus()) {
|
||||
case FILTER_USED -> hit;
|
||||
case FILTER_UNUSED -> 0;
|
||||
default -> keywordShareMapper.countHit(filter.copyWithStatus(FILTER_USED));
|
||||
};
|
||||
List<KeywordShareRowVo> rows = keywordShareMapper.selectRows(filter).stream()
|
||||
.map(this::normalizeRow)
|
||||
.toList();
|
||||
long dup = keywordShareMapper.countDupKeywords(companyId);
|
||||
|
||||
KeywordShareStatsVo stats = new KeywordShareStatsVo();
|
||||
stats.setHit(hit);
|
||||
stats.setUsed(used);
|
||||
stats.setUnused(hit - used);
|
||||
stats.setDup(dup);
|
||||
|
||||
KeywordSharePageVo vo = new KeywordSharePageVo();
|
||||
vo.setTotal(hit);
|
||||
vo.setRows(rows);
|
||||
vo.setStats(stats);
|
||||
return vo;
|
||||
}
|
||||
|
||||
public KeywordShareFiltersVo filters(Long companyId) {
|
||||
KeywordShareFiltersVo vo = new KeywordShareFiltersVo();
|
||||
vo.setCountries(keywordShareMapper.selectFilterCountries(companyId));
|
||||
|
||||
Map<String, Map<String, Map<String, Set<String>>>> tree = new LinkedHashMap<>();
|
||||
for (KeywordCategoryTreeRow row : keywordShareMapper.selectFilterTreeRows(companyId)) {
|
||||
tree.computeIfAbsent(orEmpty(row.getCategory()), c -> new LinkedHashMap<>())
|
||||
.computeIfAbsent(orEmpty(row.getSubCategory()), s -> new LinkedHashMap<>())
|
||||
.computeIfAbsent(orEmpty(row.getCategoryL3()), l -> new LinkedHashSet<>())
|
||||
.add(orEmpty(row.getCategoryL4()));
|
||||
}
|
||||
List<KeywordShareFiltersVo.CategoryNode> categories = new ArrayList<>();
|
||||
tree.forEach((category, subs) -> {
|
||||
KeywordShareFiltersVo.CategoryNode categoryNode = new KeywordShareFiltersVo.CategoryNode();
|
||||
categoryNode.setName(category);
|
||||
List<KeywordShareFiltersVo.SubCategoryNode> subNodes = new ArrayList<>();
|
||||
subs.forEach((sub, l3s) -> {
|
||||
KeywordShareFiltersVo.SubCategoryNode subNode = new KeywordShareFiltersVo.SubCategoryNode();
|
||||
subNode.setName(sub);
|
||||
List<KeywordShareFiltersVo.L3Node> l3Nodes = new ArrayList<>();
|
||||
l3s.forEach((l3, l4s) -> {
|
||||
// 三级/四级类目与桌面版同口径:空值不进名册
|
||||
if (l3.isBlank()) {
|
||||
return;
|
||||
}
|
||||
KeywordShareFiltersVo.L3Node l3Node = new KeywordShareFiltersVo.L3Node();
|
||||
l3Node.setName(l3);
|
||||
l3Node.setL4(l4s.stream().filter(l4 -> !l4.isBlank()).toList());
|
||||
l3Nodes.add(l3Node);
|
||||
});
|
||||
subNode.setL3(l3Nodes);
|
||||
subNodes.add(subNode);
|
||||
});
|
||||
categoryNode.setSubs(subNodes);
|
||||
categories.add(categoryNode);
|
||||
});
|
||||
vo.setCategories(categories);
|
||||
return vo;
|
||||
}
|
||||
|
||||
public KeywordShareStatsGroupedVo statsGrouped(Long companyId) {
|
||||
KeywordShareStatsGroupedVo vo = new KeywordShareStatsGroupedVo();
|
||||
vo.setByCountry(keywordShareMapper.selectCountryCounts(companyId));
|
||||
vo.setByCategory(keywordShareMapper.selectCategoryCounts(companyId));
|
||||
vo.setBySubCategory(keywordShareMapper.selectSubCategoryCounts(companyId));
|
||||
vo.setByCategoryL3(keywordShareMapper.selectCategoryL3Counts(companyId));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 未使用池随机抽词;国家/类目筛选可选,数量默认 10、上限 100。 */
|
||||
public List<KeywordShareRowVo> random(Long companyId, String viewerUserName,
|
||||
String country, String category, String subCategory,
|
||||
String categoryL3, String categoryL4, String search,
|
||||
Long count) {
|
||||
KeywordShareFilterQuery filter = buildFilter(companyId, viewerUserName, country, category, subCategory,
|
||||
categoryL3, categoryL4, search, FILTER_UNUSED, null, false);
|
||||
filter.setOffset(0);
|
||||
long safeCount = count == null ? DEFAULT_RANDOM_COUNT : Math.min(Math.max(count, 1), MAX_RANDOM_COUNT);
|
||||
filter.setLimit(safeCount);
|
||||
return keywordShareMapper.selectRandomUnused(filter).stream()
|
||||
.map(this::normalizeRow)
|
||||
.toList();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 写操作
|
||||
|
||||
/** 批量添加:trim 规范化、防重跳过;成功行写词本体 + 添加留痕 + 自动标记已使用。 */
|
||||
@Transactional
|
||||
public KeywordShareAddResultVo add(KeywordShareAddRequest request, Long companyId, String operatorName) {
|
||||
int skipped = 0;
|
||||
List<KeywordShareAddRequest.Item> candidates = new ArrayList<>();
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
for (KeywordShareAddRequest.Item item : request.getItems()) {
|
||||
String country = normalize(item == null ? null : item.getCountry());
|
||||
String keyword = normalize(item == null ? null : item.getKeyword());
|
||||
if (country.isEmpty() || keyword.isEmpty()) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if (!seen.add(country + "\n" + keyword)) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
KeywordShareAddRequest.Item normalized = new KeywordShareAddRequest.Item();
|
||||
normalized.setCountry(country);
|
||||
normalized.setKeyword(keyword);
|
||||
normalized.setChinese(normalize(item.getChinese()));
|
||||
candidates.add(normalized);
|
||||
}
|
||||
|
||||
List<KeywordShareEntity> toInsert = new ArrayList<>();
|
||||
if (!candidates.isEmpty()) {
|
||||
Set<String> existing = new LinkedHashSet<>();
|
||||
List<KeywordShareKey> keys = candidates.stream()
|
||||
.map(item -> KeywordShareKey.of(item.getCountry(), item.getKeyword()))
|
||||
.toList();
|
||||
for (KeywordShareKey key : keywordShareMapper.selectExistingKeywords(companyId, keys)) {
|
||||
existing.add(key.getCountry() + "\n" + key.getKeyword());
|
||||
}
|
||||
for (KeywordShareAddRequest.Item item : candidates) {
|
||||
if (existing.contains(item.getCountry() + "\n" + item.getKeyword())) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
KeywordShareEntity entity = new KeywordShareEntity();
|
||||
entity.setCountry(item.getCountry());
|
||||
entity.setKeyword(item.getKeyword());
|
||||
entity.setChinese(item.getChinese());
|
||||
entity.setKtype(KTYPE_MANUAL);
|
||||
entity.setSource(SOURCE_MANUAL);
|
||||
entity.setUserName(operatorName);
|
||||
entity.setAddTime(LocalDateTime.now());
|
||||
entity.setCompanyId(companyId);
|
||||
toInsert.add(entity);
|
||||
}
|
||||
}
|
||||
if (!toInsert.isEmpty()) {
|
||||
keywordShareMapper.insertBatchIgnore(toInsert);
|
||||
keywordAddLogMapper.insertBatch(toInsert.stream().map(row -> {
|
||||
KeywordAddLogEntity log = new KeywordAddLogEntity();
|
||||
log.setCompanyId(companyId);
|
||||
log.setCountry(row.getCountry());
|
||||
log.setKeyword(row.getKeyword());
|
||||
log.setUserName(operatorName);
|
||||
log.setAddTime(row.getAddTime());
|
||||
return log;
|
||||
}).toList());
|
||||
markInternal(companyId, operatorName, toInsert.stream()
|
||||
.map(row -> KeywordShareKey.of(row.getCountry(), row.getKeyword()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
KeywordShareAddResultVo vo = new KeywordShareAddResultVo();
|
||||
vo.setAdded(toInsert.size());
|
||||
vo.setSkipped(skipped);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 批量删除:只删本公司行并写删除留痕(谁删了哪个词可追溯)。 */
|
||||
@Transactional
|
||||
public KeywordShareDeleteResultVo delete(KeywordShareDeleteRequest request, Long companyId, String operatorName) {
|
||||
List<Long> ids = request.getIds().stream().filter(java.util.Objects::nonNull).distinct().toList();
|
||||
// 公司隔离在应用侧过滤:selectBatchIds 拉回后只认本公司行,别家的 id 传进来也不动
|
||||
List<KeywordShareEntity> rows = ids.isEmpty() ? List.of()
|
||||
: keywordShareMapper.selectBatchIds(ids).stream()
|
||||
.filter(row -> companyId != null && companyId.equals(row.getCompanyId()))
|
||||
.toList();
|
||||
if (!rows.isEmpty()) {
|
||||
keywordShareMapper.deleteBatchIds(rows.stream().map(KeywordShareEntity::getId).toList());
|
||||
keywordDeleteLogMapper.insertBatch(rows.stream().map(row -> {
|
||||
KeywordDeleteLogEntity log = new KeywordDeleteLogEntity();
|
||||
log.setCompanyId(companyId);
|
||||
log.setCountry(row.getCountry());
|
||||
log.setKeyword(row.getKeyword());
|
||||
log.setUserName(operatorName);
|
||||
log.setDeleteTime(LocalDateTime.now());
|
||||
return log;
|
||||
}).toList());
|
||||
}
|
||||
KeywordShareDeleteResultVo vo = new KeywordShareDeleteResultVo();
|
||||
vo.setDeleted(rows.size());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 批量标记已使用;唯一键冲突按 UPSERT 刷新,幂等。used_time 取服务器当前时间。 */
|
||||
@Transactional
|
||||
public KeywordShareMarkResultVo mark(KeywordUsageBatchRequest request, Long companyId, String operatorName) {
|
||||
int marked = markInternal(companyId, operatorName, normalizeKeys(request));
|
||||
KeywordShareMarkResultVo vo = new KeywordShareMarkResultVo();
|
||||
vo.setMarked(marked);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 批量取消使用:删 usage 行,返回实际删除条数。 */
|
||||
@Transactional
|
||||
public KeywordShareUnmarkResultVo unmark(KeywordUsageBatchRequest request, Long companyId) {
|
||||
List<KeywordShareKey> keys = normalizeKeys(request);
|
||||
int unmarked = keys.isEmpty() ? 0 : keywordUsageMapper.deleteBatch(companyId, keys);
|
||||
KeywordShareUnmarkResultVo vo = new KeywordShareUnmarkResultVo();
|
||||
vo.setUnmarked(unmarked);
|
||||
return vo;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 共享记录(只读)
|
||||
|
||||
public KeywordShareLogPageVo logs(Long companyId, String type, String country, Long page, Long size) {
|
||||
long safePage = safePage(page);
|
||||
long safeSize = size == null ? DEFAULT_PAGE_SIZE : Math.min(Math.max(size, 1), MAX_LOG_PAGE_SIZE);
|
||||
return switch (type == null ? "" : type) {
|
||||
case "usage" -> usageLogs(companyId, country, safePage, safeSize);
|
||||
case "add" -> addLogs(companyId, country, safePage, safeSize);
|
||||
case "delete" -> deleteLogs(companyId, country, safePage, safeSize);
|
||||
default -> throw new BusinessException("type 只支持 usage / add / delete");
|
||||
};
|
||||
}
|
||||
|
||||
private KeywordShareLogPageVo usageLogs(Long companyId, String country, long page, long size) {
|
||||
LambdaQueryWrapper<KeywordUsageEntity> query = new LambdaQueryWrapper<KeywordUsageEntity>()
|
||||
.eq(KeywordUsageEntity::getCompanyId, companyId)
|
||||
.eq(country != null && !country.isBlank(), KeywordUsageEntity::getCountry, normalize(country))
|
||||
.orderByDesc(KeywordUsageEntity::getUsedTime)
|
||||
.orderByDesc(KeywordUsageEntity::getId);
|
||||
long total = keywordUsageMapper.selectCount(query);
|
||||
List<KeywordUsageEntity> rows = keywordUsageMapper.selectList(
|
||||
query.last("LIMIT " + ((page - 1) * size) + ", " + size));
|
||||
return toLogPage(total, rows.stream().map(row -> {
|
||||
KeywordShareLogVo vo = new KeywordShareLogVo();
|
||||
vo.setUserName(orEmpty(row.getUserName()));
|
||||
vo.setCountry(orEmpty(row.getCountry()));
|
||||
vo.setKeyword(orEmpty(row.getKeyword()));
|
||||
vo.setTime(row.getUsedTime());
|
||||
return vo;
|
||||
}).toList());
|
||||
}
|
||||
|
||||
private KeywordShareLogPageVo addLogs(Long companyId, String country, long page, long size) {
|
||||
LambdaQueryWrapper<KeywordAddLogEntity> query = new LambdaQueryWrapper<KeywordAddLogEntity>()
|
||||
.eq(KeywordAddLogEntity::getCompanyId, companyId)
|
||||
.eq(country != null && !country.isBlank(), KeywordAddLogEntity::getCountry, normalize(country))
|
||||
.orderByDesc(KeywordAddLogEntity::getAddTime)
|
||||
.orderByDesc(KeywordAddLogEntity::getId);
|
||||
long total = keywordAddLogMapper.selectCount(query);
|
||||
List<KeywordAddLogEntity> rows = keywordAddLogMapper.selectList(
|
||||
query.last("LIMIT " + ((page - 1) * size) + ", " + size));
|
||||
return toLogPage(total, rows.stream().map(row -> {
|
||||
KeywordShareLogVo vo = new KeywordShareLogVo();
|
||||
vo.setUserName(orEmpty(row.getUserName()));
|
||||
vo.setCountry(orEmpty(row.getCountry()));
|
||||
vo.setKeyword(orEmpty(row.getKeyword()));
|
||||
vo.setTime(row.getAddTime());
|
||||
return vo;
|
||||
}).toList());
|
||||
}
|
||||
|
||||
private KeywordShareLogPageVo deleteLogs(Long companyId, String country, long page, long size) {
|
||||
LambdaQueryWrapper<KeywordDeleteLogEntity> query = new LambdaQueryWrapper<KeywordDeleteLogEntity>()
|
||||
.eq(KeywordDeleteLogEntity::getCompanyId, companyId)
|
||||
.eq(country != null && !country.isBlank(), KeywordDeleteLogEntity::getCountry, normalize(country))
|
||||
.orderByDesc(KeywordDeleteLogEntity::getDeleteTime)
|
||||
.orderByDesc(KeywordDeleteLogEntity::getId);
|
||||
long total = keywordDeleteLogMapper.selectCount(query);
|
||||
List<KeywordDeleteLogEntity> rows = keywordDeleteLogMapper.selectList(
|
||||
query.last("LIMIT " + ((page - 1) * size) + ", " + size));
|
||||
return toLogPage(total, rows.stream().map(row -> {
|
||||
KeywordShareLogVo vo = new KeywordShareLogVo();
|
||||
vo.setUserName(orEmpty(row.getUserName()));
|
||||
vo.setCountry(orEmpty(row.getCountry()));
|
||||
vo.setKeyword(orEmpty(row.getKeyword()));
|
||||
vo.setTime(row.getDeleteTime());
|
||||
return vo;
|
||||
}).toList());
|
||||
}
|
||||
|
||||
private KeywordShareLogPageVo toLogPage(long total, List<KeywordShareLogVo> rows) {
|
||||
KeywordShareLogPageVo vo = new KeywordShareLogPageVo();
|
||||
vo.setTotal(total);
|
||||
vo.setRows(rows);
|
||||
return vo;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
private int markInternal(Long companyId, String operatorName, List<KeywordShareKey> keys) {
|
||||
if (keys.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
List<KeywordUsageEntity> rows = keys.stream().map(key -> {
|
||||
KeywordUsageEntity entity = new KeywordUsageEntity();
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setCountry(key.getCountry());
|
||||
entity.setKeyword(key.getKeyword());
|
||||
entity.setUserName(operatorName);
|
||||
entity.setUsedTime(now);
|
||||
return entity;
|
||||
}).toList();
|
||||
keywordUsageMapper.upsertBatch(rows);
|
||||
return rows.size();
|
||||
}
|
||||
|
||||
private List<KeywordShareKey> normalizeKeys(KeywordUsageBatchRequest request) {
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
List<KeywordShareKey> keys = new ArrayList<>();
|
||||
for (KeywordUsageBatchRequest.Item item : request.getItems()) {
|
||||
String country = normalize(item == null ? null : item.getCountry());
|
||||
String keyword = normalize(item == null ? null : item.getKeyword());
|
||||
if (country.isEmpty() || keyword.isEmpty() || !seen.add(country + "\n" + keyword)) {
|
||||
continue;
|
||||
}
|
||||
keys.add(KeywordShareKey.of(country, keyword));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private KeywordShareFilterQuery buildFilter(Long companyId, String viewerUserName,
|
||||
String country, String category, String subCategory,
|
||||
String categoryL3, String categoryL4, String search,
|
||||
String status, Integer usedDays, boolean onlyMine) {
|
||||
KeywordShareFilterQuery filter = new KeywordShareFilterQuery();
|
||||
filter.setCompanyId(companyId);
|
||||
filter.setCountry(normalizeOrNull(country));
|
||||
filter.setCategory(normalizeOrNull(category));
|
||||
filter.setSubCategory(normalizeOrNull(subCategory));
|
||||
filter.setCategoryL3(normalizeOrNull(categoryL3));
|
||||
filter.setCategoryL4(normalizeOrNull(categoryL4));
|
||||
filter.setSearch(normalizeOrNull(search));
|
||||
filter.setStatus(normalizeStatus(status));
|
||||
filter.setUsedSince(resolveUsedSince(usedDays));
|
||||
filter.setOnlyMine(onlyMine);
|
||||
filter.setUserName(viewerUserName);
|
||||
return filter;
|
||||
}
|
||||
|
||||
/** usedDays:1=今天(当日零点起),7/30/90/180/360=往前推 N 天;0/null=不限。 */
|
||||
private LocalDateTime resolveUsedSince(Integer usedDays) {
|
||||
if (usedDays == null || usedDays <= 0) {
|
||||
return null;
|
||||
}
|
||||
if (usedDays == 1) {
|
||||
return LocalDate.now().atStartOfDay();
|
||||
}
|
||||
return LocalDateTime.now().minusDays(usedDays);
|
||||
}
|
||||
|
||||
private String normalizeStatus(String status) {
|
||||
String normalized = normalize(status);
|
||||
return switch (normalized) {
|
||||
case FILTER_USED -> FILTER_USED;
|
||||
case FILTER_UNUSED -> FILTER_UNUSED;
|
||||
default -> FILTER_ALL;
|
||||
};
|
||||
}
|
||||
|
||||
private KeywordShareRowVo normalizeRow(KeywordShareRowVo row) {
|
||||
if (!row.isUsed()) {
|
||||
row.setUsedUser("");
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private long safePage(Long page) {
|
||||
return page == null ? 1 : Math.max(page, 1);
|
||||
}
|
||||
|
||||
private long safePageSize(Long size) {
|
||||
return size == null ? DEFAULT_PAGE_SIZE : Math.min(Math.max(size, 1), MAX_PAGE_SIZE);
|
||||
}
|
||||
|
||||
private String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
private String normalizeOrNull(String value) {
|
||||
String normalized = normalize(value);
|
||||
return normalized.isEmpty() ? null : normalized;
|
||||
}
|
||||
|
||||
private String orEmpty(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?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.keywordshare.mapper.KeywordAddLogMapper">
|
||||
<insert id="insertBatch">
|
||||
INSERT INTO keyword_add_log (company_id, country, keyword, user_name, add_time)
|
||||
VALUES
|
||||
<foreach collection="rows" item="row" separator=",">
|
||||
(#{row.companyId}, #{row.country}, #{row.keyword}, #{row.userName}, #{row.addTime})
|
||||
</foreach>
|
||||
</insert>
|
||||
</mapper>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?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.keywordshare.mapper.KeywordDeleteLogMapper">
|
||||
<insert id="insertBatch">
|
||||
INSERT INTO keyword_delete_log (company_id, country, keyword, user_name, delete_time)
|
||||
VALUES
|
||||
<foreach collection="rows" item="row" separator=",">
|
||||
(#{row.companyId}, #{row.country}, #{row.keyword}, #{row.userName}, #{row.deleteTime})
|
||||
</foreach>
|
||||
</insert>
|
||||
</mapper>
|
||||
@@ -0,0 +1,138 @@
|
||||
<?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.keywordshare.mapper.KeywordShareMapper">
|
||||
<!-- 五国关键词共享(词本体 keyword_share)。动态筛选全部走 #{} 占位符,不做任何字符串拼接;
|
||||
排序口径对齐桌面版 keyword_share_app.py _filtered_rows_conn(未使用在前、已使用按 used_time 升序)。 -->
|
||||
|
||||
<!-- 词表 × 使用状态:usage 行按 (company_id, country, keyword) 三键对上,与桌面版同一口径 -->
|
||||
<sql id="usageJoin">
|
||||
keyword_share k
|
||||
LEFT JOIN keyword_usage u
|
||||
ON u.company_id = k.company_id
|
||||
AND u.country = k.country
|
||||
AND u.keyword = k.keyword
|
||||
</sql>
|
||||
|
||||
<sql id="filterConds">
|
||||
k.company_id = #{f.companyId}
|
||||
<if test="f.country != null and f.country != ''">AND k.country = #{f.country}</if>
|
||||
<if test="f.category != null and f.category != ''">AND k.category = #{f.category}</if>
|
||||
<if test="f.subCategory != null and f.subCategory != ''">AND k.sub_category = #{f.subCategory}</if>
|
||||
<if test="f.categoryL3 != null and f.categoryL3 != ''">AND k.category_l3 = #{f.categoryL3}</if>
|
||||
<if test="f.categoryL4 != null and f.categoryL4 != ''">AND k.category_l4 = #{f.categoryL4}</if>
|
||||
<if test="f.search != null and f.search != ''">
|
||||
AND (k.keyword LIKE CONCAT('%', #{f.search}, '%') OR k.chinese LIKE CONCAT('%', #{f.search}, '%'))
|
||||
</if>
|
||||
<if test="f.status == 'used'">AND u.country IS NOT NULL</if>
|
||||
<if test="f.status == 'unused'">AND u.country IS NULL</if>
|
||||
<if test="f.usedSince != null">AND u.country IS NOT NULL AND u.used_time >= #{f.usedSince}</if>
|
||||
<if test="f.onlyMine != null and f.onlyMine">AND u.user_name = #{f.userName}</if>
|
||||
</sql>
|
||||
|
||||
<select id="countHit" resultType="long">
|
||||
SELECT COUNT(*)
|
||||
FROM <include refid="usageJoin"/>
|
||||
WHERE <include refid="filterConds"/>
|
||||
</select>
|
||||
|
||||
<select id="selectRows" resultType="com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo">
|
||||
SELECT k.id, k.country, k.keyword, k.chinese, k.category, k.sub_category, k.category_l3, k.category_l4,
|
||||
(u.country IS NOT NULL) AS used, u.used_time, u.user_name
|
||||
FROM <include refid="usageJoin"/>
|
||||
WHERE <include refid="filterConds"/>
|
||||
ORDER BY (u.country IS NULL) ASC, u.used_time ASC
|
||||
LIMIT #{f.offset}, #{f.limit}
|
||||
</select>
|
||||
|
||||
<select id="selectRandomUnused" resultType="com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo">
|
||||
SELECT k.id, k.country, k.keyword, k.chinese, k.category, k.sub_category, k.category_l3, k.category_l4,
|
||||
(u.country IS NOT NULL) AS used, u.used_time, u.user_name
|
||||
FROM <include refid="usageJoin"/>
|
||||
WHERE <include refid="filterConds"/>
|
||||
ORDER BY RAND()
|
||||
LIMIT #{f.limit}
|
||||
</select>
|
||||
|
||||
<select id="countDupKeywords" resultType="long">
|
||||
SELECT COUNT(*)
|
||||
FROM (
|
||||
SELECT keyword FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
GROUP BY keyword
|
||||
HAVING COUNT(DISTINCT country) > 1
|
||||
) t
|
||||
</select>
|
||||
|
||||
<select id="selectFilterCountries" resultType="string">
|
||||
SELECT DISTINCT country
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND country IS NOT NULL AND country != ''
|
||||
ORDER BY country
|
||||
</select>
|
||||
|
||||
<select id="selectFilterTreeRows" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryTreeRow">
|
||||
SELECT DISTINCT category, sub_category, category_l3, category_l4
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND category IS NOT NULL AND category != ''
|
||||
ORDER BY category, sub_category, category_l3, category_l4
|
||||
</select>
|
||||
|
||||
<select id="selectCountryCounts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow">
|
||||
SELECT country AS name, COUNT(*) AS count
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND country IS NOT NULL AND country != ''
|
||||
GROUP BY country
|
||||
ORDER BY count DESC
|
||||
</select>
|
||||
|
||||
<select id="selectCategoryCounts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow">
|
||||
SELECT category AS name, COUNT(*) AS count
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND category IS NOT NULL AND category != ''
|
||||
GROUP BY category
|
||||
ORDER BY count DESC
|
||||
</select>
|
||||
|
||||
<select id="selectSubCategoryCounts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow">
|
||||
SELECT category, sub_category AS name, COUNT(*) AS count
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND category IS NOT NULL AND category != ''
|
||||
GROUP BY category, sub_category
|
||||
ORDER BY category, count DESC
|
||||
</select>
|
||||
|
||||
<select id="selectCategoryL3Counts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow">
|
||||
SELECT category, sub_category, category_l3 AS name, COUNT(*) AS count
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND category IS NOT NULL AND category != ''
|
||||
GROUP BY category, sub_category, category_l3
|
||||
ORDER BY category, count DESC
|
||||
</select>
|
||||
|
||||
<select id="selectExistingKeywords" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey">
|
||||
SELECT country, keyword
|
||||
FROM keyword_share
|
||||
WHERE company_id = #{companyId}
|
||||
AND (country, keyword) IN
|
||||
<foreach collection="keys" item="key" open="(" separator="," close=")">
|
||||
(#{key.country}, #{key.keyword})
|
||||
</foreach>
|
||||
</select>
|
||||
|
||||
<insert id="insertBatchIgnore">
|
||||
INSERT IGNORE INTO keyword_share
|
||||
(country, keyword, chinese, ktype, source, category, sub_category, category_l3, category_l4,
|
||||
user_name, add_time, company_id)
|
||||
VALUES
|
||||
<foreach collection="rows" item="row" separator=",">
|
||||
(#{row.country}, #{row.keyword}, #{row.chinese}, #{row.ktype}, #{row.source}, #{row.category},
|
||||
#{row.subCategory}, #{row.categoryL3}, #{row.categoryL4}, #{row.userName}, #{row.addTime}, #{row.companyId})
|
||||
</foreach>
|
||||
</insert>
|
||||
</mapper>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?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.keywordshare.mapper.KeywordUsageMapper">
|
||||
<!-- 使用状态批量写:UPSERT 语义对齐桌面版 ShareSync.mark(ON DUPLICATE KEY UPDATE),
|
||||
唯一键 uk_comp_cw(company_id, country, keyword) 冲突即刷新使用者与时间,天然幂等。 -->
|
||||
<insert id="upsertBatch">
|
||||
INSERT INTO keyword_usage (company_id, country, keyword, user_name, used_time)
|
||||
VALUES
|
||||
<foreach collection="rows" item="row" separator=",">
|
||||
(#{row.companyId}, #{row.country}, #{row.keyword}, #{row.userName}, #{row.usedTime})
|
||||
</foreach>
|
||||
ON DUPLICATE KEY UPDATE user_name = VALUES(user_name), used_time = VALUES(used_time)
|
||||
</insert>
|
||||
|
||||
<delete id="deleteBatch">
|
||||
DELETE FROM keyword_usage
|
||||
WHERE company_id = #{companyId}
|
||||
AND (country, keyword) IN
|
||||
<foreach collection="keys" item="key" open="(" separator="," close=")">
|
||||
(#{key.country}, #{key.keyword})
|
||||
</foreach>
|
||||
</delete>
|
||||
</mapper>
|
||||
@@ -56,7 +56,9 @@ class MigratedSqlEquivalenceTest {
|
||||
private static final int LEDGER_SELECTS = 60;
|
||||
/** 全部 mapper XML 里的 select 总数:账本 60 + TaskImageCache 5 + AsinResultCache 1。 */
|
||||
/** 66 → 67:会话容忍新增的 {@code AdminUserMapper#countLiveWorkFor} 也是一条 select。 */
|
||||
private static final int XML_SELECT_TOTAL = 67;
|
||||
// 67 → 78:keywordshare 模块新写 11 条 select,逐条登记进下方 NOT_MIGRATED
|
||||
// (与 SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 99 → 115)。
|
||||
private static final int XML_SELECT_TOTAL = 78;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -68,7 +70,19 @@ class MigratedSqlEquivalenceTest {
|
||||
// 与 increment 分两条是口径要求(计次先于响应、token 只在响应后有读数),不是随手加的第二条 SQL。
|
||||
"UserSecretUsageMapper#addTokens",
|
||||
// 失败任务重试:INSERT ... SELECT 复制采集明细行,非注解迁移件。
|
||||
"CollectDataItemMapper#copyItemsForRetry");
|
||||
"CollectDataItemMapper#copyItemsForRetry",
|
||||
// keywordshare 模块(五国关键词共享网页化,2026-10-23)新写 11 条 select。
|
||||
"KeywordShareMapper#countHit",
|
||||
"KeywordShareMapper#selectRows",
|
||||
"KeywordShareMapper#selectRandomUnused",
|
||||
"KeywordShareMapper#countDupKeywords",
|
||||
"KeywordShareMapper#selectFilterCountries",
|
||||
"KeywordShareMapper#selectFilterTreeRows",
|
||||
"KeywordShareMapper#selectCountryCounts",
|
||||
"KeywordShareMapper#selectCategoryCounts",
|
||||
"KeywordShareMapper#selectSubCategoryCounts",
|
||||
"KeywordShareMapper#selectCategoryL3Counts",
|
||||
"KeywordShareMapper#selectExistingKeywords");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -72,7 +72,9 @@ class SqlLayeringConventionTest {
|
||||
// 计次发生在发请求之前(含重试),token 只有响应回来才有读数,合成一条 upsert 就会漏计超时的那次。
|
||||
// 98 → 99:失败任务重试新增 {@code CollectDataItemMapper#copyItemsForRetry}
|
||||
// (INSERT ... SELECT 复制明细行),同样登记进 NOT_MIGRATED。
|
||||
private static final int XML_STATEMENT_TOTAL = 99;
|
||||
// 99 → 115:keywordshare 模块(五国关键词共享网页化,5 份 XML 16 条)新写语句,
|
||||
// 11 条 select 逐条登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(与本格同轮 67 → 78)。
|
||||
private static final int XML_STATEMENT_TOTAL = 115;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
package com.nanri.aiimage.modules.keywordshare.service;
|
||||
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordAddLogMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordDeleteLogMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordShareMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordUsageMapper;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareFilterQuery;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordAddLogEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordDeleteLogEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordShareEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordUsageEntity;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareAddRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareDeleteRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordUsageBatchRequest;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordSharePageVo;
|
||||
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 五国关键词共享 Service 单测:列表筛选/状态过滤/排序契约、分页与 usedDays 归一化、
|
||||
* mark 幂等、add 查重跳过 + 留痕 + 自动标记、delete 留痕、random、dup 计数。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeywordShareServiceTest {
|
||||
|
||||
private static final Long COMPANY_ID = 7L;
|
||||
private static final String VIEWER = "阿华";
|
||||
|
||||
@Mock
|
||||
private KeywordShareMapper keywordShareMapper;
|
||||
@Mock
|
||||
private KeywordUsageMapper keywordUsageMapper;
|
||||
@Mock
|
||||
private KeywordAddLogMapper keywordAddLogMapper;
|
||||
@Mock
|
||||
private KeywordDeleteLogMapper keywordDeleteLogMapper;
|
||||
|
||||
private KeywordShareService newService() {
|
||||
return new KeywordShareService(keywordShareMapper, keywordUsageMapper,
|
||||
keywordAddLogMapper, keywordDeleteLogMapper);
|
||||
}
|
||||
|
||||
private static KeywordShareRowVo row(long id, String keyword, boolean used, String usedUser) {
|
||||
KeywordShareRowVo vo = new KeywordShareRowVo();
|
||||
vo.setId(id);
|
||||
vo.setCountry("英国");
|
||||
vo.setKeyword(keyword);
|
||||
vo.setChinese("翻译" + id);
|
||||
vo.setUsed(used);
|
||||
if (used) {
|
||||
vo.setUsedTime(LocalDateTime.now().minusHours(id));
|
||||
vo.setUsedUser(usedUser);
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 列表
|
||||
|
||||
@Test
|
||||
@DisplayName("列表:命中数按用户筛选口径、命中内已使用数单独数一遍、dup 计数进统计条")
|
||||
void pageComputesHitUsedUnusedAndDup() {
|
||||
KeywordShareFilterQuery all = new KeywordShareFilterQuery();
|
||||
all.setCompanyId(COMPANY_ID);
|
||||
all.setStatus("all");
|
||||
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(10L, 4L);
|
||||
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
|
||||
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(3L);
|
||||
|
||||
KeywordSharePageVo vo = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
|
||||
null, "all", 0, false, 1L, 200L);
|
||||
|
||||
assertThat(vo.getTotal()).isEqualTo(10L);
|
||||
assertThat(vo.getStats().getHit()).isEqualTo(10L);
|
||||
assertThat(vo.getStats().getUsed()).isEqualTo(4L);
|
||||
assertThat(vo.getStats().getUnused()).isEqualTo(6L);
|
||||
assertThat(vo.getStats().getDup()).isEqualTo(3L);
|
||||
// 第二次 countHit 是「命中内已使用数」,必须把 status 换成 used、其余条件原样
|
||||
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
|
||||
verify(keywordShareMapper, org.mockito.Mockito.times(2)).countHit(captor.capture());
|
||||
assertThat(captor.getAllValues().get(0).getStatus()).isEqualTo("all");
|
||||
assertThat(captor.getAllValues().get(1).getStatus()).isEqualTo("used");
|
||||
assertThat(captor.getAllValues().get(1).getCompanyId()).isEqualTo(COMPANY_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("列表:状态过滤 used/unused 时命中内已/未使用数直接由命中推导,不再多查一遍")
|
||||
void pageWithActiveStatusFilterDerivesStats() {
|
||||
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(6L);
|
||||
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
|
||||
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
|
||||
|
||||
KeywordSharePageVo used = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
|
||||
null, "used", 0, false, 1L, 200L);
|
||||
assertThat(used.getStats().getHit()).isEqualTo(6L);
|
||||
assertThat(used.getStats().getUsed()).isEqualTo(6L);
|
||||
assertThat(used.getStats().getUnused()).isZero();
|
||||
|
||||
KeywordSharePageVo unused = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
|
||||
null, "unused", 0, false, 1L, 200L);
|
||||
assertThat(unused.getStats().getUsed()).isZero();
|
||||
assertThat(unused.getStats().getUnused()).isEqualTo(6L);
|
||||
// 状态过滤生效时不再为「命中内已使用数」多查一遍:两次 page 各查 1 次
|
||||
verify(keywordShareMapper, org.mockito.Mockito.times(2)).countHit(any(KeywordShareFilterQuery.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("列表:筛选条件(类目/搜索/仅看我/usedDays)与分页进 Mapper 载体,size 上限 500")
|
||||
void pageCarriesFilterAndNormalizedPaging() {
|
||||
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(0L);
|
||||
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
|
||||
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
|
||||
|
||||
newService().page(COMPANY_ID, VIEWER, " 英国 ", "厨房用品", "锅具", "煎锅", "平底锅",
|
||||
" storage ", "all", 30, true, 0L, 1000L);
|
||||
|
||||
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
|
||||
verify(keywordShareMapper).selectRows(captor.capture());
|
||||
KeywordShareFilterQuery filter = captor.getValue();
|
||||
assertThat(filter.getCountry()).isEqualTo("英国");
|
||||
assertThat(filter.getCategory()).isEqualTo("厨房用品");
|
||||
assertThat(filter.getSubCategory()).isEqualTo("锅具");
|
||||
assertThat(filter.getCategoryL3()).isEqualTo("煎锅");
|
||||
assertThat(filter.getCategoryL4()).isEqualTo("平底锅");
|
||||
assertThat(filter.getSearch()).isEqualTo("storage");
|
||||
assertThat(filter.getStatus()).isEqualTo("all");
|
||||
assertThat(filter.getOnlyMine()).isTrue();
|
||||
assertThat(filter.getUserName()).isEqualTo(VIEWER);
|
||||
// usedDays=30:往前推 30 天
|
||||
assertThat(filter.getUsedSince()).isNotNull();
|
||||
assertThat(filter.getUsedSince()).isBefore(LocalDateTime.now());
|
||||
assertThat(filter.getUsedSince()).isAfter(LocalDateTime.now().minusDays(31));
|
||||
// 分页归一化:page=0→1、size=1000→500
|
||||
assertThat(filter.getOffset()).isZero();
|
||||
assertThat(filter.getLimit()).isEqualTo(500L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("usedDays=1 表示「今天」:时间下限取当日零点;不传/0 表示不限")
|
||||
void usedDaysOneMeansStartOfToday() {
|
||||
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(0L);
|
||||
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
|
||||
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
|
||||
|
||||
newService().page(COMPANY_ID, VIEWER, null, null, null, null, null, null, "all", 1, false, 1L, 200L);
|
||||
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
|
||||
verify(keywordShareMapper).selectRows(captor.capture());
|
||||
assertThat(captor.getValue().getUsedSince()).isEqualTo(LocalDate.now().atStartOfDay());
|
||||
|
||||
newService().page(COMPANY_ID, VIEWER, null, null, null, null, null, null, "all", null, false, 1L, 200L);
|
||||
verify(keywordShareMapper, org.mockito.Mockito.times(2)).selectRows(captor.capture());
|
||||
assertThat(captor.getValue().getUsedSince()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("列表:行按 Mapper 返回顺序透传(SQL 侧已按未使用在前、已使用按 used_time 升序排好),未使用行不带使用者")
|
||||
void pageRowsKeepMapperOrderAndNormalizeUnusedRows() {
|
||||
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(3L);
|
||||
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of(
|
||||
row(2, "kw-old-used", true, "张三"),
|
||||
row(3, "kw-new-used", true, VIEWER),
|
||||
row(1, "kw-unused", false, "不该有名字")));
|
||||
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
|
||||
|
||||
KeywordSharePageVo vo = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
|
||||
null, "all", 0, false, 1L, 200L);
|
||||
|
||||
assertThat(vo.getRows()).extracting(KeywordShareRowVo::getId).containsExactly(2L, 3L, 1L);
|
||||
assertThat(vo.getRows().get(0).isUsed()).isTrue();
|
||||
assertThat(vo.getRows().get(0).getUsedUser()).isEqualTo("张三");
|
||||
assertThat(vo.getRows().get(2).isUsed()).isFalse();
|
||||
assertThat(vo.getRows().get(2).getUsedTime()).isNull();
|
||||
assertThat(vo.getRows().get(2).getUsedUser()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("排序契约:Mapper XML 的 ORDER BY 必须是「已使用在前(对齐桌面版)、按 used_time 升序」,且禁止 ${} 拼接")
|
||||
void mapperXmlKeepsSortContractAndPlaceholderOnly() throws Exception {
|
||||
String xml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordshare/KeywordShareMapper.xml"), StandardCharsets.UTF_8);
|
||||
assertThat(xml).contains("ORDER BY (u.country IS NULL) ASC, u.used_time ASC");
|
||||
assertThat(xml).doesNotContain("${");
|
||||
String usageXml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordshare/KeywordUsageMapper.xml"), StandardCharsets.UTF_8);
|
||||
assertThat(usageXml).contains("ON DUPLICATE KEY UPDATE").doesNotContain("${");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 标记/取消使用
|
||||
|
||||
@Test
|
||||
@DisplayName("mark:UPSERT 幂等——重复标记同一词两次结果一致,使用者与时间都取服务端当前值")
|
||||
void markIsIdempotentWithServerTime() {
|
||||
KeywordUsageBatchRequest request = new KeywordUsageBatchRequest();
|
||||
KeywordUsageBatchRequest.Item item1 = new KeywordUsageBatchRequest.Item();
|
||||
item1.setCountry("英国");
|
||||
item1.setKeyword(" storage box ");
|
||||
KeywordUsageBatchRequest.Item item2 = new KeywordUsageBatchRequest.Item();
|
||||
item2.setCountry("德国");
|
||||
item2.setKeyword("aufbewahrungsbox");
|
||||
request.setItems(List.of(item1, item2));
|
||||
|
||||
KeywordShareService service = newService();
|
||||
LocalDateTime before = LocalDateTime.now();
|
||||
var first = service.mark(request, COMPANY_ID, VIEWER);
|
||||
var second = service.mark(request, COMPANY_ID, VIEWER);
|
||||
LocalDateTime after = LocalDateTime.now();
|
||||
|
||||
assertThat(first.getMarked()).isEqualTo(2);
|
||||
assertThat(second.getMarked()).isEqualTo(2);
|
||||
|
||||
ArgumentCaptor<List<KeywordUsageEntity>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordUsageMapper, org.mockito.Mockito.times(2)).upsertBatch(captor.capture());
|
||||
List<KeywordUsageEntity> rows = captor.getAllValues().get(0);
|
||||
assertThat(rows).hasSize(2);
|
||||
assertThat(rows).allSatisfy(row -> {
|
||||
assertThat(row.getCompanyId()).isEqualTo(COMPANY_ID);
|
||||
assertThat(row.getUserName()).isEqualTo(VIEWER);
|
||||
assertThat(row.getUsedTime()).isAfterOrEqualTo(before).isBeforeOrEqualTo(after);
|
||||
});
|
||||
assertThat(rows.get(0).getKeyword()).isEqualTo("storage box");
|
||||
assertThat(rows.get(1).getCountry()).isEqualTo("德国");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("mark:批内重复键去重、空键跳过;全空时不动库")
|
||||
void markSkipsBlankAndDuplicateKeys() {
|
||||
KeywordUsageBatchRequest request = new KeywordUsageBatchRequest();
|
||||
KeywordUsageBatchRequest.Item blank = new KeywordUsageBatchRequest.Item();
|
||||
blank.setCountry("英国");
|
||||
blank.setKeyword(" ");
|
||||
KeywordUsageBatchRequest.Item dup = new KeywordUsageBatchRequest.Item();
|
||||
dup.setCountry("英国");
|
||||
dup.setKeyword("box");
|
||||
KeywordUsageBatchRequest.Item dupAgain = new KeywordUsageBatchRequest.Item();
|
||||
dupAgain.setCountry(" 英国 ");
|
||||
dupAgain.setKeyword("box");
|
||||
request.setItems(List.of(blank, dup, dupAgain));
|
||||
|
||||
var result = newService().mark(request, COMPANY_ID, VIEWER);
|
||||
|
||||
assertThat(result.getMarked()).isEqualTo(1);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KeywordUsageEntity>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordUsageMapper).upsertBatch(captor.capture());
|
||||
assertThat(captor.getValue()).hasSize(1);
|
||||
assertThat(captor.getValue().get(0).getKeyword()).isEqualTo("box");
|
||||
|
||||
KeywordUsageBatchRequest allBlank = new KeywordUsageBatchRequest();
|
||||
KeywordUsageBatchRequest.Item item = new KeywordUsageBatchRequest.Item();
|
||||
item.setKeyword(" ");
|
||||
allBlank.setItems(List.of(item));
|
||||
assertThat(newService().mark(allBlank, COMPANY_ID, VIEWER).getMarked()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("unmark:按 (company, country, keyword) 删行,返回实际删除条数")
|
||||
void unmarkDeletesRowsAndCountsAffected() {
|
||||
KeywordUsageBatchRequest request = new KeywordUsageBatchRequest();
|
||||
KeywordUsageBatchRequest.Item item = new KeywordUsageBatchRequest.Item();
|
||||
item.setCountry("英国");
|
||||
item.setKeyword("box");
|
||||
request.setItems(List.of(item));
|
||||
when(keywordUsageMapper.deleteBatch(eq(COMPANY_ID), anyList())).thenReturn(1);
|
||||
|
||||
var result = newService().unmark(request, COMPANY_ID);
|
||||
|
||||
assertThat(result.getUnmarked()).isEqualTo(1);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KeywordShareKey>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordUsageMapper).deleteBatch(eq(COMPANY_ID), captor.capture());
|
||||
assertThat(captor.getValue().get(0).getKeyword()).isEqualTo("box");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 添加
|
||||
|
||||
@Test
|
||||
@DisplayName("add:查重跳过已存在词,空词/批内重复跳过;成功行写词本体 + 添加留痕 + 自动标记已使用")
|
||||
void addSkipsExistingAndBlankAndWritesLogsAndAutoMarks() {
|
||||
KeywordShareAddRequest request = new KeywordShareAddRequest();
|
||||
KeywordShareAddRequest.Item good = new KeywordShareAddRequest.Item();
|
||||
good.setCountry("英国");
|
||||
good.setKeyword(" storage box ");
|
||||
good.setChinese("收纳盒");
|
||||
KeywordShareAddRequest.Item existing = new KeywordShareAddRequest.Item();
|
||||
existing.setCountry("德国");
|
||||
existing.setKeyword("aufbewahrungsbox");
|
||||
existing.setChinese("收纳箱");
|
||||
KeywordShareAddRequest.Item blank = new KeywordShareAddRequest.Item();
|
||||
blank.setCountry("法国");
|
||||
blank.setKeyword(" ");
|
||||
KeywordShareAddRequest.Item dup = new KeywordShareAddRequest.Item();
|
||||
dup.setCountry("英国");
|
||||
dup.setKeyword("storage box");
|
||||
request.setItems(List.of(good, existing, blank, dup));
|
||||
|
||||
KeywordShareKey existingKey = KeywordShareKey.of("德国", "aufbewahrungsbox");
|
||||
when(keywordShareMapper.selectExistingKeywords(eq(COMPANY_ID), anyList())).thenReturn(List.of(existingKey));
|
||||
|
||||
LocalDateTime before = LocalDateTime.now();
|
||||
var result = newService().add(request, COMPANY_ID, VIEWER);
|
||||
|
||||
assertThat(result.getAdded()).isEqualTo(1);
|
||||
assertThat(result.getSkipped()).isEqualTo(3);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KeywordShareEntity>> insertCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordShareMapper).insertBatchIgnore(insertCaptor.capture());
|
||||
KeywordShareEntity inserted = insertCaptor.getValue().get(0);
|
||||
assertThat(inserted.getCountry()).isEqualTo("英国");
|
||||
assertThat(inserted.getKeyword()).isEqualTo("storage box");
|
||||
assertThat(inserted.getChinese()).isEqualTo("收纳盒");
|
||||
assertThat(inserted.getKtype()).isEqualTo("主关键词");
|
||||
assertThat(inserted.getSource()).isEqualTo("手动添加");
|
||||
assertThat(inserted.getCompanyId()).isEqualTo(COMPANY_ID);
|
||||
assertThat(inserted.getUserName()).isEqualTo(VIEWER);
|
||||
assertThat(inserted.getAddTime()).isAfterOrEqualTo(before);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KeywordAddLogEntity>> logCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordAddLogMapper).insertBatch(logCaptor.capture());
|
||||
assertThat(logCaptor.getValue()).hasSize(1);
|
||||
assertThat(logCaptor.getValue().get(0).getKeyword()).isEqualTo("storage box");
|
||||
assertThat(logCaptor.getValue().get(0).getUserName()).isEqualTo(VIEWER);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KeywordUsageEntity>> usageCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordUsageMapper).upsertBatch(usageCaptor.capture());
|
||||
assertThat(usageCaptor.getValue()).hasSize(1);
|
||||
assertThat(usageCaptor.getValue().get(0).getKeyword()).isEqualTo("storage box");
|
||||
assertThat(usageCaptor.getValue().get(0).getUserName()).isEqualTo(VIEWER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("add:全部跳过时不动任何表(词本体/留痕/使用状态都不写)")
|
||||
void addWithNothingToAddTouchesNothing() {
|
||||
KeywordShareAddRequest request = new KeywordShareAddRequest();
|
||||
KeywordShareAddRequest.Item blank = new KeywordShareAddRequest.Item();
|
||||
blank.setCountry("英国");
|
||||
blank.setKeyword("");
|
||||
request.setItems(List.of(blank));
|
||||
|
||||
var result = newService().add(request, COMPANY_ID, VIEWER);
|
||||
|
||||
assertThat(result.getAdded()).isZero();
|
||||
assertThat(result.getSkipped()).isEqualTo(1);
|
||||
verify(keywordShareMapper, never()).insertBatchIgnore(anyList());
|
||||
verify(keywordAddLogMapper, never()).insertBatch(anyList());
|
||||
verify(keywordUsageMapper, never()).upsertBatch(anyList());
|
||||
verify(keywordShareMapper, never()).selectExistingKeywords(any(), anyList());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 删除
|
||||
|
||||
@Test
|
||||
@DisplayName("delete:只删本公司存在的行并逐行写删除留痕(谁删了哪个词可追溯)")
|
||||
void deleteWritesDeleteLogForCompanyRows() {
|
||||
KeywordShareDeleteRequest request = new KeywordShareDeleteRequest();
|
||||
request.setIds(List.of(1L, 2L, 999L));
|
||||
|
||||
KeywordShareEntity row1 = new KeywordShareEntity();
|
||||
row1.setId(1L);
|
||||
row1.setCountry("英国");
|
||||
row1.setKeyword("box");
|
||||
row1.setCompanyId(COMPANY_ID);
|
||||
KeywordShareEntity row2 = new KeywordShareEntity();
|
||||
row2.setId(2L);
|
||||
row2.setCountry("德国");
|
||||
row2.setKeyword("kiste");
|
||||
row2.setCompanyId(COMPANY_ID);
|
||||
KeywordShareEntity foreign = new KeywordShareEntity();
|
||||
foreign.setId(999L);
|
||||
foreign.setCountry("法国");
|
||||
foreign.setKeyword("mot-etranger");
|
||||
foreign.setCompanyId(8L);
|
||||
when(keywordShareMapper.selectBatchIds(List.of(1L, 2L, 999L))).thenReturn(List.of(row1, row2, foreign));
|
||||
|
||||
LocalDateTime before = LocalDateTime.now();
|
||||
var result = newService().delete(request, COMPANY_ID, VIEWER);
|
||||
|
||||
// 公司隔离:999 号行是别家公司的,即使 id 在请求里也绝不能删
|
||||
assertThat(result.getDeleted()).isEqualTo(2);
|
||||
verify(keywordShareMapper).deleteBatchIds(List.of(1L, 2L));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<KeywordDeleteLogEntity>> logCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(keywordDeleteLogMapper).insertBatch(logCaptor.capture());
|
||||
List<KeywordDeleteLogEntity> logs = logCaptor.getValue();
|
||||
assertThat(logs).hasSize(2);
|
||||
assertThat(logs).extracting(KeywordDeleteLogEntity::getKeyword).containsExactly("box", "kiste");
|
||||
assertThat(logs).allSatisfy(log -> {
|
||||
assertThat(log.getCompanyId()).isEqualTo(COMPANY_ID);
|
||||
assertThat(log.getUserName()).isEqualTo(VIEWER);
|
||||
assertThat(log.getDeleteTime()).isAfterOrEqualTo(before);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("delete:请求里的行都不属于本公司(或不存在)时,不动库也不留痕")
|
||||
void deleteWithNoCompanyRowsTouchesNothing() {
|
||||
KeywordShareDeleteRequest request = new KeywordShareDeleteRequest();
|
||||
request.setIds(List.of(1L));
|
||||
when(keywordShareMapper.selectBatchIds(anyList())).thenReturn(List.of());
|
||||
|
||||
var result = newService().delete(request, COMPANY_ID, VIEWER);
|
||||
|
||||
assertThat(result.getDeleted()).isZero();
|
||||
verify(keywordShareMapper, never()).deleteBatchIds(anyList());
|
||||
verify(keywordDeleteLogMapper, never()).insertBatch(anyList());
|
||||
}
|
||||
// ---------------------------------------------------------------- 随机抽词
|
||||
|
||||
@Test
|
||||
@DisplayName("random:只从「未使用」池抽,条数默认 10、上限 100、下限 1")
|
||||
void randomUsesUnusedPoolWithClampedCount() {
|
||||
when(keywordShareMapper.selectRandomUnused(any(KeywordShareFilterQuery.class))).thenReturn(List.of(
|
||||
row(5, "kw-random", false, "")));
|
||||
|
||||
var result = newService().random(COMPANY_ID, VIEWER, "英国", null, null, null, null, null, 5L);
|
||||
|
||||
assertThat(result).hasSize(1);
|
||||
assertThat(result.get(0).getKeyword()).isEqualTo("kw-random");
|
||||
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
|
||||
verify(keywordShareMapper).selectRandomUnused(captor.capture());
|
||||
assertThat(captor.getValue().getStatus()).isEqualTo("unused");
|
||||
assertThat(captor.getValue().getLimit()).isEqualTo(5L);
|
||||
assertThat(captor.getValue().getCountry()).isEqualTo("英国");
|
||||
|
||||
newService().random(COMPANY_ID, VIEWER, null, null, null, null, null, null, null);
|
||||
verify(keywordShareMapper, org.mockito.Mockito.times(2)).selectRandomUnused(captor.capture());
|
||||
assertThat(captor.getValue().getLimit()).isEqualTo(KeywordShareService.DEFAULT_RANDOM_COUNT);
|
||||
|
||||
newService().random(COMPANY_ID, VIEWER, null, null, null, null, null, null, 1000L);
|
||||
verify(keywordShareMapper, org.mockito.Mockito.times(3)).selectRandomUnused(captor.capture());
|
||||
assertThat(captor.getValue().getLimit()).isEqualTo(KeywordShareService.MAX_RANDOM_COUNT);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 防回流的供应商隔离自检
|
||||
|
||||
@Test
|
||||
@DisplayName("公司隔离:全部 Mapper 写路径的第一个参数都是服务端给的 companyId(抽查写 SQL 收口)")
|
||||
void writeSqlStaysInMapperLayerWithCompanyScope() throws Exception {
|
||||
String shareXml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordshare/KeywordShareMapper.xml"), StandardCharsets.UTF_8);
|
||||
// 词本体的读路径一律带 company_id 条件(含 dup 子查询与类目名册)
|
||||
long scopedSelects = shareXml.lines().filter(line -> line.contains("company_id = #{")).count();
|
||||
assertThat(scopedSelects).isGreaterThanOrEqualTo(5);
|
||||
String usageXml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordshare/KeywordUsageMapper.xml"), StandardCharsets.UTF_8);
|
||||
assertThat(usageXml).contains("company_id = #{companyId}");
|
||||
String addXml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordshare/KeywordAddLogMapper.xml"), StandardCharsets.UTF_8);
|
||||
String deleteXml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordshare/KeywordDeleteLogMapper.xml"), StandardCharsets.UTF_8);
|
||||
assertThat(addXml + deleteXml)
|
||||
.contains("company_id", "user_name")
|
||||
.doesNotContain("${");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user