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:
2026-10-23 21:54:52 +08:00
parent 6d9d4b98b2
commit 2d408199d6
38 changed files with 2077 additions and 4 deletions
@@ -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* 的前缀。
@@ -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) {
}
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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 &gt;= #{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) &gt; 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>