feat(admin): 实现只读词库管理后台
- 新增 Spring Boot 3 后端:JWT 认证、六个业务模块查询接口、Caffeine 聚合缓存与只读事务约束 - 新增 Vue 3 管理前端:登录、概览、词书、词条、词根词族、近反义词与数据质量 - 补充前后端 README、环境变量示例与本地构建部署说明 - 同步 OpenSpec 变更文档与任务进度(64/65,只读数据库账号待确认) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
131c2b6353
commit
4e68ba3890
137 files changed
+15423
-10
No files matched your search
@@ -0,0 +1,18 @@
|
||||
# 复制为 .env 或直接在运行环境中设置;不要提交真实值。
|
||||
DB_URL=jdbc:mysql://s1.void01.com:3306/word_market?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&connectTimeout=10000&socketTimeout=30000
|
||||
DB_USERNAME=your_read_only_user
|
||||
DB_PASSWORD=your_password
|
||||
DB_POOL_SIZE=15
|
||||
|
||||
ADMIN_USERNAME=admin
|
||||
# BCrypt 哈希,可用 htpasswd 生成:htpasswd -bnBC 10 "" 'your-password' | tr -d ':\n'
|
||||
ADMIN_PASSWORD_HASH=$2a$10$replace_with_a_real_bcrypt_hash
|
||||
JWT_SECRET=replace_with_a_random_secret_at_least_32_characters
|
||||
ADMIN_TOKEN_TTL_HOURS=8
|
||||
|
||||
CORS_ALLOWED_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||
COVER_BASE_URL=https://static.beingfine.cn
|
||||
CACHE_TTL_MINUTES=10
|
||||
CACHE_MAXIMUM_SIZE=200
|
||||
KNOWN_MISSING_ZPK_KEYS=0_53785_101_1775241011
|
||||
SERVER_PORT=8080
|
||||
+113
-4
@@ -1,7 +1,116 @@
|
||||
# backend — 单词管理后端
|
||||
# backend — 词库只读管理后端
|
||||
|
||||
占位目录,技术栈待定。
|
||||
Spring Boot 3.3 + Java 17 + MyBatis-Plus,只读连接 MySQL `word_market`,为 `frontend/` 提供查询接口。
|
||||
|
||||
用途:为 `frontend` 提供词书、词条及关联数据的查询与编辑接口,数据来源为 `importer` 生成的数据库。
|
||||
## 只读约束
|
||||
|
||||
后续确定技术栈与目录结构后在此实现。
|
||||
- 所有业务接口只执行 `SELECT`,代码中不存在任何写 Mapper。
|
||||
- 所有 Service 标注 `@Transactional(readOnly = true)`。
|
||||
- HikariCP 设置 `read-only: true`。
|
||||
- 数据库侧建议使用仅具备 `SELECT` 权限的账号;创建只读账号属于运维动作,需要单独确认后执行。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- JDK 17
|
||||
- Maven 3.9+
|
||||
- 可访问的 MySQL `word_market` 数据库
|
||||
|
||||
## 配置
|
||||
|
||||
复制 `.env.example` 或参考 `src/main/resources/application.example.yml`。所有敏感值通过环境变量注入,仓库不保存真实凭据。
|
||||
|
||||
| 变量 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `DB_URL` | 否 | JDBC 地址,默认 `jdbc:mysql://s1.void01.com:3306/word_market?...` |
|
||||
| `DB_USERNAME` | 是 | 数据库用户名 |
|
||||
| `DB_PASSWORD` | 是 | 数据库密码 |
|
||||
| `DB_POOL_SIZE` | 否 | Hikari 最大连接数,默认 15 |
|
||||
| `ADMIN_USERNAME` | 是 | 管理员用户名 |
|
||||
| `ADMIN_PASSWORD_HASH` | 是 | 管理员密码的 BCrypt 哈希 |
|
||||
| `JWT_SECRET` | 是 | HS256 签名密钥,至少 32 字节 |
|
||||
| `ADMIN_TOKEN_TTL_HOURS` | 否 | token 有效期,默认 8 小时 |
|
||||
| `CORS_ALLOWED_ORIGINS` | 否 | 逗号分隔的前端来源,默认 `http://localhost:5173,http://127.0.0.1:5173` |
|
||||
| `COVER_BASE_URL` | 否 | 封面 CDN 前缀,默认 `https://static.beingfine.cn` |
|
||||
| `CACHE_TTL_MINUTES` | 否 | 聚合缓存时长,默认 10 分钟 |
|
||||
| `CACHE_MAXIMUM_SIZE` | 否 | 聚合缓存条目上限,默认 200 |
|
||||
| `KNOWN_MISSING_ZPK_KEYS` | 否 | 已知缺失的 zpk 文件键,逗号分隔 |
|
||||
| `SERVER_PORT` | 否 | 服务端口,默认 8080 |
|
||||
|
||||
缺少 `ADMIN_USERNAME`、`ADMIN_PASSWORD_HASH` 或 `JWT_SECRET` 时应用会拒绝启动并输出缺失项;`JWT_SECRET` 少于 32 字节同样拒绝启动。
|
||||
|
||||
生成 BCrypt 哈希:
|
||||
|
||||
```bash
|
||||
htpasswd -bnBC 10 "" 'your-password' | tr -d ':\n'
|
||||
# 或
|
||||
python -c "import bcrypt; print(bcrypt.hashpw(b'your-password', bcrypt.gensalt()).decode())"
|
||||
```
|
||||
|
||||
## 启动
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
或构建后运行:
|
||||
|
||||
```bash
|
||||
mvn -DskipTests package
|
||||
java -jar target/word-market-admin-0.1.0.jar
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
统一前缀 `/api`,响应结构 `{ code, message, data }`;分页为 `{ items, total, page, size }`;数值 ID 以字符串返回。
|
||||
|
||||
| 模块 | 接口 |
|
||||
|---|---|
|
||||
| 认证 | `POST /api/auth/login` |
|
||||
| 概览 | `GET /api/dashboard/summary`、`/exam-distribution`、`/book-size-top`、`/pos-distribution` |
|
||||
| 词书 | `GET /api/books`、`/api/books/{id}`、`/api/books/{id}/entries`、`/api/exams` |
|
||||
| 词条 | `GET /api/entries`、`/api/entries/{id}`、`/{id}/senses`、`/phrases`、`/examples`、`/confusables`、`/variants`、`/books` |
|
||||
| 词根词族 | `GET /api/morphemes`、`/api/morphemes/{id}`、`/api/cards`、`/api/cards/{id}`、`/api/families`、`/api/families/{id}`、`/api/families/{id}/tree` |
|
||||
| 近反义词 | `GET /api/synonyms`、`/api/synonyms/{wordId}`、`/api/synonyms/group-size-distribution` |
|
||||
| 数据质量 | `GET /api/quality/summary`、`/declared-vs-actual`、`/missing-references`、`/cross-domain-coverage` |
|
||||
|
||||
概览与质量聚合接口支持 `?refresh=true` 跳过缓存并重新计算。分页默认每页 20 条,最大 100 条。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
mvn test
|
||||
```
|
||||
|
||||
覆盖分页边界、认证成功/失败、404、空状态与缓存刷新行为。
|
||||
|
||||
## 部署
|
||||
|
||||
后端产出可执行 jar,前端由 Nginx 托管并反向代理 `/api`。示例:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
root /srv/word-market/frontend/dist;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
生产环境必须使用 HTTPS,并按需收紧 `CORS_ALLOWED_ORIGINS`。
|
||||
|
||||
## 已知数据异常
|
||||
|
||||
`KNOWN_MISSING_ZPK_KEYS` 默认登记 `0_53785_101_1775241011`,对应 importer 导出时缺失的一个 zpk 文件。数据质量模块会列出仍引用该文件键的词书关联;如后续补齐文件或更换数据快照,调整该配置即可。
|
||||
@@ -0,0 +1,94 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.3.5</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.wordmarket</groupId>
|
||||
<artifactId>word-market-admin</artifactId>
|
||||
<version>0.1.0</version>
|
||||
<name>word-market-admin</name>
|
||||
<description>只读词库管理后台</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<mybatis-plus.version>3.5.7</mybatis-plus.version>
|
||||
<jjwt.version>0.12.6</jjwt.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-cache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.wordmarket.admin;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
|
||||
@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class)
|
||||
@ConfigurationPropertiesScan
|
||||
@EnableCaching
|
||||
public class AdminApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AdminApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
public record ApiResponse<T>(int code, String message, T data) {
|
||||
|
||||
public static <T> ApiResponse<T> ok(T data) {
|
||||
return new ApiResponse<>(0, "ok", data);
|
||||
}
|
||||
|
||||
public static ApiResponse<Void> error(int code, String message) {
|
||||
return new ApiResponse<>(code, message, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class BizException extends RuntimeException {
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
public BizException(HttpStatus status, String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public HttpStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public static BizException badRequest(String message) {
|
||||
return new BizException(HttpStatus.BAD_REQUEST, message);
|
||||
}
|
||||
|
||||
public static BizException unauthorized(String message) {
|
||||
return new BizException(HttpStatus.UNAUTHORIZED, message);
|
||||
}
|
||||
|
||||
public static BizException notFound(String message) {
|
||||
return new BizException(HttpStatus.NOT_FOUND, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BizException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleBiz(BizException ex) {
|
||||
return ResponseEntity.status(ex.getStatus())
|
||||
.body(ApiResponse.error(ex.getStatus().value(), ex.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleValidation(MethodArgumentNotValidException ex) {
|
||||
FieldError fieldError = ex.getBindingResult().getFieldError();
|
||||
String message = fieldError == null
|
||||
? "请求参数不合法"
|
||||
: "缺少或非法字段: " + fieldError.getField();
|
||||
return ResponseEntity.badRequest().body(ApiResponse.error(400, message));
|
||||
}
|
||||
|
||||
@ExceptionHandler({ConstraintViolationException.class, MethodArgumentTypeMismatchException.class,
|
||||
HttpMessageNotReadableException.class})
|
||||
public ResponseEntity<ApiResponse<Void>> handleBadRequest(Exception ex) {
|
||||
return ResponseEntity.badRequest().body(ApiResponse.error(400, "请求参数不合法"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleUnexpected(Exception ex) {
|
||||
log.error("Unhandled exception", ex);
|
||||
return ResponseEntity.internalServerError().body(ApiResponse.error(500, "服务暂时不可用"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record Items<T>(List<T> items) {
|
||||
|
||||
public static <T> Items<T> of(List<T> items) {
|
||||
return new Items<>(items);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PageResult<T>(List<T> items, long total, int page, int size) {
|
||||
|
||||
public static <T> PageResult<T> of(List<T> items, long total, int page, int size) {
|
||||
return new PageResult<>(items, total, page, size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
public final class Pages {
|
||||
|
||||
private static final int DEFAULT_SIZE = 20;
|
||||
private static final int MAX_SIZE = 100;
|
||||
|
||||
private Pages() {
|
||||
}
|
||||
|
||||
public static int page(Integer page) {
|
||||
return page == null || page < 1 ? 1 : page;
|
||||
}
|
||||
|
||||
public static int size(Integer size) {
|
||||
if (size == null || size < 1) {
|
||||
return DEFAULT_SIZE;
|
||||
}
|
||||
return Math.min(size, MAX_SIZE);
|
||||
}
|
||||
|
||||
public static int offset(int page, int size) {
|
||||
long offset = (long) (page - 1) * size;
|
||||
return (int) Math.min(offset, Integer.MAX_VALUE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestLogFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RequestLogFilter.class);
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
long started = System.currentTimeMillis();
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
long elapsed = System.currentTimeMillis() - started;
|
||||
log.info("{} {} -> {} ({} ms)", request.getMethod(), request.getRequestURI(),
|
||||
response.getStatus(), elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.wordmarket.admin.config;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@ConfigurationProperties(prefix = "admin")
|
||||
public class AdminProperties implements InitializingBean {
|
||||
|
||||
private String username;
|
||||
private String passwordHash;
|
||||
private String jwtSecret;
|
||||
private int tokenTtlHours = 8;
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
List<String> missing = new ArrayList<>();
|
||||
if (isBlank(username)) {
|
||||
missing.add("ADMIN_USERNAME / admin.username");
|
||||
}
|
||||
if (isBlank(passwordHash)) {
|
||||
missing.add("ADMIN_PASSWORD_HASH / admin.password-hash");
|
||||
}
|
||||
if (isBlank(jwtSecret)) {
|
||||
missing.add("JWT_SECRET / admin.jwt-secret");
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
throw new IllegalStateException("缺少管理员配置: " + String.join(", ", missing));
|
||||
}
|
||||
if (jwtSecret.getBytes(java.nio.charset.StandardCharsets.UTF_8).length < 32) {
|
||||
throw new IllegalStateException("JWT_SECRET 至少需要 32 字节(当前 "
|
||||
+ jwtSecret.getBytes(java.nio.charset.StandardCharsets.UTF_8).length + " 字节)");
|
||||
}
|
||||
if (tokenTtlHours <= 0) {
|
||||
throw new IllegalStateException("ADMIN_TOKEN_TTL_HOURS 必须大于 0");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public void setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
public String getJwtSecret() {
|
||||
return jwtSecret;
|
||||
}
|
||||
|
||||
public void setJwtSecret(String jwtSecret) {
|
||||
this.jwtSecret = jwtSecret;
|
||||
}
|
||||
|
||||
public int getTokenTtlHours() {
|
||||
return tokenTtlHours;
|
||||
}
|
||||
|
||||
public void setTokenTtlHours(int tokenTtlHours) {
|
||||
this.tokenTtlHours = tokenTtlHours;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.wordmarket.admin.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "app")
|
||||
public class AppProperties {
|
||||
|
||||
private final Cors cors = new Cors();
|
||||
private final Cache cache = new Cache();
|
||||
private final Quality quality = new Quality();
|
||||
private String coverBaseUrl = "https://static.beingfine.cn";
|
||||
|
||||
public static class Cors {
|
||||
private String allowedOrigins = "http://localhost:5173";
|
||||
|
||||
public String getAllowedOrigins() {
|
||||
return allowedOrigins;
|
||||
}
|
||||
|
||||
public void setAllowedOrigins(String allowedOrigins) {
|
||||
this.allowedOrigins = allowedOrigins;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Cache {
|
||||
private long ttlMinutes = 10;
|
||||
private long maximumSize = 200;
|
||||
|
||||
public long getTtlMinutes() {
|
||||
return ttlMinutes;
|
||||
}
|
||||
|
||||
public void setTtlMinutes(long ttlMinutes) {
|
||||
this.ttlMinutes = ttlMinutes;
|
||||
}
|
||||
|
||||
public long getMaximumSize() {
|
||||
return maximumSize;
|
||||
}
|
||||
|
||||
public void setMaximumSize(long maximumSize) {
|
||||
this.maximumSize = maximumSize;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Quality {
|
||||
private String knownMissingZpkKeys = "";
|
||||
|
||||
public String getKnownMissingZpkKeys() {
|
||||
return knownMissingZpkKeys;
|
||||
}
|
||||
|
||||
public void setKnownMissingZpkKeys(String knownMissingZpkKeys) {
|
||||
this.knownMissingZpkKeys = knownMissingZpkKeys;
|
||||
}
|
||||
}
|
||||
|
||||
public Cors getCors() {
|
||||
return cors;
|
||||
}
|
||||
|
||||
public Cache getCache() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
public Quality getQuality() {
|
||||
return quality;
|
||||
}
|
||||
|
||||
public String getCoverBaseUrl() {
|
||||
return coverBaseUrl;
|
||||
}
|
||||
|
||||
public void setCoverBaseUrl(String coverBaseUrl) {
|
||||
this.coverBaseUrl = coverBaseUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wordmarket.admin.config;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Configuration
|
||||
public class CacheConfig {
|
||||
|
||||
@Bean
|
||||
public Cache<String, Object> caffeineAggregateCache(AppProperties properties) {
|
||||
return Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofMinutes(properties.getCache().getTtlMinutes()))
|
||||
.maximumSize(properties.getCache().getMaximumSize())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wordmarket.admin.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
PaginationInnerInterceptor pagination = new PaginationInnerInterceptor(DbType.MYSQL);
|
||||
pagination.setMaxLimit(100L);
|
||||
interceptor.addInnerInterceptor(pagination);
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.wordmarket.admin.config;
|
||||
|
||||
import com.wordmarket.admin.security.JwtAuthFilter;
|
||||
import com.wordmarket.admin.security.RestAuthEntryPoint;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtAuthFilter jwtAuthFilter;
|
||||
private final RestAuthEntryPoint restAuthEntryPoint;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
public SecurityConfig(JwtAuthFilter jwtAuthFilter, RestAuthEntryPoint restAuthEntryPoint,
|
||||
AppProperties appProperties) {
|
||||
this.jwtAuthFilter = jwtAuthFilter;
|
||||
this.restAuthEntryPoint = restAuthEntryPoint;
|
||||
this.appProperties = appProperties;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
return http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(Customizer.withDefaults())
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||
.requestMatchers("/api/auth/login", "/error").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(handling ->
|
||||
handling.authenticationEntryPoint(restAuthEntryPoint))
|
||||
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.logout(AbstractHttpConfigurer::disable)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
List<String> origins = Arrays.stream(appProperties.getCors().getAllowedOrigins().split(","))
|
||||
.map(String::trim)
|
||||
.filter(value -> !value.isEmpty())
|
||||
.toList();
|
||||
configuration.setAllowedOrigins(origins);
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
|
||||
configuration.setMaxAge(3600L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/api/**", configuration);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.dto.AuthDtos.LoginRequest;
|
||||
import com.wordmarket.admin.dto.AuthDtos.LoginResponse;
|
||||
import com.wordmarket.admin.service.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
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.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
|
||||
return ApiResponse.ok(authService.login(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.common.Items;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookDetail;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookEntryItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookListItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.ExamOption;
|
||||
import com.wordmarket.admin.service.BookService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class BookController {
|
||||
|
||||
private final BookService bookService;
|
||||
|
||||
public BookController(BookService bookService) {
|
||||
this.bookService = bookService;
|
||||
}
|
||||
|
||||
@GetMapping("/books")
|
||||
public ApiResponse<PageResult<BookListItem>> list(
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size,
|
||||
@RequestParam(required = false) Long examId,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Boolean hasFile) {
|
||||
return ApiResponse.ok(bookService.list(page, size, examId, keyword, hasFile));
|
||||
}
|
||||
|
||||
@GetMapping("/books/{id}")
|
||||
public ApiResponse<BookDetail> detail(@PathVariable long id) {
|
||||
return ApiResponse.ok(bookService.detail(id));
|
||||
}
|
||||
|
||||
@GetMapping("/books/{id}/entries")
|
||||
public ApiResponse<PageResult<BookEntryItem>> entries(
|
||||
@PathVariable long id,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size,
|
||||
@RequestParam(required = false) String keyword) {
|
||||
return ApiResponse.ok(bookService.entries(id, page, size, keyword));
|
||||
}
|
||||
|
||||
@GetMapping("/exams")
|
||||
public ApiResponse<Items<ExamOption>> exams() {
|
||||
List<ExamOption> options = bookService.exams();
|
||||
return ApiResponse.ok(Items.of(options));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.common.Items;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.ExamStat;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.PosStat;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.Summary;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.TopBook;
|
||||
import com.wordmarket.admin.service.DashboardService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/dashboard")
|
||||
public class DashboardController {
|
||||
|
||||
private final DashboardService dashboardService;
|
||||
|
||||
public DashboardController(DashboardService dashboardService) {
|
||||
this.dashboardService = dashboardService;
|
||||
}
|
||||
|
||||
@GetMapping("/summary")
|
||||
public ApiResponse<Summary> summary(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
return ApiResponse.ok(dashboardService.summary(refresh));
|
||||
}
|
||||
|
||||
@GetMapping("/exam-distribution")
|
||||
public ApiResponse<Items<ExamStat>> examDistribution(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
return ApiResponse.ok(Items.of(dashboardService.examDistribution(refresh)));
|
||||
}
|
||||
|
||||
@GetMapping("/book-size-top")
|
||||
public ApiResponse<Items<TopBook>> bookSizeTop(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
return ApiResponse.ok(Items.of(dashboardService.topBooks(refresh)));
|
||||
}
|
||||
|
||||
@GetMapping("/pos-distribution")
|
||||
public ApiResponse<Items<PosStat>> posDistribution(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
return ApiResponse.ok(Items.of(dashboardService.posDistribution(refresh)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.common.Items;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ConfusableItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryBookItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryDetail;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryListItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleGroupItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SpellingVariantItem;
|
||||
import com.wordmarket.admin.service.EntryService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/entries")
|
||||
public class EntryController {
|
||||
|
||||
private final EntryService entryService;
|
||||
|
||||
public EntryController(EntryService entryService) {
|
||||
this.entryService = entryService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResult<EntryListItem>> list(
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size,
|
||||
@RequestParam(required = false) String keyword) {
|
||||
return ApiResponse.ok(entryService.list(page, size, keyword));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<EntryDetail> detail(@PathVariable long id) {
|
||||
return ApiResponse.ok(entryService.detail(id));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/senses")
|
||||
public ApiResponse<Items<SenseItem>> senses(@PathVariable long id) {
|
||||
List<SenseItem> items = entryService.senses(id);
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/phrases")
|
||||
public ApiResponse<PageResult<PhraseItem>> phrases(
|
||||
@PathVariable long id,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(entryService.phrases(id, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/examples")
|
||||
public ApiResponse<PageResult<ExampleGroupItem>> examples(
|
||||
@PathVariable long id,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(entryService.examples(id, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/confusables")
|
||||
public ApiResponse<Items<ConfusableItem>> confusables(@PathVariable long id) {
|
||||
List<ConfusableItem> items = entryService.confusables(id);
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/variants")
|
||||
public ApiResponse<Items<SpellingVariantItem>> variants(@PathVariable long id) {
|
||||
List<SpellingVariantItem> items = entryService.spellingVariants(id);
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/books")
|
||||
public ApiResponse<PageResult<EntryBookItem>> books(
|
||||
@PathVariable long id,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(entryService.books(id, page, size));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardDetail;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyDetail;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeDetail;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.TreePage;
|
||||
import com.wordmarket.admin.service.MorphologyService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class MorphologyController {
|
||||
|
||||
private final MorphologyService morphologyService;
|
||||
|
||||
public MorphologyController(MorphologyService morphologyService) {
|
||||
this.morphologyService = morphologyService;
|
||||
}
|
||||
|
||||
@GetMapping("/morphemes")
|
||||
public ApiResponse<PageResult<MorphemeItem>> morphemes(
|
||||
@RequestParam(required = false) String type,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(morphologyService.morphemes(type, keyword, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/morphemes/{id}")
|
||||
public ApiResponse<MorphemeDetail> morpheme(@PathVariable long id) {
|
||||
return ApiResponse.ok(morphologyService.morpheme(id));
|
||||
}
|
||||
|
||||
@GetMapping("/cards")
|
||||
public ApiResponse<PageResult<CardItem>> cards(
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(morphologyService.cards(keyword, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/cards/{id}")
|
||||
public ApiResponse<CardDetail> card(@PathVariable long id) {
|
||||
return ApiResponse.ok(morphologyService.card(id));
|
||||
}
|
||||
|
||||
@GetMapping("/families")
|
||||
public ApiResponse<PageResult<FamilyItem>> families(
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(morphologyService.families(keyword, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/families/{id}")
|
||||
public ApiResponse<FamilyDetail> family(@PathVariable long id) {
|
||||
return ApiResponse.ok(morphologyService.family(id));
|
||||
}
|
||||
|
||||
@GetMapping("/families/{id}/tree")
|
||||
public ApiResponse<TreePage> tree(
|
||||
@PathVariable long id,
|
||||
@RequestParam(required = false) String nodeType,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
return ApiResponse.ok(morphologyService.tree(id, nodeType, page, size));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.common.Items;
|
||||
import com.wordmarket.admin.dto.QualityDtos.Coverage;
|
||||
import com.wordmarket.admin.dto.QualityDtos.DeclaredDiff;
|
||||
import com.wordmarket.admin.dto.QualityDtos.MissingReference;
|
||||
import com.wordmarket.admin.dto.QualityDtos.QualitySummary;
|
||||
import com.wordmarket.admin.service.QualityService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/quality")
|
||||
public class QualityController {
|
||||
|
||||
private final QualityService qualityService;
|
||||
|
||||
public QualityController(QualityService qualityService) {
|
||||
this.qualityService = qualityService;
|
||||
}
|
||||
|
||||
@GetMapping("/summary")
|
||||
public ApiResponse<QualitySummary> summary(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
return ApiResponse.ok(qualityService.summary(refresh));
|
||||
}
|
||||
|
||||
@GetMapping("/declared-vs-actual")
|
||||
public ApiResponse<Items<DeclaredDiff>> declaredVsActual(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
List<DeclaredDiff> items = qualityService.declaredVsActual(refresh);
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
|
||||
@GetMapping("/missing-references")
|
||||
public ApiResponse<Items<MissingReference>> missingReferences(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
List<MissingReference> items = qualityService.missingReferences(refresh);
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
|
||||
@GetMapping("/cross-domain-coverage")
|
||||
public ApiResponse<Items<Coverage>> crossDomainCoverage(
|
||||
@RequestParam(defaultValue = "false") boolean refresh) {
|
||||
List<Coverage> items = qualityService.crossDomainCoverage(refresh);
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.wordmarket.admin.controller;
|
||||
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import com.wordmarket.admin.common.Items;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.SizeBucket;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordDetail;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordItem;
|
||||
import com.wordmarket.admin.service.SynonymService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/synonyms")
|
||||
public class SynonymController {
|
||||
|
||||
private final SynonymService synonymService;
|
||||
|
||||
public SynonymController(SynonymService synonymService) {
|
||||
this.synonymService = synonymService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResult<WordItem>> list(
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size,
|
||||
@RequestParam(required = false) String keyword) {
|
||||
return ApiResponse.ok(synonymService.list(page, size, keyword));
|
||||
}
|
||||
|
||||
@GetMapping("/group-size-distribution")
|
||||
public ApiResponse<Items<SizeBucket>> distribution() {
|
||||
List<SizeBucket> items = synonymService.groupSizeDistribution();
|
||||
return ApiResponse.ok(Items.of(items));
|
||||
}
|
||||
|
||||
@GetMapping("/{wordId}")
|
||||
public ApiResponse<WordDetail> detail(@PathVariable long wordId) {
|
||||
return ApiResponse.ok(synonymService.detail(wordId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public final class AuthDtos {
|
||||
|
||||
private AuthDtos() {
|
||||
}
|
||||
|
||||
public record LoginRequest(@NotBlank(message = "用户名不能为空") String username,
|
||||
@NotBlank(message = "密码不能为空") String password) {
|
||||
}
|
||||
|
||||
public record LoginResponse(String token, String expiresAt, String username) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
public final class BookDtos {
|
||||
|
||||
private BookDtos() {
|
||||
}
|
||||
|
||||
public record ExamOption(String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record BookListItem(String id, String code, String name, String examId, String examName,
|
||||
Long declared, long actual, boolean hasFile, String coverPath) {
|
||||
}
|
||||
|
||||
public record BookDetail(String id, String code, String name, String description, String examId,
|
||||
String examName, Long declared, long actual, Integer contentVersion,
|
||||
Integer schemaVersion, String coverPath, String packageUrl, boolean hasFile,
|
||||
Long sortAt, String labels, boolean mismatch) {
|
||||
}
|
||||
|
||||
public record BookDetailRow(String id, String code, String name, String description, String examId,
|
||||
String examName, Long declared, long actual, Integer contentVersion,
|
||||
Integer schemaVersion, String coverPath, String packageUrl,
|
||||
boolean hasFile, Long sortAt, String labels) {
|
||||
}
|
||||
|
||||
public record BookEntryItem(String entryId, String displayWord, String headwordText,
|
||||
Integer seqBook, Integer seqAz, Integer seqFreq, String headword,
|
||||
String indexWord) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class DashboardDtos {
|
||||
|
||||
private DashboardDtos() {
|
||||
}
|
||||
|
||||
public record Kpi(String key, String label, long value, String note, String tone) {
|
||||
}
|
||||
|
||||
public record QualityItem(String key, String label, long value, String unit, String level,
|
||||
String target) {
|
||||
}
|
||||
|
||||
public record CoverageItem(String name, long hit, long total, double pct) {
|
||||
}
|
||||
|
||||
public record Summary(List<Kpi> kpis, List<QualityItem> quality, List<CoverageItem> coverage) {
|
||||
}
|
||||
|
||||
public record ExamStat(String name, String code, long books, long entries) {
|
||||
}
|
||||
|
||||
public record TopBook(String id, String name, String code, String exam, Long declared,
|
||||
long actual, String coverPath) {
|
||||
}
|
||||
|
||||
public record PosStat(String name, long value) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class EntryDtos {
|
||||
|
||||
private EntryDtos() {
|
||||
}
|
||||
|
||||
public record ExamRef(String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record EntryListItem(String id, String headword, String indexWord, String pronunciation,
|
||||
String definition, long senseCount, long bookCount) {
|
||||
}
|
||||
|
||||
public record EntryDetail(String id, String headword, String indexWord, String usPronunciation,
|
||||
String ukPronunciation, String definitionText, String dataVersion,
|
||||
String bookExamId, String bookExamName, Integer occurrenceCount,
|
||||
boolean hasListeningExamples, String sourceZpkKey) {
|
||||
}
|
||||
|
||||
public record SenseRelation(String type, Integer position, String targetMeaningId,
|
||||
String targetEntryId) {
|
||||
}
|
||||
|
||||
public record SenseItem(String senseId, Integer senseNo, String partOfSpeech, String glossZh,
|
||||
List<ExamRef> exams, List<SenseRelation> relations) {
|
||||
}
|
||||
|
||||
public record PhraseOrder(String examId, String examName, Integer groupType, Integer position) {
|
||||
}
|
||||
|
||||
public record PhraseItem(String id, String textEn, String textZh, Integer groupType,
|
||||
String meaningId, List<ExamRef> exams, List<PhraseOrder> orders) {
|
||||
}
|
||||
|
||||
public record ExampleSentenceItem(String id, String textEn, String textZh, String sourceTitle,
|
||||
String audioUrl, boolean listening) {
|
||||
}
|
||||
|
||||
public record ExampleUsageItem(String id, String patternId, String patternText, Integer position,
|
||||
List<ExampleSentenceItem> sentences) {
|
||||
}
|
||||
|
||||
public record ExampleGroupItem(String id, Integer groupKind, String partOfSpeech,
|
||||
String entryKindCode, String headForm, String definitionEn,
|
||||
String definitionZh, List<ExamRef> exams,
|
||||
List<ExampleUsageItem> usages,
|
||||
List<ExampleSentenceItem> directSentences, long sentenceCount) {
|
||||
}
|
||||
|
||||
public record ConfusableItem(String id, String wordText, String glossZh, Integer posCode,
|
||||
String spellingFlag, Integer position) {
|
||||
}
|
||||
|
||||
public record SpellingVariantItem(Integer position, String variant) {
|
||||
}
|
||||
|
||||
public record EntryBookItem(String bookId, String bookName, String bookCode, String displayWord,
|
||||
Integer seqBook) {
|
||||
}
|
||||
|
||||
public record SenseExamRow(String senseId, String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record SenseRelationRow(String senseId, String type, Integer position, String targetMeaningId,
|
||||
String targetEntryId) {
|
||||
}
|
||||
|
||||
public record GroupExamRow(String groupId, String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record UsageRow(String id, String groupId, String patternId, String patternText,
|
||||
Integer position) {
|
||||
}
|
||||
|
||||
public record SentenceRow(String id, String groupId, String usageId, String textEn, String textZh,
|
||||
String sourceTitle, String audioUrl, boolean listening) {
|
||||
}
|
||||
|
||||
public record PhraseExamRow(String phraseId, String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record PhraseOrderRow(String examId, String examName, Integer groupType, Integer position,
|
||||
String phraseId) {
|
||||
}
|
||||
|
||||
public record SenseRow(String senseId, Integer senseNo, String partOfSpeech, String glossZh) {
|
||||
}
|
||||
|
||||
public record PhraseRow(String id, String textEn, String textZh, Integer groupType,
|
||||
String meaningId) {
|
||||
}
|
||||
|
||||
public record ExampleGroupRow(String id, Integer groupKind, String partOfSpeech,
|
||||
String entryKindCode, String headForm, String definitionEn,
|
||||
String definitionZh) {
|
||||
}
|
||||
|
||||
public record ConfusableRow(String id, String wordText, String glossZh, Integer posCode,
|
||||
String spellingFlag, Integer position) {
|
||||
}
|
||||
|
||||
public record VariantRow(Integer position, String variant) {
|
||||
}
|
||||
|
||||
public record EntryBookRow(String bookId, String bookName, String bookCode, String displayWord,
|
||||
Integer seqBook) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class MorphologyDtos {
|
||||
|
||||
private MorphologyDtos() {
|
||||
}
|
||||
|
||||
public record ExamRef(String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record MorphemeItem(String id, String type, String form, String displayText, String meaningEn,
|
||||
String meaningZh, String note) {
|
||||
}
|
||||
|
||||
public record CardBrief(String id, String word, String memoryNote, String exampleText) {
|
||||
}
|
||||
|
||||
public record CardRow(String id, String word, String highlightedWord, String memoryNote,
|
||||
String exampleText, boolean hidden, String prefixMorphemeId,
|
||||
String rootMorphemeId, String suffixMorphemeId, String defaultFamilyRef) {
|
||||
}
|
||||
|
||||
public record CardItemRow(String id, String word, String memoryNote, String highlightedWord) {
|
||||
}
|
||||
|
||||
public record FamilyRow(String id, String word, String topFamilyId, String topWord,
|
||||
String interpretation, Integer groupLevel1, Integer groupLevel2,
|
||||
Integer groupLevel3) {
|
||||
}
|
||||
|
||||
public record FamilyLinkRow(String id, Integer groupNo, String familyRef, boolean hidden) {
|
||||
}
|
||||
|
||||
public record MorphemeDetail(String id, String type, String form, String displayText,
|
||||
String meaningEn, String meaningZh, String note,
|
||||
List<CardBrief> cards, long cardCount) {
|
||||
}
|
||||
|
||||
public record CardItem(String id, String word, String memoryNote, String highlightedWord,
|
||||
List<ExamRef> exams) {
|
||||
}
|
||||
|
||||
public record CardFamilyLink(String linkId, Integer groupNo, String familyRef, boolean hidden) {
|
||||
}
|
||||
|
||||
public record CardDetail(String id, String word, String highlightedWord, String memoryNote,
|
||||
String exampleText, boolean hidden, String prefixMorphemeId, String prefixForm,
|
||||
String rootMorphemeId, String rootForm, String suffixMorphemeId,
|
||||
String suffixForm, String defaultFamilyRef, List<ExamRef> exams,
|
||||
List<CardFamilyLink> familyLinks) {
|
||||
}
|
||||
|
||||
public record FamilyItem(String id, String word, String topFamilyId, String topWord,
|
||||
String interpretation, Integer groupLevel1, Integer groupLevel2,
|
||||
Integer groupLevel3, List<ExamRef> exams) {
|
||||
}
|
||||
|
||||
public record FamilyVariantItem(String id, String variantWord, String interpretation,
|
||||
long memberCount) {
|
||||
}
|
||||
|
||||
public record FamilyMemberItem(String familyEntryId, String word, Integer position) {
|
||||
}
|
||||
|
||||
public record MiniGroupItem(String id, Integer size, List<FamilyMemberItem> members) {
|
||||
}
|
||||
|
||||
public record FamilyDetail(String id, String word, String topFamilyId, String topWord,
|
||||
String interpretation, Integer groupLevel1, Integer groupLevel2,
|
||||
Integer groupLevel3, List<ExamRef> exams,
|
||||
List<FamilyVariantItem> variants, List<MiniGroupItem> miniGroups) {
|
||||
}
|
||||
|
||||
public record TreeNode(String nodeType, String id, String label, String subtitle, long memberCount,
|
||||
boolean leaf) {
|
||||
}
|
||||
|
||||
public record TreePage(List<TreeNode> nodes, long total, int page, int size) {
|
||||
}
|
||||
|
||||
public record LinkExamRow(String cardId, String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record FamilyExamRow(String familyEntryId, String id, String code, String name) {
|
||||
}
|
||||
|
||||
public record MorphemeRefRow(String id, String form, String type, String meaningZh) {
|
||||
}
|
||||
|
||||
public record FamilyWordRow(String id, String word, String interpretation) {
|
||||
}
|
||||
|
||||
public record VariantRow(String id, String variantWord, String interpretation, long memberCount) {
|
||||
}
|
||||
|
||||
public record MiniGroupRow(String id, Integer size) {
|
||||
}
|
||||
|
||||
public record MemberRow(String familyEntryId, String word, Integer position) {
|
||||
}
|
||||
|
||||
public record CountRow(long count) {
|
||||
}
|
||||
|
||||
public record TreeCounts(long variantCount, long groupCount) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class QualityDtos {
|
||||
|
||||
private QualityDtos() {
|
||||
}
|
||||
|
||||
public record SummaryItem(String key, String label, long value, String unit, String level,
|
||||
String description) {
|
||||
}
|
||||
|
||||
public record QualitySummary(List<SummaryItem> items) {
|
||||
}
|
||||
|
||||
public record DeclaredDiff(String bookId, String bookName, String bookCode, String examName,
|
||||
long declared, long actual, long diff) {
|
||||
}
|
||||
|
||||
public record MissingReference(String type, String identifier, String source, String detail,
|
||||
String bookId) {
|
||||
}
|
||||
|
||||
public record Coverage(String key, String name, long hit, long total, double pct) {
|
||||
}
|
||||
|
||||
public record MissingBook(String bookId, String bookCode, String bookName) {
|
||||
}
|
||||
|
||||
public record MissingZpk(String sourceKey, long rowCount, String bookIds) {
|
||||
}
|
||||
|
||||
public record CountPair(long total, long hit) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.wordmarket.admin.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class SynonymDtos {
|
||||
|
||||
private SynonymDtos() {
|
||||
}
|
||||
|
||||
public record WordItem(String wordId, String word, long senseCount, boolean hasRelation) {
|
||||
}
|
||||
|
||||
public record WordRow(String wordId, String word) {
|
||||
}
|
||||
|
||||
public record SenseRow(String senseId, String partOfSpeech, String glossZh) {
|
||||
}
|
||||
|
||||
public record MemberItem(String wordId, String word, Integer position) {
|
||||
}
|
||||
|
||||
public record GroupItem(String examId, String examName, String canonicalWordId, String canonicalWord,
|
||||
Integer memberCount, List<MemberItem> members, boolean truncated) {
|
||||
}
|
||||
|
||||
public record AntonymItem(String examId, String examName, List<MemberItem> words) {
|
||||
}
|
||||
|
||||
public record SenseItem(String senseId, String partOfSpeech, String glossZh, List<GroupItem> groups,
|
||||
List<AntonymItem> antonyms) {
|
||||
}
|
||||
|
||||
public record WordDetail(String wordId, String word, List<SenseItem> senses) {
|
||||
}
|
||||
|
||||
public record SizeBucket(String label, long count, double pct) {
|
||||
}
|
||||
|
||||
public record GroupRow(String senseId, String examId, String examName, String canonicalWordId,
|
||||
String canonicalWord, Integer memberCount) {
|
||||
}
|
||||
|
||||
public record MemberRow(String senseId, String examId, String wordId, String word, Integer position) {
|
||||
}
|
||||
|
||||
public record AntonymRow(String senseId, String examId, String examName, String wordId, String word,
|
||||
Integer position) {
|
||||
}
|
||||
|
||||
public record ExamRow(String examId, String examName) {
|
||||
}
|
||||
|
||||
public record BucketRow(String label, long count) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.wordmarket.admin.mapper;
|
||||
|
||||
import com.wordmarket.admin.dto.BookDtos.BookDetailRow;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookEntryItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookListItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.ExamOption;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface BookMapper {
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*)
|
||||
FROM book b
|
||||
<where>
|
||||
<if test="examId != null">AND b.exam_id = #{examId}</if>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND (LOWER(b.book_name) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
OR LOWER(b.book_code) LIKE CONCAT('%', LOWER(#{keyword}), '%'))
|
||||
</if>
|
||||
<if test="hasFile != null">AND b.has_wordbook_file = #{hasFile}</if>
|
||||
</where>
|
||||
</script>
|
||||
""")
|
||||
long countBooks(@Param("examId") Long examId, @Param("keyword") String keyword,
|
||||
@Param("hasFile") Boolean hasFile);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT b.book_id AS id,
|
||||
b.book_code AS code,
|
||||
b.book_name AS name,
|
||||
b.exam_id AS exam_id,
|
||||
e.exam_name_zh AS exam_name,
|
||||
b.declared_entry_count AS declared,
|
||||
(SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id) AS actual,
|
||||
b.has_wordbook_file AS has_file,
|
||||
b.cover_url AS cover_path
|
||||
FROM book b
|
||||
LEFT JOIN exam e ON e.exam_id = b.exam_id
|
||||
<where>
|
||||
<if test="examId != null">AND b.exam_id = #{examId}</if>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND (LOWER(b.book_name) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
OR LOWER(b.book_code) LIKE CONCAT('%', LOWER(#{keyword}), '%'))
|
||||
</if>
|
||||
<if test="hasFile != null">AND b.has_wordbook_file = #{hasFile}</if>
|
||||
</where>
|
||||
ORDER BY b.book_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<BookListItem> listBooks(@Param("examId") Long examId, @Param("keyword") String keyword,
|
||||
@Param("hasFile") Boolean hasFile, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
SELECT b.book_id AS id,
|
||||
b.book_code AS code,
|
||||
b.book_name AS name,
|
||||
b.description,
|
||||
b.exam_id AS exam_id,
|
||||
e.exam_name_zh AS exam_name,
|
||||
b.declared_entry_count AS declared,
|
||||
(SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id) AS actual,
|
||||
b.content_version,
|
||||
b.schema_version,
|
||||
b.cover_url AS cover_path,
|
||||
b.package_url,
|
||||
b.has_wordbook_file AS has_file,
|
||||
b.sort_at,
|
||||
b.labels
|
||||
FROM book b
|
||||
LEFT JOIN exam e ON e.exam_id = b.exam_id
|
||||
WHERE b.book_id = #{id}
|
||||
""")
|
||||
BookDetailRow findBook(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*)
|
||||
FROM book_entry be
|
||||
WHERE be.book_id = #{bookId}
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND (LOWER(be.display_word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
OR LOWER(be.headword_text) LIKE CONCAT('%', LOWER(#{keyword}), '%'))
|
||||
</if>
|
||||
</script>
|
||||
""")
|
||||
long countBookEntries(@Param("bookId") long bookId, @Param("keyword") String keyword);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT be.entry_id AS entry_id,
|
||||
be.display_word AS display_word,
|
||||
be.headword_text AS headword_text,
|
||||
be.seq_book,
|
||||
be.seq_az,
|
||||
be.seq_freq,
|
||||
e.headword,
|
||||
e.index_word
|
||||
FROM book_entry be
|
||||
LEFT JOIN word_entry e ON e.entry_id = be.entry_id
|
||||
WHERE be.book_id = #{bookId}
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND (LOWER(be.display_word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
OR LOWER(be.headword_text) LIKE CONCAT('%', LOWER(#{keyword}), '%'))
|
||||
</if>
|
||||
ORDER BY be.seq_book, be.book_entry_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<BookEntryItem> listBookEntries(@Param("bookId") long bookId,
|
||||
@Param("keyword") String keyword,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
SELECT exam_id AS id, exam_code AS code, exam_name_zh AS name
|
||||
FROM exam
|
||||
WHERE is_pseudo = 0
|
||||
ORDER BY exam_id
|
||||
""")
|
||||
List<ExamOption> listExams();
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.wordmarket.admin.mapper;
|
||||
|
||||
import com.wordmarket.admin.dto.DashboardDtos.ExamStat;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.PosStat;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.TopBook;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface DashboardMapper {
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book")
|
||||
long countBooks();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book WHERE has_wordbook_file = 0")
|
||||
long countBooksWithoutFile();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM word_entry")
|
||||
long countEntries();
|
||||
|
||||
@Select("SELECT COUNT(DISTINCT index_word) FROM word_entry")
|
||||
long countIndexWords();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book_entry")
|
||||
long countBookEntries();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM example_sentence")
|
||||
long countExampleSentences();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM example_usage")
|
||||
long countExampleUsages();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM word_family")
|
||||
long countFamilies();
|
||||
|
||||
@Select("SELECT COUNT(DISTINCT top_family_id) FROM word_family")
|
||||
long countTopFamilies();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM synonym_word")
|
||||
long countSynonymWords();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM synonym_sense")
|
||||
long countSynonymSenses();
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COALESCE(e.exam_name_zh, '未归类') AS name,
|
||||
e.exam_code AS code,
|
||||
COUNT(*) AS books,
|
||||
COALESCE(SUM(x.c), 0) AS entries
|
||||
FROM book b
|
||||
LEFT JOIN exam e ON e.exam_id = b.exam_id
|
||||
LEFT JOIN (SELECT book_id, COUNT(*) AS c FROM book_entry GROUP BY book_id) x
|
||||
ON x.book_id = b.book_id
|
||||
GROUP BY b.exam_id, e.exam_name_zh, e.exam_code
|
||||
ORDER BY entries DESC, books DESC
|
||||
</script>
|
||||
""")
|
||||
List<ExamStat> examDistribution();
|
||||
|
||||
@Select("""
|
||||
SELECT b.book_id AS id,
|
||||
b.book_name AS name,
|
||||
b.book_code AS code,
|
||||
e.exam_name_zh AS exam,
|
||||
b.declared_entry_count AS declared,
|
||||
(SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id) AS actual,
|
||||
b.cover_url AS cover_path
|
||||
FROM book b
|
||||
LEFT JOIN exam e ON e.exam_id = b.exam_id
|
||||
ORDER BY actual DESC, b.book_id
|
||||
LIMIT 10
|
||||
""")
|
||||
List<TopBook> topBooks();
|
||||
|
||||
@Select("""
|
||||
SELECT COALESCE(NULLIF(part_of_speech, ''), '未标注') AS name,
|
||||
COUNT(*) AS value
|
||||
FROM word_sense
|
||||
GROUP BY part_of_speech
|
||||
ORDER BY value DESC, name
|
||||
LIMIT 10
|
||||
""")
|
||||
List<PosStat> posDistribution();
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.wordmarket.admin.mapper;
|
||||
|
||||
import com.wordmarket.admin.dto.EntryDtos.ConfusableRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryBookRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryDetail;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryListItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleGroupRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.GroupExamRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseExamRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseOrderRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseExamRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseRelationRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SentenceRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.UsageRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.VariantRow;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface EntryMapper {
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*)
|
||||
FROM word_entry e
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND (LOWER(e.headword) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
OR LOWER(e.index_word) LIKE CONCAT('%', LOWER(#{keyword}), '%'))
|
||||
</if>
|
||||
</where>
|
||||
</script>
|
||||
""")
|
||||
long countEntries(@Param("keyword") String keyword);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT e.entry_id AS id,
|
||||
e.headword,
|
||||
e.index_word,
|
||||
COALESCE(NULLIF(e.us_pronunciation, ''), e.uk_pronunciation) AS pronunciation,
|
||||
e.definition_text AS definition,
|
||||
(SELECT COUNT(*) FROM word_sense s WHERE s.entry_id = e.entry_id) AS sense_count,
|
||||
(SELECT COUNT(*) FROM book_entry be WHERE be.entry_id = e.entry_id) AS book_count
|
||||
FROM word_entry e
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND (LOWER(e.headword) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
OR LOWER(e.index_word) LIKE CONCAT('%', LOWER(#{keyword}), '%'))
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY e.entry_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<EntryListItem> listEntries(@Param("keyword") String keyword, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
SELECT e.entry_id AS id,
|
||||
e.headword,
|
||||
e.index_word,
|
||||
e.us_pronunciation,
|
||||
e.uk_pronunciation,
|
||||
e.definition_text,
|
||||
e.data_version,
|
||||
e.book_exam_id AS book_exam_id,
|
||||
ex.exam_name_zh AS book_exam_name,
|
||||
e.occurrence_count,
|
||||
e.has_listening_examples,
|
||||
e.source_zpk_key
|
||||
FROM word_entry e
|
||||
LEFT JOIN exam ex ON ex.exam_id = e.book_exam_id
|
||||
WHERE e.entry_id = #{id}
|
||||
""")
|
||||
EntryDetail findEntry(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
SELECT sense_id, sense_no, part_of_speech, gloss_zh
|
||||
FROM word_sense
|
||||
WHERE entry_id = #{entryId}
|
||||
ORDER BY sense_no, sense_id
|
||||
""")
|
||||
List<SenseRow> listSenses(@Param("entryId") long entryId);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT se.sense_id, ex.exam_id AS id, ex.exam_code AS code, ex.exam_name_zh AS name
|
||||
FROM sense_exam se
|
||||
JOIN exam ex ON ex.exam_id = se.exam_id
|
||||
WHERE se.sense_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY se.sense_id, ex.exam_id
|
||||
</script>
|
||||
""")
|
||||
List<SenseExamRow> listSenseExams(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT sr.sense_id,
|
||||
sr.relation_type AS type,
|
||||
sr.position,
|
||||
sr.target_meaning_id,
|
||||
so.entry_id AS target_entry_id
|
||||
FROM sense_relation sr
|
||||
JOIN sense_object so ON so.meaning_id = sr.target_meaning_id
|
||||
WHERE sr.sense_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY sr.sense_id, sr.relation_type, sr.position
|
||||
</script>
|
||||
""")
|
||||
List<SenseRelationRow> listSenseRelations(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("SELECT COUNT(*) FROM phrase WHERE entry_id = #{entryId}")
|
||||
long countPhrases(@Param("entryId") long entryId);
|
||||
|
||||
@Select("""
|
||||
SELECT phrase_id AS id, text_en, text_zh, group_type, meaning_id
|
||||
FROM phrase
|
||||
WHERE entry_id = #{entryId}
|
||||
ORDER BY phrase_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
""")
|
||||
List<PhraseRow> listPhrases(@Param("entryId") long entryId, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT pe.phrase_id, ex.exam_id AS id, ex.exam_code AS code, ex.exam_name_zh AS name
|
||||
FROM phrase_exam pe
|
||||
JOIN exam ex ON ex.exam_id = pe.exam_id
|
||||
WHERE pe.phrase_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY pe.phrase_id, ex.exam_id
|
||||
</script>
|
||||
""")
|
||||
List<PhraseExamRow> listPhraseExams(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
SELECT p.exam_id, ex.exam_name_zh AS exam_name, p.group_type, p.position, p.phrase_id
|
||||
FROM phrase_exam_order p
|
||||
JOIN exam ex ON ex.exam_id = p.exam_id
|
||||
WHERE p.entry_id = #{entryId}
|
||||
ORDER BY p.exam_id, p.group_type, p.position
|
||||
""")
|
||||
List<PhraseOrderRow> listPhraseOrders(@Param("entryId") long entryId);
|
||||
|
||||
@Select("SELECT COUNT(*) FROM example_group WHERE entry_id = #{entryId}")
|
||||
long countExampleGroups(@Param("entryId") long entryId);
|
||||
|
||||
@Select("""
|
||||
SELECT example_group_id AS id, group_kind, part_of_speech, entry_kind_code, head_form,
|
||||
definition_en, definition_zh
|
||||
FROM example_group
|
||||
WHERE entry_id = #{entryId}
|
||||
ORDER BY group_kind, example_group_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
""")
|
||||
List<ExampleGroupRow> listExampleGroups(@Param("entryId") long entryId,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT ge.example_group_id AS group_id, ex.exam_id AS id, ex.exam_code AS code,
|
||||
ex.exam_name_zh AS name
|
||||
FROM example_group_exam ge
|
||||
JOIN exam ex ON ex.exam_id = ge.exam_id
|
||||
WHERE ge.example_group_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY ge.example_group_id, ex.exam_id
|
||||
</script>
|
||||
""")
|
||||
List<GroupExamRow> listExampleGroupExams(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT usage_id AS id, example_group_id AS group_id, pattern_id, pattern_text, position
|
||||
FROM example_usage
|
||||
WHERE example_group_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY example_group_id, position, usage_id
|
||||
</script>
|
||||
""")
|
||||
List<UsageRow> listExampleUsages(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT sentence_id AS id, example_group_id AS group_id, usage_id, text_en, text_zh,
|
||||
source_title, audio_url, is_listening_corpus AS listening
|
||||
FROM example_sentence
|
||||
WHERE example_group_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY example_group_id, position, sentence_id
|
||||
</script>
|
||||
""")
|
||||
List<SentenceRow> listExampleSentences(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
SELECT confusable_id AS id, word_text, gloss_zh, pos_code, spelling_flag, position
|
||||
FROM confusable_word
|
||||
WHERE entry_id = #{entryId}
|
||||
ORDER BY position, confusable_id
|
||||
""")
|
||||
List<ConfusableRow> listConfusables(@Param("entryId") long entryId);
|
||||
|
||||
@Select("""
|
||||
SELECT position, variant
|
||||
FROM word_spelling_variant
|
||||
WHERE entry_id = #{entryId}
|
||||
ORDER BY position
|
||||
""")
|
||||
List<VariantRow> listSpellingVariants(@Param("entryId") long entryId);
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book_entry WHERE entry_id = #{entryId}")
|
||||
long countEntryBooks(@Param("entryId") long entryId);
|
||||
|
||||
@Select("""
|
||||
SELECT be.book_id AS book_id, b.book_name, b.book_code, be.display_word, be.seq_book
|
||||
FROM book_entry be
|
||||
JOIN book b ON b.book_id = be.book_id
|
||||
WHERE be.entry_id = #{entryId}
|
||||
ORDER BY b.book_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
""")
|
||||
List<EntryBookRow> listEntryBooks(@Param("entryId") long entryId, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package com.wordmarket.admin.mapper;
|
||||
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardBrief;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyExamRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyLinkRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyWordRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.LinkExamRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MemberRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MiniGroupRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeRefRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.TreeNode;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.TreeCounts;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.VariantRow;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface MorphologyMapper {
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*) FROM morpheme
|
||||
<where>
|
||||
<if test="type != null and type != ''">AND morpheme_type = #{type}</if>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(form) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
</script>
|
||||
""")
|
||||
long countMorphemes(@Param("type") String type, @Param("keyword") String keyword);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT morpheme_id AS id, morpheme_type AS type, form, display_text, meaning_en, meaning_zh,
|
||||
note
|
||||
FROM morpheme
|
||||
<where>
|
||||
<if test="type != null and type != ''">AND morpheme_type = #{type}</if>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(form) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY morpheme_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<MorphemeItem> listMorphemes(@Param("type") String type, @Param("keyword") String keyword,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
SELECT morpheme_id AS id, morpheme_type AS type, form, display_text, meaning_en, meaning_zh,
|
||||
note
|
||||
FROM morpheme
|
||||
WHERE morpheme_id = #{id}
|
||||
""")
|
||||
MorphemeItem findMorpheme(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(*) FROM card
|
||||
WHERE prefix_morpheme_id = #{id} OR root_morpheme_id = #{id} OR suffix_morpheme_id = #{id}
|
||||
""")
|
||||
long countCardsByMorpheme(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
SELECT card_id AS id, word, memory_note, example_text
|
||||
FROM card
|
||||
WHERE prefix_morpheme_id = #{id} OR root_morpheme_id = #{id} OR suffix_morpheme_id = #{id}
|
||||
ORDER BY card_id
|
||||
LIMIT 100
|
||||
""")
|
||||
List<CardBrief> listCardsByMorpheme(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*) FROM card
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
</script>
|
||||
""")
|
||||
long countCards(@Param("keyword") String keyword);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT card_id AS id, word, memory_note, highlighted_word
|
||||
FROM card
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY card_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<com.wordmarket.admin.dto.MorphologyDtos.CardItemRow> listCards(@Param("keyword") String keyword,
|
||||
@Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
SELECT card_id AS id, word, highlighted_word, memory_note, example_text, is_hidden AS hidden,
|
||||
prefix_morpheme_id, root_morpheme_id, suffix_morpheme_id, default_family_ref
|
||||
FROM card
|
||||
WHERE card_id = #{id}
|
||||
""")
|
||||
CardRow findCard(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT ce.card_id, ex.exam_id AS id, ex.exam_code AS code, ex.exam_name_zh AS name
|
||||
FROM card_exam ce
|
||||
JOIN exam ex ON ex.exam_id = ce.exam_id
|
||||
WHERE ce.card_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY ce.card_id, ex.exam_id
|
||||
</script>
|
||||
""")
|
||||
List<LinkExamRow> listCardExams(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT morpheme_id AS id, form, morpheme_type AS type, meaning_zh
|
||||
FROM morpheme
|
||||
WHERE morpheme_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
</script>
|
||||
""")
|
||||
List<MorphemeRefRow> listMorphemeRefs(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
SELECT link_id AS id, group_no, family_ref, is_hidden AS hidden
|
||||
FROM card_family_link
|
||||
WHERE card_id = #{cardId}
|
||||
ORDER BY group_no, link_id
|
||||
""")
|
||||
List<FamilyLinkRow> listCardFamilyLinks(@Param("cardId") long cardId);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*) FROM word_family f
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(f.word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
</script>
|
||||
""")
|
||||
long countFamilies(@Param("keyword") String keyword);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT f.family_entry_id AS id, f.word, f.top_family_id AS top_family_id,
|
||||
t.word AS top_word, f.interpretation,
|
||||
f.group_level_1, f.group_level_2, f.group_level_3
|
||||
FROM word_family f
|
||||
LEFT JOIN word_family t ON t.family_entry_id = f.top_family_id
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(f.word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY f.family_entry_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<FamilyRow> listFamilies(@Param("keyword") String keyword, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
SELECT f.family_entry_id AS id, f.word, f.top_family_id AS top_family_id,
|
||||
t.word AS top_word, f.interpretation,
|
||||
f.group_level_1, f.group_level_2, f.group_level_3
|
||||
FROM word_family f
|
||||
LEFT JOIN word_family t ON t.family_entry_id = f.top_family_id
|
||||
WHERE f.family_entry_id = #{id}
|
||||
""")
|
||||
FamilyRow findFamily(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT fe.family_entry_id, ex.exam_id AS id, ex.exam_code AS code, ex.exam_name_zh AS name
|
||||
FROM word_family_exam fe
|
||||
JOIN exam ex ON ex.exam_id = fe.exam_id
|
||||
WHERE fe.family_entry_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY fe.family_entry_id, ex.exam_id
|
||||
</script>
|
||||
""")
|
||||
List<FamilyExamRow> listFamilyExams(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
SELECT v.variant_id AS id, v.variant_word, v.interpretation,
|
||||
(SELECT COUNT(*) FROM word_family_variant_member m
|
||||
WHERE m.variant_id = v.variant_id) AS member_count
|
||||
FROM word_family_variant v
|
||||
WHERE v.top_family_id = #{topId}
|
||||
ORDER BY v.variant_id
|
||||
""")
|
||||
List<VariantRow> listVariants(@Param("topId") long topId);
|
||||
|
||||
@Select("""
|
||||
SELECT mg.mini_group_id AS id, mg.size
|
||||
FROM word_family_mini_group mg
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM word_family_mini_group_member m
|
||||
JOIN word_family f ON f.family_entry_id = m.family_entry_id
|
||||
WHERE m.mini_group_id = mg.mini_group_id AND f.top_family_id = #{topId}
|
||||
)
|
||||
ORDER BY mg.mini_group_id
|
||||
LIMIT 200
|
||||
""")
|
||||
List<MiniGroupRow> listMiniGroups(@Param("topId") long topId);
|
||||
|
||||
@Select("""
|
||||
SELECT m.family_entry_id, f.word, m.position
|
||||
FROM word_family_mini_group_member m
|
||||
JOIN word_family f ON f.family_entry_id = m.family_entry_id
|
||||
WHERE m.mini_group_id = #{miniGroupId}
|
||||
ORDER BY m.position
|
||||
LIMIT 50
|
||||
""")
|
||||
List<MemberRow> listMiniGroupMembers(@Param("miniGroupId") long miniGroupId);
|
||||
|
||||
@Select("""
|
||||
SELECT (SELECT COUNT(*) FROM word_family_variant v WHERE v.top_family_id = #{topId})
|
||||
AS variant_count,
|
||||
(SELECT COUNT(*) FROM word_family_mini_group mg WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM word_family_mini_group_member m
|
||||
JOIN word_family f ON f.family_entry_id = m.family_entry_id
|
||||
WHERE m.mini_group_id = mg.mini_group_id AND f.top_family_id = #{topId}))
|
||||
AS group_count
|
||||
""")
|
||||
TreeCounts countTopChildren(@Param("topId") long topId);
|
||||
|
||||
@Select("""
|
||||
SELECT * FROM (
|
||||
SELECT 'variant' AS node_type,
|
||||
CAST(v.variant_id AS CHAR) AS id,
|
||||
v.variant_word AS label,
|
||||
v.interpretation AS subtitle,
|
||||
(SELECT COUNT(*) FROM word_family_variant_member m
|
||||
WHERE m.variant_id = v.variant_id) AS member_count,
|
||||
0 AS leaf
|
||||
FROM word_family_variant v
|
||||
WHERE v.top_family_id = #{topId}
|
||||
UNION ALL
|
||||
SELECT 'miniGroup' AS node_type,
|
||||
CAST(mg.mini_group_id AS CHAR) AS id,
|
||||
CONCAT('小组 #', mg.mini_group_id) AS label,
|
||||
CONCAT('成员 ', mg.size) AS subtitle,
|
||||
mg.size AS member_count,
|
||||
0 AS leaf
|
||||
FROM word_family_mini_group mg
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM word_family_mini_group_member m
|
||||
JOIN word_family f ON f.family_entry_id = m.family_entry_id
|
||||
WHERE m.mini_group_id = mg.mini_group_id AND f.top_family_id = #{topId}
|
||||
)
|
||||
) t
|
||||
ORDER BY node_type, id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
""")
|
||||
List<TreeNode> listTopChildren(@Param("topId") long topId, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("SELECT COUNT(*) FROM word_family_variant_member WHERE variant_id = #{variantId}")
|
||||
long countVariantMembers(@Param("variantId") long variantId);
|
||||
|
||||
@Select("""
|
||||
SELECT 'member' AS node_type,
|
||||
CONCAT('word:', vm.member_word, ':', vm.exam_id, ':', vm.position) AS id,
|
||||
vm.member_word AS label,
|
||||
CONCAT(COALESCE(ex.exam_name_zh, CONCAT('考试 ', vm.exam_id)), ' · 第 ',
|
||||
vm.position, ' 位') AS subtitle,
|
||||
0 AS member_count,
|
||||
1 AS leaf
|
||||
FROM word_family_variant_member vm
|
||||
LEFT JOIN exam ex ON ex.exam_id = vm.exam_id
|
||||
WHERE vm.variant_id = #{variantId}
|
||||
ORDER BY vm.exam_id, vm.position
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
""")
|
||||
List<TreeNode> listVariantMemberNodes(@Param("variantId") long variantId,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
@Select("SELECT COUNT(*) FROM word_family_mini_group_member WHERE mini_group_id = #{miniGroupId}")
|
||||
long countMiniGroupMembers(@Param("miniGroupId") long miniGroupId);
|
||||
|
||||
@Select("""
|
||||
SELECT 'member' AS node_type,
|
||||
CONCAT('family:', m.family_entry_id) AS id,
|
||||
f.word AS label,
|
||||
CONCAT('词族内位置 ', m.position) AS subtitle,
|
||||
0 AS member_count,
|
||||
1 AS leaf
|
||||
FROM word_family_mini_group_member m
|
||||
JOIN word_family f ON f.family_entry_id = m.family_entry_id
|
||||
WHERE m.mini_group_id = #{miniGroupId}
|
||||
ORDER BY m.position
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
""")
|
||||
List<TreeNode> listMiniGroupMemberNodes(@Param("miniGroupId") long miniGroupId,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT family_entry_id AS id, word, interpretation
|
||||
FROM word_family
|
||||
WHERE family_entry_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
</script>
|
||||
""")
|
||||
List<FamilyWordRow> listFamilyWords(@Param("ids") List<Long> ids);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.wordmarket.admin.mapper;
|
||||
|
||||
import com.wordmarket.admin.dto.QualityDtos.DeclaredDiff;
|
||||
import com.wordmarket.admin.dto.QualityDtos.MissingBook;
|
||||
import com.wordmarket.admin.dto.QualityDtos.MissingZpk;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface QualityMapper {
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(*)
|
||||
FROM book b
|
||||
WHERE b.declared_entry_count IS NOT NULL
|
||||
AND b.declared_entry_count <> (SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id)
|
||||
""")
|
||||
long countDeclaredMismatch();
|
||||
|
||||
@Select("""
|
||||
SELECT b.book_id AS book_id,
|
||||
b.book_name,
|
||||
b.book_code,
|
||||
e.exam_name_zh AS exam_name,
|
||||
b.declared_entry_count AS declared,
|
||||
(SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id) AS actual,
|
||||
(SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id)
|
||||
- b.declared_entry_count AS diff
|
||||
FROM book b
|
||||
LEFT JOIN exam e ON e.exam_id = b.exam_id
|
||||
WHERE b.declared_entry_count IS NOT NULL
|
||||
AND b.declared_entry_count <> (SELECT COUNT(*) FROM book_entry be WHERE be.book_id = b.book_id)
|
||||
ORDER BY ABS(diff) DESC, b.book_id
|
||||
""")
|
||||
List<DeclaredDiff> listDeclaredMismatch();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book WHERE has_wordbook_file = 0")
|
||||
long countMissingFiles();
|
||||
|
||||
@Select("SELECT book_id AS book_id, book_code, book_name FROM book WHERE has_wordbook_file = 0")
|
||||
List<MissingBook> listMissingFileBooks();
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT be.source_zpk_key AS source_key,
|
||||
COUNT(*) AS row_count,
|
||||
GROUP_CONCAT(DISTINCT be.book_id ORDER BY be.book_id) AS book_ids
|
||||
FROM book_entry be
|
||||
WHERE be.source_zpk_key IN
|
||||
<foreach collection="keys" item="key" open="(" separator="," close=")">#{key}</foreach>
|
||||
GROUP BY be.source_zpk_key
|
||||
ORDER BY be.source_zpk_key
|
||||
</script>
|
||||
""")
|
||||
List<MissingZpk> listKnownMissingZpk(@Param("keys") List<String> keys);
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(*)
|
||||
FROM word_entry e
|
||||
WHERE NOT EXISTS (SELECT 1 FROM word_sense s WHERE s.entry_id = e.entry_id)
|
||||
""")
|
||||
long countEntriesWithoutSense();
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(*)
|
||||
FROM synonym_word w
|
||||
WHERE NOT EXISTS (SELECT 1 FROM synonym_sense s WHERE s.word_id = w.word_id)
|
||||
""")
|
||||
long countSynonymWordsWithoutSense();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book WHERE exam_id IS NULL")
|
||||
long countBooksWithoutExam();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM book WHERE cover_url IS NULL OR cover_url = ''")
|
||||
long countBooksWithoutCover();
|
||||
|
||||
@Select("SELECT book_id AS book_id, book_code, book_name FROM book WHERE cover_url IS NULL OR cover_url = ''")
|
||||
List<MissingBook> listBooksWithoutCover();
|
||||
|
||||
@Select("SELECT COUNT(DISTINCT LOWER(TRIM(word))) FROM card")
|
||||
long cardTotal();
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(DISTINCT LOWER(TRIM(c.word)))
|
||||
FROM card c
|
||||
WHERE EXISTS (SELECT 1 FROM word_entry e WHERE e.index_word = LOWER(TRIM(c.word)))
|
||||
""")
|
||||
long cardHit();
|
||||
|
||||
@Select("SELECT COUNT(DISTINCT LOWER(TRIM(word))) FROM word_family")
|
||||
long familyTotal();
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(DISTINCT LOWER(TRIM(f.word)))
|
||||
FROM word_family f
|
||||
WHERE EXISTS (SELECT 1 FROM word_entry e WHERE e.index_word = LOWER(TRIM(f.word)))
|
||||
""")
|
||||
long familyHit();
|
||||
|
||||
@Select("SELECT COUNT(DISTINCT LOWER(TRIM(word))) FROM synonym_word")
|
||||
long synonymTotal();
|
||||
|
||||
@Select("""
|
||||
SELECT COUNT(DISTINCT LOWER(TRIM(s.word)))
|
||||
FROM synonym_word s
|
||||
WHERE EXISTS (SELECT 1 FROM word_entry e WHERE e.index_word = LOWER(TRIM(s.word)))
|
||||
""")
|
||||
long synonymHit();
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.wordmarket.admin.mapper;
|
||||
|
||||
import com.wordmarket.admin.dto.SynonymDtos.AntonymRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.BucketRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.GroupRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.MemberRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordItem;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordRow;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface SynonymMapper {
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT COUNT(*) FROM synonym_word w
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(w.word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
</script>
|
||||
""")
|
||||
long countWords(@Param("keyword") String keyword);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT w.word_id AS word_id,
|
||||
w.word,
|
||||
(SELECT COUNT(*) FROM synonym_sense s WHERE s.word_id = w.word_id) AS sense_count,
|
||||
EXISTS (SELECT 1
|
||||
FROM synonym_sense s
|
||||
JOIN synonym_group g ON g.sense_id = s.sense_id
|
||||
WHERE s.word_id = w.word_id) AS has_relation
|
||||
FROM synonym_word w
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
AND LOWER(w.word) LIKE CONCAT('%', LOWER(#{keyword}), '%')
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY w.word_id
|
||||
LIMIT #{limit} OFFSET #{offset}
|
||||
</script>
|
||||
""")
|
||||
List<WordItem> listWords(@Param("keyword") String keyword, @Param("offset") int offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
@Select("SELECT word_id AS word_id, word FROM synonym_word WHERE word_id = #{id}")
|
||||
WordRow findWord(@Param("id") long id);
|
||||
|
||||
@Select("""
|
||||
SELECT sense_id, part_of_speech, gloss_zh
|
||||
FROM synonym_sense
|
||||
WHERE word_id = #{wordId}
|
||||
ORDER BY sense_id
|
||||
""")
|
||||
List<com.wordmarket.admin.dto.SynonymDtos.SenseRow> listSenses(@Param("wordId") long wordId);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT g.sense_id, g.exam_id, ex.exam_name_zh AS exam_name, g.canonical_word_id,
|
||||
cw.word AS canonical_word, g.member_count
|
||||
FROM synonym_group g
|
||||
JOIN exam ex ON ex.exam_id = g.exam_id
|
||||
LEFT JOIN synonym_word cw ON cw.word_id = g.canonical_word_id
|
||||
WHERE g.sense_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY g.sense_id, g.exam_id
|
||||
</script>
|
||||
""")
|
||||
List<GroupRow> listGroups(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT m.sense_id, m.exam_id, m.member_word_id AS word_id, w.word, m.position
|
||||
FROM synonym_group_member m
|
||||
JOIN synonym_word w ON w.word_id = m.member_word_id
|
||||
WHERE m.sense_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY m.sense_id, m.exam_id, m.position
|
||||
</script>
|
||||
""")
|
||||
List<MemberRow> listMembers(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT a.sense_id, a.exam_id, ex.exam_name_zh AS exam_name,
|
||||
a.antonym_word_id AS word_id, w.word, a.position
|
||||
FROM synonym_antonym a
|
||||
JOIN synonym_word w ON w.word_id = a.antonym_word_id
|
||||
JOIN exam ex ON ex.exam_id = a.exam_id
|
||||
WHERE a.sense_id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
ORDER BY a.sense_id, a.exam_id, a.position
|
||||
</script>
|
||||
""")
|
||||
List<AntonymRow> listAntonyms(@Param("ids") List<Long> ids);
|
||||
|
||||
@Select("""
|
||||
SELECT CASE
|
||||
WHEN member_count <= 1 THEN '1'
|
||||
WHEN member_count = 2 THEN '2'
|
||||
WHEN member_count = 3 THEN '3'
|
||||
WHEN member_count = 4 THEN '4'
|
||||
WHEN member_count <= 6 THEN '5-6'
|
||||
WHEN member_count <= 10 THEN '7-10'
|
||||
ELSE '11+'
|
||||
END AS label,
|
||||
COUNT(*) AS count
|
||||
FROM synonym_group
|
||||
GROUP BY label
|
||||
ORDER BY MIN(member_count)
|
||||
""")
|
||||
List<BucketRow> groupSizeDistribution();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.wordmarket.admin.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public JwtAuthFilter(JwtService jwtService, ObjectMapper objectMapper) {
|
||||
this.jwtService = jwtService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
return true;
|
||||
}
|
||||
return "/api/auth/login".equals(request.getRequestURI());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (header == null || !header.startsWith("Bearer ")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String username = jwtService.parseSubject(header.substring(7));
|
||||
var authentication = new UsernamePasswordAuthenticationToken(
|
||||
username, null, List.of(new SimpleGrantedAuthority("ROLE_ADMIN")));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
filterChain.doFilter(request, response);
|
||||
} catch (RuntimeException ex) {
|
||||
SecurityContextHolder.clearContext();
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
objectMapper.writeValue(response.getWriter(),
|
||||
ApiResponse.error(401, "登录状态无效或已过期"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.wordmarket.admin.security;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.config.AdminProperties;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtService {
|
||||
|
||||
private final SecretKey key;
|
||||
private final int ttlHours;
|
||||
|
||||
public JwtService(AdminProperties properties) {
|
||||
this.key = Keys.hmacShaKeyFor(properties.getJwtSecret().getBytes(StandardCharsets.UTF_8));
|
||||
this.ttlHours = properties.getTokenTtlHours();
|
||||
}
|
||||
|
||||
public IssuedToken issue(String username) {
|
||||
Instant now = Instant.now();
|
||||
Instant expiresAt = now.plus(ttlHours, ChronoUnit.HOURS);
|
||||
String token = Jwts.builder()
|
||||
.subject(username)
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(expiresAt))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
return new IssuedToken(token, expiresAt);
|
||||
}
|
||||
|
||||
public String parseSubject(String token) {
|
||||
try {
|
||||
Claims claims = Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
return claims.getSubject();
|
||||
} catch (JwtException | IllegalArgumentException ex) {
|
||||
throw BizException.unauthorized("登录状态无效或已过期");
|
||||
}
|
||||
}
|
||||
|
||||
public record IssuedToken(String token, Instant expiresAt) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.wordmarket.admin.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.wordmarket.admin.common.ApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Component
|
||||
public class RestAuthEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public RestAuthEntryPoint(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException authException) throws IOException {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
objectMapper.writeValue(response.getWriter(), ApiResponse.error(401, "未认证或登录已过期"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@Component
|
||||
public class AggregateCache {
|
||||
|
||||
private final Cache<String, Object> cache;
|
||||
|
||||
public AggregateCache(Cache<String, Object> aggregateCache) {
|
||||
this.cache = aggregateCache;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T get(String key, boolean refresh, Supplier<T> loader) {
|
||||
if (!refresh) {
|
||||
Object cached = cache.getIfPresent(key);
|
||||
if (cached != null) {
|
||||
return (T) cached;
|
||||
}
|
||||
}
|
||||
T value = loader.get();
|
||||
cache.put(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
cache.invalidateAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.config.AdminProperties;
|
||||
import com.wordmarket.admin.dto.AuthDtos.LoginRequest;
|
||||
import com.wordmarket.admin.dto.AuthDtos.LoginResponse;
|
||||
import com.wordmarket.admin.security.JwtService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
private final AdminProperties adminProperties;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
|
||||
public AuthService(AdminProperties adminProperties, PasswordEncoder passwordEncoder,
|
||||
JwtService jwtService) {
|
||||
this.adminProperties = adminProperties;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtService = jwtService;
|
||||
}
|
||||
|
||||
public LoginResponse login(LoginRequest request) {
|
||||
boolean usernameMatches = adminProperties.getUsername().equals(request.username());
|
||||
boolean passwordMatches = passwordEncoder.matches(request.password(),
|
||||
adminProperties.getPasswordHash());
|
||||
if (!usernameMatches || !passwordMatches) {
|
||||
throw BizException.unauthorized("用户名或密码错误");
|
||||
}
|
||||
JwtService.IssuedToken issued = jwtService.issue(request.username());
|
||||
return new LoginResponse(issued.token(), issued.expiresAt().toString(), request.username());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.common.Pages;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookDetail;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookDetailRow;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookEntryItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookListItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.ExamOption;
|
||||
import com.wordmarket.admin.mapper.BookMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class BookService {
|
||||
|
||||
private final BookMapper bookMapper;
|
||||
|
||||
public BookService(BookMapper bookMapper) {
|
||||
this.bookMapper = bookMapper;
|
||||
}
|
||||
|
||||
public PageResult<BookListItem> list(Integer pageParam, Integer sizeParam, Long examId,
|
||||
String keyword, Boolean hasFile) {
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = bookMapper.countBooks(examId, keyword, hasFile);
|
||||
List<BookListItem> items = bookMapper.listBooks(examId, keyword, hasFile,
|
||||
Pages.offset(page, size), size);
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public BookDetail detail(long id) {
|
||||
BookDetailRow detail = bookMapper.findBook(id);
|
||||
if (detail == null) {
|
||||
throw BizException.notFound("词书不存在");
|
||||
}
|
||||
boolean mismatch = detail.declared() != null && detail.declared() != detail.actual();
|
||||
return new BookDetail(detail.id(), detail.code(), detail.name(), detail.description(),
|
||||
detail.examId(), detail.examName(), detail.declared(), detail.actual(),
|
||||
detail.contentVersion(), detail.schemaVersion(), detail.coverPath(),
|
||||
detail.packageUrl(), detail.hasFile(), detail.sortAt(), detail.labels(), mismatch);
|
||||
}
|
||||
|
||||
public PageResult<BookEntryItem> entries(long bookId, Integer pageParam, Integer sizeParam,
|
||||
String keyword) {
|
||||
detail(bookId);
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = bookMapper.countBookEntries(bookId, keyword);
|
||||
List<BookEntryItem> items = bookMapper.listBookEntries(bookId, keyword,
|
||||
Pages.offset(page, size), size);
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public List<ExamOption> exams() {
|
||||
return bookMapper.listExams();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.dto.DashboardDtos.CoverageItem;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.ExamStat;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.Kpi;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.PosStat;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.QualityItem;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.Summary;
|
||||
import com.wordmarket.admin.dto.DashboardDtos.TopBook;
|
||||
import com.wordmarket.admin.mapper.DashboardMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class DashboardService {
|
||||
|
||||
private final DashboardMapper dashboardMapper;
|
||||
private final QualityService qualityService;
|
||||
private final AggregateCache cache;
|
||||
|
||||
public DashboardService(DashboardMapper dashboardMapper, QualityService qualityService,
|
||||
AggregateCache cache) {
|
||||
this.dashboardMapper = dashboardMapper;
|
||||
this.qualityService = qualityService;
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public Summary summary(boolean refresh) {
|
||||
return cache.get("dashboard:summary", refresh, this::loadSummary);
|
||||
}
|
||||
|
||||
private Summary loadSummary() {
|
||||
long books = dashboardMapper.countBooks();
|
||||
long entries = dashboardMapper.countEntries();
|
||||
long links = dashboardMapper.countBookEntries();
|
||||
long sentences = dashboardMapper.countExampleSentences();
|
||||
long families = dashboardMapper.countFamilies();
|
||||
long synonymWords = dashboardMapper.countSynonymWords();
|
||||
|
||||
long averagePerBook = books == 0 ? 0 : Math.round(links * 1.0 / books);
|
||||
|
||||
List<Kpi> kpis = List.of(
|
||||
new Kpi("books", "词书", books,
|
||||
dashboardMapper.countBooksWithoutFile() + " 本无清单文件", "blue"),
|
||||
new Kpi("entries", "词条", entries,
|
||||
String.format("%,d 个索引词", dashboardMapper.countIndexWords()), "green"),
|
||||
new Kpi("links", "词书词条关联", links,
|
||||
String.format("平均每本 %,d 条", averagePerBook), "violet"),
|
||||
new Kpi("sentences", "例句", sentences,
|
||||
String.format("含使用模式 %,d", dashboardMapper.countExampleUsages()), "amber"),
|
||||
new Kpi("families", "词族", families,
|
||||
String.format("顶层族 %,d", dashboardMapper.countTopFamilies()), "cyan"),
|
||||
new Kpi("synonyms", "近义词头", synonymWords,
|
||||
String.format("义项 %,d", dashboardMapper.countSynonymSenses()), "rose"));
|
||||
|
||||
List<QualityItem> quality = qualityService.loadSummaryItems().stream()
|
||||
.map(item -> new QualityItem(item.key(), item.label(), item.value(), item.unit(),
|
||||
item.level(), QualityService.targetOf(item.key())))
|
||||
.toList();
|
||||
|
||||
List<CoverageItem> coverage = qualityService.loadCoverage().stream()
|
||||
.map(item -> new CoverageItem(item.name(), item.hit(), item.total(), item.pct()))
|
||||
.toList();
|
||||
|
||||
return new Summary(kpis, quality, coverage);
|
||||
}
|
||||
|
||||
public List<ExamStat> examDistribution(boolean refresh) {
|
||||
return cache.get("dashboard:exam", refresh, dashboardMapper::examDistribution);
|
||||
}
|
||||
|
||||
public List<TopBook> topBooks(boolean refresh) {
|
||||
return cache.get("dashboard:top", refresh, dashboardMapper::topBooks);
|
||||
}
|
||||
|
||||
public List<PosStat> posDistribution(boolean refresh) {
|
||||
return cache.get("dashboard:pos", refresh, dashboardMapper::posDistribution);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.common.Pages;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ConfusableItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryBookItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryBookRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryDetail;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryListItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExamRef;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleGroupItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleGroupRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleSentenceItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleUsageItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.GroupExamRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseExamRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseOrder;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseOrderRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.PhraseRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseExamRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseRelation;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseRelationRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SentenceRow;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SpellingVariantItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.UsageRow;
|
||||
import com.wordmarket.admin.mapper.EntryMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class EntryService {
|
||||
|
||||
private static final int DEFINITION_PREVIEW = 120;
|
||||
|
||||
private final EntryMapper entryMapper;
|
||||
|
||||
public EntryService(EntryMapper entryMapper) {
|
||||
this.entryMapper = entryMapper;
|
||||
}
|
||||
|
||||
public PageResult<EntryListItem> list(Integer pageParam, Integer sizeParam, String keyword) {
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = entryMapper.countEntries(keyword);
|
||||
List<EntryListItem> items = entryMapper.listEntries(keyword, Pages.offset(page, size), size)
|
||||
.stream()
|
||||
.map(item -> new EntryListItem(item.id(), item.headword(), item.indexWord(),
|
||||
item.pronunciation(), preview(item.definition()), item.senseCount(),
|
||||
item.bookCount()))
|
||||
.toList();
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public EntryDetail detail(long id) {
|
||||
EntryDetail detail = entryMapper.findEntry(id);
|
||||
if (detail == null) {
|
||||
throw BizException.notFound("词条不存在");
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
public List<SenseItem> senses(long entryId) {
|
||||
detail(entryId);
|
||||
List<SenseRow> rows = entryMapper.listSenses(entryId);
|
||||
if (rows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> ids = rows.stream().map(row -> Long.parseLong(row.senseId())).toList();
|
||||
Map<Long, List<ExamRef>> exams = groupExams(entryMapper.listSenseExams(ids));
|
||||
Map<Long, List<SenseRelation>> relations = groupRelations(entryMapper.listSenseRelations(ids));
|
||||
List<SenseItem> items = new ArrayList<>(rows.size());
|
||||
for (SenseRow row : rows) {
|
||||
long senseId = Long.parseLong(row.senseId());
|
||||
items.add(new SenseItem(row.senseId(), row.senseNo(), row.partOfSpeech(), row.glossZh(),
|
||||
exams.getOrDefault(senseId, List.of()),
|
||||
relations.getOrDefault(senseId, List.of())));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
public PageResult<PhraseItem> phrases(long entryId, Integer pageParam, Integer sizeParam) {
|
||||
detail(entryId);
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = entryMapper.countPhrases(entryId);
|
||||
List<PhraseRow> rows = entryMapper.listPhrases(entryId, Pages.offset(page, size), size);
|
||||
if (rows.isEmpty()) {
|
||||
return PageResult.of(List.of(), total, page, size);
|
||||
}
|
||||
List<Long> ids = rows.stream().map(row -> Long.parseLong(row.id())).toList();
|
||||
Map<Long, List<ExamRef>> exams = groupPhraseExams(entryMapper.listPhraseExams(ids));
|
||||
Map<Long, List<PhraseOrder>> orders = new HashMap<>();
|
||||
for (PhraseOrderRow order : entryMapper.listPhraseOrders(entryId)) {
|
||||
orders.computeIfAbsent(Long.parseLong(order.phraseId()), key -> new ArrayList<>())
|
||||
.add(new PhraseOrder(order.examId(), order.examName(), order.groupType(),
|
||||
order.position()));
|
||||
}
|
||||
List<PhraseItem> items = rows.stream()
|
||||
.map(row -> {
|
||||
long phraseId = Long.parseLong(row.id());
|
||||
return new PhraseItem(row.id(), row.textEn(), row.textZh(), row.groupType(),
|
||||
row.meaningId(), exams.getOrDefault(phraseId, List.of()),
|
||||
orders.getOrDefault(phraseId, List.of()));
|
||||
})
|
||||
.toList();
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public PageResult<ExampleGroupItem> examples(long entryId, Integer pageParam, Integer sizeParam) {
|
||||
detail(entryId);
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = entryMapper.countExampleGroups(entryId);
|
||||
List<ExampleGroupRow> rows = entryMapper.listExampleGroups(entryId,
|
||||
Pages.offset(page, size), size);
|
||||
if (rows.isEmpty()) {
|
||||
return PageResult.of(List.of(), total, page, size);
|
||||
}
|
||||
List<Long> ids = rows.stream().map(row -> Long.parseLong(row.id())).toList();
|
||||
Map<Long, List<ExamRef>> exams = groupExampleExams(entryMapper.listExampleGroupExams(ids));
|
||||
Map<Long, List<UsageRow>> usages = new HashMap<>();
|
||||
for (UsageRow usage : entryMapper.listExampleUsages(ids)) {
|
||||
usages.computeIfAbsent(Long.parseLong(usage.groupId()), key -> new ArrayList<>())
|
||||
.add(usage);
|
||||
}
|
||||
Map<Long, List<SentenceRow>> sentencesByGroup = new HashMap<>();
|
||||
Map<Long, List<SentenceRow>> sentencesByUsage = new HashMap<>();
|
||||
for (SentenceRow sentence : entryMapper.listExampleSentences(ids)) {
|
||||
sentencesByGroup.computeIfAbsent(Long.parseLong(sentence.groupId()),
|
||||
key -> new ArrayList<>()).add(sentence);
|
||||
if (sentence.usageId() != null) {
|
||||
sentencesByUsage.computeIfAbsent(Long.parseLong(sentence.usageId()),
|
||||
key -> new ArrayList<>()).add(sentence);
|
||||
}
|
||||
}
|
||||
List<ExampleGroupItem> items = new ArrayList<>(rows.size());
|
||||
for (ExampleGroupRow row : rows) {
|
||||
long groupId = Long.parseLong(row.id());
|
||||
List<ExampleUsageItem> usageItems = usages.getOrDefault(groupId, List.of()).stream()
|
||||
.map(usage -> new ExampleUsageItem(usage.id(), usage.patternId(),
|
||||
usage.patternText(), usage.position(), toSentenceItems(
|
||||
sentencesByUsage.getOrDefault(Long.parseLong(usage.id()), List.of()))))
|
||||
.toList();
|
||||
List<SentenceRow> groupSentences = sentencesByGroup.getOrDefault(groupId, List.of());
|
||||
List<ExampleSentenceItem> direct = groupSentences.stream()
|
||||
.filter(sentence -> sentence.usageId() == null)
|
||||
.map(EntryService::toSentenceItem)
|
||||
.toList();
|
||||
items.add(new ExampleGroupItem(row.id(), row.groupKind(), row.partOfSpeech(),
|
||||
row.entryKindCode(), row.headForm(), row.definitionEn(), row.definitionZh(),
|
||||
exams.getOrDefault(groupId, List.of()), usageItems, direct, groupSentences.size()));
|
||||
}
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public List<ConfusableItem> confusables(long entryId) {
|
||||
detail(entryId);
|
||||
return entryMapper.listConfusables(entryId).stream()
|
||||
.map(row -> new ConfusableItem(row.id(), row.wordText(), row.glossZh(), row.posCode(),
|
||||
row.spellingFlag(), row.position()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<SpellingVariantItem> spellingVariants(long entryId) {
|
||||
detail(entryId);
|
||||
return entryMapper.listSpellingVariants(entryId).stream()
|
||||
.map(row -> new SpellingVariantItem(row.position(), row.variant()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public PageResult<EntryBookItem> books(long entryId, Integer pageParam, Integer sizeParam) {
|
||||
detail(entryId);
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = entryMapper.countEntryBooks(entryId);
|
||||
List<EntryBookItem> items = entryMapper.listEntryBooks(entryId, Pages.offset(page, size), size)
|
||||
.stream()
|
||||
.map(row -> new EntryBookItem(row.bookId(), row.bookName(), row.bookCode(),
|
||||
row.displayWord(), row.seqBook()))
|
||||
.toList();
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
private static Map<Long, List<ExamRef>> groupExams(List<SenseExamRow> rows) {
|
||||
Map<Long, List<ExamRef>> map = new HashMap<>();
|
||||
for (SenseExamRow row : rows) {
|
||||
map.computeIfAbsent(Long.parseLong(row.senseId()), key -> new ArrayList<>())
|
||||
.add(new ExamRef(row.id(), row.code(), row.name()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<Long, List<SenseRelation>> groupRelations(List<SenseRelationRow> rows) {
|
||||
Map<Long, List<SenseRelation>> map = new HashMap<>();
|
||||
for (SenseRelationRow row : rows) {
|
||||
map.computeIfAbsent(Long.parseLong(row.senseId()), key -> new ArrayList<>())
|
||||
.add(new SenseRelation(row.type(), row.position(), row.targetMeaningId(),
|
||||
row.targetEntryId()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<Long, List<ExamRef>> groupPhraseExams(List<PhraseExamRow> rows) {
|
||||
Map<Long, List<ExamRef>> map = new LinkedHashMap<>();
|
||||
for (PhraseExamRow row : rows) {
|
||||
map.computeIfAbsent(Long.parseLong(row.phraseId()), key -> new ArrayList<>())
|
||||
.add(new ExamRef(row.id(), row.code(), row.name()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<Long, List<ExamRef>> groupExampleExams(List<GroupExamRow> rows) {
|
||||
Map<Long, List<ExamRef>> map = new HashMap<>();
|
||||
for (GroupExamRow row : rows) {
|
||||
map.computeIfAbsent(Long.parseLong(row.groupId()), key -> new ArrayList<>())
|
||||
.add(new ExamRef(row.id(), row.code(), row.name()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static List<ExampleSentenceItem> toSentenceItems(List<SentenceRow> rows) {
|
||||
return rows.stream().map(EntryService::toSentenceItem).toList();
|
||||
}
|
||||
|
||||
private static ExampleSentenceItem toSentenceItem(SentenceRow row) {
|
||||
return new ExampleSentenceItem(row.id(), row.textEn(), row.textZh(), row.sourceTitle(),
|
||||
row.audioUrl(), row.listening());
|
||||
}
|
||||
|
||||
private static String preview(String text) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = text.trim();
|
||||
if (trimmed.length() <= DEFINITION_PREVIEW) {
|
||||
return trimmed;
|
||||
}
|
||||
return trimmed.substring(0, DEFINITION_PREVIEW) + "…";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.common.Pages;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardBrief;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardDetail;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardFamilyLink;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardItemRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.CardRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.ExamRef;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyDetail;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyExamRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyLinkRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyMemberItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.FamilyVariantItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.LinkExamRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MemberRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MiniGroupItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MiniGroupRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeDetail;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeItem;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.MorphemeRefRow;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.TreeCounts;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.TreeNode;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.TreePage;
|
||||
import com.wordmarket.admin.dto.MorphologyDtos.VariantRow;
|
||||
import com.wordmarket.admin.mapper.MorphologyMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class MorphologyService {
|
||||
|
||||
private static final Set<String> MORPHEME_TYPES = Set.of("prefix", "root", "suffix");
|
||||
private static final int MEMBER_PREVIEW = 50;
|
||||
|
||||
private final MorphologyMapper morphologyMapper;
|
||||
|
||||
public MorphologyService(MorphologyMapper morphologyMapper) {
|
||||
this.morphologyMapper = morphologyMapper;
|
||||
}
|
||||
|
||||
public PageResult<MorphemeItem> morphemes(String type, String keyword, Integer pageParam,
|
||||
Integer sizeParam) {
|
||||
if (type != null && !type.isBlank() && !MORPHEME_TYPES.contains(type)) {
|
||||
throw BizException.badRequest("词素类型必须为 prefix、root 或 suffix");
|
||||
}
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = morphologyMapper.countMorphemes(type, keyword);
|
||||
List<MorphemeItem> items = morphologyMapper.listMorphemes(type, keyword,
|
||||
Pages.offset(page, size), size);
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public MorphemeDetail morpheme(long id) {
|
||||
MorphemeItem item = morphologyMapper.findMorpheme(id);
|
||||
if (item == null) {
|
||||
throw BizException.notFound("词素不存在");
|
||||
}
|
||||
List<CardBrief> cards = morphologyMapper.listCardsByMorpheme(id);
|
||||
return new MorphemeDetail(item.id(), item.type(), item.form(), item.displayText(),
|
||||
item.meaningEn(), item.meaningZh(), item.note(), cards,
|
||||
morphologyMapper.countCardsByMorpheme(id));
|
||||
}
|
||||
|
||||
public PageResult<CardItem> cards(String keyword, Integer pageParam, Integer sizeParam) {
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = morphologyMapper.countCards(keyword);
|
||||
List<CardItemRow> rows = morphologyMapper.listCards(keyword, Pages.offset(page, size), size);
|
||||
if (rows.isEmpty()) {
|
||||
return PageResult.of(List.of(), total, page, size);
|
||||
}
|
||||
List<Long> ids = rows.stream().map(row -> Long.parseLong(row.id())).toList();
|
||||
Map<Long, List<ExamRef>> exams = groupCardExams(morphologyMapper.listCardExams(ids));
|
||||
List<CardItem> items = rows.stream()
|
||||
.map(row -> new CardItem(row.id(), row.word(), row.memoryNote(), row.highlightedWord(),
|
||||
exams.getOrDefault(Long.parseLong(row.id()), List.of())))
|
||||
.toList();
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public CardDetail card(long id) {
|
||||
CardRow row = morphologyMapper.findCard(id);
|
||||
if (row == null) {
|
||||
throw BizException.notFound("单词卡片不存在");
|
||||
}
|
||||
Map<Long, List<ExamRef>> exams = groupCardExams(
|
||||
morphologyMapper.listCardExams(List.of(id)));
|
||||
List<Long> morphemeIds = new ArrayList<>();
|
||||
addPositive(morphemeIds, row.prefixMorphemeId());
|
||||
addPositive(morphemeIds, row.rootMorphemeId());
|
||||
addPositive(morphemeIds, row.suffixMorphemeId());
|
||||
Map<Long, MorphemeRefRow> refs = new HashMap<>();
|
||||
if (!morphemeIds.isEmpty()) {
|
||||
for (MorphemeRefRow ref : morphologyMapper.listMorphemeRefs(morphemeIds)) {
|
||||
refs.put(Long.parseLong(ref.id()), ref);
|
||||
}
|
||||
}
|
||||
List<CardFamilyLink> links = morphologyMapper.listCardFamilyLinks(id).stream()
|
||||
.map(link -> new CardFamilyLink(link.id(), link.groupNo(), link.familyRef(),
|
||||
link.hidden()))
|
||||
.toList();
|
||||
return new CardDetail(row.id(), row.word(), row.highlightedWord(), row.memoryNote(),
|
||||
row.exampleText(), row.hidden(),
|
||||
morphemeId(row.prefixMorphemeId()), formOf(refs, row.prefixMorphemeId()),
|
||||
morphemeId(row.rootMorphemeId()), formOf(refs, row.rootMorphemeId()),
|
||||
morphemeId(row.suffixMorphemeId()), formOf(refs, row.suffixMorphemeId()),
|
||||
row.defaultFamilyRef(), exams.getOrDefault(id, List.of()), links);
|
||||
}
|
||||
|
||||
public PageResult<FamilyItem> families(String keyword, Integer pageParam, Integer sizeParam) {
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = morphologyMapper.countFamilies(keyword);
|
||||
List<FamilyRow> rows = morphologyMapper.listFamilies(keyword, Pages.offset(page, size), size);
|
||||
if (rows.isEmpty()) {
|
||||
return PageResult.of(List.of(), total, page, size);
|
||||
}
|
||||
List<Long> ids = rows.stream().map(row -> Long.parseLong(row.id())).toList();
|
||||
Map<Long, List<ExamRef>> exams = groupFamilyExams(morphologyMapper.listFamilyExams(ids));
|
||||
List<FamilyItem> items = rows.stream()
|
||||
.map(row -> new FamilyItem(row.id(), row.word(), row.topFamilyId(), row.topWord(),
|
||||
row.interpretation(), row.groupLevel1(), row.groupLevel2(), row.groupLevel3(),
|
||||
exams.getOrDefault(Long.parseLong(row.id()), List.of())))
|
||||
.toList();
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public FamilyDetail family(long id) {
|
||||
FamilyRow row = morphologyMapper.findFamily(id);
|
||||
if (row == null) {
|
||||
throw BizException.notFound("词族不存在");
|
||||
}
|
||||
Map<Long, List<ExamRef>> exams = groupFamilyExams(
|
||||
morphologyMapper.listFamilyExams(List.of(id)));
|
||||
long topId = Long.parseLong(row.topFamilyId());
|
||||
List<FamilyVariantItem> variants = morphologyMapper.listVariants(topId).stream()
|
||||
.map(variant -> new FamilyVariantItem(variant.id(), variant.variantWord(),
|
||||
variant.interpretation(), variant.memberCount()))
|
||||
.toList();
|
||||
List<MiniGroupItem> miniGroups = new ArrayList<>();
|
||||
for (MiniGroupRow group : morphologyMapper.listMiniGroups(topId)) {
|
||||
List<FamilyMemberItem> members = morphologyMapper
|
||||
.listMiniGroupMembers(Long.parseLong(group.id())).stream()
|
||||
.map(member -> new FamilyMemberItem(member.familyEntryId(), member.word(),
|
||||
member.position()))
|
||||
.toList();
|
||||
miniGroups.add(new MiniGroupItem(group.id(), group.size(), members));
|
||||
}
|
||||
return new FamilyDetail(row.id(), row.word(), row.topFamilyId(), row.topWord(),
|
||||
row.interpretation(), row.groupLevel1(), row.groupLevel2(), row.groupLevel3(),
|
||||
exams.getOrDefault(id, List.of()), variants, miniGroups);
|
||||
}
|
||||
|
||||
public TreePage tree(long id, String nodeType, Integer pageParam, Integer sizeParam) {
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
String type = nodeType == null || nodeType.isBlank() ? "top" : nodeType;
|
||||
return switch (type) {
|
||||
case "top" -> {
|
||||
if (morphologyMapper.findFamily(id) == null) {
|
||||
throw BizException.notFound("词族不存在");
|
||||
}
|
||||
TreeCounts counts = morphologyMapper.countTopChildren(id);
|
||||
List<TreeNode> nodes = morphologyMapper.listTopChildren(id, Pages.offset(page, size),
|
||||
size);
|
||||
yield new TreePage(nodes, counts.variantCount() + counts.groupCount(), page, size);
|
||||
}
|
||||
case "variant" -> new TreePage(
|
||||
morphologyMapper.listVariantMemberNodes(id, Pages.offset(page, size), size),
|
||||
morphologyMapper.countVariantMembers(id), page, size);
|
||||
case "miniGroup" -> new TreePage(
|
||||
morphologyMapper.listMiniGroupMemberNodes(id, Pages.offset(page, size), size),
|
||||
morphologyMapper.countMiniGroupMembers(id), page, size);
|
||||
default -> throw BizException.badRequest("不支持的树节点类型");
|
||||
};
|
||||
}
|
||||
|
||||
private static Map<Long, List<ExamRef>> groupCardExams(List<LinkExamRow> rows) {
|
||||
Map<Long, List<ExamRef>> map = new HashMap<>();
|
||||
for (LinkExamRow row : rows) {
|
||||
map.computeIfAbsent(Long.parseLong(row.cardId()), key -> new ArrayList<>())
|
||||
.add(new ExamRef(row.id(), row.code(), row.name()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<Long, List<ExamRef>> groupFamilyExams(List<FamilyExamRow> rows) {
|
||||
Map<Long, List<ExamRef>> map = new HashMap<>();
|
||||
for (FamilyExamRow row : rows) {
|
||||
map.computeIfAbsent(Long.parseLong(row.familyEntryId()), key -> new ArrayList<>())
|
||||
.add(new ExamRef(row.id(), row.code(), row.name()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static void addPositive(List<Long> ids, String value) {
|
||||
if (value != null && !value.isBlank() && !"0".equals(value)) {
|
||||
ids.add(Long.parseLong(value));
|
||||
}
|
||||
}
|
||||
|
||||
private static String morphemeId(String value) {
|
||||
return value == null || "0".equals(value) ? null : value;
|
||||
}
|
||||
|
||||
private static String formOf(Map<Long, MorphemeRefRow> refs, String id) {
|
||||
if (id == null || "0".equals(id)) {
|
||||
return null;
|
||||
}
|
||||
MorphemeRefRow ref = refs.get(Long.parseLong(id));
|
||||
return ref == null ? null : ref.form();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.config.AppProperties;
|
||||
import com.wordmarket.admin.dto.QualityDtos.Coverage;
|
||||
import com.wordmarket.admin.dto.QualityDtos.DeclaredDiff;
|
||||
import com.wordmarket.admin.dto.QualityDtos.MissingBook;
|
||||
import com.wordmarket.admin.dto.QualityDtos.MissingReference;
|
||||
import com.wordmarket.admin.dto.QualityDtos.MissingZpk;
|
||||
import com.wordmarket.admin.dto.QualityDtos.QualitySummary;
|
||||
import com.wordmarket.admin.dto.QualityDtos.SummaryItem;
|
||||
import com.wordmarket.admin.mapper.QualityMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class QualityService {
|
||||
|
||||
private static final String KEY_MISMATCH = "mismatch";
|
||||
private static final String KEY_NO_FILE = "nofile";
|
||||
private static final String KEY_NO_ZPK = "nozpk";
|
||||
private static final String KEY_NO_SENSE = "nosense";
|
||||
private static final String KEY_NO_SYN_SENSE = "nosyn";
|
||||
private static final String KEY_NO_EXAM = "noexam";
|
||||
private static final String KEY_NO_COVER = "nocover";
|
||||
|
||||
private final QualityMapper qualityMapper;
|
||||
private final AggregateCache cache;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
public QualityService(QualityMapper qualityMapper, AggregateCache cache, AppProperties appProperties) {
|
||||
this.qualityMapper = qualityMapper;
|
||||
this.cache = cache;
|
||||
this.appProperties = appProperties;
|
||||
}
|
||||
|
||||
public QualitySummary summary(boolean refresh) {
|
||||
return cache.get("quality:summary", refresh, () -> new QualitySummary(loadSummaryItems()));
|
||||
}
|
||||
|
||||
public List<SummaryItem> loadSummaryItems() {
|
||||
List<SummaryItem> items = new ArrayList<>();
|
||||
items.add(new SummaryItem(KEY_MISMATCH, "声明与实际词条数不一致",
|
||||
qualityMapper.countDeclaredMismatch(), "本", "warn",
|
||||
"口径:book.declared_entry_count 与 book_entry 实际行数不一致的词书。"));
|
||||
items.add(new SummaryItem(KEY_NO_FILE, "缺失词书清单文件",
|
||||
qualityMapper.countMissingFiles(), "本", "bad",
|
||||
"口径:目录中存在但磁盘缺少清单文件的词书(book.has_wordbook_file = 0)。"));
|
||||
items.add(new SummaryItem(KEY_NO_ZPK, "缺失 zpk 引用",
|
||||
missingZpkRows().size(), "个", "bad",
|
||||
"口径:配置中登记的缺失 zpk 文件键,仍被 book_entry.source_zpk_key 引用的去重数量。"));
|
||||
items.add(new SummaryItem(KEY_NO_SENSE, "无结构化义项的词条",
|
||||
qualityMapper.countEntriesWithoutSense(), "条", "warn",
|
||||
"口径:word_sense 中完全没有记录的词条。"));
|
||||
items.add(new SummaryItem(KEY_NO_SYN_SENSE, "无义项的近义词头",
|
||||
qualityMapper.countSynonymWordsWithoutSense(), "个", "warn",
|
||||
"口径:synonym_sense 中完全没有记录的近义词头。"));
|
||||
items.add(new SummaryItem(KEY_NO_EXAM, "未设置考试的词书",
|
||||
qualityMapper.countBooksWithoutExam(), "本", "info",
|
||||
"口径:book.exam_id 为空的词书,通常为非考试类或未归类。"));
|
||||
items.add(new SummaryItem(KEY_NO_COVER, "无封面词书",
|
||||
qualityMapper.countBooksWithoutCover(), "本", "info",
|
||||
"口径:book.cover_url 为空的词书,前端展示统一占位图。"));
|
||||
return items;
|
||||
}
|
||||
|
||||
public List<DeclaredDiff> declaredVsActual(boolean refresh) {
|
||||
return cache.get("quality:declared", refresh, qualityMapper::listDeclaredMismatch);
|
||||
}
|
||||
|
||||
public List<MissingReference> missingReferences(boolean refresh) {
|
||||
return cache.get("quality:missing", refresh, this::loadMissingReferences);
|
||||
}
|
||||
|
||||
private List<MissingReference> loadMissingReferences() {
|
||||
List<MissingReference> items = new ArrayList<>();
|
||||
for (MissingBook book : qualityMapper.listMissingFileBooks()) {
|
||||
items.add(new MissingReference("book_file", book.bookCode(),
|
||||
"book.has_wordbook_file", book.bookName(), book.bookId()));
|
||||
}
|
||||
List<String> keys = configuredZpkKeys();
|
||||
if (!keys.isEmpty()) {
|
||||
for (MissingZpk zpk : qualityMapper.listKnownMissingZpk(keys)) {
|
||||
items.add(new MissingReference("zpk", zpk.sourceKey(), "book_entry.source_zpk_key",
|
||||
"影响 " + zpk.rowCount() + " 行词书关联;词书 ID: " + zpk.bookIds(), null));
|
||||
}
|
||||
}
|
||||
for (MissingBook book : qualityMapper.listBooksWithoutCover()) {
|
||||
items.add(new MissingReference("cover", book.bookCode(), "book.cover_url",
|
||||
book.bookName(), book.bookId()));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
public List<Coverage> crossDomainCoverage(boolean refresh) {
|
||||
return cache.get("quality:coverage", refresh, this::loadCoverage);
|
||||
}
|
||||
|
||||
public List<Coverage> loadCoverage() {
|
||||
List<Coverage> items = new ArrayList<>();
|
||||
items.add(coverage("card", "单词卡片", qualityMapper.cardHit(), qualityMapper.cardTotal()));
|
||||
items.add(coverage("family", "词族", qualityMapper.familyHit(), qualityMapper.familyTotal()));
|
||||
items.add(coverage("synonym", "近义词头", qualityMapper.synonymHit(), qualityMapper.synonymTotal()));
|
||||
return items;
|
||||
}
|
||||
|
||||
private List<MissingZpk> missingZpkRows() {
|
||||
List<String> keys = configuredZpkKeys();
|
||||
if (keys.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return qualityMapper.listKnownMissingZpk(keys);
|
||||
}
|
||||
|
||||
private List<String> configuredZpkKeys() {
|
||||
String raw = appProperties.getQuality().getKnownMissingZpkKeys();
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
return Arrays.stream(raw.split(","))
|
||||
.map(String::trim)
|
||||
.filter(value -> !value.isEmpty())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static Coverage coverage(String key, String name, long hit, long total) {
|
||||
double pct = total == 0 ? 0 : Math.round(hit * 1000.0 / total) / 10.0;
|
||||
return new Coverage(key, name, hit, total, pct);
|
||||
}
|
||||
|
||||
public static String levelOf(String key) {
|
||||
return switch (key) {
|
||||
case KEY_NO_FILE, KEY_NO_ZPK -> "bad";
|
||||
case KEY_MISMATCH, KEY_NO_SENSE, KEY_NO_SYN_SENSE -> "warn";
|
||||
default -> "info";
|
||||
};
|
||||
}
|
||||
|
||||
public static String targetOf(String key) {
|
||||
return switch (key) {
|
||||
case KEY_NO_SENSE, KEY_NO_ZPK -> "词条";
|
||||
case KEY_NO_SYN_SENSE -> "近义词";
|
||||
default -> "词书";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.common.Pages;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.AntonymItem;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.AntonymRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.GroupItem;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.GroupRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.MemberItem;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.MemberRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.SenseItem;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.SenseRow;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.SizeBucket;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordDetail;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordItem;
|
||||
import com.wordmarket.admin.dto.SynonymDtos.WordRow;
|
||||
import com.wordmarket.admin.mapper.SynonymMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class SynonymService {
|
||||
|
||||
private static final int MEMBER_LIMIT = 50;
|
||||
|
||||
private final SynonymMapper synonymMapper;
|
||||
|
||||
public SynonymService(SynonymMapper synonymMapper) {
|
||||
this.synonymMapper = synonymMapper;
|
||||
}
|
||||
|
||||
public PageResult<WordItem> list(Integer pageParam, Integer sizeParam, String keyword) {
|
||||
int page = Pages.page(pageParam);
|
||||
int size = Pages.size(sizeParam);
|
||||
long total = synonymMapper.countWords(keyword);
|
||||
List<WordItem> items = synonymMapper.listWords(keyword, Pages.offset(page, size), size);
|
||||
return PageResult.of(items, total, page, size);
|
||||
}
|
||||
|
||||
public WordDetail detail(long wordId) {
|
||||
WordRow word = synonymMapper.findWord(wordId);
|
||||
if (word == null) {
|
||||
throw BizException.notFound("近义词词头不存在");
|
||||
}
|
||||
List<SenseRow> senses = synonymMapper.listSenses(wordId);
|
||||
if (senses.isEmpty()) {
|
||||
return new WordDetail(word.wordId(), word.word(), List.of());
|
||||
}
|
||||
List<Long> ids = senses.stream().map(sense -> Long.parseLong(sense.senseId())).toList();
|
||||
Map<String, List<GroupRow>> groupsBySense = new HashMap<>();
|
||||
for (GroupRow group : synonymMapper.listGroups(ids)) {
|
||||
groupsBySense.computeIfAbsent(group.senseId(), key -> new ArrayList<>()).add(group);
|
||||
}
|
||||
Map<String, List<MemberRow>> membersByGroup = new HashMap<>();
|
||||
for (MemberRow member : synonymMapper.listMembers(ids)) {
|
||||
membersByGroup.computeIfAbsent(member.senseId() + ":" + member.examId(),
|
||||
key -> new ArrayList<>()).add(member);
|
||||
}
|
||||
Map<String, List<AntonymRow>> antonymsByGroup = new LinkedHashMap<>();
|
||||
for (AntonymRow antonym : synonymMapper.listAntonyms(ids)) {
|
||||
antonymsByGroup.computeIfAbsent(antonym.senseId() + ":" + antonym.examId(),
|
||||
key -> new ArrayList<>()).add(antonym);
|
||||
}
|
||||
|
||||
List<SenseItem> senseItems = new ArrayList<>(senses.size());
|
||||
for (SenseRow sense : senses) {
|
||||
List<GroupItem> groups = new ArrayList<>();
|
||||
List<AntonymItem> antonyms = new ArrayList<>();
|
||||
List<String> examOrder = new ArrayList<>();
|
||||
for (GroupRow group : groupsBySense.getOrDefault(sense.senseId(), List.of())) {
|
||||
String key = group.senseId() + ":" + group.examId();
|
||||
examOrder.add(key);
|
||||
List<MemberItem> members = membersByGroup.getOrDefault(key, List.of()).stream()
|
||||
.limit(MEMBER_LIMIT)
|
||||
.map(member -> new MemberItem(member.wordId(), member.word(), member.position()))
|
||||
.toList();
|
||||
boolean truncated = membersByGroup.getOrDefault(key, List.of()).size() > MEMBER_LIMIT;
|
||||
groups.add(new GroupItem(group.examId(), group.examName(), group.canonicalWordId(),
|
||||
group.canonicalWord(), group.memberCount(), members, truncated));
|
||||
}
|
||||
for (String key : examOrder) {
|
||||
List<AntonymRow> rows = antonymsByGroup.getOrDefault(key, List.of());
|
||||
if (rows.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
AntonymRow first = rows.get(0);
|
||||
List<MemberItem> words = rows.stream()
|
||||
.map(row -> new MemberItem(row.wordId(), row.word(), row.position()))
|
||||
.toList();
|
||||
antonyms.add(new AntonymItem(first.examId(), first.examName(), words));
|
||||
}
|
||||
if (groups.isEmpty() && antonyms.isEmpty()) {
|
||||
senseItems.add(new SenseItem(sense.senseId(), sense.partOfSpeech(), sense.glossZh(),
|
||||
List.of(), List.of()));
|
||||
} else {
|
||||
senseItems.add(new SenseItem(sense.senseId(), sense.partOfSpeech(), sense.glossZh(),
|
||||
groups, antonyms));
|
||||
}
|
||||
}
|
||||
return new WordDetail(word.wordId(), word.word(), senseItems);
|
||||
}
|
||||
|
||||
public List<SizeBucket> groupSizeDistribution() {
|
||||
var rows = synonymMapper.groupSizeDistribution();
|
||||
long total = rows.stream().mapToLong(row -> row.count()).sum();
|
||||
List<SizeBucket> buckets = new ArrayList<>(rows.size());
|
||||
for (var row : rows) {
|
||||
double pct = total == 0 ? 0 : Math.round(row.count() * 1000.0 / total) / 10.0;
|
||||
buckets.add(new SizeBucket(row.label(), row.count(), pct));
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
logging:
|
||||
level:
|
||||
com.wordmarket.admin: DEBUG
|
||||
org.springframework.web: INFO
|
||||
org.mybatis: INFO
|
||||
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
@@ -0,0 +1,28 @@
|
||||
# 复制为 application-local.yml,或直接通过环境变量注入。
|
||||
# 仓库中不得出现真实凭据。
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://s1.void01.com:3306/word_market?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&connectTimeout=10000&socketTimeout=30000
|
||||
username: your_read_only_user
|
||||
password: your_password
|
||||
|
||||
admin:
|
||||
username: admin
|
||||
# 使用 BCrypt 哈希,例如:
|
||||
# htpasswd -bnBC 10 "" 'your-password' | tr -d ':\n'
|
||||
password-hash: $2a$10$replace_with_a_real_bcrypt_hash
|
||||
jwt-secret: replace_with_a_random_secret_at_least_32_characters
|
||||
token-ttl-hours: 8
|
||||
|
||||
app:
|
||||
cors:
|
||||
allowed-origins: http://localhost:5173,http://127.0.0.1:5173
|
||||
cover-base-url: https://static.beingfine.cn
|
||||
cache:
|
||||
ttl-minutes: 10
|
||||
maximum-size: 200
|
||||
quality:
|
||||
known-missing-zpk-keys: 0_53785_101_1775241011
|
||||
@@ -0,0 +1,53 @@
|
||||
server:
|
||||
port: ${SERVER_PORT:8080}
|
||||
shutdown: graceful
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: word-market-admin
|
||||
profiles:
|
||||
default: dev
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:mysql://s1.void01.com:3306/word_market?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&connectTimeout=10000&socketTimeout=30000}
|
||||
username: ${DB_USERNAME:}
|
||||
password: ${DB_PASSWORD:}
|
||||
hikari:
|
||||
read-only: true
|
||||
maximum-pool-size: ${DB_POOL_SIZE:15}
|
||||
minimum-idle: 2
|
||||
connection-timeout: 10000
|
||||
validation-timeout: 5000
|
||||
connection-init-sql: SET NAMES utf8mb4
|
||||
jackson:
|
||||
time-zone: Asia/Shanghai
|
||||
mvc:
|
||||
problemdetails:
|
||||
enabled: false
|
||||
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
default-fetch-size: 100
|
||||
global-config:
|
||||
banner: false
|
||||
|
||||
admin:
|
||||
username: ${ADMIN_USERNAME:}
|
||||
password-hash: ${ADMIN_PASSWORD_HASH:}
|
||||
jwt-secret: ${JWT_SECRET:}
|
||||
token-ttl-hours: ${ADMIN_TOKEN_TTL_HOURS:8}
|
||||
|
||||
app:
|
||||
cors:
|
||||
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://127.0.0.1:5173}
|
||||
cover-base-url: ${COVER_BASE_URL:https://static.beingfine.cn}
|
||||
cache:
|
||||
ttl-minutes: ${CACHE_TTL_MINUTES:10}
|
||||
maximum-size: ${CACHE_MAXIMUM_SIZE:200}
|
||||
quality:
|
||||
known-missing-zpk-keys: ${KNOWN_MISSING_ZPK_KEYS:0_53785_101_1775241011}
|
||||
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
com.wordmarket.admin: INFO
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.wordmarket.admin.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class PagesTest {
|
||||
|
||||
@Test
|
||||
void normalizesPageAndSize() {
|
||||
assertThat(Pages.page(null)).isEqualTo(1);
|
||||
assertThat(Pages.page(0)).isEqualTo(1);
|
||||
assertThat(Pages.page(-3)).isEqualTo(1);
|
||||
assertThat(Pages.page(4)).isEqualTo(4);
|
||||
|
||||
assertThat(Pages.size(null)).isEqualTo(20);
|
||||
assertThat(Pages.size(0)).isEqualTo(20);
|
||||
assertThat(Pages.size(500)).isEqualTo(100);
|
||||
assertThat(Pages.size(50)).isEqualTo(50);
|
||||
}
|
||||
|
||||
@Test
|
||||
void computesOffset() {
|
||||
assertThat(Pages.offset(1, 20)).isZero();
|
||||
assertThat(Pages.offset(3, 20)).isEqualTo(40);
|
||||
assertThat(Pages.offset(Integer.MAX_VALUE, 100)).isEqualTo(Integer.MAX_VALUE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class AggregateCacheTest {
|
||||
|
||||
private final Cache<String, Object> cache = Caffeine.newBuilder().maximumSize(10).build();
|
||||
private final AggregateCache aggregateCache = new AggregateCache(cache);
|
||||
|
||||
@Test
|
||||
void cachesUntilRefresh() {
|
||||
AtomicInteger loads = new AtomicInteger();
|
||||
String first = aggregateCache.get("k", false, () -> "v" + loads.incrementAndGet());
|
||||
String second = aggregateCache.get("k", false, () -> "v" + loads.incrementAndGet());
|
||||
assertThat(first).isEqualTo("v1");
|
||||
assertThat(second).isEqualTo("v1");
|
||||
assertThat(loads.get()).isEqualTo(1);
|
||||
|
||||
String refreshed = aggregateCache.get("k", true, () -> "v" + loads.incrementAndGet());
|
||||
assertThat(refreshed).isEqualTo("v2");
|
||||
assertThat(loads.get()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.config.AdminProperties;
|
||||
import com.wordmarket.admin.dto.AuthDtos.LoginRequest;
|
||||
import com.wordmarket.admin.dto.AuthDtos.LoginResponse;
|
||||
import com.wordmarket.admin.security.JwtService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuthServiceTest {
|
||||
|
||||
private final AdminProperties properties = new AdminProperties();
|
||||
private final PasswordEncoder passwordEncoder = mock(PasswordEncoder.class);
|
||||
private final JwtService jwtService = mock(JwtService.class);
|
||||
private AuthService authService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
properties.setUsername("admin");
|
||||
properties.setPasswordHash("hash");
|
||||
properties.setJwtSecret("0123456789012345678901234567890123456789");
|
||||
authService = new AuthService(properties, passwordEncoder, jwtService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void issuesTokenForValidCredentials() {
|
||||
when(passwordEncoder.matches("secret", "hash")).thenReturn(true);
|
||||
when(jwtService.issue("admin")).thenReturn(
|
||||
new JwtService.IssuedToken("token", Instant.parse("2030-01-01T00:00:00Z")));
|
||||
|
||||
LoginResponse response = authService.login(new LoginRequest("admin", "secret"));
|
||||
|
||||
assertThat(response.token()).isEqualTo("token");
|
||||
assertThat(response.username()).isEqualTo("admin");
|
||||
assertThat(response.expiresAt()).isEqualTo("2030-01-01T00:00:00Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWrongCredentials() {
|
||||
when(passwordEncoder.matches("bad", "hash")).thenReturn(false);
|
||||
|
||||
assertThatThrownBy(() -> authService.login(new LoginRequest("admin", "bad")))
|
||||
.isInstanceOf(BizException.class)
|
||||
.satisfies(error -> assertThat(((BizException) error).getStatus())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWrongUsername() {
|
||||
when(passwordEncoder.matches("secret", "hash")).thenReturn(true);
|
||||
|
||||
assertThatThrownBy(() -> authService.login(new LoginRequest("other", "secret")))
|
||||
.isInstanceOf(BizException.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.BizException;
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookDetailRow;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookEntryItem;
|
||||
import com.wordmarket.admin.dto.BookDtos.BookListItem;
|
||||
import com.wordmarket.admin.mapper.BookMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class BookServiceTest {
|
||||
|
||||
private final BookMapper bookMapper = mock(BookMapper.class);
|
||||
private final BookService bookService = new BookService(bookMapper);
|
||||
|
||||
@Test
|
||||
void detailReturnsNotFoundWhenMissing() {
|
||||
when(bookMapper.findBook(99L)).thenReturn(null);
|
||||
|
||||
assertThatThrownBy(() -> bookService.detail(99L))
|
||||
.isInstanceOf(BizException.class)
|
||||
.satisfies(error -> assertThat(((BizException) error).getStatus())
|
||||
.isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listClampsPageAndSize() {
|
||||
when(bookMapper.countBooks(isNull(), isNull(), isNull())).thenReturn(0L);
|
||||
when(bookMapper.listBooks(isNull(), isNull(), isNull(), eq(0), eq(100)))
|
||||
.thenReturn(List.<BookListItem>of());
|
||||
|
||||
PageResult<BookListItem> result = bookService.list(0, 500, null, null, null);
|
||||
|
||||
assertThat(result.page()).isEqualTo(1);
|
||||
assertThat(result.size()).isEqualTo(100);
|
||||
assertThat(result.items()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesClampPaginationAndVerifyBook() {
|
||||
when(bookMapper.findBook(3L)).thenReturn(new BookDetailRow("3", "CET6", "六级", null, "4",
|
||||
"六级", 100L, 90L, 1, 3, null, null, true, 0L, null));
|
||||
when(bookMapper.countBookEntries(3L, null)).thenReturn(0L);
|
||||
when(bookMapper.listBookEntries(eq(3L), isNull(), eq(0), eq(100)))
|
||||
.thenReturn(List.<BookEntryItem>of());
|
||||
|
||||
PageResult<BookEntryItem> result = bookService.entries(3L, 0, 500, null);
|
||||
|
||||
assertThat(result.page()).isEqualTo(1);
|
||||
assertThat(result.size()).isEqualTo(100);
|
||||
assertThat(result.total()).isZero();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.wordmarket.admin.service;
|
||||
|
||||
import com.wordmarket.admin.common.PageResult;
|
||||
import com.wordmarket.admin.dto.EntryDtos.EntryDetail;
|
||||
import com.wordmarket.admin.dto.EntryDtos.ExampleGroupItem;
|
||||
import com.wordmarket.admin.dto.EntryDtos.SenseItem;
|
||||
import com.wordmarket.admin.mapper.EntryMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EntryServiceTest {
|
||||
|
||||
private final EntryMapper entryMapper = mock(EntryMapper.class);
|
||||
private final EntryService entryService = new EntryService(entryMapper);
|
||||
|
||||
private EntryDetail detail() {
|
||||
return new EntryDetail("1", "word", "word", null, null, null, "2.0", null, null,
|
||||
0, false, "key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptySensesAndExamples() {
|
||||
when(entryMapper.findEntry(1L)).thenReturn(detail());
|
||||
when(entryMapper.listSenses(1L)).thenReturn(List.of());
|
||||
when(entryMapper.countExampleGroups(1L)).thenReturn(0L);
|
||||
when(entryMapper.listExampleGroups(1L, 0, 5)).thenReturn(List.of());
|
||||
|
||||
List<SenseItem> senses = entryService.senses(1L);
|
||||
PageResult<ExampleGroupItem> examples = entryService.examples(1L, 1, 5);
|
||||
|
||||
assertThat(senses).isEmpty();
|
||||
assertThat(examples.items()).isEmpty();
|
||||
assertThat(examples.total()).isZero();
|
||||
assertThat(examples.page()).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user