Compare commits

...
42 Commits
Author SHA1 Message Date
Timi e2e0023d13 v1.0.23
CI / build-deploy (pull_request) Successful in 23s
CI / notify-on-failure (pull_request) Skipped
2026-08-22 17:50:56 +08:00
Timi 8c6eed2379 update store delete 2026-08-22 17:21:30 +08:00
Timi c32ecd1f8c add point account list api 2026-08-22 16:42:09 +08:00
Timi 3c56e21efa add point totalConsumed 2026-08-22 11:45:00 +08:00
Timi 376f0ecd05 fix multi role invite error 2026-08-22 11:20:09 +08:00
Timi a208947a1b v1.0.22
CI / build-deploy (pull_request) Successful in 24s
CI / notify-on-failure (pull_request) Skipped
2026-08-22 01:31:14 +08:00
Timi fc62663f2c v1.0.22
CI / build-deploy (pull_request) Failing after 3s
CI / notify-on-failure (pull_request) Successful in 0s
2026-08-22 01:27:28 +08:00
Timi fcae2eac09 fix gao user invite validate 2026-08-21 23:51:38 +08:00
Timi 2e9225852d add AttachmentVariant 2026-08-21 23:43:40 +08:00
Timi 3a3809b661 fix gao user invite 2026-08-21 21:54:09 +08:00
Timi 1b8936f197 support sms login 2026-08-21 18:13:58 +08:00
Timi aff056712e v1.0.21
CI / build-deploy (pull_request) Successful in 22s
CI / notify-on-failure (pull_request) Skipped
2026-08-21 15:29:15 +08:00
Timi af18b0999d v1.0.20 2026-08-21 15:28:49 +08:00
Timi 4963988ec2 v1.0.20
CI / build-deploy (pull_request) Successful in 30s
CI / notify-on-failure (pull_request) Skipped
2026-08-21 15:25:04 +08:00
Timi 022185079c v1.0.19
CI / build-deploy (pull_request) Successful in 28s
CI / notify-on-failure (pull_request) Skipped
2026-08-21 13:52:05 +08:00
Timi acc3f05f12 support pinyin search 2026-08-21 13:51:26 +08:00
Timi a523df6a07 v1.0.18
CI / build-deploy (pull_request) Successful in 39s
CI / notify-on-failure (pull_request) Skipped
2026-08-21 01:39:14 +08:00
Timi 31c583eeb5 add internal notify 2026-08-21 01:38:51 +08:00
Timi e3ef3e5275 implement notify 2026-08-20 23:14:54 +08:00
Timi 84190b9773 point tier rule allow greater than 0 for min 2026-08-20 16:09:46 +08:00
Timi 7808d22775 support tag for customer create 2026-08-20 14:57:29 +08:00
Timi fba559cd22 fix customer delete 2026-08-20 11:19:24 +08:00
Timi dcc75efa87 v1.0.17
CI / build-deploy (pull_request) Successful in 22s
CI / notify-on-failure (pull_request) Skipped
2026-08-20 01:29:48 +08:00
Timi a9465299a9 add feedback 2026-08-20 00:22:19 +08:00
Timi 42152c7b79 fix event record DAILY_HALF_DAY 2026-08-19 17:56:05 +08:00
Timi 1a896ef457 add point rule sort 2026-08-19 16:12:23 +08:00
Timi 9d8990a028 add permission list and role list for user detail 2026-08-19 10:38:36 +08:00
Timi 17d88fc338 add event value chart 2026-08-18 17:26:56 +08:00
Timi bb40f347a3 support consume point 2026-08-18 16:46:30 +08:00
Timi 3d4e32e5da v1.0.16
CI / build-deploy (pull_request) Successful in 23s
CI / notify-on-failure (pull_request) Skipped
2026-08-16 11:36:02 +08:00
Timi bdc4cbb240 v1.0.15
CI / build-deploy (pull_request) Successful in 27s
CI / notify-on-failure (pull_request) Skipped
2026-08-16 01:49:18 +08:00
Timi 7f6cebd4e2 v1.0.15
CI / build-deploy (pull_request) Failing after 6s
CI / notify-on-failure (pull_request) Successful in 0s
2026-08-16 01:44:45 +08:00
Timi 75fd4bed18 fix event save fail for limit == 1 2026-08-15 15:01:08 +08:00
Timi 8db6f962c9 v1.0.14
CI / build-deploy (pull_request) Successful in 22s
CI / notify-on-failure (pull_request) Skipped
2026-08-15 01:30:51 +08:00
Timi e35cf3aa59 1.0.14
CI / build-deploy (pull_request) Failing after 10s
CI / notify-on-failure (pull_request) Successful in 0s
2026-08-15 01:25:08 +08:00
Timi 457e716b38 add totalNumberValue for rank 2026-08-14 18:58:04 +08:00
Timi ab4a164680 return NumberValueTotal for list 2026-08-14 18:44:53 +08:00
Timi 9dfca25f8c update point tier rule 2026-08-14 18:26:38 +08:00
Timi e369a38e2e add Gao user invite 2026-08-14 11:57:10 +08:00
Timi f1e10df6a7 rename Gao GlobalManager role name 2026-08-14 11:31:25 +08:00
Timi 36e2a37af2 v1.0.13
CI / build-deploy (pull_request) Successful in 21s
CI / notify-on-failure (pull_request) Skipped
2026-08-13 17:52:03 +08:00
Timi 348f7396a1 add point log 2026-08-13 14:04:07 +08:00
151 changed files with 5731 additions and 556 deletions
+5
View File
@@ -46,6 +46,11 @@ jobs:
<username>${{ vars.TIMI_NEXUS_USERNAME }}</username>
<password>${{ vars.TIMI_NEXUS_PASSWORD }}</password>
</server>
<server>
<id>e2ins_nexus</id>
<username>${{ vars.E2INS_NEXUS_USERNAME }}</username>
<password>${{ vars.E2INS_NEXUS_PASSWORD }}</password>
</server>
</servers>
</settings>
EOF
+26 -2
View File
@@ -11,7 +11,7 @@
<groupId>com.imyeyu.timiserverapi</groupId>
<artifactId>TimiServerAPI</artifactId>
<version>1.0.12</version>
<version>1.0.23</version>
<packaging>jar</packaging>
<name>TimiServerAPI</name>
<description>imyeyu.com API</description>
@@ -167,6 +167,16 @@
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>e2ins_nexus</id>
<url>https://nexus.e2ins.com/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
@@ -195,10 +205,15 @@
<artifactId>timi-utils</artifactId>
<version>0.0.13</version>
</dependency>
<dependency>
<groupId>me.majiajie</groupId>
<artifactId>tinypinyin</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>com.imyeyu.font.icon</groupId>
<artifactId>timi-icon-font</artifactId>
<version>0.0.1</version>
<version>0.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -225,6 +240,15 @@
<groupId>org.flywaydb</groupId>
<artifactId>flyway-mysql</artifactId>
</dependency>
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java-sms</artifactId>
<version>3.1.1281</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
@@ -50,6 +50,16 @@ public enum CorePermissionCode implements BuiltinPermissionCode {
USER_UPDATE("USER:UPDATE", "用户修改", false, true),
USER_DELETE("USER:DELETE", "用户删除", false, true),
FEEDBACK_CREATE("FEEDBACK:CREATE", "反馈创建", false, true),
FEEDBACK_READ("FEEDBACK:READ", "反馈读取", false, true),
FEEDBACK_UPDATE("FEEDBACK:UPDATE", "反馈修改", false, true),
FEEDBACK_DELETE("FEEDBACK:DELETE", "反馈删除", false, true),
NOTIFY_CREATE("NOTIFY:CREATE", "通知创建", false, true),
NOTIFY_READ("NOTIFY:READ", "通知读取", false, true),
NOTIFY_DELETE("NOTIFY:DELETE", "通知删除", false, true),
NOTIFY_CANCEL("NOTIFY:CANCEL", "通知取消", false, true),
USER_ROLE_CREATE("USER_ROLE:CREATE", "用户角色创建", true, true),
USER_ROLE_READ("USER_ROLE:READ", "用户角色读取", true, true),
USER_ROLE_DELETE("USER_ROLE:DELETE", "用户角色删除", true, true);
@@ -4,8 +4,6 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.imyeyu.utils.Time;
@@ -2,6 +2,7 @@ package com.imyeyu.api.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.common.entity.Multilingual;
import com.imyeyu.api.modules.gao.bean.GaoUserInviteCache;
import com.imyeyu.spring.bean.RedisConfigParams;
import com.imyeyu.spring.config.AbstractRedisConfig;
import com.imyeyu.spring.util.Redis;
@@ -202,4 +203,10 @@ public class RedisConfig extends AbstractRedisConfig {
public Redis<String, String> getClipboardRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.STRING);
}
/// @return GAO 用户邀请,code: 邀请缓存
@Bean("redisGaoUserInvite")
public Redis<String, GaoUserInviteCache> getGaoUserInviteRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoUserInviteCache.class));
}
}
@@ -32,6 +32,8 @@ public enum SettingModule {
TEMP_FILE(Setting.Module.TempFile.class),
USER(Setting.Module.User.class),
SYSTEM(Setting.Module.System.class),
SYSTEM_STATUS(Setting.Module.SystemStatus.class);
@@ -1,48 +0,0 @@
package com.imyeyu.api.modules.common.bean.attachment;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author 夜雨
* @since 2025-12-11 18:14
*/
public class Metadata {
/**
* 图片
*
* @author 夜雨
* @since 2025-12-11 18:15
*/
@Data
public static class Image {
private int width;
private int height;
}
/**
* 缩略图
*
* @author 夜雨
* @since 2026-01-04 18:10
*/
@Data
@EqualsAndHashCode(callSuper = true)
public static class ThumbImage extends Image {
private String sourceId;
private String sourceMongoId;
private String sourceMimeType;
/** 请求宽度(缓存键之一,null 表示未指定) */
private Integer requestWidth;
/** 请求高度(缓存键之一,null 表示未指定) */
private Integer requestHeight;
}
}
@@ -0,0 +1,17 @@
package com.imyeyu.api.modules.common.bean.attachment;
/// 缩略图缩放模式
///
/// @author 夜雨
/// @since 2026-08-21
public enum ThumbnailFitMode {
/// 保持比例完整放入目标尺寸
FIT,
/// 保持比例裁剪填满目标尺寸
COVER,
/// 强制缩放到目标尺寸,可能导致图片变形
STRETCH
}
@@ -0,0 +1,81 @@
package com.imyeyu.api.modules.common.config;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/// 通知消息队列配置
///
/// @author 夜雨
/// @since 2026-08-20
@Data
@Configuration
@ConfigurationProperties(prefix = "notify.queue")
public class NotifyQueueConfig {
private Mail mail = new Mail();
private Sms sms = new Sms();
private Wechat wechat = new Wechat();
private HTTP http = new HTTP();
/// 邮件队列配置
@Data
@EqualsAndHashCode(callSuper = true)
public static class Mail extends Queue {
private String defaultFrom;
}
/// 短信队列配置
@Data
@EqualsAndHashCode(callSuper = true)
public static class Sms extends Queue {
private String appId;
private String sign;
private String secretId;
private String secretKey;
private Captcha captcha;
/// 短信验证码
@Data
public static class Captcha {
private String templateId;
private int ttlMinute;
private int argIndex;
}
}
/// 微信队列配置
@Data
@EqualsAndHashCode(callSuper = true)
public static class Wechat extends Queue {
}
/// HTTP 队列配置
@Data
@EqualsAndHashCode(callSuper = true)
public static class HTTP extends Queue {
}
/// 通用队列配置
@Data
public static class Queue {
/// true 为启用
private boolean enable;
private String cron = "0/30 * * * * ?";
}
}
@@ -1,7 +1,9 @@
package com.imyeyu.api.modules.common.controller;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import com.imyeyu.api.modules.common.service.TempFileService;
import com.imyeyu.api.modules.common.vo.attach.TempFileResp;
import com.imyeyu.java.TimiJava;
@@ -41,6 +43,7 @@ public class AttachmentController {
private final TempFileService tempFileService;
private final AttachmentService service;
private final AttachmentVariantService variantService;
/**
* 查询附件详情
@@ -184,14 +187,19 @@ public class AttachmentController {
@AOPLog
@IgnoreGlobalReturn
@GetMapping({"/read/{id}", "/download/{id}"})
public void readById(@PathVariable String id, @RequestParam(required = false) Integer thumbWidth, @RequestParam(required = false) Integer thumbHeight) throws UnsupportedEncodingException {
public void readById(
@PathVariable String id,
@RequestParam(required = false) Integer thumbWidth,
@RequestParam(required = false) Integer thumbHeight,
@RequestParam(defaultValue = "FIT") ThumbnailFitMode fitMode
) throws UnsupportedEncodingException {
HttpServletResponse resp = TimiSpring.getResponse();
Attachment attach = service.get(id);
if (attach == null) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
responseAttachment(attach, thumbWidth, thumbHeight);
responseAttachment(attach, thumbWidth, thumbHeight, fitMode);
}
@AOPLog
@@ -207,21 +215,31 @@ public class AttachmentController {
public void read(@RequestParam String id) throws UnsupportedEncodingException {
HttpServletResponse resp = TimiSpring.getResponse();
Attachment attach = service.get(id);
if (attach == null) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (TimiSpring.getRequest().getRequestURI().endsWith("/download")) {
resp.setHeader("Content-Disposition", Network.getFileDownloadHeader(attach.getName()));
}
response(attach);
response(attach, false);
}
private void responseAttachment(Attachment attach, Integer thumbWidth, Integer thumbHeight) throws UnsupportedEncodingException {
HttpServletResponse resp = TimiSpring.getResponse();
if (attach != null && TimiSpring.getRequest().getRequestURI().endsWith("/download") && attach.getName() != null) {
resp.setHeader("Content-Disposition", Network.getFileDownloadHeader(attach.getName()));
}
responseThumb(attach, thumbWidth, thumbHeight);
private void responseAttachment(
Attachment attach,
Integer thumbWidth,
Integer thumbHeight,
ThumbnailFitMode fitMode
) throws UnsupportedEncodingException {
responseThumb(attach, thumbWidth, thumbHeight, fitMode);
}
protected void responseThumb(Attachment attachment, Integer thumbWidth, Integer thumbHeight) {
protected void responseThumb(
Attachment attachment,
Integer thumbWidth,
Integer thumbHeight,
ThumbnailFitMode fitMode
) throws UnsupportedEncodingException {
HttpServletResponse resp = TimiSpring.getResponse();
if (TimiJava.isEmpty(attachment)) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
@@ -229,21 +247,65 @@ public class AttachmentController {
}
if (thumbWidth == null && thumbHeight == null) {
// 原图
setDownloadHeader(attachment);
response(attachment);
return;
}
// 缩略图
Attachment thumb = service.fetchThumb(attachment, thumbWidth, thumbHeight);
response(TimiJava.defaultIfNull(thumb, attachment));
Attachment thumb = variantService.fetchThumb(attachment, thumbWidth, thumbHeight, fitMode);
setDownloadHeader(thumb);
response(thumb);
}
private void setDownloadHeader(Attachment attachment) throws UnsupportedEncodingException {
if (attachment != null && TimiSpring.getRequest().getRequestURI().endsWith("/download") && attachment.getName() != null) {
TimiSpring.getResponse().setHeader("Content-Disposition", Network.getFileDownloadHeader(attachment.getName()));
}
}
/// 设置附件缓存头并处理条件请求
///
/// @param attachment 实际响应附件
/// @return true 表示客户端缓存仍有效,已返回 304
private boolean responseCache(Attachment attachment) {
HttpServletResponse resp = TimiSpring.getResponse();
resp.setHeader("Cache-Control", "private, no-cache");
String md5 = attachment.getMd5();
if (md5 == null || md5.isBlank()) {
return false;
}
String etag = "\"%s\"".formatted(md5);
resp.setHeader("ETag", etag);
String ifNoneMatch = TimiSpring.getHeader("If-None-Match");
if (ifNoneMatch == null) {
return false;
}
for (String value : ifNoneMatch.split(",")) {
String candidate = value.trim();
if ("*".equals(candidate) || etag.equals(candidate) || ("W/" + etag).equals(candidate)) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
}
return false;
}
protected void response(Attachment attachment) {
response(attachment, true);
}
private void response(Attachment attachment, boolean cacheable) {
HttpServletResponse resp = TimiSpring.getResponse();
try {
if (TimiJava.isEmpty(attachment)) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (!cacheable) {
resp.setHeader("Cache-Control", "private, no-store");
} else if (responseCache(attachment)) {
return;
}
resp.setContentType(attachment.getMimeType());
attachment.doResponse();
} catch (Exception e) {
@@ -0,0 +1,100 @@
package com.imyeyu.api.modules.common.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.common.entity.Feedback;
import com.imyeyu.api.modules.common.service.FeedbackService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.CaptchaValid;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.CaptchaData;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/// 通用反馈接口
///
/// @author Codex
/// @since 2026-08-19
@RestController
@RequiredArgsConstructor
@RequestMapping("/feedback")
public class FeedbackController {
private final FeedbackService service;
private final UserLoginService userLoginService;
/// 提交反馈。登录用户和匿名用户均需提交图形验证码,匿名用户按 IP 限流
///
/// @param captchaData 带图形验证码的反馈请求
@AOPLog
@JsonView(ResponseView.Public.class)
@CaptchaValid
@RequestRateLimit(value = 3, inSeconds = 60)
@PostMapping("/create")
public void create(@RequestBody @Valid CaptchaData<Feedback> captchaData) {
Feedback feedback = captchaData.getData();
feedback.setIp(TimiSpring.getRequestIP());
if (userLoginService.isLogged()) {
feedback.setUserId(userLoginService.getRequireLoginUserId());
}
service.create(feedback);
}
/// 查询反馈列表
///
/// @param page 分页参数
/// @return 反馈分页
@JsonView(ResponseView.Admin.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FEEDBACK_READ)
@PostMapping("/list")
public PageResult<Feedback> list(@RequestBody Page<Feedback> page) {
return service.page(page);
}
/// 查询反馈详情
///
/// @param id 反馈 ID
/// @return 反馈详情
@JsonView(ResponseView.Admin.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FEEDBACK_READ)
@PostMapping("/detail")
public Feedback detail(@RequestParam String id) {
return service.get(id);
}
/// 更新反馈
///
/// @param feedback 反馈
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FEEDBACK_UPDATE)
@PostMapping("/update")
public void update(@RequestBody Feedback feedback) {
feedback.setRespondedBy(userLoginService.getRequireLoginUserId());
service.update(feedback);
}
/// 删除反馈
///
/// @param id 反馈 ID
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FEEDBACK_DELETE)
@PostMapping("/delete")
public void delete(@RequestParam String id) {
service.delete(id);
}
}
@@ -0,0 +1,189 @@
package com.imyeyu.api.modules.common.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.common.entity.Notify;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.service.NotifyDetailService;
import com.imyeyu.api.modules.common.service.NotifyService;
import com.imyeyu.api.modules.common.service.SmsService;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.CaptchaValid;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.annotation.RequiredToken;
import com.imyeyu.spring.bean.CaptchaData;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/// 通知接口
///
/// @author 夜雨
/// @since 2026-08-20
@RestController
@RequiredArgsConstructor
@RequestMapping("/notify")
public class NotifyController {
private final SmsService smsService;
private final UserService userService;
private final NotifyService service;
private final UserLoginService userLoginService;
private final NotifyDetailService detailService;
/// 创建通知,同时创建通知详情
///
/// @param notify 通知及通知详情
/// @return 创建后的通知
@RequireCorePermission(CorePermissionCode.NOTIFY_CREATE)
@RequiredToken
@PostMapping("/create")
public Notify create(@RequestBody Notify notify) {
service.create(notify);
return notify;
}
/// 查询通知详情
///
/// @param id 通知 ID
/// @return 通知及通知详情
@JsonView(ResponseView.Public.class)
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@RequestMapping("/detail")
public Notify detail(@RequestParam String id) {
Notify notify = service.get(id);
{
List<NotifyDetail> detailList = detailService.listByNotifyId(id);
Set<String> userIdSet = detailList.stream()
.filter(item -> item.getMsgType() == NotifyDetail.MsgType.INTERNAL)
.flatMap(item -> Stream.of(item.getSendFrom(), item.getSendTo()))
.collect(Collectors.toSet());
Map<String, User> userMap = userService.mapByIdList(userIdSet);
for (NotifyDetail detail : detailList) {
if (TimiJava.isNotEmpty(detail.getSendFrom())) {
detail.setFromUser(userMap.get(detail.getSendFrom()));
}
if (TimiJava.isNotEmpty(detail.getSendTo())) {
detail.setToUser(userMap.get(detail.getSendTo()));
}
}
notify.setDetailList(detailList);
}
return notify;
}
/// 删除通知及其通知详情
///
/// @param id 通知 ID
@RequireCorePermission(CorePermissionCode.NOTIFY_DELETE)
@RequiredToken
@PostMapping("/delete")
public void delete(@RequestParam String id) {
service.delete(id);
}
/// 取消尚未成功发送的通知详情
///
/// @param id 通知 ID
@RequireCorePermission(CorePermissionCode.NOTIFY_CANCEL)
@RequiredToken
@PostMapping("/cancel")
public void cancel(@RequestParam String id) {
service.cancel(id);
}
@AOPLog
@CaptchaValid
@RequestRateLimit(value = 1, inSeconds = 59)
@PostMapping("/sms/captcha/create")
public String smsCaptchaCreate(@RequestBody CaptchaData<Notify> req) {
return smsService.captchaCreate(req.getData());
}
/// 查询当前用户的站内通知
///
/// @param page 分页参数
/// @param unreadOnly true 为只查询未读通知
/// @return 站内通知分页结果
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@PostMapping("/internal/internal")
public PageResult<NotifyDetail> listInternal(
@RequestBody(required = false) Page<NotifyDetail> page,
@RequestParam(defaultValue = "false") boolean unreadOnly
) {
return detailService.pageInternalByUserId(page, userLoginService.getRequireLoginUserId(), unreadOnly);
}
@JsonView(ResponseView.Public.class)
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@PostMapping("/internal/detail")
public NotifyDetail internalDetail(@RequestParam String id) {
NotifyDetail detail = detailService.getInternalByUserId(id, userLoginService.getRequireLoginUserId());
if (TimiJava.isNotEmpty(detail.getSendFrom())) {
detail.setFromUser(userService.get(detail.getSendFrom()));
}
if (TimiJava.isNotEmpty(detail.getSendTo())) {
detail.setToUser(userService.get(detail.getSendTo()));
}
return detail;
}
/// 删除当前用户的一条站内通知
///
/// @param id 通知详情 ID
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@PostMapping("/internal/delete")
public void deleteInternal(@RequestParam String id) {
detailService.deleteInternalByUserId(id, userLoginService.getRequireLoginUserId());
}
/// 查询当前用户未读通知数量
///
/// @return 未读通知数量
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@PostMapping("/internal/unread/count")
public long countUnreadSite() {
return detailService.countUnreadSiteByUserId(userLoginService.getRequireLoginUserId());
}
/// 标记当前用户的一条站内通知已读
///
/// @param id 通知详情 ID
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@PostMapping("/internal/read")
public void markSiteRead(@RequestParam String id) {
detailService.markSiteRead(userLoginService.getRequireLoginUserId(), id);
}
/// 标记当前用户全部站内通知已读
@RequireCorePermission(CorePermissionCode.NOTIFY_READ)
@RequiredToken
@PostMapping("/internal/read/all")
public void markAllSiteRead() {
detailService.markAllSiteRead(userLoginService.getRequireLoginUserId());
}
}
@@ -28,7 +28,10 @@ public class Article extends UUIDEntity implements SettingSupport {
public enum BizType {
/** 博客 */
BLOG
BLOG,
/// 反馈
FEEDBACK
}
/**
@@ -49,6 +52,19 @@ public class Article extends UUIDEntity implements SettingSupport {
TIP_TAP
}
/// 文章状态
public enum Status {
/// 草稿
DART,
/// 正常
NORMAL,
/// 隐藏
HIDDEN
}
/** 业务类型 */
protected BizType bizType;
@@ -58,8 +74,8 @@ public class Article extends UUIDEntity implements SettingSupport {
/** 标题 */
protected String title;
/** 摘要 */
protected String digest;
/** 描述 */
protected String description;
/** 正文类型 */
protected ContentType contentType;
@@ -74,9 +90,15 @@ public class Article extends UUIDEntity implements SettingSupport {
/** 喜欢数量 */
protected Integer likes;
/** 文章状态 */
protected Status status;
@Transient
protected List<Setting> settingList;
@Transient
protected List<Comment> commentList;
@Transient
protected List<Attachment> attachmentList;
}
@@ -30,6 +30,8 @@ public class Attachment extends UUIDEntity {
/// @since 2026-07-17 20:52
public enum BizType {
ARTICLE,
USER,
GAO_CUSTOMER,
@@ -0,0 +1,68 @@
package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import lombok.Data;
/// 附件缩略图变体记录
///
/// @author 夜雨
/// @since 2026-08-21
@Data
public class AttachmentVariant {
/// 变体 ID
@Id
@AutoUUID
private String id;
/// 源附件 ID
private String sourceAttachmentId;
/// 源文件版本,使用源 GridFS ID
private String sourceMongoId;
/// 源文件摘要
private String sourceMd5;
/// 请求宽度,0 表示未指定
private int requestWidth;
/// 请求高度,0 表示未指定
private int requestHeight;
/// 缩放模式
private ThumbnailFitMode fitMode;
/// 输出格式
private String outputFormat;
/// 缩略图算法版本
private String algorithmVersion;
/// 缩略图 GridFS ID
private String mongoId;
/// 缩略图名称
private String name;
/// 缩略图 MIME 类型
private String mimeType;
/// 缩略图元数据
private ObjectNode metadata;
/// 缩略图大小
private long size;
/// 缩略图摘要
private String md5;
/// 创建时间
private long createdAt;
/// 过期时间
private long expireAt;
}
@@ -0,0 +1,61 @@
package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import com.imyeyu.spring.entity.Creatable;
import com.imyeyu.spring.entity.Destroyable;
import com.imyeyu.spring.entity.IDEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
/// 通知基础队列实体
///
/// @author 夜雨
/// @since 2026-08-20
@Data
@NoArgsConstructor
public class BaseQueueEntity implements IDEntity<String>, Creatable, Destroyable {
/** 主键 */
@Id
@AutoUUID
protected String id;
/** 所属通知详情 ID */
protected String notifyDetailId;
/** 内容 */
protected String data;
/** 参数 */
protected JsonNode args;
/** 发送去向 */
protected String sendTo;
/** 发送时间 */
protected Long sendAt;
/** 剩余重试次数 */
protected Integer retry;
/** 超时时间 */
protected Long timeoutAt;
/** 创建时间 */
protected Long createdAt;
/// 从通知详情创建队列实体
///
/// @param detail 通知详情
public BaseQueueEntity(NotifyDetail detail) {
notifyDetailId = detail.getId();
data = detail.getData();
args = detail.getArgs();
sendTo = detail.getSendTo();
sendAt = detail.getSendAt();
retry = detail.getRetry();
timeoutAt = detail.getTimeoutAt();
}
}
@@ -0,0 +1,79 @@
package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import com.imyeyu.spring.util.ResponseView;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/// 通用反馈
///
/// @author Codex
/// @since 2026-08-19
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Feedback extends UUIDEntity {
/// 反馈处理状态
public enum Status {
/// 待处理
PENDING,
/// 已回复
REPLIED,
/// 已关闭
CLOSED
}
/// 所属模块
@JsonView(ResponseView.Public.class)
private ModuleCode module;
/// 提交用户 ID匿名反馈为 null
@JsonView(ResponseView.Admin.class)
private String userId;
/// 反馈内容文章 ID
@JsonView(ResponseView.Public.class)
private String contentId;
/// 联系方式
@JsonView(ResponseView.Public.class)
private String contact;
/// 提交 IP
@JsonView(ResponseView.Admin.class)
private String ip;
/// 处理状态
@JsonView(ResponseView.Public.class)
private Status status;
/// 管理员回复文章 ID
@JsonView(ResponseView.Public.class)
private String responseId;
/// 回复用户 ID
@JsonView(ResponseView.Admin.class)
private String respondedBy;
/// 回复时间
@JsonView(ResponseView.Public.class)
private Long respondedAt;
/// 管理员回复文章
@Transient
@JsonView(ResponseView.Public.class)
private Article content;
/// 管理员回复文章
@Transient
@JsonView(ResponseView.Public.class)
private Article response;
}
@@ -0,0 +1,26 @@
package com.imyeyu.api.modules.common.entity;
import com.imyeyu.spring.annotation.table.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
/// HTTP 回调队列
///
/// @author 夜雨
/// @since 2026-08-20
@Data
@EqualsAndHashCode(callSuper = true)
@Table("http_queue")
public class HTTPQueue extends BaseQueueEntity {
/** HTTP 请求方法 */
protected String method;
/// 从通知详情创建 HTTP 队列
///
/// @param detail 通知详情
public HTTPQueue(NotifyDetail detail) {
super(detail);
method = "POST";
}
}
@@ -0,0 +1,54 @@
package com.imyeyu.api.modules.common.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/// 邮件发送队列
///
/// @author 夜雨
/// @since 2026-08-20
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class MailQueue extends BaseQueueEntity {
/** 邮件标题 */
protected String subject;
/** 邮件附件 */
protected String attachments;
/** 发送来源 */
protected String sendFrom;
/// 从通知详情创建邮件队列
///
/// @param detail 通知详情
public MailQueue(NotifyDetail detail) {
super(detail);
subject = detail.getSubject();
sendFrom = detail.getSendFrom();
}
/// 邮件附件
@Data
public static class Attachment {
/** 附件类型 */
private Type type;
/** 附件值 */
private String value;
/// 附件来源类型
public enum Type {
/** 系统附件 */
E2INS_ATTACH,
/** URL 附件 */
URL
}
}
}
@@ -1,6 +1,8 @@
package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.imyeyu.java.bean.Language;
import com.imyeyu.spring.annotation.table.Column;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -15,6 +17,18 @@ public class Multilingual extends UUIDEntity {
protected String zhCN;
@Column("zh_cn_pinyin_full")
@JsonIgnore
protected String zhCNPinyinFull;
@Column("zh_cn_pinyin_initial")
@JsonIgnore
protected String zhCNPinyinInitial;
@Column("zh_cn_pinyin_mixed")
@JsonIgnore
protected String zhCNPinyinMixed;
protected String zhTW;
protected String enUS;
@@ -1,7 +1,5 @@
package com.imyeyu.api.modules.common.entity;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
@@ -19,11 +17,6 @@ import java.util.List;
@EqualsAndHashCode(callSuper = true)
public class Notify extends UUIDEntity {
/** 主键 */
@Id
@AutoUUID
private String id;
/** 业务类型 */
private String bizType;
@@ -1,7 +1,17 @@
package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.TimiServerAPI;
import com.imyeyu.api.modules.common.service.BaseQueueService;
import com.imyeyu.api.modules.common.service.HTTPQueueService;
import com.imyeyu.api.modules.common.service.MailQueueService;
import com.imyeyu.api.modules.common.service.SmsQueueService;
import com.imyeyu.api.modules.common.service.WechatQueueService;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import com.imyeyu.spring.util.ResponseView;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -25,13 +35,32 @@ public class NotifyDetail extends UUIDEntity {
@AllArgsConstructor
public enum MsgType {
SMS,
/** 站内通知,不进入外部消息队列 */
INTERNAL(null),
MAIL,
SMS(SmsQueueService.class),
HTTP,
MAIL(MailQueueService.class),
WECHAT;
HTTP(HTTPQueueService.class),
WECHAT(WechatQueueService.class);
private final Class<? extends BaseQueueService<?>> queueServiceClass;
/// 获取消息队列服务
///
/// @return 消息队列服务
public BaseQueueService<?> getService() {
return TimiServerAPI.applicationContext.getBean(queueServiceClass);
}
/// 判断是否需要外部消息队列
///
/// @return true 为需要外部消息队列
public boolean isQueue() {
return queueServiceClass != null;
}
}
/**
@@ -54,44 +83,67 @@ public class NotifyDetail extends UUIDEntity {
}
/** 所属通知 ID */
@JsonView(ResponseView.Public.class)
private String notifyId;
/** 消息类型 */
@JsonView(ResponseView.Public.class)
private MsgType msgType;
/** 模板 ID */
@JsonView(ResponseView.Admin.class)
private String templateId;
/** 标题 */
@JsonView(ResponseView.Public.class)
private String subject;
/** 内容 */
@JsonView(ResponseView.Public.class)
private String data;
/** 参数 */
private String args;
@JsonView(ResponseView.Public.class)
private JsonNode args;
/** 发送来源 */
@JsonView(ResponseView.Public.class)
private String sendFrom;
/** 发送去向 */
@JsonView(ResponseView.Public.class)
private String sendTo;
/** 发送时间 */
@JsonView(ResponseView.Public.class)
private Long sendAt;
/** 重试计数 */
@JsonView(ResponseView.Admin.class)
private Integer retry;
/** 超时时间 */
@JsonView(ResponseView.Admin.class)
private Long timeoutAt;
/** 结果描述 */
@JsonView(ResponseView.Admin.class)
private String resultDesc;
/** 状态 */
@JsonView(ResponseView.Public.class)
private Status status;
/** 已读时间,站内通知未读时为空 */
@JsonView(ResponseView.Public.class)
private Long readAt;
@Transient
protected Notify notify;
@Transient
protected User fromUser;
@Transient
protected User toUser;
}
@@ -0,0 +1,26 @@
package com.imyeyu.api.modules.common.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/// 短信发送队列
///
/// @author 夜雨
/// @since 2026-08-20
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class SmsQueue extends BaseQueueEntity {
/** 短信模板 ID */
protected String templateId;
/// 从通知详情创建短信队列
///
/// @param detail 通知详情
public SmsQueue(NotifyDetail detail) {
super(detail);
templateId = detail.getTemplateId();
}
}
@@ -14,6 +14,21 @@ import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
public class Tag extends UUIDEntity {
///
///
/// @author 夜雨
/// @since 2026-08-12 16:49
public enum OwnerType {
GAO_STORE
}
/// 归属类型
protected OwnerType ownerType;
/// 归属 ID
protected String ownerId;
/// 名称多语言 ID
protected String nameLangId;
@@ -0,0 +1,20 @@
package com.imyeyu.api.modules.common.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/// 微信消息发送队列
///
/// @author 夜雨
/// @since 2026-08-20
@Data
@EqualsAndHashCode(callSuper = true)
public class WechatQueue extends BaseQueueEntity {
/// 从通知详情创建微信队列
///
/// @param detail 通知详情
public WechatQueue(NotifyDetail detail) {
super(detail);
}
}
@@ -32,30 +32,10 @@ public interface AttachmentMapper extends BaseMapper<Attachment, String>, RawMap
List<Attachment> selectByBizId(Attachment.BizType bizType, String bizId, List<String> attachTypes, Page<Attachment> page);
List<Attachment> selectByBizIdList(Attachment.BizType bizType, Collection<String> bizIdList, List<String> attachTypes);
List<Attachment> selectAllByBizIdList(Attachment.BizType bizType, Collection<String> bizIdList, List<String> attachTypes);
long countByBizId(Attachment.BizType bizType, String bizId, List<String> attachTypes);
/**
* 按源附件 ID 与请求尺寸查询已缓存缩略图
*
* @param bizType 源附件业务类型
* @param sourceId 源附件 ID
* @param requestWidth 请求宽度,{@code null} 表示未指定
* @param requestHeight 请求高度,{@code null} 表示未指定
* @return 缩略图附件,不存在返回 {@code null}
*/
Attachment selectThumb(Attachment.BizType bizType, String sourceId, Integer requestWidth, Integer requestHeight);
/**
* 查询源附件的所有未销毁缩略图(含已软删除)
*
* @param sourceId 源附件 ID
* @return 缩略图列表
*/
@Select("SELECT * FROM attachment WHERE biz_id = #{sourceId} AND attach_type = 'THUMB' AND is_destroyed = FALSE")
List<Attachment> selectThumbsBySourceId(String sourceId);
@Select("SELECT * FROM attachment WHERE `is_destroyed` = FALSE AND `destroy_at` < " + UNIX_TIME)
List<Attachment> selectNeedDestroy();
}
@@ -0,0 +1,78 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.entity.AttachmentVariant;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/// 附件缩略图变体 Mapper
///
/// @author 夜雨
/// @since 2026-08-21
public interface AttachmentVariantMapper {
/// 查询有效缩略图附件
///
/// @param sourceAttachmentId 源附件 ID
/// @param sourceMongoId 源 GridFS ID
/// @param requestWidth 请求宽度,0 表示未指定
/// @param requestHeight 请求高度,0 表示未指定
/// @param fitMode 缩放模式
/// @param outputFormat 输出格式
/// @param algorithmVersion 算法版本
/// @param now 当前时间
/// @return 缩略图附件
Attachment selectValidAttachment(
@Param("sourceAttachmentId") String sourceAttachmentId,
@Param("sourceMongoId") String sourceMongoId,
@Param("requestWidth") int requestWidth,
@Param("requestHeight") int requestHeight,
@Param("fitMode") String fitMode,
@Param("outputFormat") String outputFormat,
@Param("algorithmVersion") String algorithmVersion,
@Param("now") long now
);
/// 查询指定变体记录,不判断是否过期
///
/// @param sourceAttachmentId 源附件 ID
/// @param sourceMongoId 源 GridFS ID
/// @param requestWidth 请求宽度,0 表示未指定
/// @param requestHeight 请求高度,0 表示未指定
/// @param fitMode 缩放模式
/// @param outputFormat 输出格式
/// @param algorithmVersion 算法版本
/// @return 变体记录
AttachmentVariant selectByKey(
@Param("sourceAttachmentId") String sourceAttachmentId,
@Param("sourceMongoId") String sourceMongoId,
@Param("requestWidth") int requestWidth,
@Param("requestHeight") int requestHeight,
@Param("fitMode") String fitMode,
@Param("outputFormat") String outputFormat,
@Param("algorithmVersion") String algorithmVersion
);
/// 查询源附件的所有变体
///
/// @param sourceAttachmentId 源附件 ID
/// @return 变体列表
List<AttachmentVariant> selectBySourceAttachmentId(@Param("sourceAttachmentId") String sourceAttachmentId);
/// 查询已过期变体
///
/// @param now 当前时间
/// @return 已过期变体列表
List<AttachmentVariant> selectExpired(@Param("now") long now);
/// 新增变体
///
/// @param variant 变体
void insert(AttachmentVariant variant);
/// 删除变体
///
/// @param id 变体 ID
void delete(@Param("id") String id);
}
@@ -0,0 +1,26 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.BaseQueueEntity;
import com.imyeyu.api.modules.common.util.QueueSQLProvider;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import java.util.List;
/// 通知队列基础 Mapper
///
/// @param <T> 队列实体类型
/// @author 夜雨
/// @since 2026-08-20
public interface BaseQueueMapper<T extends BaseQueueEntity> extends BaseMapper<T, String> {
/** 查询已到发送时间的队列 */
@SelectProvider(type = QueueSQLProvider.class, method = "listReadyQueue")
List<T> listReadyQueue();
/** 根据通知详情 ID 物理删除队列 */
@DeleteProvider(type = QueueSQLProvider.class, method = "destroyByNotifyDetailId")
void destroyByNotifyDetailId(@Param("notifyDetailId") String notifyDetailId);
}
@@ -0,0 +1,11 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.Feedback;
import com.imyeyu.spring.mapper.BaseMapper;
/// 通用反馈 Mapper
///
/// @author Codex
/// @since 2026-08-19
public interface FeedbackMapper extends BaseMapper<Feedback, String> {
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.HTTPQueue;
/// HTTP 队列 Mapper
///
/// @author 夜雨
/// @since 2026-08-20
public interface HTTPQueueMapper extends BaseQueueMapper<HTTPQueue> {
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.MailQueue;
/// 邮件队列 Mapper
///
/// @author 夜雨
/// @since 2026-08-20
public interface MailQueueMapper extends BaseQueueMapper<MailQueue> {
}
@@ -2,6 +2,11 @@ package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* 通知详情 Mapper
@@ -10,4 +15,36 @@ import com.imyeyu.spring.mapper.BaseMapper;
* @since 2026-05-13 14:46
*/
public interface NotifyDetailMapper extends BaseMapper<NotifyDetail, String> {
/** 查询用户的站内通知 */
@Select("SELECT * FROM `notify_detail` WHERE `msg_type` = 'INTERNAL' AND `send_to` = #{userId} " + NOT_DELETE + " ORDER BY `created_at` DESC LIMIT #{offset}, #{limit}")
List<NotifyDetail> selectSiteByUserId(@Param("userId") String userId, @Param("offset") long offset, @Param("limit") long limit);
/** 查询用户的未读站内通知 */
@Select("SELECT * FROM `notify_detail` WHERE `msg_type` = 'INTERNAL' AND `send_to` = #{userId} AND `read_at` IS NULL " + NOT_DELETE + " ORDER BY `created_at` DESC LIMIT #{offset}, #{limit}")
List<NotifyDetail> selectUnreadSiteByUserId(@Param("userId") String userId, @Param("offset") long offset, @Param("limit") long limit);
/** 统计用户的站内通知数量 */
@Select("SELECT COUNT(*) FROM `notify_detail` WHERE `msg_type` = 'INTERNAL' AND `send_to` = #{userId} " + NOT_DELETE)
long countSiteByUserId(@Param("userId") String userId);
/** 统计用户的未读站内通知数量 */
@Select("SELECT COUNT(*) FROM `notify_detail` WHERE `msg_type` = 'INTERNAL' AND `send_to` = #{userId} AND `read_at` IS NULL " + NOT_DELETE)
long countUnreadSiteByUserId(@Param("userId") String userId);
/** 查询用户拥有的站内通知 */
@Select("SELECT * FROM `notify_detail` WHERE `id` = #{detailId} AND `msg_type` = 'INTERNAL' AND `send_to` = #{userId} " + NOT_DELETE + " LIMIT 1")
NotifyDetail selectSiteByIdAndUserId(@Param("detailId") String detailId, @Param("userId") String userId);
/** 删除用户的站内通知 */
@Update("UPDATE `notify_detail` SET `deleted_at` = " + UNIX_TIME + ", `updated_at` = " + UNIX_TIME + " WHERE `id` = #{detailId} AND `msg_type` = 'INTERNAL' AND `send_to` = #{userId} " + NOT_DELETE)
int deleteSiteByIdAndUserId(@Param("detailId") String detailId, @Param("userId") String userId);
/** 标记站内通知已读 */
@Update("UPDATE `notify_detail` SET `read_at` = #{readAt}, `updated_at` = " + UNIX_TIME + " WHERE `id` = #{detailId} AND `msg_type` = 'INTERNAL' AND `send_to` = #{userId} AND `read_at` IS NULL " + NOT_DELETE)
int markSiteRead(@Param("detailId") String detailId, @Param("userId") String userId, @Param("readAt") long readAt);
/** 标记用户全部站内通知已读 */
@Update("UPDATE `notify_detail` SET `read_at` = #{readAt}, `updated_at` = " + UNIX_TIME + " WHERE `msg_type` = 'INTERNAL' AND `send_to` = #{userId} AND `read_at` IS NULL " + NOT_DELETE)
int markAllSiteRead(@Param("userId") String userId, @Param("readAt") long readAt);
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.SmsQueue;
/// 短信队列 Mapper
///
/// @author 夜雨
/// @since 2026-08-20
public interface SmsQueueMapper extends BaseQueueMapper<SmsQueue> {
}
@@ -2,6 +2,7 @@ package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.Tag;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.Collection;
import java.util.List;
@@ -13,4 +14,24 @@ import java.util.List;
public interface TagMapper extends BaseMapper<Tag, String> {
List<Tag> selectByIdList(Collection<String> idList);
/// 按归属和名称关键词查询标签总数
///
/// @param ownerType 归属类型
/// @param ownerId 归属 ID
/// @param keyword 名称关键词
/// @return 标签总数
long countByOwnerAndKeyword(@Param("ownerType") Tag.OwnerType ownerType, @Param("ownerId") String ownerId, @Param("keyword") String keyword);
/// 按归属和名称关键词分页查询标签
///
/// @param ownerType 归属类型
/// @param ownerId 归属 ID
/// @param keyword 名称关键词
/// @param offset 分页偏移量
/// @param limit 分页数量
/// @return 标签列表
List<Tag> selectByOwnerAndKeyword(@Param("ownerType") Tag.OwnerType ownerType, @Param("ownerId") String ownerId, @Param("keyword") String keyword, @Param("offset") long offset, @Param("limit") long limit);
Tag selectByOwnerAndZhCN(@Param("ownerType") Tag.OwnerType ownerType, @Param("ownerId") String ownerId, @Param("zhCN") String zhCN);
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.WechatQueue;
/// 微信队列 Mapper
///
/// @author 夜雨
/// @since 2026-08-20
public interface WechatQueueMapper extends BaseQueueMapper<WechatQueue> {
}
@@ -25,18 +25,6 @@ public interface AttachmentService extends BaseService<Attachment, String> {
/// @return 克隆后的附件
Attachment clone(String id);
/**
* 按需获取或创建缩略图附件。
* <p>当附件为图片或视频时,若指定尺寸的缩略图已存在则直接返回缓存,
* 否则生成并持久化后返回。不支持缩略图的附件类型返回 {@code null}。</p>
*
* @param source 源附件(必须已持久化,mimeType 已填充)
* @param requestWidth 请求宽度,{@code null} 表示未指定
* @param requestHeight 请求高度,{@code null} 表示未指定
* @return 缩略图附件,不支持时返回 {@code null}
*/
Attachment fetchThumb(Attachment source, Integer requestWidth, Integer requestHeight);
Attachment getByBizId(Attachment.BizType bizType, String bizId);
Attachment getByAttachType(Attachment.BizType bizType, String bizId, String attachType);
@@ -0,0 +1,28 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode;
import com.imyeyu.api.modules.common.entity.Attachment;
/// 附件缩略图变体服务
///
/// @author 夜雨
/// @since 2026-08-21
public interface AttachmentVariantService {
/// 按需获取或创建缩略图附件
///
/// @param source 源附件
/// @param requestWidth 请求宽度
/// @param requestHeight 请求高度
/// @param fitMode 缩放模式
/// @return 缩略图附件
Attachment fetchThumb(Attachment source, Integer requestWidth, Integer requestHeight, ThumbnailFitMode fitMode);
/// 删除源附件对应的全部缩略图变体
///
/// @param sourceAttachmentId 源附件 ID
void deleteBySourceId(String sourceAttachmentId);
/// 清理已过期的缩略图变体
void clearExpired();
}
@@ -0,0 +1,30 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.BaseQueueEntity;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
/// 通知队列基础服务
///
/// @param <T> 队列实体类型
/// @author 夜雨
/// @since 2026-08-20
public interface BaseQueueService<T extends BaseQueueEntity> {
/// 创建队列
///
/// @param detail 通知详情
void createQueue(NotifyDetail detail);
/// 删除队列
///
/// @param detail 通知详情
void destroyQueue(NotifyDetail detail);
/// 执行已到期队列
void invokeQueue();
/// 发送队列消息
///
/// @param queue 队列
void send(T queue);
}
@@ -0,0 +1,11 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.Feedback;
import com.imyeyu.spring.service.BaseService;
/// 通用反馈服务
///
/// @author Codex
/// @since 2026-08-19
public interface FeedbackService extends BaseService<Feedback, String> {
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.HTTPQueue;
/// HTTP 队列服务
///
/// @author 夜雨
/// @since 2026-08-20
public interface HTTPQueueService extends BaseQueueService<HTTPQueue> {
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.MailQueue;
/// 邮件队列服务
///
/// @author 夜雨
/// @since 2026-08-20
public interface MailQueueService extends BaseQueueService<MailQueue> {
}
@@ -1,8 +1,12 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
import java.util.List;
/**
* 通知详情服务
*
@@ -10,4 +14,53 @@ import com.imyeyu.spring.service.BaseService;
* @since 2026-05-13 14:46
*/
public interface NotifyDetailService extends BaseService<NotifyDetail, String> {
/// 查询通知下的全部详情
///
/// @param notifyId 通知 ID
/// @return 通知详情列表
List<NotifyDetail> listByNotifyId(String notifyId);
/// 重新将通知详情放入消息队列
///
/// @param detailId 通知详情 ID
void requeue(String detailId);
/// 分页查询用户的站内通知
///
/// @param page 分页参数
/// @param userId 用户 ID
/// @param unreadOnly true 为只查询未读通知
/// @return 站内通知分页结果
PageResult<NotifyDetail> pageInternalByUserId(Page<NotifyDetail> page, String userId, boolean unreadOnly);
/// 查询当前用户拥有的站内通知详情
///
/// @param detailId 通知详情 ID
/// @param userId 用户 ID
/// @return 通知详情
NotifyDetail getInternalByUserId(String detailId, String userId);
/// 删除当前用户拥有的站内通知详情
///
/// @param detailId 通知详情 ID
/// @param userId 用户 ID
void deleteInternalByUserId(String detailId, String userId);
/// 查询用户未读站内通知数量
///
/// @param userId 用户 ID
/// @return 未读数量
long countUnreadSiteByUserId(String userId);
/// 标记站内通知已读
///
/// @param userId 用户 ID
/// @param detailId 通知详情 ID
void markSiteRead(String userId, String detailId);
/// 标记用户全部站内通知已读
///
/// @param userId 用户 ID
void markAllSiteRead(String userId);
}
@@ -10,4 +10,9 @@ import com.imyeyu.spring.service.BaseService;
* @since 2026-05-13 14:46
*/
public interface NotifyService extends BaseService<Notify, String> {
/// 取消通知中尚未成功发送的通知详情
///
/// @param notifyId 通知 ID
void cancel(String notifyId);
}
@@ -1,10 +1,10 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.bean.SettingModule;
import com.imyeyu.api.modules.common.bean.attachment.SettingSupport;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.java.TimiJava;
import com.imyeyu.spring.service.BaseService;
import com.imyeyu.utils.Text;
import java.util.List;
@@ -19,7 +19,7 @@ public interface SettingService extends BaseService<Setting, String> {
Setting getByCode(String bizType, String bizId, String code);
default Setting getSystem(Enum<?> bizType) {
return getByCode(Text.bizClassName(bizType.getClass()), TimiJava.ZERO_UUID, bizType.toString());
return getByCode(SettingModule.fromClass(bizType.getClass()).name(), TimiJava.ZERO_UUID, bizType.toString());
}
List<Setting> listByBizId(String bizType, String bizId);
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.SmsQueue;
/// 短信队列服务
///
/// @author 夜雨
/// @since 2026-08-20
public interface SmsQueueService extends BaseQueueService<SmsQueue> {
}
@@ -0,0 +1,30 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.Notify;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
/**
*
*
* @author 夜雨
* @since 2026-05-14 12:12
*/
public interface SmsService {
/**
* 创建短信验证码通知
*
* @param detail 通知
* @return 通知详情 ID
*/
String captchaCreate(Notify detail);
/**
* 校验短信验证码
*
* @param detailId 通知详情 ID
* @param captcha 请求验证码
* @return 通知详情
*/
NotifyDetail captchaVerify(String detailId, String captcha);
}
@@ -2,6 +2,8 @@ package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.Tag;
import com.imyeyu.api.modules.common.entity.TagApply;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
import java.util.Collection;
@@ -15,6 +17,15 @@ public interface TagService extends BaseService<Tag, String> {
List<Tag> listByIdList(Collection<String> idList);
/// 按归属和名称关键词分页查询标签
///
/// @param page 分页参数
/// @param ownerType 归属类型
/// @param ownerId 归属 ID
/// @param keyword 名称关键词
/// @return 标签分页
PageResult<Tag> pageByOwnerAndKeyword(Page<Tag> page, Tag.OwnerType ownerType, String ownerId, String keyword);
/// 按业务查询标签列表
///
/// @param bizType 业务类型
@@ -28,4 +39,10 @@ public interface TagService extends BaseService<Tag, String> {
/// @param bizId 业务 ID
/// @param tagIdList 标签 ID 列表
void apply(TagApply.BizType bizType, String bizId, List<String> tagIdList);
/// 删除指定归属下的全部标签
///
/// @param ownerType 归属类型
/// @param ownerId 归属 ID
void deleteByOwner(Tag.OwnerType ownerType, String ownerId);
}
@@ -0,0 +1,10 @@
package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.WechatQueue;
/// 微信队列服务
///
/// @author 夜雨
/// @since 2026-08-20
public interface WechatQueueService extends BaseQueueService<WechatQueue> {
}
@@ -0,0 +1,126 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.entity.BaseQueueEntity;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.mapper.BaseQueueMapper;
import com.imyeyu.api.modules.common.service.BaseQueueService;
import com.imyeyu.api.modules.common.service.NotifyDetailService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Time;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
/// 通知队列抽象服务
///
/// @param <T> 队列实体类型
/// @param <C> 队列配置类型
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
public abstract class AbstractQueueService<T extends BaseQueueEntity, C extends NotifyQueueConfig.Queue> implements BaseQueueService<T> {
private NotifyDetailService notifyDetailService;
/// 注入通知详情服务
@Autowired
private void setNotifyDetailService(NotifyDetailService notifyDetailService) {
this.notifyDetailService = notifyDetailService;
}
/// 获取队列 Mapper
///
/// @return 队列 Mapper
protected abstract BaseQueueMapper<T> mapper();
/// 获取队列配置
///
/// @return 队列配置
protected abstract C config();
/// 校验发送目标
///
/// @param sendTo 发送目标
protected abstract void validateSendTo(String sendTo);
@Override
public void destroyQueue(NotifyDetail detail) {
TimiException.required(detail, "未找到通知详情");
TimiException.required(detail.getId(), "未找到通知详情 ID");
mapper().destroyByNotifyDetailId(detail.getId());
}
@Override
public void invokeQueue() {
for (T queue : mapper().listReadyQueue()) {
send(queue);
}
}
/// 处理单个队列消息
///
/// @param queue 队列
@Override
public final void send(T queue) {
TimiException.required(queue, "未找到通知队列");
NotifyDetail detail = notifyDetailService.get(queue.getNotifyDetailId());
if (detail == null) {
mapper().destroy(queue.getId());
return;
}
try {
long now = Time.now();
queue.setSendAt(now);
if (queue.getTimeoutAt() < now) {
throw new TimiException(TimiCode.RESULT_TIMEOUT, "通知队列已超时");
}
validateSendTo(queue.getSendTo());
if (!config().isEnable()) {
throw new TimiException(TimiCode.IGNORE, "通知队列未启用");
}
doSend(queue);
detail.setStatus(NotifyDetail.Status.REMINDED);
} catch (TimiException e) {
if (e.getCode() == TimiCode.IGNORE) {
detail.setStatus(NotifyDetail.Status.CANCEL);
detail.setResultDesc(e.getMessage());
} else if (e.getCode() == TimiCode.RESULT_TIMEOUT) {
detail.setStatus(NotifyDetail.Status.TIMEOUT);
detail.setResultDesc(e.getMessage());
} else {
log.error("处理通知队列失败", e);
detail.setStatus(NotifyDetail.Status.FAIL);
detail.setResultDesc(TimiJava.serializeThrowable(e));
}
} catch (Exception e) {
log.error("处理通知队列失败", e);
detail.setStatus(NotifyDetail.Status.FAIL);
detail.setResultDesc(TimiJava.serializeThrowable(e));
} finally {
try {
notifyDetailService.update(detail);
if (detail.getStatus() == NotifyDetail.Status.REMINDED
|| detail.getStatus() == NotifyDetail.Status.CANCEL
|| queue.getRetry() < 0
) {
mapper().destroy(queue.getId());
} else {
queue.setRetry(queue.getRetry() - 1);
mapper().update(queue);
}
} catch (Exception e) {
log.error("通知队列收尾处理失败", e);
mapper().destroy(queue.getId());
}
}
}
/// 执行实际发送动作
///
/// @param queue 队列
/// @throws Exception 发送异常
protected abstract void doSend(T queue) throws Exception;
}
@@ -1,8 +1,15 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.modules.common.entity.Article;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.mapper.ArticleMapper;
import com.imyeyu.api.modules.common.service.ArticleService;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.service.AbstractEntityService;
import lombok.RequiredArgsConstructor;
@@ -20,10 +27,57 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor
public class ArticleServiceImplement extends AbstractEntityService<Article, String> implements ArticleService {
private final LoggerService loggerService;
private final AttachmentService attachmentService;
private final ArticleMapper mapper;
@Override
protected BaseMapper<Article, String> mapper() {
return mapper;
}
@Override
public void create(Article article) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_ARTICLE_CREATE");
try {
super.create(article);
attachmentService.updateByBizId(Attachment.BizType.ARTICLE, article.getId(), article.getAttachmentList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(article.getId());
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("create article error", e);
throw new TimiException(TimiCode.ERROR, "create article error", e);
} finally {
loggerService.create(logger);
}
}
@Override
public void update(Article article) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_ARTICLE_UPDATE");
try {
super.update(article);
attachmentService.updateByBizId(Attachment.BizType.ARTICLE, article.getId(), article.getAttachmentList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(article.getId());
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("update article error", e);
throw new TimiException(TimiCode.ERROR, "update article error", e);
} finally {
loggerService.create(logger);
}
}
}
@@ -3,19 +3,14 @@ package com.imyeyu.api.modules.common.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.bean.attachment.MediaAttach;
import com.imyeyu.api.modules.common.bean.attachment.Metadata;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.mapper.AttachmentMapper;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.util.JavaCV;
import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArg;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.ref.Ref;
import com.imyeyu.network.Network;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
@@ -26,7 +21,6 @@ import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.tika.Tika;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
@@ -36,9 +30,6 @@ import org.springframework.transaction.annotation.Transactional;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
@@ -47,7 +38,6 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
@@ -64,6 +54,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
private final ObjectMapper jackson;
private final GridFSBucket gridFSBucket;
private final GridFsTemplate gridFsTemplate;
private final AttachmentVariantService variantService;
@Override
protected BaseMapper<Attachment, String> mapper() {
@@ -124,6 +115,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
}
// 有新文件时,先查旧记录获取旧 mongoId 和兜底字段
Attachment old = mapper.selectRaw(attachment.getId());
TimiException.required(old, "not found attachment");
// 存储新文件
newMongoId = gridFsTemplate.store(stream, attachment.buildMongoName()).toString();
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(newMongoId)));
@@ -141,6 +133,8 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
// 更新数据库后删除旧 GridFS 文件
super.update(attachment);
// 源文件版本已变化,旧缩略图全部失效
variantService.deleteBySourceId(attachment.getId());
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(old.getMongoId())));
} catch (Exception e) {
// 新文件已上传但后续操作失败,清理新文件防止孤儿数据
@@ -155,36 +149,18 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void delete(String id) {
mapper.selectThumbsBySourceId(id).forEach(thumb -> super.delete(thumb.getId()));
variantService.deleteBySourceId(id);
super.delete(id);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void destroy(String id) {
CallbackArg<Attachment> doDestroy = attach -> {
try {
if (attach.getMongoId() != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(attach.getMongoId())));
variantService.deleteBySourceId(id);
Attachment attachment = mapper.selectRaw(id);
if (attachment != null) {
destroyAttachment(attachment);
}
if (!attach.isDeleted()) {
attach.setDeletedAt(Time.now());
}
attach.setIsDestroyed(true);
attach.setDestroyAt(Time.now());
mapper.update(attach);
if (Ref.toType(MediaAttach.Type.class, attach.getAttachType()) == MediaAttach.Type.THUMB) {
// 缩略图记录物理删除
mapper.destroy(attach.getId());
}
} catch (Exception e) {
log.error("delete mongo file error, id={}", attach.getId(), e);
throw new TimiException(TimiCode.ERROR, "TODO delete mongo file error");
}
};
mapper.selectThumbsBySourceId(id).forEach(doDestroy::handler);
doDestroy.handler(mapper.selectRaw(id));
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@@ -216,74 +192,20 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public Attachment fetchThumb(Attachment source, Integer requestWidth, Integer requestHeight) {
TimiException.requiredTrue(requestWidth != null || requestHeight != null, "required width or height");
String mimeType = source.getMimeType();
boolean isImage = mimeType != null && Set.of("image/png", "image/bmp", "image/jpeg").contains(mimeType);
boolean isVideo = mimeType != null && Set.of("video/mp4", "video/quicktime").contains(mimeType);
if (!isImage && !isVideo) {
return null;
}
Attachment cached = mapper.selectThumb(source.getBizType(), source.getId(), requestWidth, requestHeight);
if (cached != null) {
// 命中缓存直接返回
return cached;
}
private void destroyAttachment(Attachment attachment) {
try {
ByteArrayOutputStream thumbStream = new ByteArrayOutputStream();
CallbackArg<InputStream> applyThumbSize = inputStream -> {
try {
Thumbnails.Builder<? extends InputStream> builder = Thumbnails.of(inputStream);
if (requestWidth != null && requestHeight != null) {
builder.size(requestWidth, requestHeight).keepAspectRatio(false).toOutputStream(thumbStream);
} else if (requestWidth != null) {
builder.width(requestWidth).keepAspectRatio(true).toOutputStream(thumbStream);
} else {
builder.height(requestHeight).keepAspectRatio(true).toOutputStream(thumbStream);
if (attachment.getMongoId() != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(attachment.getMongoId())));
}
} catch (IOException e) {
log.error("applyThumbSize error for fetchThumb", e);
throw new RuntimeException(e);
if (!attachment.isDeleted()) {
attachment.setDeletedAt(Time.now());
}
};
if (isImage) {
applyThumbSize.handler(source.openInputStream());
} else {
String name = source.getName();
File tempFile = IO.file("temp/%s_%s".formatted(UUID.randomUUID(), name));
try {
IO.toFile(tempFile, source.openInputStream());
ByteArrayOutputStream baos = JavaCV.captureThumbnail(IO.getInputStream(tempFile), 2);
applyThumbSize.handler(IO.toInputStream(baos));
} finally {
IO.destroy(tempFile);
}
}
Metadata.ThumbImage thumbMeta = new Metadata.ThumbImage();
thumbMeta.setSourceId(source.getId());
thumbMeta.setSourceMongoId(source.getMongoId());
thumbMeta.setSourceMimeType(mimeType);
thumbMeta.setRequestWidth(requestWidth);
thumbMeta.setRequestHeight(requestHeight);
Attachment thumb = new Attachment();
thumb.setName(Network.simpleURIFileName(source.getName()) + ".png");
thumb.setBizType(source.getBizType());
thumb.setBizId(source.getId());
thumb.setAttachType(MediaAttach.Type.THUMB.toString());
thumb.setMetadata(jackson.valueToTree(thumbMeta));
thumb.setInputStream(new ByteArrayInputStream(thumbStream.toByteArray()));
// 缩略图 7 天后过期,额外 1 天宽限供后台任务销毁
long expireAt = Time.now() + 7 * Time.D;
thumb.setDeletedAt(expireAt);
thumb.setDestroyAt(expireAt + Time.D);
create(thumb);
return thumb;
attachment.setIsDestroyed(true);
attachment.setDestroyAt(Time.now());
mapper.update(attachment);
} catch (Exception e) {
log.error("create thumbnail error", e);
throw new TimiException(TimiCode.ERROR, "exception.attachment.create.error");
log.error("delete mongo file error, id={}", attachment.getId(), e);
throw new TimiException(TimiCode.ERROR, "TODO delete mongo file error", e);
}
}
@@ -319,12 +241,12 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Override
public List<Attachment> listByBizId(Attachment.BizType bizType, String bizId, String... attachTypes) {
return mapper.selectByBizId(bizType, bizId, List.of(attachTypes), null);
return mapper.selectAllByBizIdList(bizType, List.of(bizId), List.of(attachTypes));
}
@Override
public Map<String, List<Attachment>> mapByBizIdList(Attachment.BizType bizType, Collection<String> bizIdList, String... attachTypes) {
return mapper.selectByBizIdList(bizType, bizIdList, List.of(attachTypes)).stream().collect(Collectors.groupingBy(Attachment::getBizId));
return mapper.selectAllByBizIdList(bizType, bizIdList, List.of(attachTypes)).stream().collect(Collectors.groupingBy(Attachment::getBizId));
}
@Override
@@ -390,6 +312,8 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
// 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录
Attachment current = mapper.selectRaw(item.getId());
Attachment tempFile = mapper.selectRaw(tempFileId);
// 源文件版本已变化,旧缩略图全部失效
variantService.deleteBySourceId(current.getId());
// 删除旧 GridFS 文件
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(current.getMongoId())));
// 将存储信息从临时记录迁移到永久记录
@@ -0,0 +1,339 @@
package com.imyeyu.api.modules.common.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.bean.attachment.MediaAttach;
import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.entity.AttachmentVariant;
import com.imyeyu.api.modules.common.mapper.AttachmentVariantMapper;
import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import com.imyeyu.api.util.JavaCV;
import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.network.Network;
import com.imyeyu.spring.util.Redis;
import com.imyeyu.utils.Time;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Set;
import java.util.UUID;
/// 附件缩略图变体服务实现
///
/// 负责缩略图生成、变体缓存、并发控制和变体文件清理,源附件生命周期由 `AttachmentService` 负责
///
/// @author 夜雨
/// @since 2026-08-21
@Slf4j
@Service
@RequiredArgsConstructor
public class AttachmentVariantServiceImplement implements AttachmentVariantService {
private static final int THUMB_MAX_WIDTH = 4096;
private static final int THUMB_MAX_HEIGHT = 4096;
private static final long THUMB_MAX_PIXELS = 16_000_000L;
private static final long THUMB_CACHE_TTL = Time.D * 7;
private static final long THUMB_LOCK_TTL = Time.M * 10;
private static final double THUMB_TARGET_SECONDS = 2;
private static final String THUMB_OUTPUT_FORMAT = "png";
private static final String THUMB_ALGORITHM_VERSION = "v3";
private static final String THUMB_LOCK_KEY_PREFIX = "ATTACHMENT:THUMB:LOCK:";
private final AttachmentVariantMapper variantMapper;
private final ObjectMapper jackson;
private final GridFSBucket gridFSBucket;
private final GridFsTemplate gridFsTemplate;
@Qualifier("redisLocker")
private final Redis<String, Integer> redisLocker;
@Override
public Attachment fetchThumb(Attachment source, Integer requestWidth, Integer requestHeight, ThumbnailFitMode fitMode) {
TimiException.required(source, "not found source attachment");
TimiException.required(source.getId(), "not found source attachment.id");
TimiException.required(source.getMongoId(), "not found source attachment.mongoId");
TimiException.requiredTrue(requestWidth != null || requestHeight != null, "required width or height");
if (requestWidth != null && !(0 < requestWidth && requestWidth < THUMB_MAX_WIDTH + 1)) {
throw new TimiException(TimiCode.ARG_BAD, "attachment.thumbnail.width.invalid");
}
if (requestHeight != null && !(0 < requestHeight && requestHeight < THUMB_MAX_HEIGHT + 1)) {
throw new TimiException(TimiCode.ARG_BAD, "attachment.thumbnail.height.invalid");
}
if (requestWidth != null && requestHeight != null) {
long pixels = (long) requestWidth * requestHeight;
if (THUMB_MAX_PIXELS < pixels) {
throw new TimiException(TimiCode.ARG_BAD, "attachment.thumbnail.area.invalid");
}
}
fitMode = TimiJava.defaultIfNull(fitMode, ThumbnailFitMode.FIT);
String mimeType = source.getMimeType();
boolean isImage = mimeType != null && Set.of("image/png", "image/bmp", "image/jpeg").contains(mimeType);
boolean isVideo = mimeType != null && Set.of("video/mp4", "video/quicktime").contains(mimeType);
if (!isImage && !isVideo) {
throw new TimiException(TimiCode.ARG_BAD, "attachment.thumbnail.not.support");
}
int width = TimiJava.defaultIfNull(requestWidth, 0);
int height = TimiJava.defaultIfNull(requestHeight, 0);
long now = Time.now();
Attachment cached = variantMapper.selectValidAttachment(
source.getId(),
source.getMongoId(),
width,
height,
fitMode.toString(),
THUMB_OUTPUT_FORMAT,
THUMB_ALGORITHM_VERSION,
now
);
if (cached != null) {
return cached;
}
String lockKey = buildThumbLockKey(source, width, height, fitMode);
if (!redisLocker.lock(lockKey, 1, THUMB_LOCK_TTL)) {
throw new TimiException(TimiCode.ERROR_SERVICE_BUSY, "attachment.thumbnail.generating");
}
try {
cached = variantMapper.selectValidAttachment(
source.getId(),
source.getMongoId(),
width,
height,
fitMode.toString(),
THUMB_OUTPUT_FORMAT,
THUMB_ALGORITHM_VERSION,
Time.now()
);
if (cached != null) {
return cached;
}
AttachmentVariant oldVariant = variantMapper.selectByKey(
source.getId(),
source.getMongoId(),
width,
height,
fitMode.toString(),
THUMB_OUTPUT_FORMAT,
THUMB_ALGORITHM_VERSION
);
if (oldVariant != null) {
deleteVariant(oldVariant);
}
File thumbFile = null;
AttachmentVariant variant = null;
boolean variantInserted = false;
try {
thumbFile = createThumbFile(source, requestWidth, requestHeight, fitMode, isImage);
variant = new AttachmentVariant();
variant.setId(UUID.randomUUID().toString());
variant.setName(Network.simpleURIFileName(source.getName()) + "." + THUMB_OUTPUT_FORMAT);
variant.setMimeType("image/" + THUMB_OUTPUT_FORMAT);
long expireAt = Time.now() + THUMB_CACHE_TTL;
variant.setSourceAttachmentId(source.getId());
variant.setSourceMongoId(source.getMongoId());
variant.setSourceMd5(source.getMd5());
variant.setRequestWidth(width);
variant.setRequestHeight(height);
variant.setFitMode(fitMode);
variant.setOutputFormat(THUMB_OUTPUT_FORMAT);
variant.setAlgorithmVersion(THUMB_ALGORITHM_VERSION);
variant.setCreatedAt(Time.now());
variant.setExpireAt(expireAt);
BufferedImage image = ImageIO.read(thumbFile);
if (image != null) {
ObjectNode metadata = jackson.createObjectNode();
metadata.put("width", image.getWidth());
metadata.put("height", image.getHeight());
variant.setMetadata(metadata);
}
try (InputStream inputStream = Files.newInputStream(thumbFile.toPath())) {
String mongoId = gridFsTemplate.store(inputStream, variant.getName()).toString();
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(mongoId)));
variant.setMongoId(mongoId);
variant.setSize(gridFSFile.getLength());
try (InputStream md5InputStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId())) {
variant.setMd5(IO.md5(md5InputStream));
}
}
try {
variantMapper.insert(variant);
variantInserted = true;
} catch (DuplicateKeyException e) {
destroyVariantFile(variant);
Attachment concurrent = variantMapper.selectValidAttachment(
source.getId(),
source.getMongoId(),
width,
height,
fitMode.toString(),
THUMB_OUTPUT_FORMAT,
THUMB_ALGORITHM_VERSION,
Time.now()
);
if (concurrent != null) {
return concurrent;
}
throw e;
}
return toThumbAttachment(source, variant);
} catch (Exception e) {
if (variant != null) {
destroyVariantFile(variant);
if (variantInserted) {
variantMapper.delete(variant.getId());
}
}
throw e;
} finally {
IO.destroy(thumbFile);
}
} catch (TimiException e) {
throw e;
} catch (Exception e) {
log.error("create thumbnail error", e);
throw new TimiException(TimiCode.ERROR, "exception.attachment.create.error", e);
} finally {
redisLocker.releaseLock(lockKey);
}
}
private String buildThumbLockKey(Attachment source, int width, int height, ThumbnailFitMode fitMode) {
return "%s%s:%s:%s:%s:%s".formatted(
THUMB_LOCK_KEY_PREFIX,
source.getId(),
source.getMongoId(),
width,
height,
fitMode
);
}
private File createThumbFile(
Attachment source,
Integer requestWidth,
Integer requestHeight,
ThumbnailFitMode fitMode,
boolean isImage
) throws Exception {
File thumbFile = Files.createTempFile("timi-thumb-", ".png").toFile();
try {
if (isImage) {
try (InputStream inputStream = source.openInputStream()) {
resize(inputStream, thumbFile, requestWidth, requestHeight, fitMode);
}
return thumbFile;
}
try (InputStream inputStream = source.openInputStream()) {
ByteArrayOutputStream frame = JavaCV.captureThumbnail(inputStream, THUMB_TARGET_SECONDS);
if (!(0 < frame.size())) {
throw new TimiException(TimiCode.ERROR_NOT_SUPPORT, "attachment.thumbnail.video.frame.empty");
}
try (InputStream frameInputStream = new ByteArrayInputStream(frame.toByteArray())) {
resize(frameInputStream, thumbFile, requestWidth, requestHeight, fitMode);
}
return thumbFile;
}
} catch (Exception e) {
IO.destroy(thumbFile);
throw e;
}
}
private void resize(
InputStream inputStream,
File outputFile,
Integer requestWidth,
Integer requestHeight,
ThumbnailFitMode fitMode
) throws IOException {
Thumbnails.Builder<? extends InputStream> builder = Thumbnails.of(inputStream)
.useExifOrientation(true)
.outputFormat(THUMB_OUTPUT_FORMAT);
if (requestWidth != null && requestHeight != null) {
switch (fitMode) {
case FIT -> builder.size(requestWidth, requestHeight).keepAspectRatio(true);
case COVER -> builder.size(requestWidth, requestHeight).keepAspectRatio(true).crop(Positions.CENTER);
case STRETCH -> builder.size(requestWidth, requestHeight).keepAspectRatio(false);
}
} else if (requestWidth != null) {
builder.width(requestWidth).keepAspectRatio(true);
} else {
builder.height(requestHeight).keepAspectRatio(true);
}
builder.toFile(outputFile);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void deleteBySourceId(String sourceAttachmentId) {
for (AttachmentVariant variant : variantMapper.selectBySourceAttachmentId(sourceAttachmentId)) {
deleteVariant(variant);
}
}
private void deleteVariant(AttachmentVariant variant) {
destroyVariantFile(variant);
variantMapper.delete(variant.getId());
}
private void destroyVariantFile(AttachmentVariant variant) {
if (variant.getMongoId() != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(variant.getMongoId())));
}
}
private Attachment toThumbAttachment(Attachment source, AttachmentVariant variant) {
Attachment thumb = new Attachment();
thumb.setId(variant.getId());
thumb.setBizType(source.getBizType());
thumb.setBizId(source.getId());
thumb.setAttachType(MediaAttach.Type.THUMB.toString());
thumb.setMongoId(variant.getMongoId());
thumb.setName(variant.getName());
thumb.setMimeType(variant.getMimeType());
thumb.setMetadata(variant.getMetadata());
thumb.setSize(variant.getSize());
thumb.setMd5(variant.getMd5());
thumb.setIsDestroyed(false);
thumb.setDestroyAt(variant.getExpireAt());
return thumb;
}
@Override
public void clearExpired() {
for (AttachmentVariant variant : variantMapper.selectExpired(Time.now())) {
try {
deleteVariant(variant);
} catch (Exception e) {
log.error("clear expired thumbnail variant error, id={}", variant.getId(), e);
}
}
}
}
@@ -0,0 +1,141 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.Feedback;
import com.imyeyu.api.modules.common.mapper.FeedbackMapper;
import com.imyeyu.api.modules.common.service.ArticleService;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.service.FeedbackService;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.service.AbstractEntityService;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/// 通用反馈服务实现
///
/// @author Codex
/// @since 2026-08-19
@Service
@RequiredArgsConstructor
@Slf4j
public class FeedbackServiceImplement extends AbstractEntityService<Feedback, String> implements FeedbackService {
private static final long ANONYMOUS_ATTACHMENT_MAX_SIZE = 500L * 1024;
private final LoggerService loggerService;
private final ArticleService articleService;
private final UserLoginService userLoginService;
private final AttachmentService attachmentService;
private final FeedbackMapper mapper;
@Override
protected BaseMapper<Feedback, String> mapper() {
return mapper;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(Feedback feedback) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_FEEDBACK_CREATE");
try {
TimiException.required(feedback, "未找到反馈");
articleService.create(feedback.getContent());
feedback.setContentId(feedback.getContent().getId());
feedback.setStatus(TimiJava.defaultIfNull(feedback.getStatus(), Feedback.Status.PENDING));
super.create(feedback);
logger.setLevel(Logger.Level.INFO);
logger.setResult(feedback.getId());
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("create feedback error", e);
throw new TimiException(TimiCode.ERROR, "create feedback error", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(Feedback feedback) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_FEEDBACK_UPDATE");
try {
TimiException.required(feedback, "未找到反馈");
TimiException.required(feedback.getId(), "未找到反馈 ID");
Feedback dbFeedback = get(feedback.getId());
TimiException.required(dbFeedback, "未找到反馈");
feedback.getContent().setId(dbFeedback.getContentId());
articleService.update(feedback.getContent());
dbFeedback.setModule(TimiJava.defaultIfNull(feedback.getModule(), dbFeedback.getModule()));
if (TimiJava.isNotEmpty(feedback.getResponse())) {
if (TimiJava.isEmpty(feedback.getResponseId())) {
articleService.create(feedback.getResponse());
dbFeedback.setResponseId(feedback.getResponse().getId());
dbFeedback.setRespondedAt(Time.now());
} else {
feedback.getResponse().setId(dbFeedback.getResponseId());
articleService.update(feedback.getResponse());
}
dbFeedback.setStatus(Feedback.Status.REPLIED);
dbFeedback.setRespondedBy(userLoginService.getRequireLoginUserId());
}
super.update(dbFeedback);
logger.setLevel(Logger.Level.INFO);
logger.setResult(feedback.getId());
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("修改反馈失败", e);
throw new TimiException(TimiCode.ERROR, "修改反馈失败", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void delete(String id) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_FEEDBACK_DELETE");
try {
Feedback feedback = get(id);
articleService.delete(feedback.getContentId());
if (TimiJava.isNotEmpty(feedback.getResponseId())) {
articleService.delete(feedback.getResponseId());
}
super.delete(id);
logger.setLevel(Logger.Level.INFO);
logger.setResult(id);
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("delete feedback error", e);
throw new TimiException(TimiCode.ERROR, "delete feedback error", e);
} finally {
loggerService.create(logger);
}
}
}
@@ -0,0 +1,59 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.entity.HTTPQueue;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.mapper.BaseQueueMapper;
import com.imyeyu.api.modules.common.mapper.HTTPQueueMapper;
import com.imyeyu.api.modules.common.service.HTTPQueueService;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.net.URI;
/// HTTP 队列服务实现
///
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
@Service
@RequiredArgsConstructor
public class HTTPQueueServiceImplement extends AbstractQueueService<HTTPQueue, NotifyQueueConfig.HTTP> implements HTTPQueueService {
private final NotifyQueueConfig config;
private final HTTPQueueMapper mapper;
@Override
protected NotifyQueueConfig.HTTP config() {
return config.getHttp();
}
@Override
protected BaseQueueMapper<HTTPQueue> mapper() {
return mapper;
}
@Override
protected void validateSendTo(String sendTo) {
try {
URI uri = URI.create(sendTo);
TimiException.requiredTrue(uri.isAbsolute(), "发送目标不是有效 URI");
} catch (IllegalArgumentException e) {
throw new TimiException(TimiCode.ARG_BAD, "发送目标不是有效 URI", e);
}
}
@Override
public void createQueue(NotifyDetail detail) {
mapper.insert(new HTTPQueue(detail));
}
@Override
protected void doSend(HTTPQueue queue) {
throw new TimiException(TimiCode.ERROR_NOT_SUPPORT, "HTTP 推送暂未实现");
}
}
@@ -0,0 +1,67 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.entity.MailQueue;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.mapper.BaseQueueMapper;
import com.imyeyu.api.modules.common.mapper.MailQueueMapper;
import com.imyeyu.api.modules.common.service.MailQueueService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Regex;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
/// 邮件队列服务实现
///
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
@Service
@RequiredArgsConstructor
public class MailQueueServiceImplement extends AbstractQueueService<MailQueue, NotifyQueueConfig.Mail> implements MailQueueService {
private final NotifyQueueConfig config;
private final JavaMailSender mailSender;
private final MailQueueMapper mapper;
@Override
protected NotifyQueueConfig.Mail config() {
return config.getMail();
}
@Override
protected BaseQueueMapper<MailQueue> mapper() {
return mapper;
}
@Override
protected void validateSendTo(String sendTo) {
TimiException.requiredTrue(Regex.isMatch(Regex.EMAIL, sendTo), "发送目标不是有效邮箱");
}
@Override
public void createQueue(NotifyDetail detail) {
MailQueue queue = new MailQueue(detail);
queue.setSendFrom(TimiJava.defaultIfEmpty(queue.getSendFrom(), config.getMail().getDefaultFrom()));
mapper.insert(queue);
}
@Override
protected void doSend(MailQueue queue) {
TimiException.required(queue.getSendFrom(), "邮件发送来源不能为空");
TimiException.required(queue.getSubject(), "邮件标题不能为空");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(queue.getSendFrom());
message.setTo(queue.getSendTo());
message.setSubject(queue.getSubject());
message.setText(queue.getData());
mailSender.send(message);
log.info("邮件发送成功,目标:{}", queue.getSendTo());
}
}
@@ -3,6 +3,7 @@ package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.modules.common.entity.Multilingual;
import com.imyeyu.api.modules.common.mapper.MultilingualMapper;
import com.imyeyu.api.modules.common.service.MultilingualService;
import com.imyeyu.api.util.PinyinUtil;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.service.AbstractEntityService;
import com.imyeyu.spring.util.Redis;
@@ -34,6 +35,18 @@ public class MultilingualServiceImplement extends AbstractEntityService<Multilin
return mapper;
}
@Override
public void create(Multilingual multilingual) {
fillPinyin(multilingual);
super.create(multilingual);
}
@Override
public void update(Multilingual multilingual) {
fillPinyin(multilingual);
super.update(multilingual);
}
@Override
public Multilingual get(String id) {
Multilingual result = redisLanguage.get(getKey(id));
@@ -81,4 +94,14 @@ public class MultilingualServiceImplement extends AbstractEntityService<Multilin
private String getKey(String id) {
return "%s%s".formatted(KEY_PREFIX, id);
}
private void fillPinyin(Multilingual multilingual) {
if (multilingual == null) {
return;
}
String zhCN = multilingual.getZhCN();
multilingual.setZhCNPinyinFull(PinyinUtil.full(zhCN));
multilingual.setZhCNPinyinInitial(PinyinUtil.initial(zhCN));
multilingual.setZhCNPinyinMixed(PinyinUtil.mixed(zhCN));
}
}
@@ -1,12 +1,24 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.entity.Notify;
import com.imyeyu.api.modules.common.mapper.NotifyDetailMapper;
import com.imyeyu.api.modules.common.mapper.NotifyMapper;
import com.imyeyu.api.modules.common.service.NotifyDetailService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.AbstractEntityService;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 通知详情服务实现
@@ -18,10 +30,174 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor
public class NotifyDetailServiceImplement extends AbstractEntityService<NotifyDetail, String> implements NotifyDetailService {
private final NotifyMapper notifyMapper;
private final NotifyDetailMapper mapper;
@Override
protected BaseMapper<NotifyDetail, String> mapper() {
return mapper;
}
/// 创建通知详情,同时初始化投递状态和时间参数
///
/// @param detail 通知详情
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(NotifyDetail detail) {
TimiException.required(detail, "未找到通知详情");
TimiException.required(detail.getNotifyId(), "未找到通知 ID");
TimiException.required(detail.getMsgType(), "未找到消息类型");
Notify notify = notifyMapper.select(detail.getNotifyId());
TimiException.required(notify, "未找到通知");
if (detail.getMsgType() == NotifyDetail.MsgType.INTERNAL) {
TimiException.required(detail.getSendTo(), "未找到站内通知接收用户 ID");
}
detail.setRetry(TimiJava.defaultIfNull(detail.getRetry(), 1));
detail.setSendAt(TimiJava.defaultIfNull(detail.getSendAt(), Time.now()));
detail.setTimeoutAt(TimiJava.defaultIfNull(detail.getTimeoutAt(), detail.getSendAt() + Time.D));
detail.setStatus(detail.getMsgType() == NotifyDetail.MsgType.INTERNAL
? NotifyDetail.Status.REMINDED
: NotifyDetail.Status.WAITING);
detail.setReadAt(null);
super.create(detail);
if (detail.getMsgType().isQueue()) {
// 加入外部消息队列
detail.getMsgType().getService().createQueue(detail);
}
}
/// 查询通知下的全部详情
///
/// @param notifyId 通知 ID
/// @return 通知详情列表
@Override
public List<NotifyDetail> listByNotifyId(String notifyId) {
NotifyDetail example = new NotifyDetail();
example.setNotifyId(notifyId);
return mapper.selectAllByExample(example);
}
/// 删除通知详情
///
/// @param detailId 通知详情 ID
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void delete(String detailId) {
TimiException.required(detailId, "未找到通知详情 ID");
NotifyDetail detail = get(detailId);
TimiException.required(detail, "未找到通知详情");
if (detail.getMsgType().isQueue()) {
detail.getMsgType().getService().destroyQueue(detail);
}
super.delete(detailId);
}
/// 重新将通知详情放入消息队列
///
/// @param detailId 通知详情 ID
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void requeue(String detailId) {
NotifyDetail detail = get(detailId);
TimiException.required(detail, "未找到通知详情");
TimiException.required(detail.getMsgType(), "未找到消息类型");
TimiException.requiredTrue(detail.getMsgType().isQueue(), "站内通知不支持重新入队");
if (detail.getStatus() == NotifyDetail.Status.WAITING) {
throw new TimiException(TimiCode.RESULT_BAD, "通知详情已经在等待队列中");
}
detail.getMsgType().getService().destroyQueue(detail);
detail.setStatus(NotifyDetail.Status.WAITING);
detail.setResultDesc(null);
detail.setRetry(1);
detail.setSendAt(Time.now());
detail.setTimeoutAt(detail.getSendAt() + Time.D);
update(detail);
// 加入消息队列
detail.getMsgType().getService().createQueue(detail);
}
/// 分页查询用户的站内通知
///
/// @param page 分页参数
/// @param userId 用户 ID
/// @param unreadOnly true 为只查询未读通知
/// @return 站内通知分页结果
@Override
public PageResult<NotifyDetail> pageInternalByUserId(Page<NotifyDetail> page, String userId, boolean unreadOnly) {
TimiException.required(userId, "未找到用户 ID");
Page<NotifyDetail> validPage = TimiJava.defaultIfNull(page, new Page<>());
PageResult<NotifyDetail> result = new PageResult<>();
result.setTotal(unreadOnly
? mapper.countUnreadSiteByUserId(userId)
: mapper.countSiteByUserId(userId));
result.setList(unreadOnly
? mapper.selectUnreadSiteByUserId(userId, validPage.getOffset(), validPage.getLimit())
: mapper.selectSiteByUserId(userId, validPage.getOffset(), validPage.getLimit()));
return result;
}
/// 查询当前用户拥有的站内通知详情
///
/// @param detailId 通知详情 ID
/// @param userId 用户 ID
/// @return 通知详情
@Override
public NotifyDetail getInternalByUserId(String detailId, String userId) {
TimiException.required(detailId, "未找到通知详情 ID");
TimiException.required(userId, "未找到用户 ID");
NotifyDetail detail = mapper.selectSiteByIdAndUserId(detailId, userId);
TimiException.required(detail, "未找到站内通知");
return detail;
}
/// 删除当前用户拥有的站内通知详情
///
/// @param detailId 通知详情 ID
/// @param userId 用户 ID
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void deleteInternalByUserId(String detailId, String userId) {
TimiException.required(detailId, "未找到通知详情 ID");
TimiException.required(userId, "未找到用户 ID");
int affected = mapper.deleteSiteByIdAndUserId(detailId, userId);
TimiException.requiredTrue(0 < affected, "未找到站内通知");
}
/// 查询用户未读站内通知数量
///
/// @param userId 用户 ID
/// @return 未读数量
@Override
public long countUnreadSiteByUserId(String userId) {
TimiException.required(userId, "未找到用户 ID");
return mapper.countUnreadSiteByUserId(userId);
}
/// 标记站内通知已读
///
/// @param userId 用户 ID
/// @param detailId 通知详情 ID
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void markSiteRead(String userId, String detailId) {
TimiException.required(userId, "未找到用户 ID");
TimiException.required(detailId, "未找到通知详情 ID");
TimiException.required(mapper.selectSiteByIdAndUserId(detailId, userId), "未找到站内通知");
mapper.markSiteRead(detailId, userId, Time.now());
}
/// 标记用户全部站内通知已读
///
/// @param userId 用户 ID
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void markAllSiteRead(String userId) {
TimiException.required(userId, "未找到用户 ID");
mapper.markAllSiteRead(userId, Time.now());
}
}
@@ -1,12 +1,25 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.Notify;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.mapper.NotifyMapper;
import com.imyeyu.api.modules.common.service.NotifyDetailService;
import com.imyeyu.api.modules.common.service.NotifyService;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.service.AbstractEntityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 通知服务实现
@@ -14,14 +27,118 @@ import org.springframework.stereotype.Service;
* @author 夜雨
* @since 2026-05-13 14:46
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class NotifyServiceImplement extends AbstractEntityService<Notify, String> implements NotifyService {
private final LoggerService loggerService;
private final UserLoginService userLoginService;
private final NotifyDetailService detailService;
private final NotifyMapper mapper;
@Override
protected BaseMapper<Notify, String> mapper() {
return mapper;
}
/// 创建通知并级联创建通知详情
///
/// @param notify 通知
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(Notify notify) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_NOTIFY_CREATE");
try {
TimiException.required(notify, "未找到通知");
TimiException.required(notify.getDetailList(), "未找到通知详情列表");
super.create(notify);
String sendFrom = null;
if (userLoginService.isLogged()) {
sendFrom = userLoginService.getRequireLoginUserId();
}
for (NotifyDetail detail : notify.getDetailList()) {
detail.setNotifyId(notify.getId());
if (TimiJava.isNotEmpty(sendFrom)) {
detail.setSendFrom(sendFrom);
}
detailService.create(detail);
}
logger.setLevel(Logger.Level.INFO);
logger.setResult(notify.getId());
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("创建通知失败", e);
throw new TimiException(TimiCode.ERROR, "创建通知失败", e);
} finally {
loggerService.create(logger);
}
}
/// 删除通知并级联软删除通知详情
///
/// @param notifyId 通知 ID
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void delete(String notifyId) {
Logger logger = new Logger(Logger.Module.COMMON, "COMMON_NOTIFY_DELETE");
try {
TimiException.required(notifyId, "未找到通知 ID");
TimiException.required(get(notifyId), "未找到通知");
List<NotifyDetail> detailList = detailService.listByNotifyId(notifyId);
for (NotifyDetail detail : detailList) {
detailService.delete(detail.getId());
}
super.delete(notifyId);
logger.setLevel(Logger.Level.INFO);
logger.setResult(notifyId);
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage());
throw e;
} catch (Exception e) {
logger.setLevel(Logger.Level.ERROR);
logger.setException(TimiJava.serializeThrowable(e));
log.error("删除通知失败", e);
throw new TimiException(TimiCode.ERROR, "删除通知失败", e);
} finally {
loggerService.create(logger);
}
}
/// 取消通知中尚未成功发送的通知详情
///
/// @param notifyId 通知 ID
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void cancel(String notifyId) {
TimiException.required(notifyId, "未找到通知 ID");
TimiException.required(get(notifyId), "未找到通知");
boolean canceled = false;
for (NotifyDetail detail : detailService.listByNotifyId(notifyId)) {
if (detail.getStatus() == NotifyDetail.Status.REMINDED
|| detail.getStatus() == NotifyDetail.Status.CANCEL
) {
continue;
}
if (detail.getMsgType() != null && detail.getMsgType().isQueue()) {
detail.getMsgType().getService().destroyQueue(detail);
}
detail.setStatus(NotifyDetail.Status.CANCEL);
detail.setResultDesc("通知已取消");
detailService.update(detail);
canceled = true;
}
if (!canceled) {
throw new TimiException(TimiCode.RESULT_BAD, "通知没有可取消的通知详情");
}
}
}
@@ -0,0 +1,72 @@
package com.imyeyu.api.modules.common.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.entity.SmsQueue;
import com.imyeyu.api.modules.common.mapper.BaseQueueMapper;
import com.imyeyu.api.modules.common.mapper.SmsQueueMapper;
import com.imyeyu.api.modules.common.service.SmsQueueService;
import com.imyeyu.api.modules.common.util.QCloudSmsProxy;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Regex;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/// 短信队列服务实现
///
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsQueueServiceImplement extends AbstractQueueService<SmsQueue, NotifyQueueConfig.Sms> implements SmsQueueService {
private final NotifyQueueConfig config;
private final ObjectMapper jackson;
private final QCloudSmsProxy smsProxy;
private final SmsQueueMapper mapper;
@Override
protected NotifyQueueConfig.Sms config() {
return config.getSms();
}
@Override
protected BaseQueueMapper<SmsQueue> mapper() {
return mapper;
}
@Override
protected void validateSendTo(String sendTo) {
TimiException.requiredTrue(Regex.isMatch(Regex.MOBILE_PHONE, sendTo), "发送目标不是手机号");
}
@Override
public void createQueue(NotifyDetail detail) {
mapper.insert(new SmsQueue(detail));
}
@Override
protected void doSend(SmsQueue queue) {
try {
String[] args = jackson.treeToValue(queue.getArgs(), String[].class);
SendSmsResponse response = smsProxy.send(queue.getSendTo(), queue.getTemplateId(), args);
TimiException.required(response, "未找到短信响应");
SendStatus[] statusSet = response.getSendStatusSet();
TimiException.requiredTrue(statusSet != null && 0 < statusSet.length, "短信响应为空");
if (!"ok".equalsIgnoreCase(statusSet[0].getCode())) {
throw new TimiException(TimiCode.ERROR, jackson.writeValueAsString(response));
}
} catch (TimiException e) {
throw e;
} catch (Exception e) {
throw new TimiException(TimiCode.ERROR, "短信发送失败", e);
}
}
}
@@ -0,0 +1,85 @@
package com.imyeyu.api.modules.common.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.entity.Notify;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.service.NotifyDetailService;
import com.imyeyu.api.modules.common.service.NotifyService;
import com.imyeyu.api.modules.common.service.SmsService;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Regex;
import com.imyeyu.utils.Text;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
*
* @author 夜雨
* @since 2026-05-14 12:12
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsServiceImplement implements SmsService {
@Value("${spring.profiles.active}")
private String env;
private final NotifyQueueConfig config;
private final ObjectMapper jackson;
private final NotifyService notifyService;
private final NotifyDetailService notifyDetailService;
@Override
public String captchaCreate(Notify notify) {
NotifyQueueConfig.Sms.Captcha captchaConf = config.getSms().getCaptcha();
NotifyDetail detail = notify.getDetailList().getFirst();
TimiException.requiredTrue(Regex.isMatch(Regex.MOBILE_PHONE, detail.getSendTo()), "invalid mobilePhone");
String code = Text.randomString("0123456789", 6);
if (!env.equalsIgnoreCase("prod")) {
code = "123456";
}
detail.setMsgType(NotifyDetail.MsgType.SMS);
detail.setTemplateId(captchaConf.getTemplateId());
detail.setArgs(jackson.valueToTree(List.of(code, captchaConf.getTtlMinute())));
notifyService.create(notify);
return notifyDetailService.listByNotifyId(notify.getId()).getFirst().getId();
}
@Override
public NotifyDetail captchaVerify(String detailId, String captcha) {
NotifyQueueConfig.Sms.Captcha captchaConf = config.getSms().getCaptcha();
NotifyDetail detail = notifyDetailService.get(detailId);
TimiException.required(detail, "短信验证码无效");
TimiException.required(detail.getSendAt(), "短信验证码无效");
TimiException.requiredTrue(NotifyDetail.MsgType.SMS == detail.getMsgType(), "短信验证码无效");
if (Time.M * captchaConf.getTtlMinute() < Time.now() - detail.getSendAt()) {
throw new TimiException(TimiCode.ARG_EXPIRED, "验证码过期");
}
if (detail.getArgs() instanceof ArrayNode array) {
String dbCaptcha = array.get(captchaConf.getArgIndex()).asText();
if (!dbCaptcha.equalsIgnoreCase(captcha)) {
throw new TimiException(TimiCode.RESULT_BAD, "验证码错误");
}
} else {
throw new TimiException(TimiCode.ERROR, "not array args");
}
detail.setNotify(notifyService.get(detail.getNotifyId()));
return detail;
}
}
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.Tag;
import com.imyeyu.api.modules.common.entity.TagApply;
import com.imyeyu.api.modules.common.mapper.TagApplyMapper;
@@ -7,11 +8,14 @@ import com.imyeyu.api.modules.common.mapper.TagMapper;
import com.imyeyu.api.modules.common.service.MultilingualService;
import com.imyeyu.api.modules.common.service.TagService;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.service.AbstractEntityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
@@ -40,6 +44,9 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
public void create(Tag tag) {
TimiException.required(tag, "not found tag");
TimiException.required(tag.getZhCN(), "not found tag.zhCN");
TimiException.required(tag.getOwnerType(), "not found ownerType");
TimiException.required(tag.getOwnerId(), "not found ownerId");
checkZhCNUniqueInOwner(tag, null);
tag.setNameLangId(multilingualService.create(tag.getZhCN()));
super.create(tag);
}
@@ -48,12 +55,15 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
public void update(Tag tag) {
TimiException.required(tag, "not found tag");
TimiException.required(tag.getId(), "not found tag.id");
if (tag.getZhCN() != null) {
if (tag.getNameLangId() == null) {
Tag dbTag = get(tag.getId());
TimiException.required(dbTag, "not found tag");
tag.setOwnerType(dbTag.getOwnerType());
tag.setOwnerId(dbTag.getOwnerId());
if (tag.getZhCN() != null) {
if (tag.getNameLangId() == null) {
tag.setNameLangId(dbTag.getNameLangId());
}
checkZhCNUniqueInOwner(tag, tag.getId());
tag.setNameLangId(multilingualService.createIfDifferent(tag.getNameLangId(), tag.getZhCN()));
}
super.update(tag);
@@ -64,6 +74,14 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
return mapper.selectByIdList(new HashSet<>(idList));
}
@Override
public PageResult<Tag> pageByOwnerAndKeyword(Page<Tag> page, Tag.OwnerType ownerType, String ownerId, String keyword) {
PageResult<Tag> result = new PageResult<>();
result.setTotal(mapper.countByOwnerAndKeyword(ownerType, ownerId, keyword));
result.setList(mapper.selectByOwnerAndKeyword(ownerType, ownerId, keyword, page.getOffset(), page.getLimit()));
return result;
}
@Override
public List<Tag> listByBizType(TagApply.BizType bizType, String bizId) {
return listByIdList(listApply(bizType, bizId).stream().map(TagApply::getTagId).toList());
@@ -88,6 +106,19 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void deleteByOwner(Tag.OwnerType ownerType, String ownerId) {
TimiException.required(ownerType, "not found ownerType");
TimiException.required(ownerId, "not found ownerId");
Tag example = new Tag();
example.setOwnerType(ownerType);
example.setOwnerId(ownerId);
for (Tag tag : mapper.selectAllByExample(example)) {
super.delete(tag.getId());
}
}
private List<TagApply> listApply(TagApply.BizType bizType, String bizId) {
TimiException.required(bizType, "not found bizType");
TimiException.required(bizId, "not found bizId");
@@ -97,4 +128,9 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
example.setBizId(bizId);
return applyMapper.selectAllByExample(example);
}
private void checkZhCNUniqueInOwner(Tag tag, String allowedId) {
Tag existed = mapper.selectByOwnerAndZhCN(tag.getOwnerType(), tag.getOwnerId(), tag.getZhCN());
TimiException.requiredTrue(existed == null || existed.getId().equals(allowedId), "该标签名称已存在");
}
}
@@ -0,0 +1,52 @@
package com.imyeyu.api.modules.common.service.implement;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.common.entity.WechatQueue;
import com.imyeyu.api.modules.common.mapper.BaseQueueMapper;
import com.imyeyu.api.modules.common.mapper.WechatQueueMapper;
import com.imyeyu.api.modules.common.service.WechatQueueService;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/// 微信队列服务实现
///
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatQueueServiceImplement extends AbstractQueueService<WechatQueue, NotifyQueueConfig.Wechat> implements WechatQueueService {
private final NotifyQueueConfig config;
private final WechatQueueMapper mapper;
@Override
protected NotifyQueueConfig.Wechat config() {
return config.getWechat();
}
@Override
protected BaseQueueMapper<WechatQueue> mapper() {
return mapper;
}
@Override
protected void validateSendTo(String sendTo) {
TimiException.required(sendTo, "发送目标不能为空");
}
@Override
public void createQueue(NotifyDetail detail) {
mapper.insert(new WechatQueue(detail));
}
@Override
protected void doSend(WechatQueue queue) {
throw new TimiException(TimiCode.ERROR_NOT_SUPPORT, "微信推送暂未实现");
}
}
@@ -2,6 +2,7 @@ package com.imyeyu.api.modules.common.task;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
@@ -23,6 +24,7 @@ import java.util.List;
public class AttachmentClearTask {
private final AttachmentService attachmentService;
private final AttachmentVariantService attachmentVariantService;
@Scheduled(cron = "0 0 1 * * ?")
public void run() {
@@ -31,8 +33,7 @@ public class AttachmentClearTask {
List<Attachment> needDestroyList = attachmentService.listNeedDestroy();
if (needDestroyList.isEmpty()) {
log.info("nothing attachment need clear");
return;
}
} else {
for (Attachment attach : needDestroyList) {
try {
attachmentService.destroy(attach.getId());
@@ -41,6 +42,8 @@ public class AttachmentClearTask {
log.error("clear attachment error: id[{}]", attach.getId(), e);
}
}
}
attachmentVariantService.clearExpired();
log.info("end clear expired attachments");
} catch (Exception e) {
log.error("attachment clear task error", e);
@@ -0,0 +1,46 @@
package com.imyeyu.api.modules.common.task;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.service.MailQueueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
/// 邮件队列定时任务
///
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
@Service
@RequiredArgsConstructor
public class MailQueueTask implements SchedulingConfigurer {
private final NotifyQueueConfig config;
private final MailQueueService service;
private boolean running;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
if (!config.getMail().isEnable()) {
log.warn("邮件队列任务已禁用");
return;
}
taskRegistrar.addTriggerTask(() -> {
if (running) {
log.info("邮件队列任务正在运行,跳过本次执行");
return;
}
running = true;
try {
service.invokeQueue();
} finally {
running = false;
}
}, triggerContext -> new CronTrigger(config.getMail().getCron()).nextExecution(triggerContext));
}
}
@@ -0,0 +1,46 @@
package com.imyeyu.api.modules.common.task;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.imyeyu.api.modules.common.service.SmsQueueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
/// 短信队列定时任务
///
/// @author 夜雨
/// @since 2026-08-20
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsQueueTask implements SchedulingConfigurer {
private final NotifyQueueConfig config;
private final SmsQueueService service;
private boolean running;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
if (!config.getSms().isEnable()) {
log.warn("短信队列任务已禁用");
return;
}
taskRegistrar.addTriggerTask(() -> {
if (running) {
log.info("短信队列任务正在运行,跳过本次执行");
return;
}
running = true;
try {
service.invokeQueue();
} finally {
running = false;
}
}, triggerContext -> new CronTrigger(config.getSms().getCron()).nextExecution(triggerContext));
}
}
@@ -0,0 +1,8 @@
package com.imyeyu.api.modules.common.task;
/// 微信队列定时任务占位
///
/// @author 夜雨
/// @since 2026-08-20
public class WechatQueueTask {
}
@@ -0,0 +1,73 @@
package com.imyeyu.api.modules.common.util;
import com.imyeyu.api.modules.common.config.NotifyQueueConfig;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.List;
/// 腾讯云短信服务代理
///
/// @author 夜雨
/// @since 2026-08-20
@Component
@RequiredArgsConstructor
public class QCloudSmsProxy {
private final NotifyQueueConfig config;
/// 发送短信
///
/// @param mobilePhone 手机号
/// @param templateId 模板 ID
/// @param args 模板参数
/// @return 腾讯云短信响应
/// @throws TencentCloudSDKException 腾讯云 SDK 调用异常
public SendSmsResponse send(String mobilePhone, String templateId, String[] args) throws TencentCloudSDKException {
return send(List.of(mobilePhone), templateId, args);
}
/// 批量发送短信
///
/// @param mobilePhoneList 手机号列表
/// @param templateId 模板 ID
/// @param args 模板参数
/// @return 腾讯云短信响应
/// @throws TencentCloudSDKException 腾讯云 SDK 调用异常
public SendSmsResponse send(List<String> mobilePhoneList, String templateId, String[] args) throws TencentCloudSDKException {
SmsClient client = createSmsClient();
NotifyQueueConfig.Sms sms = config.getSms();
SendSmsRequest request = new SendSmsRequest();
request.setSmsSdkAppId(sms.getAppId().trim());
request.setSignName(sms.getSign().trim());
request.setTemplateId(templateId);
request.setTemplateParamSet(args);
request.setPhoneNumberSet(mobilePhoneList.toArray(new String[0]));
return client.SendSms(request);
}
private SmsClient createSmsClient() {
NotifyQueueConfig.Sms sms = config.getSms();
Credential credential = new Credential(sms.getSecretId().trim(), sms.getSecretKey().trim());
HttpProfile httpProfile = new HttpProfile();
httpProfile.setReqMethod("GET");
httpProfile.setConnTimeout(10);
httpProfile.setWriteTimeout(10);
httpProfile.setReadTimeout(10);
httpProfile.setEndpoint("sms.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setSignMethod("HmacSHA256");
clientProfile.setHttpProfile(httpProfile);
return new SmsClient(credential, "ap-guangzhou", clientProfile);
}
}
@@ -0,0 +1,35 @@
package com.imyeyu.api.modules.common.util;
import com.imyeyu.api.modules.common.entity.BaseQueueEntity;
import com.imyeyu.spring.util.SQLProvider;
import com.imyeyu.utils.Time;
import org.apache.ibatis.builder.annotation.ProviderContext;
/// 通知队列 SQL 提供器
///
/// @author 夜雨
/// @since 2026-08-20
public class QueueSQLProvider extends SQLProvider {
/// 查询已到发送时间的队列
///
/// @param context Mapper 上下文
/// @return 查询 SQL
public String listReadyQueue(ProviderContext context) {
EntityMeta meta = getEntityMeta(context);
StringBuilder sql = new StringBuilder("SELECT * FROM %s WHERE 1 = 1".formatted(meta.getTable()));
if (BaseQueueEntity.class.isAssignableFrom(meta.getEntityClass())) {
sql.append(" AND `send_at` < %d".formatted(Time.now()));
}
return sql.toString();
}
/// 根据通知详情 ID 物理删除队列
///
/// @param context Mapper 上下文
/// @return 删除 SQL
public String destroyByNotifyDetailId(ProviderContext context) {
EntityMeta meta = getEntityMeta(context);
return "DELETE FROM %s WHERE `notify_detail_id` = #{notifyDetailId}".formatted(meta.getTable());
}
}
@@ -0,0 +1,15 @@
package com.imyeyu.api.modules.common.vo;
import lombok.Data;
///
///
/// @author 夜雨
/// @since 2026-08-21 17:59
@Data
public class SmsCaptchaVerifyRequest {
private String detailId;
private String captcha;
}
@@ -84,7 +84,7 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
@Getter
final boolean grantToStoreManager;
/// `true` 为初始化时授权给全局管理角色
/// `true` 为初始化时授权给门店管理角色
@Getter
final boolean grantToGlobalManager;
@@ -12,8 +12,8 @@ import lombok.AllArgsConstructor;
@AllArgsConstructor
public enum GaoRoleCode implements BuiltinRoleCode {
/// 全局管理
GLOBAL_MANAGER("全局管理", null),
/// 门店管理
GLOBAL_MANAGER("门店管理", null),
/// 店长
STORE_MANAGER("店长", GLOBAL_MANAGER.name());
@@ -0,0 +1,29 @@
package com.imyeyu.api.modules.gao.bean;
import lombok.Data;
/// GAO 用户邀请缓存
///
/// @author Codex
/// @since 2026-08-13
@Data
public class GaoUserInviteCache {
/// 发起邀请的用户 ID
private String inviterUserId;
/// 门店 IDGLOBAL_MANAGER 可为空
private String storeId;
/// 角色 ID
private String roleId;
/// 邀请来源或场景
private String scene;
/// 邀请创建时间,毫秒时间戳
private Long createdAt;
/// 邀请过期时间,毫秒时间戳
private Long expireAt;
}
@@ -12,6 +12,7 @@ import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStateReq;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
@@ -60,8 +61,8 @@ public class GaoCustomerController {
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/list")
@JsonView(ResponseView.Public.class)
public PageResult<GaoCustomer> list(@RequestBody Page<GaoCustomer> page) {
PageResult<GaoCustomer> result = service.page(page);
public PageResult<GaoCustomer> list(@RequestBody GaoCustomerPage page) {
PageResult<GaoCustomer> result = service.pageByQuery(page);
List<String> idList = result.getList().stream().map(GaoCustomer::getId).distinct().toList();
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, idList);
@@ -62,7 +62,9 @@ public class GaoEventController {
@RequireGaoPermission(GaoPermissionCode.EVENT_READ)
@PostMapping("/detail")
public GaoEvent detail(@RequestParam String id) {
return service.get(id);
GaoEvent event = service.get(id);
event.setRoleCodeList(service.listRoleCode(event.getId()));
return event;
}
@AOPLog
@@ -16,6 +16,7 @@ import com.imyeyu.api.modules.gao.service.GaoEventService;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPageResult;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
@@ -64,8 +65,12 @@ public class GaoEventRecordController {
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_READ)
@PostMapping("/list")
@JsonView(ResponseView.Public.class)
public PageResult<GaoEventRecord> list(@RequestBody GaoEventRecordPage page) {
PageResult<GaoEventRecord> result = service.pageByRange(page);
public GaoEventRecordPageResult list(@RequestBody GaoEventRecordPage page) {
PageResult<GaoEventRecord> pageResult = service.pageByRange(page);
GaoEventRecordPageResult result = new GaoEventRecordPageResult();
result.setTotal(pageResult.getTotal());
result.setList(pageResult.getList());
result.setNumberValueTotal(resolveNumberValueTotal(page));
{
List<String> customerIdList = result.getList().stream().map(GaoEventRecord::getCustomerId).toList();
Map<String, GaoEvent> eventMap = eventService.mapByIdList(result.getList().stream().map(GaoEventRecord::getEventId).toList());
@@ -80,6 +85,22 @@ public class GaoEventRecordController {
return result;
}
/// 根据列表筛选条件返回单个 NUMBER 事件的数值合计
///
/// @param page 登记记录范围查询请求
/// @return 数值合计,不满足单个 NUMBER 事件条件时为空
private Long resolveNumberValueTotal(GaoEventRecordPage page) {
List<String> eventIdList = page.getEventIdList();
if (eventIdList == null || eventIdList.size() != 1) {
return null;
}
GaoEvent event = eventService.mapByIdList(eventIdList).get(eventIdList.get(0));
if (event == null || event.getValueType() != GaoEvent.ValueType.NUMBER) {
return null;
}
return service.sumNumberValueByRange(page);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_READ)
@@ -7,11 +7,15 @@ import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.entity.GaoPointAccount;
import com.imyeyu.api.modules.gao.service.GaoPointAccountService;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.vo.GaoPointAccountPage;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.PageResult;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@@ -32,12 +36,30 @@ public class GaoPointAccountController {
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.POINT_ACCOUNT_READ)
@PostMapping("/account/detail")
@PostMapping("/account/list")
public PageResult<GaoPointAccount> list(@RequestBody GaoPointAccountPage page) {
TimiException.required(page, "not found page");
page.setStoreId(resolveStoreId(page.getStoreId()));
return accountService.pageByQuery(page);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.POINT_ACCOUNT_READ)
@PostMapping("/account/detail/customer")
public GaoPointAccount detail(@RequestParam String customerId, @RequestParam(required = false) String storeId) {
storeId = resolveStoreId(storeId);
return accountService.getByCustomerId(storeId, customerId);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.POINT_ACCOUNT_READ)
@PostMapping("/account/detail")
public GaoPointAccount detailById(@RequestParam String id, @RequestParam(required = false) String storeId) {
return accountService.getByIdAndStoreId(resolveStoreId(storeId), id);
}
private String resolveStoreId(String requestedStoreId) {
if (roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.GLOBAL_MANAGER.name())) {
return requestedStoreId;
@@ -21,6 +21,8 @@ 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;
/// GAO 客户积分规则接口
///
/// @author Codex
@@ -78,6 +80,19 @@ public class GaoPointRuleController {
ruleService.update(rule);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.POINT_RULE_UPDATE)
@PostMapping("/rule/sort")
public void sort(@RequestBody List<String> idList) {
if (idList != null) {
for (GaoPointRule rule : ruleService.listByIdList(idList)) {
checkStore(rule.getStoreId());
}
}
ruleService.sort(idList);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.POINT_RULE_DELETE)
@@ -7,6 +7,7 @@ import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordNumberValueDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoStoreChartReq;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
@@ -57,6 +58,15 @@ public class GaoStoreChartController {
return service.eventRecordDailyStat(req);
}
/// 查询登记事件每日数值合计
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/event/record/number-value/daily")
public List<GaoEventRecordNumberValueDailyStatView> eventRecordNumberValueDaily(@RequestBody GaoStoreChartReq req) {
return service.eventRecordNumberValueDailyStat(req);
}
/// 查询登记事件日历记录
@AOPLog
@RequestRateLimit
@@ -0,0 +1,145 @@
package com.imyeyu.api.modules.gao.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.common.entity.Tag;
import com.imyeyu.api.modules.common.entity.TagApply;
import com.imyeyu.api.modules.common.service.TagService;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/// GAO 标签接口
///
/// @author Codex
/// @since 2026-08-13
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/tag")
public class GaoTagController {
private final TagService service;
private final RoleChecker roleChecker;
private final GaoStoreService storeService;
/// 查询标签列表
///
/// @param page 分页参数
/// @return 标签分页
@JsonView(ResponseView.Public.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_READ)
@PostMapping("/list")
public PageResult<Tag> list(@RequestBody Page<Tag> page) {
TimiException.required(page, "未找到分页参数");
String ownerId = null;
page.setEqualsExample(TimiJava.defaultIfNull(page.getEqualsExample(), new Tag()));
page.getEqualsExample().setOwnerType(Tag.OwnerType.GAO_STORE);
if (!roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.GLOBAL_MANAGER.name())) {
ownerId = storeService.getBelongIdByRequiredLoginUserId();
page.getEqualsExample().setOwnerId(ownerId);
}
String keyword = page.getLikesExample() == null ? null : page.getLikesExample().getName();
if (TimiJava.isNotEmpty(keyword)) {
return service.pageByOwnerAndKeyword(page, Tag.OwnerType.GAO_STORE, ownerId, keyword.trim());
}
return service.page(page);
}
/// 查询标签详情
///
/// @param id 标签 ID
/// @return 标签详情
@JsonView(ResponseView.Public.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_READ)
@PostMapping("/detail")
public Tag detail(@RequestParam String id) {
return service.get(id);
}
/// 创建标签
///
/// @param tag 标签
/// @return 标签
@AOPLog
@JsonView(ResponseView.Public.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_CREATE)
@PostMapping("/create")
public Tag create(@RequestBody Tag tag) {
tag.setOwnerType(Tag.OwnerType.GAO_STORE);
if (!roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.GLOBAL_MANAGER.name())) {
tag.setOwnerId(storeService.getBelongIdByRequiredLoginUserId());
}
service.create(tag);
return tag;
}
/// 更新标签
///
/// @param tag 标签
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_UPDATE)
@PostMapping("/update")
public void update(@RequestBody Tag tag) {
Tag dbTag = service.get(tag.getId());
tag.setOwnerType(dbTag.getOwnerType());
tag.setOwnerId(dbTag.getOwnerId());
service.update(tag);
}
/// 删除标签
///
/// @param id 标签 ID
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_DELETE)
@PostMapping("/delete")
public void delete(@RequestParam String id) {
service.delete(id);
}
/// 按业务查询标签
///
/// @param bizType 业务类型
/// @param bizId 业务 ID
/// @return 标签列表
@JsonView(ResponseView.Public.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_READ)
@GetMapping("/list/biz/id")
public List<Tag> listByBizType(@RequestParam TagApply.BizType bizType, @RequestParam String bizId) {
return service.listByBizType(bizType, bizId);
}
/// 差分保存业务标签
///
/// @param apply 标签请求
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.TAG_APPLY)
@PostMapping("/apply")
public void apply(@RequestBody TagApply apply) {
service.apply(apply.getBizType(), apply.getBizId(), apply.getTagIdList());
}
}
@@ -9,7 +9,14 @@ import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.entity.GaoUser;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.service.GaoUserInviteService;
import com.imyeyu.api.modules.gao.service.GaoUserService;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteCreateResponse;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteRegisterData;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteRegisterRequest;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteValidateRequest;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteValidateResponse;
import com.imyeyu.api.modules.user.entity.Role;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.RoleChecker;
@@ -17,12 +24,14 @@ import com.imyeyu.api.modules.user.service.RoleService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserRoleService;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.api.modules.user.vo.LoginResponse;
import com.imyeyu.java.TimiJava;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -32,6 +41,7 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/// GAO 用户接口
///
@@ -46,11 +56,37 @@ public class GaoUserController {
private final RoleService roleService;
private final RoleChecker roleChecker;
private final GaoUserService service;
private final GaoUserInviteService inviteService;
private final UserRoleService userRoleService;
private final GaoStoreService gaoStoreService;
private final UserLoginService userLoginService;
private final AttachmentService attachmentService;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.USER_CREATE)
@PostMapping("/invite")
public GaoUserInviteCreateResponse invite(@RequestBody @Valid GaoUserInviteCreateRequest req) {
return inviteService.create(req);
}
@AOPLog
@RequestRateLimit(20)
@PostMapping("/invite/validate")
public GaoUserInviteValidateResponse validateInvite(@RequestBody @Valid GaoUserInviteValidateRequest req) {
return inviteService.validate(req.getCode());
}
@AOPLog
@JsonView(ResponseView.Public.class)
@RequestRateLimit(value = 5, inSeconds = 60)
@PostMapping("/invite/register")
public LoginResponse registerByInvite(@RequestBody @Valid GaoUserInviteRegisterRequest req) {
GaoUserInviteRegisterData data = req.getData();
String userId = inviteService.register(data, req.getDetailId(), req.getCaptcha());
return userLoginService.login(UUID.randomUUID().toString(), userId);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.USER_READ)
@@ -85,7 +121,9 @@ public class GaoUserController {
{
User user = userService.get(result.getUserId());
user.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.USER, user.getId()));
user.setRoleList(userRoleService.listAllRoleCodeByUserId(user.getId()));
user.setRoleEntityList(userRoleService.listRoleByUserId(user.getId()));
user.setPermissionList(userRoleService.listAllPermissionCodeByUserId(user.getId()));
result.setUser(user);
}
return result;
@@ -137,6 +175,7 @@ public class GaoUserController {
@RequireGaoPermission(GaoPermissionCode.USER_READ)
@PostMapping("/role/list")
public List<Role> roleList() {
// TODO 此接口获取本模块所有角色,需要限制角色
return roleService.listByModuleCode(ModuleCode.GAO);
}
}
@@ -3,9 +3,12 @@ package com.imyeyu.api.modules.gao.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.entity.TagApply;
import com.imyeyu.api.modules.user.bean.Gender;
import com.imyeyu.api.modules.user.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.imyeyu.java.TimiJava;
import com.imyeyu.spring.annotation.table.Column;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
@@ -30,7 +33,11 @@ public class GaoCustomer extends UUIDEntity {
/// @since 2026-07-27
public enum AttachType {
PHOTO
PHOTO,
POINT_CARD,
OTHER
}
///
@@ -54,6 +61,18 @@ public class GaoCustomer extends UUIDEntity {
/// 姓名
private String name;
@Column("name_pinyin_full")
@JsonIgnore
private String namePinyinFull;
@Column("name_pinyin_initial")
@JsonIgnore
private String namePinyinInitial;
@Column("name_pinyin_mixed")
@JsonIgnore
private String namePinyinMixed;
/// 性别
private Gender gender;
@@ -105,6 +124,9 @@ public class GaoCustomer extends UUIDEntity {
@Transient
private List<GaoEventRecord> eventRecordList;
@Transient
private TagApply tagApply;
public boolean hasIntroducer() {
return TimiJava.isNotEmpty(introducerCustomerId);
}
@@ -38,6 +38,26 @@ public class GaoEvent extends UUIDEntity {
DELETED
}
/// 事件数值类型
public enum ValueType {
/// 不携带数值
NONE,
/// 携带整数数值
NUMBER
}
/// 事件数值单位
public enum ValueUnit {
/// 金额分
CENT,
/// 次数
COUNT
}
/// 登记限制类型
///
/// @author 夜雨
@@ -70,6 +90,9 @@ public class GaoEvent extends UUIDEntity {
final Long min;
}
/// 统计图表颜色
private String color;
/// 登记事件名称
private String name;
@@ -79,8 +102,14 @@ public class GaoEvent extends UUIDEntity {
/// 说明
private String description;
/// 统计图表颜色
private String color;
/// 数值类型
private ValueType valueType;
/// 数值单位
private ValueUnit valueUnit;
/// true 为登记时必须提交 numberValue
private Boolean requireValue;
/// 状态
private Status status;
@@ -40,6 +40,15 @@ public class GaoEventRecord extends UUIDEntity {
/// 操作管理员用户 ID
private String operatorUserId;
/// 本次登记提交的积分值
private Long pointValue;
/// 本次登记通过积分规则获得的积分总和
private Long earnedPointValue;
/// 本次登记提交的整数业务数值
private Long numberValue;
/// 备注
private String remark;
@@ -52,10 +61,6 @@ public class GaoEventRecord extends UUIDEntity {
/// 营业日递增序号
private Long businessDayNo;
/// 本次登记提交的积分值,只参与积分触发,不落库
@Transient
private Long pointValue;
@Transient
private GaoCustomer customer;
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -24,6 +25,9 @@ public class GaoPointAccount extends UUIDEntity {
/// 累计获得积分
private Long totalEarned;
/// 累计消耗积分
private Long totalConsumed;
/// 累计撤销积分
private Long totalRevoked;
@@ -32,4 +36,8 @@ public class GaoPointAccount extends UUIDEntity {
/// 乐观锁版本
private Long version;
/// 客户信息
@Transient
private GaoCustomer customer;
}
@@ -17,9 +17,12 @@ public class GaoPointLedger extends UUIDEntity {
/// 流水变化类型
public enum ChangeType {
/// 登记事件获得积分
/// 登记事件发放积分
EARN,
/// 登记事件消费积分
CONSUME,
/// 删除登记记录撤销积分
REVOKE,
@@ -42,7 +42,10 @@ public class GaoPointRule extends UUIDEntity {
AFTER_COUNT_EVERY_TIME,
/// 使用登记接口提交的积分值触发
SOURCE_VALUE
SOURCE_VALUE,
/// 按来源事件数值累计分档触发
CUSTOMER_EVENT_VALUE_TIER
}
/// 积分值模式
@@ -52,7 +55,10 @@ public class GaoPointRule extends UUIDEntity {
FIXED,
/// 使用登记接口提交的积分值
SOURCE_VALUE
SOURCE_VALUE,
/// 使用条件配置中的分档积分值
TIER
}
/// 门店 ID
@@ -3,6 +3,7 @@ package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerPage;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
@@ -35,4 +36,16 @@ public interface GaoCustomerMapper extends BaseMapper<GaoCustomer, String> {
///
/// @return 性别统计列表
List<GaoCustomerGenderStatView> stateGender(@Param("storeId") String storeId);
/// 查询客户总数
///
/// @param page 查询条件
/// @return 客户总数
long countByQuery(GaoCustomerPage page);
/// 分页查询客户
///
/// @param page 查询条件
/// @return 客户列表
List<GaoCustomer> selectByQuery(GaoCustomerPage page);
}
@@ -5,6 +5,7 @@ import com.imyeyu.api.modules.gao.vo.GaoCustomerChartReq;
import com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordNumberValueDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.api.modules.gao.vo.GaoStoreChartReq;
@@ -21,6 +22,28 @@ public interface GaoEventRecordMapper extends BaseMapper<GaoEventRecord, String>
Long count(String storeId, String customerId, String eventId, Long beginAt, Long endAt);
/// 查询事件中已携带数值的登记记录数量
///
/// @param eventId 事件 ID
/// @return 携带数值的登记记录数量
Long countByEventIdAndNumberValue(String eventId);
/// 汇总客户指定来源事件在时间范围内的数值
///
/// @param storeId 门店 ID
/// @param customerId 客户 ID
/// @param eventId 来源事件 ID
/// @param beginAt 起始时间,包含
/// @param endAt 结束时间,不包含
/// @return 数值总和
Long sumNumberValue(@Param("storeId") String storeId, @Param("customerId") String customerId, @Param("eventId") String eventId, @Param("beginAt") Long beginAt, @Param("endAt") Long endAt);
/// 回写登记记录最终获得的积分快照
///
/// @param id 登记记录 ID
/// @param earnedPointValue 获得积分总和
void updateEarnedPointValue(@Param("id") String id, @Param("earnedPointValue") Long earnedPointValue);
/// 按门店和登记日期统计登记记录数
///
/// @param storeId 门店 ID
@@ -42,6 +65,12 @@ public interface GaoEventRecordMapper extends BaseMapper<GaoEventRecord, String>
/// @return 登记事件记录列表
List<GaoEventRecord> selectByRange(GaoEventRecordPage page);
/// 按登记记录列表条件汇总数值
///
/// @param page 登记记录范围查询请求
/// @return 登记数值合计
Long sumNumberValueByRange(GaoEventRecordPage page);
/// 统计客户登记排行榜总数
///
/// @param page 排行榜分页请求
@@ -60,6 +89,9 @@ public interface GaoEventRecordMapper extends BaseMapper<GaoEventRecord, String>
/// @return 每日登记数
List<GaoEventRecordDailyStatView> stateDailyByRange(GaoStoreChartReq req);
/// 按时间范围和事件统计每日登记数值合计
List<GaoEventRecordNumberValueDailyStatView> stateNumberValueDailyByRange(GaoStoreChartReq req);
/// 按时间范围查询登记日历记录
///
/// @param req 门店报表查询请求
@@ -1,9 +1,12 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoPointAccount;
import com.imyeyu.api.modules.gao.vo.GaoPointAccountPage;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/// GAO 客户积分账户 Mapper
///
/// @author Codex
@@ -17,6 +20,25 @@ public interface GaoPointAccountMapper extends BaseMapper<GaoPointAccount, Strin
/// @return 积分账户
GaoPointAccount selectByStoreIdAndCustomerId(@Param("storeId") String storeId, @Param("customerId") String customerId);
/// 按账户 ID 和门店查询积分账户
///
/// @param storeId 门店 ID,可为空
/// @param id 账户 ID
/// @return 积分账户
GaoPointAccount selectByIdAndStoreId(@Param("storeId") String storeId, @Param("id") String id);
/// 统计积分账户数量
///
/// @param page 查询条件
/// @return 账户数量
long countByQuery(GaoPointAccountPage page);
/// 分页查询积分账户
///
/// @param page 查询条件
/// @return 账户列表
List<GaoPointAccount> selectByQuery(GaoPointAccountPage page);
/// 创建客户积分账户,已存在时保持原账户不变
///
/// @param account 积分账户
@@ -33,9 +55,10 @@ public interface GaoPointAccountMapper extends BaseMapper<GaoPointAccount, Strin
/// @param id 账户 ID
/// @param delta 本次余额变化
/// @param totalEarnedDelta 累计获得积分变化
/// @param totalConsumedDelta 累计消耗积分变化
/// @param totalRevokedDelta 累计撤销积分变化
/// @param totalAdjustedDelta 累计人工调整积分变化
/// @param updatedAt 更新时间
/// @return 更新行数
int updateBalance(@Param("id") String id, @Param("delta") long delta, @Param("totalEarnedDelta") long totalEarnedDelta, @Param("totalRevokedDelta") long totalRevokedDelta, @Param("totalAdjustedDelta") long totalAdjustedDelta, @Param("updatedAt") long updatedAt);
int updateBalance(@Param("id") String id, @Param("delta") long delta, @Param("totalEarnedDelta") long totalEarnedDelta, @Param("totalConsumedDelta") long totalConsumedDelta, @Param("totalRevokedDelta") long totalRevokedDelta, @Param("totalAdjustedDelta") long totalAdjustedDelta, @Param("updatedAt") long updatedAt);
}
@@ -19,11 +19,11 @@ public interface GaoPointLedgerMapper extends BaseMapper<GaoPointLedger, String>
/// @return 流水
GaoPointLedger selectByIdempotencyKey(@Param("idempotencyKey") String idempotencyKey);
/// 查询登记记录产生的原始获得积分流水
/// 查询登记记录产生的原始规则积分流水
///
/// @param eventRecordId 登记记录 ID
/// @return 获得积分流水
List<GaoPointLedger> selectEarnByEventRecordId(@Param("eventRecordId") String eventRecordId);
/// @return 原始规则积分流水
List<GaoPointLedger> selectRuleChangeByEventRecordId(@Param("eventRecordId") String eventRecordId);
/// 批量查询幂等键对应的流水
///
@@ -4,6 +4,7 @@ import com.imyeyu.api.modules.gao.entity.GaoPointRule;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.Collection;
import java.util.List;
/// GAO 客户积分规则 Mapper
@@ -12,6 +13,8 @@ import java.util.List;
/// @since 2026-08-11
public interface GaoPointRuleMapper extends BaseMapper<GaoPointRule, String> {
List<GaoPointRule> selectByIdList(Collection<String> idList);
/// 查询当前时间可匹配的启用规则
///
/// @param storeId 门店 ID
@@ -3,8 +3,10 @@ package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStateReq;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
import java.io.IOException;
@@ -19,6 +21,12 @@ import java.util.stream.Collectors;
/// @since 2026-07-27 14:12
public interface GaoCustomerService extends BaseService<GaoCustomer, String> {
/// 按查询条件分页查询客户
///
/// @param page 查询条件
/// @return 客户分页
PageResult<GaoCustomer> pageByQuery(GaoCustomerPage page);
void updateWithAttachment(GaoCustomer customer);
/// 按编码查询客户
@@ -37,6 +45,11 @@ public interface GaoCustomerService extends BaseService<GaoCustomer, String> {
List<GaoCustomer> listByIdList(Collection<String> idList);
/// 删除门店下的全部客户及其关联业务数据
///
/// @param storeId 门店 ID
void deleteByStoreId(String storeId);
default Map<String, GaoCustomer> mapByIdList(Collection<String> idList) {
return listByIdList(idList).stream().collect(Collectors.toMap(GaoCustomer::getId, item -> item));
}
@@ -18,6 +18,12 @@ import java.util.List;
/// @since 2026-07-27 14:09
public interface GaoEventRecordService extends BaseService<GaoEventRecord, String> {
/// 按客户查询登记事件记录
///
/// @param customerId 客户 ID
/// @return 登记事件记录列表
List<GaoEventRecord> listByCustomerId(String customerId);
default void createBatch(List<GaoEventRecord> recordList) {
for (GaoEventRecord record : TimiJava.safeIterable(recordList)) {
create(record);
@@ -32,6 +38,12 @@ public interface GaoEventRecordService extends BaseService<GaoEventRecord, Strin
/// @return 登记事件记录列表
PageResult<GaoEventRecord> pageByRange(GaoEventRecordPage req);
/// 按登记记录列表条件汇总数值
///
/// @param req 登记记录范围查询请求
/// @return 登记数值合计
Long sumNumberValueByRange(GaoEventRecordPage req);
/// 按时间范围查询客户登记排行榜
///
/// @param page 范围查询请求,不传时间为全部时间
@@ -24,6 +24,11 @@ public interface GaoEventService extends BaseService<GaoEvent, String> {
/// @return 登记事件列表
List<GaoEvent> listValid(String storeId);
/// 删除门店下的全部登记事件及角色关联
///
/// @param storeId 门店 ID
void deleteByStoreId(String storeId);
/// 查询登记事件要求的角色
///
/// @param eventId 登记事件 ID
@@ -1,6 +1,8 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoPointAccount;
import com.imyeyu.api.modules.gao.vo.GaoPointAccountPage;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
/// GAO 客户积分账户服务
@@ -9,6 +11,12 @@ import com.imyeyu.spring.service.BaseService;
/// @since 2026-08-11
public interface GaoPointAccountService extends BaseService<GaoPointAccount, String> {
/// 分页查询积分账户
///
/// @param page 查询条件
/// @return 账户分页
PageResult<GaoPointAccount> pageByQuery(GaoPointAccountPage page);
/// 查询客户当前有效积分账户
///
/// @param storeId 门店 ID
@@ -16,6 +24,18 @@ public interface GaoPointAccountService extends BaseService<GaoPointAccount, Str
/// @return 积分账户,不存在时返回 null
GaoPointAccount getByCustomerId(String storeId, String customerId);
/// 按账户 ID 查询积分账户
///
/// @param storeId 门店 ID,可为空
/// @param id 账户 ID
/// @return 积分账户,不存在时返回 null
GaoPointAccount getByIdAndStoreId(String storeId, String id);
/// 删除门店下的全部积分账户
///
/// @param storeId 门店 ID
void deleteByStoreId(String storeId);
/// 获取并锁定客户积分账户,不存在时创建
///
/// @param storeId 门店 ID
@@ -28,8 +48,9 @@ public interface GaoPointAccountService extends BaseService<GaoPointAccount, Str
/// @param accountId 账户 ID
/// @param delta 本次余额变化
/// @param totalEarnedDelta 累计获得积分变化
/// @param totalConsumedDelta 累计消耗积分变化
/// @param totalRevokedDelta 累计撤销积分变化
/// @param totalAdjustedDelta 累计人工调整积分变化
/// @return 更新行数
int updateBalance(String accountId, long delta, long totalEarnedDelta, long totalRevokedDelta, long totalAdjustedDelta);
int updateBalance(String accountId, long delta, long totalEarnedDelta, long totalConsumedDelta, long totalRevokedDelta, long totalAdjustedDelta);
}
@@ -15,18 +15,18 @@ import com.imyeyu.spring.service.BaseService;
/// @since 2026-08-11
public interface GaoPointLedgerService extends BaseService<GaoPointLedger, String> {
/// 写入登记获得积分流水
/// 写入登记规则积分流水
///
/// @param record 登记记录
/// @param rule 命中规则
/// @param pointDelta 积分变化
/// @param sourcePayload 来源快照
/// @return 积分流水
GaoPointLedger earn(GaoEventRecord record, GaoPointRule rule, long pointDelta, JsonNode sourcePayload);
GaoPointLedger applyRule(GaoEventRecord record, GaoPointRule rule, long pointDelta, JsonNode sourcePayload);
/// 写入删除登记记录的撤销流水
///
/// @param originLedger 原始获得积分流水
/// @param originLedger 原始规则积分流水
/// @param record 登记记录
/// @return 撤销流水
GaoPointLedger revoke(GaoPointLedger originLedger, GaoEventRecord record);
@@ -19,6 +19,22 @@ public interface GaoPointRuleService extends BaseService<GaoPointRule, String> {
/// @return 规则列表
List<GaoPointRule> listActive(String storeId, String eventId, long now);
/// 查询规则 ID 列表
///
/// @param idList 规则 ID 列表
/// @return 规则列表
List<GaoPointRule> listByIdList(List<String> idList);
/// 删除门店下的全部积分规则
///
/// @param storeId 门店 ID
void deleteByStoreId(String storeId);
/// 按客户端提交的顺序更新启用规则优先级
///
/// @param idList 规则 ID 列表
void sort(List<String> idList);
/// 创建积分规则
///
/// @param rule 积分规则
@@ -36,4 +36,9 @@ public interface GaoStoreBusinessDayService extends BaseService<GaoStoreBusiness
/// @param endDateValue 结束日期值,格式为 yyyyMMdd
/// @return 营业日列表
java.util.List<GaoStoreBusinessDay> listByDateRange(String storeId, Integer beginDateValue, Integer endDateValue);
/// 删除门店下的全部营业日
///
/// @param storeId 门店 ID
void deleteByStoreId(String storeId);
}
@@ -4,6 +4,7 @@ import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordNumberValueDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoStoreChartReq;
import java.util.List;
@@ -23,6 +24,9 @@ public interface GaoStoreChartService {
/// 查询登记事件每日统计
List<GaoEventRecordDailyStatView> eventRecordDailyStat(GaoStoreChartReq req);
/// 查询登记事件每日数值合计
List<GaoEventRecordNumberValueDailyStatView> eventRecordNumberValueDailyStat(GaoStoreChartReq req);
/// 查询登记事件日历记录
List<GaoEventRecordCalendarView> eventRecordCalendar(GaoStoreChartReq req);
}
@@ -0,0 +1,33 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteCreateResponse;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteRegisterData;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteValidateResponse;
/// GAO 用户邀请注册服务
///
/// @author Codex
/// @since 2026-08-13
public interface GaoUserInviteService {
/// 创建 GAO 用户邀请
///
/// @param req 邀请创建请求
/// @return 邀请 code 和过期时间
GaoUserInviteCreateResponse create(GaoUserInviteCreateRequest req);
/// 校验 GAO 用户邀请是否可用
///
/// @param code 邀请 code
/// @return 校验结果
GaoUserInviteValidateResponse validate(String code);
/// 使用邀请注册 GAO 用户
///
/// @param data 注册数据
/// @param smsDetailId 短信通知详情 ID
/// @param smsCaptcha 短信验证码
/// @return 注册成功的用户 ID
String register(GaoUserInviteRegisterData data, String smsDetailId, String smsCaptcha);
}

Some files were not shown because too many files have changed in this diff Show More