Compare commits
50
Commits
7baaeddf26
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2904e59e71 | ||
|
|
a5c9357a24 | ||
|
|
12c28963f5 | ||
|
|
32cac38a0e | ||
|
|
a706621786 | ||
|
|
64eadf1446 | ||
|
|
2fee329002 | ||
|
|
9b2833dfd3 | ||
|
|
af0bf7f90e | ||
|
|
a36276051d | ||
|
|
3df66c2f4c | ||
|
|
32ada4c2bf | ||
|
|
eba7d400e1 | ||
|
|
3faeba0589 | ||
|
|
8a5a381b44 | ||
|
|
afd8d00752 | ||
|
|
958de5ef22 | ||
|
|
f2103f6604 | ||
|
|
0d4d510aee | ||
|
|
4d796089a0 | ||
|
|
f71498339c | ||
|
|
e4fe82283c | ||
|
|
26102332ac | ||
|
|
aa5954ef6a | ||
|
|
963bf5c0da | ||
|
|
a71d2701d1 | ||
|
|
025fbe73f0 | ||
|
|
0d161f318f | ||
|
|
2eac1fe31d | ||
|
|
09b0f89e8d | ||
|
|
8fb1f52777 | ||
|
|
44b7abcd0f | ||
|
|
181b338780 | ||
|
|
657190d5a8 | ||
|
|
3e2d6a06d9 | ||
|
|
fc9e429187 | ||
|
|
5d139783c9 | ||
|
|
ddd2406f32 | ||
|
|
272aa62434 | ||
|
|
a41ab18636 | ||
|
|
8999ff395d | ||
|
|
229f1d0198 | ||
|
|
2dadca6288 | ||
|
|
2cf8f9a1c3 | ||
|
|
d9a1670a72 | ||
|
|
5ff4626b33 | ||
|
|
6bbde0b100 | ||
|
|
884324b8fd | ||
|
|
6abb09e5c2 | ||
|
|
8b37e23951 |
No files matched your search
@@ -0,0 +1,25 @@
|
|||||||
|
# Author: fruit.com.cn
|
||||||
|
# FruitServer 后端 CI:编译 + 测试门禁
|
||||||
|
name: backend-ci
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [develop, main]
|
||||||
|
pull_request:
|
||||||
|
branches: [develop, main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
cache: maven
|
||||||
|
- name: 编译 + 单测
|
||||||
|
run: mvn -B -T 1C test -DfailIfNoTests=false
|
||||||
|
- name: 打包(跳过测试)
|
||||||
|
if: success()
|
||||||
|
run: mvn -B package -DskipTests -q
|
||||||
+16
@@ -19,3 +19,19 @@ data/uploads/*
|
|||||||
|
|
||||||
# 部署用的真实环境变量(含密钥),只提交 .env.example
|
# 部署用的真实环境变量(含密钥),只提交 .env.example
|
||||||
.env
|
.env
|
||||||
|
*.secrets.env
|
||||||
|
dump.rdb
|
||||||
|
|
||||||
|
# 看门狗飞书告警 Webhook,只存在于部署机
|
||||||
|
deploy/feishu-webhook.txt
|
||||||
|
|
||||||
|
# SSL 证书与私钥(.crt/.cer/.pem/.key/.p12/.jks)—— 部署机本地文件,禁止入库
|
||||||
|
*.crt
|
||||||
|
*.cer
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
*.jks
|
||||||
|
|
||||||
|
# 部署用 nginx 配置目录(挂载卷的本地配置,随环境而异)
|
||||||
|
nginx/
|
||||||
+15
-1
@@ -15,6 +15,20 @@
|
|||||||
FROM maven:3.9-eclipse-temurin-21 AS build
|
FROM maven:3.9-eclipse-temurin-21 AS build
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
|
# Maven Central 在国内网络下拉依赖不稳定(构建时曾出现 maven-filtering:3.3.1 解析失败),
|
||||||
|
# 构建阶段固定走阿里云 central 镜像;其它仓库仍直连。
|
||||||
|
RUN mkdir -p /root/.m2 \
|
||||||
|
&& printf '%s\n' \
|
||||||
|
'<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0">' \
|
||||||
|
' <mirrors>' \
|
||||||
|
' <mirror>' \
|
||||||
|
' <id>aliyun-central</id>' \
|
||||||
|
' <mirrorOf>central</mirrorOf>' \
|
||||||
|
' <url>https://maven.aliyun.com/repository/central</url>' \
|
||||||
|
' </mirror>' \
|
||||||
|
' </mirrors>' \
|
||||||
|
'</settings>' > /root/.m2/settings.xml
|
||||||
|
|
||||||
# 先只拷各模块 pom 再拉依赖:依赖层可复用,改业务代码不会重新下载依赖
|
# 先只拷各模块 pom 再拉依赖:依赖层可复用,改业务代码不会重新下载依赖
|
||||||
COPY pom.xml .
|
COPY pom.xml .
|
||||||
COPY fruitshorts-common/pom.xml fruitshorts-common/
|
COPY fruitshorts-common/pom.xml fruitshorts-common/
|
||||||
@@ -30,7 +44,7 @@ COPY fruitshorts-module-creator/pom.xml fruitshorts-module-creator/
|
|||||||
COPY fruitshorts-admin-api/pom.xml fruitshorts-admin-api/
|
COPY fruitshorts-admin-api/pom.xml fruitshorts-admin-api/
|
||||||
COPY fruitshorts-app-api/pom.xml fruitshorts-app-api/
|
COPY fruitshorts-app-api/pom.xml fruitshorts-app-api/
|
||||||
COPY fruitshorts-transcode-worker/pom.xml fruitshorts-transcode-worker/
|
COPY fruitshorts-transcode-worker/pom.xml fruitshorts-transcode-worker/
|
||||||
RUN mvn -B -q -DskipTests dependency:go-offline || true
|
RUN mvn -B -q -DskipTests dependency:go-offline
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
ARG MODULE=fruitshorts-app-api
|
ARG MODULE=fruitshorts-app-api
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ java -jar fruitshorts-app-api/target/fruitshorts-app-api-1.0.0-SNAPSHOT.jar
|
|||||||
|
|
||||||
## 第一阶段实现进度
|
## 第一阶段实现进度
|
||||||
|
|
||||||
> 最后更新:2026-10-16(后端 `develop` 分支 `4418a84`)。**未完成清单见文末「尚未完成」。**
|
> 最后更新:2026-10-24(拉取 `develop` 最新代码后)。**未完成清单见文末「尚未完成」。**
|
||||||
|
|
||||||
| 模块 | 状态 | 说明 |
|
| 模块 | 状态 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -200,11 +200,11 @@ java -jar fruitshorts-app-api/target/fruitshorts-app-api-1.0.0-SNAPSHOT.jar
|
|||||||
| 03 内容发现与详情 | 已实现 | 首页/发现/分类/详情;内容分级、可播区域、版权窗口、标签字段 |
|
| 03 内容发现与详情 | 已实现 | 首页/发现/分类/详情;内容分级、可播区域、版权窗口、标签字段 |
|
||||||
| 04 播放器与播放控制 | 已实现 | 播放票据 + 签名地址 + 进度;多码率 HLS 由转码 worker 产出(见 10) |
|
| 04 播放器与播放控制 | 已实现 | 播放票据 + 签名地址 + 进度;多码率 HLS 由转码 worker 产出(见 10) |
|
||||||
| 05 记录、收藏与下载 | 已实现 | 进度、观看流水、收藏、离线下载授权与任务 |
|
| 05 记录、收藏与下载 | 已实现 | 进度、观看流水、收藏、离线下载授权与任务 |
|
||||||
| 06 评论、点赞与分享 | 已实现 | 评论(游标翻页/审核/删除)、点赞、举报、敏感词;**分享埋点待 C3** |
|
| 06 评论、点赞与分享 | 已实现 | 评论(游标翻页/审核/删除)、点赞、举报、敏感词、分享 |
|
||||||
| 07 创作者中心 | 已实现 | **在后台管理(Web 端 `ReelShortWeb`)**:工作台、内容编辑、分片上传与断点续传、提交审核与上下架、分集收费与试看、数据看板;不含提现/结算。**App 客户端不提供创作者中心**(口径 2026-10-16) |
|
| 07 创作者中心 | 已实现 | **在后台管理(Web 端 `ReelShortWeb`)**:工作台、内容编辑、分片上传与断点续传、提交审核与上下架、分集收费与试看、数据看板;不含提现/结算。**App 客户端不提供创作者中心**(口径 2026-10-16) |
|
||||||
| 08 平台运营后台 | 已实现 | 用户管理、内容治理、订单与权益、创作者与内容审核、数据看板 + 四个后台页面 |
|
| 08 平台运营后台 | 已实现 | 用户管理、内容治理、订单与权益、创作者与内容审核、数据看板 + 四个后台页面 |
|
||||||
| 09 分集收费与支付 | 部分 | **Google Play 票据校验闭环已实现**(校验→建单→发权益、幂等与防重放、恢复购买、退款拒付回收、对账);**Apple IAP 只留端口未实现**(印尼 iOS 占比低,文档口径为"预留") |
|
| 09 分集收费与支付 | 部分 | **Google Play 票据校验闭环已实现**(校验→建单→发权益、幂等与防重放、恢复购买、退款拒付回收、对账);**Apple IAP 只留端口未实现**(印尼 iOS 占比低,文档口径为"预留") |
|
||||||
| 10 质量、数据与上线 | 部分 | **转码 worker(C1)已实现**;**Redis 缓存与限流(C2)、埋点(C3)、压测未做** |
|
| 10 质量、数据与上线 | 部分 | **转码 worker(C1)、Redis 缓存与限流(C2)、埋点(C3)均已实现**;**压测未做** |
|
||||||
|
|
||||||
### 已完成批次(按提交顺序)
|
### 已完成批次(按提交顺序)
|
||||||
|
|
||||||
@@ -426,18 +426,18 @@ public Result<Long> create(@Valid @RequestBody DramaCategorySaveReqVO req) { ...
|
|||||||
|
|
||||||
## 尚未完成
|
## 尚未完成
|
||||||
|
|
||||||
> 最后更新:2026-10-16。完成后请同步本表与 [docs/api-phase1.md](docs/api-phase1.md)。
|
> 最后更新:2026-10-24。完成后请同步本表与 [docs/api-phase1.md](docs/api-phase1.md)。
|
||||||
|
|
||||||
### 一、后端研发(剩余)
|
### 一、后端研发(剩余)
|
||||||
|
|
||||||
|
> 已完成的项(不再列出):**C2 Redis 缓存与限流**(`framework/redis` 的 `RedisService` + `RateLimit` 切面)、**C3 埋点**(客户端埋点 SDK),均于 10-20 ~ 10-23 落地。
|
||||||
|
|
||||||
| # | 项 | 内容 | 依据 |
|
| # | 项 | 内容 | 依据 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| 1 | **C2 Redis 缓存与限流** | 首页/发现/分类等热点接口缓存(Cache-Aside)+ 验证码/注册/登录限流;生产 Redis 规格 `4C16G 主从 2~3 哨兵` | 任务清单 C2、`17-风险评估` R-10、`10-安全方案` §三 |
|
| 1 | **Apple IAP 票据校验** | 目前只留端口与枚举,未做真实校验(印尼 iOS 占比低,文档口径为"预留") | `api-phase1` §1.8 |
|
||||||
| 2 | **C3 埋点** | 播放/支付/转化事件 + 数据字典对齐(含 06 的分享埋点) | 任务清单 C3、`api-phase1` §3 |
|
| 2 | **压测** | 目标 `P95 < 50ms`(预热后);容量口径文档里有两套("1 万并发"与"2 万并发 + 3000 QPS"),需定稿 | `09-测试计划` §五、`13/14-容量` |
|
||||||
| 3 | **Apple IAP 票据校验** | 目前只留端口与枚举,未做真实校验(印尼 iOS 占比低,文档口径为"预留") | `api-phase1` §1.8 |
|
| 3 | **对账数据源** | 结算金额/手续费/税只能从 Play Console 财务报告取(需报表权限);当前 `storeAmountSum` 恒为 `null` + `notes` 说明 | B1-2 待确认 |
|
||||||
| 4 | **压测** | 目标 `P95 < 50ms`(预热后);容量口径文档里有两套("1 万并发"与"2 万并发 + 3000 QPS"),需定稿 | `09-测试计划` §五、`13/14-容量` |
|
| 4 | **退款口径完善** | 部分退款按比例回收、退款实时性(当前由每日对账 + 手动驱动,未接 RTDN 推送) | B1-2 待确认 |
|
||||||
| 5 | **对账数据源** | 结算金额/手续费/税只能从 Play Console 财务报告取(需报表权限);当前 `storeAmountSum` 恒为 `null` + `notes` 说明 | B1-2 待确认 |
|
|
||||||
| 6 | **退款口径完善** | 部分退款按比例回收、退款实时性(当前由每日对账 + 手动驱动,未接 RTDN 推送) | B1-2 待确认 |
|
|
||||||
|
|
||||||
### 二、上线前必补(P0 / Go-No-Go:非研发,但阻塞上线)
|
### 二、上线前必补(P0 / Go-No-Go:非研发,但阻塞上线)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-16"?>
|
||||||
|
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||||
|
<RegistrationInfo>
|
||||||
|
<Description>FruitShorts backend watchdog: health check every 2 minutes and restart unhealthy services.</Description>
|
||||||
|
</RegistrationInfo>
|
||||||
|
<Principals>
|
||||||
|
<Principal id="Author">
|
||||||
|
<UserId>S-1-5-18</UserId>
|
||||||
|
<RunLevel>HighestAvailable</RunLevel>
|
||||||
|
</Principal>
|
||||||
|
</Principals>
|
||||||
|
<Settings>
|
||||||
|
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||||
|
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
||||||
|
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
||||||
|
<StartWhenAvailable>true</StartWhenAvailable>
|
||||||
|
<ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
|
||||||
|
</Settings>
|
||||||
|
<Triggers>
|
||||||
|
<!-- BootTrigger 上挂 <Repetition> 在 Windows 计划任务里不生效(导入后 Next Run Time 为 N/A,
|
||||||
|
实际只在开机跑一次)。改成 TimeTrigger + 无限重复,配合 StartWhenAvailable
|
||||||
|
保证开机后若错过也会立即补跑;这样才真正做到每 2 分钟巡检一次。 -->
|
||||||
|
<TimeTrigger>
|
||||||
|
<StartBoundary>2026-01-01T00:00:00</StartBoundary>
|
||||||
|
<Repetition>
|
||||||
|
<Interval>PT2M</Interval>
|
||||||
|
<Duration>P3650D</Duration>
|
||||||
|
<StopAtDurationEnd>false</StopAtDurationEnd>
|
||||||
|
</Repetition>
|
||||||
|
</TimeTrigger>
|
||||||
|
</Triggers>
|
||||||
|
<Actions Context="Author">
|
||||||
|
<Exec>
|
||||||
|
<Command>powershell.exe</Command>
|
||||||
|
<Arguments>-NoProfile -ExecutionPolicy Bypass -File "C:\Users\Administrator\Desktop\ReelShorts\FruitServer\deploy\watchdog.ps1" -ComposeDir "C:\Users\Administrator\Desktop\ReelShorts\FruitServer" -LogDir "C:\Users\Administrator\Desktop\ReelShorts\FruitServer\logs"</Arguments>
|
||||||
|
</Exec>
|
||||||
|
</Actions>
|
||||||
|
</Task>
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
# Author: fruit.com.cn
|
||||||
|
#
|
||||||
|
# 服务看门狗:每 2 分钟检查一次,挂了自动拉起,连续失败发飞书告警。
|
||||||
|
# 注册为 Windows 计划任务后无人值守运行。
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$ComposeDir = "C:\FruitServer",
|
||||||
|
[string]$LogDir = "C:\FruitServer\logs",
|
||||||
|
[string]$FeishuWebhook = "",
|
||||||
|
[int]$MaxRestarts = 3,
|
||||||
|
[string]$FrontendTask = "FruitShorts-Web-3005"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Continue"
|
||||||
|
$ComposeFile = Join-Path $ComposeDir "docker-compose.yml"
|
||||||
|
$LogFile = Join-Path $LogDir "watchdog-$(Get-Date -Format 'yyyy-MM-dd').log"
|
||||||
|
# 连续失败计数落盘文件:计划任务每 2 分钟起一个新进程,计数只放进程内永远累积不到
|
||||||
|
# $MaxRestarts,告警会静默哑火。
|
||||||
|
$StateFile = Join-Path $LogDir "watchdog-state.json"
|
||||||
|
|
||||||
|
function Write-Log($msg) {
|
||||||
|
$line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $msg"
|
||||||
|
Add-Content -Path $LogFile -Value $line -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
function Send-Alert($title, $msg) {
|
||||||
|
if (-not $FeishuWebhook) { return }
|
||||||
|
$json = @{
|
||||||
|
msg_type = "text"
|
||||||
|
content = @{ text = "[$title] $msg" }
|
||||||
|
} | ConvertTo-Json -Depth 3
|
||||||
|
try {
|
||||||
|
# PS5 的 Invoke-RestMethod 对字符串 body 默认按 Latin-1 编码,中文会变成 ???,
|
||||||
|
# 必须手动转 UTF-8 字节数组发送
|
||||||
|
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
|
||||||
|
Invoke-RestMethod -Uri $FeishuWebhook -Method Post -Body $bytes -ContentType "application/json; charset=utf-8" -TimeoutSec 10
|
||||||
|
} catch {
|
||||||
|
Write-Log "飞书告警发送失败: $_"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 连续失败计数的读写:JSON 落盘,跨进程保留
|
||||||
|
function Import-FailCounts {
|
||||||
|
$counts = @{}
|
||||||
|
if (-not (Test-Path $StateFile)) { return $counts }
|
||||||
|
try {
|
||||||
|
$saved = Get-Content -Path $StateFile -Raw | ConvertFrom-Json
|
||||||
|
foreach ($prop in $saved.PSObject.Properties) {
|
||||||
|
$counts[$prop.Name] = [int]$prop.Value
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
Write-Log "看门狗计数文件解析失败,各服务按 0 重新计数: $_"
|
||||||
|
}
|
||||||
|
return $counts
|
||||||
|
}
|
||||||
|
|
||||||
|
function Export-FailCounts($counts) {
|
||||||
|
try {
|
||||||
|
$counts | ConvertTo-Json | Set-Content -Path $StateFile -Encoding UTF8
|
||||||
|
} catch {
|
||||||
|
Write-Log "看门狗计数文件写入失败: $_"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-Docker {
|
||||||
|
docker info --format "{{.ServerVersion}}" 2>$null | Out-Null
|
||||||
|
return ($LASTEXITCODE -eq 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-Http([string]$url) {
|
||||||
|
try {
|
||||||
|
$response = Invoke-WebRequest -Uri $url -TimeoutSec 10 -UseBasicParsing -ErrorAction Stop
|
||||||
|
return ($response.StatusCode -ge 200 -and $response.StatusCode -lt 400)
|
||||||
|
} catch {
|
||||||
|
return $false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-Container([string]$container) {
|
||||||
|
$status = docker inspect -f "{{.State.Status}}" $container 2>$null
|
||||||
|
return ($status -eq "running")
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-Compose([string[]]$composeArgs) {
|
||||||
|
& docker compose -f $ComposeFile @composeArgs 2>&1 | Out-Null
|
||||||
|
return $LASTEXITCODE
|
||||||
|
}
|
||||||
|
|
||||||
|
# 确保日志目录存在
|
||||||
|
New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
|
||||||
|
|
||||||
|
# 告警 Webhook:命令行参数 > 环境变量 > deploy 目录下的 feishu-webhook.txt。
|
||||||
|
# 计划任务注册命令里不写密钥(密钥不该进版本库),由部署机本地放文件或配环境变量。
|
||||||
|
if (-not $FeishuWebhook) { $FeishuWebhook = $env:FRUITSHORTS_FEISHU_WEBHOOK }
|
||||||
|
if (-not $FeishuWebhook) {
|
||||||
|
$webhookFile = Join-Path $PSScriptRoot "feishu-webhook.txt"
|
||||||
|
if (Test-Path $webhookFile) {
|
||||||
|
$FeishuWebhook = (Get-Content -Path $webhookFile -Raw -ErrorAction SilentlyContinue)
|
||||||
|
if ($FeishuWebhook) { $FeishuWebhook = $FeishuWebhook.Trim() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $FeishuWebhook) {
|
||||||
|
Write-Log "未配置飞书 Webhook(参数/环境变量/feishu-webhook.txt 均为空),告警只写本地日志"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Docker Desktop 登录后偶尔尚未就绪,先等待并尝试拉起。
|
||||||
|
# 注意:本脚本以 SYSTEM 身份运行,绝不能直接 Start-Process Docker Desktop.exe。
|
||||||
|
# WSL 不支持本地系统账户运行(WSL_E_LOCAL_SYSTEM_NOT_SUPPORTED),
|
||||||
|
# 以 SYSTEM 启动会把 docker-desktop 发行版搞成僵死状态(VHD 已挂载无法终止),
|
||||||
|
# 结果是登录用户会话里的 Docker Desktop 也永远起不来。
|
||||||
|
# 因此改为触发以登录用户身份运行的 FruitShorts-DockerDesktop 计划任务。
|
||||||
|
if (-not (Test-Docker)) {
|
||||||
|
Write-Log "Docker 未就绪,尝试通过用户会话启动 Docker Desktop"
|
||||||
|
$desktopTask = "FruitShorts-DockerDesktop"
|
||||||
|
try {
|
||||||
|
# Docker Desktop.exe 是任务进程树的一部分,GUI 活着时任务一直是 Running,
|
||||||
|
# 直接 Start-ScheduledTask 会被 IgnoreNew 忽略,所以先结束旧实例再拉起。
|
||||||
|
$t = Get-ScheduledTask -TaskName $desktopTask -ErrorAction Stop
|
||||||
|
if ($t.State -eq "Running") {
|
||||||
|
Stop-ScheduledTask -TaskName $desktopTask -ErrorAction SilentlyContinue
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
}
|
||||||
|
Start-ScheduledTask -TaskName $desktopTask -ErrorAction Stop
|
||||||
|
} catch {
|
||||||
|
Write-Log "触发 Docker Desktop 启动任务失败: $_"
|
||||||
|
}
|
||||||
|
|
||||||
|
for ($i = 0; $i -lt 18; $i++) {
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
if (Test-Docker) { break }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Docker)) {
|
||||||
|
Write-Log "Docker 在 90 秒内未就绪,跳过本轮检查"
|
||||||
|
Send-Alert "服务异常" "Docker Desktop 无法启动,请人工检查桌面机。"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 健康检查定义:名称 → 检查方式
|
||||||
|
$checks = @(
|
||||||
|
@{ Name = "app-api"; Type = "http"; Url = "http://127.0.0.1:8081/healthz"; Service = "app-api"; Container = "fruitshorts-app-api" },
|
||||||
|
@{ Name = "admin-api"; Type = "http"; Url = "http://127.0.0.1:8080/healthz"; Service = "admin-api"; Container = "fruitshorts-admin-api" },
|
||||||
|
@{ Name = "frontend"; Type = "frontend"; Url = "http://127.0.0.1:3005/dist-dev/" },
|
||||||
|
@{ Name = "Grafana"; Type = "http"; Url = "http://127.0.0.1:3000/api/health"; Service = "grafana"; Container = "fruitshorts-grafana" },
|
||||||
|
@{ Name = "PostgreSQL"; Type = "docker"; Service = "db"; Container = "fruitshorts-db" },
|
||||||
|
@{ Name = "Redis"; Type = "docker"; Service = "redis"; Container = "fruitshorts-redis" },
|
||||||
|
@{ Name = "Prometheus"; Type = "http"; Url = "http://127.0.0.1:9090/-/healthy"; Service = "prometheus"; Container = "fruitshorts-prometheus" }
|
||||||
|
)
|
||||||
|
|
||||||
|
# 跟踪每个服务的连续失败次数(跨进程从状态文件恢复)
|
||||||
|
$failCounts = Import-FailCounts
|
||||||
|
|
||||||
|
foreach ($check in $checks) {
|
||||||
|
$name = $check.Name
|
||||||
|
$healthy = $false
|
||||||
|
|
||||||
|
if ($check.Type -eq "http") {
|
||||||
|
$healthy = Test-Http $check.Url
|
||||||
|
} elseif ($check.Type -eq "frontend") {
|
||||||
|
$healthy = Test-Http $check.Url
|
||||||
|
} else {
|
||||||
|
$healthy = Test-Container $check.Container
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($healthy) {
|
||||||
|
if ($failCounts[$name] -gt 0) {
|
||||||
|
Write-Log "$name 恢复正常(此前连续失败 $($failCounts[$name]) 次)"
|
||||||
|
Send-Alert "服务恢复" "$name 已恢复正常"
|
||||||
|
}
|
||||||
|
$failCounts[$name] = 0
|
||||||
|
} else {
|
||||||
|
if ($null -eq $failCounts[$name]) {
|
||||||
|
$failCounts[$name] = 0
|
||||||
|
}
|
||||||
|
$failCounts[$name] = $failCounts[$name] + 1
|
||||||
|
$count = $failCounts[$name]
|
||||||
|
Write-Log "$name 不健康(第 $count 次)"
|
||||||
|
|
||||||
|
if ($check.Type -eq "frontend") {
|
||||||
|
Write-Log "$name 重启计划任务 $FrontendTask"
|
||||||
|
Stop-ScheduledTask -TaskName $FrontendTask -ErrorAction SilentlyContinue
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
Start-ScheduledTask -TaskName $FrontendTask -ErrorAction SilentlyContinue
|
||||||
|
Start-Sleep -Seconds 6
|
||||||
|
$healthy = Test-Http $check.Url
|
||||||
|
} elseif ($check.Type -eq "http") {
|
||||||
|
Write-Log "$name 重启 Compose 服务 $($check.Service)"
|
||||||
|
Invoke-Compose @("restart", $check.Service) | Out-Null
|
||||||
|
Start-Sleep -Seconds 12
|
||||||
|
$healthy = Test-Http $check.Url
|
||||||
|
|
||||||
|
if (-not $healthy) {
|
||||||
|
Write-Log "$name 重启后仍不健康,执行 compose up -d"
|
||||||
|
Invoke-Compose @("up", "-d", $check.Service) | Out-Null
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Log "$name 拉起容器 $($check.Container)"
|
||||||
|
docker start $check.Container 2>&1 | Out-Null
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
$healthy = Test-Container $check.Container
|
||||||
|
|
||||||
|
if (-not $healthy) {
|
||||||
|
Write-Log "$name 启动失败,执行 compose up -d"
|
||||||
|
Invoke-Compose @("up", "-d", $check.Service) | Out-Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 连续失败达到上限 → 告警。计数会跨进程累积,所以只在首次达阈值和
|
||||||
|
# 之后每 30 轮(约 1 小时)提醒一次,避免每 2 分钟刷屏。
|
||||||
|
if (-not $healthy -and $count -ge $MaxRestarts -and
|
||||||
|
($count -eq $MaxRestarts -or $count % 30 -eq 0)) {
|
||||||
|
Send-Alert "服务异常" "$name 已连续 $count 次不健康,已尝试重启。请人工介入检查。"
|
||||||
|
Write-Log "$name 连续 $count 次失败,已发告警"
|
||||||
|
} elseif ($healthy) {
|
||||||
|
Write-Log "$name 已自动恢复"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 磁盘检查:超过 85% 告警
|
||||||
|
$drive = (Get-PSDrive C -ErrorAction SilentlyContinue)
|
||||||
|
if ($drive) {
|
||||||
|
$pct = [math]::Round(($drive.Used / ($drive.Used + $drive.Free)) * 100)
|
||||||
|
if ($pct -gt 85) {
|
||||||
|
Write-Log "磁盘使用率 ${pct}%(超过 85%)"
|
||||||
|
Send-Alert "磁盘告警" "C 盘使用率 ${pct}%,请清理日志或扩容"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 本轮结果落盘,供下一轮(2 分钟后的新进程)继续累加
|
||||||
|
Export-FailCounts $failCounts
|
||||||
+41
-3
@@ -71,11 +71,16 @@ services:
|
|||||||
env_file: .env
|
env_file: .env
|
||||||
environment:
|
environment:
|
||||||
SERVER_PORT: "8081"
|
SERVER_PORT: "8081"
|
||||||
# 默认连编排里的 db;要连外部库就在 .env 里覆盖 DB_URL
|
# 默认连编排里的 db;要连外部库就在 .env 里覆盖 DB_URL。
|
||||||
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}}
|
# reWriteBatchedInserts=true:pgjdbc 把 JDBC 批内多条 INSERT 重写成多值
|
||||||
|
# INSERT,观看进度缓冲落库(watch:pg:dirty 消费任务)依赖它跑满吞吐。
|
||||||
|
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}?reWriteBatchedInserts=true}
|
||||||
# 限流/缓存用 Redis;容器内 127.0.0.1 是容器自身,必须指向编排里的 redis
|
# 限流/缓存用 Redis;容器内 127.0.0.1 是容器自身,必须指向编排里的 redis
|
||||||
REDIS_HOST: ${REDIS_HOST:-redis}
|
REDIS_HOST: ${REDIS_HOST:-redis}
|
||||||
REDIS_PORT: ${REDIS_PORT:-6379}
|
REDIS_PORT: ${REDIS_PORT:-6379}
|
||||||
|
# CORS:公网入口 nginx 把 SSL 跑在 80 端口上(腾讯云安全组只放 80),
|
||||||
|
# 浏览器 fetch 带 Origin 时端口不匹配会被 Spring CORS 拒(必须精确字符串匹配)。
|
||||||
|
CORS_ALLOWED_ORIGINS: "https://api.frostgiant.vip:80,https://api.frostgiant.vip,http://api.frostgiant.vip,https://39.162.50.99:8081,http://localhost:3005,http://127.0.0.1:3005,http://39.162.50.99:3007,http://192.168.31.250:3007"
|
||||||
ports:
|
ports:
|
||||||
- "8081:8081"
|
- "8081:8081"
|
||||||
volumes:
|
volumes:
|
||||||
@@ -106,7 +111,8 @@ services:
|
|||||||
SERVER_PORT: "8080"
|
SERVER_PORT: "8080"
|
||||||
SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE: "2GB"
|
SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE: "2GB"
|
||||||
SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE: "2GB"
|
SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE: "2GB"
|
||||||
CORS_ALLOWED_ORIGINS: "http://localhost:3005,http://127.0.0.1:3005,http://39.162.50.99:3005,http://192.168.31.250:3005"
|
# 浏览后台时 Origin 是实际访问地址,必须精确列全:本机、局域网、公网 IP、域名。
|
||||||
|
CORS_ALLOWED_ORIGINS: "http://localhost:3005,http://127.0.0.1:3005,http://39.162.50.99:3005,http://192.168.31.250:3005,https://api.frostgiant.vip,https://admin.frostgiant.vip"
|
||||||
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}}
|
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}}
|
||||||
# 管理端仅内网,页面上直接播放/下载裸媒资地址(不签播放签名),
|
# 管理端仅内网,页面上直接播放/下载裸媒资地址(不签播放签名),
|
||||||
# 因此这里不启用 /files/episode/** 的签名校验;公开的 app-api 仍保持开启。
|
# 因此这里不启用 /files/episode/** 的签名校验;公开的 app-api 仍保持开启。
|
||||||
@@ -197,9 +203,40 @@ services:
|
|||||||
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
|
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
|
||||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Grafana 管理员密码必填,见 .env.example}
|
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Grafana 管理员密码必填,见 .env.example}
|
||||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||||
|
# 新用户默认界面语言:简体中文
|
||||||
|
GF_USERS_LANGUAGE: "zh-Hans"
|
||||||
TZ: Asia/Shanghai
|
TZ: Asia/Shanghai
|
||||||
depends_on:
|
depends_on:
|
||||||
- prometheus
|
- prometheus
|
||||||
|
- loki
|
||||||
|
|
||||||
|
# ─────────── 日志(Loki + Promtail)───────────
|
||||||
|
# Loki:日志存储与查询引擎;Promtail:采集容器 stdout/stderr 推给 Loki。
|
||||||
|
# Grafana 里通过 Loki 数据源可直接搜索/过滤各容器的请求日志。
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:latest
|
||||||
|
container_name: fruitshorts-loki
|
||||||
|
restart: unless-stopped
|
||||||
|
command: -config.file=/etc/loki/local-config.yaml
|
||||||
|
volumes:
|
||||||
|
- ./loki-config.yml:/etc/loki/local-config.yaml:ro
|
||||||
|
- loki-data:/loki
|
||||||
|
expose:
|
||||||
|
- "3100"
|
||||||
|
# 镜像为 distroless(无 shell/wget),无法在容器内做 HTTP 探活;
|
||||||
|
# 靠 restart: unless-stopped 自动拉起,Grafana 数据源状态可反映可用性。
|
||||||
|
|
||||||
|
promtail:
|
||||||
|
image: grafana/promtail:latest
|
||||||
|
container_name: fruitshorts-promtail
|
||||||
|
restart: unless-stopped
|
||||||
|
command: -config.file=/etc/promtail/config.yml
|
||||||
|
volumes:
|
||||||
|
- ./promtail-config.yml:/etc/promtail/config.yml:ro
|
||||||
|
# 读取容器日志需要 Docker socket
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
depends_on:
|
||||||
|
- loki
|
||||||
|
|
||||||
# 黑盒探活:从外部探测接口可用性与耗时
|
# 黑盒探活:从外部探测接口可用性与耗时
|
||||||
blackbox:
|
blackbox:
|
||||||
@@ -227,3 +264,4 @@ volumes:
|
|||||||
redis-data:
|
redis-data:
|
||||||
prometheus-data:
|
prometheus-data:
|
||||||
grafana-data:
|
grafana-data:
|
||||||
|
loki-data:
|
||||||
+121
-7
@@ -115,6 +115,8 @@ POST /app/auth/register
|
|||||||
| 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) |
|
| 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) |
|
||||||
| 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) |
|
| 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) |
|
||||||
| 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 |
|
| 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 |
|
||||||
|
| 国家 / 语言 / 时区 / 币种 | 优先按客户端 IP(`X-Forwarded-For` / `X-Real-IP`,离线 ip2region)解析国家;内网或解析失败才用请求体 `countryCode`(ISO-2),最后兜底 `ID`。`language` / `timezone` / `currency` 随国家映射,不再写死 `id-ID` / `IDR` |
|
||||||
|
| 登录时修正国家 | `/app/auth/login`、`/app/auth/google` 会用 IP 重新解析国家并更新 `country_code` / `region_code`(历史账号下次登录即自愈);`language` / `timezone` / `currency` 只在仍是旧国家映射值时才同步,用户自己改过就保留 |
|
||||||
|
|
||||||
频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。
|
频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。
|
||||||
|
|
||||||
@@ -168,8 +170,9 @@ app.register.max-per-device-per-day
|
|||||||
| GET | `/app/home/feed` | 首页:轮播 + 分区,卡片带 `preview` 可播预览集与 `language` 语种 |
|
| GET | `/app/home/feed` | 首页:轮播 + 分区,卡片带 `preview` 可播预览集与 `language` 语种 |
|
||||||
| GET | `/app/discover/feed` | 发现页分区 |
|
| GET | `/app/discover/feed` | 发现页分区 |
|
||||||
| GET | `/app/feed?types=ANIME,LIVE&categoryId=7&cursor=&size=20` | 推荐流;支持内容类型与分类叠加过滤,游标翻页 |
|
| GET | `/app/feed?types=ANIME,LIVE&categoryId=7&cursor=&size=20` | 推荐流;支持内容类型与分类叠加过滤,游标翻页 |
|
||||||
| GET | `/app/categories` | 已启用首页分类。`name` 为中文,`locales` 为 `{zh,en,id}` |
|
| GET | `/app/categories` | 已启用首页分类。名称在 `locales`;另带 `code`、`layoutType`(`GRID` / `RANKING`)、`revision` |
|
||||||
| GET | `/app/categories/{id}/dramas?pageIndex=&pageSize=` | 分类下已上线短剧,分页。`pageIndex` 默认 1,`pageSize` 默认 20、最大 50 |
|
| GET | `/app/categories/{id}/dramas?pageIndex=&pageSize=` | 分类下已上线短剧,分页。`pageIndex` 默认 1,`pageSize` 默认 20、最大 50 |
|
||||||
|
| GET | `/app/categories/{id}/ranking` | 推荐榜快照;只接受 `layoutType=RANKING` 的已启用分类,按后台位置返回连续排名 |
|
||||||
| GET | `/app/drama-categories` | 已启用类型。`locales` 为 `{zh,en,id}` |
|
| GET | `/app/drama-categories` | 已启用类型。`locales` 为 `{zh,en,id}` |
|
||||||
| GET | `/app/tags` | 已启用标签。`locales` 为 `{zh,en,id}` |
|
| GET | `/app/tags` | 已启用标签。`locales` 为 `{zh,en,id}` |
|
||||||
| POST | `/app/dramas/page` | 全部短剧分页。请求体 `pageIndex`(默认 1)、`pageSize`(默认 20、最大 50)、`categoryIds`、`classificationIds`、`tagIds`。id 用 JSON 数组,不放查询串。同一组多选为或,组与组之间为且 |
|
| POST | `/app/dramas/page` | 全部短剧分页。请求体 `pageIndex`(默认 1)、`pageSize`(默认 20、最大 50)、`categoryIds`、`classificationIds`、`tagIds`。id 用 JSON 数组,不放查询串。同一组多选为或,组与组之间为且 |
|
||||||
@@ -203,6 +206,10 @@ app.register.max-per-device-per-day
|
|||||||
> 卡片文案只放语言表:`titleLocales`、`synopsisLocales`、`types`、`tagLocales`。
|
> 卡片文案只放语言表:`titleLocales`、`synopsisLocales`、`types`、`tagLocales`。
|
||||||
> `tagColor` 是标签背景色。中文取各表的 `zh`。
|
> `tagColor` 是标签背景色。中文取各表的 `zh`。
|
||||||
>
|
>
|
||||||
|
> `tagCode` 是标签语义码(如 `NEW_ARRIVAL`),来自 `content_tag.code`。
|
||||||
|
> 客户端按码判断板块(推荐页「上新」横滑),`tagLocales` 只用于展示;
|
||||||
|
> 码为空时客户端才退回按文案匹配。后台标签管理可配置该码。
|
||||||
|
>
|
||||||
> 卡片新增 `dramaType`:`ANIME` 表示漫剧,`LIVE` 表示真人剧。
|
> 卡片新增 `dramaType`:`ANIME` 表示漫剧,`LIVE` 表示真人剧。
|
||||||
> 客户端字段仍返回主内容类型;后台多选值保存在 `drama.drama_types`,
|
> 客户端字段仍返回主内容类型;后台多选值保存在 `drama.drama_types`,
|
||||||
> App 类型筛选按逗号列整词匹配,因此 `ANIME,LIVE` 多标签剧可被任一类型命中。
|
> App 类型筛选按逗号列整词匹配,因此 `ANIME,LIVE` 多标签剧可被任一类型命中。
|
||||||
@@ -216,6 +223,28 @@ app.register.max-per-device-per-day
|
|||||||
> 只返回 `status = 1` 的剧单,排序与后台剧单排序一致,卡片顺序与后台关联顺序一致。
|
> 只返回 `status = 1` 的剧单,排序与后台剧单排序一致,卡片顺序与后台关联顺序一致。
|
||||||
> 剧单列表越界页返回空 `list`,`total` 仍是全部剧单数。详情越界页同样返回空 `list`。
|
> 剧单列表越界页返回空 `list`,`total` 仍是全部剧单数。详情越界页同样返回空 `list`。
|
||||||
|
|
||||||
|
#### 推荐榜(`GET /app/categories/{id}/ranking`)
|
||||||
|
|
||||||
|
- 分类列表中的 `layoutType=RANKING` 表示客户端必须使用榜单布局,禁止按分类名称判断。
|
||||||
|
- 榜单内容与顺序以 `drama_classification_drama.position asc` 为准;客户端不得按播放量重新排序。
|
||||||
|
- 已下架、未发布或不存在的短剧会被过滤,剩余项目的 `rank` 从 1 连续补齐。
|
||||||
|
- 最多返回 50 部;`revision` 在后台保存内容或顺序后递增,供缓存与曝光埋点使用。
|
||||||
|
- 响应 `list` 项结构为 `{rank, drama}`,其中 `drama` 沿用 `AppDramaCardVO`。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "2112807182243336193",
|
||||||
|
"code": "RECOMMEND_RANKING",
|
||||||
|
"locales": {"zh": "推荐榜", "en": "Top Picks", "id": "Pilihan Teratas"},
|
||||||
|
"revision": "8",
|
||||||
|
"generatedAt": "2026-11-02T10:00:00",
|
||||||
|
"total": 1,
|
||||||
|
"list": [
|
||||||
|
{"rank": 1, "drama": {"id": "2112807182243336194", "titleLocales": {"zh": "短剧 A"}}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
#### 推荐类型流(`GET /app/feed`)
|
#### 推荐类型流(`GET /app/feed`)
|
||||||
|
|
||||||
- `types` 可选,逗号分隔,支持 `ANIME`、`LIVE` 或多选 `ANIME,LIVE`;不传或空值返回全部已上线内容。
|
- `types` 可选,逗号分隔,支持 `ANIME`、`LIVE` 或多选 `ANIME,LIVE`;不传或空值返回全部已上线内容。
|
||||||
@@ -460,6 +489,7 @@ app.register.max-per-device-per-day
|
|||||||
"id": "Pengantin Pengganti: Kesayangan Presiden Direktur"
|
"id": "Pengantin Pengganti: Kesayangan Presiden Direktur"
|
||||||
},
|
},
|
||||||
"dramaCover": "/files/drama_cover/12.jpg",
|
"dramaCover": "/files/drama_cover/12.jpg",
|
||||||
|
"dramaCoverLandscape": "/files/drama_cover/12-wide.jpg",
|
||||||
"episodeNumber": 6,
|
"episodeNumber": 6,
|
||||||
"totalEpisodes": 68,
|
"totalEpisodes": 68,
|
||||||
"viewCount": "1800",
|
"viewCount": "1800",
|
||||||
@@ -482,7 +512,8 @@ app.register.max-per-device-per-day
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `dramaTitle` | string / null | 短剧中文标题,旧客户端回退用 |
|
| `dramaTitle` | string / null | 短剧中文标题,旧客户端回退用 |
|
||||||
| `titleLocales` | object / null | 短剧标题语言表,key 为 `zh` / `en` / `id`。客户端按当前语言取,没有对应语言时回退 `zh` |
|
| `titleLocales` | object / null | 短剧标题语言表,key 为 `zh` / `en` / `id`。客户端按当前语言取,没有对应语言时回退 `zh` |
|
||||||
| `dramaCover` | string / null | 短剧封面 |
|
| `dramaCover` | string / null | 短剧竖版封面 |
|
||||||
|
| `dramaCoverLandscape` | string / null | 短剧横版封面,供继续观看横幅等横向位使用;为空时客户端回退 `dramaCover` |
|
||||||
| `episodeNumber` | int / null | 当前续看集号 `ep_no` |
|
| `episodeNumber` | int / null | 当前续看集号 `ep_no` |
|
||||||
| `totalEpisodes` | int / null | 短剧总集数 |
|
| `totalEpisodes` | int / null | 短剧总集数 |
|
||||||
| `viewCount` | Long(JSON 字符串)/ null | 短剧热度,取 `drama.view_count`。`playCount` 是用户自己的播放次数 |
|
| `viewCount` | Long(JSON 字符串)/ null | 短剧热度,取 `drama.view_count`。`playCount` 是用户自己的播放次数 |
|
||||||
@@ -555,6 +586,53 @@ app.register.max-per-device-per-day
|
|||||||
解锁后播放入口与下载入口会同时放行 —— 权益判定由交易模块的 `EntitlementPort` 实现提供,
|
解锁后播放入口与下载入口会同时放行 —— 权益判定由交易模块的 `EntitlementPort` 实现提供,
|
||||||
播放域与下载域都不需要改代码。金币变动一律带幂等键并写 `coin_ledger`,钱包余额与流水同事务。
|
播放域与下载域都不需要改代码。金币变动一律带幂等键并写 `coin_ledger`,钱包余额与流水同事务。
|
||||||
|
|
||||||
|
### 1.8.1 奖励中心(已实现)
|
||||||
|
|
||||||
|
奖励中心复用钱包和金币流水,首发时区固定为 `Asia/Jakarta`。任务配置、奖励金币、任务文案、动作、周期和上下线状态均由后台维护;客户端不能直接提交任务进度,观看进度由服务端在 `/app/watch/progress` 校验成功后累计。
|
||||||
|
|
||||||
|
| 方法 | 路径 | 鉴权 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| GET | `/app/rewards/overview` | 匿名 | 返回任务配置、任务分组、签到规则和活动卡片;未登录时余额为 `0`、用户进度为 `0`、签到状态为未签到;登录后补充用户数据;`locale` 可选 `id/en/zh` |
|
||||||
|
| GET | `/app/rewards/activities` | 匿名 | 返回当前生效活动卡片,活动一期只展示和跳转 |
|
||||||
|
| GET | `/app/rewards/check-in` | 登录 | 返回今日是否签到、连续天数、7 天规则 |
|
||||||
|
| POST | `/app/rewards/check-in` | 登录 | 按服务端日期和连续签到规则发放金币;同用户同日期幂等 |
|
||||||
|
| POST | `/app/rewards/tasks/{taskId}/claim` | 登录 | 领取已完成任务;同任务同周期幂等 |
|
||||||
|
|
||||||
|
总览响应核心字段:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"serverDate": "2026-11-05",
|
||||||
|
"timezone": "Asia/Jakarta",
|
||||||
|
"coinBalance": "135",
|
||||||
|
"checkin": {
|
||||||
|
"taskId": "202611050001",
|
||||||
|
"checkedInToday": false,
|
||||||
|
"streak": 2,
|
||||||
|
"currentDay": 3,
|
||||||
|
"days": [{"dayIndex": 1, "rewardCoin": "35", "checked": true, "current": false}]
|
||||||
|
},
|
||||||
|
"sections": [{
|
||||||
|
"code": "DAILY",
|
||||||
|
"title": "Tugas harian",
|
||||||
|
"tasks": [{
|
||||||
|
"id": "202611050002",
|
||||||
|
"code": "watch_5_minutes",
|
||||||
|
"type": "WATCH_DURATION",
|
||||||
|
"progressValue": "120",
|
||||||
|
"targetValue": "300",
|
||||||
|
"rewardCoin": "20",
|
||||||
|
"status": "IN_PROGRESS"
|
||||||
|
}]
|
||||||
|
}],
|
||||||
|
"activities": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
一期任务类型为 `DAILY_CHECK_IN`、`WATCH_DURATION`、`WATCH_EPISODES`、`COMPLETE_PROFILE`、`FIRST_PURCHASE`;`FIRST_LOGIN` 预留给登录事件接入。任务状态为 `IN_PROGRESS`、`COMPLETED`、`CLAIMED`。奖励发放使用 `coin_ledger.biz_type=REWARD`,任务领取幂等键为 `reward:{taskCode}:{userId}:{cycleKey}`,签到幂等键为 `reward:checkin:{userId}:{date}`。重复请求返回既有发放结果,不重复增加钱包余额。
|
||||||
|
|
||||||
|
失败场景:任务未完成或已停用返回 `200003`;任务、签到规则不存在返回 `200002`;奖励金币为 0 或请求参数非法返回 `400`;钱包余额和发放单不一致时整笔事务回滚。
|
||||||
|
|
||||||
**`POST /app/orders/verify`(B1-1:Google Play 票据校验闭环)**
|
**`POST /app/orders/verify`(B1-1:Google Play 票据校验闭环)**
|
||||||
|
|
||||||
请求体:
|
请求体:
|
||||||
@@ -631,6 +709,7 @@ B1-2 的退款/拒付复验依赖它。服务端凭据(`packageName` + service
|
|||||||
| `noticeEnabled` | `app.notice.enabled` | `true` | 公告入口开关 |
|
| `noticeEnabled` | `app.notice.enabled` | `true` | 公告入口开关 |
|
||||||
| `coinUnlockEnabled` | `app.coin.unlock.enabled` | `true` | 金币解锁开关 |
|
| `coinUnlockEnabled` | `app.coin.unlock.enabled` | `true` | 金币解锁开关 |
|
||||||
| `downloadEnabled` | `app.download.enabled` | `true` | 离线下载开关 |
|
| `downloadEnabled` | `app.download.enabled` | `true` | 离线下载开关 |
|
||||||
|
| `loginBackgroundUrl` | `app.login.background.url` | `""` | 登录页全屏海报背景;留空 App 用内置默认图。**建议尺寸 1170×2532**(iPhone 14 Pro Max 3× 整屏竖图),后台走 `/admin/media/upload/` 任意 bizType 上传后把返回的相对路径(`/files/login_bg/xxx.jpg`)写入即可 |
|
||||||
|
|
||||||
**口径**:**只下发上述白名单键**(服务端硬编码白名单),后台配置里的其它键(可能含内部开关)
|
**口径**:**只下发上述白名单键**(服务端硬编码白名单),后台配置里的其它键(可能含内部开关)
|
||||||
**一律不下发**;库里缺键时用「契约默认值」兜底,**不返回 null 让客户端自己猜默认值**。
|
**一律不下发**;库里缺键时用「契约默认值」兜底,**不返回 null 让客户端自己猜默认值**。
|
||||||
@@ -863,13 +942,13 @@ GET /app/notices?pageIndex=1&pageSize=20
|
|||||||
|
|
||||||
| 方法 | 路径 | 权限点 | 说明 |
|
| 方法 | 路径 | 权限点 | 说明 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource |
|
| GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource、platform(ANDROID/IOS,按用户**最近一次**会话平台筛选) |
|
||||||
| GET | `/admin/app-users/{id}` | `app-user:list` | 详情 |
|
| GET | `/admin/app-users/{id}` | `app-user:list` | 详情 |
|
||||||
| GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 |
|
| GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 |
|
||||||
| GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) |
|
| GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) |
|
||||||
| GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime |
|
| GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime、platform(ANDROID/IOS,按**最近一次会话**) |
|
||||||
| GET | `/admin/favorites/page` | `favorite:list` | 收藏只读分页,含游客 |
|
| GET | `/admin/favorites/page` | `favorite:list` | 收藏只读分页,含游客;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
|
||||||
| GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标 |
|
| GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
|
||||||
| PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned |
|
| PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned |
|
||||||
|
|
||||||
状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。
|
状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。
|
||||||
@@ -1201,6 +1280,24 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评
|
|||||||
|
|
||||||
> `id` 以字符串下发:见 **§0「ID 字段一律以字符串下发」**(本节不再单独规定)。
|
> `id` 以字符串下发:见 **§0「ID 字段一律以字符串下发」**(本节不再单独规定)。
|
||||||
|
|
||||||
|
### 2.11.1 奖励中心管理(已实现)
|
||||||
|
|
||||||
|
| 方法 | 路径 | 权限点 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| GET | `/admin/rewards/tasks/page` · `/tasks/{id}` | `reward:list` | 奖励任务分页与详情 |
|
||||||
|
| POST | `/admin/rewards/tasks` | `reward:update` | 新建任务,默认下线 |
|
||||||
|
| PUT | `/admin/rewards/tasks/{id}` · `/{id}/status` | `reward:update` | 编辑、上线 / 下线;编辑会递增版本 |
|
||||||
|
| GET | `/admin/rewards/activities/page` · `/activities/{id}` | `reward:list` | 奖励活动分页与详情 |
|
||||||
|
| POST | `/admin/rewards/activities` | `reward:update` | 新建活动,默认下线 |
|
||||||
|
| PUT | `/admin/rewards/activities/{id}` · `/{id}/status` | `reward:update` | 编辑、上线 / 下线 |
|
||||||
|
| GET · PUT | `/admin/rewards/check-in/rules` | `reward:checkin` | 查看 / 保存签到每日奖励规则,天数不能重复 |
|
||||||
|
| GET | `/admin/rewards/grants/page` | `reward:grant` | 用户、任务、来源、状态筛选发放记录 |
|
||||||
|
| POST | `/admin/rewards/grants/manual` | `reward:grant` | 人工补发;仍写 `REWARD` 钱包流水并要求幂等键 |
|
||||||
|
|
||||||
|
后台任务保存字段包括 `code`、`sectionCode`、`type`、`verifyMode`、`targetValue`、`rewardCoin`、`cycleType`、`cycleLimit`、三语言文案、动作、排序和生效时间。任务配置不允许后台写任意脚本,扩展字段只能放在 `configJson`。
|
||||||
|
|
||||||
|
后台活动保存字段包括 `code`、`coverUrl`、`actionType`、`actionUrl`、三语言标题、三语言摘要、三语言按钮文案、排序和生效时间。活动与任务共用 `reward:update` 权限,新建活动默认下线。
|
||||||
|
|
||||||
**校验与错误码**:
|
**校验与错误码**:
|
||||||
|
|
||||||
| 场景 | 结果 |
|
| 场景 | 结果 |
|
||||||
@@ -1260,6 +1357,7 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评
|
|||||||
| GET | `/admin/drama-classifications/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) |
|
| GET | `/admin/drama-classifications/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) |
|
||||||
| POST | `/admin/drama-classifications/{id}/dramas` | `drama:update` | 批量关联短剧,返回实际新增数量 |
|
| POST | `/admin/drama-classifications/{id}/dramas` | `drama:update` | 批量关联短剧,返回实际新增数量 |
|
||||||
| DELETE | `/admin/drama-classifications/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) |
|
| DELETE | `/admin/drama-classifications/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) |
|
||||||
|
| PUT | `/admin/drama-classifications/{id}/ranking-items` | `drama:update` | 原子保存推荐榜完整顺序,最多 50 部;空数组表示清空 |
|
||||||
|
|
||||||
**列表响应**
|
**列表响应**
|
||||||
|
|
||||||
@@ -1271,6 +1369,9 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评
|
|||||||
{
|
{
|
||||||
"id": "2112807182243336193",
|
"id": "2112807182243336193",
|
||||||
"name": "本周必看",
|
"name": "本周必看",
|
||||||
|
"code": "CLASSIFICATION_2112807182243336193",
|
||||||
|
"layoutType": "GRID",
|
||||||
|
"revision": "1",
|
||||||
"sort": 1,
|
"sort": 1,
|
||||||
"status": 1,
|
"status": 1,
|
||||||
"dramaCount": 12,
|
"dramaCount": 12,
|
||||||
@@ -1286,12 +1387,20 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评
|
|||||||
**新建 / 编辑请求体**
|
**新建 / 编辑请求体**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{ "name": "本周必看", "sort": 1, "status": 1 }
|
{
|
||||||
|
"name": "推荐榜",
|
||||||
|
"code": "RECOMMEND_RANKING",
|
||||||
|
"layoutType": "RANKING",
|
||||||
|
"sort": 1,
|
||||||
|
"status": 1
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| 字段 | 必填 | 说明 |
|
| 字段 | 必填 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写分类名称」 |
|
| `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写分类名称」 |
|
||||||
|
| `code` | 否 | 稳定语义码,只允许大写字母、数字、下划线;不传时生成 `CLASSIFICATION_{id}` |
|
||||||
|
| `layoutType` | 否 | `GRID` 普通分类 / `RANKING` 推荐榜;默认 `GRID` |
|
||||||
| `sort` | 否 | 新建不传时取 `现有条数 + 1`;编辑不传(null)时保持原值 |
|
| `sort` | 否 | 新建不传时取 `现有条数 + 1`;编辑不传(null)时保持原值 |
|
||||||
| `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1`,编辑不传保持原值 |
|
| `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1`,编辑不传保持原值 |
|
||||||
|
|
||||||
@@ -1305,6 +1414,11 @@ POST /admin/drama-classifications/2112807182243336193/dramas
|
|||||||
返回 `data` 为实际新增条数(整数)。已关联的、以及不存在的 `dramaId` 会被静默跳过,不报错;
|
返回 `data` 为实际新增条数(整数)。已关联的、以及不存在的 `dramaId` 会被静默跳过,不报错;
|
||||||
全部跳过时返回 `0`。`dramaIds` 为空数组 → `400 请选择短剧`。
|
全部跳过时返回 `0`。`dramaIds` 为空数组 → `400 请选择短剧`。
|
||||||
|
|
||||||
|
推荐榜应使用 `PUT /{id}/ranking-items` 一次提交完整有序 `dramaIds`。接口会去重、校验短剧存在,
|
||||||
|
按数组顺序写入 `position=1..N` 并递增分类 `revision`;`dramaIds` 必须显式传数组,空数组表示清空。
|
||||||
|
普通分类调用该接口返回 `200003`;推荐榜调用旧的 `POST /{id}/dramas` 或
|
||||||
|
`DELETE /{id}/dramas/{dramaId}` 同样返回 `200003`,防止绕过版本与排序更新。
|
||||||
|
|
||||||
**短剧列表项(`GET /{id}/dramas` 与 `/dramas/candidates` 共用)**
|
**短剧列表项(`GET /{id}/dramas` 与 `/dramas/candidates` 共用)**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
|
|||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.admin.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||||
|
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台接口的时间格式统一成 `yyyy-MM-dd HH:mm:ss`。
|
||||||
|
*
|
||||||
|
* <p>application.yml 里的 `spring.jackson.date-format` 只作用于 java.util.Date,
|
||||||
|
* LocalDateTime 仍会输出 ISO 的 `2026-10-27T14:14:12.644`,后台表格里会露出一串带 T 的原文。
|
||||||
|
* 该配置只放在 admin-api,C 端保持 ISO,避免影响客户端解析。
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class AdminJacksonTimeConfig {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Jackson2ObjectMapperBuilderCustomizer adminLocalDateTimeFormat() {
|
||||||
|
return builder -> builder.serializers(new LocalDateTimeSerializer(DATE_TIME));
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -32,12 +32,13 @@ import java.util.List;
|
|||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private final AuthService authService;
|
private final AuthService authService;
|
||||||
|
private final WebUtils webUtils;
|
||||||
|
|
||||||
@Operation(summary = "管理端登录")
|
@Operation(summary = "管理端登录")
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
@OperationLog(module = "认证", action = "登录")
|
@OperationLog(module = "认证", action = "登录")
|
||||||
public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) {
|
public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) {
|
||||||
return Result.ok(authService.login(req, WebUtils.getClientIp(request)));
|
return Result.ok(authService.login(req, webUtils.clientIp(request)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */
|
/** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */
|
||||||
|
|||||||
+4
-4
@@ -70,8 +70,8 @@ public class CreatorAdminController {
|
|||||||
return Result.ok(creatorService.audit(id, req, SecurityUtils.getUserId()));
|
return Result.ok(creatorService.audit(id, req, SecurityUtils.getUserId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 手工录入创作者主体(C 端申请入驻还没实现,先用它打通链路)。 */
|
/** 手工录入创作者主体:录入即通过,可直接开号。 */
|
||||||
@Operation(summary = "手工录入创作者主体")
|
@Operation(summary = "手工录入创作者主体(录入即通过)")
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@PreAuthorize("@ss.hasPermission('creator:audit')")
|
@PreAuthorize("@ss.hasPermission('creator:audit')")
|
||||||
@OperationLog(module = "创作者管理", action = "新增创作者")
|
@OperationLog(module = "创作者管理", action = "新增创作者")
|
||||||
@@ -79,8 +79,8 @@ public class CreatorAdminController {
|
|||||||
return Result.ok(creatorService.create(req));
|
return Result.ok(creatorService.create(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 开通创作者账号:仅审核通过可开;已开通则幂等返回,不重复建号。 */
|
/** 开通创作者账号:不再校验入驻审核,仅冻结状态拒绝;已开通则幂等返回。 */
|
||||||
@Operation(summary = "开通创作者账号(仅审核通过可开通,幂等)")
|
@Operation(summary = "开通创作者账号(仅冻结状态拒绝,幂等)")
|
||||||
@PostMapping("/{id}/account")
|
@PostMapping("/{id}/account")
|
||||||
@PreAuthorize("@ss.hasPermission('creator:account')")
|
@PreAuthorize("@ss.hasPermission('creator:account')")
|
||||||
@OperationLog(module = "创作者管理", action = "开通创作者账号")
|
@OperationLog(module = "创作者管理", action = "开通创作者账号")
|
||||||
|
|||||||
+20
@@ -12,6 +12,8 @@ import com.fruitshorts.creator.service.CreatorContentService;
|
|||||||
import com.fruitshorts.creator.vo.CreatorAttachReqVO;
|
import com.fruitshorts.creator.vo.CreatorAttachReqVO;
|
||||||
import com.fruitshorts.creator.vo.CreatorDramaEditReqVO;
|
import com.fruitshorts.creator.vo.CreatorDramaEditReqVO;
|
||||||
import com.fruitshorts.creator.vo.CreatorEpisodeReqVO;
|
import com.fruitshorts.creator.vo.CreatorEpisodeReqVO;
|
||||||
|
import com.fruitshorts.creator.vo.CreatorPublishReqVO;
|
||||||
|
import com.fruitshorts.creator.vo.CreatorPublishRespVO;
|
||||||
import com.fruitshorts.creator.vo.CreatorSubmitReqVO;
|
import com.fruitshorts.creator.vo.CreatorSubmitReqVO;
|
||||||
import com.fruitshorts.framework.log.OperationLog;
|
import com.fruitshorts.framework.log.OperationLog;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
@@ -53,6 +55,15 @@ public class CreatorContentController {
|
|||||||
return Result.ok(creatorContentService.createDrama(req));
|
return Result.ok(creatorContentService.createDrama(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 一键发布:建作品 + 建分集 + 绑定视频(可选同时提交审核),一个事务完成。 */
|
||||||
|
@Operation(summary = "一键发布(建作品 / 分集 / 绑定视频 / 可选提交审核)")
|
||||||
|
@PostMapping("/publish")
|
||||||
|
@PreAuthorize("@ss.hasPermission('creator-center:drama:edit')")
|
||||||
|
@OperationLog(module = "创作者中心", action = "一键发布作品")
|
||||||
|
public Result<CreatorPublishRespVO> publish(@Valid @RequestBody CreatorPublishReqVO req) {
|
||||||
|
return Result.ok(creatorContentService.publish(req));
|
||||||
|
}
|
||||||
|
|
||||||
/** 编辑作品信息(仅草稿 / 已下线可改)。 */
|
/** 编辑作品信息(仅草稿 / 已下线可改)。 */
|
||||||
@Operation(summary = "编辑作品信息(仅草稿 / 已下线可改)")
|
@Operation(summary = "编辑作品信息(仅草稿 / 已下线可改)")
|
||||||
@PutMapping("/dramas/{id}")
|
@PutMapping("/dramas/{id}")
|
||||||
@@ -101,6 +112,15 @@ public class CreatorContentController {
|
|||||||
return Result.ok();
|
return Result.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除作品")
|
||||||
|
@DeleteMapping("/dramas/{id}")
|
||||||
|
@PreAuthorize("@ss.hasPermission('creator-center:drama:edit')")
|
||||||
|
@OperationLog(module = "创作者中心", action = "删除作品")
|
||||||
|
public Result<Void> deleteDrama(@PathVariable Long id) {
|
||||||
|
creatorContentService.deleteDrama(id);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
/** 批量排序:body 里按新顺序给出分集 id。 */
|
/** 批量排序:body 里按新顺序给出分集 id。 */
|
||||||
@Operation(summary = "分集批量排序")
|
@Operation(summary = "分集批量排序")
|
||||||
@PutMapping("/dramas/{id}/episodes/sort")
|
@PutMapping("/dramas/{id}/episodes/sort")
|
||||||
|
|||||||
+2
-2
@@ -31,14 +31,14 @@ public class DictController {
|
|||||||
|
|
||||||
@Operation(summary = "短剧分类字典")
|
@Operation(summary = "短剧分类字典")
|
||||||
@GetMapping("/drama-category")
|
@GetMapping("/drama-category")
|
||||||
@PreAuthorize("@ss.hasPermission('drama:list')")
|
@PreAuthorize("@ss.hasAnyPermission('drama:list','creator-center:view')")
|
||||||
public Result<List<DramaCategoryRespVO>> dramaCategories() {
|
public Result<List<DramaCategoryRespVO>> dramaCategories() {
|
||||||
return Result.ok(dramaCategoryService.list());
|
return Result.ok(dramaCategoryService.list());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "内容状态字典")
|
@Operation(summary = "内容状态字典")
|
||||||
@GetMapping("/content-status")
|
@GetMapping("/content-status")
|
||||||
@PreAuthorize("@ss.hasPermission('drama:list')")
|
@PreAuthorize("@ss.hasAnyPermission('drama:list','creator-center:view')")
|
||||||
public Result<List<Map<String, String>>> contentStatus() {
|
public Result<List<Map<String, String>>> contentStatus() {
|
||||||
return Result.ok(Arrays.stream(ContentStatus.values())
|
return Result.ok(Arrays.stream(ContentStatus.values())
|
||||||
.map(status -> Map.of("code", status.getCode(), "text", status.getText()))
|
.map(status -> Map.of("code", status.getCode(), "text", status.getText()))
|
||||||
|
|||||||
+11
@@ -9,6 +9,7 @@ import com.fruitshorts.content.vo.DramaBriefVO;
|
|||||||
import com.fruitshorts.content.vo.DramaClassificationRespVO;
|
import com.fruitshorts.content.vo.DramaClassificationRespVO;
|
||||||
import com.fruitshorts.content.vo.DramaClassificationSaveReqVO;
|
import com.fruitshorts.content.vo.DramaClassificationSaveReqVO;
|
||||||
import com.fruitshorts.content.vo.DramaIdsReqVO;
|
import com.fruitshorts.content.vo.DramaIdsReqVO;
|
||||||
|
import com.fruitshorts.content.vo.DramaRankingItemsReqVO;
|
||||||
import com.fruitshorts.framework.log.OperationLog;
|
import com.fruitshorts.framework.log.OperationLog;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
@@ -104,6 +105,16 @@ public class DramaClassificationController {
|
|||||||
return Result.ok(classificationService.bindDramas(id, req.getDramaIds()));
|
return Result.ok(classificationService.bindDramas(id, req.getDramaIds()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "保存推荐榜完整内容与顺序")
|
||||||
|
@PutMapping("/{id}/ranking-items")
|
||||||
|
@PreAuthorize("@ss.hasPermission('drama:update')")
|
||||||
|
@OperationLog(module = "内容管理", action = "保存推荐榜顺序")
|
||||||
|
public Result<Void> saveRankingItems(@PathVariable Long id,
|
||||||
|
@Valid @RequestBody DramaRankingItemsReqVO req) {
|
||||||
|
classificationService.saveRankingItems(id, req.getDramaIds());
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "移除分类下的短剧")
|
@Operation(summary = "移除分类下的短剧")
|
||||||
@DeleteMapping("/{id}/dramas/{dramaId}")
|
@DeleteMapping("/{id}/dramas/{dramaId}")
|
||||||
@PreAuthorize("@ss.hasPermission('drama:update')")
|
@PreAuthorize("@ss.hasPermission('drama:update')")
|
||||||
|
|||||||
+9
@@ -113,6 +113,15 @@ public class DramaController {
|
|||||||
return Result.ok();
|
return Result.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "审核通过并上线")
|
||||||
|
@PostMapping("/{id}/approve-publish")
|
||||||
|
@PreAuthorize("@ss.hasPermission('drama:review')")
|
||||||
|
@OperationLog(module = "内容管理", action = "审核通过并上线")
|
||||||
|
public Result<Void> approvePublish(@PathVariable Long id, @RequestBody(required = false) DramaStatusReqVO req) {
|
||||||
|
changeStatus(id, "APPROVE_PUBLISH", req);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "上线")
|
@Operation(summary = "上线")
|
||||||
@PostMapping("/{id}/publish")
|
@PostMapping("/{id}/publish")
|
||||||
@PreAuthorize("@ss.hasPermission('drama:review')")
|
@PreAuthorize("@ss.hasPermission('drama:review')")
|
||||||
|
|||||||
+171
@@ -0,0 +1,171 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.admin.controller;
|
||||||
|
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardCheckinService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardActivityAdminService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardGrantService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardTaskService;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivitySaveReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinRuleSaveReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardGrantQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardGrantRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardManualGrantReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardRuleDayVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskSaveReqVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import com.fruitshorts.common.pojo.PageResult;
|
||||||
|
import com.fruitshorts.common.pojo.Result;
|
||||||
|
import com.fruitshorts.framework.log.OperationLog;
|
||||||
|
import com.fruitshorts.framework.security.SecurityUtils;
|
||||||
|
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 后台奖励任务、签到规则和发放记录管理。 */
|
||||||
|
@Tag(name = "后台-奖励中心")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin/rewards")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RewardAdminController {
|
||||||
|
|
||||||
|
private final RewardTaskService taskService;
|
||||||
|
private final RewardActivityAdminService activityService;
|
||||||
|
private final RewardCheckinService checkinService;
|
||||||
|
private final RewardGrantService grantService;
|
||||||
|
private final AppUserMapper appUserMapper;
|
||||||
|
|
||||||
|
@Operation(summary = "奖励任务分页")
|
||||||
|
@GetMapping("/tasks/page")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:list')")
|
||||||
|
public Result<PageResult<RewardTaskRespVO>> page(@Validated RewardTaskQueryReqVO req) {
|
||||||
|
return Result.ok(taskService.page(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励任务详情")
|
||||||
|
@GetMapping("/tasks/{id}")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:list')")
|
||||||
|
public Result<RewardTaskRespVO> detail(@PathVariable Long id) {
|
||||||
|
return Result.ok(taskService.detail(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新建奖励任务")
|
||||||
|
@PostMapping("/tasks")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:update')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "新建奖励任务")
|
||||||
|
public Result<Long> create(@Valid @RequestBody RewardTaskSaveReqVO req) {
|
||||||
|
return Result.ok(taskService.create(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "编辑奖励任务")
|
||||||
|
@PutMapping("/tasks/{id}")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:update')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "编辑奖励任务")
|
||||||
|
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody RewardTaskSaveReqVO req) {
|
||||||
|
taskService.update(id, req);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励任务上下线")
|
||||||
|
@PutMapping("/tasks/{id}/status")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:update')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "奖励任务上下线")
|
||||||
|
public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
|
||||||
|
taskService.updateStatus(id, status);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励活动分页")
|
||||||
|
@GetMapping("/activities/page")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:list')")
|
||||||
|
public Result<PageResult<RewardActivityRespVO>> activityPage(@Validated RewardActivityQueryReqVO req) {
|
||||||
|
return Result.ok(activityService.page(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励活动详情")
|
||||||
|
@GetMapping("/activities/{id}")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:list')")
|
||||||
|
public Result<RewardActivityRespVO> activityDetail(@PathVariable Long id) {
|
||||||
|
return Result.ok(activityService.detail(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新建奖励活动")
|
||||||
|
@PostMapping("/activities")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:update')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "新建奖励活动")
|
||||||
|
public Result<Long> createActivity(@Valid @RequestBody RewardActivitySaveReqVO req) {
|
||||||
|
return Result.ok(activityService.create(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "编辑奖励活动")
|
||||||
|
@PutMapping("/activities/{id}")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:update')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "编辑奖励活动")
|
||||||
|
public Result<Void> updateActivity(@PathVariable Long id, @Valid @RequestBody RewardActivitySaveReqVO req) {
|
||||||
|
activityService.update(id, req);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励活动上下线")
|
||||||
|
@PutMapping("/activities/{id}/status")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:update')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "奖励活动上下线")
|
||||||
|
public Result<Void> updateActivityStatus(@PathVariable Long id, @RequestParam Integer status) {
|
||||||
|
activityService.updateStatus(id, status);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "签到规则")
|
||||||
|
@GetMapping("/check-in/rules")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:checkin')")
|
||||||
|
public Result<List<RewardRuleDayVO>> rules() {
|
||||||
|
return Result.ok(checkinService.rulesForAdmin());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "保存签到规则")
|
||||||
|
@PutMapping("/check-in/rules")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:checkin')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "保存签到规则")
|
||||||
|
public Result<Void> saveRules(@Valid @RequestBody RewardCheckinRuleSaveReqVO req) {
|
||||||
|
checkinService.saveRules(req);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励发放记录分页")
|
||||||
|
@GetMapping("/grants/page")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:grant')")
|
||||||
|
public Result<PageResult<RewardGrantRespVO>> grants(@Validated RewardGrantQueryReqVO req) {
|
||||||
|
return Result.ok(grantService.page(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "人工补发奖励")
|
||||||
|
@PostMapping("/grants/manual")
|
||||||
|
@PreAuthorize("@ss.hasPermission('reward:grant')")
|
||||||
|
@OperationLog(module = "奖励中心", action = "人工补发奖励")
|
||||||
|
public Result<RewardGrantRespVO> manualGrant(@Valid @RequestBody RewardManualGrantReqVO req) {
|
||||||
|
if (appUserMapper.selectById(req.getUserId()) == null) {
|
||||||
|
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "用户不存在,无法补发奖励");
|
||||||
|
}
|
||||||
|
return Result.ok(grantService.manualGrant(req.getUserId(), req.getTaskId(), req.getAmount(),
|
||||||
|
req.getIdempotentKey(), SecurityUtils.getUserId()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+52
-1
@@ -3,7 +3,9 @@
|
|||||||
package com.fruitshorts.admin.service;
|
package com.fruitshorts.admin.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||||
|
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
|
||||||
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -13,16 +15,19 @@ import java.util.ArrayList;
|
|||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按用户最近会话解析系统。同一设备优先,否则用仍有效的最近一次登录。
|
* 按设备画像解析系统,缺画像时回退到用户最近会话。
|
||||||
|
* 设备画像不依赖登录态,游客行为也能显示系统。
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class AppSessionSystemService {
|
public class AppSessionSystemService {
|
||||||
|
|
||||||
private final AppUserSessionMapper sessionMapper;
|
private final AppUserSessionMapper sessionMapper;
|
||||||
|
private final AppDeviceProfileMapper profileMapper;
|
||||||
|
|
||||||
/** 按用户分组,组内按最近活跃倒序。 */
|
/** 按用户分组,组内按最近活跃倒序。 */
|
||||||
public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) {
|
public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) {
|
||||||
@@ -31,6 +36,9 @@ public class AppSessionSystemService {
|
|||||||
return grouped;
|
return grouped;
|
||||||
}
|
}
|
||||||
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
|
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
|
||||||
|
.select(AppUserSession::getId, AppUserSession::getUserId, AppUserSession::getDeviceId,
|
||||||
|
AppUserSession::getPlatform, AppUserSession::getOsVersion,
|
||||||
|
AppUserSession::getRevokedAt, AppUserSession::getLastActiveAt)
|
||||||
.in(AppUserSession::getUserId, userIds)
|
.in(AppUserSession::getUserId, userIds)
|
||||||
.orderByDesc(AppUserSession::getLastActiveAt)
|
.orderByDesc(AppUserSession::getLastActiveAt)
|
||||||
.orderByDesc(AppUserSession::getId));
|
.orderByDesc(AppUserSession::getId));
|
||||||
@@ -40,6 +48,49 @@ public class AppSessionSystemService {
|
|||||||
return grouped;
|
return grouped;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 按 device_id 批量取设备画像,未建档的设备不出现在结果里。 */
|
||||||
|
public Map<String, AppDeviceProfile> deviceProfiles(Collection<String> deviceIds) {
|
||||||
|
Map<String, AppDeviceProfile> result = new HashMap<>();
|
||||||
|
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
List<String> keys = deviceIds.stream()
|
||||||
|
.filter(StringUtils::hasText).map(String::trim).distinct().toList();
|
||||||
|
if (keys.isEmpty()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
for (AppDeviceProfile profile : profileMapper.selectList(
|
||||||
|
Wrappers.<AppDeviceProfile>lambdaQuery().in(AppDeviceProfile::getDeviceId, keys))) {
|
||||||
|
result.put(profile.getDeviceId(), profile);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 平台筛选的命中范围:设备平台直接给 device_id;登录用户的行为行不带 device_id,
|
||||||
|
* 只能按该用户登录会话的平台判定,两者取并集。
|
||||||
|
*/
|
||||||
|
public record PlatformScope(List<String> deviceIds, List<Long> userIds) {
|
||||||
|
public boolean empty() {
|
||||||
|
return deviceIds.isEmpty() && userIds.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按平台解析命中范围;未传平台返回 null 表示不限制。 */
|
||||||
|
public PlatformScope platformScope(String platform) {
|
||||||
|
if (!StringUtils.hasText(platform)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String value = platform.trim().toUpperCase(Locale.ROOT);
|
||||||
|
List<String> deviceIds = profileMapper.selectList(Wrappers.<AppDeviceProfile>lambdaQuery()
|
||||||
|
.select(AppDeviceProfile::getDeviceId)
|
||||||
|
.eq(AppDeviceProfile::getPlatform, value))
|
||||||
|
.stream().map(AppDeviceProfile::getDeviceId).toList();
|
||||||
|
// 只认「最近一次登录」的平台,与列表里展示的系统保持一致
|
||||||
|
List<Long> userIds = sessionMapper.selectUserIdsByLatestPlatform(value);
|
||||||
|
return new PlatformScope(deviceIds, userIds);
|
||||||
|
}
|
||||||
|
|
||||||
/** 观看记录优先匹配同一设备,其次取未吊销会话。 */
|
/** 观看记录优先匹配同一设备,其次取未吊销会话。 */
|
||||||
public AppUserSession match(List<AppUserSession> sessions, String deviceId) {
|
public AppUserSession match(List<AppUserSession> sessions, String deviceId) {
|
||||||
if (sessions == null || sessions.isEmpty()) {
|
if (sessions == null || sessions.isEmpty()) {
|
||||||
|
|||||||
+45
@@ -9,13 +9,19 @@ import com.fruitshorts.common.exception.ErrorCode;
|
|||||||
import com.fruitshorts.common.exception.ServiceException;
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
import com.fruitshorts.content.dal.entity.Drama;
|
import com.fruitshorts.content.dal.entity.Drama;
|
||||||
import com.fruitshorts.content.dal.mapper.DramaMapper;
|
import com.fruitshorts.content.dal.mapper.DramaMapper;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||||
import com.fruitshorts.user.dal.entity.AppUser;
|
import com.fruitshorts.user.dal.entity.AppUser;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||||
|
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
|
||||||
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||||
|
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
@@ -35,6 +41,9 @@ public class EngagementAdminLookup {
|
|||||||
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
|
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
|
||||||
private final AppUserMapper userMapper;
|
private final AppUserMapper userMapper;
|
||||||
private final DramaMapper dramaMapper;
|
private final DramaMapper dramaMapper;
|
||||||
|
private final AppDeviceProfileMapper deviceProfileMapper;
|
||||||
|
private final AppUserSessionMapper sessionMapper;
|
||||||
|
private final AppSessionSystemService sessionSystem;
|
||||||
|
|
||||||
/** 规范化页码和页大小。 */
|
/** 规范化页码和页大小。 */
|
||||||
public <T> Page<T> page(EngagementQueryReqVO req) {
|
public <T> Page<T> page(EngagementQueryReqVO req) {
|
||||||
@@ -96,6 +105,42 @@ public class EngagementAdminLookup {
|
|||||||
.collect(Collectors.toMap(Drama::getId, Function.identity()));
|
.collect(Collectors.toMap(Drama::getId, Function.identity()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 按 device_id 批量读取设备画像;游客也有记录,没建档的不返回。 */
|
||||||
|
public Map<String, AppDeviceProfile> deviceProfiles(Collection<String> deviceIds) {
|
||||||
|
List<String> keys = deviceIds.stream().filter(StringUtils::hasText)
|
||||||
|
.map(String::trim).distinct().toList();
|
||||||
|
return keys.isEmpty() ? Map.of() : deviceProfileMapper.selectList(
|
||||||
|
Wrappers.<AppDeviceProfile>lambdaQuery().in(AppDeviceProfile::getDeviceId, keys))
|
||||||
|
.stream().collect(Collectors.toMap(AppDeviceProfile::getDeviceId,
|
||||||
|
Function.identity(), (first, second) -> first));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每个用户取最近一次登录会话。
|
||||||
|
* 已登录用户的互动行 device_id 为空(写入时会清空),只能退回会话取系统。
|
||||||
|
*/
|
||||||
|
public Map<Long, AppUserSession> latestSessions(Collection<Long> userIds) {
|
||||||
|
List<Long> keys = keys(userIds);
|
||||||
|
if (keys.isEmpty()) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
Map<Long, AppUserSession> result = new HashMap<>();
|
||||||
|
for (AppUserSession session : sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
|
||||||
|
.select(AppUserSession::getId, AppUserSession::getUserId,
|
||||||
|
AppUserSession::getPlatform)
|
||||||
|
.in(AppUserSession::getUserId, keys)
|
||||||
|
.orderByDesc(AppUserSession::getLastActiveAt)
|
||||||
|
.orderByDesc(AppUserSession::getId))) {
|
||||||
|
result.putIfAbsent(session.getUserId(), session);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按平台解析命中范围;未传平台返回 null 表示不限制。 */
|
||||||
|
public AppSessionSystemService.PlatformScope platformScope(String platform) {
|
||||||
|
return sessionSystem.platformScope(platform);
|
||||||
|
}
|
||||||
|
|
||||||
private List<Long> keys(Collection<Long> ids) {
|
private List<Long> keys(Collection<Long> ids) {
|
||||||
return ids.stream().filter(Objects::nonNull).distinct().toList();
|
return ids.stream().filter(Objects::nonNull).distinct().toList();
|
||||||
}
|
}
|
||||||
|
|||||||
+38
-4
@@ -10,7 +10,9 @@ import com.fruitshorts.content.dal.entity.Drama;
|
|||||||
import com.fruitshorts.content.enums.ContentStatus;
|
import com.fruitshorts.content.enums.ContentStatus;
|
||||||
import com.fruitshorts.playback.dal.entity.UserFavorite;
|
import com.fruitshorts.playback.dal.entity.UserFavorite;
|
||||||
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
|
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||||
import com.fruitshorts.user.dal.entity.AppUser;
|
import com.fruitshorts.user.dal.entity.AppUser;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@@ -34,6 +36,10 @@ public class FavoriteAdminService {
|
|||||||
if (lookup.noMatch(dramaIds)) {
|
if (lookup.noMatch(dramaIds)) {
|
||||||
return PageResult.empty();
|
return PageResult.empty();
|
||||||
}
|
}
|
||||||
|
var scope = lookup.platformScope(req.getPlatform());
|
||||||
|
if (scope != null && scope.empty()) {
|
||||||
|
return PageResult.empty();
|
||||||
|
}
|
||||||
var query = Wrappers.<UserFavorite>lambdaQuery()
|
var query = Wrappers.<UserFavorite>lambdaQuery()
|
||||||
.eq(req.getUserId() != null, UserFavorite::getUserId, req.getUserId())
|
.eq(req.getUserId() != null, UserFavorite::getUserId, req.getUserId())
|
||||||
.in(userIds != null, UserFavorite::getUserId, userIds)
|
.in(userIds != null, UserFavorite::getUserId, userIds)
|
||||||
@@ -41,8 +47,22 @@ public class FavoriteAdminService {
|
|||||||
.eq(req.getDramaId() != null, UserFavorite::getDramaId, req.getDramaId())
|
.eq(req.getDramaId() != null, UserFavorite::getDramaId, req.getDramaId())
|
||||||
.in(dramaIds != null, UserFavorite::getDramaId, dramaIds)
|
.in(dramaIds != null, UserFavorite::getDramaId, dramaIds)
|
||||||
.ge(req.getStartTime() != null, UserFavorite::getCreatedAt, req.getStartTime())
|
.ge(req.getStartTime() != null, UserFavorite::getCreatedAt, req.getStartTime())
|
||||||
.le(req.getEndTime() != null, UserFavorite::getCreatedAt, req.getEndTime())
|
.le(req.getEndTime() != null, UserFavorite::getCreatedAt, req.getEndTime());
|
||||||
.orderByDesc(UserFavorite::getCreatedAt, UserFavorite::getId);
|
// orderBy 必须最后追加,否则条件会被拼到 ORDER BY 后面
|
||||||
|
if (scope != null) {
|
||||||
|
query.and(inner -> {
|
||||||
|
if (!scope.deviceIds().isEmpty()) {
|
||||||
|
inner.in(UserFavorite::getDeviceId, scope.deviceIds());
|
||||||
|
}
|
||||||
|
if (!scope.userIds().isEmpty()) {
|
||||||
|
if (!scope.deviceIds().isEmpty()) {
|
||||||
|
inner.or();
|
||||||
|
}
|
||||||
|
inner.in(UserFavorite::getUserId, scope.userIds());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
query.orderByDesc(UserFavorite::getCreatedAt, UserFavorite::getId);
|
||||||
var result = favoriteMapper.selectPage(lookup.page(req), query);
|
var result = favoriteMapper.selectPage(lookup.page(req), query);
|
||||||
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
|
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
|
||||||
}
|
}
|
||||||
@@ -53,17 +73,31 @@ public class FavoriteAdminService {
|
|||||||
}
|
}
|
||||||
Map<Long, AppUser> users = lookup.users(rows.stream().map(UserFavorite::getUserId).toList());
|
Map<Long, AppUser> users = lookup.users(rows.stream().map(UserFavorite::getUserId).toList());
|
||||||
Map<Long, Drama> dramas = lookup.dramas(rows.stream().map(UserFavorite::getDramaId).toList());
|
Map<Long, Drama> dramas = lookup.dramas(rows.stream().map(UserFavorite::getDramaId).toList());
|
||||||
|
Map<String, AppDeviceProfile> profiles =
|
||||||
|
lookup.deviceProfiles(rows.stream().map(UserFavorite::getDeviceId).toList());
|
||||||
|
Map<Long, AppUserSession> sessions =
|
||||||
|
lookup.latestSessions(rows.stream().map(UserFavorite::getUserId).toList());
|
||||||
return rows.stream().map(row -> toVo(row, row.getUserId() == null ? null : users.get(row.getUserId()),
|
return rows.stream().map(row -> toVo(row, row.getUserId() == null ? null : users.get(row.getUserId()),
|
||||||
row.getDramaId() == null ? null : dramas.get(row.getDramaId())))
|
row.getDramaId() == null ? null : dramas.get(row.getDramaId()),
|
||||||
|
row.getDeviceId() == null ? null : profiles.get(row.getDeviceId()),
|
||||||
|
row.getUserId() == null ? null : sessions.get(row.getUserId())))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private AdminFavoriteVO toVo(UserFavorite row, AppUser user, Drama drama) {
|
private AdminFavoriteVO toVo(UserFavorite row, AppUser user, Drama drama,
|
||||||
|
AppDeviceProfile profile, AppUserSession session) {
|
||||||
AdminFavoriteVO vo = new AdminFavoriteVO();
|
AdminFavoriteVO vo = new AdminFavoriteVO();
|
||||||
vo.setId(row.getId());
|
vo.setId(row.getId());
|
||||||
vo.setUserId(row.getUserId());
|
vo.setUserId(row.getUserId());
|
||||||
vo.setDeviceId(row.getDeviceId());
|
vo.setDeviceId(row.getDeviceId());
|
||||||
vo.setAnonymous(row.getUserId() == null);
|
vo.setAnonymous(row.getUserId() == null);
|
||||||
|
if (profile != null) {
|
||||||
|
vo.setPlatform(profile.getPlatform());
|
||||||
|
}
|
||||||
|
// 已登录用户的互动行不带 device_id,设备平台查不到时退回最近一次登录会话
|
||||||
|
if (!StringUtils.hasText(vo.getPlatform()) && session != null) {
|
||||||
|
vo.setPlatform(session.getPlatform());
|
||||||
|
}
|
||||||
vo.setDramaId(row.getDramaId());
|
vo.setDramaId(row.getDramaId());
|
||||||
vo.setCreatedAt(row.getCreatedAt());
|
vo.setCreatedAt(row.getCreatedAt());
|
||||||
if (user != null) {
|
if (user != null) {
|
||||||
|
|||||||
+43
-4
@@ -14,7 +14,9 @@ import com.fruitshorts.interaction.dal.entity.ContentComment;
|
|||||||
import com.fruitshorts.interaction.dal.entity.ContentLike;
|
import com.fruitshorts.interaction.dal.entity.ContentLike;
|
||||||
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
|
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
|
||||||
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
|
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||||
import com.fruitshorts.user.dal.entity.AppUser;
|
import com.fruitshorts.user.dal.entity.AppUser;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@@ -67,6 +69,23 @@ public class LikeAdminService {
|
|||||||
return PageResult.empty();
|
return PageResult.empty();
|
||||||
}
|
}
|
||||||
var query = buildQuery(req, users);
|
var query = buildQuery(req, users);
|
||||||
|
var scope = lookup.platformScope(req.getPlatform());
|
||||||
|
if (scope != null && scope.empty()) {
|
||||||
|
return PageResult.empty();
|
||||||
|
}
|
||||||
|
if (scope != null) {
|
||||||
|
query.and(inner -> {
|
||||||
|
if (!scope.deviceIds().isEmpty()) {
|
||||||
|
inner.in(ContentLike::getDeviceId, scope.deviceIds());
|
||||||
|
}
|
||||||
|
if (!scope.userIds().isEmpty()) {
|
||||||
|
if (!scope.deviceIds().isEmpty()) {
|
||||||
|
inner.or();
|
||||||
|
}
|
||||||
|
inner.in(ContentLike::getUserId, scope.userIds());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
if (req.getDramaId() != null) {
|
if (req.getDramaId() != null) {
|
||||||
query.and(q -> q.apply(DRAMA_MATCH, req.getDramaId()));
|
query.and(q -> q.apply(DRAMA_MATCH, req.getDramaId()));
|
||||||
}
|
}
|
||||||
@@ -80,6 +99,8 @@ public class LikeAdminService {
|
|||||||
if (req.getEpisodeId() != null) {
|
if (req.getEpisodeId() != null) {
|
||||||
query.and(q -> q.apply(EPISODE_MATCH, req.getEpisodeId()));
|
query.and(q -> q.apply(EPISODE_MATCH, req.getEpisodeId()));
|
||||||
}
|
}
|
||||||
|
// orderBy 必须最后追加,否则条件会被拼到 ORDER BY 后面
|
||||||
|
query.orderByDesc(ContentLike::getCreatedAt, ContentLike::getId);
|
||||||
var result = likeMapper.selectPage(lookup.page(req), query);
|
var result = likeMapper.selectPage(lookup.page(req), query);
|
||||||
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
|
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
|
||||||
}
|
}
|
||||||
@@ -92,8 +113,7 @@ public class LikeAdminService {
|
|||||||
.eq(StringUtils.hasText(req.getTargetType()), ContentLike::getTargetType, req.getTargetType())
|
.eq(StringUtils.hasText(req.getTargetType()), ContentLike::getTargetType, req.getTargetType())
|
||||||
.eq(req.getTargetId() != null, ContentLike::getTargetId, req.getTargetId())
|
.eq(req.getTargetId() != null, ContentLike::getTargetId, req.getTargetId())
|
||||||
.ge(req.getStartTime() != null, ContentLike::getCreatedAt, req.getStartTime())
|
.ge(req.getStartTime() != null, ContentLike::getCreatedAt, req.getStartTime())
|
||||||
.le(req.getEndTime() != null, ContentLike::getCreatedAt, req.getEndTime())
|
.le(req.getEndTime() != null, ContentLike::getCreatedAt, req.getEndTime());
|
||||||
.orderByDesc(ContentLike::getCreatedAt, ContentLike::getId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<AdminLikeVO> assemble(List<ContentLike> rows) {
|
private List<AdminLikeVO> assemble(List<ContentLike> rows) {
|
||||||
@@ -110,7 +130,13 @@ public class LikeAdminService {
|
|||||||
comments.values().stream().map(ContentComment::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
|
comments.values().stream().map(ContentComment::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
|
||||||
episodes.values().stream().map(DramaEpisode::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
|
episodes.values().stream().map(DramaEpisode::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
|
||||||
Map<Long, Drama> dramas = lookup.dramas(dramaIds);
|
Map<Long, Drama> dramas = lookup.dramas(dramaIds);
|
||||||
return rows.stream().map(row -> toVo(row, users, comments, episodes, dramas)).toList();
|
Map<String, AppDeviceProfile> profiles =
|
||||||
|
lookup.deviceProfiles(rows.stream().map(ContentLike::getDeviceId).toList());
|
||||||
|
Map<Long, AppUserSession> sessions =
|
||||||
|
lookup.latestSessions(rows.stream().map(ContentLike::getUserId).toList());
|
||||||
|
return rows.stream()
|
||||||
|
.map(row -> toVo(row, users, comments, episodes, dramas, profiles, sessions))
|
||||||
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Long> targetIds(List<ContentLike> rows, String type) {
|
private List<Long> targetIds(List<ContentLike> rows, String type) {
|
||||||
@@ -130,12 +156,25 @@ public class LikeAdminService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private AdminLikeVO toVo(ContentLike row, Map<Long, AppUser> users, Map<Long, ContentComment> comments,
|
private AdminLikeVO toVo(ContentLike row, Map<Long, AppUser> users, Map<Long, ContentComment> comments,
|
||||||
Map<Long, DramaEpisode> episodes, Map<Long, Drama> dramas) {
|
Map<Long, DramaEpisode> episodes, Map<Long, Drama> dramas,
|
||||||
|
Map<String, AppDeviceProfile> profiles,
|
||||||
|
Map<Long, AppUserSession> sessions) {
|
||||||
AdminLikeVO vo = new AdminLikeVO();
|
AdminLikeVO vo = new AdminLikeVO();
|
||||||
vo.setId(row.getId());
|
vo.setId(row.getId());
|
||||||
vo.setUserId(row.getUserId());
|
vo.setUserId(row.getUserId());
|
||||||
vo.setDeviceId(row.getDeviceId());
|
vo.setDeviceId(row.getDeviceId());
|
||||||
vo.setAnonymous(row.getUserId() == null);
|
vo.setAnonymous(row.getUserId() == null);
|
||||||
|
AppDeviceProfile profile = row.getDeviceId() == null ? null : profiles.get(row.getDeviceId());
|
||||||
|
if (profile != null) {
|
||||||
|
vo.setPlatform(profile.getPlatform());
|
||||||
|
}
|
||||||
|
// 已登录用户的互动行不带 device_id,设备平台查不到时退回最近一次登录会话
|
||||||
|
if (!StringUtils.hasText(vo.getPlatform()) && row.getUserId() != null) {
|
||||||
|
AppUserSession session = sessions.get(row.getUserId());
|
||||||
|
if (session != null) {
|
||||||
|
vo.setPlatform(session.getPlatform());
|
||||||
|
}
|
||||||
|
}
|
||||||
vo.setTargetType(row.getTargetType());
|
vo.setTargetType(row.getTargetType());
|
||||||
vo.setTargetId(row.getTargetId());
|
vo.setTargetId(row.getTargetId());
|
||||||
vo.setCreatedAt(row.getCreatedAt());
|
vo.setCreatedAt(row.getCreatedAt());
|
||||||
|
|||||||
+76
-15
@@ -8,6 +8,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
|||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.fruitshorts.admin.vo.AdminWatchHistoryVO;
|
import com.fruitshorts.admin.vo.AdminWatchHistoryVO;
|
||||||
import com.fruitshorts.admin.vo.WatchHistoryQueryReqVO;
|
import com.fruitshorts.admin.vo.WatchHistoryQueryReqVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
import com.fruitshorts.common.pojo.PageResult;
|
import com.fruitshorts.common.pojo.PageResult;
|
||||||
import com.fruitshorts.content.dal.entity.Drama;
|
import com.fruitshorts.content.dal.entity.Drama;
|
||||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||||
@@ -16,6 +18,7 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
|
|||||||
import com.fruitshorts.content.enums.ContentStatus;
|
import com.fruitshorts.content.enums.ContentStatus;
|
||||||
import com.fruitshorts.playback.dal.entity.WatchHistory;
|
import com.fruitshorts.playback.dal.entity.WatchHistory;
|
||||||
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
|
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
|
||||||
|
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||||
import com.fruitshorts.user.dal.entity.AppUser;
|
import com.fruitshorts.user.dal.entity.AppUser;
|
||||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||||
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||||
@@ -27,6 +30,7 @@ import java.util.ArrayList;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 后台观看记录分页与跨域装配。
|
* 后台观看记录分页与跨域装配。
|
||||||
@@ -42,6 +46,8 @@ public class WatchHistoryAdminService {
|
|||||||
private static final int DEFAULT_PAGE_SIZE = 10;
|
private static final int DEFAULT_PAGE_SIZE = 10;
|
||||||
private static final int MAX_PAGE_SIZE = 100;
|
private static final int MAX_PAGE_SIZE = 100;
|
||||||
private static final long FINISHED_TOLERANCE_MS = 1000L;
|
private static final long FINISHED_TOLERANCE_MS = 1000L;
|
||||||
|
private static final int MAX_LOOKUP_SIZE = 2000;
|
||||||
|
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
|
||||||
|
|
||||||
private final WatchHistoryMapper watchHistoryMapper;
|
private final WatchHistoryMapper watchHistoryMapper;
|
||||||
private final AppUserMapper appUserMapper;
|
private final AppUserMapper appUserMapper;
|
||||||
@@ -65,14 +71,19 @@ public class WatchHistoryAdminService {
|
|||||||
if (matchedDramaIds != null && matchedDramaIds.isEmpty()) {
|
if (matchedDramaIds != null && matchedDramaIds.isEmpty()) {
|
||||||
return emptyPage();
|
return emptyPage();
|
||||||
}
|
}
|
||||||
|
var scope = sessionSystem.platformScope(req.getPlatform());
|
||||||
|
if (scope != null && scope.empty()) {
|
||||||
|
return emptyPage();
|
||||||
|
}
|
||||||
IPage<WatchHistory> result = watchHistoryMapper.selectPage(new Page<>(pageIndex, pageSize),
|
IPage<WatchHistory> result = watchHistoryMapper.selectPage(new Page<>(pageIndex, pageSize),
|
||||||
buildQuery(req, matchedUserIds, matchedDramaIds));
|
buildQuery(req, matchedUserIds, matchedDramaIds, scope));
|
||||||
return new PageResult<>(result.getTotal(), toVoList(result.getRecords()));
|
return new PageResult<>(result.getTotal(), toVoList(result.getRecords()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private LambdaQueryWrapper<WatchHistory> buildQuery(WatchHistoryQueryReqVO req,
|
private LambdaQueryWrapper<WatchHistory> buildQuery(WatchHistoryQueryReqVO req,
|
||||||
List<Long> matchedUserIds,
|
List<Long> matchedUserIds,
|
||||||
List<Long> matchedDramaIds) {
|
List<Long> matchedDramaIds,
|
||||||
|
AppSessionSystemService.PlatformScope scope) {
|
||||||
LambdaQueryWrapper<WatchHistory> wrapper = Wrappers.<WatchHistory>lambdaQuery()
|
LambdaQueryWrapper<WatchHistory> wrapper = Wrappers.<WatchHistory>lambdaQuery()
|
||||||
.eq(req.getUserId() != null, WatchHistory::getUserId, req.getUserId())
|
.eq(req.getUserId() != null, WatchHistory::getUserId, req.getUserId())
|
||||||
.in(matchedUserIds != null, WatchHistory::getUserId, matchedUserIds)
|
.in(matchedUserIds != null, WatchHistory::getUserId, matchedUserIds)
|
||||||
@@ -82,6 +93,19 @@ public class WatchHistoryAdminService {
|
|||||||
.eq(StringUtils.hasText(req.getSource()), WatchHistory::getSource, req.getSource())
|
.eq(StringUtils.hasText(req.getSource()), WatchHistory::getSource, req.getSource())
|
||||||
.ge(req.getStartTime() != null, WatchHistory::getWatchedAt, req.getStartTime())
|
.ge(req.getStartTime() != null, WatchHistory::getWatchedAt, req.getStartTime())
|
||||||
.le(req.getEndTime() != null, WatchHistory::getWatchedAt, req.getEndTime());
|
.le(req.getEndTime() != null, WatchHistory::getWatchedAt, req.getEndTime());
|
||||||
|
if (scope != null) {
|
||||||
|
wrapper.and(inner -> {
|
||||||
|
if (!scope.deviceIds().isEmpty()) {
|
||||||
|
inner.in(WatchHistory::getDeviceId, scope.deviceIds());
|
||||||
|
}
|
||||||
|
if (!scope.userIds().isEmpty()) {
|
||||||
|
if (!scope.deviceIds().isEmpty()) {
|
||||||
|
inner.or();
|
||||||
|
}
|
||||||
|
inner.in(WatchHistory::getUserId, scope.userIds());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
applyFinished(wrapper, req.getFinished());
|
applyFinished(wrapper, req.getFinished());
|
||||||
return wrapper.orderByDesc(WatchHistory::getWatchedAt)
|
return wrapper.orderByDesc(WatchHistory::getWatchedAt)
|
||||||
.orderByDesc(WatchHistory::getId);
|
.orderByDesc(WatchHistory::getId);
|
||||||
@@ -100,24 +124,37 @@ public class WatchHistoryAdminService {
|
|||||||
|
|
||||||
private List<Long> searchUserIds(String keyword) {
|
private List<Long> searchUserIds(String keyword) {
|
||||||
String value = keyword.trim();
|
String value = keyword.trim();
|
||||||
return appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
|
List<Long> ids = appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
|
||||||
.select(AppUser::getId)
|
.select(AppUser::getId)
|
||||||
.and(query -> query.like(AppUser::getUid, value)
|
.and(query -> query.like(AppUser::getUid, value)
|
||||||
.or()
|
.or()
|
||||||
.like(AppUser::getNickname, value)))
|
.like(AppUser::getNickname, value))
|
||||||
|
.last("LIMIT " + LOOKUP_PROBE))
|
||||||
.stream()
|
.stream()
|
||||||
.map(AppUser::getId)
|
.map(AppUser::getId)
|
||||||
.toList();
|
.toList();
|
||||||
|
return ensureLookupSize(ids, "uid / 昵称");
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Long> searchDramaIds(String dramaTitle) {
|
private List<Long> searchDramaIds(String dramaTitle) {
|
||||||
String value = dramaTitle.trim();
|
String value = dramaTitle.trim();
|
||||||
return dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
|
List<Long> ids = dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
|
||||||
.select(Drama::getId)
|
.select(Drama::getId)
|
||||||
.like(Drama::getTitle, value))
|
.like(Drama::getTitle, value)
|
||||||
|
.last("LIMIT " + LOOKUP_PROBE))
|
||||||
.stream()
|
.stream()
|
||||||
.map(Drama::getId)
|
.map(Drama::getId)
|
||||||
.toList();
|
.toList();
|
||||||
|
return ensureLookupSize(ids, "短剧名称");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关键词命中过多时直接提示收窄条件,避免把整张表塞进 IN。 */
|
||||||
|
private List<Long> ensureLookupSize(List<Long> ids, String field) {
|
||||||
|
if (ids.size() > MAX_LOOKUP_SIZE) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST,
|
||||||
|
field + "命中超过 " + MAX_LOOKUP_SIZE + " 条,请使用更精确的筛选条件");
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<AdminWatchHistoryVO> toVoList(List<WatchHistory> rows) {
|
private List<AdminWatchHistoryVO> toVoList(List<WatchHistory> rows) {
|
||||||
@@ -129,19 +166,28 @@ public class WatchHistoryAdminService {
|
|||||||
Map<Long, DramaEpisode> episodes = loadEpisodes(rows);
|
Map<Long, DramaEpisode> episodes = loadEpisodes(rows);
|
||||||
Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser(
|
Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser(
|
||||||
rows.stream().map(WatchHistory::getUserId).distinct().toList());
|
rows.stream().map(WatchHistory::getUserId).distinct().toList());
|
||||||
|
Map<String, AppDeviceProfile> profiles = sessionSystem.deviceProfiles(
|
||||||
|
rows.stream().map(WatchHistory::getDeviceId).toList());
|
||||||
List<AdminWatchHistoryVO> list = new ArrayList<>(rows.size());
|
List<AdminWatchHistoryVO> list = new ArrayList<>(rows.size());
|
||||||
for (WatchHistory row : rows) {
|
for (WatchHistory row : rows) {
|
||||||
list.add(toVo(row, users.get(row.getUserId()), dramas.get(row.getDramaId()),
|
list.add(toVo(row, users.get(row.getUserId()), dramas.get(row.getDramaId()),
|
||||||
episodes.get(row.getEpisodeId()),
|
episodes.get(row.getEpisodeId()),
|
||||||
sessionSystem.match(sessions.get(row.getUserId()), row.getDeviceId())));
|
sessionSystem.match(sessions.get(row.getUserId()), row.getDeviceId()),
|
||||||
|
profiles.get(row.getDeviceId())));
|
||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<Long, AppUser> loadUsers(List<WatchHistory> rows) {
|
private Map<Long, AppUser> loadUsers(List<WatchHistory> rows) {
|
||||||
Map<Long, AppUser> result = new HashMap<>();
|
Map<Long, AppUser> result = new HashMap<>();
|
||||||
List<Long> ids = rows.stream().map(WatchHistory::getUserId).distinct().toList();
|
List<Long> ids = rows.stream().map(WatchHistory::getUserId).filter(Objects::nonNull).distinct().toList();
|
||||||
for (AppUser user : appUserMapper.selectBatchIds(ids)) {
|
if (ids.isEmpty()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
// 列表只需要身份展示字段,避免把整行用户资料拉回来
|
||||||
|
for (AppUser user : appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
|
||||||
|
.select(AppUser::getId, AppUser::getUid, AppUser::getNickname)
|
||||||
|
.in(AppUser::getId, ids))) {
|
||||||
result.put(user.getId(), user);
|
result.put(user.getId(), user);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
@@ -149,8 +195,13 @@ public class WatchHistoryAdminService {
|
|||||||
|
|
||||||
private Map<Long, Drama> loadDramas(List<WatchHistory> rows) {
|
private Map<Long, Drama> loadDramas(List<WatchHistory> rows) {
|
||||||
Map<Long, Drama> result = new HashMap<>();
|
Map<Long, Drama> result = new HashMap<>();
|
||||||
List<Long> ids = rows.stream().map(WatchHistory::getDramaId).distinct().toList();
|
List<Long> ids = rows.stream().map(WatchHistory::getDramaId).filter(Objects::nonNull).distinct().toList();
|
||||||
for (Drama drama : dramaMapper.selectBatchIds(ids)) {
|
if (ids.isEmpty()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
for (Drama drama : dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
|
||||||
|
.select(Drama::getId, Drama::getTitle, Drama::getStatus)
|
||||||
|
.in(Drama::getId, ids))) {
|
||||||
result.put(drama.getId(), drama);
|
result.put(drama.getId(), drama);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
@@ -158,15 +209,22 @@ public class WatchHistoryAdminService {
|
|||||||
|
|
||||||
private Map<Long, DramaEpisode> loadEpisodes(List<WatchHistory> rows) {
|
private Map<Long, DramaEpisode> loadEpisodes(List<WatchHistory> rows) {
|
||||||
Map<Long, DramaEpisode> result = new HashMap<>();
|
Map<Long, DramaEpisode> result = new HashMap<>();
|
||||||
List<Long> ids = rows.stream().map(WatchHistory::getEpisodeId).distinct().toList();
|
List<Long> ids = rows.stream().map(WatchHistory::getEpisodeId).filter(Objects::nonNull).distinct().toList();
|
||||||
for (DramaEpisode episode : dramaEpisodeMapper.selectBatchIds(ids)) {
|
if (ids.isEmpty()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
for (DramaEpisode episode : dramaEpisodeMapper.selectList(Wrappers.<DramaEpisode>lambdaQuery()
|
||||||
|
.select(DramaEpisode::getId, DramaEpisode::getDramaId,
|
||||||
|
DramaEpisode::getEpNo, DramaEpisode::getTitle)
|
||||||
|
.in(DramaEpisode::getId, ids))) {
|
||||||
result.put(episode.getId(), episode);
|
result.put(episode.getId(), episode);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama,
|
private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama,
|
||||||
DramaEpisode episode, AppUserSession session) {
|
DramaEpisode episode, AppUserSession session,
|
||||||
|
AppDeviceProfile profile) {
|
||||||
AdminWatchHistoryVO vo = new AdminWatchHistoryVO();
|
AdminWatchHistoryVO vo = new AdminWatchHistoryVO();
|
||||||
vo.setId(row.getId());
|
vo.setId(row.getId());
|
||||||
vo.setUserId(row.getUserId());
|
vo.setUserId(row.getUserId());
|
||||||
@@ -177,7 +235,10 @@ public class WatchHistoryAdminService {
|
|||||||
vo.setSource(row.getSource());
|
vo.setSource(row.getSource());
|
||||||
vo.setDeviceId(row.getDeviceId());
|
vo.setDeviceId(row.getDeviceId());
|
||||||
vo.setWatchedAt(row.getWatchedAt());
|
vo.setWatchedAt(row.getWatchedAt());
|
||||||
if (session != null) {
|
// 设备平台不依赖登录态,优先;没有记录(老数据)再回退到登录会话
|
||||||
|
if (profile != null && StringUtils.hasText(profile.getPlatform())) {
|
||||||
|
vo.setPlatform(profile.getPlatform());
|
||||||
|
} else if (session != null) {
|
||||||
vo.setPlatform(session.getPlatform());
|
vo.setPlatform(session.getPlatform());
|
||||||
vo.setOsVersion(session.getOsVersion());
|
vo.setOsVersion(session.getOsVersion());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ public class AdminFavoriteVO {
|
|||||||
private String uid;
|
private String uid;
|
||||||
private String nickname;
|
private String nickname;
|
||||||
private String deviceId;
|
private String deviceId;
|
||||||
|
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
|
||||||
|
private String platform;
|
||||||
private Boolean anonymous;
|
private Boolean anonymous;
|
||||||
private Long dramaId;
|
private Long dramaId;
|
||||||
private String dramaTitle;
|
private String dramaTitle;
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ public class AdminLikeVO {
|
|||||||
private String uid;
|
private String uid;
|
||||||
private String nickname;
|
private String nickname;
|
||||||
private String deviceId;
|
private String deviceId;
|
||||||
|
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
|
||||||
|
private String platform;
|
||||||
private Boolean anonymous;
|
private Boolean anonymous;
|
||||||
private Long dramaId;
|
private Long dramaId;
|
||||||
private String dramaTitle;
|
private String dramaTitle;
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ public class EngagementQueryReqVO {
|
|||||||
private String keyword;
|
private String keyword;
|
||||||
private Long userId;
|
private Long userId;
|
||||||
private String deviceId;
|
private String deviceId;
|
||||||
|
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制。 */
|
||||||
|
private String platform;
|
||||||
private String dramaTitle;
|
private String dramaTitle;
|
||||||
private Long dramaId;
|
private Long dramaId;
|
||||||
@DateTimeFormat(pattern = TIME_PATTERN)
|
@DateTimeFormat(pattern = TIME_PATTERN)
|
||||||
|
|||||||
+2
@@ -20,6 +20,8 @@ public class WatchHistoryQueryReqVO {
|
|||||||
private String dramaTitle;
|
private String dramaTitle;
|
||||||
private Long dramaId;
|
private Long dramaId;
|
||||||
private Long episodeId;
|
private Long episodeId;
|
||||||
|
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制。 */
|
||||||
|
private String platform;
|
||||||
private String source;
|
private String source;
|
||||||
private Boolean finished;
|
private Boolean finished;
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,12 @@ spring:
|
|||||||
url: ${DB_URL:jdbc:postgresql://127.0.0.1:5432/fruitshorts}
|
url: ${DB_URL:jdbc:postgresql://127.0.0.1:5432/fruitshorts}
|
||||||
username: ${DB_USER:fruitshorts}
|
username: ${DB_USER:fruitshorts}
|
||||||
password: ${DB_PASSWORD:fruitshorts}
|
password: ${DB_PASSWORD:fruitshorts}
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
# 与 app-api 共用同一个 Redis 实例;容器内必须显式指定 host,
|
||||||
|
# 否则 Spring Boot 默认连 127.0.0.1(容器内即自身)导致健康检查报 DOWN。
|
||||||
|
host: ${REDIS_HOST:127.0.0.1}
|
||||||
|
port: ${REDIS_PORT:6379}
|
||||||
jackson:
|
jackson:
|
||||||
date-format: yyyy-MM-dd HH:mm:ss
|
date-format: yyyy-MM-dd HH:mm:ss
|
||||||
time-zone: Asia/Shanghai
|
time-zone: Asia/Shanghai
|
||||||
@@ -40,20 +46,25 @@ mybatis-plus:
|
|||||||
datacenter-id: 1
|
datacenter-id: 1
|
||||||
|
|
||||||
fruitshorts:
|
fruitshorts:
|
||||||
|
web:
|
||||||
|
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
|
||||||
|
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
|
||||||
|
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
|
||||||
|
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
|
||||||
media:
|
media:
|
||||||
# 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads
|
# 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads
|
||||||
root-dir: ${MEDIA_ROOT_DIR:./data/uploads}
|
root-dir: ${MEDIA_ROOT_DIR:./data/uploads}
|
||||||
public-prefix: /files
|
public-prefix: /files
|
||||||
chunk-size: 5242880
|
chunk-size: 5242880
|
||||||
max-file-size: 2147483648
|
max-file-size: 2147483648
|
||||||
signature-secret: ${MEDIA_SIGNATURE_SECRET:fruitshorts-media-dev-secret-change-me-in-production-32b}
|
signature-secret: ${MEDIA_SIGNATURE_SECRET:}
|
||||||
signature-required: ${MEDIA_SIGNATURE_REQUIRED:false}
|
signature-required: ${MEDIA_SIGNATURE_REQUIRED:false}
|
||||||
signature-ttl-minutes: 15
|
signature-ttl-minutes: 15
|
||||||
jwt:
|
jwt:
|
||||||
# 双密钥都要外置:只配 admin 而漏配 app,生产会静默用 dev 默认值(prod fail-fast 会拦住)
|
# ⚠️ 所有环境必须注入 JWT_ADMIN_SECRET / JWT_APP_SECRET,不设任何代码级默认值
|
||||||
admin-secret: ${JWT_ADMIN_SECRET:fruitshorts-admin-dev-secret-change-me-in-production-32b}
|
admin-secret: ${JWT_ADMIN_SECRET:}
|
||||||
admin-ttl-hours: 12
|
admin-ttl-hours: 12
|
||||||
app-secret: ${JWT_APP_SECRET:fruitshorts-app-dev-secret-change-me-in-production-32bytes}
|
app-secret: ${JWT_APP_SECRET:}
|
||||||
app-access-ttl-minutes: 120
|
app-access-ttl-minutes: 120
|
||||||
app-refresh-ttl-days: 30
|
app-refresh-ttl-days: 30
|
||||||
cors:
|
cors:
|
||||||
|
|||||||
+5
@@ -32,6 +32,11 @@ class AdminPermissionAnnotationTest {
|
|||||||
assertThat(permissionsOf(NoticeAdminController.class))
|
assertThat(permissionsOf(NoticeAdminController.class))
|
||||||
.containsExactlyInAnyOrder("notice:list", "notice:list",
|
.containsExactlyInAnyOrder("notice:list", "notice:list",
|
||||||
"notice:update", "notice:update", "notice:update", "notice:update");
|
"notice:update", "notice:update", "notice:update", "notice:update");
|
||||||
|
assertThat(permissionsOf(RewardAdminController.class))
|
||||||
|
.containsExactlyInAnyOrder("reward:list", "reward:list", "reward:update",
|
||||||
|
"reward:update", "reward:update", "reward:checkin", "reward:checkin",
|
||||||
|
"reward:grant", "reward:grant", "reward:list", "reward:list",
|
||||||
|
"reward:update", "reward:update", "reward:update");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 收集控制器里所有映射方法的 @PreAuthorize 权限点(缺失则记为 MISSING,便于断言直接看到)。 */
|
/** 收集控制器里所有映射方法的 @PreAuthorize 权限点(缺失则记为 MISSING,便于断言直接看到)。 */
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
/** 观看记录匹配登录系统。 */
|
/** 观看记录匹配登录系统。 */
|
||||||
class AppSessionSystemServiceTest {
|
class AppSessionSystemServiceTest {
|
||||||
|
|
||||||
private final AppSessionSystemService service = new AppSessionSystemService(null);
|
private final AppSessionSystemService service = new AppSessionSystemService(null, null);
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void should_use_same_device_session_when_watch_history_has_device() {
|
void should_use_same_device_session_when_watch_history_has_device() {
|
||||||
|
|||||||
+4
-3
@@ -199,9 +199,10 @@ class WatchHistoryAdminServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void stubBatchData() {
|
private void stubBatchData() {
|
||||||
given(appUserMapper.selectBatchIds(any())).willReturn(List.of(user(7L, "Alice")));
|
// 装配阶段按需列查询,而不是 selectBatchIds,桩法要跟着改
|
||||||
given(dramaMapper.selectBatchIds(any())).willReturn(List.of(drama(5L, "Signal")));
|
given(appUserMapper.selectList(any())).willReturn(List.of(user(7L, "Alice")));
|
||||||
given(dramaEpisodeMapper.selectBatchIds(any())).willReturn(List.of(episode(11L)));
|
given(dramaMapper.selectList(any())).willReturn(List.of(drama(5L, "Signal")));
|
||||||
|
given(dramaEpisodeMapper.selectList(any())).willReturn(List.of(episode(11L)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
|||||||
+3
-1
@@ -30,7 +30,9 @@ public final class ControllerContractSupport {
|
|||||||
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
|
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static MockMvc mockMvcOf(Object controller) {
|
public static MockMvc mockMvcOf(Object controller) {
|
||||||
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class));
|
AccessDeniedRecorder recorder = new AccessDeniedRecorder(
|
||||||
|
Mockito.mock(ObjectProvider.class),
|
||||||
|
Mockito.mock(ObjectProvider.class));
|
||||||
return MockMvcBuilders.standaloneSetup(controller)
|
return MockMvcBuilders.standaloneSetup(controller)
|
||||||
.setControllerAdvice(new GlobalExceptionHandler(recorder))
|
.setControllerAdvice(new GlobalExceptionHandler(recorder))
|
||||||
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
|
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
|
||||||
|
|||||||
+6
-4
@@ -35,13 +35,14 @@ public class AppAuthController {
|
|||||||
|
|
||||||
private final AppOtpService otpService;
|
private final AppOtpService otpService;
|
||||||
private final AppAuthService authService;
|
private final AppAuthService authService;
|
||||||
|
private final WebUtils webUtils;
|
||||||
|
|
||||||
/** 发送验证码。频控在服务端,客户端不需要自己限流。 */
|
/** 发送验证码。频控在服务端,客户端不需要自己限流。 */
|
||||||
@Operation(summary = "发送验证码(频控在服务端)")
|
@Operation(summary = "发送验证码(频控在服务端)")
|
||||||
@RateLimit(limit = 20, windowSeconds = 60, key = "otp")
|
@RateLimit(limit = 20, windowSeconds = 60, key = "otp")
|
||||||
@PostMapping("/otp")
|
@PostMapping("/otp")
|
||||||
public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) {
|
public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) {
|
||||||
otpService.send(req, WebUtils.getClientIp(request));
|
otpService.send(req, webUtils.clientIp(request));
|
||||||
return Result.ok();
|
return Result.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ public class AppAuthController {
|
|||||||
public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req,
|
public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req,
|
||||||
HttpServletRequest request) {
|
HttpServletRequest request) {
|
||||||
applyHeaderDeviceId(req, request);
|
applyHeaderDeviceId(req, request);
|
||||||
return Result.ok(authService.register(req, WebUtils.getClientIp(request)));
|
return Result.ok(authService.register(req, webUtils.clientIp(request)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "登录(验证码或密码)")
|
@Operation(summary = "登录(验证码或密码)")
|
||||||
@@ -59,7 +60,7 @@ public class AppAuthController {
|
|||||||
public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req,
|
public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req,
|
||||||
HttpServletRequest request) {
|
HttpServletRequest request) {
|
||||||
applyHeaderDeviceId(req, request);
|
applyHeaderDeviceId(req, request);
|
||||||
return Result.ok(authService.login(req, WebUtils.getClientIp(request)));
|
return Result.ok(authService.login(req, webUtils.clientIp(request)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)")
|
@Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)")
|
||||||
@@ -69,7 +70,8 @@ public class AppAuthController {
|
|||||||
String headerDeviceId = request.getHeader("X-Device-Id");
|
String headerDeviceId = request.getHeader("X-Device-Id");
|
||||||
String deviceId = StringUtils.hasText(headerDeviceId)
|
String deviceId = StringUtils.hasText(headerDeviceId)
|
||||||
? headerDeviceId : req.getDeviceId();
|
? headerDeviceId : req.getDeviceId();
|
||||||
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId));
|
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId,
|
||||||
|
webUtils.clientIp(request)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
|
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
|
||||||
|
|||||||
+9
@@ -3,11 +3,13 @@
|
|||||||
package com.fruitshorts.app.controller;
|
package com.fruitshorts.app.controller;
|
||||||
|
|
||||||
import com.fruitshorts.app.service.AppCatalogService;
|
import com.fruitshorts.app.service.AppCatalogService;
|
||||||
|
import com.fruitshorts.app.service.AppRankingService;
|
||||||
import com.fruitshorts.app.vo.AppCategoryVO;
|
import com.fruitshorts.app.vo.AppCategoryVO;
|
||||||
import com.fruitshorts.app.vo.AppDramaPageReqVO;
|
import com.fruitshorts.app.vo.AppDramaPageReqVO;
|
||||||
import com.fruitshorts.app.vo.AppFeedVO;
|
import com.fruitshorts.app.vo.AppFeedVO;
|
||||||
import com.fruitshorts.app.vo.AppDramaCardVO;
|
import com.fruitshorts.app.vo.AppDramaCardVO;
|
||||||
import com.fruitshorts.app.vo.AppPlaylistDetailVO;
|
import com.fruitshorts.app.vo.AppPlaylistDetailVO;
|
||||||
|
import com.fruitshorts.app.vo.AppRankingVO;
|
||||||
import com.fruitshorts.common.pojo.CursorResult;
|
import com.fruitshorts.common.pojo.CursorResult;
|
||||||
import com.fruitshorts.common.pojo.PageResult;
|
import com.fruitshorts.common.pojo.PageResult;
|
||||||
import com.fruitshorts.common.pojo.Result;
|
import com.fruitshorts.common.pojo.Result;
|
||||||
@@ -37,6 +39,7 @@ public class AppCatalogController {
|
|||||||
private static final int DRAMA_PAGE_SIZE = 20;
|
private static final int DRAMA_PAGE_SIZE = 20;
|
||||||
|
|
||||||
private final AppCatalogService appCatalogService;
|
private final AppCatalogService appCatalogService;
|
||||||
|
private final AppRankingService appRankingService;
|
||||||
|
|
||||||
@Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页")
|
@Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页")
|
||||||
@GetMapping("/home/feed")
|
@GetMapping("/home/feed")
|
||||||
@@ -75,6 +78,12 @@ public class AppCatalogController {
|
|||||||
return Result.ok(appCatalogService.categoryDramas(id, pageIndex, pageSize));
|
return Result.ok(appCatalogService.categoryDramas(id, pageIndex, pageSize));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "推荐榜:按后台配置顺序返回榜单快照")
|
||||||
|
@GetMapping("/categories/{id}/ranking")
|
||||||
|
public Result<AppRankingVO> categoryRanking(@PathVariable Long id) {
|
||||||
|
return Result.ok(appRankingService.ranking(id));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "已启用类型")
|
@Operation(summary = "已启用类型")
|
||||||
@GetMapping("/drama-categories")
|
@GetMapping("/drama-categories")
|
||||||
public Result<List<AppCategoryVO>> dramaCategories() {
|
public Result<List<AppCategoryVO>> dramaCategories() {
|
||||||
|
|||||||
+2
-1
@@ -48,6 +48,7 @@ public class AppCommentController {
|
|||||||
private final EpisodeService episodeService;
|
private final EpisodeService episodeService;
|
||||||
private final InteractionIdentityResolver identityResolver;
|
private final InteractionIdentityResolver identityResolver;
|
||||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||||
|
private final WebUtils webUtils;
|
||||||
|
|
||||||
@Operation(summary = "发布评论")
|
@Operation(summary = "发布评论")
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@@ -59,7 +60,7 @@ public class AppCommentController {
|
|||||||
req.getDeviceId());
|
req.getDeviceId());
|
||||||
anonymousRateLimiter.check(identity, "comment");
|
anonymousRateLimiter.check(identity, "comment");
|
||||||
return Result.ok(commentService.publish(
|
return Result.ok(commentService.publish(
|
||||||
identity, req, WebUtils.getClientIp(request)));
|
identity, req, webUtils.clientIp(request)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "评论列表(游标翻页,可匿名浏览)")
|
@Operation(summary = "评论列表(游标翻页,可匿名浏览)")
|
||||||
|
|||||||
+11
-2
@@ -7,12 +7,14 @@ import com.fruitshorts.commerce.service.OrderService;
|
|||||||
import com.fruitshorts.commerce.service.ProductService;
|
import com.fruitshorts.commerce.service.ProductService;
|
||||||
import com.fruitshorts.commerce.service.UnlockService;
|
import com.fruitshorts.commerce.service.UnlockService;
|
||||||
import com.fruitshorts.commerce.service.WalletService;
|
import com.fruitshorts.commerce.service.WalletService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardTaskService;
|
||||||
import com.fruitshorts.commerce.vo.ProductRespVO;
|
import com.fruitshorts.commerce.vo.ProductRespVO;
|
||||||
import com.fruitshorts.common.pojo.Result;
|
import com.fruitshorts.common.pojo.Result;
|
||||||
import com.fruitshorts.framework.security.SecurityUtils;
|
import com.fruitshorts.framework.security.SecurityUtils;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
@@ -41,6 +43,8 @@ public class AppCommerceController {
|
|||||||
private final UnlockService unlockService;
|
private final UnlockService unlockService;
|
||||||
private final OrderService orderService;
|
private final OrderService orderService;
|
||||||
private final ProductService productService;
|
private final ProductService productService;
|
||||||
|
@Autowired(required = false)
|
||||||
|
private RewardTaskService rewardTaskService;
|
||||||
|
|
||||||
/** 我的钱包:余额 + 最近流水,客户端一处渲染。 */
|
/** 我的钱包:余额 + 最近流水,客户端一处渲染。 */
|
||||||
@Operation(summary = "我的钱包(余额 + 最近流水)")
|
@Operation(summary = "我的钱包(余额 + 最近流水)")
|
||||||
@@ -92,9 +96,14 @@ public class AppCommerceController {
|
|||||||
@Operation(summary = "提交商店票据(校验后建单并发权益,重复提交幂等)")
|
@Operation(summary = "提交商店票据(校验后建单并发权益,重复提交幂等)")
|
||||||
@PostMapping("/orders/verify")
|
@PostMapping("/orders/verify")
|
||||||
public Result<Orders> verify(@RequestBody Map<String, String> body) {
|
public Result<Orders> verify(@RequestBody Map<String, String> body) {
|
||||||
return Result.ok(orderService.verifyAndDeliver(SecurityUtils.getAppUserId(),
|
Orders order = orderService.verifyAndDeliver(SecurityUtils.getAppUserId(),
|
||||||
body.getOrDefault("platform", ""),
|
body.getOrDefault("platform", ""),
|
||||||
body.getOrDefault("productId", ""),
|
body.getOrDefault("productId", ""),
|
||||||
body.getOrDefault("receipt", "")));
|
body.getOrDefault("receipt", ""));
|
||||||
|
if (rewardTaskService != null && OrderService.STATUS_DELIVERED.equals(order.getStatus())) {
|
||||||
|
rewardTaskService.recordEvent(order.getUserId(), RewardTaskService.TYPE_FIRST_PURCHASE,
|
||||||
|
order.getOrderNo(), 1L);
|
||||||
|
}
|
||||||
|
return Result.ok(order);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -37,6 +37,7 @@ public class AppDramaController {
|
|||||||
private final EpisodeService episodeService;
|
private final EpisodeService episodeService;
|
||||||
private final CommentService commentService;
|
private final CommentService commentService;
|
||||||
private final AppEpisodeStatsService appEpisodeStatsService;
|
private final AppEpisodeStatsService appEpisodeStatsService;
|
||||||
|
private final WebUtils webUtils;
|
||||||
|
|
||||||
/** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */
|
/** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */
|
||||||
@Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)")
|
@Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)")
|
||||||
@@ -56,7 +57,7 @@ public class AppDramaController {
|
|||||||
SecurityUtils.getUserIdOrNull(),
|
SecurityUtils.getUserIdOrNull(),
|
||||||
id,
|
id,
|
||||||
request.getHeader("X-Device-Id"),
|
request.getHeader("X-Device-Id"),
|
||||||
WebUtils.getClientIp(request));
|
webUtils.clientIp(request));
|
||||||
DramaEpisode episode = episodeService.getExisting(id);
|
DramaEpisode episode = episodeService.getExisting(id);
|
||||||
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
|
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
|
||||||
vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L));
|
vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L));
|
||||||
|
|||||||
+2
-1
@@ -25,11 +25,12 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
public class AppEventController {
|
public class AppEventController {
|
||||||
|
|
||||||
private final AppEventService eventService;
|
private final AppEventService eventService;
|
||||||
|
private final WebUtils webUtils;
|
||||||
|
|
||||||
@Operation(summary = "埋点事件批量上报")
|
@Operation(summary = "埋点事件批量上报")
|
||||||
@PostMapping("/events")
|
@PostMapping("/events")
|
||||||
public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) {
|
public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) {
|
||||||
eventService.save(req, SecurityUtils.getUserIdOrNull(), WebUtils.getClientIp(request));
|
eventService.save(req, SecurityUtils.getUserIdOrNull(), webUtils.clientIp(request));
|
||||||
return Result.ok();
|
return Result.ok();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+13
-1
@@ -9,16 +9,19 @@ import com.fruitshorts.user.service.AppUserService;
|
|||||||
import com.fruitshorts.user.vo.AppUserRespVO;
|
import com.fruitshorts.user.vo.AppUserRespVO;
|
||||||
import com.fruitshorts.user.vo.DeactivateReqVO;
|
import com.fruitshorts.user.vo.DeactivateReqVO;
|
||||||
import com.fruitshorts.user.vo.ProfileUpdateReqVO;
|
import com.fruitshorts.user.vo.ProfileUpdateReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardTaskService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -32,6 +35,8 @@ import java.util.Map;
|
|||||||
public class AppMeController {
|
public class AppMeController {
|
||||||
|
|
||||||
private final AppUserService userService;
|
private final AppUserService userService;
|
||||||
|
@Autowired(required = false)
|
||||||
|
private RewardTaskService rewardTaskService;
|
||||||
|
|
||||||
@Operation(summary = "我的资料")
|
@Operation(summary = "我的资料")
|
||||||
@GetMapping
|
@GetMapping
|
||||||
@@ -42,7 +47,14 @@ public class AppMeController {
|
|||||||
@Operation(summary = "修改资料(昵称 / 头像 / 语言等)")
|
@Operation(summary = "修改资料(昵称 / 头像 / 语言等)")
|
||||||
@PutMapping
|
@PutMapping
|
||||||
public Result<AppUserRespVO> update(@Valid @RequestBody ProfileUpdateReqVO req) {
|
public Result<AppUserRespVO> update(@Valid @RequestBody ProfileUpdateReqVO req) {
|
||||||
return Result.ok(userService.updateProfile(SecurityUtils.getAppUserId(), req));
|
Long userId = SecurityUtils.getAppUserId();
|
||||||
|
AppUserRespVO profile = userService.updateProfile(userId, req);
|
||||||
|
if (rewardTaskService != null && StringUtils.hasText(profile.getNickname())
|
||||||
|
&& StringUtils.hasText(profile.getAvatarUrl())) {
|
||||||
|
rewardTaskService.recordEvent(userId, RewardTaskService.TYPE_COMPLETE_PROFILE,
|
||||||
|
userId.toString(), 1L);
|
||||||
|
}
|
||||||
|
return Result.ok(profile);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "我的登录设备列表")
|
@Operation(summary = "我的登录设备列表")
|
||||||
|
|||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.controller;
|
||||||
|
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardCheckinService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardGrantService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardTaskService;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardClaimRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardOverviewVO;
|
||||||
|
import com.fruitshorts.common.pojo.Result;
|
||||||
|
import com.fruitshorts.commerce.service.WalletService;
|
||||||
|
import com.fruitshorts.framework.security.SecurityUtils;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 客户端奖励中心:总览、签到、任务领取与活动。 */
|
||||||
|
@Tag(name = "客户端-奖励中心")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/app/rewards")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AppRewardController {
|
||||||
|
|
||||||
|
private final RewardTaskService taskService;
|
||||||
|
private final RewardCheckinService checkinService;
|
||||||
|
private final RewardGrantService grantService;
|
||||||
|
private final WalletService walletService;
|
||||||
|
|
||||||
|
@Operation(summary = "奖励中心总览")
|
||||||
|
@GetMapping("/overview")
|
||||||
|
public Result<RewardOverviewVO> overview(@RequestParam(required = false) String locale) {
|
||||||
|
Long userId = SecurityUtils.getAppUserIdOrNull();
|
||||||
|
long coinBalance = userId == null ? 0L : walletService.getOrCreate(userId).getCoinBalance();
|
||||||
|
RewardOverviewVO overview = taskService.overview(
|
||||||
|
userId, locale, coinBalance);
|
||||||
|
overview.setCheckin(checkinService.status(userId));
|
||||||
|
return Result.ok(overview);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "奖励活动列表")
|
||||||
|
@GetMapping("/activities")
|
||||||
|
public Result<List<RewardActivityVO>> activities(@RequestParam(required = false) String locale) {
|
||||||
|
return Result.ok(taskService.activities(locale));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "签到状态")
|
||||||
|
@GetMapping("/check-in")
|
||||||
|
public Result<RewardCheckinVO> checkInStatus() {
|
||||||
|
return Result.ok(checkinService.status(SecurityUtils.getAppUserId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "执行签到")
|
||||||
|
@PostMapping("/check-in")
|
||||||
|
public Result<RewardCheckinRespVO> checkIn() {
|
||||||
|
return Result.ok(checkinService.checkIn(SecurityUtils.getAppUserId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "领取已完成任务奖励")
|
||||||
|
@PostMapping("/tasks/{taskId}/claim")
|
||||||
|
public Result<RewardClaimRespVO> claim(
|
||||||
|
@Parameter(description = "奖励任务 ID") @PathVariable Long taskId) {
|
||||||
|
Long userId = SecurityUtils.getAppUserId();
|
||||||
|
var task = taskService.getExisting(taskId);
|
||||||
|
return Result.ok(grantService.claim(userId, task, taskService.currentProgress(userId, task)));
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-1
@@ -9,6 +9,7 @@ import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
|||||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||||
import com.fruitshorts.framework.security.SecurityUtils;
|
import com.fruitshorts.framework.security.SecurityUtils;
|
||||||
import com.fruitshorts.playback.service.WatchProgressService;
|
import com.fruitshorts.playback.service.WatchProgressService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardTaskService;
|
||||||
import com.fruitshorts.playback.vo.ProgressRespVO;
|
import com.fruitshorts.playback.vo.ProgressRespVO;
|
||||||
import com.fruitshorts.playback.vo.ProgressSaveReqVO;
|
import com.fruitshorts.playback.vo.ProgressSaveReqVO;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
@@ -16,6 +17,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
|||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
@@ -33,6 +35,8 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
public class AppWatchController {
|
public class AppWatchController {
|
||||||
|
|
||||||
private final WatchProgressService progressService;
|
private final WatchProgressService progressService;
|
||||||
|
@Autowired(required = false)
|
||||||
|
private RewardTaskService rewardTaskService;
|
||||||
private final InteractionIdentityResolver identityResolver;
|
private final InteractionIdentityResolver identityResolver;
|
||||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||||
|
|
||||||
@@ -46,7 +50,12 @@ public class AppWatchController {
|
|||||||
request.getHeader("X-Device-Id"),
|
request.getHeader("X-Device-Id"),
|
||||||
req.getDeviceId());
|
req.getDeviceId());
|
||||||
anonymousRateLimiter.check(identity, "watch");
|
anonymousRateLimiter.check(identity, "watch");
|
||||||
return Result.ok(progressService.save(identity, req));
|
ProgressRespVO saved = progressService.save(identity, req);
|
||||||
|
if (rewardTaskService != null && identity.authenticated()) {
|
||||||
|
rewardTaskService.recordWatch(identity.userId(), saved.getEpisodeId(),
|
||||||
|
saved.getPositionMs(), Boolean.TRUE.equals(saved.getFinished()));
|
||||||
|
}
|
||||||
|
return Result.ok(saved);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 某部剧的续看位置,进详情页时用它决定"续看第 N 集"。 */
|
/** 某部剧的续看位置,进详情页时用它决定"续看第 N 集"。 */
|
||||||
|
|||||||
+18
-18
@@ -34,7 +34,6 @@ import org.springframework.stereotype.Service;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
@@ -93,6 +92,11 @@ public class AppCatalogService {
|
|||||||
c.getNameLocales(), c.getName(), c.getNameEn(), c.getNameId());
|
c.getNameLocales(), c.getName(), c.getNameEn(), c.getNameId());
|
||||||
AppCategoryVO vo = new AppCategoryVO(c.getId(), ContentLocaleTexts.value(locales, ContentLocaleTexts.ZH));
|
AppCategoryVO vo = new AppCategoryVO(c.getId(), ContentLocaleTexts.value(locales, ContentLocaleTexts.ZH));
|
||||||
vo.setLocales(locales);
|
vo.setLocales(locales);
|
||||||
|
vo.setCode(c.getCode());
|
||||||
|
vo.setLayoutType(c.getLayoutType() == null
|
||||||
|
? DramaClassificationService.LAYOUT_GRID
|
||||||
|
: c.getLayoutType());
|
||||||
|
vo.setRevision(c.getRevision() == null ? 1L : c.getRevision());
|
||||||
return vo;
|
return vo;
|
||||||
})
|
})
|
||||||
.toList();
|
.toList();
|
||||||
@@ -206,6 +210,7 @@ public class AppCatalogService {
|
|||||||
detail.setTitleLocales(titles);
|
detail.setTitleLocales(titles);
|
||||||
detail.setSynopsisLocales(synopses);
|
detail.setSynopsisLocales(synopses);
|
||||||
detail.setCover(drama.getCoverUrl());
|
detail.setCover(drama.getCoverUrl());
|
||||||
|
detail.setCoverLandscape(drama.getHorizontalCoverUrl());
|
||||||
detail.setTypes(types);
|
detail.setTypes(types);
|
||||||
fillDetailTag(detail, drama);
|
fillDetailTag(detail, drama);
|
||||||
detail.setTotalEpisodes(drama.getTotalEpisodes());
|
detail.setTotalEpisodes(drama.getTotalEpisodes());
|
||||||
@@ -348,7 +353,8 @@ public class AppCatalogService {
|
|||||||
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
|
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
|
||||||
card.setTitleLocales(titles);
|
card.setTitleLocales(titles);
|
||||||
card.setCover(drama.getCoverUrl());
|
card.setCover(drama.getCoverUrl());
|
||||||
card.setSynopsisLocales(shortLocales(synopses));
|
card.setCoverLandscape(drama.getHorizontalCoverUrl());
|
||||||
|
card.setSynopsisLocales(synopses);
|
||||||
card.setTypes(types);
|
card.setTypes(types);
|
||||||
fillTag(card, drama, tags);
|
fillTag(card, drama, tags);
|
||||||
card.setTotalEpisodes(drama.getTotalEpisodes());
|
card.setTotalEpisodes(drama.getTotalEpisodes());
|
||||||
@@ -411,6 +417,7 @@ public class AppCatalogService {
|
|||||||
ContentTag tag = tagOf(drama, tags);
|
ContentTag tag = tagOf(drama, tags);
|
||||||
Map<String, String> locales = tagLocales(tag);
|
Map<String, String> locales = tagLocales(tag);
|
||||||
card.setTagLocales(locales);
|
card.setTagLocales(locales);
|
||||||
|
card.setTagCode(tagCode(tag));
|
||||||
card.setTagColor(tag == null ? "" : tag.getBgColor());
|
card.setTagColor(tag == null ? "" : tag.getBgColor());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -418,9 +425,18 @@ public class AppCatalogService {
|
|||||||
ContentTag tag = tagOf(drama, loadTags(List.of(drama)));
|
ContentTag tag = tagOf(drama, loadTags(List.of(drama)));
|
||||||
Map<String, String> locales = tagLocales(tag);
|
Map<String, String> locales = tagLocales(tag);
|
||||||
detail.setTagLocales(locales);
|
detail.setTagLocales(locales);
|
||||||
|
detail.setTagCode(tagCode(tag));
|
||||||
detail.setTagColor(tag == null ? "" : tag.getBgColor());
|
detail.setTagColor(tag == null ? "" : tag.getBgColor());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 语义码直接下发,客户端据此判断板块;未配置时给空串,由客户端按文案兜底。 */
|
||||||
|
private String tagCode(ContentTag tag) {
|
||||||
|
if (tag == null || tag.getCode() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return tag.getCode().trim();
|
||||||
|
}
|
||||||
|
|
||||||
private ContentTag tagOf(Drama drama, Map<Long, ContentTag> tags) {
|
private ContentTag tagOf(Drama drama, Map<Long, ContentTag> tags) {
|
||||||
if (drama.getTagId() == null || drama.getTagId() <= 0L) {
|
if (drama.getTagId() == null || drama.getTagId() <= 0L) {
|
||||||
return null;
|
return null;
|
||||||
@@ -439,20 +455,4 @@ public class AppCatalogService {
|
|||||||
return dramaCategoryService.localeMap();
|
return dramaCategoryService.localeMap();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 卡片只带一句简介,避免列表响应体过大 */
|
|
||||||
private Map<String, String> shortLocales(Map<String, String> locales) {
|
|
||||||
Map<String, String> result = new LinkedHashMap<>();
|
|
||||||
if (locales == null) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
locales.forEach((code, text) -> result.put(code, shortSynopsis(text)));
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String shortSynopsis(String synopsis) {
|
|
||||||
if (synopsis == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return synopsis.length() <= 60 ? synopsis : synopsis.substring(0, 60);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -35,6 +35,7 @@ public class AppConfigService {
|
|||||||
KEYS.put("noticeEnabled", new KeySpec("app.notice.enabled", "true"));
|
KEYS.put("noticeEnabled", new KeySpec("app.notice.enabled", "true"));
|
||||||
KEYS.put("coinUnlockEnabled", new KeySpec("app.coin.unlock.enabled", "true"));
|
KEYS.put("coinUnlockEnabled", new KeySpec("app.coin.unlock.enabled", "true"));
|
||||||
KEYS.put("downloadEnabled", new KeySpec("app.download.enabled", "true"));
|
KEYS.put("downloadEnabled", new KeySpec("app.download.enabled", "true"));
|
||||||
|
KEYS.put("loginBackgroundUrl", new KeySpec("app.login.background.url", ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
private final SysConfigMapper sysConfigMapper;
|
private final SysConfigMapper sysConfigMapper;
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.service;
|
||||||
|
|
||||||
|
import com.fruitshorts.app.vo.AppDramaCardVO;
|
||||||
|
import com.fruitshorts.app.vo.AppRankingEntryVO;
|
||||||
|
import com.fruitshorts.app.vo.AppRankingVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import com.fruitshorts.content.dal.entity.Drama;
|
||||||
|
import com.fruitshorts.content.service.ContentLocaleTexts;
|
||||||
|
import com.fruitshorts.content.service.DramaClassificationService;
|
||||||
|
import com.fruitshorts.content.service.DramaService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** C 端推荐榜快照组装。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AppRankingService {
|
||||||
|
|
||||||
|
private static final int MAX_RANKING_ITEMS = 50;
|
||||||
|
|
||||||
|
private final DramaClassificationService classificationService;
|
||||||
|
private final DramaService dramaService;
|
||||||
|
private final AppCatalogService catalogService;
|
||||||
|
|
||||||
|
/** 过滤未上线短剧后保持后台位置,排名连续补齐。 */
|
||||||
|
public AppRankingVO ranking(Long classificationId) {
|
||||||
|
var classification = classificationService.getEnabledById(classificationId);
|
||||||
|
if (!DramaClassificationService.LAYOUT_RANKING.equals(classification.getLayoutType())) {
|
||||||
|
throw new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED, "该分类不是推荐榜");
|
||||||
|
}
|
||||||
|
List<Long> ids = classificationService.listDramaIdsByClassification(classificationId);
|
||||||
|
List<Drama> ordered = orderedPublished(ids).stream().limit(MAX_RANKING_ITEMS).toList();
|
||||||
|
List<AppDramaCardVO> cards = catalogService.toCards(ordered);
|
||||||
|
List<AppRankingEntryVO> entries = entries(cards);
|
||||||
|
Map<String, String> locales = ContentLocaleTexts.read(
|
||||||
|
classification.getNameLocales(), classification.getName(),
|
||||||
|
classification.getNameEn(), classification.getNameId());
|
||||||
|
AppRankingVO ranking = new AppRankingVO();
|
||||||
|
ranking.setId(classification.getId());
|
||||||
|
ranking.setCode(classification.getCode());
|
||||||
|
ranking.setLocales(locales);
|
||||||
|
ranking.setRevision(classification.getRevision() == null ? 1L : classification.getRevision());
|
||||||
|
ranking.setGeneratedAt(classification.getUpdatedAt());
|
||||||
|
ranking.setTotal(entries.size());
|
||||||
|
ranking.setList(entries);
|
||||||
|
return ranking;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AppRankingEntryVO> entries(List<AppDramaCardVO> cards) {
|
||||||
|
List<AppRankingEntryVO> entries = new ArrayList<>();
|
||||||
|
for (int index = 0; index < cards.size(); index++) {
|
||||||
|
entries.add(new AppRankingEntryVO(index + 1, cards.get(index)));
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Drama> orderedPublished(List<Long> ids) {
|
||||||
|
if (ids.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
Map<Long, Integer> positions = new HashMap<>();
|
||||||
|
for (int index = 0; index < ids.size(); index++) {
|
||||||
|
positions.put(ids.get(index), index);
|
||||||
|
}
|
||||||
|
return dramaService.listPublishedByIds(ids).stream()
|
||||||
|
.sorted((left, right) -> Integer.compare(
|
||||||
|
positions.getOrDefault(left.getId(), Integer.MAX_VALUE),
|
||||||
|
positions.getOrDefault(right.getId(), Integer.MAX_VALUE)))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -35,7 +35,9 @@ public class AppSearchService {
|
|||||||
Page<Drama> page = new Page<>(safeIndex, safeSize);
|
Page<Drama> page = new Page<>(safeIndex, safeSize);
|
||||||
Page<Drama> result = dramaMapper.selectPage(page, Wrappers.<Drama>lambdaQuery()
|
Page<Drama> result = dramaMapper.selectPage(page, Wrappers.<Drama>lambdaQuery()
|
||||||
.eq(Drama::getStatus, ContentStatus.PUBLISHED.getCode())
|
.eq(Drama::getStatus, ContentStatus.PUBLISHED.getCode())
|
||||||
.and(w -> w.like(Drama::getTitle, keyword.trim())
|
.and(w -> w.like(Drama::getTitleLocales, keyword.trim())
|
||||||
|
.or().like(Drama::getSynopsisLocales, keyword.trim())
|
||||||
|
.or().like(Drama::getTitle, keyword.trim())
|
||||||
.or().like(Drama::getSynopsis, keyword.trim()))
|
.or().like(Drama::getSynopsis, keyword.trim()))
|
||||||
.orderByDesc(Drama::getSort)
|
.orderByDesc(Drama::getSort)
|
||||||
.orderByDesc(Drama::getId));
|
.orderByDesc(Drama::getId));
|
||||||
|
|||||||
@@ -11,10 +11,15 @@ import java.util.Map;
|
|||||||
public class AppCategoryVO {
|
public class AppCategoryVO {
|
||||||
|
|
||||||
private Long id;
|
private Long id;
|
||||||
|
private String code;
|
||||||
|
private String layoutType;
|
||||||
|
private Long revision;
|
||||||
private Map<String, String> locales;
|
private Map<String, String> locales;
|
||||||
|
|
||||||
public AppCategoryVO(Long id, String name) {
|
public AppCategoryVO(Long id, String name) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
|
this.layoutType = "GRID";
|
||||||
|
this.revision = 1L;
|
||||||
this.locales = name == null || name.isBlank() ? Map.of() : Map.of("zh", name);
|
this.locales = name == null || name.isBlank() ? Map.of() : Map.of("zh", name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,11 +15,15 @@ public class AppDramaCardVO {
|
|||||||
private Long id;
|
private Long id;
|
||||||
private Map<String, String> titleLocales;
|
private Map<String, String> titleLocales;
|
||||||
private String cover;
|
private String cover;
|
||||||
|
/** 横版封面(16:9),横幅等横向位优先用它;空串表示未上传,客户端回退竖版。 */
|
||||||
|
private String coverLandscape;
|
||||||
private Map<String, String> synopsisLocales;
|
private Map<String, String> synopsisLocales;
|
||||||
/** 短剧选中的全部类型,每项是一份语言表。 */
|
/** 短剧选中的全部类型,每项是一份语言表。 */
|
||||||
private List<Map<String, String>> types;
|
private List<Map<String, String>> types;
|
||||||
/** 标签语言表,key 为 zh / en / id。 */
|
/** 标签语言表,key 为 zh / en / id。 */
|
||||||
private Map<String, String> tagLocales;
|
private Map<String, String> tagLocales;
|
||||||
|
/** 标签语义码,如 NEW_ARRIVAL;客户端按码判断板块,文案仅用于展示。 */
|
||||||
|
private String tagCode;
|
||||||
/** 标签角标背景色,#RRGGBB。 */
|
/** 标签角标背景色,#RRGGBB。 */
|
||||||
private String tagColor;
|
private String tagColor;
|
||||||
private Integer totalEpisodes;
|
private Integer totalEpisodes;
|
||||||
|
|||||||
@@ -14,8 +14,12 @@ public class AppDramaDetailVO {
|
|||||||
private Map<String, String> titleLocales;
|
private Map<String, String> titleLocales;
|
||||||
private Map<String, String> synopsisLocales;
|
private Map<String, String> synopsisLocales;
|
||||||
private String cover;
|
private String cover;
|
||||||
|
/** 横版封面(16:9);空串表示未上传。 */
|
||||||
|
private String coverLandscape;
|
||||||
private List<Map<String, String>> types;
|
private List<Map<String, String>> types;
|
||||||
private Map<String, String> tagLocales;
|
private Map<String, String> tagLocales;
|
||||||
|
/** 标签语义码,如 NEW_ARRIVAL;空表示未配置。 */
|
||||||
|
private String tagCode;
|
||||||
private String tagColor;
|
private String tagColor;
|
||||||
private Integer totalEpisodes;
|
private Integer totalEpisodes;
|
||||||
private Integer freeEpisodes;
|
private Integer freeEpisodes;
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 推荐榜单项,排名由服务端确定。 */
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class AppRankingEntryVO {
|
||||||
|
|
||||||
|
private Integer rank;
|
||||||
|
private AppDramaCardVO drama;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** 推荐榜快照。 */
|
||||||
|
@Data
|
||||||
|
public class AppRankingVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String code;
|
||||||
|
private Map<String, String> locales;
|
||||||
|
private Long revision;
|
||||||
|
private LocalDateTime generatedAt;
|
||||||
|
private Integer total;
|
||||||
|
private List<AppRankingEntryVO> list;
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.web;
|
||||||
|
|
||||||
|
import com.fruitshorts.user.service.DeviceProfileService;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收集客户端上报的平台(iOS / Android)。
|
||||||
|
*
|
||||||
|
* <p>客户端在请求头带 `X-Client-Platform`,这里按 device_id 建档,
|
||||||
|
* 后台列表据此区分两端;游客请求同样入库,这是与旧会话方案的关键差异。
|
||||||
|
* 同一设备 60 秒内只写一次,避免每个请求都打库。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DeviceProfileFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private static final long THROTTLE_MS = 60_000L;
|
||||||
|
private static final int MAX_TRACKED_DEVICES = 20_000;
|
||||||
|
|
||||||
|
private final DeviceProfileService deviceProfileService;
|
||||||
|
private final Map<String, Long> lastWriteAt = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
try {
|
||||||
|
collect(request);
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
// 画像只服务于后台展示,任何异常都不能影响业务请求
|
||||||
|
log.warn("device-profile collect failed reason={}", ex.getMessage());
|
||||||
|
}
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collect(HttpServletRequest request) {
|
||||||
|
String deviceId = request.getHeader("X-Device-Id");
|
||||||
|
if (!StringUtils.hasText(deviceId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
Long last = lastWriteAt.get(deviceId);
|
||||||
|
if (last != null && now - last < THROTTLE_MS) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (lastWriteAt.size() > MAX_TRACKED_DEVICES) {
|
||||||
|
lastWriteAt.clear();
|
||||||
|
}
|
||||||
|
lastWriteAt.put(deviceId, now);
|
||||||
|
deviceProfileService.touch(deviceId, request.getHeader("X-Client-Platform"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,13 @@ fruitshorts:
|
|||||||
cors:
|
cors:
|
||||||
# 生产只允许显式配置的来源;没配就等于空,浏览器侧会被拦住(比"*"安全)
|
# 生产只允许显式配置的来源;没配就等于空,浏览器侧会被拦住(比"*"安全)
|
||||||
allowed-origins: ${CORS_ALLOWED_ORIGINS:}
|
allowed-origins: ${CORS_ALLOWED_ORIGINS:}
|
||||||
|
watch-progress:
|
||||||
|
# 观看进度写缓冲:POST 先写 Redis 立即返回,后台任务批量合并进 watch_progress。
|
||||||
|
# 消化能力 = batch-size / interval ≈ 5000 条/秒,覆盖 30 万 DAU 峰值 ~3700 条/秒上报。
|
||||||
|
# 关掉(false)即回退同步写库,接口契约不变。
|
||||||
|
buffer: true
|
||||||
|
flush-interval-ms: 2000
|
||||||
|
flush-batch-size: 10000
|
||||||
|
|
||||||
springdoc:
|
springdoc:
|
||||||
# 生产只留机器可读契约,关掉 UI(doc.html 不对外开放)
|
# 生产只留机器可读契约,关掉 UI(doc.html 不对外开放)
|
||||||
|
|||||||
@@ -11,13 +11,22 @@ spring:
|
|||||||
datasource:
|
datasource:
|
||||||
driver-class-name: org.postgresql.Driver
|
driver-class-name: org.postgresql.Driver
|
||||||
# 地址必须外置:不同环境(本机 / 测试 / 生产)连的库不一样,
|
# 地址必须外置:不同环境(本机 / 测试 / 生产)连的库不一样,
|
||||||
# 生产请用 DB_URL 注入(prod profile 会校验它非空)
|
# 生产请用 DB_URL 注入(prod profile 会校验它非空)。
|
||||||
url: ${DB_URL:jdbc:postgresql://127.0.0.1:5432/fruitshorts}
|
# reWriteBatchedInserts:pgjdbc 把批内多条 INSERT 重写成多值 INSERT,
|
||||||
|
# 观看进度缓冲落库依赖它才能跑满批量吞吐。
|
||||||
|
url: ${DB_URL:jdbc:postgresql://127.0.0.1:5432/fruitshorts?reWriteBatchedInserts=true}
|
||||||
username: ${DB_USER:fruitshorts}
|
username: ${DB_USER:fruitshorts}
|
||||||
password: ${DB_PASSWORD:fruitshorts}
|
password: ${DB_PASSWORD:fruitshorts}
|
||||||
jackson:
|
jackson:
|
||||||
date-format: yyyy-MM-dd HH:mm:ss
|
date-format: yyyy-MM-dd HH:mm:ss
|
||||||
time-zone: Asia/Shanghai
|
time-zone: Asia/Shanghai
|
||||||
|
task:
|
||||||
|
scheduling:
|
||||||
|
# 默认调度池只有 1 条线程:观看进度落库(每 2s)会和其他定时任务互相排队,
|
||||||
|
# 落库一旦拖慢就会连带推迟对时延敏感的任务,必须给池子多几条线程。
|
||||||
|
pool:
|
||||||
|
size: 4
|
||||||
|
thread-name-prefix: fruitshorts-sched-
|
||||||
data:
|
data:
|
||||||
redis:
|
redis:
|
||||||
host: ${REDIS_HOST:127.0.0.1}
|
host: ${REDIS_HOST:127.0.0.1}
|
||||||
@@ -47,10 +56,20 @@ springdoc:
|
|||||||
path: /v3/api-docs
|
path: /v3/api-docs
|
||||||
|
|
||||||
fruitshorts:
|
fruitshorts:
|
||||||
|
web:
|
||||||
|
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
|
||||||
|
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
|
||||||
|
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
|
||||||
|
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
|
||||||
auth:
|
auth:
|
||||||
# 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」
|
# 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」
|
||||||
register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5}
|
register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5}
|
||||||
register-max-per-device-per-day: ${REGISTER_MAX_PER_DEVICE_PER_DAY:3}
|
register-max-per-device-per-day: ${REGISTER_MAX_PER_DEVICE_PER_DAY:3}
|
||||||
|
google:
|
||||||
|
# Google 登录允许的客户端 id(逗号分隔)。idToken 的 aud 随平台不同:
|
||||||
|
# iOS 为 iOS 客户端 id,Android 为 serverClientId 对应的 Web 客户端 id。
|
||||||
|
# 客户端 id 属公开信息,不是密钥;生产可用 GOOGLE_CLIENT_IDS 覆盖。
|
||||||
|
client-ids: ${GOOGLE_CLIENT_IDS:11115008580-51gv4sj2c78rud6n127g3shu4d2n96un.apps.googleusercontent.com,11115008580-dbqe47fhp5560nhrocrppiq7hcnlvl1s.apps.googleusercontent.com,11115008580-1v5pt5mfgbbuba74ebia6hngj618ne3a.apps.googleusercontent.com}
|
||||||
interaction:
|
interaction:
|
||||||
# MACHINE_FIRST:机审通过即发布,命中 REVIEW 级敏感词才转人工
|
# MACHINE_FIRST:机审通过即发布,命中 REVIEW 级敏感词才转人工
|
||||||
# PRE_REVIEW :全部先审后发(生产建议)
|
# PRE_REVIEW :全部先审后发(生产建议)
|
||||||
@@ -80,15 +99,15 @@ fruitshorts:
|
|||||||
chunk-size: 5242880
|
chunk-size: 5242880
|
||||||
max-file-size: 2147483648
|
max-file-size: 2147483648
|
||||||
# 播放地址签名:生产必开(docs/12-上线检查清单),prod profile 里强制为 true
|
# 播放地址签名:生产必开(docs/12-上线检查清单),prod profile 里强制为 true
|
||||||
signature-secret: ${MEDIA_SIGNATURE_SECRET:fruitshorts-media-dev-secret-change-me-in-production-32b}
|
signature-secret: ${MEDIA_SIGNATURE_SECRET:}
|
||||||
signature-required: ${MEDIA_SIGNATURE_REQUIRED:false}
|
signature-required: ${MEDIA_SIGNATURE_REQUIRED:false}
|
||||||
signature-ttl-minutes: 15
|
signature-ttl-minutes: 15
|
||||||
jwt:
|
jwt:
|
||||||
# 双密钥:管理端与客户端物理隔离,token 不能互换(AGENTS.md 强制约束 2)
|
# 双密钥:管理端与客户端物理隔离,token 不能互换(AGENTS.md 强制约束 2)
|
||||||
# 注意 app-secret 以前没写在这里,一直用代码里的 dev 默认值 —— 生产必须注入 JWT_APP_SECRET
|
# ⚠️ 所有环境必须注入 JWT_ADMIN_SECRET / JWT_APP_SECRET,不设任何代码级默认值
|
||||||
admin-secret: ${JWT_ADMIN_SECRET:fruitshorts-admin-dev-secret-change-me-in-production-32b}
|
admin-secret: ${JWT_ADMIN_SECRET:}
|
||||||
admin-ttl-hours: 12
|
admin-ttl-hours: 12
|
||||||
app-secret: ${JWT_APP_SECRET:fruitshorts-app-dev-secret-change-me-in-production-32bytes}
|
app-secret: ${JWT_APP_SECRET:}
|
||||||
app-access-ttl-minutes: 120
|
app-access-ttl-minutes: 120
|
||||||
app-refresh-ttl-days: 30
|
app-refresh-ttl-days: 30
|
||||||
cors:
|
cors:
|
||||||
|
|||||||
+4
-1
@@ -4,6 +4,7 @@ package com.fruitshorts.app.controller;
|
|||||||
import com.fruitshorts.app.support.ControllerContractSupport;
|
import com.fruitshorts.app.support.ControllerContractSupport;
|
||||||
import com.fruitshorts.common.exception.ErrorCode;
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
import com.fruitshorts.common.exception.ServiceException;
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import com.fruitshorts.framework.web.WebUtils;
|
||||||
import com.fruitshorts.user.service.AppAuthService;
|
import com.fruitshorts.user.service.AppAuthService;
|
||||||
import com.fruitshorts.user.service.AppOtpService;
|
import com.fruitshorts.user.service.AppOtpService;
|
||||||
import com.fruitshorts.user.vo.TokenRespVO;
|
import com.fruitshorts.user.vo.TokenRespVO;
|
||||||
@@ -32,13 +33,15 @@ class AppAuthControllerContractTest {
|
|||||||
|
|
||||||
private AppOtpService otpService;
|
private AppOtpService otpService;
|
||||||
private AppAuthService authService;
|
private AppAuthService authService;
|
||||||
|
private WebUtils webUtils;
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
otpService = mock(AppOtpService.class);
|
otpService = mock(AppOtpService.class);
|
||||||
authService = mock(AppAuthService.class);
|
authService = mock(AppAuthService.class);
|
||||||
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService));
|
webUtils = mock(WebUtils.class);
|
||||||
|
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService, webUtils));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+38
-2
@@ -3,6 +3,7 @@ package com.fruitshorts.app.controller;
|
|||||||
|
|
||||||
import com.fruitshorts.app.service.AppCatalogService;
|
import com.fruitshorts.app.service.AppCatalogService;
|
||||||
import com.fruitshorts.app.service.AppEpisodeStatsService;
|
import com.fruitshorts.app.service.AppEpisodeStatsService;
|
||||||
|
import com.fruitshorts.app.service.AppRankingService;
|
||||||
import com.fruitshorts.app.support.ControllerContractSupport;
|
import com.fruitshorts.app.support.ControllerContractSupport;
|
||||||
import com.fruitshorts.app.vo.AppBannerVO;
|
import com.fruitshorts.app.vo.AppBannerVO;
|
||||||
import com.fruitshorts.app.vo.AppCategoryVO;
|
import com.fruitshorts.app.vo.AppCategoryVO;
|
||||||
@@ -10,6 +11,8 @@ import com.fruitshorts.app.vo.AppDramaCardVO;
|
|||||||
import com.fruitshorts.app.vo.AppDramaDetailVO;
|
import com.fruitshorts.app.vo.AppDramaDetailVO;
|
||||||
import com.fruitshorts.app.vo.AppFeedVO;
|
import com.fruitshorts.app.vo.AppFeedVO;
|
||||||
import com.fruitshorts.app.vo.AppSectionVO;
|
import com.fruitshorts.app.vo.AppSectionVO;
|
||||||
|
import com.fruitshorts.app.vo.AppRankingEntryVO;
|
||||||
|
import com.fruitshorts.app.vo.AppRankingVO;
|
||||||
import com.fruitshorts.common.pojo.CursorResult;
|
import com.fruitshorts.common.pojo.CursorResult;
|
||||||
import com.fruitshorts.content.service.EpisodeService;
|
import com.fruitshorts.content.service.EpisodeService;
|
||||||
import com.fruitshorts.common.exception.ErrorCode;
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
@@ -41,17 +44,21 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
|||||||
class AppCatalogControllerContractTest {
|
class AppCatalogControllerContractTest {
|
||||||
|
|
||||||
private AppCatalogService catalogService;
|
private AppCatalogService catalogService;
|
||||||
|
private AppRankingService rankingService;
|
||||||
private MockMvc catalogMvc;
|
private MockMvc catalogMvc;
|
||||||
private MockMvc dramaMvc;
|
private MockMvc dramaMvc;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
catalogService = mock(AppCatalogService.class);
|
catalogService = mock(AppCatalogService.class);
|
||||||
catalogMvc = ControllerContractSupport.mockMvcOf(new AppCatalogController(catalogService));
|
rankingService = mock(AppRankingService.class);
|
||||||
|
catalogMvc = ControllerContractSupport.mockMvcOf(
|
||||||
|
new AppCatalogController(catalogService, rankingService));
|
||||||
dramaMvc = ControllerContractSupport.mockMvcOf(
|
dramaMvc = ControllerContractSupport.mockMvcOf(
|
||||||
new AppDramaController(catalogService, mock(PlaybackService.class),
|
new AppDramaController(catalogService, mock(PlaybackService.class),
|
||||||
mock(EpisodeService.class), mock(CommentService.class),
|
mock(EpisodeService.class), mock(CommentService.class),
|
||||||
mock(AppEpisodeStatsService.class)));
|
mock(AppEpisodeStatsService.class),
|
||||||
|
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -121,15 +128,44 @@ class AppCatalogControllerContractTest {
|
|||||||
@Test
|
@Test
|
||||||
void should_return_category_list_when_categories_are_requested() throws Exception {
|
void should_return_category_list_when_categories_are_requested() throws Exception {
|
||||||
AppCategoryVO category = new AppCategoryVO(3L, "都市");
|
AppCategoryVO category = new AppCategoryVO(3L, "都市");
|
||||||
|
category.setCode("RECOMMEND_RANKING");
|
||||||
|
category.setLayoutType("RANKING");
|
||||||
|
category.setRevision(7L);
|
||||||
given(catalogService.categories()).willReturn(List.of(category));
|
given(catalogService.categories()).willReturn(List.of(category));
|
||||||
|
|
||||||
catalogMvc.perform(get("/app/categories"))
|
catalogMvc.perform(get("/app/categories"))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(jsonPath("$.code").value(0))
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
.andExpect(jsonPath("$.data[0].id").value(3))
|
.andExpect(jsonPath("$.data[0].id").value(3))
|
||||||
|
.andExpect(jsonPath("$.data[0].code").value("RECOMMEND_RANKING"))
|
||||||
|
.andExpect(jsonPath("$.data[0].layoutType").value("RANKING"))
|
||||||
|
.andExpect(jsonPath("$.data[0].revision").value("7"))
|
||||||
.andExpect(jsonPath("$.data[0].locales.zh").value("都市"));
|
.andExpect(jsonPath("$.data[0].locales.zh").value("都市"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_return_server_rank_when_ranking_is_requested() throws Exception {
|
||||||
|
AppDramaCardVO card = new AppDramaCardVO();
|
||||||
|
card.setId(12L);
|
||||||
|
card.setTitleLocales(Map.of("zh", "榜首短剧"));
|
||||||
|
AppRankingVO ranking = new AppRankingVO();
|
||||||
|
ranking.setId(3L);
|
||||||
|
ranking.setCode("RECOMMEND_RANKING");
|
||||||
|
ranking.setRevision(8L);
|
||||||
|
ranking.setTotal(1);
|
||||||
|
ranking.setList(List.of(new AppRankingEntryVO(1, card)));
|
||||||
|
given(rankingService.ranking(3L)).willReturn(ranking);
|
||||||
|
|
||||||
|
catalogMvc.perform(get("/app/categories/3/ranking"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
|
.andExpect(jsonPath("$.data.revision").value("8"))
|
||||||
|
.andExpect(jsonPath("$.data.list[0].rank").value(1))
|
||||||
|
.andExpect(jsonPath("$.data.list[0].drama.id").value("12"));
|
||||||
|
|
||||||
|
verify(rankingService).ranking(3L);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void should_bind_path_variable_when_drama_detail_is_requested() throws Exception {
|
void should_bind_path_variable_when_drama_detail_is_requested() throws Exception {
|
||||||
AppDramaDetailVO detail = new AppDramaDetailVO();
|
AppDramaDetailVO detail = new AppDramaDetailVO();
|
||||||
|
|||||||
+2
-1
@@ -38,7 +38,8 @@ class AppCommentControllerContractTest {
|
|||||||
commentService,
|
commentService,
|
||||||
episodeService,
|
episodeService,
|
||||||
mock(InteractionIdentityResolver.class),
|
mock(InteractionIdentityResolver.class),
|
||||||
mock(AnonymousInteractionRateLimiter.class)));
|
mock(AnonymousInteractionRateLimiter.class),
|
||||||
|
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+8
-4
@@ -234,7 +234,8 @@ class AppCommentCountAnonymousSecurityTest {
|
|||||||
commentService,
|
commentService,
|
||||||
episodeService,
|
episodeService,
|
||||||
identityResolver,
|
identityResolver,
|
||||||
rateLimiter);
|
rateLimiter,
|
||||||
|
mock(com.fruitshorts.framework.web.WebUtils.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -303,7 +304,8 @@ class AppCommentCountAnonymousSecurityTest {
|
|||||||
mock(PlaybackService.class),
|
mock(PlaybackService.class),
|
||||||
episodeService,
|
episodeService,
|
||||||
commentService,
|
commentService,
|
||||||
appEpisodeStatsService);
|
appEpisodeStatsService,
|
||||||
|
mock(com.fruitshorts.framework.web.WebUtils.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -326,7 +328,9 @@ class AppCommentCountAnonymousSecurityTest {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
AppCatalogController appCatalogController(AppCatalogService appCatalogService) {
|
AppCatalogController appCatalogController(AppCatalogService appCatalogService) {
|
||||||
return new AppCatalogController(appCatalogService);
|
return new AppCatalogController(
|
||||||
|
appCatalogService,
|
||||||
|
mock(com.fruitshorts.app.service.AppRankingService.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -340,7 +344,7 @@ class AppCommentCountAnonymousSecurityTest {
|
|||||||
RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) {
|
RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) {
|
||||||
return new RestAuthEntryPoint(
|
return new RestAuthEntryPoint(
|
||||||
objectMapper,
|
objectMapper,
|
||||||
new AccessDeniedRecorder(mock(ObjectProvider.class)));
|
new AccessDeniedRecorder(mock(ObjectProvider.class), mock(ObjectProvider.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+2
@@ -90,6 +90,7 @@ class AppCreatorAndConfigContractTest {
|
|||||||
whitelist.put("noticeEnabled", true);
|
whitelist.put("noticeEnabled", true);
|
||||||
whitelist.put("coinUnlockEnabled", true);
|
whitelist.put("coinUnlockEnabled", true);
|
||||||
whitelist.put("downloadEnabled", true);
|
whitelist.put("downloadEnabled", true);
|
||||||
|
whitelist.put("loginBackgroundUrl", "");
|
||||||
given(appConfigService.appConfig()).willReturn(whitelist);
|
given(appConfigService.appConfig()).willReturn(whitelist);
|
||||||
|
|
||||||
String body = configMvc.perform(get("/app/config"))
|
String body = configMvc.perform(get("/app/config"))
|
||||||
@@ -97,6 +98,7 @@ class AppCreatorAndConfigContractTest {
|
|||||||
.andExpect(jsonPath("$.code").value(0))
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
.andExpect(jsonPath("$.data.agreementVersion").value("2026-10-01"))
|
.andExpect(jsonPath("$.data.agreementVersion").value("2026-10-01"))
|
||||||
.andExpect(jsonPath("$.data.forceUpdate").value(false))
|
.andExpect(jsonPath("$.data.forceUpdate").value(false))
|
||||||
|
.andExpect(jsonPath("$.data.loginBackgroundUrl").value(""))
|
||||||
.andReturn().getResponse().getContentAsString(java.nio.charset.StandardCharsets.UTF_8);
|
.andReturn().getResponse().getContentAsString(java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
|
||||||
// 没登录也能拿到(匿名)
|
// 没登录也能拿到(匿名)
|
||||||
|
|||||||
+2
-1
@@ -54,7 +54,8 @@ class AppPlaybackContractTest {
|
|||||||
given(commentService.countByEpisodes(any())).willReturn(Map.of());
|
given(commentService.countByEpisodes(any())).willReturn(Map.of());
|
||||||
mockMvc = ControllerContractSupport.mockMvcOf(
|
mockMvc = ControllerContractSupport.mockMvcOf(
|
||||||
new AppDramaController(mock(AppCatalogService.class), playbackService,
|
new AppDramaController(mock(AppCatalogService.class), playbackService,
|
||||||
episodeService, commentService, episodeStatsService));
|
episodeService, commentService, episodeStatsService,
|
||||||
|
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.controller;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardCheckinService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardGrantService;
|
||||||
|
import com.fruitshorts.commerce.reward.service.RewardTaskService;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardOverviewVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityVO;
|
||||||
|
import com.fruitshorts.commerce.service.WalletService;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.framework.log.AccessDeniedRecorder;
|
||||||
|
import com.fruitshorts.framework.security.JwtAuthenticationFilter;
|
||||||
|
import com.fruitshorts.framework.security.JwtTokenProvider;
|
||||||
|
import com.fruitshorts.framework.security.RestAuthEntryPoint;
|
||||||
|
import com.fruitshorts.framework.security.SecurityConfig;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.web.FilterChainProxy;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
import org.springframework.test.context.web.WebAppConfiguration;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.isNull;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
/** 奖励中心匿名浏览与写操作鉴权的安全链契约。 */
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@WebAppConfiguration
|
||||||
|
@ContextConfiguration(classes = AppRewardAnonymousSecurityTest.TestConfig.class)
|
||||||
|
class AppRewardAnonymousSecurityTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mockMvc;
|
||||||
|
@Autowired
|
||||||
|
private RewardTaskService taskService;
|
||||||
|
@Autowired
|
||||||
|
private RewardCheckinService checkinService;
|
||||||
|
@Autowired
|
||||||
|
private WalletService walletService;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_allow_anonymous_reward_overview_without_creating_wallet() throws Exception {
|
||||||
|
RewardOverviewVO overview = new RewardOverviewVO();
|
||||||
|
overview.setCoinBalance(0L);
|
||||||
|
overview.setSections(List.of());
|
||||||
|
overview.setActivities(List.of());
|
||||||
|
given(taskService.overview(isNull(), org.mockito.ArgumentMatchers.eq("en"),
|
||||||
|
org.mockito.ArgumentMatchers.eq(0L))).willReturn(overview);
|
||||||
|
given(checkinService.status(isNull())).willReturn(new RewardCheckinVO());
|
||||||
|
|
||||||
|
mockMvc.perform(get("/app/rewards/overview").param("locale", "en"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
|
.andExpect(jsonPath("$.data.coinBalance").value(0));
|
||||||
|
|
||||||
|
verify(walletService, never()).getOrCreate(org.mockito.ArgumentMatchers.any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_allow_anonymous_reward_activities() throws Exception {
|
||||||
|
given(taskService.activities("id")).willReturn(List.of(new RewardActivityVO()));
|
||||||
|
|
||||||
|
mockMvc.perform(get("/app/rewards/activities").param("locale", "id"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
|
.andExpect(jsonPath("$.data").isArray())
|
||||||
|
.andExpect(jsonPath("$.data", org.hamcrest.Matchers.hasSize(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_keep_personal_reward_operations_login_required() throws Exception {
|
||||||
|
mockMvc.perform(get("/app/rewards/check-in"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||||
|
mockMvc.perform(post("/app/rewards/check-in"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||||
|
mockMvc.perform(post("/app/rewards/tasks/9/claim"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebMvc
|
||||||
|
@EnableWebSecurity
|
||||||
|
@Import(SecurityConfig.class)
|
||||||
|
static class TestConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RewardTaskService rewardTaskService() {
|
||||||
|
return mock(RewardTaskService.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RewardCheckinService rewardCheckinService() {
|
||||||
|
return mock(RewardCheckinService.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RewardGrantService rewardGrantService() {
|
||||||
|
return mock(RewardGrantService.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
WalletService walletService() {
|
||||||
|
return mock(WalletService.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
AppRewardController appRewardController(
|
||||||
|
RewardTaskService taskService,
|
||||||
|
RewardCheckinService checkinService,
|
||||||
|
RewardGrantService grantService,
|
||||||
|
WalletService walletService) {
|
||||||
|
return new AppRewardController(taskService, checkinService, grantService, walletService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
JwtAuthenticationFilter jwtAuthenticationFilter() {
|
||||||
|
return new JwtAuthenticationFilter(mock(JwtTokenProvider.class), mock(ObjectProvider.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) {
|
||||||
|
return new RestAuthEntryPoint(objectMapper,
|
||||||
|
new AccessDeniedRecorder(mock(ObjectProvider.class), mock(ObjectProvider.class)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ObjectMapper objectMapper() {
|
||||||
|
return new ObjectMapper();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
MockMvc mockMvc(WebApplicationContext context) {
|
||||||
|
FilterChainProxy securityFilter = context.getBean(
|
||||||
|
"springSecurityFilterChain", FilterChainProxy.class);
|
||||||
|
return MockMvcBuilders.webAppContextSetup(context)
|
||||||
|
.addFilters(securityFilter)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
-4
@@ -22,6 +22,7 @@ import com.fruitshorts.user.service.AppOtpService;
|
|||||||
import com.fruitshorts.user.service.CredentialHasher;
|
import com.fruitshorts.user.service.CredentialHasher;
|
||||||
import com.fruitshorts.user.service.GoogleIdTokenVerifier;
|
import com.fruitshorts.user.service.GoogleIdTokenVerifier;
|
||||||
import com.fruitshorts.user.service.GoogleUser;
|
import com.fruitshorts.user.service.GoogleUser;
|
||||||
|
import com.fruitshorts.user.service.IpRegionService;
|
||||||
import com.fruitshorts.user.service.OtpSender;
|
import com.fruitshorts.user.service.OtpSender;
|
||||||
import com.fruitshorts.user.vo.LoginReqVO;
|
import com.fruitshorts.user.vo.LoginReqVO;
|
||||||
import com.fruitshorts.user.vo.RegisterReqVO;
|
import com.fruitshorts.user.vo.RegisterReqVO;
|
||||||
@@ -67,6 +68,7 @@ class AppAuthServiceTest {
|
|||||||
private ConfigService configService;
|
private ConfigService configService;
|
||||||
private GoogleIdTokenVerifier googleVerifier;
|
private GoogleIdTokenVerifier googleVerifier;
|
||||||
private ApplicationEventPublisher eventPublisher;
|
private ApplicationEventPublisher eventPublisher;
|
||||||
|
private IpRegionService ipRegionService;
|
||||||
private AppAuthService authService;
|
private AppAuthService authService;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
@@ -83,11 +85,14 @@ class AppAuthServiceTest {
|
|||||||
configService = mock(ConfigService.class);
|
configService = mock(ConfigService.class);
|
||||||
googleVerifier = mock(GoogleIdTokenVerifier.class);
|
googleVerifier = mock(GoogleIdTokenVerifier.class);
|
||||||
eventPublisher = mock(ApplicationEventPublisher.class);
|
eventPublisher = mock(ApplicationEventPublisher.class);
|
||||||
|
ipRegionService = mock(IpRegionService.class);
|
||||||
given(configService.get(anyString(), anyString()))
|
given(configService.get(anyString(), anyString()))
|
||||||
.willAnswer(invocation -> invocation.getArgument(1));
|
.willAnswer(invocation -> invocation.getArgument(1));
|
||||||
|
// 单测里默认解析不出国家,走客户端区域 / 印尼兜底
|
||||||
|
given(ipRegionService.resolveCountry(any())).willReturn("");
|
||||||
authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
|
authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
|
||||||
deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService,
|
deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService,
|
||||||
googleVerifier, eventPublisher);
|
googleVerifier, eventPublisher, ipRegionService);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -264,6 +269,41 @@ class AppAuthServiceTest {
|
|||||||
assertThat(event.deviceId()).isEqualTo("device-9");
|
assertThat(event.deviceId()).isEqualTo("device-9");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_sync_country_from_ip_on_login() {
|
||||||
|
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
|
||||||
|
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
|
||||||
|
given(ipRegionService.resolveCountry(any())).willReturn("TH");
|
||||||
|
|
||||||
|
authService.login(emailLogin("abcd1234"), "49.237.8.1");
|
||||||
|
|
||||||
|
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
|
||||||
|
verify(userMapper).updateById(captor.capture());
|
||||||
|
AppUser saved = captor.getValue();
|
||||||
|
assertThat(saved.getCountryCode()).isEqualTo("TH");
|
||||||
|
assertThat(saved.getRegionCode()).isEqualTo("TH");
|
||||||
|
assertThat(saved.getLanguage()).isEqualTo("en-US");
|
||||||
|
assertThat(saved.getTimezone()).isEqualTo("Asia/Bangkok");
|
||||||
|
assertThat(saved.getCurrency()).isEqualTo("THB");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_keep_user_customized_language_when_syncing_country() {
|
||||||
|
AppUser user = user(AppUserStatus.NORMAL);
|
||||||
|
user.setLanguage("zh-CN");
|
||||||
|
stubLogin(credential("bcrypt-hash"), user);
|
||||||
|
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
|
||||||
|
given(ipRegionService.resolveCountry(any())).willReturn("TH");
|
||||||
|
|
||||||
|
authService.login(emailLogin("abcd1234"), "49.237.8.1");
|
||||||
|
|
||||||
|
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
|
||||||
|
verify(userMapper).updateById(captor.capture());
|
||||||
|
assertThat(captor.getValue().getCountryCode()).isEqualTo("TH");
|
||||||
|
// 用户自己改过的语言不被 IP 覆盖
|
||||||
|
assertThat(captor.getValue().getLanguage()).isEqualTo("zh-CN");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void should_reject_login_when_password_does_not_match() {
|
void should_reject_login_when_password_does_not_match() {
|
||||||
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
|
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
|
||||||
@@ -318,7 +358,7 @@ class AppAuthServiceTest {
|
|||||||
});
|
});
|
||||||
given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get());
|
given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get());
|
||||||
|
|
||||||
TokenRespVO resp = authService.googleLogin("google-id-token", "device-9");
|
TokenRespVO resp = authService.googleLogin("google-id-token", "device-9", "203.0.113.9");
|
||||||
|
|
||||||
assertThat(resp.getAccessToken()).isEqualTo("access-1");
|
assertThat(resp.getAccessToken()).isEqualTo("access-1");
|
||||||
assertThat(resp.isNewUser()).isTrue();
|
assertThat(resp.isNewUser()).isTrue();
|
||||||
@@ -333,7 +373,7 @@ class AppAuthServiceTest {
|
|||||||
given(googleVerifier.verify(anyString()))
|
given(googleVerifier.verify(anyString()))
|
||||||
.willReturn(new GoogleUser("sub-1", "", "Alice", ""));
|
.willReturn(new GoogleUser("sub-1", "", "Alice", ""));
|
||||||
|
|
||||||
assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9"))
|
assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9", "203.0.113.9"))
|
||||||
.isInstanceOf(ServiceException.class)
|
.isInstanceOf(ServiceException.class)
|
||||||
.hasMessage("Google 账号未返回邮箱,无法登录");
|
.hasMessage("Google 账号未返回邮箱,无法登录");
|
||||||
}
|
}
|
||||||
@@ -392,7 +432,7 @@ class AppAuthServiceTest {
|
|||||||
AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher);
|
AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher);
|
||||||
return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
|
return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
|
||||||
deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService,
|
deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService,
|
||||||
googleVerifier, eventPublisher);
|
googleVerifier, eventPublisher, ipRegionService);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setRegisterLimits(int perIp, int perDevice) {
|
private void setRegisterLimits(int perIp, int perDevice) {
|
||||||
|
|||||||
+19
@@ -130,6 +130,25 @@ class AppCatalogServiceTest {
|
|||||||
verify(commentService, never()).countByDrama(any());
|
verify(commentService, never()).countByDrama(any());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_keep_full_synopsis_on_card_when_text_exceeds_card_length() {
|
||||||
|
String longSynopsis = "一纸婚约,开启了甜蜜又心动的同居生活。"
|
||||||
|
+ "真相只有一个,而她亲手揭开迷雾。一场意外替嫁,让她成为冷面总裁的契约新娘。";
|
||||||
|
Drama drama = new Drama();
|
||||||
|
drama.setId(1L);
|
||||||
|
drama.setTitle("第一部");
|
||||||
|
drama.setSynopsis(longSynopsis);
|
||||||
|
given(episodeService.firstPlayableByDramas(List.of(1L))).willReturn(Map.of());
|
||||||
|
given(dramaCategoryService.listBasic()).willReturn(List.of());
|
||||||
|
given(commentService.countByEpisodes(List.of())).willReturn(Map.of());
|
||||||
|
|
||||||
|
List<AppDramaCardVO> cards = catalogService.toCards(List.of(drama));
|
||||||
|
|
||||||
|
assertThat(cards).hasSize(1);
|
||||||
|
assertThat(cards.get(0).getSynopsisLocales())
|
||||||
|
.containsEntry("zh", longSynopsis);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void should_filter_feed_by_drama_type_and_expose_it_on_card() {
|
void should_filter_feed_by_drama_type_and_expose_it_on_card() {
|
||||||
Drama anime = drama(1L, "ANIME");
|
Drama anime = drama(1L, "ANIME");
|
||||||
|
|||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.app.service;
|
||||||
|
|
||||||
|
import com.fruitshorts.app.vo.AppDramaCardVO;
|
||||||
|
import com.fruitshorts.app.vo.AppRankingVO;
|
||||||
|
import com.fruitshorts.content.dal.entity.Drama;
|
||||||
|
import com.fruitshorts.content.dal.entity.DramaClassification;
|
||||||
|
import com.fruitshorts.content.service.DramaClassificationService;
|
||||||
|
import com.fruitshorts.content.service.DramaService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
|
/** 推荐榜快照顺序与排名测试。 */
|
||||||
|
class AppRankingServiceTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_preserve_server_order_and_compact_rank_when_offline_items_are_filtered() {
|
||||||
|
DramaClassificationService classificationService = mock(DramaClassificationService.class);
|
||||||
|
DramaService dramaService = mock(DramaService.class);
|
||||||
|
AppCatalogService catalogService = mock(AppCatalogService.class);
|
||||||
|
AppRankingService service = new AppRankingService(
|
||||||
|
classificationService, dramaService, catalogService);
|
||||||
|
DramaClassification classification = rankingClassification();
|
||||||
|
Drama second = drama(22L);
|
||||||
|
Drama first = drama(11L);
|
||||||
|
given(classificationService.getEnabledById(3L)).willReturn(classification);
|
||||||
|
given(classificationService.listDramaIdsByClassification(3L))
|
||||||
|
.willReturn(List.of(11L, 99L, 22L));
|
||||||
|
given(dramaService.listPublishedByIds(List.of(11L, 99L, 22L)))
|
||||||
|
.willReturn(List.of(second, first));
|
||||||
|
AppDramaCardVO firstCard = card(11L);
|
||||||
|
AppDramaCardVO secondCard = card(22L);
|
||||||
|
given(catalogService.toCards(List.of(first, second)))
|
||||||
|
.willReturn(List.of(firstCard, secondCard));
|
||||||
|
|
||||||
|
AppRankingVO result = service.ranking(3L);
|
||||||
|
|
||||||
|
assertThat(result.getRevision()).isEqualTo(7L);
|
||||||
|
assertThat(result.getList()).extracting(item -> item.getDrama().getId())
|
||||||
|
.containsExactly(11L, 22L);
|
||||||
|
assertThat(result.getList()).extracting(item -> item.getRank())
|
||||||
|
.containsExactly(1, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DramaClassification rankingClassification() {
|
||||||
|
DramaClassification classification = new DramaClassification();
|
||||||
|
classification.setId(3L);
|
||||||
|
classification.setCode("RECOMMEND_RANKING");
|
||||||
|
classification.setName("推荐榜");
|
||||||
|
classification.setNameLocales("{\"zh\":\"推荐榜\"}");
|
||||||
|
classification.setLayoutType(DramaClassificationService.LAYOUT_RANKING);
|
||||||
|
classification.setRevision(7L);
|
||||||
|
return classification;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Drama drama(Long id) {
|
||||||
|
Drama drama = new Drama();
|
||||||
|
drama.setId(id);
|
||||||
|
return drama;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AppDramaCardVO card(Long id) {
|
||||||
|
AppDramaCardVO card = new AppDramaCardVO();
|
||||||
|
card.setId(id);
|
||||||
|
card.setTitleLocales(Map.of("zh", "短剧" + id));
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
package com.fruitshorts.app.service;
|
||||||
|
|
||||||
|
import com.fruitshorts.user.enums.CountryProfile;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/** 国家解析与映射:IP 库文本 → ISO-2,再据此选语言/时区/币种。 */
|
||||||
|
class CountryProfileTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_map_ip_region_text_to_iso_code() {
|
||||||
|
assertThat(CountryProfile.fromIpRegion("中国|0|广东省|深圳市|电信")).isEqualTo("CN");
|
||||||
|
assertThat(CountryProfile.fromIpRegion("中国|0|台湾省|0|中华电信")).isEqualTo("TW");
|
||||||
|
assertThat(CountryProfile.fromIpRegion("中国|0|香港|0|0")).isEqualTo("HK");
|
||||||
|
assertThat(CountryProfile.fromIpRegion("中国|0|澳门|0|澳门电讯")).isEqualTo("MO");
|
||||||
|
assertThat(CountryProfile.fromIpRegion("美国|0|0|0|Level3")).isEqualTo("US");
|
||||||
|
assertThat(CountryProfile.fromIpRegion("印度尼西亚|0|大雅加达|雅加达|0")).isEqualTo("ID");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_return_empty_for_private_ip_and_unknown_country() {
|
||||||
|
assertThat(CountryProfile.fromIpRegion("0|0|0|内网IP|内网IP")).isEmpty();
|
||||||
|
assertThat(CountryProfile.fromIpRegion("")).isEmpty();
|
||||||
|
// 未收录的国家交给上层回退到客户端区域
|
||||||
|
assertThat(CountryProfile.fromIpRegion("津巴布韦|0|0|0|0")).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_normalize_client_region_and_fallback_to_default() {
|
||||||
|
assertThat(CountryProfile.normalizeClientCode(" id ")).isEqualTo("ID");
|
||||||
|
assertThat(CountryProfile.normalizeClientCode("us")).isEqualTo("US");
|
||||||
|
assertThat(CountryProfile.normalizeClientCode("XX")).isEmpty();
|
||||||
|
assertThat(CountryProfile.normalizeClientCode("")).isEmpty();
|
||||||
|
|
||||||
|
assertThat(CountryProfile.of("US").currency()).isEqualTo("USD");
|
||||||
|
assertThat(CountryProfile.of("US").language()).isEqualTo("en-US");
|
||||||
|
assertThat(CountryProfile.of("").code()).isEqualTo("ID");
|
||||||
|
assertThat(CountryProfile.of("").currency()).isEqualTo("IDR");
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
package com.fruitshorts.app.service;
|
||||||
|
|
||||||
|
import com.fruitshorts.user.service.IpRegionService;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IpRegionService 集成测试:真实 xdb 文件 + 真实 resolve。
|
||||||
|
*
|
||||||
|
* <p>xdb 在 fruitshorts-module-user 的 resources/ip2region/ip2region.xdb 下(11MB),
|
||||||
|
* 打包后会进 app-api 的 classpath。这个测试验证 Service 层调 ip2region 库的行为——
|
||||||
|
* 合法公网 IP → ISO-2 国家码,内网/保留地址/空 → 空串。
|
||||||
|
*/
|
||||||
|
class IpRegionServiceTest {
|
||||||
|
|
||||||
|
private IpRegionService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
service = new IpRegionService();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_resolve_known_public_ips() {
|
||||||
|
assertThat(service.resolveCountry("8.8.8.8")).isEqualTo("US");
|
||||||
|
assertThat(service.resolveCountry("114.114.114.114")).isEqualTo("CN");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_return_empty_for_private_loopback_and_reserved() {
|
||||||
|
assertThat(service.resolveCountry("127.0.0.1")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("0.0.0.0")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("10.0.0.1")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("192.168.1.1")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("172.16.0.1")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("169.254.1.1")).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_return_empty_for_invalid_inputs() {
|
||||||
|
assertThat(service.resolveCountry("")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry(null)).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("not-an-ip")).isEmpty();
|
||||||
|
assertThat(service.resolveCountry("999.999.999.999")).isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-1
@@ -2,6 +2,7 @@
|
|||||||
package com.fruitshorts.app.support;
|
package com.fruitshorts.app.support;
|
||||||
|
|
||||||
import com.fruitshorts.framework.log.AccessDeniedRecorder;
|
import com.fruitshorts.framework.log.AccessDeniedRecorder;
|
||||||
|
import com.fruitshorts.framework.web.WebUtils;
|
||||||
import com.fruitshorts.framework.web.JacksonLongToStringConfig;
|
import com.fruitshorts.framework.web.JacksonLongToStringConfig;
|
||||||
import com.fruitshorts.framework.web.GlobalExceptionHandler;
|
import com.fruitshorts.framework.web.GlobalExceptionHandler;
|
||||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
@@ -30,7 +31,9 @@ public final class ControllerContractSupport {
|
|||||||
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
|
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static MockMvc mockMvcOf(Object controller) {
|
public static MockMvc mockMvcOf(Object controller) {
|
||||||
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class));
|
AccessDeniedRecorder recorder = new AccessDeniedRecorder(
|
||||||
|
Mockito.mock(ObjectProvider.class),
|
||||||
|
Mockito.mock(ObjectProvider.class));
|
||||||
return MockMvcBuilders.standaloneSetup(controller)
|
return MockMvcBuilders.standaloneSetup(controller)
|
||||||
.setControllerAdvice(new GlobalExceptionHandler(recorder))
|
.setControllerAdvice(new GlobalExceptionHandler(recorder))
|
||||||
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
|
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
|
||||||
|
|||||||
+135
-1
@@ -20,18 +20,28 @@ import com.fruitshorts.playback.vo.ProgressRespVO;
|
|||||||
import com.fruitshorts.playback.vo.ProgressSaveReqVO;
|
import com.fruitshorts.playback.vo.ProgressSaveReqVO;
|
||||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.session.ExecutorType;
|
||||||
|
import org.apache.ibatis.session.SqlSession;
|
||||||
|
import org.apache.ibatis.session.SqlSessionFactory;
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InOrder;
|
||||||
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.BDDMockito.given;
|
import static org.mockito.BDDMockito.given;
|
||||||
|
import static org.mockito.Mockito.inOrder;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
@@ -58,11 +68,18 @@ class WatchProgressServiceTest {
|
|||||||
historyMapper = mock(WatchHistoryMapper.class);
|
historyMapper = mock(WatchHistoryMapper.class);
|
||||||
dramaService = mock(DramaService.class);
|
dramaService = mock(DramaService.class);
|
||||||
episodeService = mock(EpisodeService.class);
|
episodeService = mock(EpisodeService.class);
|
||||||
|
// 测试统一走缓冲关闭(同步写库)路径:getIfAvailable 返回 null
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
ObjectProvider<WatchProgressBuffer> bufferProvider = mock(ObjectProvider.class);
|
||||||
|
given(bufferProvider.getIfAvailable()).willReturn(null);
|
||||||
progressService = new WatchProgressService(
|
progressService = new WatchProgressService(
|
||||||
progressMapper,
|
progressMapper,
|
||||||
historyMapper,
|
historyMapper,
|
||||||
dramaService,
|
dramaService,
|
||||||
episodeService);
|
episodeService,
|
||||||
|
bufferProvider,
|
||||||
|
mock(SqlSessionFactory.class),
|
||||||
|
new TransactionTemplate(mock(PlatformTransactionManager.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -319,6 +336,123 @@ class WatchProgressServiceTest {
|
|||||||
verify(progressMapper).deleteById(1L);
|
verify(progressMapper).deleteById(1L);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_delete_buffer_state_when_removing_or_clearing_history() {
|
||||||
|
WatchProgressBuffer buffer = mock(WatchProgressBuffer.class);
|
||||||
|
WatchProgressService service = serviceWithBuffer(buffer);
|
||||||
|
|
||||||
|
service.remove(new InteractionIdentity(9L, ""), 5L);
|
||||||
|
service.clear(new InteractionIdentity(9L, ""));
|
||||||
|
|
||||||
|
verify(buffer).remove(any(InteractionIdentity.class), eq(5L));
|
||||||
|
verify(buffer).clear(any(InteractionIdentity.class));
|
||||||
|
verify(progressMapper, times(2)).delete(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_not_bring_back_deleted_drama_from_buffer_in_recent_page() {
|
||||||
|
WatchProgressBuffer buffer = mock(WatchProgressBuffer.class);
|
||||||
|
WatchProgressService service = serviceWithBuffer(buffer);
|
||||||
|
Page<WatchProgress> emptyPage = new Page<>(1, 20, 0);
|
||||||
|
emptyPage.setRecords(List.of());
|
||||||
|
given(progressMapper.selectPage(any(Page.class), any())).willReturn(emptyPage);
|
||||||
|
given(buffer.getAll(any(InteractionIdentity.class))).willReturn(Map.of(
|
||||||
|
5L, new WatchProgressBuffer.BufferedProgress(
|
||||||
|
5L, 88L, 1_000L, 2_000L, false, "feed", "", 1_700_000_000_000L)));
|
||||||
|
// 库里该剧只剩逻辑删除行:缓冲状态不得再把它读回列表
|
||||||
|
WatchProgress hidden = progress(5L, 88L);
|
||||||
|
hidden.setDeleted(1);
|
||||||
|
given(progressMapper.selectAnyForIdentityIn(9L, "", List.of(5L)))
|
||||||
|
.willReturn(List.of(hidden));
|
||||||
|
|
||||||
|
PageResult<ProgressRespVO> result =
|
||||||
|
service.recentPage(new InteractionIdentity(9L, ""), 1, 20);
|
||||||
|
|
||||||
|
assertThat(result.getList()).isEmpty();
|
||||||
|
assertThat(result.getTotal()).isZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_drop_buffered_refs_whose_state_is_gone_instead_of_requeue() {
|
||||||
|
WatchProgressBuffer buffer = mock(WatchProgressBuffer.class);
|
||||||
|
WatchProgressService service = serviceWithBuffer(buffer);
|
||||||
|
given(buffer.drain(10)).willReturn(
|
||||||
|
List.of(new WatchProgressBuffer.IdentityRef("u:9", 9L, "", 5L)));
|
||||||
|
given(buffer.getAllBatch(List.of("u:9"))).willReturn(Map.of());
|
||||||
|
|
||||||
|
int flushed = service.flushBuffered(10);
|
||||||
|
|
||||||
|
// 状态已消失(用户删除/清空历史或 TTL 过期):必须丢弃,退回队列会变成永不消失的僵尸条目
|
||||||
|
assertThat(flushed).isZero();
|
||||||
|
verify(buffer, never()).requeue(any());
|
||||||
|
verify(progressMapper, never()).selectBatchForPairs(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_flush_device_buffer_before_merging_and_clear_it_after() {
|
||||||
|
WatchProgressBuffer buffer = mock(WatchProgressBuffer.class);
|
||||||
|
given(buffer.getAll(any(InteractionIdentity.class))).willReturn(Map.of());
|
||||||
|
WatchProgressService service = serviceWithBuffer(buffer);
|
||||||
|
given(progressMapper.selectList(any())).willReturn(List.of());
|
||||||
|
given(historyMapper.selectList(any())).willReturn(List.of());
|
||||||
|
|
||||||
|
service.mergeDeviceIntoUser(9L, "device-a");
|
||||||
|
|
||||||
|
// 合并前先把缓冲落库,合并完再清掉设备侧缓冲
|
||||||
|
InOrder order = inOrder(buffer);
|
||||||
|
order.verify(buffer).getAll(any(InteractionIdentity.class));
|
||||||
|
order.verify(buffer).clear(any(InteractionIdentity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void should_drop_late_buffered_ref_when_row_is_already_deleted() {
|
||||||
|
WatchProgressBuffer buffer = mock(WatchProgressBuffer.class);
|
||||||
|
SqlSessionFactory sessionFactory = mock(SqlSessionFactory.class);
|
||||||
|
SqlSession session = mock(SqlSession.class);
|
||||||
|
WatchProgressMapper batchProgress = mock(WatchProgressMapper.class);
|
||||||
|
WatchHistoryMapper batchHistory = mock(WatchHistoryMapper.class);
|
||||||
|
given(sessionFactory.openSession(ExecutorType.BATCH, false)).willReturn(session);
|
||||||
|
given(session.getMapper(WatchProgressMapper.class)).willReturn(batchProgress);
|
||||||
|
given(session.getMapper(WatchHistoryMapper.class)).willReturn(batchHistory);
|
||||||
|
WatchProgressService service = serviceWithBuffer(buffer, sessionFactory);
|
||||||
|
|
||||||
|
given(buffer.drain(10)).willReturn(
|
||||||
|
List.of(new WatchProgressBuffer.IdentityRef("u:9", 9L, "", 5L)));
|
||||||
|
given(buffer.getAllBatch(List.of("u:9"))).willReturn(Map.of("u:9", Map.of(
|
||||||
|
5L, new WatchProgressBuffer.BufferedProgress(
|
||||||
|
5L, 88L, 1_000L, 2_000L, false, "feed", "", 1_700_000_000_000L))));
|
||||||
|
// 库里是逻辑删除行,且删除时刻晚于该条缓冲的上报时刻
|
||||||
|
WatchProgress hidden = progress(5L, 88L);
|
||||||
|
hidden.setUserId(9L);
|
||||||
|
hidden.setDeleted(1);
|
||||||
|
hidden.setUpdatedAt(LocalDateTime.of(2026, 10, 28, 12, 0));
|
||||||
|
given(progressMapper.selectBatchForPairs(any())).willReturn(List.of(hidden));
|
||||||
|
|
||||||
|
service.flushBuffered(10);
|
||||||
|
|
||||||
|
verify(batchProgress, never()).updateRowAny(any());
|
||||||
|
verify(batchHistory, never()).insert(any(WatchHistory.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private WatchProgressService serviceWithBuffer(WatchProgressBuffer buffer) {
|
||||||
|
return serviceWithBuffer(buffer, mock(SqlSessionFactory.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private WatchProgressService serviceWithBuffer(
|
||||||
|
WatchProgressBuffer buffer, SqlSessionFactory sessionFactory) {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
ObjectProvider<WatchProgressBuffer> provider = mock(ObjectProvider.class);
|
||||||
|
given(provider.getIfAvailable()).willReturn(buffer);
|
||||||
|
return new WatchProgressService(
|
||||||
|
progressMapper,
|
||||||
|
historyMapper,
|
||||||
|
dramaService,
|
||||||
|
episodeService,
|
||||||
|
provider,
|
||||||
|
sessionFactory,
|
||||||
|
new TransactionTemplate(mock(PlatformTransactionManager.class)));
|
||||||
|
}
|
||||||
|
|
||||||
private Drama drama(Long id, String title, int totalEpisodes) {
|
private Drama drama(Long id, String title, int totalEpisodes) {
|
||||||
Drama drama = new Drama();
|
Drama drama = new Drama();
|
||||||
drama.setId(id);
|
drama.setId(id);
|
||||||
|
|||||||
+8
-1
@@ -22,6 +22,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
|
|||||||
public class AccessDeniedRecorder {
|
public class AccessDeniedRecorder {
|
||||||
|
|
||||||
private final ObjectProvider<OperationLogSink> sinkProvider;
|
private final ObjectProvider<OperationLogSink> sinkProvider;
|
||||||
|
private final ObjectProvider<WebUtils> webUtilsProvider;
|
||||||
|
|
||||||
public void record(HttpServletRequest request) {
|
public void record(HttpServletRequest request) {
|
||||||
OperationLogSink sink = sinkProvider.getIfAvailable();
|
OperationLogSink sink = sinkProvider.getIfAvailable();
|
||||||
@@ -47,10 +48,16 @@ public class AccessDeniedRecorder {
|
|||||||
.status("FAIL")
|
.status("FAIL")
|
||||||
.errorMsg("无权限")
|
.errorMsg("无权限")
|
||||||
.durationMs(0)
|
.durationMs(0)
|
||||||
.ip(request == null ? "" : WebUtils.getClientIp(request))
|
.ip(request == null ? "" : clientIp(request))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
|
||||||
|
private String clientIp(HttpServletRequest request) {
|
||||||
|
WebUtils webUtils = webUtilsProvider.getIfAvailable();
|
||||||
|
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
|
||||||
|
}
|
||||||
|
|
||||||
/** 从当前线程取出请求,供全局异常处理使用。 */
|
/** 从当前线程取出请求,供全局异常处理使用。 */
|
||||||
public void recordCurrentRequest() {
|
public void recordCurrentRequest() {
|
||||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
|
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
|
||||||
|
|||||||
+8
-1
@@ -43,6 +43,7 @@ public class OperationLogAspect {
|
|||||||
|
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final ObjectProvider<OperationLogSink> sinkProvider;
|
private final ObjectProvider<OperationLogSink> sinkProvider;
|
||||||
|
private final ObjectProvider<WebUtils> webUtilsProvider;
|
||||||
|
|
||||||
@Around("@annotation(operationLog)")
|
@Around("@annotation(operationLog)")
|
||||||
public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable {
|
public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable {
|
||||||
@@ -86,10 +87,16 @@ public class OperationLogAspect {
|
|||||||
.status(error == null ? "SUCCESS" : "FAIL")
|
.status(error == null ? "SUCCESS" : "FAIL")
|
||||||
.errorMsg(error == null ? "" : truncate(error.getMessage()))
|
.errorMsg(error == null ? "" : truncate(error.getMessage()))
|
||||||
.durationMs(durationMs)
|
.durationMs(durationMs)
|
||||||
.ip(request == null ? "" : WebUtils.getClientIp(request))
|
.ip(request == null ? "" : clientIp(request))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
|
||||||
|
private String clientIp(HttpServletRequest request) {
|
||||||
|
WebUtils webUtils = webUtilsProvider.getIfAvailable();
|
||||||
|
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
|
||||||
|
}
|
||||||
|
|
||||||
/** 把方法入参整理成 JSON,文件只记名称和大小。 */
|
/** 把方法入参整理成 JSON,文件只记名称和大小。 */
|
||||||
private String body(ProceedingJoinPoint point) {
|
private String body(ProceedingJoinPoint point) {
|
||||||
Object[] args = point.getArgs();
|
Object[] args = point.getArgs();
|
||||||
|
|||||||
+2
@@ -62,6 +62,8 @@ public final class ImpersonationGuard {
|
|||||||
|
|
||||||
public static String clientIp() {
|
public static String clientIp() {
|
||||||
HttpServletRequest request = currentRequest();
|
HttpServletRequest request = currentRequest();
|
||||||
|
// 这里走静态 getClientIp——等价于 trusted-proxies 为空时的逻辑(只用 remoteAddr,不解析 XFF)。
|
||||||
|
// 这个类是纯静态工具(无 Spring 注入),且只在 Creator 代看场景用,安全影响低。
|
||||||
return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request);
|
return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -11,17 +11,17 @@ import org.springframework.stereotype.Component;
|
|||||||
@ConfigurationProperties(prefix = "fruitshorts.jwt")
|
@ConfigurationProperties(prefix = "fruitshorts.jwt")
|
||||||
public class JwtProperties {
|
public class JwtProperties {
|
||||||
|
|
||||||
/** 管理端签名密钥,长度必须 >= 32 字节。生产环境通过环境变量注入。 */
|
/** 管理端签名密钥,长度必须 >= 32 字节。**所有环境必须通过环境变量注入,不设任何默认值。** */
|
||||||
private String adminSecret = "fruitshorts-admin-dev-secret-change-me-in-production-32b";
|
private String adminSecret = "";
|
||||||
|
|
||||||
/** 管理端 token 有效期(小时)。 */
|
/** 管理端 token 有效期(小时)。 */
|
||||||
private int adminTtlHours = 12;
|
private int adminTtlHours = 12;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 客户端签名密钥。与管理端物理隔离:管理端 token 拿到客户端接口上无法通过验签,
|
* 客户端签名密钥。与管理端物理隔离:管理端 token 拿到客户端接口上无法通过验签,
|
||||||
* 反之亦然。生产环境必须通过环境变量注入,不要沿用默认值。
|
* 反之亦然。**所有环境必须通过环境变量注入,不设任何默认值。**
|
||||||
*/
|
*/
|
||||||
private String appSecret = "fruitshorts-app-dev-secret-change-me-in-production-32bytes";
|
private String appSecret = "";
|
||||||
|
|
||||||
/** 客户端 access token 有效期(分钟)。 */
|
/** 客户端 access token 有效期(分钟)。 */
|
||||||
private int appAccessTtlMinutes = 120;
|
private int appAccessTtlMinutes = 120;
|
||||||
|
|||||||
+4
-1
@@ -50,6 +50,9 @@ public class SecurityConfig {
|
|||||||
/* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */
|
/* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */
|
||||||
"/app/config",
|
"/app/config",
|
||||||
"/app/notices",
|
"/app/notices",
|
||||||
|
/* 奖励中心只读配置:登录前可浏览任务与活动,签到/领取仍需登录。 */
|
||||||
|
"/app/rewards/overview",
|
||||||
|
"/app/rewards/activities",
|
||||||
/* 服务条款与隐私协议:登录前就要能打开,按语言返回 HTML */
|
/* 服务条款与隐私协议:登录前就要能打开,按语言返回 HTML */
|
||||||
"/privacy/**",
|
"/privacy/**",
|
||||||
"/terms/**",
|
"/terms/**",
|
||||||
@@ -108,7 +111,7 @@ public class SecurityConfig {
|
|||||||
@Bean
|
@Bean
|
||||||
public CorsConfigurationSource corsConfigurationSource() {
|
public CorsConfigurationSource corsConfigurationSource() {
|
||||||
CorsConfiguration configuration = new CorsConfiguration();
|
CorsConfiguration configuration = new CorsConfiguration();
|
||||||
configuration.setAllowedOrigins(Arrays.stream(allowedOrigins.split(",")).map(String::trim).toList());
|
configuration.setAllowedOriginPatterns(Arrays.stream(allowedOrigins.split(",")).map(String::trim).toList());
|
||||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||||
configuration.setAllowedHeaders(List.of("*"));
|
configuration.setAllowedHeaders(List.of("*"));
|
||||||
configuration.setAllowCredentials(true);
|
configuration.setAllowCredentials(true);
|
||||||
|
|||||||
+6
@@ -58,4 +58,10 @@ public final class SecurityUtils {
|
|||||||
}
|
}
|
||||||
return loginUser.userId();
|
return loginUser.userId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 客户端匿名只读接口取当前用户,未登录或非客户端用户返回 null。 */
|
||||||
|
public static Long getAppUserIdOrNull() {
|
||||||
|
LoginUser loginUser = getLoginUserOrNull();
|
||||||
|
return isAppUser(loginUser) ? loginUser.userId() : null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,25 +3,146 @@
|
|||||||
package com.fruitshorts.framework.web;
|
package com.fruitshorts.framework.web;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
public final class WebUtils {
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取真实客户端 IP。
|
||||||
|
*
|
||||||
|
* <p>安全策略:默认信任 {@link HttpServletRequest#getRemoteAddr()} 本身,只有当
|
||||||
|
* 它属于配置的可信代理 CIDR 时才解析 X-Forwarded-For / X-Real-IP 等头。
|
||||||
|
* 这样客户端伪造的 XFF 不会生效,只有经 Nginx / K8s ingress 等前置代理转发的请求
|
||||||
|
* 才能带上可信的 XFF 链。
|
||||||
|
*
|
||||||
|
* <p>生产建议:同时开启 Tomcat RemoteIpValve(prod profile 已配置),让
|
||||||
|
* {@code getRemoteAddr()} 在经过代理后直接就是客户端真实 IP。此时可信代理列表
|
||||||
|
* 配成空即可,Valve 已经帮我们做了 XFF 解析。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class WebUtils {
|
||||||
|
|
||||||
private static final String UNKNOWN = "unknown";
|
private static final String UNKNOWN = "unknown";
|
||||||
|
private static final String[] PROXY_HEADERS = {"X-Forwarded-For", "X-Real-IP",
|
||||||
|
"Proxy-Client-IP", "WL-Proxy-Client-IP"};
|
||||||
|
|
||||||
private WebUtils() {
|
/** 可信代理 CIDR 列表,逗号分隔;空表示永不解析 XFF,直接用 remoteAddr。 */
|
||||||
|
@Value("${fruitshorts.web.trusted-proxies:}")
|
||||||
|
private String trustedProxies = "";
|
||||||
|
|
||||||
|
/** 纯静态调用路径(不依赖 Spring),供测试或无 IoC 场景使用。 */
|
||||||
|
public static String getClientIp(HttpServletRequest request) {
|
||||||
|
return resolve(request, List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 取真实客户端 IP,兼容 Nginx 反向代理。 */
|
/** Spring 注入版:自动按配置解析 XFF。 */
|
||||||
public static String getClientIp(HttpServletRequest request) {
|
public String clientIp(HttpServletRequest request) {
|
||||||
String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"};
|
List<String> cidrs = StringUtils.hasText(trustedProxies)
|
||||||
for (String header : headers) {
|
? Arrays.asList(trustedProxies.split(","))
|
||||||
|
: List.of();
|
||||||
|
return resolve(request, cidrs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String resolve(HttpServletRequest request, List<String> trustedCidrs) {
|
||||||
|
String remoteAddr = request.getRemoteAddr();
|
||||||
|
if (isTrustedProxy(remoteAddr, trustedCidrs)) {
|
||||||
|
String fromHeader = readProxyHeader(request);
|
||||||
|
if (StringUtils.hasText(fromHeader)) {
|
||||||
|
return fromHeader;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return remoteAddr;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String readProxyHeader(HttpServletRequest request) {
|
||||||
|
for (String header : PROXY_HEADERS) {
|
||||||
String value = request.getHeader(header);
|
String value = request.getHeader(header);
|
||||||
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) {
|
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) {
|
||||||
int comma = value.indexOf(',');
|
// XFF 链格式:client, proxy1, proxy2 —— 最左侧是原始客户端 IP
|
||||||
return comma > 0 ? value.substring(0, comma).trim() : value.trim();
|
String[] parts = value.split(",");
|
||||||
|
return parts[0].trim();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return request.getRemoteAddr();
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断 remoteAddr 是否属于可信代理。
|
||||||
|
*
|
||||||
|
* <p>CIDR 简化实现:只支持单个 IP 或 "/24" 这类前缀掩码,不支持复杂区间。
|
||||||
|
* 生产反代一般就是 127.0.0.1、10.0.0.0/8 这类,够用。
|
||||||
|
*/
|
||||||
|
static boolean isTrustedProxy(String remoteAddr, List<String> trustedCidrs) {
|
||||||
|
if (!StringUtils.hasText(remoteAddr) || trustedCidrs.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
InetAddress remote = InetAddress.getByName(remoteAddr.trim());
|
||||||
|
for (String cidr : trustedCidrs) {
|
||||||
|
if (cidrMatches(remote, cidr.trim())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (UnknownHostException ex) {
|
||||||
|
log.debug("无法解析 remoteAddr {} 为 IP,跳过 XFF 信任判定", remoteAddr);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean cidrMatches(InetAddress target, String cidr) {
|
||||||
|
if (!cidr.contains("/")) {
|
||||||
|
// 单 IP 精确匹配
|
||||||
|
InetAddress trusted;
|
||||||
|
try {
|
||||||
|
trusted = InetAddress.getByName(cidr);
|
||||||
|
} catch (UnknownHostException ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return trusted.equals(target);
|
||||||
|
}
|
||||||
|
String[] parts = cidr.split("/", 2);
|
||||||
|
String netPart = parts[0];
|
||||||
|
int prefixLen;
|
||||||
|
try {
|
||||||
|
prefixLen = Integer.parseInt(parts[1]);
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
InetAddress net;
|
||||||
|
try {
|
||||||
|
net = InetAddress.getByName(netPart);
|
||||||
|
} catch (UnknownHostException ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
byte[] targetBytes = target.getAddress();
|
||||||
|
byte[] netBytes = net.getAddress();
|
||||||
|
if (targetBytes.length != netBytes.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int fullBytes = prefixLen / 8;
|
||||||
|
int remainingBits = prefixLen % 8;
|
||||||
|
for (int i = 0; i < fullBytes; i++) {
|
||||||
|
if (targetBytes[i] != netBytes[i]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (remainingBits > 0 && fullBytes < targetBytes.length) {
|
||||||
|
int mask = (0xFF << (8 - remainingBits)) & 0xFF;
|
||||||
|
if ((targetBytes[fullBytes] & mask) != (netBytes[fullBytes] & mask)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Spring 直接实例化;保留 package-private 方便单测 new。 */
|
||||||
|
WebUtils() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 奖励中心活动展示卡片。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_activity")
|
||||||
|
public class RewardActivity {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private String code;
|
||||||
|
private String coverUrl;
|
||||||
|
private String actionType;
|
||||||
|
private String actionUrl;
|
||||||
|
private String titleId;
|
||||||
|
private String titleEn;
|
||||||
|
private String titleZh;
|
||||||
|
private String summaryId;
|
||||||
|
private String summaryEn;
|
||||||
|
private String summaryZh;
|
||||||
|
private String ctaId;
|
||||||
|
private String ctaEn;
|
||||||
|
private String ctaZh;
|
||||||
|
private Integer sort;
|
||||||
|
private Integer status;
|
||||||
|
private LocalDateTime startAt;
|
||||||
|
private LocalDateTime endAt;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 用户签到事实,日期唯一用于幂等防刷。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_checkin_record")
|
||||||
|
public class RewardCheckinRecord {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private Long userId;
|
||||||
|
private Long taskId;
|
||||||
|
private LocalDate checkinDate;
|
||||||
|
private Integer dayIndex;
|
||||||
|
private Integer streak;
|
||||||
|
private Long rewardCoin;
|
||||||
|
private Long grantId;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 签到周期中某一天的金币奖励。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_checkin_rule_day")
|
||||||
|
public class RewardCheckinRuleDay {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private Long taskId;
|
||||||
|
private Integer dayIndex;
|
||||||
|
private Long rewardCoin;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 服务端已验证奖励事件,用幂等键防止重复上报累计。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_event_log")
|
||||||
|
public class RewardEventLog {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private Long userId;
|
||||||
|
private String eventType;
|
||||||
|
private String sourceId;
|
||||||
|
private Long eventValue;
|
||||||
|
private String idempotentKey;
|
||||||
|
private LocalDateTime occurredAt;
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 奖励发放单,关联钱包流水并保留操作审计信息。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_grant")
|
||||||
|
public class RewardGrant {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private Long userId;
|
||||||
|
private Long taskId;
|
||||||
|
private String cycleKey;
|
||||||
|
private Integer claimSeq;
|
||||||
|
private Long amount;
|
||||||
|
private String status;
|
||||||
|
private String idempotentKey;
|
||||||
|
private Long coinLedgerId;
|
||||||
|
private String source;
|
||||||
|
private Long operatorId;
|
||||||
|
private String failureReason;
|
||||||
|
private LocalDateTime grantedAt;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 奖励任务配置,后台维护后由客户端奖励页读取。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_task")
|
||||||
|
public class RewardTask {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private String code;
|
||||||
|
private String sectionCode;
|
||||||
|
private String type;
|
||||||
|
private String verifyMode;
|
||||||
|
private Long targetValue;
|
||||||
|
private Long rewardCoin;
|
||||||
|
private String cycleType;
|
||||||
|
private Integer cycleLimit;
|
||||||
|
private String actionType;
|
||||||
|
private String actionUrl;
|
||||||
|
private String iconUrl;
|
||||||
|
private String titleId;
|
||||||
|
private String titleEn;
|
||||||
|
private String titleZh;
|
||||||
|
private String subtitleId;
|
||||||
|
private String subtitleEn;
|
||||||
|
private String subtitleZh;
|
||||||
|
private String ctaId;
|
||||||
|
private String ctaEn;
|
||||||
|
private String ctaZh;
|
||||||
|
private String sectionTitleId;
|
||||||
|
private String sectionTitleEn;
|
||||||
|
private String sectionTitleZh;
|
||||||
|
private String configJson;
|
||||||
|
private Integer sort;
|
||||||
|
private Integer status;
|
||||||
|
private LocalDateTime startAt;
|
||||||
|
private LocalDateTime endAt;
|
||||||
|
private Integer version;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 用户任务在一个周期内的服务端进度。 */
|
||||||
|
@Data
|
||||||
|
@TableName("reward_task_progress")
|
||||||
|
public class RewardTaskProgress {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private Long id;
|
||||||
|
private Long userId;
|
||||||
|
private Long taskId;
|
||||||
|
private String cycleKey;
|
||||||
|
private Long progressValue;
|
||||||
|
private Long targetValue;
|
||||||
|
private String status;
|
||||||
|
private Integer claimSeq;
|
||||||
|
private LocalDateTime completedAt;
|
||||||
|
private LocalDateTime claimedAt;
|
||||||
|
private LocalDateTime lastEventAt;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardActivity;
|
||||||
|
|
||||||
|
/** 奖励活动访问。 */
|
||||||
|
public interface RewardActivityMapper extends BaseMapper<RewardActivity> {
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardCheckinRecord;
|
||||||
|
|
||||||
|
/** 用户签到事实访问。 */
|
||||||
|
public interface RewardCheckinRecordMapper extends BaseMapper<RewardCheckinRecord> {
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardCheckinRuleDay;
|
||||||
|
|
||||||
|
/** 签到规则访问。 */
|
||||||
|
public interface RewardCheckinRuleDayMapper extends BaseMapper<RewardCheckinRuleDay> {
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardEventLog;
|
||||||
|
|
||||||
|
/** 服务端奖励事件访问。 */
|
||||||
|
public interface RewardEventLogMapper extends BaseMapper<RewardEventLog> {
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardGrant;
|
||||||
|
|
||||||
|
/** 奖励发放单访问。 */
|
||||||
|
public interface RewardGrantMapper extends BaseMapper<RewardGrant> {
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTask;
|
||||||
|
|
||||||
|
/** 奖励任务表访问。 */
|
||||||
|
public interface RewardTaskMapper extends BaseMapper<RewardTask> {
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.dal.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTaskProgress;
|
||||||
|
|
||||||
|
/** 用户奖励进度表访问。 */
|
||||||
|
public interface RewardTaskProgressMapper extends BaseMapper<RewardTaskProgress> {
|
||||||
|
}
|
||||||
+136
@@ -0,0 +1,136 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardActivity;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardActivityMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivitySaveReqVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import com.fruitshorts.common.pojo.PageResult;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/** 奖励中心活动的后台配置服务。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RewardActivityAdminService {
|
||||||
|
|
||||||
|
private final RewardActivityMapper activityMapper;
|
||||||
|
|
||||||
|
/** 分页查询活动配置。 */
|
||||||
|
public PageResult<RewardActivityRespVO> page(RewardActivityQueryReqVO req) {
|
||||||
|
Page<RewardActivity> page = new Page<>(req.getSafePageIndex(), req.getSafePageSize());
|
||||||
|
IPage<RewardActivity> result = activityMapper.selectPage(page, Wrappers.<RewardActivity>lambdaQuery()
|
||||||
|
.eq(RewardActivity::getDeleted, 0)
|
||||||
|
.eq(req.getStatus() != null, RewardActivity::getStatus, req.getStatus())
|
||||||
|
.and(StringUtils.hasText(req.getKeyword()), w -> w
|
||||||
|
.like(RewardActivity::getCode, req.getKeyword())
|
||||||
|
.or().like(RewardActivity::getTitleId, req.getKeyword())
|
||||||
|
.or().like(RewardActivity::getTitleEn, req.getKeyword())
|
||||||
|
.or().like(RewardActivity::getTitleZh, req.getKeyword()))
|
||||||
|
.orderByAsc(RewardActivity::getSort)
|
||||||
|
.orderByDesc(RewardActivity::getId));
|
||||||
|
return new PageResult<>(result.getTotal(), result.getRecords().stream()
|
||||||
|
.map(RewardActivityRespVO::of).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查询活动详情。 */
|
||||||
|
public RewardActivityRespVO detail(Long id) {
|
||||||
|
return RewardActivityRespVO.of(getExisting(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 新建活动,默认下线,避免半配置内容立即展示。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Long create(RewardActivitySaveReqVO req) {
|
||||||
|
validate(req);
|
||||||
|
String code = req.getCode().trim();
|
||||||
|
requireCodeFree(code, null);
|
||||||
|
RewardActivity activity = new RewardActivity();
|
||||||
|
activity.setCode(code);
|
||||||
|
apply(activity, req);
|
||||||
|
activity.setStatus(0);
|
||||||
|
activityMapper.insert(activity);
|
||||||
|
return activity.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 编辑活动,保留现有上下线状态。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void update(Long id, RewardActivitySaveReqVO req) {
|
||||||
|
validate(req);
|
||||||
|
RewardActivity activity = getExisting(id);
|
||||||
|
String code = req.getCode().trim();
|
||||||
|
requireCodeFree(code, id);
|
||||||
|
activity.setCode(code);
|
||||||
|
apply(activity, req);
|
||||||
|
activityMapper.updateById(activity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 上线或下线活动。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void updateStatus(Long id, Integer status) {
|
||||||
|
if (status == null || (status != 0 && status != 1)) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST, "状态只能是 0 或 1");
|
||||||
|
}
|
||||||
|
RewardActivity activity = getExisting(id);
|
||||||
|
activity.setStatus(status);
|
||||||
|
activityMapper.updateById(activity);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validate(RewardActivitySaveReqVO req) {
|
||||||
|
if (req == null || !StringUtils.hasText(req.getCode()) || !StringUtils.hasText(req.getTitleId())) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST, "请填写活动编码和印尼语标题");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void apply(RewardActivity activity, RewardActivitySaveReqVO req) {
|
||||||
|
activity.setCoverUrl(valueOrEmpty(req.getCoverUrl()));
|
||||||
|
activity.setActionType(valueOrDefault(req.getActionType(), "NONE"));
|
||||||
|
activity.setActionUrl(valueOrEmpty(req.getActionUrl()));
|
||||||
|
activity.setTitleId(req.getTitleId().trim());
|
||||||
|
activity.setTitleEn(valueOrEmpty(req.getTitleEn()));
|
||||||
|
activity.setTitleZh(valueOrEmpty(req.getTitleZh()));
|
||||||
|
activity.setSummaryId(valueOrEmpty(req.getSummaryId()));
|
||||||
|
activity.setSummaryEn(valueOrEmpty(req.getSummaryEn()));
|
||||||
|
activity.setSummaryZh(valueOrEmpty(req.getSummaryZh()));
|
||||||
|
activity.setCtaId(valueOrEmpty(req.getCtaId()));
|
||||||
|
activity.setCtaEn(valueOrEmpty(req.getCtaEn()));
|
||||||
|
activity.setCtaZh(valueOrEmpty(req.getCtaZh()));
|
||||||
|
activity.setSort(req.getSort() == null ? 0 : req.getSort());
|
||||||
|
activity.setStartAt(req.getStartAt());
|
||||||
|
activity.setEndAt(req.getEndAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardActivity getExisting(Long id) {
|
||||||
|
RewardActivity activity = id == null ? null : activityMapper.selectById(id);
|
||||||
|
if (activity == null || Integer.valueOf(1).equals(activity.getDeleted())) {
|
||||||
|
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "奖励活动不存在");
|
||||||
|
}
|
||||||
|
return activity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireCodeFree(String code, Long excludeId) {
|
||||||
|
Long count = activityMapper.selectCount(Wrappers.<RewardActivity>lambdaQuery()
|
||||||
|
.eq(RewardActivity::getCode, code)
|
||||||
|
.eq(RewardActivity::getDeleted, 0)
|
||||||
|
.ne(excludeId != null, RewardActivity::getId, excludeId));
|
||||||
|
if (count != null && count > 0) {
|
||||||
|
throw new ServiceException(ErrorCode.DATA_EXISTS, "活动编码已存在:" + code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String valueOrEmpty(String value) {
|
||||||
|
return value == null ? "" : value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String valueOrDefault(String value, String fallback) {
|
||||||
|
return StringUtils.hasText(value) ? value.trim() : fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
+170
@@ -0,0 +1,170 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardCheckinRecord;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardCheckinRuleDay;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTask;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardCheckinRecordMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardCheckinRuleDayMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardTaskMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinRuleDayReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinRuleSaveReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardCheckinVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardRuleDayVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 每日签到规则与签到发放。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RewardCheckinService {
|
||||||
|
|
||||||
|
private static final String CHECKIN_CODE = "daily_check_in";
|
||||||
|
private static final String CHECKIN_TYPE = RewardTaskService.TYPE_DAILY_CHECK_IN;
|
||||||
|
|
||||||
|
private final RewardTaskMapper taskMapper;
|
||||||
|
private final RewardCheckinRuleDayMapper ruleMapper;
|
||||||
|
private final RewardCheckinRecordMapper recordMapper;
|
||||||
|
private final RewardGrantService grantService;
|
||||||
|
|
||||||
|
/** 客户端签到状态。 */
|
||||||
|
public RewardCheckinVO status(Long userId) {
|
||||||
|
RewardTask task = task();
|
||||||
|
List<RewardCheckinRuleDay> rules = rules(task.getId());
|
||||||
|
if (userId == null) {
|
||||||
|
return anonymousStatus(task, rules);
|
||||||
|
}
|
||||||
|
RewardCheckinRecord latest = latest(userId, task.getId());
|
||||||
|
LocalDate today = LocalDate.now(RewardTaskService.REWARD_ZONE);
|
||||||
|
boolean checked = recordMapper.selectCount(Wrappers.<RewardCheckinRecord>lambdaQuery()
|
||||||
|
.eq(RewardCheckinRecord::getUserId, userId).eq(RewardCheckinRecord::getTaskId, task.getId())
|
||||||
|
.eq(RewardCheckinRecord::getCheckinDate, today)) > 0;
|
||||||
|
int currentDay = latest == null ? 1 : Math.min(latest.getDayIndex() + 1, rules.size());
|
||||||
|
RewardCheckinVO vo = new RewardCheckinVO();
|
||||||
|
vo.setTaskId(task.getId());
|
||||||
|
vo.setCheckedInToday(checked);
|
||||||
|
vo.setStreak(latest == null ? 0 : latest.getStreak());
|
||||||
|
vo.setCurrentDay(currentDay);
|
||||||
|
vo.setDays(rules.stream().map(rule -> new RewardRuleDayVO(rule.getDayIndex(), rule.getRewardCoin(),
|
||||||
|
checked && latest != null && rule.getDayIndex() <= latest.getDayIndex(),
|
||||||
|
rule.getDayIndex() == currentDay)).toList());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardCheckinVO anonymousStatus(RewardTask task, List<RewardCheckinRuleDay> rules) {
|
||||||
|
RewardCheckinVO vo = new RewardCheckinVO();
|
||||||
|
vo.setTaskId(task.getId());
|
||||||
|
vo.setCheckedInToday(false);
|
||||||
|
vo.setStreak(0);
|
||||||
|
vo.setCurrentDay(1);
|
||||||
|
vo.setDays(rules.stream().map(rule -> new RewardRuleDayVO(
|
||||||
|
rule.getDayIndex(), rule.getRewardCoin(), false, rule.getDayIndex() == 1)).toList());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 后台查看当前签到规则。 */
|
||||||
|
public List<RewardRuleDayVO> rulesForAdmin() {
|
||||||
|
RewardTask task = task();
|
||||||
|
return rules(task.getId()).stream()
|
||||||
|
.map(rule -> new RewardRuleDayVO(rule.getDayIndex(), rule.getRewardCoin(), false, false))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 客户端执行签到,按印尼时区计算连续天数。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public RewardCheckinRespVO checkIn(Long userId) {
|
||||||
|
RewardTask task = task();
|
||||||
|
LocalDate today = LocalDate.now(RewardTaskService.REWARD_ZONE);
|
||||||
|
RewardCheckinRecord existed = recordMapper.selectOne(Wrappers.<RewardCheckinRecord>lambdaQuery()
|
||||||
|
.eq(RewardCheckinRecord::getUserId, userId).eq(RewardCheckinRecord::getTaskId, task.getId())
|
||||||
|
.eq(RewardCheckinRecord::getCheckinDate, today).last("limit 1"));
|
||||||
|
if (existed != null) return toResp(existed, true, userId);
|
||||||
|
List<RewardCheckinRuleDay> rules = rules(task.getId());
|
||||||
|
RewardCheckinRecord latest = latest(userId, task.getId());
|
||||||
|
int streak = latest != null && latest.getCheckinDate().plusDays(1).equals(today)
|
||||||
|
? latest.getStreak() + 1 : 1;
|
||||||
|
int dayIndex = ((streak - 1) % rules.size()) + 1;
|
||||||
|
RewardCheckinRuleDay rule = rules.stream().filter(item -> item.getDayIndex() == dayIndex).findFirst()
|
||||||
|
.orElseThrow(() -> new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED, "签到规则未配置"));
|
||||||
|
String key = "reward:checkin:" + userId + ":" + today;
|
||||||
|
var grant = grantService.grant(userId, task.getId(), today.toString(), rule.getRewardCoin(),
|
||||||
|
RewardGrantService.SOURCE_APP, 0L, key);
|
||||||
|
RewardCheckinRecord record = new RewardCheckinRecord();
|
||||||
|
record.setUserId(userId);
|
||||||
|
record.setTaskId(task.getId());
|
||||||
|
record.setCheckinDate(today);
|
||||||
|
record.setDayIndex(dayIndex);
|
||||||
|
record.setStreak(streak);
|
||||||
|
record.setRewardCoin(rule.getRewardCoin());
|
||||||
|
record.setGrantId(grant.getId());
|
||||||
|
try {
|
||||||
|
recordMapper.insert(record);
|
||||||
|
} catch (DuplicateKeyException ex) {
|
||||||
|
RewardCheckinRecord raced = recordMapper.selectOne(Wrappers.<RewardCheckinRecord>lambdaQuery()
|
||||||
|
.eq(RewardCheckinRecord::getUserId, userId).eq(RewardCheckinRecord::getTaskId, task.getId())
|
||||||
|
.eq(RewardCheckinRecord::getCheckinDate, today).last("limit 1"));
|
||||||
|
if (raced != null) return toResp(raced, true, userId);
|
||||||
|
throw ex;
|
||||||
|
}
|
||||||
|
return toResp(record, false, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 后台覆盖签到规则,按天数唯一校验。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void saveRules(RewardCheckinRuleSaveReqVO req) {
|
||||||
|
RewardTask task = task();
|
||||||
|
long distinct = req.getDays().stream().map(RewardCheckinRuleDayReqVO::getDayIndex).distinct().count();
|
||||||
|
if (distinct != req.getDays().size()) throw new ServiceException(ErrorCode.BAD_REQUEST, "签到天数不能重复");
|
||||||
|
ruleMapper.delete(Wrappers.<RewardCheckinRuleDay>lambdaQuery().eq(RewardCheckinRuleDay::getTaskId, task.getId()));
|
||||||
|
for (RewardCheckinRuleDayReqVO item : req.getDays()) {
|
||||||
|
RewardCheckinRuleDay row = new RewardCheckinRuleDay();
|
||||||
|
row.setTaskId(task.getId());
|
||||||
|
row.setDayIndex(item.getDayIndex());
|
||||||
|
row.setRewardCoin(item.getRewardCoin());
|
||||||
|
ruleMapper.insert(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardTask task() {
|
||||||
|
RewardTask task = taskMapper.selectOne(Wrappers.<RewardTask>lambdaQuery()
|
||||||
|
.eq(RewardTask::getCode, CHECKIN_CODE).eq(RewardTask::getType, CHECKIN_TYPE)
|
||||||
|
.eq(RewardTask::getStatus, 1).eq(RewardTask::getDeleted, 0).last("limit 1"));
|
||||||
|
if (task == null) throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "签到任务未配置");
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<RewardCheckinRuleDay> rules(Long taskId) {
|
||||||
|
List<RewardCheckinRuleDay> rows = ruleMapper.selectList(Wrappers.<RewardCheckinRuleDay>lambdaQuery()
|
||||||
|
.eq(RewardCheckinRuleDay::getTaskId, taskId).orderByAsc(RewardCheckinRuleDay::getDayIndex));
|
||||||
|
if (rows.isEmpty()) throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "签到规则未配置");
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardCheckinRecord latest(Long userId, Long taskId) {
|
||||||
|
return recordMapper.selectOne(Wrappers.<RewardCheckinRecord>lambdaQuery()
|
||||||
|
.eq(RewardCheckinRecord::getUserId, userId).eq(RewardCheckinRecord::getTaskId, taskId)
|
||||||
|
.orderByDesc(RewardCheckinRecord::getCheckinDate).last("limit 1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardCheckinRespVO toResp(RewardCheckinRecord record, boolean existed, Long userId) {
|
||||||
|
RewardCheckinRespVO vo = new RewardCheckinRespVO();
|
||||||
|
vo.setTaskId(record.getTaskId());
|
||||||
|
vo.setGrantId(record.getGrantId());
|
||||||
|
vo.setDayIndex(record.getDayIndex());
|
||||||
|
vo.setStreak(record.getStreak());
|
||||||
|
vo.setRewardCoin(record.getRewardCoin());
|
||||||
|
vo.setCoinBalance(grantService.balance(userId));
|
||||||
|
vo.setAlreadyCheckedIn(existed);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
}
|
||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.fruitshorts.commerce.dal.entity.CoinLedger;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardGrant;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTask;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTaskProgress;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardGrantMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardTaskProgressMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardClaimRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardGrantQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardGrantRespVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import com.fruitshorts.common.pojo.PageResult;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 奖励发放、任务领取和人工补发,统一复用钱包流水。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RewardGrantService {
|
||||||
|
|
||||||
|
public static final String STATUS_PENDING = "PENDING";
|
||||||
|
public static final String STATUS_GRANTED = "GRANTED";
|
||||||
|
public static final String SOURCE_APP = "APP";
|
||||||
|
public static final String SOURCE_ADMIN = "ADMIN";
|
||||||
|
|
||||||
|
private final RewardGrantMapper grantMapper;
|
||||||
|
private final RewardTaskProgressMapper progressMapper;
|
||||||
|
private final WalletServiceFacade wallet;
|
||||||
|
|
||||||
|
/** 领取已完成任务。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public RewardClaimRespVO claim(Long userId, RewardTask task, RewardTaskProgress progress) {
|
||||||
|
if (progress == null || (!RewardTaskService.STATUS_COMPLETED.equals(progress.getStatus())
|
||||||
|
&& !RewardTaskService.STATUS_CLAIMED.equals(progress.getStatus()))) {
|
||||||
|
throw new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED, "任务尚未完成");
|
||||||
|
}
|
||||||
|
String key = "reward:" + task.getCode() + ":" + userId + ":" + progress.getCycleKey();
|
||||||
|
boolean existed = grantMapper.selectCount(Wrappers.<RewardGrant>lambdaQuery()
|
||||||
|
.eq(RewardGrant::getIdempotentKey, key)) > 0;
|
||||||
|
RewardGrant grant = grant(userId, task.getId(), progress.getCycleKey(), task.getRewardCoin(),
|
||||||
|
SOURCE_APP, 0L, key);
|
||||||
|
RewardClaimRespVO result = new RewardClaimRespVO();
|
||||||
|
result.setTaskId(task.getId());
|
||||||
|
result.setGrantId(grant.getId());
|
||||||
|
result.setRewardCoin(grant.getAmount());
|
||||||
|
result.setCoinBalance(wallet.balance(userId));
|
||||||
|
result.setAlreadyGranted(existed);
|
||||||
|
progress.setStatus(RewardTaskService.STATUS_CLAIMED);
|
||||||
|
progress.setClaimedAt(LocalDateTime.now());
|
||||||
|
progressMapper.updateById(progress);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统一发放事务;先登记发放单,再写钱包流水,最后回填流水 id。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public RewardGrant grant(Long userId, Long taskId, String cycleKey, Long amount,
|
||||||
|
String source, Long operatorId, String idempotentKey) {
|
||||||
|
if (amount == null || amount <= 0) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST, "奖励金币必须大于 0");
|
||||||
|
}
|
||||||
|
RewardGrant existed = grantMapper.selectOne(Wrappers.<RewardGrant>lambdaQuery()
|
||||||
|
.eq(RewardGrant::getIdempotentKey, idempotentKey).last("limit 1"));
|
||||||
|
if (existed != null && STATUS_GRANTED.equals(existed.getStatus())) return existed;
|
||||||
|
RewardGrant row = existed == null ? newGrant(userId, taskId, cycleKey, amount, source, operatorId, idempotentKey) : existed;
|
||||||
|
if (existed == null) {
|
||||||
|
try {
|
||||||
|
grantMapper.insert(row);
|
||||||
|
} catch (DuplicateKeyException ex) {
|
||||||
|
RewardGrant raced = grantMapper.selectOne(Wrappers.<RewardGrant>lambdaQuery()
|
||||||
|
.eq(RewardGrant::getIdempotentKey, idempotentKey).last("limit 1"));
|
||||||
|
if (raced != null) return raced;
|
||||||
|
throw ex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CoinLedger ledger = wallet.change(userId, amount, idempotentKey, source, operatorId);
|
||||||
|
row.setStatus(STATUS_GRANTED);
|
||||||
|
row.setCoinLedgerId(ledger.getId());
|
||||||
|
row.setGrantedAt(LocalDateTime.now());
|
||||||
|
row.setFailureReason("");
|
||||||
|
grantMapper.updateById(row);
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 后台分页查看发放记录。 */
|
||||||
|
public PageResult<RewardGrantRespVO> page(RewardGrantQueryReqVO req) {
|
||||||
|
Page<RewardGrant> page = new Page<>(req.getSafePageIndex(), req.getSafePageSize());
|
||||||
|
IPage<RewardGrant> result = grantMapper.selectPage(page, Wrappers.<RewardGrant>lambdaQuery()
|
||||||
|
.eq(req.getUserId() != null, RewardGrant::getUserId, req.getUserId())
|
||||||
|
.eq(req.getTaskId() != null, RewardGrant::getTaskId, req.getTaskId())
|
||||||
|
.eq(StringUtils.hasText(req.getStatus()), RewardGrant::getStatus, req.getStatus())
|
||||||
|
.eq(StringUtils.hasText(req.getSource()), RewardGrant::getSource, req.getSource())
|
||||||
|
.orderByDesc(RewardGrant::getCreatedAt));
|
||||||
|
return new PageResult<>(result.getTotal(), result.getRecords().stream()
|
||||||
|
.map(RewardGrantRespVO::of).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 返回奖励发放后的钱包余额。 */
|
||||||
|
public Long balance(Long userId) {
|
||||||
|
return wallet.balance(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 后台人工补发奖励,幂等键为空时生成一次性操作键。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public RewardGrantRespVO manualGrant(Long userId, Long taskId, Long amount,
|
||||||
|
String idempotentKey, Long operatorId) {
|
||||||
|
String key = StringUtils.hasText(idempotentKey) ? idempotentKey.trim()
|
||||||
|
: "reward-admin:" + operatorId + ":" + userId + ":" + System.currentTimeMillis();
|
||||||
|
RewardGrant grant = grant(userId, taskId, "MANUAL", amount, SOURCE_ADMIN, operatorId, key);
|
||||||
|
return RewardGrantRespVO.of(grant);
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardGrant newGrant(Long userId, Long taskId, String cycleKey, Long amount,
|
||||||
|
String source, Long operatorId, String key) {
|
||||||
|
RewardGrant row = new RewardGrant();
|
||||||
|
row.setUserId(userId);
|
||||||
|
row.setTaskId(taskId == null ? 0L : taskId);
|
||||||
|
row.setCycleKey(cycleKey == null ? "MANUAL" : cycleKey);
|
||||||
|
row.setClaimSeq(1);
|
||||||
|
row.setAmount(amount);
|
||||||
|
row.setStatus(STATUS_PENDING);
|
||||||
|
row.setIdempotentKey(key);
|
||||||
|
row.setCoinLedgerId(0L);
|
||||||
|
row.setSource(source);
|
||||||
|
row.setOperatorId(operatorId == null ? 0L : operatorId);
|
||||||
|
row.setFailureReason("");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
}
|
||||||
+77
@@ -0,0 +1,77 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTask;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskSaveReqVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/** 奖励任务后台配置的字段校验、查询与复制规则。 */
|
||||||
|
final class RewardTaskConfiguration {
|
||||||
|
|
||||||
|
private RewardTaskConfiguration() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static LambdaQueryWrapper<RewardTask> taskQuery(RewardTaskQueryReqVO req) {
|
||||||
|
return Wrappers.<RewardTask>lambdaQuery().eq(RewardTask::getDeleted, 0)
|
||||||
|
.eq(StringUtils.hasText(req.getType()), RewardTask::getType, req.getType())
|
||||||
|
.eq(StringUtils.hasText(req.getSectionCode()), RewardTask::getSectionCode, req.getSectionCode())
|
||||||
|
.eq(req.getStatus() != null, RewardTask::getStatus, req.getStatus())
|
||||||
|
.and(StringUtils.hasText(req.getKeyword()), wrapper -> wrapper
|
||||||
|
.like(RewardTask::getCode, req.getKeyword())
|
||||||
|
.or().like(RewardTask::getTitleId, req.getKeyword())
|
||||||
|
.or().like(RewardTask::getTitleEn, req.getKeyword()))
|
||||||
|
.orderByAsc(RewardTask::getSort).orderByDesc(RewardTask::getId);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void validate(RewardTaskSaveReqVO req) {
|
||||||
|
if (req.getStartAt() != null && req.getEndAt() != null
|
||||||
|
&& req.getStartAt().isAfter(req.getEndAt())) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST, "任务开始时间不能晚于结束时间");
|
||||||
|
}
|
||||||
|
if (RewardTaskService.CYCLE_ONCE.equals(req.getCycleType())
|
||||||
|
&& req.getCycleLimit() != null && req.getCycleLimit() > 1) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST, "一次性任务的周期上限只能为 1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void apply(RewardTask task, RewardTaskSaveReqVO req) {
|
||||||
|
task.setSectionCode(req.getSectionCode().trim());
|
||||||
|
task.setType(req.getType().trim().toUpperCase(Locale.ROOT));
|
||||||
|
task.setVerifyMode(StringUtils.hasText(req.getVerifyMode()) ? req.getVerifyMode() : "SERVER");
|
||||||
|
task.setTargetValue(req.getTargetValue());
|
||||||
|
task.setRewardCoin(req.getRewardCoin());
|
||||||
|
task.setCycleType(req.getCycleType().trim().toUpperCase(Locale.ROOT));
|
||||||
|
task.setCycleLimit(req.getCycleLimit() == null ? 1 : req.getCycleLimit());
|
||||||
|
task.setActionType(StringUtils.hasText(req.getActionType()) ? req.getActionType() : "NONE");
|
||||||
|
task.setActionUrl(blank(req.getActionUrl()));
|
||||||
|
task.setIconUrl(blank(req.getIconUrl()));
|
||||||
|
task.setTitleId(req.getTitleId().trim());
|
||||||
|
task.setTitleEn(blank(req.getTitleEn()));
|
||||||
|
task.setTitleZh(blank(req.getTitleZh()));
|
||||||
|
task.setSubtitleId(blank(req.getSubtitleId()));
|
||||||
|
task.setSubtitleEn(blank(req.getSubtitleEn()));
|
||||||
|
task.setSubtitleZh(blank(req.getSubtitleZh()));
|
||||||
|
task.setCtaId(blank(req.getCtaId()));
|
||||||
|
task.setCtaEn(blank(req.getCtaEn()));
|
||||||
|
task.setCtaZh(blank(req.getCtaZh()));
|
||||||
|
task.setSectionTitleId(req.getSectionTitleId().trim());
|
||||||
|
task.setSectionTitleEn(blank(req.getSectionTitleEn()));
|
||||||
|
task.setSectionTitleZh(blank(req.getSectionTitleZh()));
|
||||||
|
task.setConfigJson(blank(req.getConfigJson()));
|
||||||
|
task.setSort(req.getSort() == null ? 0 : req.getSort());
|
||||||
|
task.setStartAt(req.getStartAt());
|
||||||
|
task.setEndAt(req.getEndAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String blank(String value) {
|
||||||
|
return value == null ? "" : value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
+306
@@ -0,0 +1,306 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardActivity;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardEventLog;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTask;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTaskProgress;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardActivityMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardEventLogMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardTaskMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.mapper.RewardTaskProgressMapper;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardOverviewVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardSectionVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskItemVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskQueryReqVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskRespVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskSaveReqVO;
|
||||||
|
import com.fruitshorts.common.exception.ErrorCode;
|
||||||
|
import com.fruitshorts.common.exception.ServiceException;
|
||||||
|
import com.fruitshorts.common.pojo.PageResult;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.temporal.WeekFields;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** 奖励任务配置、用户进度与客户端总览。 */
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RewardTaskService {
|
||||||
|
|
||||||
|
public static final String TYPE_DAILY_CHECK_IN = "DAILY_CHECK_IN";
|
||||||
|
public static final String TYPE_WATCH_DURATION = "WATCH_DURATION";
|
||||||
|
public static final String TYPE_WATCH_EPISODES = "WATCH_EPISODES";
|
||||||
|
public static final String TYPE_FIRST_LOGIN = "FIRST_LOGIN";
|
||||||
|
public static final String TYPE_COMPLETE_PROFILE = "COMPLETE_PROFILE";
|
||||||
|
public static final String TYPE_FIRST_PURCHASE = "FIRST_PURCHASE";
|
||||||
|
public static final String STATUS_PROGRESS = "IN_PROGRESS";
|
||||||
|
public static final String STATUS_COMPLETED = "COMPLETED";
|
||||||
|
public static final String STATUS_CLAIMED = "CLAIMED";
|
||||||
|
public static final String CYCLE_ONCE = "ONCE";
|
||||||
|
public static final String CYCLE_DAILY = "DAILY";
|
||||||
|
public static final String CYCLE_WEEKLY = "WEEKLY";
|
||||||
|
public static final ZoneId REWARD_ZONE = ZoneId.of("Asia/Jakarta");
|
||||||
|
|
||||||
|
private final RewardTaskMapper taskMapper;
|
||||||
|
private final RewardTaskProgressMapper progressMapper;
|
||||||
|
private final RewardEventLogMapper eventLogMapper;
|
||||||
|
private final RewardActivityMapper activityMapper;
|
||||||
|
|
||||||
|
/** 后台分页查询任务配置。 */
|
||||||
|
public PageResult<RewardTaskRespVO> page(RewardTaskQueryReqVO req) {
|
||||||
|
Page<RewardTask> page = new Page<>(req.getSafePageIndex(), req.getSafePageSize());
|
||||||
|
IPage<RewardTask> result = taskMapper.selectPage(page, RewardTaskConfiguration.taskQuery(req));
|
||||||
|
return new PageResult<>(result.getTotal(), result.getRecords().stream()
|
||||||
|
.map(RewardTaskRespVO::of).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查询任务详情。 */
|
||||||
|
public RewardTaskRespVO detail(Long id) {
|
||||||
|
return RewardTaskRespVO.of(getExisting(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 新建奖励任务,默认下线,避免半配置立即暴露给客户端。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Long create(RewardTaskSaveReqVO req) {
|
||||||
|
RewardTaskConfiguration.validate(req);
|
||||||
|
requireCodeFree(req.getCode().trim(), null);
|
||||||
|
RewardTask task = new RewardTask();
|
||||||
|
task.setCode(req.getCode().trim());
|
||||||
|
RewardTaskConfiguration.apply(task, req);
|
||||||
|
task.setStatus(0);
|
||||||
|
task.setVersion(1);
|
||||||
|
taskMapper.insert(task);
|
||||||
|
return task.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 编辑奖励任务。已产生进度的任务保留原 id,版本递增。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void update(Long id, RewardTaskSaveReqVO req) {
|
||||||
|
RewardTaskConfiguration.validate(req);
|
||||||
|
RewardTask task = getExisting(id);
|
||||||
|
requireCodeFree(req.getCode().trim(), id);
|
||||||
|
task.setCode(req.getCode().trim());
|
||||||
|
RewardTaskConfiguration.apply(task, req);
|
||||||
|
task.setVersion((task.getVersion() == null ? 0 : task.getVersion()) + 1);
|
||||||
|
taskMapper.updateById(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 上线或下线任务。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void updateStatus(Long id, Integer status) {
|
||||||
|
if (status == null || (status != 0 && status != 1)) {
|
||||||
|
throw new ServiceException(ErrorCode.BAD_REQUEST, "状态只能是 0 或 1");
|
||||||
|
}
|
||||||
|
RewardTask task = getExisting(id);
|
||||||
|
task.setStatus(status);
|
||||||
|
taskMapper.updateById(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 客户端奖励总览。 */
|
||||||
|
public RewardOverviewVO overview(Long userId, String locale, Long coinBalance) {
|
||||||
|
String language = RewardViewAssembler.normalizeLocale(locale);
|
||||||
|
List<RewardTask> tasks = activeTasks();
|
||||||
|
Map<String, List<RewardTaskItemVO>> grouped = new LinkedHashMap<>();
|
||||||
|
for (RewardTask task : tasks) {
|
||||||
|
RewardTaskProgress progress = currentProgress(userId, task);
|
||||||
|
grouped.computeIfAbsent(task.getSectionCode(), key -> new ArrayList<>())
|
||||||
|
.add(RewardViewAssembler.toItem(task, progress, language));
|
||||||
|
}
|
||||||
|
RewardOverviewVO overview = new RewardOverviewVO();
|
||||||
|
overview.setServerDate(LocalDate.now(REWARD_ZONE).toString());
|
||||||
|
overview.setTimezone(REWARD_ZONE.getId());
|
||||||
|
overview.setCoinBalance(coinBalance);
|
||||||
|
overview.setSections(grouped.entrySet().stream()
|
||||||
|
.map(entry -> new RewardSectionVO(entry.getKey(),
|
||||||
|
RewardViewAssembler.sectionTitle(tasks, entry.getKey(), language),
|
||||||
|
entry.getValue())).toList());
|
||||||
|
overview.setActivities(activities(language));
|
||||||
|
return overview;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 服务端记录已验证事件并推进任务。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void recordEvent(Long userId, String eventType, String sourceId, long eventValue) {
|
||||||
|
if (userId == null || !StringUtils.hasText(eventType) || !StringUtils.hasText(sourceId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (RewardTask task : activeTasks()) {
|
||||||
|
if (!eventType.equals(task.getType())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String eventKey = eventKey(task, userId, sourceId);
|
||||||
|
if (!insertEvent(userId, eventType, sourceId, eventValue, eventKey)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
addProgress(userId, task, Math.max(eventValue, 0L));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 记录服务端校验后的观看进度,时长按单集最大值增量累计,完播集数按分集去重。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void recordWatch(Long userId, Long episodeId, Long positionMs, boolean finished) {
|
||||||
|
if (userId == null || episodeId == null) return;
|
||||||
|
for (RewardTask task : activeTasks()) {
|
||||||
|
if (TYPE_WATCH_DURATION.equals(task.getType())) {
|
||||||
|
recordWatchDuration(userId, episodeId, positionMs, task);
|
||||||
|
} else if (TYPE_WATCH_EPISODES.equals(task.getType()) && finished) {
|
||||||
|
recordWatchEpisode(userId, episodeId, task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取现有任务实体。 */
|
||||||
|
public RewardTask getExisting(Long id) {
|
||||||
|
RewardTask task = id == null ? null : taskMapper.selectById(id);
|
||||||
|
if (task == null || Integer.valueOf(1).equals(task.getDeleted())) {
|
||||||
|
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "奖励任务不存在");
|
||||||
|
}
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取当前周期进度。 */
|
||||||
|
public RewardTaskProgress currentProgress(Long userId, RewardTask task) {
|
||||||
|
return findProgress(userId, task.getId(), cycleKey(task));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 周期键规则集中管理,保证进度和幂等键一致。 */
|
||||||
|
public String cycleKey(RewardTask task) {
|
||||||
|
LocalDate today = LocalDate.now(REWARD_ZONE);
|
||||||
|
return switch (task.getCycleType()) {
|
||||||
|
case CYCLE_DAILY -> today.toString();
|
||||||
|
case CYCLE_WEEKLY -> today.getYear() + "-W" + today.get(WeekFields.ISO.weekOfWeekBasedYear());
|
||||||
|
default -> CYCLE_ONCE;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<RewardTask> activeTasks() {
|
||||||
|
LocalDateTime now = LocalDateTime.now(REWARD_ZONE);
|
||||||
|
return taskMapper.selectList(Wrappers.<RewardTask>lambdaQuery()
|
||||||
|
.eq(RewardTask::getStatus, 1).eq(RewardTask::getDeleted, 0)
|
||||||
|
.and(w -> w.isNull(RewardTask::getStartAt).or().le(RewardTask::getStartAt, now))
|
||||||
|
.and(w -> w.isNull(RewardTask::getEndAt).or().ge(RewardTask::getEndAt, now))
|
||||||
|
.orderByAsc(RewardTask::getSort).orderByAsc(RewardTask::getId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 返回当前生效活动卡片。 */
|
||||||
|
public List<RewardActivityVO> activities(String locale) {
|
||||||
|
String language = RewardViewAssembler.normalizeLocale(locale);
|
||||||
|
LocalDateTime now = LocalDateTime.now(REWARD_ZONE);
|
||||||
|
return activityMapper.selectList(Wrappers.<RewardActivity>lambdaQuery()
|
||||||
|
.eq(RewardActivity::getStatus, 1).eq(RewardActivity::getDeleted, 0)
|
||||||
|
.and(w -> w.isNull(RewardActivity::getStartAt).or().le(RewardActivity::getStartAt, now))
|
||||||
|
.and(w -> w.isNull(RewardActivity::getEndAt).or().ge(RewardActivity::getEndAt, now))
|
||||||
|
.orderByAsc(RewardActivity::getSort)).stream()
|
||||||
|
.map(row -> RewardViewAssembler.toActivity(row, language)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardTaskProgress findProgress(Long userId, Long taskId, String cycleKey) {
|
||||||
|
if (userId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return progressMapper.selectOne(Wrappers.<RewardTaskProgress>lambdaQuery()
|
||||||
|
.eq(RewardTaskProgress::getUserId, userId).eq(RewardTaskProgress::getTaskId, taskId)
|
||||||
|
.eq(RewardTaskProgress::getCycleKey, cycleKey).last("limit 1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RewardTaskProgress newProgress(Long userId, RewardTask task, String cycleKey) {
|
||||||
|
RewardTaskProgress progress = new RewardTaskProgress();
|
||||||
|
progress.setUserId(userId);
|
||||||
|
progress.setTaskId(task.getId());
|
||||||
|
progress.setCycleKey(cycleKey);
|
||||||
|
progress.setProgressValue(0L);
|
||||||
|
progress.setTargetValue(task.getTargetValue());
|
||||||
|
progress.setStatus(STATUS_PROGRESS);
|
||||||
|
progress.setClaimSeq(0);
|
||||||
|
return progress;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean insertEvent(Long userId, String eventType, String sourceId, long value, String key) {
|
||||||
|
RewardEventLog event = new RewardEventLog();
|
||||||
|
event.setUserId(userId);
|
||||||
|
event.setEventType(eventType);
|
||||||
|
event.setSourceId(sourceId);
|
||||||
|
event.setEventValue(value);
|
||||||
|
event.setIdempotentKey(key);
|
||||||
|
try {
|
||||||
|
eventLogMapper.insert(event);
|
||||||
|
return true;
|
||||||
|
} catch (DuplicateKeyException ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void recordWatchDuration(Long userId, Long episodeId, Long positionMs, RewardTask task) {
|
||||||
|
long seconds = Math.max(positionMs == null ? 0L : positionMs / 1000L, 0L);
|
||||||
|
String key = eventKey(task, userId, episodeId.toString());
|
||||||
|
RewardEventLog event = eventLogMapper.selectOne(Wrappers.<RewardEventLog>lambdaQuery()
|
||||||
|
.eq(RewardEventLog::getIdempotentKey, key).last("limit 1"));
|
||||||
|
long previous = event == null || event.getEventValue() == null ? 0L : event.getEventValue();
|
||||||
|
if (seconds <= previous) return;
|
||||||
|
if (event == null) {
|
||||||
|
event = new RewardEventLog();
|
||||||
|
event.setUserId(userId);
|
||||||
|
event.setEventType(TYPE_WATCH_DURATION);
|
||||||
|
event.setSourceId(episodeId.toString());
|
||||||
|
event.setEventValue(seconds);
|
||||||
|
event.setIdempotentKey(key);
|
||||||
|
eventLogMapper.insert(event);
|
||||||
|
} else {
|
||||||
|
event.setEventValue(seconds);
|
||||||
|
eventLogMapper.updateById(event);
|
||||||
|
}
|
||||||
|
addProgress(userId, task, seconds - previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void recordWatchEpisode(Long userId, Long episodeId, RewardTask task) {
|
||||||
|
String key = eventKey(task, userId, episodeId.toString());
|
||||||
|
if (insertEvent(userId, TYPE_WATCH_EPISODES, episodeId.toString(), 1L, key)) {
|
||||||
|
addProgress(userId, task, 1L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addProgress(Long userId, RewardTask task, long delta) {
|
||||||
|
if (delta <= 0) return;
|
||||||
|
String cycleKey = cycleKey(task);
|
||||||
|
RewardTaskProgress progress = findProgress(userId, task.getId(), cycleKey);
|
||||||
|
if (progress == null) {
|
||||||
|
progress = newProgress(userId, task, cycleKey);
|
||||||
|
progressMapper.insert(progress);
|
||||||
|
}
|
||||||
|
long next = progress.getProgressValue() + delta;
|
||||||
|
progress.setProgressValue(Math.min(next, task.getTargetValue()));
|
||||||
|
progress.setLastEventAt(LocalDateTime.now());
|
||||||
|
if (progress.getProgressValue() >= task.getTargetValue()) {
|
||||||
|
progress.setStatus(STATUS_COMPLETED);
|
||||||
|
progress.setCompletedAt(LocalDateTime.now());
|
||||||
|
}
|
||||||
|
progressMapper.updateById(progress);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String eventKey(RewardTask task, Long userId, String sourceId) {
|
||||||
|
return "reward-event:" + task.getCode() + ":" + userId + ":" + cycleKey(task) + ":" + sourceId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireCodeFree(String code, Long excludeId) {
|
||||||
|
Long count = taskMapper.selectCount(Wrappers.<RewardTask>lambdaQuery().eq(RewardTask::getCode, code)
|
||||||
|
.eq(RewardTask::getDeleted, 0).ne(excludeId != null, RewardTask::getId, excludeId));
|
||||||
|
if (count != null && count > 0) throw new ServiceException(ErrorCode.DATA_EXISTS, "任务编码已存在:" + code);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardActivity;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTask;
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardTaskProgress;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardActivityVO;
|
||||||
|
import com.fruitshorts.commerce.reward.vo.RewardTaskItemVO;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/** 奖励中心多语言展示模型组装器。 */
|
||||||
|
final class RewardViewAssembler {
|
||||||
|
|
||||||
|
private RewardViewAssembler() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static RewardTaskItemVO toItem(RewardTask task, RewardTaskProgress progress, String locale) {
|
||||||
|
RewardTaskItemVO item = new RewardTaskItemVO();
|
||||||
|
item.setId(task.getId());
|
||||||
|
item.setCode(task.getCode());
|
||||||
|
item.setType(task.getType());
|
||||||
|
item.setTitle(text(task.getTitleId(), task.getTitleEn(), task.getTitleZh(), locale));
|
||||||
|
item.setSubtitle(text(task.getSubtitleId(), task.getSubtitleEn(), task.getSubtitleZh(), locale));
|
||||||
|
item.setCtaText(text(task.getCtaId(), task.getCtaEn(), task.getCtaZh(), locale));
|
||||||
|
item.setIconUrl(task.getIconUrl());
|
||||||
|
item.setActionType(task.getActionType());
|
||||||
|
item.setActionUrl(task.getActionUrl());
|
||||||
|
item.setTargetValue(task.getTargetValue());
|
||||||
|
item.setRewardCoin(task.getRewardCoin());
|
||||||
|
item.setProgressValue(progress == null ? 0L : progress.getProgressValue());
|
||||||
|
item.setStatus(progress == null ? RewardTaskService.STATUS_PROGRESS : progress.getStatus());
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
static RewardActivityVO toActivity(RewardActivity row, String locale) {
|
||||||
|
RewardActivityVO vo = new RewardActivityVO();
|
||||||
|
vo.setId(row.getId());
|
||||||
|
vo.setCode(row.getCode());
|
||||||
|
vo.setCoverUrl(row.getCoverUrl());
|
||||||
|
vo.setTitle(text(row.getTitleId(), row.getTitleEn(), row.getTitleZh(), locale));
|
||||||
|
vo.setSummary(text(row.getSummaryId(), row.getSummaryEn(), row.getSummaryZh(), locale));
|
||||||
|
vo.setCtaText(text(row.getCtaId(), row.getCtaEn(), row.getCtaZh(), locale));
|
||||||
|
vo.setActionType(row.getActionType());
|
||||||
|
vo.setActionUrl(row.getActionUrl());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String sectionTitle(List<RewardTask> tasks, String code, String locale) {
|
||||||
|
return tasks.stream().filter(task -> code.equals(task.getSectionCode())).findFirst()
|
||||||
|
.map(task -> text(task.getSectionTitleId(), task.getSectionTitleEn(),
|
||||||
|
task.getSectionTitleZh(), locale))
|
||||||
|
.orElse(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String normalizeLocale(String locale) {
|
||||||
|
if (!StringUtils.hasText(locale)) {
|
||||||
|
return "id";
|
||||||
|
}
|
||||||
|
String normalized = locale.trim().toLowerCase(Locale.ROOT);
|
||||||
|
if (normalized.startsWith("zh")) {
|
||||||
|
return "zh";
|
||||||
|
}
|
||||||
|
return normalized.startsWith("en") ? "en" : "id";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(String id, String en, String zh, String locale) {
|
||||||
|
if ("zh".equals(locale) && StringUtils.hasText(zh)) {
|
||||||
|
return zh;
|
||||||
|
}
|
||||||
|
if ("en".equals(locale) && StringUtils.hasText(en)) {
|
||||||
|
return en;
|
||||||
|
}
|
||||||
|
return StringUtils.hasText(id) ? id : (StringUtils.hasText(en) ? en : zh);
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.service;
|
||||||
|
|
||||||
|
import com.fruitshorts.commerce.dal.entity.CoinLedger;
|
||||||
|
import com.fruitshorts.commerce.dal.entity.Wallet;
|
||||||
|
import com.fruitshorts.commerce.service.WalletService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/** 奖励域对钱包能力的最小适配,避免奖励服务泄露钱包实现细节。 */
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class WalletServiceFacade {
|
||||||
|
|
||||||
|
private final WalletService walletService;
|
||||||
|
|
||||||
|
/** 以 REWARD 类型写入金币流水。 */
|
||||||
|
public CoinLedger change(Long userId, long amount, String idempotentKey,
|
||||||
|
String source, Long operatorId) {
|
||||||
|
return walletService.change(userId, amount, WalletService.BIZ_REWARD,
|
||||||
|
idempotentKey, idempotentKey, "奖励发放:" + source, false, operatorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查询当前钱包余额。 */
|
||||||
|
public Long balance(Long userId) {
|
||||||
|
Wallet wallet = walletService.getOrCreate(userId);
|
||||||
|
return wallet.getCoinBalance();
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import com.fruitshorts.common.pojo.PageParam;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
/** 后台奖励活动分页条件。 */
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public class RewardActivityQueryReqVO extends PageParam {
|
||||||
|
|
||||||
|
private String keyword;
|
||||||
|
private Integer status;
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import com.fruitshorts.commerce.reward.dal.entity.RewardActivity;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 后台奖励活动响应。 */
|
||||||
|
@Data
|
||||||
|
public class RewardActivityRespVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String code;
|
||||||
|
private String coverUrl;
|
||||||
|
private String actionType;
|
||||||
|
private String actionUrl;
|
||||||
|
private String titleId;
|
||||||
|
private String titleEn;
|
||||||
|
private String titleZh;
|
||||||
|
private String summaryId;
|
||||||
|
private String summaryEn;
|
||||||
|
private String summaryZh;
|
||||||
|
private String ctaId;
|
||||||
|
private String ctaEn;
|
||||||
|
private String ctaZh;
|
||||||
|
private Integer sort;
|
||||||
|
private Integer status;
|
||||||
|
private String statusText;
|
||||||
|
private LocalDateTime startAt;
|
||||||
|
private LocalDateTime endAt;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
/** 将活动实体转换为后台展示模型。 */
|
||||||
|
public static RewardActivityRespVO of(RewardActivity activity) {
|
||||||
|
RewardActivityRespVO vo = new RewardActivityRespVO();
|
||||||
|
vo.id = activity.getId();
|
||||||
|
vo.code = activity.getCode();
|
||||||
|
vo.coverUrl = activity.getCoverUrl();
|
||||||
|
vo.actionType = activity.getActionType();
|
||||||
|
vo.actionUrl = activity.getActionUrl();
|
||||||
|
vo.titleId = activity.getTitleId();
|
||||||
|
vo.titleEn = activity.getTitleEn();
|
||||||
|
vo.titleZh = activity.getTitleZh();
|
||||||
|
vo.summaryId = activity.getSummaryId();
|
||||||
|
vo.summaryEn = activity.getSummaryEn();
|
||||||
|
vo.summaryZh = activity.getSummaryZh();
|
||||||
|
vo.ctaId = activity.getCtaId();
|
||||||
|
vo.ctaEn = activity.getCtaEn();
|
||||||
|
vo.ctaZh = activity.getCtaZh();
|
||||||
|
vo.sort = activity.getSort();
|
||||||
|
vo.status = activity.getStatus();
|
||||||
|
vo.statusText = activity.getStatus() != null && activity.getStatus() == 1 ? "已上线" : "已下线";
|
||||||
|
vo.startAt = activity.getStartAt();
|
||||||
|
vo.endAt = activity.getEndAt();
|
||||||
|
vo.createdAt = activity.getCreatedAt();
|
||||||
|
vo.updatedAt = activity.getUpdatedAt();
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 后台奖励活动新增和编辑参数。 */
|
||||||
|
@Data
|
||||||
|
public class RewardActivitySaveReqVO {
|
||||||
|
|
||||||
|
@NotBlank(message = "请填写活动编码")
|
||||||
|
@Size(max = 64, message = "活动编码过长")
|
||||||
|
private String code;
|
||||||
|
@Size(max = 512, message = "封面地址过长")
|
||||||
|
private String coverUrl;
|
||||||
|
private String actionType;
|
||||||
|
@Size(max = 512, message = "跳转地址过长")
|
||||||
|
private String actionUrl;
|
||||||
|
@NotBlank(message = "请填写印尼语标题")
|
||||||
|
private String titleId;
|
||||||
|
private String titleEn;
|
||||||
|
private String titleZh;
|
||||||
|
private String summaryId;
|
||||||
|
private String summaryEn;
|
||||||
|
private String summaryZh;
|
||||||
|
private String ctaId;
|
||||||
|
private String ctaEn;
|
||||||
|
private String ctaZh;
|
||||||
|
private Integer sort;
|
||||||
|
private LocalDateTime startAt;
|
||||||
|
private LocalDateTime endAt;
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 客户端奖励活动卡片。 */
|
||||||
|
@Data
|
||||||
|
public class RewardActivityVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String code;
|
||||||
|
private String coverUrl;
|
||||||
|
private String title;
|
||||||
|
private String summary;
|
||||||
|
private String ctaText;
|
||||||
|
private String actionType;
|
||||||
|
private String actionUrl;
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 客户端签到结果。 */
|
||||||
|
@Data
|
||||||
|
public class RewardCheckinRespVO {
|
||||||
|
|
||||||
|
private Long taskId;
|
||||||
|
private Long grantId;
|
||||||
|
private Integer dayIndex;
|
||||||
|
private Integer streak;
|
||||||
|
private Long rewardCoin;
|
||||||
|
private Long coinBalance;
|
||||||
|
private Boolean alreadyCheckedIn;
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 后台签到单日奖励参数。 */
|
||||||
|
@Data
|
||||||
|
public class RewardCheckinRuleDayReqVO {
|
||||||
|
|
||||||
|
@NotNull(message = "请填写签到天数")
|
||||||
|
@Min(value = 1, message = "签到天数必须大于 0")
|
||||||
|
private Integer dayIndex;
|
||||||
|
@NotNull(message = "请填写签到奖励")
|
||||||
|
@Min(value = 0, message = "签到奖励不能小于 0")
|
||||||
|
private Long rewardCoin;
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
package com.fruitshorts.commerce.reward.vo;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 后台保存签到周期奖励。 */
|
||||||
|
@Data
|
||||||
|
public class RewardCheckinRuleSaveReqVO {
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
@NotEmpty(message = "签到规则不能为空")
|
||||||
|
private List<RewardCheckinRuleDayReqVO> days;
|
||||||
|
}
|
||||||
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user