refactor gao module

This commit is contained in:
Timi
2026-08-06 10:52:50 +08:00
parent 568563475e
commit 1709316ce1
67 changed files with 1770 additions and 3319 deletions
+1
View File
@@ -3,6 +3,7 @@
<component name="SqlDialectMappings"> <component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/resources/db/migration/timiserver/V1__init_schema.sql" dialect="MariaDB" /> <file url="file://$PROJECT_DIR$/src/main/resources/db/migration/timiserver/V1__init_schema.sql" dialect="MariaDB" />
<file url="file://$PROJECT_DIR$/src/main/resources/db/migration/timiserver/V2__init_system_data.sql" dialect="GenericSQL" /> <file url="file://$PROJECT_DIR$/src/main/resources/db/migration/timiserver/V2__init_system_data.sql" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/src/main/resources/mapper/timi-server/GaoEventRecordMapper.xml" dialect="MariaDB" />
<file url="PROJECT" dialect="MariaDB" /> <file url="PROJECT" dialect="MariaDB" />
</component> </component>
</project> </project>
+2 -2
View File
@@ -188,12 +188,12 @@
<dependency> <dependency>
<groupId>com.imyeyu.java</groupId> <groupId>com.imyeyu.java</groupId>
<artifactId>timi-java</artifactId> <artifactId>timi-java</artifactId>
<version>0.0.6</version> <version>0.0.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.imyeyu.utils</groupId> <groupId>com.imyeyu.utils</groupId>
<artifactId>timi-utils</artifactId> <artifactId>timi-utils</artifactId>
<version>0.0.12</version> <version>0.0.13</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.imyeyu.font.icon</groupId> <groupId>com.imyeyu.font.icon</groupId>
@@ -3,8 +3,6 @@ package com.imyeyu.api.modules.common.controller;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.service.TempFileService; import com.imyeyu.api.modules.common.service.TempFileService;
import com.imyeyu.api.modules.common.vo.attach.BizDeleteReq;
import com.imyeyu.api.modules.common.vo.attach.BizUpdateReq;
import com.imyeyu.api.modules.common.vo.attach.TempFileResp; import com.imyeyu.api.modules.common.vo.attach.TempFileResp;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.network.Network; import com.imyeyu.network.Network;
@@ -183,30 +181,6 @@ public class AttachmentController {
return service.pageByBizId(bizType, bizId, attachTypeList, page); return service.pageByBizId(bizType, bizId, attachTypeList, page);
} }
/**
* 按业务差分更新附件
*
* @param req 更新请求
*/
@AOPLog
@RequestRateLimit
@PostMapping("/update/biz")
public void updateByBiz(@RequestBody BizUpdateReq req) {
service.updateByBiz(req);
}
/**
* 按业务删除全部附件
*
* @param req 删除请求
*/
@AOPLog
@RequestRateLimit
@PostMapping("/delete/biz")
public void deleteByBiz(@RequestBody BizDeleteReq req) {
service.deleteByBiz(req);
}
@AOPLog @AOPLog
@IgnoreGlobalReturn @IgnoreGlobalReturn
@GetMapping({"/read/{id}", "/download/{id}"}) @GetMapping({"/read/{id}", "/download/{id}"})
@@ -1,9 +1,10 @@
package com.imyeyu.api.modules.common.entity; package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.TimiServerAPI; import com.imyeyu.api.TimiServerAPI;
import com.imyeyu.api.modules.common.bean.attachment.AccessKey; import com.imyeyu.api.modules.common.bean.attachment.AccessKey;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.ref.Ref; import com.imyeyu.java.ref.Ref;
import com.imyeyu.spring.TimiSpring; import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.table.Transient; import com.imyeyu.spring.annotation.table.Transient;
@@ -33,7 +34,7 @@ public class Attachment extends UUIDEntity {
GAO_CUSTOMER, GAO_CUSTOMER,
GAO_REGISTRATION_EVENT_RECORD, GAO_EVENT_RECORD,
TEMP_FILE, TEMP_FILE,
@@ -54,7 +55,7 @@ public class Attachment extends UUIDEntity {
protected String mimeType; protected String mimeType;
protected JsonNode metadata; protected ObjectNode metadata;
protected Long size; protected Long size;
@@ -82,6 +83,14 @@ public class Attachment extends UUIDEntity {
@Transient @Transient
protected MultipartFile file; protected MultipartFile file;
public String buildMongoName() {
StringBuilder result = new StringBuilder(bizType.name());
if (TimiJava.isNotEmpty(attachType)) {
result.append('_').append(attachType.toUpperCase());
}
return result.append('_').append(name).toString();
}
public InputStream openInputStream() { public InputStream openInputStream() {
AttachmentService service = TimiServerAPI.applicationContext.getBean(AttachmentService.class); AttachmentService service = TimiServerAPI.applicationContext.getBean(AttachmentService.class);
return service.getInputStreamByMongoId(mongoId); return service.getInputStreamByMongoId(mongoId);
@@ -4,9 +4,9 @@ import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.mapper.BaseMapper; import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.mapper.RawMapper; import com.imyeyu.spring.mapper.RawMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import java.util.Collection;
import java.util.List; import java.util.List;
/** /**
@@ -32,7 +32,7 @@ public interface AttachmentMapper extends BaseMapper<Attachment, String>, RawMap
List<Attachment> selectByBizId(Attachment.BizType bizType, String bizId, List<String> attachTypes, Page<Attachment> page); List<Attachment> selectByBizId(Attachment.BizType bizType, String bizId, List<String> attachTypes, Page<Attachment> page);
List<Attachment> selectByBizIdList(@Param("bizType") Attachment.BizType bizType, @Param("bizIdList") List<String> bizIdList, @Param("attachTypes") List<String> attachTypes); List<Attachment> selectByBizIdList(Attachment.BizType bizType, Collection<String> bizIdList, List<String> attachTypes);
long countByBizId(Attachment.BizType bizType, String bizId, List<String> attachTypes); long countByBizId(Attachment.BizType bizType, String bizId, List<String> attachTypes);
@@ -1,13 +1,12 @@
package com.imyeyu.api.modules.common.service; package com.imyeyu.api.modules.common.service;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.vo.attach.BizDeleteReq;
import com.imyeyu.api.modules.common.vo.attach.BizUpdateReq;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult; import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService; import com.imyeyu.spring.service.BaseService;
import java.io.InputStream; import java.io.InputStream;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -19,6 +18,13 @@ import java.util.Map;
*/ */
public interface AttachmentService extends BaseService<Attachment, String> { public interface AttachmentService extends BaseService<Attachment, String> {
///
/// 克隆附件,复制业务属性和文件内容并生成新的附件记录
///
/// @param id 源附件 ID
/// @return 克隆后的附件
Attachment clone(String id);
/** /**
* 按需获取或创建缩略图附件。 * 按需获取或创建缩略图附件。
* <p>当附件为图片或视频时,若指定尺寸的缩略图已存在则直接返回缓存, * <p>当附件为图片或视频时,若指定尺寸的缩略图已存在则直接返回缓存,
@@ -52,14 +58,14 @@ public interface AttachmentService extends BaseService<Attachment, String> {
List<Attachment> listByBizId(Attachment.BizType bizType, String bizId, String... attachTypes); List<Attachment> listByBizId(Attachment.BizType bizType, String bizId, String... attachTypes);
/** /**
* 根据多个业务 ID 批量获取附件 * 根据多个业务 ID 批量获取附件
* *
* @param bizType 业务类型 * @param bizType 业务类型
* @param bizIdList 业务 ID 列表 * @param bizIdList 业务 ID 列表
* @param attachTypes 附件类型,可为 null * @param attachTypes 附件类型,可为 null
* @return 按业务 ID 分组的附件列表 * @return 按业务 ID 分组的附件列表
*/ */
Map<String, List<Attachment>> mapByBizIdList(Attachment.BizType bizType, List<String> bizIdList, String... attachTypes); Map<String, List<Attachment>> mapByBizIdList(Attachment.BizType bizType, Collection<String> bizIdList, String... attachTypes);
/** /**
* 根据业务获取所有附件 * 根据业务获取所有附件
@@ -84,10 +90,8 @@ public interface AttachmentService extends BaseService<Attachment, String> {
* <li>请求有、数据库有、无 tempFileId → 仅更新元数据</li> * <li>请求有、数据库有、无 tempFileId → 仅更新元数据</li>
* <li>请求有、数据库有、有 tempFileId → 更新文件与元数据</li> * <li>请求有、数据库有、有 tempFileId → 更新文件与元数据</li>
* </ul> * </ul>
*
* @param req 差分更新请求
*/ */
void updateByBiz(BizUpdateReq req); void updateByBizId(Attachment.BizType bizType, String bizId, List<Attachment> list);
void deleteByBiz(BizDeleteReq req); void deleteByBizId(Attachment.BizType bizType, String bizId);
} }
@@ -8,8 +8,6 @@ import com.imyeyu.api.modules.common.bean.attachment.Metadata;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.mapper.AttachmentMapper; import com.imyeyu.api.modules.common.mapper.AttachmentMapper;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.vo.attach.BizDeleteReq;
import com.imyeyu.api.modules.common.vo.attach.BizUpdateReq;
import com.imyeyu.api.util.JavaCV; import com.imyeyu.api.util.JavaCV;
import com.imyeyu.io.IO; import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
@@ -43,7 +41,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@@ -71,6 +69,88 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
return mapper; return mapper;
} }
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(Attachment attachment) {
TimiException.required(attachment.getBizType(), "not found String");
TimiException.required(attachment.getName(), "not found attachment.name");
String mongoId = null;
try {
if (attachment.getFile() != null) {
attachment.setInputStream(attachment.getFile().getInputStream());
}
InputStream is = attachment.getInputStream();
TimiException.required(is, "not found attachment.inputStream");
mongoId = gridFsTemplate.store(attachment.getInputStream(), attachment.buildMongoName()).toString();
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(mongoId)));
attachment.setMongoId(mongoId);
attachment.setSize(gridFSFile.getLength());
attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setUploaderIp(TimiSpring.getRequestIP());
attachment.setIsDestroyed(false);
if (attachment.getMimeType().startsWith("image")) {
BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()));
ObjectNode metadata = TimiJava.defaultIfNull(attachment.getMetadata(), jackson.createObjectNode());
metadata.put("width", image.getWidth());
metadata.put("height", image.getHeight());
attachment.setMetadata(metadata);
}
mapper.insert(attachment);
} catch (Exception e) {
if (mongoId != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(mongoId)));
}
log.error("create error", e);
throw new TimiException(TimiCode.ARG_BAD, "TODO read attachment input stream error");
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(Attachment attachment) {
String newMongoId = null;
try {
if (attachment.getFile() != null) {
attachment.setInputStream(attachment.getFile().getInputStream());
}
InputStream stream = attachment.getInputStream();
if (stream == null) {
// 无新文件,仅更新元数据字段
super.update(attachment);
return;
}
// 有新文件时,先查旧记录获取旧 mongoId 和兜底字段
Attachment old = mapper.selectRaw(attachment.getId());
// 存储新文件
newMongoId = gridFsTemplate.store(stream, attachment.buildMongoName()).toString();
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(newMongoId)));
attachment.setMongoId(newMongoId);
attachment.setSize(gridFSFile.getLength());
attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
if (attachment.getMimeType().startsWith("image")) {
BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()));
ObjectNode metadata = TimiJava.defaultIfNull(attachment.getMetadata(), jackson.createObjectNode());
metadata.put("width", image.getWidth());
metadata.put("height", image.getHeight());
attachment.setMetadata(metadata);
}
// 更新数据库后删除旧 GridFS 文件
super.update(attachment);
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(old.getMongoId())));
} catch (Exception e) {
// 新文件已上传但后续操作失败,清理新文件防止孤儿数据
if (TimiJava.isNotEmpty(newMongoId)) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(newMongoId)));
}
log.error("update error", e);
throw new TimiException(TimiCode.ERROR, "TODO update file error");
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void delete(String id) { public void delete(String id) {
@@ -108,101 +188,30 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void create(Attachment attachment) { public Attachment clone(String id) {
TimiException.required(attachment.getBizType(), "not found String"); TimiException.required(id, "not found id");
TimiException.required(attachment.getName(), "not found attachment.name"); Attachment source = mapper.selectRaw(id);
String mongoId = null; TimiException.required(source, "not found attachment");
try { TimiException.required(source.getMongoId(), "not found mongoId");
if (attachment.getFile() != null) {
attachment.setInputStream(attachment.getFile().getInputStream());
}
InputStream is = attachment.getInputStream();
TimiException.required(is, "not found attachment.inputStream");
StringBuilder mongoName = new StringBuilder(attachment.getBizType().name()); Attachment target = new Attachment();
if (TimiJava.isNotEmpty(attachment.getAttachType())) { target.setBizType(source.getBizType());
mongoName.append("_").append(attachment.getAttachType().toUpperCase()).append("_"); target.setBizId(source.getBizId());
target.setAttachType(source.getAttachType());
target.setTitle(source.getTitle());
target.setName(source.getName());
target.setMetadata(source.getMetadata() == null ? null : source.getMetadata().deepCopy());
target.setDestroyAt(source.getDestroyAt());
try (InputStream inputStream = getInputStreamByMongoId(source.getMongoId())) {
target.setInputStream(inputStream);
create(target);
return target;
} catch (IOException e) {
if (target.getMongoId() != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(target.getMongoId())));
} }
mongoName.append(attachment.getName()); log.error("clone attachment error, id={}", id, e);
throw new TimiException(TimiCode.ERROR, "clone attachment error", e);
mongoId = gridFsTemplate.store(attachment.getInputStream(), mongoName.toString()).toString();
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(mongoId)));
attachment.setMongoId(mongoId);
attachment.setSize(gridFSFile.getLength());
attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setUploaderIp(TimiSpring.getRequestIP());
attachment.setIsDestroyed(false);
if (attachment.getMimeType().startsWith("image")) {
BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()));
attachment.setMetadata(TimiJava.defaultIfNull(attachment.getMetadata(), jackson.createObjectNode()));
if (attachment.getMetadata() instanceof ObjectNode obj) {
obj.put("width", image.getWidth());
obj.put("height", image.getHeight());
}
}
mapper.insert(attachment);
} catch (Exception e) {
if (mongoId != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(mongoId)));
}
log.error("create error", e);
throw new TimiException(TimiCode.ARG_BAD, "TODO read attachment input stream error");
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(Attachment attachment) {
String newMongoId = null;
try {
if (attachment.getFile() != null) {
attachment.setInputStream(attachment.getFile().getInputStream());
}
InputStream stream = attachment.getInputStream();
if (stream == null) {
// 无新文件,仅更新元数据字段
super.update(attachment);
return;
}
// 有新文件时,先查旧记录获取旧 mongoId 和兜底字段
Attachment old = mapper.selectRaw(attachment.getId());
// 构建存储名,优先取调用方设置的字段,否则沿用旧值
Attachment.BizType bizType = TimiJava.defaultIfNull(attachment.getBizType(), old.getBizType());
String attachType = TimiJava.defaultIfEmpty(attachment.getAttachType(), old.getAttachType());
String name = TimiJava.defaultIfEmpty(attachment.getName(), old.getName());
StringBuilder mongoName = new StringBuilder(bizType.name());
if (TimiJava.isNotEmpty(attachType)) {
mongoName.append("_").append(attachType.toUpperCase()).append("_");
}
mongoName.append(name);
// 存储新文件
newMongoId = gridFsTemplate.store(stream, mongoName.toString()).toString();
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(newMongoId)));
attachment.setMongoId(newMongoId);
attachment.setSize(gridFSFile.getLength());
attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
if (attachment.getMimeType().startsWith("image")) {
BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()));
attachment.setMetadata(TimiJava.defaultIfNull(attachment.getMetadata(), jackson.createObjectNode()));
if (attachment.getMetadata() instanceof ObjectNode obj) {
obj.put("width", image.getWidth());
obj.put("height", image.getHeight());
}
}
// 更新数据库后删除旧 GridFS 文件
super.update(attachment);
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(old.getMongoId())));
} catch (Exception e) {
// 新文件已上传但后续操作失败,清理新文件防止孤儿数据
if (newMongoId != null) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(newMongoId)));
}
log.error("update error", e);
throw new TimiException(TimiCode.ERROR, "TODO update file error");
} }
} }
@@ -216,9 +225,9 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
if (!isImage && !isVideo) { if (!isImage && !isVideo) {
return null; return null;
} }
// 命中缓存直接返回
Attachment cached = mapper.selectThumb(source.getBizType(), source.getId(), requestWidth, requestHeight); Attachment cached = mapper.selectThumb(source.getBizType(), source.getId(), requestWidth, requestHeight);
if (cached != null) { if (cached != null) {
// 命中缓存直接返回
return cached; return cached;
} }
try { try {
@@ -313,19 +322,8 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
} }
@Override @Override
public Map<String, List<Attachment>> mapByBizIdList(Attachment.BizType bizType, List<String> bizIdList, String... attachTypes) { public Map<String, List<Attachment>> mapByBizIdList(Attachment.BizType bizType, Collection<String> bizIdList, String... attachTypes) {
if (bizIdList == null || bizIdList.isEmpty()) { return mapper.selectByBizIdList(bizType, bizIdList, List.of(attachTypes)).stream().collect(Collectors.groupingBy(Attachment::getBizId));
return Map.of();
}
List<String> normalizedBizIdList = bizIdList.stream()
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
if (normalizedBizIdList.isEmpty()) {
return Map.of();
}
return mapper.selectByBizIdList(bizType, new ArrayList<>(normalizedBizIdList), List.of(attachTypes)).stream()
.collect(Collectors.groupingBy(Attachment::getBizId));
} }
@Override @Override
@@ -348,16 +346,12 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void updateByBiz(BizUpdateReq req) { public void updateByBizId(Attachment.BizType bizType, String bizId, List<Attachment> list) {
Attachment.BizType bizType = req.getBizType();
String bizId = req.getBizId();
List<Attachment> items = req.getItems();
// 数据库现有附件 // 数据库现有附件
List<Attachment> dbList = mapper.selectAllByBizId(bizType, bizId); List<Attachment> dbList = mapper.selectAllByBizId(bizType, bizId);
Set<String> dbIds = dbList.stream().map(Attachment::getId).collect(Collectors.toSet()); Set<String> dbIds = dbList.stream().map(Attachment::getId).collect(Collectors.toSet());
// 请求附件 ID // 请求附件 ID
Set<String> reqIds = items.stream().map(Attachment::getId).filter(Objects::nonNull).collect(Collectors.toSet()); Set<String> reqIds = list.stream().map(Attachment::getId).filter(Objects::nonNull).collect(Collectors.toSet());
// 数据库有、请求无:删除 // 数据库有、请求无:删除
for (Attachment attach : dbList) { for (Attachment attach : dbList) {
if (!reqIds.contains(attach.getId())) { if (!reqIds.contains(attach.getId())) {
@@ -365,7 +359,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
} }
} }
for (Attachment item : items) { for (Attachment item : list) {
boolean isNew = item.getId() == null || !dbIds.contains(item.getId()); boolean isNew = item.getId() == null || !dbIds.contains(item.getId());
String tempFileId = item.getTempFileId(); String tempFileId = item.getTempFileId();
@@ -432,8 +426,8 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void deleteByBiz(BizDeleteReq req) { public void deleteByBizId(Attachment.BizType bizType, String bizId) {
List<Attachment> attachmentList = mapper.selectAllByBizId(req.getBizType(), req.getBizId()); List<Attachment> attachmentList = mapper.selectAllByBizId(bizType, bizId);
for (Attachment attachment : attachmentList) { for (Attachment attachment : attachmentList) {
delete(attachment.getId()); delete(attachment.getId());
} }
@@ -1,20 +0,0 @@
package com.imyeyu.api.modules.common.vo.attach;
import com.imyeyu.api.modules.common.entity.Attachment;
import lombok.Data;
/**
* 业务附件差分更新请求
*
* @author 夜雨
* @since 2026-03-11 00:00
*/
@Data
public class BizDeleteReq {
/** 业务类型 */
private Attachment.BizType bizType;
/** 业务 ID */
private String bizId;
}
@@ -1,26 +0,0 @@
package com.imyeyu.api.modules.common.vo.attach;
import com.imyeyu.api.modules.common.entity.Attachment;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 业务附件差分更新请求
*
* @author 夜雨
* @since 2026-03-11 00:00
*/
@Data
public class BizUpdateReq {
/** 业务类型 */
private Attachment.BizType bizType;
/** 业务 ID */
private String bizId;
/** 附件项列表 */
private List<Attachment> items = new ArrayList<>();
}
@@ -2,6 +2,7 @@ package com.imyeyu.api.modules.gao.bean;
import com.imyeyu.api.bean.ModuleCode; import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.bean.BuiltinPermissionCode; import com.imyeyu.api.modules.user.bean.BuiltinPermissionCode;
import lombok.Getter;
/// ///
/// GAO 模块权限枚举 /// GAO 模块权限枚举
@@ -20,23 +21,23 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
CUSTOMER_DELETE("CUSTOMER:DELETE", "客户删除"), CUSTOMER_DELETE("CUSTOMER:DELETE", "客户删除"),
REGISTRATION_EVENT_CREATE("REGISTRATION_EVENT:CREATE", "登记事件创建"), EVENT_CREATE("EVENT:CREATE", "登记事件创建"),
REGISTRATION_EVENT_READ("REGISTRATION_EVENT:READ", "登记事件读取"), EVENT_READ("EVENT:READ", "登记事件读取"),
REGISTRATION_EVENT_UPDATE("REGISTRATION_EVENT:UPDATE", "登记事件修改"), EVENT_UPDATE("EVENT:UPDATE", "登记事件修改"),
REGISTRATION_EVENT_DELETE("REGISTRATION_EVENT:DELETE", "登记事件删除"), EVENT_DELETE("EVENT:DELETE", "登记事件删除"),
REGISTRATION_EVENT_RECORD_CREATE("REGISTRATION_EVENT_RECORD:CREATE", "登记事件记录创建"), EVENT_RECORD_CREATE("EVENT_RECORD:CREATE", "登记事件记录创建"),
REGISTRATION_EVENT_RECORD_READ("REGISTRATION_EVENT_RECORD:READ", "登记事件记录读取"), EVENT_RECORD_READ("EVENT_RECORD:READ", "登记事件记录读取"),
REGISTRATION_EVENT_RECORD_EXPORT("REGISTRATION_EVENT_RECORD:EXPORT", "登记事件记录导出", true), EVENT_RECORD_EXPORT("EVENT_RECORD:EXPORT", "登记事件记录导出", true),
REGISTRATION_EVENT_RECORD_UPDATE("REGISTRATION_EVENT_RECORD:UPDATE", "登记事件记录修改"), EVENT_RECORD_UPDATE("EVENT_RECORD:UPDATE", "登记事件记录修改"),
REGISTRATION_EVENT_RECORD_DELETE("REGISTRATION_EVENT_RECORD:DELETE", "登记事件记录删除"), EVENT_RECORD_DELETE("EVENT_RECORD:DELETE", "登记事件记录删除"),
STAT_READ("STAT:READ", "统计读取"), STAT_READ("STAT:READ", "统计读取"),
@@ -52,6 +53,9 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
final String value; final String value;
final String defaultName; final String defaultName;
/// `true` 为初始化时授权给店长角色
@Getter
final boolean grantToStoreManager; final boolean grantToStoreManager;
GaoPermissionCode(String value, String defaultName) { GaoPermissionCode(String value, String defaultName) {
@@ -88,11 +92,4 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
public boolean isGrantToAdmin() { public boolean isGrantToAdmin() {
return false; return false;
} }
/// true 为初始化时授权给店长角色
///
/// @return 是否授权给店长角色
public boolean isGrantToStoreManager() {
return grantToStoreManager;
}
} }
@@ -1,29 +1,29 @@
package com.imyeyu.api.modules.gao.controller; package com.imyeyu.api.modules.gao.controller;
import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.bean.RoleMatchMode; import com.imyeyu.api.bean.RoleMatchMode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.annotation.RequireGaoRole; import com.imyeyu.api.modules.gao.annotation.RequireGaoRole;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventService;
import com.imyeyu.api.modules.gao.service.GaoCustomerService; import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventRecordService; import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView; import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerInviteUpdateReq; import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStateReq;
import com.imyeyu.api.modules.gao.vo.GaoCustomerSearchReq; import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStatReq; import com.imyeyu.java.TimiJava;
import com.imyeyu.api.modules.gao.vo.GaoQuickRegistrationEventRecordReq; import com.imyeyu.network.Network;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit; import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult; import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView; import com.imyeyu.spring.util.ResponseView;
import com.imyeyu.utils.Time;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@@ -33,28 +33,22 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.IOException; import java.io.IOException;
import java.net.URLEncoder;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
///
/// GAO 客户接口 /// GAO 客户接口
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-07-27 /// @since 2026-07-27 14:12
@RestController @RestController
@RequireGaoRole(value = {GaoRoleCode.STORE_MANAGER, GaoRoleCode.EMPLOYEE}, mode = RoleMatchMode.ANY)
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/gao/customer") @RequestMapping("/gao/customer")
@RequireGaoRole(value = {GaoRoleCode.STORE_MANAGER, GaoRoleCode.EMPLOYEE}, mode = RoleMatchMode.ANY)
public class GaoCustomerController { public class GaoCustomerController {
private static final String SIGN_IN_REGISTRATION_EVENT_NAME = "签到"; private final UserService userService;
private final AttachmentService attachmentService;
private final GaoCustomerService service; private final GaoCustomerService service;
private final GaoRegistrationEventRecordService registrationEventRecordService;
private final GaoRegistrationEventService registrationEventService;
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@@ -63,74 +57,32 @@ public class GaoCustomerController {
@JsonView(ResponseView.Public.class) @JsonView(ResponseView.Public.class)
public PageResult<GaoCustomer> list(@RequestBody Page<GaoCustomer> page) { public PageResult<GaoCustomer> list(@RequestBody Page<GaoCustomer> page) {
PageResult<GaoCustomer> result = service.page(page); PageResult<GaoCustomer> result = service.page(page);
fillLastSignInAt(result.getList());
List<String> idList = result.getList().stream().map(GaoCustomer::getId).distinct().toList();
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, idList);
for (GaoCustomer customer : result.getList()) {
customer.setAttachmentList(attachmentMap.get(customer.getId()));
}
return result; return result;
} }
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/search")
@JsonView(ResponseView.Public.class)
public List<GaoCustomer> search(@RequestBody GaoCustomerSearchReq req) {
return service.search(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/search/page")
@JsonView(ResponseView.Public.class)
public PageResult<GaoCustomer> searchPage(@RequestBody Page<GaoCustomerSearchReq> page) {
return service.searchPage(page);
}
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_EXPORT)
@PostMapping("/export")
public void export(@RequestBody GaoCustomerSearchReq req, HttpServletResponse resp) throws IOException {
String fileName = URLEncoder.encode("客户列表.xlsx", "UTF-8").replace("+", "%20");
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", "attachment; filename=\"gao-customer.xlsx\"; filename*=UTF-8''" + fileName);
resp.getOutputStream().write(service.exportSearchExcel(req));
}
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/detail") @PostMapping("/detail")
@JsonView(ResponseView.Public.class) @JsonView(ResponseView.Public.class)
public GaoCustomer detail(@RequestParam String id) { public GaoCustomer detail(@RequestParam String id) {
return service.get(id); GaoCustomer customer = service.get(id);
} if (TimiJava.isNotEmpty(customer.getIntroducerCustomerId())) {
GaoCustomer introducerCustomer = service.get(customer.getIntroducerCustomerId());
@AOPLog introducerCustomer.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_CUSTOMER, introducerCustomer.getId()));
@RequestRateLimit customer.setIntroducerCustomer(introducerCustomer);
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ) }
@PostMapping("/detail/code") if (TimiJava.isNotEmpty(customer.getCreatorUserId())) {
@JsonView(ResponseView.Public.class) customer.setCreatorUser(userService.get(customer.getCreatorUserId()));
public GaoCustomer detailByCode(@RequestParam String code) { }
return service.getByCode(code); customer.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_CUSTOMER, customer.getId()));
} return customer;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/detail/code/nullable")
@JsonView(ResponseView.Public.class)
public GaoCustomer nullableDetailByCode(@RequestParam String code) {
return service.getNullableByCode(code);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/invited/list")
@JsonView(ResponseView.Public.class)
public List<GaoCustomer> invitedList(@RequestParam String introducerCustomerId) {
return service.listInvited(introducerCustomerId);
} }
@AOPLog @AOPLog
@@ -138,17 +90,9 @@ public class GaoCustomerController {
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_CREATE) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_CREATE)
@PostMapping("/create") @PostMapping("/create")
@JsonView(ResponseView.Public.class) @JsonView(ResponseView.Public.class)
public GaoCustomer create(@RequestBody GaoCustomer customer) { public String create(@RequestBody GaoCustomer customer) {
service.create(customer); service.create(customer);
return customer; return customer.getId();
}
@AOPLog
@RequestRateLimit
@PostMapping("/quick/register")
@JsonView(ResponseView.Public.class)
public GaoRegistrationEventRecord quickRegister(@RequestBody GaoQuickRegistrationEventRecordReq req) {
return registrationEventRecordService.quickRegister(req);
} }
@AOPLog @AOPLog
@@ -169,27 +113,66 @@ public class GaoCustomerController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_UPDATE) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/invite/create") @PostMapping("/find/code")
public void createInvite(@RequestBody GaoCustomerInviteUpdateReq req) { @JsonView(ResponseView.Public.class)
service.saveInviteRelation(req); public GaoCustomer findByCode(@RequestParam String code) {
GaoCustomer customer = service.getByCode(code);
if (customer == null) {
return null;
}
customer.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_CUSTOMER, customer.getId()));
return customer;
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/invite/detail") @PostMapping("/find/name")
@JsonView(ResponseView.Public.class) @JsonView(ResponseView.Public.class)
public GaoCustomer inviteDetail(@RequestParam String customerId) { public GaoCustomer findByName(@RequestParam String name) {
return service.get(customerId); GaoCustomer customer = service.getByName(name);
if (customer == null) {
return null;
}
customer.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_CUSTOMER, customer.getId()));
return customer;
}
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_EXPORT)
@PostMapping("/export")
public void export(@RequestBody Page<GaoCustomer> page) throws IOException {
HttpServletResponse resp = TimiSpring.getResponse();
String contentDisposition = Network.getFileDownloadHeader("客户列表-%s.xlsx".formatted(Time.serialize.format(Time.now())));
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", contentDisposition);
resp.getOutputStream().write(service.export(page));
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/invited/list")
@JsonView(ResponseView.Public.class)
public List<GaoCustomer> listInvited(@RequestParam String introducerCustomerId) {
List<GaoCustomer> result = service.listInvited(introducerCustomerId);
List<String> idList = result.stream().map(GaoCustomer::getId).distinct().toList();
Map<String, List<Attachment>> attachMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, idList);
for (GaoCustomer customer : result) {
customer.setAttachmentList(attachMap.get(customer.getId()));
}
return result;
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_UPDATE) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_UPDATE)
@PostMapping("/invite/update") @PostMapping("/invite/save")
public void updateInvite(@RequestBody GaoCustomerInviteUpdateReq req) { public void saveInvite(@RequestParam String introducerCustomerId, @RequestParam String customerId) {
service.saveInviteRelation(req); service.saveInviteRelation(introducerCustomerId, customerId);
} }
@AOPLog @AOPLog
@@ -200,46 +183,21 @@ public class GaoCustomerController {
service.deleteInviteRelation(customerId); service.deleteInviteRelation(customerId);
} }
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/stat/daily")
/// 按天统计客户新增数和累计总数 /// 按天统计客户新增数和累计总数
public List<GaoCustomerDailyStatView> dailyStat(@RequestBody GaoCustomerTrendStatReq req) {
return service.statDailyTrend(req);
}
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@PostMapping("/stat/gender") @PostMapping("/state/daily")
/// 统计客户性别分布 public List<GaoCustomerDailyStateView> dailyStat(@RequestBody GaoCustomerTrendStateReq req) {
public List<GaoCustomerGenderStatView> genderStat() { return service.stateDailyTrend(req);
return service.statGender();
} }
private void fillLastSignInAt(List<GaoCustomer> customerList) { /// 统计客户性别分布
if (customerList == null || customerList.isEmpty()) { @AOPLog
return; @RequestRateLimit
} @RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
String signInRegistrationEventId = null; @PostMapping("/state/gender")
for (GaoRegistrationEvent registrationEvent : registrationEventService.listEnabled()) { public List<GaoCustomerGenderStatView> genderStat() {
if (SIGN_IN_REGISTRATION_EVENT_NAME.equals(registrationEvent.getName())) { return service.stateGender();
signInRegistrationEventId = registrationEvent.getId();
break;
}
}
if (signInRegistrationEventId == null) {
return;
}
List<String> customerIdList = customerList.stream().map(GaoCustomer::getId).toList();
Map<String, GaoRegistrationEventRecord> recordMap = registrationEventRecordService.listLatestByCustomerIdListAndRegistrationEventId(customerIdList, signInRegistrationEventId).stream()
.collect(Collectors.toMap(GaoRegistrationEventRecord::getCustomerId, Function.identity(), (left, right) -> left));
for (GaoCustomer customer : customerList) {
GaoRegistrationEventRecord record = recordMap.get(customer.getId());
if (record != null) {
customer.setLastSignInAt(record.getRegisteredAt());
}
}
} }
} }
@@ -1,12 +1,12 @@
package com.imyeyu.api.modules.gao.controller; package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.bean.RoleMatchMode;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.annotation.RequireGaoRole; import com.imyeyu.api.modules.gao.annotation.RequireGaoRole;
import com.imyeyu.api.bean.RoleMatchMode;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode; import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent; import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventService; import com.imyeyu.api.modules.gao.service.GaoEventService;
import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit; import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
@@ -19,62 +19,67 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
import java.util.Map;
///
/// GAO 登记事件接口 /// GAO 登记事件接口
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-07-27 /// @since 2026-07-27 14:13
@RestController @RestController
@RequiredArgsConstructor
@RequestMapping("/gao/registration-event")
@RequireGaoRole(value = {GaoRoleCode.STORE_MANAGER, GaoRoleCode.EMPLOYEE}, mode = RoleMatchMode.ANY) @RequireGaoRole(value = {GaoRoleCode.STORE_MANAGER, GaoRoleCode.EMPLOYEE}, mode = RoleMatchMode.ANY)
public class GaoRegistrationEventController { @RequiredArgsConstructor
@RequestMapping("/gao/event")
public class GaoEventController {
private final GaoRegistrationEventService service; private final GaoEventService service;
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_READ) @RequireGaoPermission(GaoPermissionCode.EVENT_READ)
@PostMapping("/list") @PostMapping("/list")
public PageResult<GaoRegistrationEvent> list(@RequestBody Page<GaoRegistrationEvent> page) { public PageResult<GaoEvent> list(@RequestBody Page<GaoEvent> page) {
return service.pageWithRegistrationEventLimit(page); PageResult<GaoEvent> result = service.page(page);
Map<String, List<String>> roleMap = service.mapRoleCodeListByEventIdList(result.getList().stream().map(GaoEvent::getId).toList());
for (GaoEvent event : result.getList()) {
event.setRoleCodeList(roleMap.get(event.getId()));
}
return result;
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@PostMapping("/enabled/list") @PostMapping("/list/valid")
public List<GaoRegistrationEvent> enabledList() { public List<GaoEvent> listValid() {
return service.listEnabled(); return service.listValid();
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_READ) @RequireGaoPermission(GaoPermissionCode.EVENT_READ)
@PostMapping("/detail") @PostMapping("/detail")
public GaoRegistrationEvent detail(@RequestParam String id) { public GaoEvent detail(@RequestParam String id) {
return service.get(id); return service.get(id);
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_CREATE) @RequireGaoPermission(GaoPermissionCode.EVENT_CREATE)
@PostMapping("/create") @PostMapping("/create")
public void create(@RequestBody GaoRegistrationEvent registrationEvent) { public void create(@RequestBody GaoEvent registrationEvent) {
service.create(registrationEvent); service.create(registrationEvent);
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_UPDATE) @RequireGaoPermission(GaoPermissionCode.EVENT_UPDATE)
@PostMapping("/update") @PostMapping("/update")
public void update(@RequestBody GaoRegistrationEvent registrationEvent) { public void update(@RequestBody GaoEvent registrationEvent) {
service.update(registrationEvent); service.update(registrationEvent);
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_UPDATE) @RequireGaoPermission(GaoPermissionCode.EVENT_UPDATE)
@PostMapping("/sort") @PostMapping("/sort")
public void sort(@RequestBody List<String> idList) { public void sort(@RequestBody List<String> idList) {
service.sort(idList); service.sort(idList);
@@ -82,7 +87,7 @@ public class GaoRegistrationEventController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_DELETE) @RequireGaoPermission(GaoPermissionCode.EVENT_DELETE)
@PostMapping("/delete") @PostMapping("/delete")
public void delete(@RequestParam String id) { public void delete(@RequestParam String id) {
service.delete(id); service.delete(id);
@@ -0,0 +1,152 @@
package com.imyeyu.api.modules.gao.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.bean.RoleMatchMode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.annotation.RequireGaoRole;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoEventRecordService;
import com.imyeyu.api.modules.gao.service.GaoEventService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.network.Network;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView;
import com.imyeyu.utils.Time;
import jakarta.servlet.http.HttpServletResponse;
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.io.IOException;
import java.util.List;
import java.util.Map;
/// GAO 登记事件记录接口
///
/// @author 夜雨
/// @since 2026-07-27 14:11
@RestController
@RequireGaoRole(value = {GaoRoleCode.STORE_MANAGER, GaoRoleCode.EMPLOYEE}, mode = RoleMatchMode.ANY)
@RequiredArgsConstructor
@RequestMapping("/gao/event/record")
public class GaoEventRecordController {
private final UserService userService;
private final GaoEventService eventService;
private final AttachmentService attachmentService;
private final GaoCustomerService customerService;
private final GaoEventRecordService service;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_READ)
@PostMapping("/list")
@JsonView(ResponseView.Public.class)
public PageResult<GaoEventRecord> list(@RequestBody GaoEventRecordPage page) {
PageResult<GaoEventRecord> result = service.pageByRange(page);
{
List<String> customerIdList = result.getList().stream().map(GaoEventRecord::getCustomerId).toList();
Map<String, GaoEvent> eventMap = eventService.mapByIdList(result.getList().stream().map(GaoEventRecord::getEventId).toList());
Map<String, GaoCustomer> customerMap = customerService.mapByIdList(customerIdList);
Map<String, List<Attachment>> attachMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList);
for (GaoEventRecord record : result.getList()) {
record.setEvent(eventMap.get(record.getEventId()));
record.setCustomer(customerMap.get(record.getCustomerId()));
record.getCustomer().setAttachmentList(attachMap.get(record.getCustomerId()));
}
}
return result;
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_READ)
@PostMapping("/detail")
@JsonView(ResponseView.Public.class)
public GaoEventRecord detail(@RequestParam String id) {
GaoEventRecord record = service.get(id);
record.setCustomer(customerService.get(record.getCustomerId()));
record.getCustomer().setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_CUSTOMER, record.getCustomerId()));
record.setEvent(eventService.get(record.getEventId()));
record.setOperator(userService.get(record.getOperatorUserId()));
record.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_EVENT_RECORD, record.getId()));
return record;
}
@AOPLog
@RequestRateLimit
@PostMapping("/create")
@JsonView(ResponseView.Public.class)
public void create(@RequestBody GaoEventRecord record) {
service.create(record);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_UPDATE)
@PostMapping("/update")
public void update(@RequestBody GaoEventRecord record) {
service.update(record);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_DELETE)
@PostMapping("/delete")
public void delete(@RequestParam String id) {
service.delete(id);
}
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_EXPORT)
@PostMapping("/export")
public void export(@RequestBody GaoEventRecordPage page) throws IOException {
HttpServletResponse resp = TimiSpring.getResponse();
String contentDisposition = Network.getFileDownloadHeader("登记事件记录-%s.xlsx".formatted(Time.serialize.format(Time.now())));
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", contentDisposition);
resp.getOutputStream().write(service.export(page));
}
/// 按时间范围查询客户登记排行榜
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/rank")
public PageResult<GaoCustomerEventRankView> eventRank(@RequestBody GaoEventRecordRankPage page) {
PageResult<GaoCustomerEventRankView> result = service.pageRankByRange(page);
List<String> customerIdList = result.getList().stream().map(GaoCustomerEventRankView::getCustomerId).distinct().toList();
if (customerIdList.isEmpty()) {
return result;
}
Map<String, GaoCustomer> customerMap = customerService.mapByIdList(customerIdList);
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList);
for (GaoCustomerEventRankView view : result.getList()) {
GaoCustomer customer = customerMap.get(view.getCustomerId());
if (customer != null) {
customer.setAttachmentList(attachmentMap.get(view.getCustomerId()));
}
view.setCustomer(customer);
}
return result;
}
}
@@ -1,201 +0,0 @@
package com.imyeyu.api.modules.gao.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.bean.RoleMatchMode;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.annotation.RequireGaoRole;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventRecordService;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventPeriodStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegistrationRankView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCreateReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordListItemView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordPeriodReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordRangeReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordStatReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordTrendStatReq;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
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.servlet.http.HttpServletResponse;
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.io.IOException;
import java.net.URLEncoder;
import java.util.List;
///
/// GAO 登记事件记录接口
///
/// @author Codex
/// @since 2026-07-27
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/registration-event-record")
@RequireGaoRole(value = {GaoRoleCode.STORE_MANAGER, GaoRoleCode.EMPLOYEE}, mode = RoleMatchMode.ANY)
public class GaoRegistrationEventRecordController {
private final GaoRegistrationEventRecordService service;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_READ)
@PostMapping("/list")
@JsonView(ResponseView.Public.class)
public PageResult<GaoRegistrationEventRecord> list(@RequestBody Page<GaoRegistrationEventRecord> page) {
return service.page(page);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_READ)
@PostMapping("/range/page")
public PageResult<GaoRegistrationEventRecordListItemView> rangePage(@RequestBody Page<GaoRegistrationEventRecordRangeReq> page) {
return service.pageByRange(page);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_READ)
@PostMapping("/detail")
@JsonView(ResponseView.Public.class)
public GaoRegistrationEventRecord detail(@RequestParam String id) {
return service.get(id);
}
@AOPLog
@RequestRateLimit
@PostMapping("/create")
@JsonView(ResponseView.Public.class)
public List<GaoRegistrationEventRecord> create(@RequestBody GaoRegistrationEventRecordCreateReq req) {
return service.createRecords(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_UPDATE)
@PostMapping("/update")
public void update(@RequestBody GaoRegistrationEventRecord record) {
service.update(record);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_DELETE)
@PostMapping("/delete")
public void delete(@RequestParam String id) {
service.delete(id);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_READ)
@PostMapping("/period/list")
@JsonView(ResponseView.Public.class)
public List<GaoRegistrationEventRecord> periodList(@RequestBody GaoRegistrationEventRecordPeriodReq req) {
return service.listByRegistrationEventAndPeriod(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_READ)
@PostMapping("/range/list")
@JsonView(ResponseView.Public.class)
public List<GaoRegistrationEventRecord> rangeList(@RequestBody GaoRegistrationEventRecordRangeReq req) {
return service.listByRange(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_READ)
@PostMapping("/range/calendar/list")
public List<GaoRegistrationEventRecordCalendarView> calendarRangeList(@RequestBody GaoRegistrationEventRecordRangeReq req) {
return service.listCalendarByRange(req);
}
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequireGaoPermission(GaoPermissionCode.REGISTRATION_EVENT_RECORD_EXPORT)
@PostMapping("/range/export")
public void rangeExport(@RequestBody GaoRegistrationEventRecordRangeReq req, HttpServletResponse resp) throws IOException {
String fileName = URLEncoder.encode("登记事件记录.xlsx", "UTF-8").replace("+", "%20");
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", "attachment; filename=\"gao-registration-event-record.xlsx\"; filename*=UTF-8''" + fileName);
resp.getOutputStream().write(service.exportRangeExcel(req));
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/period/stat")
public List<GaoRegistrationEventPeriodStatView> periodStat(@RequestBody GaoRegistrationEventRecordPeriodReq req) {
return service.statByRegistrationEventAndPeriodType(req.getRegistrationEventId(), req.getPeriodType());
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/customer/stat")
public List<GaoCustomerRegisterStatView> customerStat(@RequestParam String customerId) {
return service.statByCustomerId(customerId);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/customer/range/stat")
/// 按时间段统计单个客户各登记事件记录数
public List<GaoCustomerRegisterStatView> customerRangeStat(@RequestBody GaoRegistrationEventRecordStatReq req) {
return service.statByCustomerAndRange(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/all-customer/range/stat")
/// 按时间段统计全部客户各登记事件记录数
public List<GaoCustomerRegisterStatView> allCustomerRangeStat(@RequestBody GaoRegistrationEventRecordStatReq req) {
return service.statAllCustomerByRange(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/customer/registration-rank")
/// 按时间范围查询客户登记排行榜
public List<GaoCustomerRegistrationRankView> customerRegistrationRank(@RequestBody(required = false) GaoRegistrationEventRecordRangeReq req) {
return service.listCustomerRegistrationRank(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/customer/registration-event/daily/stat")
/// 按天统计单个客户单个登记事件记录趋势
public List<GaoRegistrationEventRecordDailyStatView> customerRegistrationEventDailyStat(@RequestBody GaoRegistrationEventRecordTrendStatReq req) {
return service.statDailyByCustomerAndRegistrationEvent(req);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.STAT_READ)
@PostMapping("/all-customer/registration-event/daily/stat")
/// 按天统计全部客户单个登记事件记录趋势
public List<GaoRegistrationEventRecordDailyStatView> allCustomerRegistrationEventDailyStat(@RequestBody GaoRegistrationEventRecordTrendStatReq req) {
return service.statDailyByRegistrationEvent(req);
}
}
@@ -14,15 +14,14 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
///
/// GAO 角色接口 /// GAO 角色接口
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-07-28 /// @since 2026-07-28 14:15
@RestController @RestController
@RequireGaoRole(GaoRoleCode.STORE_MANAGER)
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/gao/role") @RequestMapping("/gao/role")
@RequireGaoRole(GaoRoleCode.STORE_MANAGER)
public class GaoRoleController { public class GaoRoleController {
private final RoleService roleService; private final RoleService roleService;
@@ -24,11 +24,10 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
///
/// GAO 用户接口 /// GAO 用户接口
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-07-30 /// @since 2026-07-30 14:15
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/gao/user") @RequestMapping("/gao/user")
@@ -1,11 +1,11 @@
package com.imyeyu.api.modules.gao.entity; package com.imyeyu.api.modules.gao.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.bean.Gender; import com.imyeyu.api.modules.user.bean.Gender;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.java.TimiJava;
import com.imyeyu.spring.annotation.table.Transient; import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity; import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data; import lombok.Data;
@@ -55,7 +55,7 @@ public class GaoCustomer extends UUIDEntity {
private Gender gender; private Gender gender;
/// 年龄 /// 年龄
private Integer age; private Long age;
/// 出生日期,数据库只保存公历日期 /// 出生日期,数据库只保存公历日期
@JsonFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd")
@@ -64,15 +64,6 @@ public class GaoCustomer extends UUIDEntity {
/// 出生日期录入时使用的历法 /// 出生日期录入时使用的历法
private BirthdateCalendar birthdateCalendar; private BirthdateCalendar birthdateCalendar;
@JsonIgnore
@Transient
private boolean birthdateProvided;
public void setBirthdate(LocalDate birthdate) {
this.birthdate = birthdate;
this.birthdateProvided = true;
}
/// 电话 /// 电话
private String telephone; private String telephone;
@@ -91,24 +82,24 @@ public class GaoCustomer extends UUIDEntity {
/// 介绍人客户 ID /// 介绍人客户 ID
private String introducerCustomerId; private String introducerCustomerId;
private Long invitedCount;
/// 录入用户 ID /// 录入用户 ID
private String creatorUserId; private String creatorUserId;
@Transient
private Long lastSignInAt;
@Transient @Transient
private GaoCustomer introducerCustomer; private GaoCustomer introducerCustomer;
@Transient @Transient
private User creatorUser; private User creatorUser;
private Long invitedCount;
@Transient @Transient
private List<Attachment> attachmentList; private List<Attachment> attachmentList;
/// 临时照片附件 ID 列表
@Transient @Transient
private List<String> attachmentIdList; private GaoEventRecord eventRecord;
public boolean hasIntroducer() {
return TimiJava.isNotEmpty(introducerCustomerId);
}
} }
@@ -2,8 +2,10 @@ package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.spring.annotation.table.Transient; import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity; import com.imyeyu.spring.entity.UUIDEntity;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter;
import java.util.List; import java.util.List;
@@ -14,7 +16,7 @@ import java.util.List;
/// @since 2026-07-27 /// @since 2026-07-27
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class GaoRegistrationEvent extends UUIDEntity { public class GaoEvent extends UUIDEntity {
/// ///
/// 登记事件状态 /// 登记事件状态
@@ -36,33 +38,36 @@ public class GaoRegistrationEvent extends UUIDEntity {
DELETED DELETED
} }
///
/// 登记限制类型 /// 登记限制类型
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-08-01 /// @since 2026-08-01 14:37
@Getter
@AllArgsConstructor
public enum LimitType { public enum LimitType {
/// 不限制 /// 不限制
NONE, NONE(null),
/// 每天上午下午各 /// 每天上午下午各 N
DAILY_HALF_DAY, DAILY_HALF_DAY(1L),
/// 每个自然日 /// 每个自然日 N
NATURAL_DAY, NATURAL_DAY(1L),
/// 每隔 N 小时一次 /// 每隔 N 小时一次
INTERVAL_HOUR, INTERVAL_HOUR(1L),
/// 每个自然月 /// 每个自然月 N
NATURAL_MONTH, NATURAL_MONTH(1L),
/// 事件总登记次数上限 /// 事件总登记次数上限
TOTAL_LIMIT, TOTAL_LIMIT(1L),
/// 单个客户总登记次数上限 /// 单个客户总登记次数上限
CUSTOMER_TOTAL_LIMIT CUSTOMER_TOTAL_LIMIT(1L);
final Long min;
} }
/// 登记事件名称 /// 登记事件名称
@@ -16,7 +16,7 @@ import java.util.List;
/// @since 2026-07-27 /// @since 2026-07-27
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class GaoRegistrationEventRecord extends UUIDEntity { public class GaoEventRecord extends UUIDEntity {
/// ///
/// 登记事件记录附件类型 /// 登记事件记录附件类型
@@ -32,7 +32,7 @@ public class GaoRegistrationEventRecord extends UUIDEntity {
private String customerId; private String customerId;
/// 登记登记事件 ID /// 登记登记事件 ID
private String registrationEventId; private String eventId;
/// 操作管理员用户 ID /// 操作管理员用户 ID
private String operatorUserId; private String operatorUserId;
@@ -47,7 +47,7 @@ public class GaoRegistrationEventRecord extends UUIDEntity {
private GaoCustomer customer; private GaoCustomer customer;
@Transient @Transient
private GaoRegistrationEvent registrationEvent; private GaoEvent event;
@Transient @Transient
private User operator; private User operator;
@@ -55,7 +55,7 @@ public class GaoRegistrationEventRecord extends UUIDEntity {
@Transient @Transient
private List<Attachment> attachmentList; private List<Attachment> attachmentList;
/// 临时照片附件 ID 列表 /// 客户 ID 列表批量登记时使用
@Transient @Transient
private List<String> attachmentIdList; private List<String> customerIdList;
} }
@@ -11,10 +11,10 @@ import lombok.EqualsAndHashCode;
/// @since 2026-07-28 /// @since 2026-07-28
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class GaoRegistrationEventRoleRelation extends UUIDEntity { public class GaoEventRoleRelation extends UUIDEntity {
/// 登记事件 ID /// 登记事件 ID
private String registrationEventId; private String eventId;
/// 角色代码 /// 角色代码
private String roleCode; private String roleCode;
@@ -1,12 +1,11 @@
package com.imyeyu.api.modules.gao.mapper; package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStatView; import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView; import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.spring.mapper.BaseMapper; import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.Collection;
import java.util.List; import java.util.List;
/// ///
@@ -16,41 +15,23 @@ import java.util.List;
/// @since 2026-07-27 /// @since 2026-07-27
public interface GaoCustomerMapper extends BaseMapper<GaoCustomer, String> { public interface GaoCustomerMapper extends BaseMapper<GaoCustomer, String> {
@Select("SELECT * FROM `gao_customer` WHERE `code` = #{code} AND `deleted_at` IS NULL LIMIT 1") List<GaoCustomer> selectByIdList(Collection<String> idList);
GaoCustomer selectByCode(@Param("code") String code);
@Select("SELECT * FROM `gao_customer` WHERE `name` = #{name} AND `deleted_at` IS NULL LIMIT 1")
GaoCustomer selectByName(@Param("name") String name);
List<GaoCustomer> selectByIdList(@Param("idList") List<String> idList);
List<GaoCustomer> search(@Param("keyword") String keyword, @Param("introducerCustomerId") String introducerCustomerId);
Long countSearch(@Param("keyword") String keyword, @Param("introducerCustomerId") String introducerCustomerId);
List<GaoCustomer> searchPage(@Param("keyword") String keyword, @Param("introducerCustomerId") String introducerCustomerId, @Param("offset") Long offset, @Param("size") Long size);
List<GaoCustomer> selectInvitedList(@Param("introducerCustomerId") String introducerCustomerId);
Long countInvited(@Param("introducerCustomerId") String introducerCustomerId);
void updateInvitedCountDelta(@Param("customerId") String customerId, @Param("delta") Long delta);
/// 统计每日新增客户数 /// 统计每日新增客户数
/// ///
/// @param beginCreatedAt 开始创建时间 /// @param beginCreatedAt 开始创建时间
/// @param endCreatedAt 结束创建时间 /// @param endCreatedAt 结束创建时间
/// @return 每日新增客户数 /// @return 每日新增客户数
List<GaoCustomerDailyStatView> statDailyNewCustomer(@Param("beginCreatedAt") Long beginCreatedAt, @Param("endCreatedAt") Long endCreatedAt); List<GaoCustomerDailyStateView> stateDailyNewCustomer(Long beginCreatedAt, Long endCreatedAt);
/// 统计开始时间前客户总数 /// 统计开始时间前客户总数
/// ///
/// @param beginCreatedAt 开始创建时间 /// @param beginCreatedAt 开始创建时间
/// @return 客户总数 /// @return 客户总数
Long countCreatedBefore(@Param("beginCreatedAt") Long beginCreatedAt); Long countCreatedBefore(Long beginCreatedAt);
/// 统计客户性别分布 /// 统计客户性别分布
/// ///
/// @return 性别统计列表 /// @return 性别统计列表
List<GaoCustomerGenderStatView> statGender(); List<GaoCustomerGenderStatView> stateGender();
} }
@@ -0,0 +1,19 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.spring.mapper.BaseMapper;
import java.util.Collection;
import java.util.List;
///
/// 登记事件 Mapper
///
/// @author 夜雨
/// @since 2026-07-27 15:53
public interface GaoEventMapper extends BaseMapper<GaoEvent, String> {
List<GaoEvent> selectByIdList(Collection<String> idList);
List<GaoEvent> selectValidList(Long now);
}
@@ -0,0 +1,37 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.spring.mapper.BaseMapper;
import java.util.List;
/// 登记事件记录 Mapper
///
/// @author 夜雨
/// @since 2026-07-27 14:11
public interface GaoEventRecordMapper extends BaseMapper<GaoEventRecord, String> {
Long count(String customerId, String eventId, Long beginAt, Long endAt);
long countByRange(GaoEventRecordPage page);
/// 按任意时间范围查询登记事件记录
///
/// @return 登记事件记录列表
List<GaoEventRecord> selectByRange(GaoEventRecordPage page);
/// 统计客户登记排行榜总数
///
/// @param page 排行榜分页请求
/// @return 客户数
long countRankByRange(GaoEventRecordRankPage page);
/// 分页查询客户登记排行榜
///
/// @param page 排行榜分页请求
/// @return 客户登记排行榜
List<GaoCustomerEventRankView> selectRankByRange(GaoEventRecordRankPage page);
}
@@ -0,0 +1,16 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoEventRoleRelation;
import com.imyeyu.spring.mapper.BaseMapper;
import java.util.Collection;
import java.util.List;
/// 登记事件角色关联 Mapper
///
/// @author 夜雨
/// @since 2026-07-28 14:23
public interface GaoEventRoleRelationMapper extends BaseMapper<GaoEventRoleRelation, String> {
List<GaoEventRoleRelation> selectAllByEventIdList(Collection<String> idList);
}
@@ -1,19 +0,0 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
///
/// 登记事件 Mapper
///
/// @author Codex
/// @since 2026-07-27
public interface GaoRegistrationEventMapper extends BaseMapper<GaoRegistrationEvent, String> {
List<GaoRegistrationEvent> selectByIdList(@Param("idList") List<String> idList);
List<GaoRegistrationEvent> selectEnabledList(@Param("now") Long now);
}
@@ -1,157 +0,0 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventPeriodStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegistrationDayStatView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordListItemView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordPeriodReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordRangeReq;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
///
/// 登记事件记录 Mapper
///
/// @author Codex
/// @since 2026-07-27
public interface GaoRegistrationEventRecordMapper extends BaseMapper<GaoRegistrationEventRecord, String> {
/// 按登记事件查询客户最后登记事件记录
///
/// @param customerIdList 客户 ID 列表
/// @param registrationEventId 登记事件 ID
/// @return 最后登记事件记录列表
List<GaoRegistrationEventRecord> selectByRegistrationEventAndPeriod(@Param("registrationEventId") String registrationEventId, @Param("periodType") GaoRegistrationEventRecordPeriodReq.PeriodType periodType, @Param("periodValue") Integer periodValue);
/// 统计客户指定登记事件在时间范围内的登记数
///
/// @param customerId 客户 ID
/// @param registrationEventId 登记事件 ID
/// @param beginRegisteredAt 开始登记时间
/// @param endRegisteredAt 结束登记时间
/// @return 登记数
Long countByCustomerIdAndRegistrationEventIdRange(@Param("customerId") String customerId, @Param("registrationEventId") String registrationEventId, @Param("beginRegisteredAt") Long beginRegisteredAt, @Param("endRegisteredAt") Long endRegisteredAt);
/// 统计客户指定登记事件总登记数
///
/// @param customerId 客户 ID
/// @param registrationEventId 登记事件 ID
/// @return 登记数
Long countByCustomerIdAndRegistrationEventId(@Param("customerId") String customerId, @Param("registrationEventId") String registrationEventId);
/// 统计登记事件总登记数
///
/// @param registrationEventId 登记事件 ID
/// @return 登记数
Long countByRegistrationEventId(@Param("registrationEventId") String registrationEventId);
/// 按周期统计登记事件记录
///
/// @param registrationEventId 登记事件 ID
/// @param periodType 周期类型
/// @return 统计结果
List<GaoRegistrationEventPeriodStatView> statByRegistrationEventAndPeriodType(@Param("registrationEventId") String registrationEventId, @Param("periodType") GaoRegistrationEventRecordPeriodReq.PeriodType periodType);
/// 统计客户所有登记
///
/// @param customerId 客户 ID
/// @return 统计结果
List<GaoCustomerRegisterStatView> statByCustomerId(@Param("customerId") String customerId);
/// 按时间段统计单个客户登记
///
/// @param customerId 客户 ID
/// @param beginRegisteredAt 开始登记时间
/// @param endRegisteredAt 结束登记时间
/// @return 统计结果
List<GaoCustomerRegisterStatView> statByCustomerIdAndRange(@Param("customerId") String customerId, @Param("beginRegisteredAt") Long beginRegisteredAt, @Param("endRegisteredAt") Long endRegisteredAt);
/// 按时间段统计全部客户登记
///
/// @param beginRegisteredAt 开始登记时间
/// @param endRegisteredAt 结束登记时间
/// @return 统计结果
List<GaoCustomerRegisterStatView> statAllCustomerByRange(@Param("beginRegisteredAt") Long beginRegisteredAt, @Param("endRegisteredAt") Long endRegisteredAt);
/// 按时间范围统计全部客户每日登记
///
/// @param req 范围查询请求
/// @return 每个有登记客户的每日统计
List<GaoCustomerRegistrationDayStatView> statCustomerRegistrationDay(@Param("req") GaoRegistrationEventRecordRangeReq req);
/// 统计单个客户单个登记事件的每日登记事件记录数
///
/// @param customerId 客户 ID
/// @param registrationEventId 登记事件 ID
/// @param beginRegisteredAt 开始登记时间
/// @param endRegisteredAt 结束登记时间
/// @return 每日统计
List<GaoRegistrationEventRecordDailyStatView> statDailyCountByCustomerIdAndRegistrationEventIdRange(@Param("customerId") String customerId, @Param("registrationEventId") String registrationEventId, @Param("beginRegisteredAt") Long beginRegisteredAt, @Param("endRegisteredAt") Long endRegisteredAt);
/// 统计全部客户单个登记事件的每日登记事件记录数
///
/// @param registrationEventId 登记事件 ID
/// @param beginRegisteredAt 开始登记时间
/// @param endRegisteredAt 结束登记时间
/// @return 每日统计
List<GaoRegistrationEventRecordDailyStatView> statDailyCountByRegistrationEventIdRange(@Param("registrationEventId") String registrationEventId, @Param("beginRegisteredAt") Long beginRegisteredAt, @Param("endRegisteredAt") Long endRegisteredAt);
/// 统计时间段前单个客户单个登记事件累计登记事件记录数
///
/// @param customerId 客户 ID
/// @param registrationEventId 登记事件 ID
/// @param beginRegisteredAt 开始登记时间
/// @return 累计登记数
Long countBeforeByCustomerIdAndRegistrationEventId(@Param("customerId") String customerId, @Param("registrationEventId") String registrationEventId, @Param("beginRegisteredAt") Long beginRegisteredAt);
/// 统计时间段前全部客户单个登记事件累计登记事件记录数
///
/// @param registrationEventId 登记事件 ID
/// @param beginRegisteredAt 开始登记时间
/// @return 累计登记数
Long countBeforeByRegistrationEventId(@Param("registrationEventId") String registrationEventId, @Param("beginRegisteredAt") Long beginRegisteredAt);
/// 查询客户指定登记事件的最后登记事件记录
///
/// @param customerIdList 客户 ID 列表
/// @param registrationEventId 登记事件 ID
/// @return 最后登记事件记录列表
List<GaoRegistrationEventRecord> selectLatestByCustomerIdListAndRegistrationEventId(@Param("customerIdList") List<String> customerIdList, @Param("registrationEventId") String registrationEventId);
/// 查询客户全部登记事件的最后登记事件记录
///
/// @param customerId 客户 ID
/// @return 最后登记事件记录列表
List<GaoRegistrationEventRecord> selectLatestByCustomerId(@Param("customerId") String customerId);
/// 按任意时间范围查询登记事件记录
///
/// @param req 范围查询请求
/// @return 登记事件记录列表
List<GaoRegistrationEventRecord> selectByRange(@Param("req") GaoRegistrationEventRecordRangeReq req);
/// 按任意时间范围查询日历轻量记录
///
/// @param req 范围查询请求
/// @return 日历轻量记录列表
List<GaoRegistrationEventRecordCalendarView> selectCalendarByRange(@Param("req") GaoRegistrationEventRecordRangeReq req);
/// 按任意时间范围统计登记事件记录
///
/// @param req 范围查询请求
/// @return 登记事件记录数
Long countByRange(@Param("req") GaoRegistrationEventRecordRangeReq req);
/// 按任意时间范围分页查询登记事件记录
///
/// @param req 范围查询请求
/// @param offset 偏移量
/// @param size 每页条数
/// @return 登记事件记录列表
List<GaoRegistrationEventRecordListItemView> selectPageByRange(@Param("req") GaoRegistrationEventRecordRangeReq req, @Param("offset") Long offset, @Param("size") Long size);
}
@@ -1,36 +0,0 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRoleRelation;
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
///
/// @author Codex
/// @since 2026-07-28
public interface GaoRegistrationEventRoleRelationMapper extends BaseMapper<GaoRegistrationEventRoleRelation, String> {
@Select("SELECT `role_code` FROM `gao_registration_event_role_relation` WHERE `registration_event_id` = #{registrationEventId} AND `deleted_at` IS NULL ORDER BY `created_at` ASC")
List<String> selectRoleCodeListByRegistrationEventId(@Param("registrationEventId") String registrationEventId);
@Select({
"<script>",
"SELECT * FROM `gao_registration_event_role_relation`",
"WHERE `registration_event_id` IN",
"<foreach collection='registrationEventIdList' item='registrationEventId' open='(' separator=',' close=')'>",
"#{registrationEventId}",
"</foreach>",
"AND `deleted_at` IS NULL",
"ORDER BY `created_at` ASC",
"</script>"
})
List<GaoRegistrationEventRoleRelation> selectByRegistrationEventIdList(@Param("registrationEventIdList") List<String> registrationEventIdList);
@Update("UPDATE `gao_registration_event_role_relation` SET `deleted_at` = UNIX_TIMESTAMP() WHERE `registration_event_id` = #{registrationEventId} AND `deleted_at` IS NULL")
void deleteByRegistrationEventId(@Param("registrationEventId") String registrationEventId);
}
@@ -1,23 +1,22 @@
package com.imyeyu.api.modules.gao.service; package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStatView; import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView; import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerInviteUpdateReq; import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStateReq;
import com.imyeyu.api.modules.gao.vo.GaoCustomerSearchReq;
import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStatReq;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService; import com.imyeyu.spring.service.BaseService;
import java.io.IOException; import java.io.IOException;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
///
/// 客户服务 /// 客户服务
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-07-27 /// @since 2026-07-27 14:12
public interface GaoCustomerService extends BaseService<GaoCustomer, String> { public interface GaoCustomerService extends BaseService<GaoCustomer, String> {
/// 按编码查询客户 /// 按编码查询客户
@@ -26,35 +25,18 @@ public interface GaoCustomerService extends BaseService<GaoCustomer, String> {
/// @return 客户 /// @return 客户
GaoCustomer getByCode(String code); GaoCustomer getByCode(String code);
/// 按编码查询客户,不存在时返回 null GaoCustomer getByName(String name);
///
/// @param code 客户编码
/// @return 客户
GaoCustomer getNullableByCode(String code);
/// 按编码获取或快速创建客户 List<GaoCustomer> listByIdList(Collection<String> idList);
///
/// @param code 客户编码
/// @return 客户
GaoCustomer getOrQuickCreateByCode(String code);
/// 搜索客户 default Map<String, GaoCustomer> mapByIdList(Collection<String> idList) {
/// return listByIdList(idList).stream().collect(Collectors.toMap(GaoCustomer::getId, item -> item));
/// @param req 搜索请求 }
/// @return 客户列表
List<GaoCustomer> search(GaoCustomerSearchReq req);
/// 分页搜索客户
///
/// @param page 分页搜索请求
/// @return 客户分页结果
PageResult<GaoCustomer> searchPage(Page<GaoCustomerSearchReq> page);
/// 按搜索条件导出客户 Excel /// 按搜索条件导出客户 Excel
/// ///
/// @param req 搜索请求
/// @return xlsx 文件字节 /// @return xlsx 文件字节
byte[] exportSearchExcel(GaoCustomerSearchReq req) throws IOException; byte[] export(Page<GaoCustomer> page) throws IOException;
/// 查询邀请的客户 /// 查询邀请的客户
/// ///
@@ -64,8 +46,9 @@ public interface GaoCustomerService extends BaseService<GaoCustomer, String> {
/// 保存邀请关系 /// 保存邀请关系
/// ///
/// @param req 邀请关系请求 /// @param introducerCustomerId 邀请来源客户 ID
void saveInviteRelation(GaoCustomerInviteUpdateReq req); /// @param customerId 客户 ID
void saveInviteRelation(String introducerCustomerId, String customerId);
/// 删除邀请关系 /// 删除邀请关系
/// ///
@@ -76,10 +59,10 @@ public interface GaoCustomerService extends BaseService<GaoCustomer, String> {
/// ///
/// @param req 趋势统计请求 /// @param req 趋势统计请求
/// @return 每日趋势列表 /// @return 每日趋势列表
List<GaoCustomerDailyStatView> statDailyTrend(GaoCustomerTrendStatReq req); List<GaoCustomerDailyStateView> stateDailyTrend(GaoCustomerTrendStateReq req);
/// 统计客户性别分布 /// 统计客户性别分布
/// ///
/// @return 性别统计列表 /// @return 性别统计列表
List<GaoCustomerGenderStatView> statGender(); List<GaoCustomerGenderStatView> stateGender();
} }
@@ -0,0 +1,35 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
import java.io.IOException;
/// 登记事件记录服务
///
/// @author 夜雨
/// @since 2026-07-27 14:09
public interface GaoEventRecordService extends BaseService<GaoEventRecord, String> {
/// 按任意时间范围查询登记事件记录
///
/// @param req 范围查询请求
/// @return 登记事件记录列表
PageResult<GaoEventRecord> pageByRange(GaoEventRecordPage req);
/// 按时间范围查询客户登记排行榜
///
/// @param page 范围查询请求,不传时间为全部时间
/// @return 客户登记排行榜
PageResult<GaoCustomerEventRankView> pageRankByRange(GaoEventRecordRankPage page);
/// 按任意时间范围导出登记事件记录 Excel
///
/// @param page 范围查询请求
/// @return xlsx 文件字节
byte[] export(GaoEventRecordPage page) throws IOException;
}
@@ -0,0 +1,36 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.spring.service.BaseService;
import java.util.Collection;
import java.util.List;
import java.util.Map;
///
/// 登记事件服务
///
/// @author Codex
/// @since 2026-07-27
public interface GaoEventService extends BaseService<GaoEvent, String> {
Map<String, GaoEvent> mapByIdList(Collection<String> idList);
Map<String, List<String>> mapRoleCodeListByEventIdList(Collection<String> eventIdList);
/// 查询启用的登记事件
///
/// @return 登记事件列表
List<GaoEvent> listValid();
/// 查询登记事件要求的角色
///
/// @param eventId 登记事件 ID
/// @return 角色代码列表
List<String> listRoleCode(String eventId);
/// 按客户端提交的顺序更新登记事件排序
///
/// @param idList 登记事件 ID 列表
void sort(List<String> idList);
}
@@ -1,127 +0,0 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventPeriodStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegistrationRankView;
import com.imyeyu.api.modules.gao.vo.GaoQuickRegistrationEventRecordReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCreateReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordListItemView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordPeriodReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordRangeReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordStatReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordTrendStatReq;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
import java.io.IOException;
import java.util.List;
///
/// 登记事件记录服务
///
/// @author Codex
/// @since 2026-07-27
public interface GaoRegistrationEventRecordService extends BaseService<GaoRegistrationEventRecord, String> {
/// 批量创建登记事件记录
///
/// @param req 批量创建请求
/// @return 创建后的登记事件记录列表
List<GaoRegistrationEventRecord> createRecords(GaoRegistrationEventRecordCreateReq req);
/// 快速录入客户并创建登记事件记录
///
/// @param req 快速录入请求
/// @return 创建后的登记事件记录
GaoRegistrationEventRecord quickRegister(GaoQuickRegistrationEventRecordReq req);
/// 按任意时间范围查询登记事件记录
///
/// @param req 范围查询请求
/// @return 登记事件记录列表
List<GaoRegistrationEventRecord> listByRange(GaoRegistrationEventRecordRangeReq req);
/// 按任意时间范围查询日历轻量记录
///
/// @param req 范围查询请求
/// @return 日历轻量记录列表
List<GaoRegistrationEventRecordCalendarView> listCalendarByRange(GaoRegistrationEventRecordRangeReq req);
/// 按任意时间范围分页查询登记事件记录
///
/// @param page 分页参数
/// @return 登记事件记录分页结果
PageResult<GaoRegistrationEventRecordListItemView> pageByRange(Page<GaoRegistrationEventRecordRangeReq> page);
/// 按任意时间范围导出登记事件记录 Excel
///
/// @param req 范围查询请求
/// @return xlsx 文件字节
byte[] exportRangeExcel(GaoRegistrationEventRecordRangeReq req) throws IOException;
/// 按周期查询登记事件记录
///
/// @param req 周期请求
/// @return 登记事件记录列表
List<GaoRegistrationEventRecord> listByRegistrationEventAndPeriod(GaoRegistrationEventRecordPeriodReq req);
/// 按周期统计登记事件记录
///
/// @param registrationEventId 登记事件 ID
/// @param periodType 周期类型
/// @return 统计列表
List<GaoRegistrationEventPeriodStatView> statByRegistrationEventAndPeriodType(String registrationEventId, GaoRegistrationEventRecordPeriodReq.PeriodType periodType);
/// 查询客户指定登记事件的最后登记事件记录
///
/// @param customerIdList 客户 ID 列表
/// @param registrationEventId 登记事件 ID
/// @return 每个客户的最后登记事件记录
List<GaoRegistrationEventRecord> listLatestByCustomerIdListAndRegistrationEventId(List<String> customerIdList, String registrationEventId);
/// 统计客户所有登记
///
/// @param customerId 客户 ID
/// @return 统计结果
List<GaoCustomerRegisterStatView> statByCustomerId(String customerId);
/// 按时间段统计单个客户登记
///
/// @param req 统计请求
/// @return 统计结果
List<GaoCustomerRegisterStatView> statByCustomerAndRange(GaoRegistrationEventRecordStatReq req);
/// 按时间段统计全部客户登记
///
/// @param req 统计请求
/// @return 统计结果
List<GaoCustomerRegisterStatView> statAllCustomerByRange(GaoRegistrationEventRecordStatReq req);
/// 按时间范围查询客户登记排行榜
///
/// @param req 范围查询请求,不传时间为全部时间
/// @return 客户登记排行榜
List<GaoCustomerRegistrationRankView> listCustomerRegistrationRank(GaoRegistrationEventRecordRangeReq req);
/// 按时间段统计单个客户单个登记事件每日趋势
///
/// @param req 趋势统计请求
/// @return 每日趋势列表
List<GaoRegistrationEventRecordDailyStatView> statDailyByCustomerAndRegistrationEvent(GaoRegistrationEventRecordTrendStatReq req);
/// 按时间段统计全部客户单个登记事件每日趋势
///
/// @param req 趋势统计请求
/// @return 每日趋势列表
List<GaoRegistrationEventRecordDailyStatView> statDailyByRegistrationEvent(GaoRegistrationEventRecordTrendStatReq req);
/// 查询客户全部登记事件的最后登记事件记录
///
/// @param customerId 客户 ID
/// @return 每个登记事件的最后登记事件记录
List<GaoRegistrationEventRecord> listLatestByCustomerId(String customerId);
}
@@ -1,38 +0,0 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.service.BaseService;
import java.util.List;
///
/// 登记事件服务
///
/// @author Codex
/// @since 2026-07-27
public interface GaoRegistrationEventService extends BaseService<GaoRegistrationEvent, String> {
/// 分页查询登记事件并填充可登记角色
///
/// @param page 分页参数
/// @return 登记事件分页
PageResult<GaoRegistrationEvent> pageWithRegistrationEventLimit(Page<GaoRegistrationEvent> page);
/// 查询启用的登记事件
///
/// @return 登记事件列表
List<GaoRegistrationEvent> listEnabled();
/// 查询登记事件要求的角色
///
/// @param registrationEventId 登记事件 ID
/// @return 角色代码列表
List<String> listRoleCode(String registrationEventId);
/// 按客户端提交的顺序更新登记事件排序
///
/// @param idList 登记事件 ID 列表
void sort(List<String> idList);
}
@@ -4,54 +4,39 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig; import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.vo.attach.BizUpdateReq;
import com.imyeyu.api.modules.gao.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper; import com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerService; import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStatView; import com.imyeyu.api.modules.gao.util.CustomerXSSFBuilder;
import com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView; import com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerInviteUpdateReq; import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStateReq;
import com.imyeyu.api.modules.gao.vo.GaoCustomerSearchReq;
import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStatReq;
import com.imyeyu.api.modules.system.entity.Logger; import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService; import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.mapper.BaseMapper; import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.spring.service.AbstractEntityService; import com.imyeyu.spring.service.AbstractEntityService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
///
/// 客户服务实现 /// 客户服务实现
/// ///
/// @author Codex /// @author Codex
@@ -62,14 +47,16 @@ import java.util.stream.Collectors;
public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustomer, String> implements GaoCustomerService { public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustomer, String> implements GaoCustomerService {
private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd"); private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final DateTimeFormatter EXPORT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
private final GaoCustomerMapper mapper;
private final ObjectMapper jackson; private final ObjectMapper jackson;
private final AttachmentService attachmentService;
private final LoggerService loggerService; private final LoggerService loggerService;
private final UserLoginService userLoginService; private final UserLoginService userLoginService;
private final UserService userService; private final AttachmentService attachmentService;
private final GaoCustomerMapper mapper;
private final CustomerXSSFBuilder customerXSSFBuilder;
@Override @Override
protected BaseMapper<GaoCustomer, String> mapper() { protected BaseMapper<GaoCustomer, String> mapper() {
@@ -77,26 +64,41 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
} }
@Override @Override
public PageResult<GaoCustomer> page(Page<GaoCustomer> page) { public void create(GaoCustomer customer) {
PageResult<GaoCustomer> result = super.page(page); TimiException.required(customer.getName(), "not found customer.name");
loadListTransient(result.getList());
return result;
}
@Override
public void create(GaoCustomer entity) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_CREATE"); Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_CREATE");
try { try {
logger.setContent(jackson.writeValueAsString(entity)); logger.setContent(jackson.writeValueAsString(customer));
checkEntity(entity, false); {
entity.setCreatorUserId(userLoginService.getRequireLoginUserId()); GaoCustomer byName = getByName(customer.getName());
entity.setInvitedCount(0L); TimiException.requiredNull(byName, "该姓名客户已登记");
super.create(entity); }
saveAttachment(entity.getId(), resolveAttachmentList(entity)); if (TimiJava.isNotEmpty(customer.getCode())) {
changeInvitedCount(entity.getIntroducerCustomerId(), 1L); GaoCustomer byCode = getByCode(customer.getCode());
loadDetailTransient(entity); TimiException.requiredNull(byCode, "该编码客户已登记");
}
if (TimiJava.isNotEmpty(customer.getIntroducerCustomerId())) {
TimiException.requiredTrue(!customer.getIntroducerCustomerId().equals(customer.getId()), "customer.introducerCustomerId invalid");
TimiException.required(super.get(customer.getIntroducerCustomerId()), "not found introducer customer");
}
customer.setBirthdateCalendar(TimiJava.defaultIfNull(customer.getBirthdateCalendar(), GaoCustomer.BirthdateCalendar.SOLAR));
if (TimiJava.isNotEmpty(customer.getBirthdate())) {
customer.setAge(ChronoUnit.YEARS.between(customer.getBirthdate(), LocalDate.now()));
}
customer.setInvitedCount(0L);
if (customer.hasIntroducer()) {
customer.setInvitedCount(1L);
}
customer.setCreatorUserId(userLoginService.getRequireLoginUserId());
super.create(customer);
// 附件
attachmentService.updateByBizId(Attachment.BizType.GAO_CUSTOMER, customer.getId(), customer.getAttachmentList());
logger.setLevel(Logger.Level.INFO); logger.setLevel(Logger.Level.INFO);
logger.setResult(entity.getId()); logger.setResult(customer.getId());
} catch (TimiException e) { } catch (TimiException e) {
logger.setLevel(Logger.Level.WARN); logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage()); logger.setException(e.getMessage());
@@ -112,23 +114,44 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
} }
@Override @Override
public void update(GaoCustomer entity) { public void update(GaoCustomer customer) {
TimiException.required(customer, "not found customer");
TimiException.required(customer.getId(), "not found customer.id");
TimiException.required(customer.getName(), "not found customer.name");
Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_UPDATE"); Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_UPDATE");
try { try {
logger.setContent(jackson.writeValueAsString(entity)); logger.setContent(jackson.writeValueAsString(customer));
TimiException.required(entity, "not found customer"); GaoCustomer dbCustomer = get(customer.getId());
TimiException.required(entity.getId(), "not found customer.id"); dbCustomer.setCode(TimiJava.defaultIfEmpty(customer.getCode(), null));
GaoCustomer dbCustomer = super.get(entity.getId()); {
if (!entity.isBirthdateProvided()) { if (!dbCustomer.getCode().equals(customer.getCode())) {
entity.setBirthdate(dbCustomer.getBirthdate()); GaoCustomer byCode = getByCode(customer.getCode());
entity.setBirthdateCalendar(dbCustomer.getBirthdateCalendar()); TimiException.requiredTrue(byCode == null || !byCode.getId().equals(dbCustomer.getId()), "该姓名客户已登记");
}
if (!dbCustomer.getName().equals(customer.getName())) {
GaoCustomer byName = getByName(customer.getName());
TimiException.requiredTrue(byName == null || !byName.getId().equals(dbCustomer.getId()), "该姓名客户已登记");
}
} }
checkEntity(entity, true); dbCustomer.setName(customer.getName());
mapper.update(entity); dbCustomer.setGender(customer.getGender());
saveAttachment(entity.getId(), resolveAttachmentList(entity)); dbCustomer.setAge(customer.getAge());
syncIntroducerInvitedCount(dbCustomer.getIntroducerCustomerId(), entity.getIntroducerCustomerId()); dbCustomer.setBirthdateCalendar(customer.getBirthdateCalendar());
if (TimiJava.isNotEmpty(customer.getBirthdate())) {
dbCustomer.setAge(ChronoUnit.YEARS.between(customer.getBirthdate(), LocalDate.now()));
}
dbCustomer.setTelephone(customer.getTelephone());
dbCustomer.setAddress(customer.getAddress());
dbCustomer.setRemark(customer.getRemark());
dbCustomer.setDisease(customer.getDisease());
dbCustomer.setConditioningPart(customer.getConditioningPart());
mapper.update(dbCustomer);
// 附件
attachmentService.updateByBizId(Attachment.BizType.GAO_CUSTOMER, customer.getId(), customer.getAttachmentList());
logger.setLevel(Logger.Level.INFO); logger.setLevel(Logger.Level.INFO);
logger.setResult(entity.getId()); logger.setResult(customer.getId());
} catch (TimiException e) { } catch (TimiException e) {
logger.setLevel(Logger.Level.WARN); logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage()); logger.setException(e.getMessage());
@@ -149,9 +172,9 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_DELETE"); Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_DELETE");
try { try {
logger.setContent(id); logger.setContent(id);
GaoCustomer customer = super.get(id); GaoCustomer customer = get(id);
super.delete(id); super.delete(id);
changeInvitedCount(customer.getIntroducerCustomerId(), -1L); changeInvitedCount(customer.getIntroducerCustomerId(), -1);
logger.setLevel(Logger.Level.INFO); logger.setLevel(Logger.Level.INFO);
logger.setResult(id); logger.setResult(id);
} catch (TimiException e) { } catch (TimiException e) {
@@ -168,142 +191,77 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
} }
} }
@Override
public GaoCustomer get(String id) {
GaoCustomer customer = super.get(id);
loadDetailTransient(customer);
return customer;
}
@Override @Override
public GaoCustomer getByCode(String code) { public GaoCustomer getByCode(String code) {
TimiException.required(code, "not found customer.code"); TimiException.required(code, "not found code");
GaoCustomer customer = mapper.selectByCode(code); GaoCustomer example = new GaoCustomer();
TimiException.required(customer, "not found customer"); example.setCode(code);
loadDetailTransient(customer); return mapper.selectByExample(example);
return customer;
} }
@Override @Override
public GaoCustomer getNullableByCode(String code) { public GaoCustomer getByName(String name) {
TimiException.required(code, "not found customer.code"); TimiException.required(name, "not found name");
GaoCustomer customer = mapper.selectByCode(code); GaoCustomer example = new GaoCustomer();
loadDetailTransient(customer); example.setName(name);
return customer; return mapper.selectByExample(example);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public GaoCustomer getOrQuickCreateByCode(String code) {
GaoCustomer customer = getNullableByCode(code);
if (customer != null) {
return customer;
}
customer = new GaoCustomer();
customer.setCode(code);
customer.setName(code);
create(customer);
return customer;
} }
@Override @Override
public List<GaoCustomer> search(GaoCustomerSearchReq req) { public List<GaoCustomer> listByIdList(Collection<String> idList) {
req = resolveSearchReq(req); return mapper.selectByIdList(idList);
List<GaoCustomer> list = mapper.search(req.getKeyword(), req.getIntroducerCustomerId());
loadListTransient(list);
return list;
} }
@Override @Override
public PageResult<GaoCustomer> searchPage(Page<GaoCustomerSearchReq> page) { public byte[] export(Page<GaoCustomer> page) throws IOException {
TimiException.required(page, "not found page"); page.setIndex(0);
TimiException.required(page.getIndex(), "not found page.index"); page.setSize(Long.MAX_VALUE);
TimiException.required(page.getSize(), "not found page.size"); List<GaoCustomer> list = mapper.selectByPage(page);
TimiException.requiredTrue(0 <= page.getIndex(), "page.index lt 0"); {
TimiException.requiredTrue(0 < page.getSize(), "page.size lte 0"); List<String> idList = list.stream().map(GaoCustomer::getIntroducerCustomerId).filter(TimiJava::isNotEmpty).distinct().toList();
GaoCustomerSearchReq req = resolveSearchReq(page.getEqualsExample()); Map<String, GaoCustomer> map = mapByIdList(idList);
Long total = TimiJava.defaultIfNull(mapper.countSearch(req.getKeyword(), req.getIntroducerCustomerId()), 0L);
List<GaoCustomer> list = mapper.searchPage(req.getKeyword(), req.getIntroducerCustomerId(), page.getIndex() * page.getSize(), page.getSize());
loadListTransient(list);
PageResult<GaoCustomer> result = new PageResult<>();
result.setTotal(total);
result.setList(list);
return result;
}
@Override
public byte[] exportSearchExcel(GaoCustomerSearchReq req) throws IOException {
List<GaoCustomer> list = search(req);
loadIntroducerCustomer(list);
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("客户列表");
CellStyle titleStyle = workbook.createCellStyle();
Font titleFont = workbook.createFont();
titleFont.setBold(true);
titleFont.setFontHeightInPoints((short) 14);
titleStyle.setFont(titleFont);
CellStyle headerStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
appendRow(sheet, 0, titleStyle, "客户列表导出");
appendRow(sheet, 1, null, "生成时间", EXPORT_TIME_FORMATTER.format(Instant.now()));
appendRow(sheet, 2, null, "关键词", req == null || req.getKeyword() == null || req.getKeyword().isBlank() ? "全部" : req.getKeyword().trim());
appendRow(sheet, 3, null, "记录总数", String.valueOf(list.size()));
appendRow(sheet, 5, headerStyle, "客户编码", "姓名", "性别", "出生日期(公历)", "出生日期历法", "年龄", "电话", "地址", "病症", "备注", "邀请人", "邀请客户数", "创建时间");
int rowIndex = 6;
for (GaoCustomer customer : list) { for (GaoCustomer customer : list) {
appendRow(sheet, rowIndex, null, customer.setIntroducerCustomer(map.get(customer.getIntroducerCustomerId()));
text(customer.getCode()),
text(customer.getName()),
formatGender(customer),
text(customer.getBirthdate()),
formatBirthdateCalendar(customer),
customer.getAge() == null ? "" : String.valueOf(customer.getAge()),
text(customer.getTelephone()),
text(customer.getAddress()),
text(customer.getDisease()),
text(customer.getRemark()),
customer.getIntroducerCustomer() == null ? "" : text(customer.getIntroducerCustomer().getName()),
customer.getInvitedCount() == null ? "0" : String.valueOf(customer.getInvitedCount()),
formatExportTime(customer.getCreatedAt())
);
rowIndex++;
} }
for (int index = 0; index < 13; index++) {
sheet.autoSizeColumn(index);
sheet.setColumnWidth(index, Math.min(Math.max(sheet.getColumnWidth(index), 10 * 256), 36 * 256));
}
workbook.write(output);
return output.toByteArray();
} }
return customerXSSFBuilder.build(list);
} }
@Override @Override
public List<GaoCustomer> listInvited(String introducerCustomerId) { public List<GaoCustomer> listInvited(String introducerCustomerId) {
TimiException.required(introducerCustomerId, "not found introducerCustomerId"); TimiException.required(introducerCustomerId, "not found introducerCustomerId");
List<GaoCustomer> list = mapper.selectInvitedList(introducerCustomerId); GaoCustomer example = new GaoCustomer();
loadListTransient(list); example.setIntroducerCustomerId(introducerCustomerId);
return list; return mapper.selectAllByExample(example);
} }
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void saveInviteRelation(GaoCustomerInviteUpdateReq req) { public void saveInviteRelation(String introducerCustomerId, String customerId) {
TimiException.required(customerId, "not found customerId");
TimiException.required(introducerCustomerId, "not found introducerCustomerId");
Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_SAVE_INVITE_RELATION"); Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_SAVE_INVITE_RELATION");
try { try {
logger.setContent(jackson.writeValueAsString(req)); logger.setContent("introducerCustomerId: %s, customerId: %s".formatted(introducerCustomerId, customerId));
TimiException.required(req, "not found invite req"); GaoCustomer customer = get(customerId);
TimiException.required(req.getCustomerId(), "not found invite req.customerId"); TimiException.required(customer, "not found customer");
GaoCustomer customer = super.get(req.getCustomerId()); GaoCustomer introducerCustomer = get(introducerCustomerId);
String oldIntroducerCustomerId = customer.getIntroducerCustomerId(); TimiException.required(introducerCustomer, "not found introducerCustomer");
customer.setIntroducerCustomerId(req.getIntroducerCustomerId()); if (introducerCustomer.getIntroducerCustomerId().equals(customer.getIntroducerCustomerId())) {
checkEntity(customer, true); throw new TimiException(TimiCode.ARG_BAD, "customer can not upper be introducer customer");
super.update(customer); }
syncIntroducerInvitedCount(oldIntroducerCustomerId, customer.getIntroducerCustomerId()); // 存在旧的邀请来源
if (TimiJava.isNotEmpty(customer.getIntroducerCustomerId())) {
if (customer.getIntroducerCustomerId().equals(introducerCustomerId)) {
return;
}
changeInvitedCount(customer.getIntroducerCustomerId(), -1);
}
customer.setIntroducerCustomerId(introducerCustomerId);
mapper.update(customer);
changeInvitedCount(introducerCustomerId, +1);
logger.setLevel(Logger.Level.INFO); logger.setLevel(Logger.Level.INFO);
logger.setResult(req.getCustomerId());
} catch (TimiException e) { } catch (TimiException e) {
logger.setLevel(Logger.Level.WARN); logger.setLevel(Logger.Level.WARN);
logger.setException(e.getMessage()); logger.setException(e.getMessage());
@@ -321,15 +279,16 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void deleteInviteRelation(String customerId) { public void deleteInviteRelation(String customerId) {
TimiException.required(customerId, "not found customerId");
Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_DELETE_INVITE_RELATION"); Logger logger = new Logger(Logger.Module.GAO, "GAO_CUSTOMER_DELETE_INVITE_RELATION");
try { try {
logger.setContent(customerId); logger.setContent(customerId);
TimiException.required(customerId, "not found customerId"); GaoCustomer customer = get(customerId);
GaoCustomer customer = super.get(customerId);
String oldIntroducerCustomerId = customer.getIntroducerCustomerId();
customer.setIntroducerCustomerId(null); customer.setIntroducerCustomerId(null);
super.update(customer); mapper.update(customer);
changeInvitedCount(oldIntroducerCustomerId, -1L);
changeInvitedCount(customer.getIntroducerCustomerId(), -1);
logger.setLevel(Logger.Level.INFO); logger.setLevel(Logger.Level.INFO);
logger.setResult(customerId); logger.setResult(customerId);
} catch (TimiException e) { } catch (TimiException e) {
@@ -347,7 +306,7 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
} }
@Override @Override
public List<GaoCustomerDailyStatView> statDailyTrend(GaoCustomerTrendStatReq req) { public List<GaoCustomerDailyStateView> stateDailyTrend(GaoCustomerTrendStateReq req) {
TimiException.required(req, "not found req"); TimiException.required(req, "not found req");
TimiException.required(req.getBeginCreatedAt(), "not found req.beginCreatedAt"); TimiException.required(req.getBeginCreatedAt(), "not found req.beginCreatedAt");
TimiException.required(req.getEndCreatedAt(), "not found req.endCreatedAt"); TimiException.required(req.getEndCreatedAt(), "not found req.endCreatedAt");
@@ -355,20 +314,23 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
ZoneId zoneId = ZoneId.systemDefault(); ZoneId zoneId = ZoneId.systemDefault();
LocalDate beginDate = Instant.ofEpochMilli(req.getBeginCreatedAt()).atZone(zoneId).toLocalDate(); LocalDate beginDate = Instant.ofEpochMilli(req.getBeginCreatedAt()).atZone(zoneId).toLocalDate();
LocalDate endDate = Instant.ofEpochMilli(req.getEndCreatedAt()).atZone(zoneId).toLocalDate(); LocalDate endDate = Instant.ofEpochMilli(req.getEndCreatedAt()).atZone(zoneId).toLocalDate();
checkDailyStatRange(beginDate, endDate);
long days = ChronoUnit.DAYS.between(beginDate, endDate) + 1;
TimiException.requiredTrue(days <= 366, "daily stat range too large");
long beginCreatedAt = beginDate.atStartOfDay(zoneId).toInstant().toEpochMilli(); long beginCreatedAt = beginDate.atStartOfDay(zoneId).toInstant().toEpochMilli();
long endCreatedAt = endDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1; long endCreatedAt = endDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1;
Map<Integer, Long> newCustomerCountMap = new HashMap<>(); Map<Integer, Long> newCustomerCountMap = new HashMap<>();
for (GaoCustomerDailyStatView view : mapper.statDailyNewCustomer(beginCreatedAt, endCreatedAt)) { for (GaoCustomerDailyStateView view : mapper.stateDailyNewCustomer(beginCreatedAt, endCreatedAt)) {
newCustomerCountMap.put(view.getDateValue(), TimiJava.defaultIfNull(view.getNewCustomerCount(), 0L)); newCustomerCountMap.put(view.getDateValue(), TimiJava.defaultIfNull(view.getNewCustomerCount(), 0L));
} }
long totalCustomerCount = TimiJava.defaultIfNull(mapper.countCreatedBefore(beginCreatedAt), 0L); long totalCustomerCount = TimiJava.defaultIfNull(mapper.countCreatedBefore(beginCreatedAt), 0L);
List<GaoCustomerDailyStatView> list = new ArrayList<>(); List<GaoCustomerDailyStateView> list = new ArrayList<>();
for (LocalDate date = beginDate; !date.isAfter(endDate); date = date.plusDays(1)) { for (LocalDate date = beginDate; !date.isAfter(endDate); date = date.plusDays(1)) {
int dateValue = Integer.parseInt(DAY_FORMATTER.format(date)); int dateValue = Integer.parseInt(DAY_FORMATTER.format(date));
long newCustomerCount = TimiJava.defaultIfNull(newCustomerCountMap.get(dateValue), 0L); long newCustomerCount = TimiJava.defaultIfNull(newCustomerCountMap.get(dateValue), 0L);
totalCustomerCount += newCustomerCount; totalCustomerCount += newCustomerCount;
GaoCustomerDailyStatView view = new GaoCustomerDailyStatView(); GaoCustomerDailyStateView view = new GaoCustomerDailyStateView();
view.setDateValue(dateValue); view.setDateValue(dateValue);
view.setNewCustomerCount(newCustomerCount); view.setNewCustomerCount(newCustomerCount);
view.setTotalCustomerCount(totalCustomerCount); view.setTotalCustomerCount(totalCustomerCount);
@@ -378,219 +340,16 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
} }
@Override @Override
public List<GaoCustomerGenderStatView> statGender() { public List<GaoCustomerGenderStatView> stateGender() {
return mapper.statGender(); return mapper.stateGender();
}
private void checkDailyStatRange(LocalDate beginDate, LocalDate endDate) {
long days = ChronoUnit.DAYS.between(beginDate, endDate) + 1;
TimiException.requiredTrue(days <= 366, "daily stat range too large");
}
private GaoCustomerSearchReq resolveSearchReq(GaoCustomerSearchReq req) {
return req == null ? new GaoCustomerSearchReq() : req;
}
private GaoCustomer checkEntity(GaoCustomer entity, boolean requireId) {
TimiException.required(entity, "not found customer");
GaoCustomer dbCustomer = null;
entity.setCode(normalizeText(entity.getCode()));
entity.setIntroducerCustomerId(normalizeText(entity.getIntroducerCustomerId()));
if (entity.getBirthdateCalendar() == null) {
entity.setBirthdateCalendar(GaoCustomer.BirthdateCalendar.SOLAR);
}
refreshAge(entity);
if (requireId) {
TimiException.required(entity.getId(), "not found customer.id");
dbCustomer = super.get(entity.getId());
entity.setCreatorUserId(dbCustomer.getCreatorUserId());
}
TimiException.required(entity.getName(), "not found customer.name");
entity.setName(entity.getName().trim());
TimiException.requiredTrue(!entity.getName().isEmpty(), "not found customer.name");
GaoCustomer duplicateCustomer = mapper.selectByName(entity.getName());
if (duplicateCustomer != null && !duplicateCustomer.getId().equals(entity.getId())) {
throw new TimiException(TimiCode.ARG_BAD, "客户姓名已存在");
}
if (TimiJava.isNotEmpty(entity.getCode())) {
duplicateCustomer = mapper.selectByCode(entity.getCode());
if (duplicateCustomer != null && !duplicateCustomer.getId().equals(entity.getId())) {
throw new TimiException(TimiCode.ARG_BAD, "客户编码已存在");
}
}
if (TimiJava.isNotEmpty(entity.getIntroducerCustomerId())) {
TimiException.requiredTrue(!entity.getIntroducerCustomerId().equals(entity.getId()), "customer.introducerCustomerId invalid");
TimiException.required(super.get(entity.getIntroducerCustomerId()), "not found introducer customer");
}
return dbCustomer;
}
private void loadDetailTransient(GaoCustomer customer) {
if (customer == null) {
return;
}
refreshAge(customer);
loadIntroducerCustomer(List.of(customer));
if (TimiJava.isNotEmpty(customer.getCreatorUserId())) {
customer.setCreatorUser(userService.get(customer.getCreatorUserId()));
}
List<GaoCustomer> detailCustomerList = new ArrayList<>();
detailCustomerList.add(customer);
if (customer.getIntroducerCustomer() != null) {
detailCustomerList.add(customer.getIntroducerCustomer());
}
loadAttachmentList(detailCustomerList);
}
private void loadListTransient(List<GaoCustomer> customerList) {
if (customerList != null) {
customerList.forEach(this::refreshAge);
}
loadAttachmentList(customerList);
}
/// 根据出生日期计算当前周岁。出生日期为空时保留旧数据中的手工年龄。
private void refreshAge(GaoCustomer customer) {
if (customer.getBirthdate() == null) {
return;
}
LocalDate today = LocalDate.now();
TimiException.requiredTrue(!customer.getBirthdate().isAfter(today), "customer.birthdate invalid");
customer.setAge(Period.between(customer.getBirthdate(), today).getYears());
}
private void loadIntroducerCustomer(List<GaoCustomer> customerList) {
if (customerList == null || customerList.isEmpty()) {
return;
}
List<String> introducerCustomerIdList = customerList.stream()
.map(GaoCustomer::getIntroducerCustomerId)
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
if (introducerCustomerIdList.isEmpty()) {
return;
}
Map<String, GaoCustomer> introducerCustomerMap = mapper.selectByIdList(new ArrayList<>(introducerCustomerIdList)).stream()
.collect(Collectors.toMap(GaoCustomer::getId, item -> item, (left, right) -> left));
for (GaoCustomer customer : customerList) {
customer.setIntroducerCustomer(introducerCustomerMap.get(customer.getIntroducerCustomerId()));
}
}
private void loadAttachmentList(List<GaoCustomer> customerList) {
if (customerList == null || customerList.isEmpty()) {
return;
}
List<String> customerIdList = customerList.stream()
.map(GaoCustomer::getId)
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList, GaoCustomer.AttachType.PHOTO.name());
for (GaoCustomer customer : customerList) {
customer.setAttachmentList(attachmentMap.getOrDefault(customer.getId(), List.of()));
}
}
private void syncIntroducerInvitedCount(String oldIntroducerCustomerId, String newIntroducerCustomerId) {
String normalizedOldIntroducerCustomerId = normalizeText(oldIntroducerCustomerId);
String normalizedNewIntroducerCustomerId = normalizeText(newIntroducerCustomerId);
if (Objects.equals(normalizedOldIntroducerCustomerId, normalizedNewIntroducerCustomerId)) {
return;
}
changeInvitedCount(normalizedOldIntroducerCustomerId, -1L);
changeInvitedCount(normalizedNewIntroducerCustomerId, 1L);
} }
private void changeInvitedCount(String customerId, long delta) { private void changeInvitedCount(String customerId, long delta) {
String normalizedCustomerId = normalizeText(customerId); if (delta == 0) {
if (normalizedCustomerId == null || delta == 0) {
return; return;
} }
mapper.updateInvitedCountDelta(normalizedCustomerId, delta); GaoCustomer customer = get(customerId);
} customer.setInvitedCount(customer.getInvitedCount() + delta);
mapper.update(customer);
private String normalizeText(String value) {
if (value == null) {
return null;
}
String trimmedValue = value.trim();
return trimmedValue.isEmpty() ? null : trimmedValue;
}
private void saveAttachment(String customerId, List<Attachment> attachmentList) {
if (attachmentList == null) {
return;
}
for (Attachment attachment : attachmentList) {
attachment.setBizType(Attachment.BizType.GAO_CUSTOMER);
attachment.setBizId(customerId);
attachment.setAttachType(GaoCustomer.AttachType.PHOTO.name());
}
BizUpdateReq req = new BizUpdateReq();
req.setBizType(Attachment.BizType.GAO_CUSTOMER);
req.setBizId(customerId);
req.setItems(attachmentList);
attachmentService.updateByBiz(req);
}
private List<Attachment> resolveAttachmentList(GaoCustomer customer) {
if (customer.getAttachmentIdList() != null) {
return buildPhotoAttachmentList(customer.getAttachmentIdList());
}
return customer.getAttachmentList();
}
private List<Attachment> buildPhotoAttachmentList(List<String> attachmentIdList) {
List<Attachment> list = new ArrayList<>();
for (String attachmentId : attachmentIdList) {
if (attachmentId == null || attachmentId.isBlank()) {
continue;
}
Attachment attachment = new Attachment();
attachment.setTempFileId(attachmentId.trim());
attachment.setAttachType(GaoCustomer.AttachType.PHOTO.name());
list.add(attachment);
}
return list;
}
private void appendRow(Sheet sheet, int rowIndex, CellStyle style, String... values) {
Row row = sheet.createRow(rowIndex);
for (int index = 0; index < values.length; index++) {
row.createCell(index).setCellValue(values[index]);
if (style != null) {
row.getCell(index).setCellStyle(style);
}
}
}
private String formatGender(GaoCustomer customer) {
if (customer.getGender() == null) {
return "";
}
return switch (customer.getGender()) {
case MALE -> "";
case FEMALE -> "";
};
}
private String formatBirthdateCalendar(GaoCustomer customer) {
if (customer.getBirthdateCalendar() == null) {
return "公历";
}
return customer.getBirthdateCalendar() == GaoCustomer.BirthdateCalendar.LUNAR ? "农历" : "公历";
}
private String formatExportTime(Long value) {
if (value == null) {
return "";
}
return EXPORT_TIME_FORMATTER.format(Instant.ofEpochMilli(value));
}
private String text(Object value) {
return value == null ? "" : value.toString();
} }
} }
@@ -0,0 +1,252 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.mapper.GaoEventRecordMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoEventRecordService;
import com.imyeyu.api.modules.gao.service.GaoEventService;
import com.imyeyu.api.modules.gao.util.EventRecordXSSFBuilder;
import com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.user.service.RoleChecker;
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.bean.PageResult;
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;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
/// 登记事件记录服务实现
///
/// @author 夜雨
/// @since 2026-07-27 14:11
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoEventRecordServiceImplement extends AbstractEntityService<GaoEventRecord, String> implements GaoEventRecordService {
private final ObjectMapper jackson;
private final RoleChecker roleChecker;
private final LoggerService loggerService;
private final GaoEventService eventService;
private final UserLoginService userLoginService;
private final AttachmentService attachmentService;
private final GaoCustomerService customerService;
private final GaoEventRecordMapper mapper;
private final EventRecordXSSFBuilder xssfBuilder;
@Override
protected BaseMapper<GaoEventRecord, String> mapper() {
return mapper;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(GaoEventRecord record) {
TimiException.required(record, "not found record");
Logger logger = new Logger(Logger.Module.GAO, "GAO_EVENT_RECORD_BATCH_CREATE");
try {
logger.setContent(jackson.writeValueAsString(record));
String loginUserId = userLoginService.getRequireLoginUserId();
Long registeredAt = TimiJava.defaultIfNull(record.getRegisteredAt(), Time.now());
GaoEvent event = eventService.get(record.getEventId());
// 检查权限
checkEventPermission(event);
List<String> customerIdList = TimiJava.defaultIfEmpty(record.getCustomerIdList(), List.of(record.getCustomerId()));
if (TimiJava.isNotEmpty(record.getCustomer())) {
// 客户未创建,补录客户后登记
customerService.create(record.getCustomer());
customerIdList.add(record.getCustomer().getId());
}
TimiException.required(customerIdList, "not found customerId or empty customerIdList");
GaoEventRecord firstRecord = null;
List<String> logIdList = new ArrayList<>();
for (int i = 0; i < customerIdList.size(); i++) {
String customerId = customerIdList.get(i);
// 检查事件可登记
checkEventCreatable(customerId, event, registeredAt);
GaoEventRecord dbRecord = new GaoEventRecord();
dbRecord.setCustomerId(customerId);
dbRecord.setEventId(record.getEventId());
dbRecord.setOperatorUserId(loginUserId);
dbRecord.setRemark(record.getRemark());
dbRecord.setRegisteredAt(registeredAt);
super.create(dbRecord);
// 附件
if (i == 0) {
// 第一个记录储存附件
firstRecord = dbRecord;
attachmentService.updateByBizId(Attachment.BizType.GAO_EVENT_RECORD, dbRecord.getId(), record.getAttachmentList());
} else {
// 其他记录克隆第一个记录附件
List<Attachment> attachmentList = attachmentService.listByBizId(Attachment.BizType.GAO_EVENT_RECORD, firstRecord.getId());
for (Attachment attachment : attachmentList) {
Attachment clone = attachmentService.clone(attachment.getId());
clone.setId(dbRecord.getId());
attachmentService.update(clone);
}
}
logIdList.add(dbRecord.getId());
}
logger.setLevel(Logger.Level.INFO);
logger.setResult(String.join(",", logIdList));
} 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 event record error", e);
throw new TimiException(TimiCode.ERROR, "create event record error", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(GaoEventRecord record) {
TimiException.required(record, "not found record");
TimiException.required(record.getId(), "not found record.id");
Logger logger = new Logger(Logger.Module.GAO, "GAO_EVENT_RECORD_UPDATE");
try {
logger.setContent(jackson.writeValueAsString(record));
TimiException.required(record.getCustomerId(), "not found record.customerId");
TimiException.required(record.getEventId(), "not found record.eventId");
record.setRegisteredAt(TimiJava.defaultIfNull(record.getRegisteredAt(), Time.now()));
GaoEvent event = eventService.get(record.getEventId());
checkEventPermission(event);
checkEventCreatable(record.getCustomerId(), event, record.getRegisteredAt());
super.update(record);
attachmentService.updateByBizId(Attachment.BizType.GAO_EVENT_RECORD, record.getId(), record.getAttachmentList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(record.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("修改 GAO 登记记录失败", e);
throw new TimiException(TimiCode.ERROR, "修改 GAO 登记记录失败", e);
} finally {
loggerService.create(logger);
}
}
@Override
public PageResult<GaoEventRecord> pageByRange(GaoEventRecordPage page) {
PageResult<GaoEventRecord> result = new PageResult<>();
result.setTotal(mapper.countByRange(page));
result.setList(mapper.selectByRange(page));
return result;
}
@Override
public byte[] export(GaoEventRecordPage page) throws IOException {
List<GaoEventRecord> list = mapper.selectByRange(page);
return xssfBuilder.build(list);
}
@Override
public PageResult<GaoCustomerEventRankView> pageRankByRange(GaoEventRecordRankPage page) {
PageResult<GaoCustomerEventRankView> result = new PageResult<>();
result.setTotal(mapper.countRankByRange(page));
result.setList(mapper.selectRankByRange(page));
return result;
}
private void checkEventPermission(GaoEvent event) {
List<String> roleCodeList = eventService.listRoleCode(event.getId());
TimiException.requiredTrue(roleCodeList != null && !roleCodeList.isEmpty(), "登记事件未配置可登记角色");
roleChecker.checkAny(ModuleCode.GAO, roleCodeList.toArray(String[]::new));
}
private void checkEventCreatable(String customerId, GaoEvent event, long registeredAt) {
TimiException.requiredTrue(event.getStatus() == null || event.getStatus() == GaoEvent.Status.ACTIVE, "登记事件不可登记");
TimiException.requiredTrue(event.getBeginAt() == null || event.getBeginAt() <= registeredAt, "登记事件未到可登记时间");
TimiException.requiredTrue(event.getEndAt() == null || registeredAt <= event.getEndAt(), "登记事件已过可登记时间");
GaoEvent.LimitType limitType = TimiJava.defaultIfNull(event.getLimitType(), GaoEvent.LimitType.NONE);
switch (limitType) {
case DAILY_HALF_DAY -> {
long today = Time.today(registeredAt);
long noon = today + Time.D / 2;
long beginAt = today, endAt;
if (today + registeredAt < noon) {
// 上半日
endAt = noon;
} else {
// 下半日
beginAt = noon;
endAt = today + Time.D;
}
Long count = mapper.count(customerId, event.getId(), beginAt, endAt);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < 1, "该客户当前半日已登记该事件");
}
case NATURAL_DAY -> {
long beginAt = Time.today(registeredAt);
long endAt = beginAt + Time.D;
Long count = mapper.count(customerId, event.getId(), beginAt, endAt);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < 1, "该客户当前半日已登记该事件");
}
case INTERVAL_HOUR -> {
long beginAt = registeredAt - event.getLimitValue() * Time.H;
Long count = mapper.count(customerId, event.getId(), beginAt, registeredAt);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < 1, "该客户登记该事件间隔不足");
}
case NATURAL_MONTH -> {
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime zdt = Instant.ofEpochMilli(registeredAt).atZone(zone);
long beginAt = zdt.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS).toInstant().toEpochMilli();
long endAt = zdt.with(TemporalAdjusters.firstDayOfNextMonth()).truncatedTo(ChronoUnit.DAYS).toInstant().toEpochMilli();
Long count = mapper.count(customerId, event.getId(), beginAt, endAt);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < 1, "该客户当月已登记该事件");
}
case TOTAL_LIMIT -> {
Long count = mapper.count(null, event.getId(), null, null);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < event.getLimitValue(), "登记事件总次数已达上限");
}
case CUSTOMER_TOTAL_LIMIT -> {
Long count = mapper.count(customerId, event.getId(), null, null);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < event.getLimitValue(), "该客户登记该事件次数已达上限");
}
}
}
}
@@ -0,0 +1,215 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.api.modules.gao.entity.GaoEventRoleRelation;
import com.imyeyu.api.modules.gao.mapper.GaoEventMapper;
import com.imyeyu.api.modules.gao.mapper.GaoEventRoleRelationMapper;
import com.imyeyu.api.modules.gao.service.GaoEventService;
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 com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
///
/// 登记事件服务实现
///
/// @author 夜雨
/// @since 2026-07-27 09:00
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoEventServiceImplement extends AbstractEntityService<GaoEvent, String> implements GaoEventService {
private final ObjectMapper jackson;
private final LoggerService loggerService;
private final GaoEventMapper mapper;
private final GaoEventRoleRelationMapper roleRelationMapper;
@Override
protected BaseMapper<GaoEvent, String> mapper() {
return mapper;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(GaoEvent event) {
TimiException.required(event, "not found event");
TimiException.required(event.getName(), "not found event.name");
Logger logger = new Logger(Logger.Module.GAO, "GAO_EVENT_CREATE");
try {
logger.setContent(jackson.writeValueAsString(event));
event.setStatus(TimiJava.defaultIfNull(event.getStatus(), GaoEvent.Status.DRAFT));
event.setRequirePhoto(TimiJava.defaultIfNull(event.getRequirePhoto(), false));
event.setLimitType(TimiJava.defaultIfNull(event.getLimitType(), GaoEvent.LimitType.NONE));
if (TimiJava.isNotEmpty(event.getLimitType())) {
TimiException.requiredTrue(event.getLimitType().getMin() < event.getLimitValue(), "约束值最低 %s".formatted(event.getLimitType().getMin()));
}
if (event.getBeginAt() != null || event.getEndAt() != null) {
TimiException.requiredTrue(event.getBeginAt() == null || event.getEndAt() == null || event.getBeginAt() <= event.getEndAt(), "invalid beginAt or endAt");
}
event.setSort(TimiJava.defaultIfNull(event.getSort(), 0));
super.create(event);
saveRoleRelation(event.getId(), event.getRoleCodeList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(event.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 event error", e);
throw new TimiException(TimiCode.ERROR, "create event error", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(GaoEvent entity) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_EVENT_UPDATE");
try {
logger.setContent(jackson.writeValueAsString(entity));
GaoEvent dbEvent = get(entity.getId());
dbEvent.setName(entity.getName());
dbEvent.setDescription(entity.getDescription());
dbEvent.setColor(entity.getColor());
dbEvent.setStatus(entity.getStatus());
dbEvent.setRequirePhoto(entity.getRequirePhoto());
dbEvent.setLimitType(entity.getLimitType());
dbEvent.setLimitValue(entity.getLimitValue());
dbEvent.setBeginAt(entity.getBeginAt());
dbEvent.setEndAt(entity.getEndAt());
mapper.update(dbEvent);
saveRoleRelation(entity.getId(), entity.getRoleCodeList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(entity.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 event error", e);
throw new TimiException(TimiCode.ERROR, "update event error", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void delete(String id) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_EVENT_DELETE");
try {
logger.setContent(id);
GaoEvent event = get(id);
event.setStatus(GaoEvent.Status.DELETED);
super.update(event);
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 event error", e);
throw new TimiException(TimiCode.ERROR, "delete event error", e);
} finally {
loggerService.create(logger);
}
}
@Override
public Map<String, GaoEvent> mapByIdList(Collection<String> idList) {
return mapper.selectByIdList(new HashSet<>(idList)).stream().collect(Collectors.toMap(GaoEvent::getId, Function.identity()));
}
@Override
public Map<String, List<String>> mapRoleCodeListByEventIdList(Collection<String> eventIdList) {
return roleRelationMapper.selectAllByEventIdList(new HashSet<>(eventIdList))
.stream()
.collect(Collectors.groupingBy(GaoEventRoleRelation::getEventId, Collectors.mapping(GaoEventRoleRelation::getRoleCode, Collectors.toList())));
}
@Override
public List<GaoEvent> listValid() {
return mapper.selectValidList(Time.now());
}
@Override
public List<String> listRoleCode(String eventId) {
GaoEventRoleRelation example = new GaoEventRoleRelation();
example.setEventId(eventId);
return roleRelationMapper.selectAllByExample(example).stream().map(GaoEventRoleRelation::getRoleCode).toList();
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void sort(List<String> idList) {
if (TimiJava.isEmpty(idList)) {
return;
}
idList = new ArrayList<>(new LinkedHashSet<>(idList));
Map<String, GaoEvent> eventMap = mapper.selectByIdList(idList).stream().collect(Collectors.toMap(GaoEvent::getId, Function.identity()));
for (int i = 0; i < idList.size(); i++) {
GaoEvent event = eventMap.get(idList.get(i));
event.setSort(i);
mapper.update(event);
}
}
private void saveRoleRelation(String eventId, List<String> roleCodeList) {
List<GaoEventRoleRelation> dbRoleRelationList = roleRelationMapper.selectAllByEventIdList(List.of(eventId));
Set<String> roleCodeSet = TimiJava.defaultIfEmpty(roleCodeList, List.<String>of()).stream().filter(TimiJava::isNotEmpty).collect(Collectors.toSet());
Set<String> retainedRoleCodeSet = new HashSet<>();
for (GaoEventRoleRelation dbEventRole : dbRoleRelationList) {
String roleCode = dbEventRole.getRoleCode();
if (roleCode != null) {
roleCode = roleCode.trim();
}
if (!roleCodeSet.contains(roleCode) || !retainedRoleCodeSet.add(roleCode)) {
roleRelationMapper.delete(dbEventRole.getId());
}
}
for (String roleCode : roleCodeSet) {
if (retainedRoleCodeSet.contains(roleCode)) {
continue;
}
GaoEventRoleRelation relation = new GaoEventRoleRelation();
relation.setEventId(eventId);
relation.setRoleCode(roleCode);
roleRelationMapper.insert(relation);
}
}
}
@@ -1,761 +0,0 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.vo.attach.BizUpdateReq;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord;
import com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRegistrationEventMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRegistrationEventRecordMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventService;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventRecordService;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventPeriodStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegistrationDayStatView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerRegistrationRankView;
import com.imyeyu.api.modules.gao.vo.GaoQuickRegistrationEventRecordReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCalendarView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCreateReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordDailyStatView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordListItemView;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordPeriodReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordRangeReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordStatReq;
import com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordTrendStatReq;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.api.modules.user.mapper.UserMapper;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.TimiSpring;
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 com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.stream.Collectors;
///
/// 登记事件记录服务实现
///
/// @author Codex
/// @since 2026-07-27
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoRegistrationEventRecordServiceImplement extends AbstractEntityService<GaoRegistrationEventRecord, String> implements GaoRegistrationEventRecordService {
private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.BASIC_ISO_DATE;
private static final DateTimeFormatter EXPORT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
private final GaoRegistrationEventRecordMapper mapper;
private final ObjectMapper jackson;
private final GaoCustomerMapper customerMapper;
private final GaoRegistrationEventMapper registrationEventMapper;
private final UserMapper userMapper;
private final AttachmentService attachmentService;
private final LoggerService loggerService;
private final RoleChecker roleChecker;
private final UserLoginService userLoginService;
private final UserService userService;
private final GaoCustomerService customerService;
private final GaoRegistrationEventService registrationEventService;
@Override
protected BaseMapper<GaoRegistrationEventRecord, String> mapper() {
return mapper;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public List<GaoRegistrationEventRecord> createRecords(GaoRegistrationEventRecordCreateReq req) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_REGISTRATION_EVENT_RECORD_BATCH_CREATE");
try {
TimiException.required(req, "not found req");
TimiException.requiredTrue(req.getCustomerIdList() != null && !req.getCustomerIdList().isEmpty(), "customerIdList is empty");
logger.setContent(jackson.writeValueAsString(req));
List<GaoRegistrationEventRecord> recordList = new ArrayList<>();
for (int index = 0; index < req.getCustomerIdList().size(); index++) {
String customerId = req.getCustomerIdList().get(index);
GaoRegistrationEventRecordCreateReq customerReq = copyCreateReq(req);
customerReq.setAttachmentIdList(0 == index && canUseSourceTempFileList(req.getAttachmentIdList())
? req.getAttachmentIdList()
: duplicateTempFileList(req.getAttachmentIdList()));
recordList.add(doCreateRecord(customerReq, customerId));
}
logger.setLevel(Logger.Level.INFO);
logger.setResult(recordList.stream().map(GaoRegistrationEventRecord::getId).collect(Collectors.joining(",")));
return recordList;
} 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("批量新增 GAO 登记记录失败", e);
throw new TimiException(TimiCode.ERROR, "批量新增 GAO 登记记录失败", e);
} finally {
loggerService.create(logger);
}
}
private List<String> duplicateTempFileList(List<String> sourceIdList) {
if (sourceIdList == null) {
return null;
}
List<String> targetIdList = new ArrayList<>();
for (String sourceId : sourceIdList) {
if (sourceId == null || sourceId.isBlank()) {
continue;
}
Attachment source = attachmentService.get(sourceId.trim());
TimiException.required(source, "not found attachment");
TimiException.required(source.getMongoId(), "not found attachment.mongoId");
Attachment target = new Attachment();
target.setBizType(Attachment.BizType.TEMP_FILE);
target.setName(source.getName());
target.setInputStream(new ByteArrayInputStream(attachmentService.readAllByMongoId(source.getMongoId())));
attachmentService.create(target);
targetIdList.add(target.getId());
}
return targetIdList;
}
private boolean canUseSourceTempFileList(List<String> sourceIdList) {
if (sourceIdList == null || sourceIdList.isEmpty()) {
return true;
}
for (String sourceId : sourceIdList) {
if (sourceId == null || sourceId.isBlank()) {
continue;
}
Attachment source = attachmentService.get(sourceId.trim());
if (source == null || source.getBizType() != Attachment.BizType.TEMP_FILE) {
return false;
}
}
return true;
}
private GaoRegistrationEventRecordCreateReq copyCreateReq(GaoRegistrationEventRecordCreateReq source) {
GaoRegistrationEventRecordCreateReq target = new GaoRegistrationEventRecordCreateReq();
target.setRegistrationEventId(source.getRegistrationEventId());
target.setRemark(source.getRemark());
target.setRegisteredAt(source.getRegisteredAt());
return target;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public GaoRegistrationEventRecord quickRegister(GaoQuickRegistrationEventRecordReq req) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_REGISTRATION_EVENT_RECORD_QUICK_REGISTER");
try {
logger.setContent(jackson.writeValueAsString(req));
TimiException.required(req, "not found req");
TimiException.required(req.getCustomerCode(), "not found req.customerCode");
TimiException.required(req.getRegistrationEventId(), "not found req.registrationEventId");
GaoCustomer customer = customerService.getOrQuickCreateByCode(req.getCustomerCode());
GaoRegistrationEventRecordCreateReq recordReq = new GaoRegistrationEventRecordCreateReq();
recordReq.setCustomerIdList(List.of(customer.getId()));
recordReq.setRegistrationEventId(req.getRegistrationEventId());
recordReq.setRemark(req.getRemark());
recordReq.setAttachmentIdList(req.getAttachmentIdList());
GaoRegistrationEventRecord record = createRecords(recordReq).get(0);
logger.setLevel(Logger.Level.INFO);
logger.setResult(record.getId());
return record;
} 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("GAO 快速登记失败", e);
throw new TimiException(TimiCode.ERROR, "GAO 快速登记失败", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(GaoRegistrationEventRecord entity) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_REGISTRATION_EVENT_RECORD_UPDATE");
try {
logger.setContent(jackson.writeValueAsString(entity));
TimiException.required(entity, "not found record");
TimiException.required(entity.getId(), "not found record.id");
TimiException.required(entity.getCustomerId(), "not found record.customerId");
TimiException.required(entity.getRegistrationEventId(), "not found record.registrationEventId");
customerService.get(entity.getCustomerId());
GaoRegistrationEvent registrationEvent = registrationEventService.get(entity.getRegistrationEventId());
checkRegistrationEventPermission(registrationEvent);
entity.setRegisteredAt(TimiJava.defaultIfNull(entity.getRegisteredAt(), Time.now()));
super.update(entity);
saveAttachment(entity.getId(), resolveAttachmentList(entity));
logger.setLevel(Logger.Level.INFO);
logger.setResult(entity.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("修改 GAO 登记记录失败", e);
throw new TimiException(TimiCode.ERROR, "修改 GAO 登记记录失败", e);
} finally {
loggerService.create(logger);
}
}
@Override
public GaoRegistrationEventRecord get(String id) {
GaoRegistrationEventRecord record = super.get(id);
loadTransient(List.of(record));
return record;
}
@Override
public List<GaoRegistrationEventRecord> listByRegistrationEventAndPeriod(GaoRegistrationEventRecordPeriodReq req) {
TimiException.required(req, "not found req");
TimiException.required(req.getRegistrationEventId(), "not found req.registrationEventId");
TimiException.required(req.getPeriodType(), "not found req.periodType");
TimiException.required(req.getPeriodValue(), "not found req.periodValue");
List<GaoRegistrationEventRecord> list = mapper.selectByRegistrationEventAndPeriod(req.getRegistrationEventId(), req.getPeriodType(), req.getPeriodValue());
loadTransient(list);
return list;
}
@Override
public List<GaoRegistrationEventRecord> listByRange(GaoRegistrationEventRecordRangeReq req) {
TimiException.required(req, "not found req");
checkStatRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
List<GaoRegistrationEventRecord> list = mapper.selectByRange(req);
loadTransient(list);
return list;
}
@Override
public List<GaoRegistrationEventRecordCalendarView> listCalendarByRange(GaoRegistrationEventRecordRangeReq req) {
TimiException.required(req, "not found req");
checkStatRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
return mapper.selectCalendarByRange(req);
}
@Override
public PageResult<GaoRegistrationEventRecordListItemView> pageByRange(Page<GaoRegistrationEventRecordRangeReq> page) {
TimiException.required(page, "not found page");
TimiException.required(page.getIndex(), "not found page.index");
TimiException.required(page.getSize(), "not found page.size");
TimiException.requiredTrue(0 <= page.getIndex(), "page.index lt 0");
TimiException.requiredTrue(0 < page.getSize(), "page.size lte 0");
GaoRegistrationEventRecordRangeReq req = TimiJava.defaultIfNull(page.getEqualsExample(), new GaoRegistrationEventRecordRangeReq());
checkStatRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
Long total = TimiJava.defaultIfNull(mapper.countByRange(req), 0L);
List<GaoRegistrationEventRecordListItemView> list = mapper.selectPageByRange(req, page.getIndex() * page.getSize(), page.getSize());
PageResult<GaoRegistrationEventRecordListItemView> result = new PageResult<>();
result.setTotal(total);
result.setList(list);
return result;
}
@Override
public byte[] exportRangeExcel(GaoRegistrationEventRecordRangeReq req) throws IOException {
List<GaoRegistrationEventRecord> list = listByRange(req);
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("登记事件记录");
CellStyle titleStyle = workbook.createCellStyle();
Font titleFont = workbook.createFont();
titleFont.setBold(true);
titleFont.setFontHeightInPoints((short) 14);
titleStyle.setFont(titleFont);
CellStyle headerStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
appendRow(sheet, 0, titleStyle, "登记事件记录导出");
appendRow(sheet, 1, null, "生成时间", EXPORT_TIME_FORMATTER.format(Instant.now()));
appendRow(sheet, 2, null, "时间范围", "%s ~ %s".formatted(formatExportTime(req.getBeginRegisteredAt()), formatExportTime(req.getEndRegisteredAt())));
appendRow(sheet, 3, null, "事件筛选", buildEventFilterText(req));
appendRow(sheet, 4, null, "关键词", req.getKeyword() == null || req.getKeyword().isBlank() ? "全部" : req.getKeyword().trim());
appendRow(sheet, 5, null, "记录总数", String.valueOf(list.size()));
appendRow(sheet, 7, headerStyle, "客户编码", "客户姓名", "登记事件", "登记时间", "登记人", "备注");
int rowIndex = 8;
for (GaoRegistrationEventRecord record : list) {
appendRow(sheet, rowIndex, null,
record.getCustomer() == null ? "" : text(record.getCustomer().getCode()),
record.getCustomer() == null ? "" : text(record.getCustomer().getName()),
record.getRegistrationEvent() == null ? "" : text(record.getRegistrationEvent().getName()),
formatExportTime(record.getRegisteredAt()),
getOperatorName(record),
text(record.getRemark())
);
rowIndex++;
}
for (int index = 0; index < 6; index++) {
sheet.autoSizeColumn(index);
sheet.setColumnWidth(index, Math.min(Math.max(sheet.getColumnWidth(index), 12 * 256), 40 * 256));
}
workbook.write(output);
return output.toByteArray();
}
}
@Override
public List<GaoRegistrationEventPeriodStatView> statByRegistrationEventAndPeriodType(String registrationEventId, GaoRegistrationEventRecordPeriodReq.PeriodType periodType) {
TimiException.required(registrationEventId, "not found registrationEventId");
TimiException.required(periodType, "not found periodType");
return mapper.statByRegistrationEventAndPeriodType(registrationEventId, periodType);
}
@Override
public List<GaoRegistrationEventRecord> listLatestByCustomerIdListAndRegistrationEventId(List<String> customerIdList, String registrationEventId) {
TimiException.required(registrationEventId, "not found registrationEventId");
if (TimiJava.isEmpty(customerIdList)) {
return Collections.emptyList();
}
List<GaoRegistrationEventRecord> list = mapper.selectLatestByCustomerIdListAndRegistrationEventId(customerIdList, registrationEventId);
loadTransient(list);
return list;
}
@Override
public List<GaoCustomerRegisterStatView> statByCustomerId(String customerId) {
TimiException.required(customerId, "not found customerId");
return mapper.statByCustomerId(customerId);
}
@Override
public List<GaoCustomerRegisterStatView> statByCustomerAndRange(GaoRegistrationEventRecordStatReq req) {
TimiException.required(req, "not found req");
TimiException.required(req.getCustomerId(), "not found req.customerId");
checkStatRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
return mapper.statByCustomerIdAndRange(req.getCustomerId(), req.getBeginRegisteredAt(), req.getEndRegisteredAt());
}
@Override
public List<GaoCustomerRegisterStatView> statAllCustomerByRange(GaoRegistrationEventRecordStatReq req) {
TimiException.required(req, "not found req");
checkStatRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
return mapper.statAllCustomerByRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
}
@Override
public List<GaoCustomerRegistrationRankView> listCustomerRegistrationRank(GaoRegistrationEventRecordRangeReq req) {
GaoRegistrationEventRecordRangeReq rangeReq = TimiJava.defaultIfNull(req, new GaoRegistrationEventRecordRangeReq());
if (rangeReq.getBeginRegisteredAt() != null || rangeReq.getEndRegisteredAt() != null) {
checkStatRange(rangeReq.getBeginRegisteredAt(), rangeReq.getEndRegisteredAt());
}
List<GaoCustomerRegistrationDayStatView> dayStatList = mapper.statCustomerRegistrationDay(rangeReq);
Map<String, List<GaoCustomerRegistrationDayStatView>> customerDayStatMap = dayStatList.stream()
.collect(Collectors.groupingBy(GaoCustomerRegistrationDayStatView::getCustomerId));
List<GaoCustomerRegistrationRankView> rankList = new ArrayList<>();
for (Map.Entry<String, List<GaoCustomerRegistrationDayStatView>> entry : customerDayStatMap.entrySet()) {
rankList.add(buildCustomerRegistrationRank(entry.getValue()));
}
rankList.sort(Comparator
.comparing(GaoCustomerRegistrationRankView::getTotalRegistrationDays, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(GaoCustomerRegistrationRankView::getTotalRegistrationCount, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(GaoCustomerRegistrationRankView::getLatestRegisteredAt, Comparator.nullsLast(Comparator.reverseOrder())));
for (int index = 0; index < rankList.size(); index++) {
rankList.get(index).setRank(index + 1);
}
return rankList;
}
@Override
public List<GaoRegistrationEventRecordDailyStatView> statDailyByCustomerAndRegistrationEvent(GaoRegistrationEventRecordTrendStatReq req) {
TimiException.required(req, "not found req");
TimiException.required(req.getCustomerId(), "not found req.customerId");
customerService.get(req.getCustomerId());
return buildDailyTrend(req, true);
}
@Override
public List<GaoRegistrationEventRecordDailyStatView> statDailyByRegistrationEvent(GaoRegistrationEventRecordTrendStatReq req) {
TimiException.required(req, "not found req");
return buildDailyTrend(req, false);
}
@Override
public List<GaoRegistrationEventRecord> listLatestByCustomerId(String customerId) {
TimiException.required(customerId, "not found customerId");
List<GaoRegistrationEventRecord> list = mapper.selectLatestByCustomerId(customerId);
loadTransient(list);
return list;
}
private String resolveCustomerId(String customerId) {
TimiException.required(customerId, "not found customerId");
customerService.get(customerId);
return customerId;
}
private GaoRegistrationEventRecord doCreateRecord(GaoRegistrationEventRecordCreateReq req, String customerId) {
TimiException.required(req, "not found req");
TimiException.required(req.getRegistrationEventId(), "not found req.registrationEventId");
customerId = resolveCustomerId(customerId);
GaoRegistrationEvent registrationEvent = registrationEventService.get(req.getRegistrationEventId());
checkRegistrationEventPermission(registrationEvent);
long registeredAt = TimiJava.defaultIfNull(req.getRegisteredAt(), Time.now());
checkRegistrationEventCreatable(registrationEvent, customerId, registeredAt);
if (Boolean.TRUE.equals(registrationEvent.getRequirePhoto())) {
TimiException.requiredTrue(req.getAttachmentIdList() != null && !req.getAttachmentIdList().isEmpty(), "required record photo");
}
GaoRegistrationEventRecord record = new GaoRegistrationEventRecord();
record.setCustomerId(customerId);
record.setRegistrationEventId(req.getRegistrationEventId());
record.setOperatorUserId(userLoginService.getRequireLoginUserId());
record.setRemark(req.getRemark());
record.setRegisteredAt(registeredAt);
super.create(record);
saveAttachment(record.getId(), buildPhotoAttachmentList(req.getAttachmentIdList()));
return get(record.getId());
}
private void checkRegistrationEventPermission(GaoRegistrationEvent registrationEvent) {
List<String> roleCodeList = registrationEventService.listRoleCode(registrationEvent.getId());
TimiException.requiredTrue(roleCodeList != null && !roleCodeList.isEmpty(), "登记事件未配置可登记角色");
roleChecker.checkAny(ModuleCode.GAO, roleCodeList.toArray(String[]::new));
}
private void checkRegistrationEventCreatable(GaoRegistrationEvent registrationEvent, String customerId, long registeredAt) {
TimiException.requiredTrue(registrationEvent.getStatus() == null || registrationEvent.getStatus() == GaoRegistrationEvent.Status.ACTIVE, "登记事件不可登记");
TimiException.requiredTrue(registrationEvent.getBeginAt() == null || registrationEvent.getBeginAt() <= registeredAt, "登记事件未到可登记时间");
TimiException.requiredTrue(registrationEvent.getEndAt() == null || registeredAt <= registrationEvent.getEndAt(), "登记事件已过可登记时间");
GaoRegistrationEvent.LimitType limitType = TimiJava.defaultIfNull(registrationEvent.getLimitType(), GaoRegistrationEvent.LimitType.NONE);
switch (limitType) {
case DAILY_HALF_DAY -> checkRegistrationLimitRange(customerId, registrationEvent.getId(), getHalfDayBegin(registeredAt), getHalfDayEnd(registeredAt), "该客户当前半日已登记该事件");
case NATURAL_DAY -> checkRegistrationLimitRange(customerId, registrationEvent.getId(), getDayBegin(registeredAt), getDayEnd(registeredAt), "该客户当日已登记该事件");
case INTERVAL_HOUR -> checkIntervalHourRegistrationLimit(registrationEvent, customerId, registeredAt);
case NATURAL_MONTH -> checkRegistrationLimitRange(customerId, registrationEvent.getId(), getMonthBegin(registeredAt), getMonthEnd(registeredAt), "该客户当月已登记该事件");
case TOTAL_LIMIT -> checkTotalRegistrationLimit(registrationEvent);
case CUSTOMER_TOTAL_LIMIT -> checkCustomerTotalRegistrationLimit(registrationEvent, customerId);
default -> {
}
}
}
private void checkRegistrationLimitRange(String customerId, String registrationEventId, long beginRegisteredAt, long endRegisteredAt, String message) {
Long count = mapper.countByCustomerIdAndRegistrationEventIdRange(customerId, registrationEventId, beginRegisteredAt, endRegisteredAt);
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < 1, message);
}
private void checkIntervalHourRegistrationLimit(GaoRegistrationEvent registrationEvent, String customerId, long registeredAt) {
Integer limitValue = registrationEvent.getLimitValue();
TimiException.requiredTrue(limitValue != null && 0 < limitValue, "登记事件间隔小时配置错误");
long beginRegisteredAt = registeredAt - limitValue * 60L * 60L * 1000L + 1;
checkRegistrationLimitRange(customerId, registrationEvent.getId(), beginRegisteredAt, registeredAt, "该客户登记该事件间隔不足");
}
private void checkCustomerTotalRegistrationLimit(GaoRegistrationEvent registrationEvent, String customerId) {
Integer limitValue = registrationEvent.getLimitValue();
TimiException.requiredTrue(limitValue != null && 0 < limitValue, "登记事件单客户总次数配置错误");
Long count = mapper.countByCustomerIdAndRegistrationEventId(customerId, registrationEvent.getId());
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < limitValue, "该客户登记该事件次数已达上限");
}
private void checkTotalRegistrationLimit(GaoRegistrationEvent registrationEvent) {
Integer limitValue = registrationEvent.getLimitValue();
TimiException.requiredTrue(limitValue != null && 0 < limitValue, "登记事件总次数配置错误");
Long count = mapper.countByRegistrationEventId(registrationEvent.getId());
TimiException.requiredTrue(TimiJava.defaultIfNull(count, 0L) < limitValue, "登记事件总次数已达上限");
}
private long getDayBegin(long registeredAt) {
ZoneId zoneId = ZoneId.systemDefault();
return Instant.ofEpochMilli(registeredAt).atZone(zoneId).toLocalDate().atStartOfDay(zoneId).toInstant().toEpochMilli();
}
private long getDayEnd(long registeredAt) {
ZoneId zoneId = ZoneId.systemDefault();
return Instant.ofEpochMilli(registeredAt).atZone(zoneId).toLocalDate().plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1;
}
private long getHalfDayBegin(long registeredAt) {
ZoneId zoneId = ZoneId.systemDefault();
int hour = Instant.ofEpochMilli(registeredAt).atZone(zoneId).getHour();
long dayBegin = getDayBegin(registeredAt);
return hour < 12 ? dayBegin : dayBegin + 12L * 60L * 60L * 1000L;
}
private long getHalfDayEnd(long registeredAt) {
ZoneId zoneId = ZoneId.systemDefault();
int hour = Instant.ofEpochMilli(registeredAt).atZone(zoneId).getHour();
long dayBegin = getDayBegin(registeredAt);
return hour < 12 ? dayBegin + 12L * 60L * 60L * 1000L - 1 : getDayEnd(registeredAt);
}
private long getMonthBegin(long registeredAt) {
ZoneId zoneId = ZoneId.systemDefault();
LocalDate date = Instant.ofEpochMilli(registeredAt).atZone(zoneId).toLocalDate();
return date.withDayOfMonth(1).atStartOfDay(zoneId).toInstant().toEpochMilli();
}
private long getMonthEnd(long registeredAt) {
ZoneId zoneId = ZoneId.systemDefault();
LocalDate date = Instant.ofEpochMilli(registeredAt).atZone(zoneId).toLocalDate();
return date.withDayOfMonth(1).plusMonths(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1;
}
private void checkStatRange(Long beginRegisteredAt, Long endRegisteredAt) {
TimiException.required(beginRegisteredAt, "not found beginRegisteredAt");
TimiException.required(endRegisteredAt, "not found endRegisteredAt");
TimiException.requiredTrue(endRegisteredAt >= beginRegisteredAt, "endRegisteredAt lt beginRegisteredAt");
}
private List<GaoRegistrationEventRecordDailyStatView> buildDailyTrend(GaoRegistrationEventRecordTrendStatReq req, boolean byCustomer) {
TimiException.required(req.getRegistrationEventId(), "not found req.registrationEventId");
registrationEventService.get(req.getRegistrationEventId());
checkStatRange(req.getBeginRegisteredAt(), req.getEndRegisteredAt());
ZoneId zoneId = ZoneId.systemDefault();
LocalDate beginDate = Instant.ofEpochMilli(req.getBeginRegisteredAt()).atZone(zoneId).toLocalDate();
LocalDate endDate = Instant.ofEpochMilli(req.getEndRegisteredAt()).atZone(zoneId).toLocalDate();
checkDailyStatRange(beginDate, endDate);
long beginRegisteredAt = beginDate.atStartOfDay(zoneId).toInstant().toEpochMilli();
long endRegisteredAt = endDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1;
Map<Integer, Long> dailyCountMap = new HashMap<>();
List<GaoRegistrationEventRecordDailyStatView> dbList = byCustomer
? mapper.statDailyCountByCustomerIdAndRegistrationEventIdRange(req.getCustomerId(), req.getRegistrationEventId(), beginRegisteredAt, endRegisteredAt)
: mapper.statDailyCountByRegistrationEventIdRange(req.getRegistrationEventId(), beginRegisteredAt, endRegisteredAt);
for (GaoRegistrationEventRecordDailyStatView view : dbList) {
dailyCountMap.put(view.getDateValue(), TimiJava.defaultIfNull(view.getDailyCount(), 0L));
}
long totalCount = byCustomer
? TimiJava.defaultIfNull(mapper.countBeforeByCustomerIdAndRegistrationEventId(req.getCustomerId(), req.getRegistrationEventId(), beginRegisteredAt), 0L)
: TimiJava.defaultIfNull(mapper.countBeforeByRegistrationEventId(req.getRegistrationEventId(), beginRegisteredAt), 0L);
List<GaoRegistrationEventRecordDailyStatView> list = new ArrayList<>();
for (LocalDate date = beginDate; !date.isAfter(endDate); date = date.plusDays(1)) {
int dateValue = Integer.parseInt(DAY_FORMATTER.format(date));
long dailyCount = TimiJava.defaultIfNull(dailyCountMap.get(dateValue), 0L);
totalCount += dailyCount;
GaoRegistrationEventRecordDailyStatView view = new GaoRegistrationEventRecordDailyStatView();
view.setDateValue(dateValue);
view.setDailyCount(dailyCount);
view.setTotalCount(totalCount);
list.add(view);
}
return list;
}
private GaoCustomerRegistrationRankView buildCustomerRegistrationRank(List<GaoCustomerRegistrationDayStatView> dayStatList) {
List<GaoCustomerRegistrationDayStatView> sortedDayStatList = dayStatList.stream()
.sorted(Comparator.comparing(GaoCustomerRegistrationDayStatView::getDateValue, Comparator.nullsLast(Comparator.reverseOrder())))
.toList();
GaoCustomerRegistrationDayStatView first = sortedDayStatList.get(0);
GaoCustomerRegistrationRankView view = new GaoCustomerRegistrationRankView();
view.setCustomerId(first.getCustomerId());
view.setCustomerCode(first.getCustomerCode());
view.setCustomerName(first.getCustomerName());
view.setCustomerPhotoAttachmentId(first.getCustomerPhotoAttachmentId());
view.setTotalRegistrationDays((long) sortedDayStatList.size());
view.setTotalRegistrationCount(sortedDayStatList.stream().mapToLong(item -> TimiJava.defaultIfNull(item.getDailyCount(), 0L)).sum());
view.setLatestRegisteredAt(sortedDayStatList.stream().map(GaoCustomerRegistrationDayStatView::getLatestRegisteredAt).filter(Objects::nonNull).max(Long::compareTo).orElse(null));
view.setRecentContinuousRegistrationDays(countRecentContinuousRegistrationDays(sortedDayStatList));
return view;
}
private long countRecentContinuousRegistrationDays(List<GaoCustomerRegistrationDayStatView> sortedDayStatList) {
if (sortedDayStatList.isEmpty() || sortedDayStatList.get(0).getDateValue() == null) {
return 0;
}
LocalDate expectedDate = LocalDate.parse(String.valueOf(sortedDayStatList.get(0).getDateValue()), DAY_FORMATTER);
long count = 0;
for (GaoCustomerRegistrationDayStatView item : sortedDayStatList) {
if (item.getDateValue() == null) {
continue;
}
LocalDate date = LocalDate.parse(String.valueOf(item.getDateValue()), DAY_FORMATTER);
if (!date.equals(expectedDate)) {
break;
}
count++;
expectedDate = expectedDate.minusDays(1);
}
return count;
}
private void loadTransient(List<GaoRegistrationEventRecord> recordList) {
if (recordList == null || recordList.isEmpty()) {
return;
}
List<String> customerIdList = recordList.stream()
.map(GaoRegistrationEventRecord::getCustomerId)
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
Map<String, GaoCustomer> customerMap = customerMapper.selectByIdList(new ArrayList<>(customerIdList)).stream()
.collect(Collectors.toMap(GaoCustomer::getId, Function.identity(), (left, right) -> left));
List<String> registrationEventIdList = recordList.stream()
.map(GaoRegistrationEventRecord::getRegistrationEventId)
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
Map<String, GaoRegistrationEvent> registrationEventMap = registrationEventMapper.selectByIdList(new ArrayList<>(registrationEventIdList)).stream()
.collect(Collectors.toMap(GaoRegistrationEvent::getId, Function.identity(), (left, right) -> left));
List<String> operatorUserIdList = recordList.stream()
.map(GaoRegistrationEventRecord::getOperatorUserId)
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
Map<String, com.imyeyu.api.modules.user.entity.User> userMap = userMapper.listByIdList(new ArrayList<>(operatorUserIdList)).stream()
.collect(Collectors.toMap(com.imyeyu.api.modules.user.entity.User::getId, Function.identity(), (left, right) -> left));
List<String> recordIdList = recordList.stream()
.map(GaoRegistrationEventRecord::getId)
.filter(TimiJava::isNotEmpty)
.distinct()
.toList();
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(
Attachment.BizType.GAO_REGISTRATION_EVENT_RECORD,
recordIdList,
GaoRegistrationEventRecord.AttachType.PHOTO.name()
);
for (GaoRegistrationEventRecord record : recordList) {
record.setCustomer(customerMap.get(record.getCustomerId()));
record.setRegistrationEvent(registrationEventMap.get(record.getRegistrationEventId()));
record.setOperator(userMap.get(record.getOperatorUserId()));
record.setAttachmentList(attachmentMap.getOrDefault(record.getId(), List.of()));
}
}
private void checkDailyStatRange(LocalDate beginDate, LocalDate endDate) {
long days = ChronoUnit.DAYS.between(beginDate, endDate) + 1;
TimiException.requiredTrue(days <= 366, "daily stat range too large");
}
private void saveAttachment(String recordId, List<Attachment> attachmentList) {
if (attachmentList == null) {
return;
}
for (Attachment attachment : attachmentList) {
attachment.setBizType(Attachment.BizType.GAO_REGISTRATION_EVENT_RECORD);
attachment.setBizId(recordId);
attachment.setAttachType(GaoRegistrationEventRecord.AttachType.PHOTO.name());
}
BizUpdateReq req = new BizUpdateReq();
req.setBizType(Attachment.BizType.GAO_REGISTRATION_EVENT_RECORD);
req.setBizId(recordId);
req.setItems(attachmentList);
attachmentService.updateByBiz(req);
}
private List<Attachment> resolveAttachmentList(GaoRegistrationEventRecord record) {
if (record.getAttachmentIdList() != null) {
return buildPhotoAttachmentList(record.getAttachmentIdList());
}
return record.getAttachmentList();
}
private List<Attachment> buildPhotoAttachmentList(List<String> attachmentIdList) {
if (attachmentIdList == null) {
return null;
}
List<Attachment> list = new ArrayList<>();
for (String attachmentId : attachmentIdList) {
if (attachmentId == null || attachmentId.isBlank()) {
continue;
}
Attachment attachment = new Attachment();
attachment.setTempFileId(attachmentId.trim());
attachment.setAttachType(GaoRegistrationEventRecord.AttachType.PHOTO.name());
list.add(attachment);
}
return list;
}
private void appendRow(Sheet sheet, int rowIndex, CellStyle style, String... values) {
Row row = sheet.createRow(rowIndex);
for (int index = 0; index < values.length; index++) {
row.createCell(index).setCellValue(values[index]);
if (style != null) {
row.getCell(index).setCellStyle(style);
}
}
}
private String buildEventFilterText(GaoRegistrationEventRecordRangeReq req) {
if ((req.getRegistrationEventId() == null || req.getRegistrationEventId().isBlank()) && (req.getRegistrationEventIdList() == null || req.getRegistrationEventIdList().isEmpty())) {
return "全部事件";
}
if (req.getRegistrationEventId() != null && !req.getRegistrationEventId().isBlank()) {
return "事件 ID" + req.getRegistrationEventId();
}
StringJoiner joiner = new StringJoiner("");
req.getRegistrationEventIdList().stream()
.filter(Objects::nonNull)
.filter(item -> !item.isBlank())
.forEach(joiner::add);
return "事件 ID" + joiner;
}
private String formatExportTime(Long value) {
if (value == null) {
return "";
}
return EXPORT_TIME_FORMATTER.format(Instant.ofEpochMilli(value));
}
private String getOperatorName(GaoRegistrationEventRecord record) {
if (record.getOperator() == null) {
return text(record.getOperatorUserId());
}
if (record.getOperator().getNick() != null && !record.getOperator().getNick().isBlank()) {
return record.getOperator().getNick();
}
if (record.getOperator().getName() != null && !record.getOperator().getName().isBlank()) {
return record.getOperator().getName();
}
return text(record.getOperatorUserId());
}
private String text(Object value) {
return value == null ? "" : value.toString();
}
}
@@ -1,260 +0,0 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent;
import com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRoleRelation;
import com.imyeyu.api.modules.gao.mapper.GaoRegistrationEventMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRegistrationEventRoleRelationMapper;
import com.imyeyu.api.modules.gao.service.GaoRegistrationEventService;
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.bean.Page;
import com.imyeyu.spring.bean.PageResult;
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;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
///
/// 登记事件服务实现
///
/// @author 夜雨
/// @since 2026-07-27 09:00
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoRegistrationEventServiceImplement extends AbstractEntityService<GaoRegistrationEvent, String> implements GaoRegistrationEventService {
private final ObjectMapper jackson;
private final LoggerService loggerService;
private final GaoRegistrationEventMapper mapper;
private final GaoRegistrationEventRoleRelationMapper roleRelationMapper;
@Override
protected BaseMapper<GaoRegistrationEvent, String> mapper() {
return mapper;
}
@Override
public PageResult<GaoRegistrationEvent> pageWithRegistrationEventLimit(Page<GaoRegistrationEvent> page) {
PageResult<GaoRegistrationEvent> result = page(page);
result.setList(result.getList().stream().filter(item -> item.getStatus() != GaoRegistrationEvent.Status.DELETED).toList());
loadRegistrationEventLimit(result.getList());
return result;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(GaoRegistrationEvent entity) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_REGISTRATION_EVENT_CREATE");
try {
logger.setContent(jackson.writeValueAsString(entity));
checkEntity(entity, false);
super.create(entity);
saveRoleRelation(entity.getId(), entity.getRoleCodeList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(entity.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("新增 GAO 登记事件失败", e);
throw new TimiException(TimiCode.ERROR, "新增 GAO 登记事件失败", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void update(GaoRegistrationEvent entity) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_REGISTRATION_EVENT_UPDATE");
try {
logger.setContent(jackson.writeValueAsString(entity));
Integer sort = entity.getSort();
checkEntity(entity, true);
GaoRegistrationEvent current = get(entity.getId());
current.setName(entity.getName());
current.setDescription(entity.getDescription());
current.setColor(entity.getColor());
current.setStatus(entity.getStatus());
current.setRequirePhoto(entity.getRequirePhoto());
current.setLimitType(entity.getLimitType());
current.setLimitValue(entity.getLimitValue());
current.setBeginAt(entity.getBeginAt());
current.setEndAt(entity.getEndAt());
if (sort != null) {
current.setSort(sort);
}
mapper.update(current);
saveRoleRelation(entity.getId(), entity.getRoleCodeList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(entity.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("修改 GAO 登记事件失败", e);
throw new TimiException(TimiCode.ERROR, "修改 GAO 登记事件失败", e);
} finally {
loggerService.create(logger);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void delete(String id) {
Logger logger = new Logger(Logger.Module.GAO, "GAO_REGISTRATION_EVENT_DELETE");
try {
logger.setContent(id);
GaoRegistrationEvent entity = get(id);
entity.setStatus(GaoRegistrationEvent.Status.DELETED);
super.update(entity);
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("删除 GAO 登记事件失败", e);
throw new TimiException(TimiCode.ERROR, "删除 GAO 登记事件失败", e);
} finally {
loggerService.create(logger);
}
}
@Override
public GaoRegistrationEvent get(String id) {
GaoRegistrationEvent registrationEvent = super.get(id);
registrationEvent.setRoleCodeList(roleRelationMapper.selectRoleCodeListByRegistrationEventId(id));
return registrationEvent;
}
@Override
public List<GaoRegistrationEvent> listEnabled() {
List<GaoRegistrationEvent> list = mapper.selectEnabledList(Time.now());
loadRegistrationEventLimit(list);
list = list.stream().filter(item -> !TimiJava.isEmpty(item.getRoleCodeList())).toList();
return list;
}
@Override
public List<String> listRoleCode(String registrationEventId) {
return roleRelationMapper.selectRoleCodeListByRegistrationEventId(registrationEventId);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void sort(List<String> idList) {
if (idList == null || idList.isEmpty()) {
return;
}
List<String> distinctIdList = new ArrayList<>(new LinkedHashSet<>(idList));
Map<String, GaoRegistrationEvent> eventMap = mapper.selectByIdList(distinctIdList).stream().collect(Collectors.toMap(GaoRegistrationEvent::getId, item -> item));
TimiException.requiredTrue(eventMap.size() == distinctIdList.size(), "not found registrationEvent");
for (int index = 0; index < distinctIdList.size(); index++) {
GaoRegistrationEvent registrationEvent = eventMap.get(distinctIdList.get(index));
registrationEvent.setSort(index);
mapper.update(registrationEvent);
}
}
private void checkEntity(GaoRegistrationEvent entity, boolean requireId) {
TimiException.required(entity, "not found registrationEvent");
if (requireId) {
TimiException.required(entity.getId(), "not found registrationEvent.id");
}
TimiException.required(entity.getName(), "not found registrationEvent.name");
if (entity.getStatus() == null) {
entity.setStatus(GaoRegistrationEvent.Status.ACTIVE);
}
if (entity.getRequirePhoto() == null) {
entity.setRequirePhoto(false);
}
if (entity.getLimitType() == null) {
entity.setLimitType(GaoRegistrationEvent.LimitType.NONE);
}
TimiException.requiredTrue(entity.getRoleCodeList() != null && entity.getRoleCodeList()
.stream()
.anyMatch(item -> item != null && !item.isBlank()), "not found registrationEvent.roleCodeList");
checkRegistrationLimit(entity);
checkRegisterablePeriod(entity);
if (entity.getColor() != null) {
entity.setColor(entity.getColor().trim());
}
if (entity.getSort() == null) {
entity.setSort(0);
}
}
private void checkRegistrationLimit(GaoRegistrationEvent entity) {
if (entity.getLimitType() == GaoRegistrationEvent.LimitType.INTERVAL_HOUR || entity.getLimitType() == GaoRegistrationEvent.LimitType.TOTAL_LIMIT || entity.getLimitType() == GaoRegistrationEvent.LimitType.CUSTOMER_TOTAL_LIMIT) {
TimiException.required(entity.getLimitValue(), "not found registrationEvent.limitValue");
TimiException.requiredTrue(0 < entity.getLimitValue(), "registrationEvent.limitValue lte 0");
return;
}
entity.setLimitValue(null);
}
private void checkRegisterablePeriod(GaoRegistrationEvent entity) {
if (entity.getBeginAt() == null && entity.getEndAt() == null) {
return;
}
TimiException.requiredTrue(entity.getBeginAt() == null || entity.getEndAt() == null || entity.getBeginAt() <= entity.getEndAt(), "registrationEvent.beginAt gt registrationEvent.endAt");
}
private void saveRoleRelation(String registrationEventId, List<String> roleCodeList) {
roleRelationMapper.deleteByRegistrationEventId(registrationEventId);
if (roleCodeList == null || roleCodeList.isEmpty()) {
return;
}
Set<String> distinctCodeSet = new LinkedHashSet<>(roleCodeList);
for (String roleCode : distinctCodeSet) {
if (roleCode == null || roleCode.isBlank()) {
continue;
}
GaoRegistrationEventRoleRelation relation = new GaoRegistrationEventRoleRelation();
relation.setRegistrationEventId(registrationEventId);
relation.setRoleCode(roleCode.trim());
roleRelationMapper.insert(relation);
}
}
private void loadRegistrationEventLimit(List<GaoRegistrationEvent> registrationEventList) {
if (registrationEventList == null || registrationEventList.isEmpty()) {
return;
}
List<String> registrationEventIdList = registrationEventList.stream().map(GaoRegistrationEvent::getId).distinct().toList();
Map<String, List<String>> roleCodeMap = roleRelationMapper.selectByRegistrationEventIdList(new ArrayList<>(registrationEventIdList))
.stream()
.collect(Collectors.groupingBy(GaoRegistrationEventRoleRelation::getRegistrationEventId, Collectors.mapping(GaoRegistrationEventRoleRelation::getRoleCode, Collectors.toList())));
for (GaoRegistrationEvent registrationEvent : registrationEventList) {
registrationEvent.setRoleCodeList(roleCodeMap.getOrDefault(registrationEvent.getId(), List.of()));
}
}
}
@@ -0,0 +1,67 @@
package com.imyeyu.api.modules.gao.util;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.util.BaseXSSFBuilder;
import com.imyeyu.utils.Time;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
///
///
/// @author 夜雨
/// @since 2026-08-04 15:59
@Component
public class CustomerXSSFBuilder extends BaseXSSFBuilder<GaoCustomer> {
public byte[] build(List<GaoCustomer> list) throws IOException {
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("客户列表");
CellStyle titleStyle = createTitleStyle(workbook);
CellStyle headerStyle = createHeaderStyle(workbook);
appendRow(sheet, 0, titleStyle, "客户列表导出");
appendRow(sheet, 1, null, "生成时间", Time.nowString());
appendRow(sheet, 2, null, "记录总数", String.valueOf(list.size()));
appendRow(sheet, 3, headerStyle, "客户编码", "姓名", "性别", "出生日期(公历)", "出生日期历法", "年龄", "电话", "地址", "病症", "备注", "邀请人", "邀请客户数", "创建时间");
int rowIndex = 4;
for (GaoCustomer customer : list) {
appendRow(sheet, rowIndex, null,
text(customer.getCode()),
text(customer.getName()),
gender(customer.getGender()),
text(customer.getBirthdate()),
formatBirthdateCalendar(customer),
customer.getAge() == null ? "" : String.valueOf(customer.getAge()),
text(customer.getTelephone()),
text(customer.getAddress()),
text(customer.getDisease()),
text(customer.getRemark()),
customer.getIntroducerCustomer() == null ? "" : text(customer.getIntroducerCustomer().getName()),
String.valueOf(customer.getInvitedCount()),
Time.toDateTime(customer.getCreatedAt())
);
rowIndex++;
}
for (int index = 0; index < 13; index++) {
sheet.autoSizeColumn(index);
sheet.setColumnWidth(index, Math.clamp(sheet.getColumnWidth(index), 10 * 256, 36 * 256));
}
workbook.write(output);
return output.toByteArray();
}
}
private String formatBirthdateCalendar(GaoCustomer customer) {
if (customer.getBirthdateCalendar() == null) {
return "公历";
}
return customer.getBirthdateCalendar() == GaoCustomer.BirthdateCalendar.LUNAR ? "农历" : "公历";
}
}
@@ -0,0 +1,53 @@
package com.imyeyu.api.modules.gao.util;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.util.BaseXSSFBuilder;
import com.imyeyu.utils.Time;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
///
///
/// @author 夜雨
/// @since 2026-08-05 11:03
@Component
public class EventRecordXSSFBuilder extends BaseXSSFBuilder<GaoEventRecord> {
public byte[] build(List<GaoEventRecord> list) throws IOException {
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("登记事件记录");
CellStyle titleStyle = createTitleStyle(workbook);
CellStyle headerStyle = createHeaderStyle(workbook);
appendRow(sheet, 0, titleStyle, "登记事件记录导出");
appendRow(sheet, 1, null, "生成时间", Time.nowString());
appendRow(sheet, 2, null, "记录总数", String.valueOf(list.size()));
appendRow(sheet, 3, headerStyle, "客户编码", "客户姓名", "登记事件", "登记时间", "登记人", "备注");
int rowIndex = 4;
for (GaoEventRecord record : list) {
appendRow(sheet, rowIndex, null,
record.getCustomer() == null ? "" : text(record.getCustomer().getCode()),
record.getCustomer() == null ? "" : text(record.getCustomer().getName()),
record.getEvent() == null ? "" : text(record.getEvent().getName()),
Time.toDateTime(record.getRegisteredAt()),
record.getOperator().getName(),
text(record.getRemark())
);
rowIndex++;
}
for (int i = 0; i < 6; i++) {
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, Math.clamp(sheet.getColumnWidth(i), 12 * 256, 40 * 256));
}
workbook.write(output);
return output.toByteArray();
}
}
}
@@ -8,7 +8,7 @@ import lombok.Data;
/// @author Codex /// @author Codex
/// @since 2026-07-28 /// @since 2026-07-28
@Data @Data
public class GaoCustomerDailyStatView { public class GaoCustomerDailyStateView {
/// 日期值格式为 yyyyMMdd /// 日期值格式为 yyyyMMdd
private Integer dateValue; private Integer dateValue;
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.gao.vo; package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import lombok.Data; import lombok.Data;
/// ///
@@ -8,7 +9,7 @@ import lombok.Data;
/// @author Codex /// @author Codex
/// @since 2026-08-03 /// @since 2026-08-03
@Data @Data
public class GaoCustomerRegistrationRankView { public class GaoCustomerEventRankView {
/// 排名 /// 排名
private Integer rank; private Integer rank;
@@ -16,23 +17,17 @@ public class GaoCustomerRegistrationRankView {
/// 客户 ID /// 客户 ID
private String customerId; private String customerId;
/// 客户编码 /// 客户
private String customerCode; private GaoCustomer customer;
/// 客户姓名
private String customerName;
/// 客户头像附件 ID
private String customerPhotoAttachmentId;
/// 累计登记天数 /// 累计登记天数
private Long totalRegistrationDays; private Long totalEventDays;
/// 累计登记次数 /// 累计登记次数
private Long totalRegistrationCount; private Long totalEventCount;
/// 最近连续登记天数 /// 最近连续登记天数
private Long recentContinuousRegistrationDays; private Long recentContinuousEventDays;
/// 最后登记时间 /// 最后登记时间
private Long latestRegisteredAt; private Long latestRegisteredAt;
@@ -1,18 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 客户邀请关系更新请求
///
/// @author Codex
/// @since 2026-07-27
@Data
public class GaoCustomerInviteUpdateReq {
/// 客户 ID
private String customerId;
/// 介绍人客户 ID
private String introducerCustomerId;
}
@@ -1,30 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 客户登记统计视图
///
/// @author Codex
/// @since 2026-07-27
@Data
public class GaoCustomerRegisterStatView {
/// 客户 ID
private String customerId;
/// 客户姓名
private String customerName;
/// 登记事件 ID
private String registrationEventId;
/// 登记事件名称
private String registrationEventName;
/// 数量
private Long count;
/// 最后登记时间
private Long latestRegisteredAt;
}
@@ -1,33 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 客户登记日期统计视图
///
/// @author Codex
/// @since 2026-08-03
@Data
public class GaoCustomerRegistrationDayStatView {
/// 客户 ID
private String customerId;
/// 客户编码
private String customerCode;
/// 客户姓名
private String customerName;
/// 客户头像附件 ID
private String customerPhotoAttachmentId;
/// 登记日期,格式 yyyyMMdd
private Integer dateValue;
/// 当日登记次数
private Long dailyCount;
/// 当日最后登记时间
private Long latestRegisteredAt;
}
@@ -1,18 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 客户搜索请求
///
/// @author Codex
/// @since 2026-07-27
@Data
public class GaoCustomerSearchReq {
/// 关键字,匹配编码、姓名、手机号、电话、住址、病症、条例部位
private String keyword;
/// 介绍人客户 ID
private String introducerCustomerId;
}
@@ -8,7 +8,7 @@ import lombok.Data;
/// @author Codex /// @author Codex
/// @since 2026-07-28 /// @since 2026-07-28
@Data @Data
public class GaoCustomerTrendStatReq { public class GaoCustomerTrendStateReq {
/// 开始创建时间 /// 开始创建时间
private Long beginCreatedAt; private Long beginCreatedAt;
@@ -1,32 +1,32 @@
package com.imyeyu.api.modules.gao.vo; package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.java.bean.BasePage;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List; import java.util.List;
/// ///
/// 登记事件记录范围查询请求 /// 登记事件记录范围查询请求
/// ///
/// @author Codex /// @author 夜雨
/// @since 2026-07-28 /// @since 2026-07-28 11:01
@Data @Data
public class GaoRegistrationEventRecordRangeReq { @EqualsAndHashCode(callSuper = true)
public class GaoEventRecordPage extends BasePage {
/// 客户 ID为空查询全部客户 /// 客户 ID为空查询全部客户
private String customerId; private String customerId;
/// 登记事件 ID为空查询全部登记事件
private String registrationEventId;
/// 登记事件 ID 列表为空查询全部登记事件 /// 登记事件 ID 列表为空查询全部登记事件
private List<String> registrationEventIdList; private List<String> eventIdList;
/// 关键词匹配客户登记事件备注登记人 /// 关键词匹配客户登记事件备注登记人
private String keyword; private String keyword;
/// 开始登记时间 /// 开始登记时间
private Long beginRegisteredAt; private Long beginAt;
/// 结束登记时间 /// 结束登记时间
private Long endRegisteredAt; private Long endAt;
} }
@@ -0,0 +1,28 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.java.bean.BasePage;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
///
///
/// @author 夜雨
/// @since 2026-08-05 12:44
@Data
@EqualsAndHashCode(callSuper = true)
public class GaoEventRecordRankPage extends BasePage {
/// 客户 ID,为空查询全部客户
private String customerId;
/// 登记事件 ID 列表,为空查询全部登记事件
private List<String> eventIdList;
/// 开始登记时间
private Long beginAt;
/// 结束登记时间
private Long endAt;
}
@@ -1,27 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
///
/// 快速录入并登记请求
///
/// @author Codex
/// @since 2026-07-28
@Data
public class GaoQuickRegistrationEventRecordReq {
/// 客户编码
private String customerCode;
/// 登记登记事件 ID
private String registrationEventId;
/// 备注
private String remark;
/// 临时照片附件 ID 列表
private List<String> attachmentIdList = new ArrayList<>();
}
@@ -1,21 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件周期统计视图
///
/// @author Codex
/// @since 2026-07-27
@Data
public class GaoRegistrationEventPeriodStatView {
/// 登记事件 ID
private String registrationEventId;
/// 周期值
private Integer periodValue;
/// 数量
private Long count;
}
@@ -1,30 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件记录日历轻量视图
///
/// @author Codex
/// @since 2026-08-01
@Data
public class GaoRegistrationEventRecordCalendarView {
/// 记录 ID
private String id;
/// 客户 ID
private String customerId;
/// 客户编码
private String customerCode;
/// 客户姓名
private String customerName;
/// 登记事件 ID
private String registrationEventId;
/// 登记时间
private Long registeredAt;
}
@@ -1,30 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
///
/// 登记登记事件记录创建请求
///
/// @author Codex
/// @since 2026-07-27
@Data
public class GaoRegistrationEventRecordCreateReq {
/// 客户 ID 列表,批量登记时使用
private List<String> customerIdList = new ArrayList<>();
/// 登记事件 ID
private String registrationEventId;
/// 备注
private String remark;
/// 登记时间
private Long registeredAt;
/// 临时照片附件 ID 列表
private List<String> attachmentIdList = new ArrayList<>();
}
@@ -1,21 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件记录每日统计视图
///
/// @author Codex
/// @since 2026-07-28
@Data
public class GaoRegistrationEventRecordDailyStatView {
/// 日期值,格式为 yyyyMMdd
private Integer dateValue;
/// 当日登记数
private Long dailyCount;
/// 截止当日累计登记数
private Long totalCount;
}
@@ -1,33 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件记录列表项视图
///
/// @author Codex
/// @since 2026-08-01
@Data
public class GaoRegistrationEventRecordListItemView {
/// 记录 ID
private String id;
/// 客户 ID
private String customerId;
/// 客户姓名
private String customerName;
/// 客户头像附件 ID
private String customerPhotoAttachmentId;
/// 登记事件 ID
private String registrationEventId;
/// 登记事件名称
private String registrationEventName;
/// 登记时间
private Long registeredAt;
}
@@ -1,35 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件记录按周期查询请求
///
/// @author Codex
/// @since 2026-07-27
@Data
public class GaoRegistrationEventRecordPeriodReq {
///
/// 周期类型
///
/// @author Codex
/// @since 2026-07-27
public enum PeriodType {
DAY,
MONTH,
YEAR
}
/// 登记事件 ID
private String registrationEventId;
/// 周期类型
private PeriodType periodType;
/// 周期值,日为 yyyyMMdd,月为 yyyyMM,年为 yyyy
private Integer periodValue;
}
@@ -1,21 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件记录统计请求
///
/// @author Codex
/// @since 2026-07-28
@Data
public class GaoRegistrationEventRecordStatReq {
/// 客户 ID,全部客户统计时不传
private String customerId;
/// 开始登记时间
private Long beginRegisteredAt;
/// 结束登记时间
private Long endRegisteredAt;
}
@@ -1,24 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
///
/// 登记事件记录趋势统计请求
///
/// @author Codex
/// @since 2026-07-28
@Data
public class GaoRegistrationEventRecordTrendStatReq {
/// 客户 ID,全部客户趋势时不传
private String customerId;
/// 登记事件 ID
private String registrationEventId;
/// 开始登记时间
private Long beginRegisteredAt;
/// 结束登记时间
private Long endRegisteredAt;
}
@@ -7,7 +7,6 @@ import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.bean.CoreRoleCode; import com.imyeyu.api.bean.CoreRoleCode;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.vo.attach.BizUpdateReq;
import com.imyeyu.api.modules.user.entity.User; import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserService; import com.imyeyu.api.modules.user.service.UserService;
@@ -245,9 +244,6 @@ public class UserController {
if (tempFileIdList == null || tempFileIdList.isEmpty()) { if (tempFileIdList == null || tempFileIdList.isEmpty()) {
return; return;
} }
BizUpdateReq req = new BizUpdateReq();
req.setBizType(Attachment.BizType.USER);
req.setBizId(userId);
List<Attachment> items = attachmentService.listByBizId(Attachment.BizType.USER, userId).stream() List<Attachment> items = attachmentService.listByBizId(Attachment.BizType.USER, userId).stream()
.filter(item -> !User.AttachType.AVATAR.name().equals(item.getAttachType())) .filter(item -> !User.AttachType.AVATAR.name().equals(item.getAttachType()))
.map(item -> { .map(item -> {
@@ -264,7 +260,6 @@ public class UserController {
}).toList(); }).toList();
items = new ArrayList<>(items); items = new ArrayList<>(items);
items.addAll(avatarItems); items.addAll(avatarItems);
req.setItems(items); attachmentService.updateByBizId(Attachment.BizType.USER, userId, items);
attachmentService.updateByBiz(req);
} }
} }
@@ -0,0 +1,65 @@
package com.imyeyu.api.util;
import com.imyeyu.api.modules.user.bean.Gender;
import com.imyeyu.java.TimiJava;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.IOException;
import java.util.List;
///
///
/// @author 夜雨
/// @since 2026-08-04 15:57
public abstract class BaseXSSFBuilder<T> {
public abstract byte[] build(List<T> list) throws IOException;
protected CellStyle createTitleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 14);
style.setFont(font);
return style;
}
protected CellStyle createHeaderStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
return style;
}
protected void appendRow(Sheet sheet, int rowIndex, CellStyle style, String... values) {
Row row = sheet.createRow(rowIndex);
for (int index = 0; index < values.length; index++) {
row.createCell(index).setCellValue(values[index]);
if (style != null) {
row.getCell(index).setCellStyle(style);
}
}
}
protected String text(Object obj) {
if (obj == null) {
return "";
}
return TimiJava.defaultIfEmpty(obj.toString(), "");
}
protected String gender(Gender gender) {
if (gender == null) {
return "";
}
return switch (gender) {
case MALE -> "";
case FEMALE -> "";
};
}
}
@@ -0,0 +1,54 @@
RENAME TABLE `gao_registration_event` TO `gao_event`;
ALTER TABLE `gao_event`
DROP KEY `idx_gao_registration_event_status`,
ADD KEY `idx_gao_event_status` (`status`, `deleted_at`, `sort`, `created_at`);
RENAME TABLE `gao_registration_event_role_relation` TO `gao_event_role_relation`;
ALTER TABLE `gao_event_role_relation`
DROP KEY `idx_gao_registration_event_role_relation_registration_event_id`,
CHANGE COLUMN `registration_event_id` `event_id` VARCHAR(36) NOT NULL COMMENT '登记事件 ID',
ADD KEY `idx_gao_event_role_relation_event_id` (`event_id`);
RENAME TABLE `gao_registration_event_record` TO `gao_event_record`;
ALTER TABLE `gao_event_record`
DROP KEY `idx_gao_registration_event_record_customer_id`,
DROP KEY `idx_gao_registration_event_record_registration_event_id`,
DROP KEY `idx_gao_registration_event_record_registered_at`,
CHANGE COLUMN `registration_event_id` `event_id` VARCHAR(36) NOT NULL COMMENT '登记事件 ID',
ADD KEY `idx_gao_event_record_customer_id` (`customer_id`),
ADD KEY `idx_gao_event_record_event_id` (`event_id`),
ADD KEY `idx_gao_event_record_registered_at` (`registered_at`);
UPDATE `attachment`
SET `biz_type` = 'GAO_EVENT_RECORD'
WHERE `biz_type` = 'GAO_REGISTRATION_EVENT_RECORD';
UPDATE `permission`
SET `code` = CASE `code`
WHEN 'REGISTRATION_EVENT:CREATE' THEN 'EVENT:CREATE'
WHEN 'REGISTRATION_EVENT:READ' THEN 'EVENT:READ'
WHEN 'REGISTRATION_EVENT:UPDATE' THEN 'EVENT:UPDATE'
WHEN 'REGISTRATION_EVENT:DELETE' THEN 'EVENT:DELETE'
WHEN 'REGISTRATION_EVENT_RECORD:CREATE' THEN 'EVENT_RECORD:CREATE'
WHEN 'REGISTRATION_EVENT_RECORD:READ' THEN 'EVENT_RECORD:READ'
WHEN 'REGISTRATION_EVENT_RECORD:EXPORT' THEN 'EVENT_RECORD:EXPORT'
WHEN 'REGISTRATION_EVENT_RECORD:UPDATE' THEN 'EVENT_RECORD:UPDATE'
WHEN 'REGISTRATION_EVENT_RECORD:DELETE' THEN 'EVENT_RECORD:DELETE'
ELSE `code`
END
WHERE
`module_code` = 'GAO'
AND `code` IN (
'REGISTRATION_EVENT:CREATE',
'REGISTRATION_EVENT:READ',
'REGISTRATION_EVENT:UPDATE',
'REGISTRATION_EVENT:DELETE',
'REGISTRATION_EVENT_RECORD:CREATE',
'REGISTRATION_EVENT_RECORD:READ',
'REGISTRATION_EVENT_RECORD:EXPORT',
'REGISTRATION_EVENT_RECORD:UPDATE',
'REGISTRATION_EVENT_RECORD:DELETE'
);
@@ -14,7 +14,7 @@
</foreach> </foreach>
</if> </if>
<if test="bizIdList == null or bizIdList.isEmpty()"> <if test="bizIdList == null or bizIdList.isEmpty()">
AND 1 = 0 AND FALSE
</if> </if>
AND `deleted_at` IS NULL AND `deleted_at` IS NULL
AND (`destroy_at` IS NULL OR UNIX_TIMESTAMP() &lt; `destroy_at`) AND (`destroy_at` IS NULL OR UNIX_TIMESTAMP() &lt; `destroy_at`)
@@ -24,6 +24,35 @@
#{attachType} #{attachType}
</foreach> </foreach>
</if> </if>
ORDER BY `created_at` ASC ORDER BY `created_at`
</select>
<select id="selectThumb" resultType="com.imyeyu.api.modules.common.entity.Attachment">
SELECT
*
FROM
`attachment`
WHERE
biz_type = #{bizType}
AND biz_id = #{sourceId}
AND attach_type = 'THUMB'
<choose>
<when test="requestWidth != null">
AND JSON_EXTRACT(metadata, '$.requestWidth') = #{requestWidth}
</when>
<otherwise>
AND JSON_EXTRACT(metadata, '$.requestWidth') IS NULL
</otherwise>
</choose>
<choose>
<when test="requestHeight != null">
AND JSON_EXTRACT(metadata, '$.requestHeight') = #{requestHeight}
</when>
<otherwise>
AND JSON_EXTRACT(metadata, '$.requestHeight') IS NULL
</otherwise>
</choose>
AND is_destroyed = FALSE
AND UNIX_TIMESTAMP() * 1000 &lt; destroy_at
LIMIT 1
</select> </select>
</mapper> </mapper>
@@ -1,33 +1,6 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper"> <mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper">
<sql id="searchWhere">
1 = 1
AND `deleted_at` IS NULL
<if test="keyword != null and keyword != ''">
AND (
`code` LIKE CONCAT('%', #{keyword}, '%')
OR `name` LIKE CONCAT('%', #{keyword}, '%')
OR `telephone` LIKE CONCAT('%', #{keyword}, '%')
OR `address` LIKE CONCAT('%', #{keyword}, '%')
OR `disease` LIKE CONCAT('%', #{keyword}, '%')
OR CAST(`conditioning_part` AS CHAR) LIKE CONCAT('%', #{keyword}, '%')
)
</if>
<if test="introducerCustomerId != null and introducerCustomerId != ''">
AND `introducer_customer_id` = #{introducerCustomerId}
</if>
</sql>
<select id="search" resultType="com.imyeyu.api.modules.gao.entity.GaoCustomer">
SELECT
*
FROM `gao_customer`
WHERE
<include refid="searchWhere"/>
ORDER BY `created_at` DESC
</select>
<select id="selectByIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoCustomer"> <select id="selectByIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoCustomer">
SELECT SELECT
* *
@@ -40,54 +13,7 @@
AND `deleted_at` IS NULL AND `deleted_at` IS NULL
</select> </select>
<select id="countSearch" resultType="java.lang.Long"> <select id="stateDailyNewCustomer" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStateView">
SELECT
COUNT(1)
FROM `gao_customer`
WHERE
<include refid="searchWhere"/>
</select>
<select id="searchPage" resultType="com.imyeyu.api.modules.gao.entity.GaoCustomer">
SELECT
*
FROM `gao_customer`
WHERE
<include refid="searchWhere"/>
ORDER BY `created_at` DESC
LIMIT #{offset}, #{size}
</select>
<select id="selectInvitedList" resultType="com.imyeyu.api.modules.gao.entity.GaoCustomer">
SELECT
*
FROM `gao_customer`
WHERE
`introducer_customer_id` = #{introducerCustomerId}
AND `deleted_at` IS NULL
ORDER BY `created_at` DESC
</select>
<select id="countInvited" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_customer`
WHERE
`introducer_customer_id` = #{introducerCustomerId}
AND `deleted_at` IS NULL
</select>
<update id="updateInvitedCountDelta">
UPDATE `gao_customer`
SET
`invited_count` = GREATEST(IFNULL(`invited_count`, 0) + #{delta}, 0),
`updated_at` = UNIX_TIMESTAMP() * 1000
WHERE
`id` = #{customerId}
AND `deleted_at` IS NULL
</update>
<select id="statDailyNewCustomer" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerDailyStatView">
SELECT SELECT
CAST(DATE_FORMAT(FROM_UNIXTIME(`created_at` / 1000), '%Y%m%d') AS UNSIGNED) AS `dateValue`, CAST(DATE_FORMAT(FROM_UNIXTIME(`created_at` / 1000), '%Y%m%d') AS UNSIGNED) AS `dateValue`,
COUNT(1) AS `newCustomerCount` COUNT(1) AS `newCustomerCount`
@@ -109,7 +35,7 @@
AND `deleted_at` IS NULL AND `deleted_at` IS NULL
</select> </select>
<select id="statGender" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView"> <select id="stateGender" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerGenderStatView">
SELECT SELECT
IFNULL(CAST(`gender` AS CHAR), 'UNKNOWN') AS `genderCode`, IFNULL(CAST(`gender` AS CHAR), 'UNKNOWN') AS `genderCode`,
COUNT(1) AS `count` COUNT(1) AS `count`
@@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoRegistrationEventMapper"> <mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoEventMapper">
<select id="selectByIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent"> <select id="selectByIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoEvent">
SELECT SELECT
* *
FROM `gao_registration_event` FROM `gao_event`
WHERE WHERE
1 = 1 TRUE
<if test="idList != null and !idList.isEmpty()"> <if test="idList != null and !idList.isEmpty()">
AND `id` IN AND `id` IN
<foreach collection="idList" item="id" separator="," open="(" close=")"> <foreach collection="idList" item="id" separator="," open="(" close=")">
@@ -14,20 +14,20 @@
</foreach> </foreach>
</if> </if>
<if test="idList == null or idList.isEmpty()"> <if test="idList == null or idList.isEmpty()">
AND 1 = 0 AND FALSE
</if> </if>
AND `deleted_at` IS NULL AND `deleted_at` IS NULL
</select> </select>
<select id="selectEnabledList" resultType="com.imyeyu.api.modules.gao.entity.GaoRegistrationEvent"> <select id="selectValidList" resultType="com.imyeyu.api.modules.gao.entity.GaoEvent">
SELECT SELECT
* *
FROM `gao_registration_event` FROM `gao_event`
WHERE WHERE
(`status` IS NULL OR `status` = 'ACTIVE') `status` = '${@com.imyeyu.api.modules.gao.entity.GaoEvent$Status@ACTIVE.name()}'
AND (`begin_at` IS NULL OR `begin_at` &lt;= #{now}) AND (`begin_at` IS NULL OR `begin_at` &lt;= #{now})
AND (`end_at` IS NULL OR #{now} &lt;= `end_at`) AND (`end_at` IS NULL OR #{now} &lt;= `end_at`)
AND `deleted_at` IS NULL AND `deleted_at` IS NULL
ORDER BY `sort` ASC, `created_at` ASC ORDER BY `sort`, `created_at`
</select> </select>
</mapper> </mapper>
@@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoEventRecordMapper">
<select id="count" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM
`gao_event_record`
WHERE
TRUE
<if test="customerId != null">
AND `customer_id` = #{customerId}
</if>
<if test="eventId != null">
AND `event_id` = #{eventId}
</if>
<if test="beginAt != null">
AND `registered_at` &gt;= #{beginAt}
</if>
<if test="endAt != null">
AND `registered_at` &gt;= #{endAt}
</if>
AND `deleted_at` IS NULL
</select>
<sql id="rangeFrom">
FROM `gao_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
</sql>
<sql id="rangeWhere">
r.`registered_at` &gt;= #{beginAt}
AND r.`registered_at` &lt;= #{endAt}
AND r.`deleted_at` IS NULL
<if test="customerId != null">
AND r.`customer_id` = #{customerId}
</if>
<if test="eventIdList != null and eventIdList.size() > 0">
AND r.`event_id` IN
<foreach collection="eventIdList" item="eventId" open="(" separator="," close=")">
#{eventId}
</foreach>
</if>
<if test="keyword != null and keyword.trim() != ''">
AND (
c.`code` LIKE CONCAT('%', #{keyword}, '%')
OR c.`name` LIKE CONCAT('%', #{keyword}, '%')
OR r.`remark` LIKE CONCAT('%', #{keyword}, '%')
OR r.`operator_user_id` LIKE CONCAT('%', #{keyword}, '%')
)
</if>
</sql>
<select id="countByRange" resultType="long">
SELECT
COUNT(1)
<include refid="rangeFrom"/>
WHERE
<include refid="rangeWhere"/>
</select>
<select id="selectByRange" resultType="com.imyeyu.api.modules.gao.entity.GaoEventRecord">
SELECT
r.*
<include refid="rangeFrom"/>
WHERE
<include refid="rangeWhere"/>
ORDER BY r.`registered_at` DESC, r.`created_at` DESC
LIMIT #{offset}, #{limit}
</select>
<sql id="rankWhere">
r.`deleted_at` IS NULL
AND c.`deleted_at` IS NULL
<if test="customerId != null and customerId != ''">
AND r.`customer_id` = #{customerId}
</if>
<if test="beginAt != null">
AND r.`registered_at` &gt;= #{beginAt}
</if>
<if test="endAt != null">
AND r.`registered_at` &lt;= #{endAt}
</if>
<if test="eventIdList != null and eventIdList.size() > 0">
AND r.`event_id` IN
<foreach collection="eventIdList" item="eventId" open="(" separator="," close=")">
#{eventId}
</foreach>
</if>
</sql>
<select id="countRankByRange" resultType="long">
SELECT
COUNT(DISTINCT r.`customer_id`)
FROM `gao_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
WHERE
<include refid="rankWhere"/>
</select>
<select id="selectRankByRange" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerEventRankView">
WITH `daily_stat` AS (
SELECT
r.`customer_id` AS `customerId`,
DATE(FROM_UNIXTIME(r.`registered_at` / 1000)) AS `eventDate`,
COUNT(1) AS `dailyCount`,
MAX(r.`registered_at`) AS `latestRegisteredAt`
FROM `gao_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
WHERE
<include refid="rankWhere"/>
GROUP BY
r.`customer_id`,
DATE(FROM_UNIXTIME(r.`registered_at` / 1000))
),
`rank_stat` AS (
SELECT
`customerId`,
COUNT(1) AS `totalEventDays`,
SUM(`dailyCount`) AS `totalEventCount`,
MAX(`latestRegisteredAt`) AS `latestRegisteredAt`
FROM `daily_stat`
GROUP BY `customerId`
),
`continuous_ordered` AS (
SELECT
`customerId`,
`eventDate`,
ROW_NUMBER() OVER (PARTITION BY `customerId` ORDER BY `eventDate` DESC) AS `dayIndex`
FROM `daily_stat`
),
`latest_date` AS (
SELECT
`customerId`,
MAX(`eventDate`) AS `latestEventDate`
FROM `daily_stat`
GROUP BY `customerId`
),
`continuous_stat` AS (
SELECT
o.`customerId`,
COUNT(1) AS `recentContinuousEventDays`
FROM `continuous_ordered` o
LEFT JOIN `latest_date` l ON o.`customerId` = l.`customerId`
WHERE DATE_ADD(o.`eventDate`, INTERVAL o.`dayIndex` DAY) = DATE_ADD(l.`latestEventDate`, INTERVAL 1 DAY)
GROUP BY o.`customerId`
),
`ranked` AS (
SELECT
ROW_NUMBER() OVER (
ORDER BY
r.`totalEventDays` DESC,
r.`totalEventCount` DESC,
r.`latestRegisteredAt` DESC,
r.`customerId`
) AS `rank`,
r.`customerId`,
r.`totalEventDays`,
r.`totalEventCount`,
COALESCE(c.`recentContinuousEventDays`, 0) AS `recentContinuousEventDays`,
r.`latestRegisteredAt`
FROM `rank_stat` r
LEFT JOIN `continuous_stat` c ON r.`customerId` = c.`customerId`
)
SELECT
`rank`,
`customerId`,
`totalEventDays`,
`totalEventCount`,
`recentContinuousEventDays`,
`latestRegisteredAt`
FROM `ranked`
ORDER BY `rank`
LIMIT #{offset}, #{limit}
</select>
</mapper>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoEventRoleRelationMapper">
<select id="selectAllByEventIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoEventRoleRelation">
SELECT
*
FROM `gao_event_role_relation`
WHERE
TRUE
<if test="idList != null and !idList.isEmpty()">
AND `event_id` IN
<foreach collection="idList" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</if>
<if test="idList == null or idList.isEmpty()">
AND FALSE
</if>
AND `deleted_at` IS NULL
ORDER BY `created_at`
</select>
</mapper>
@@ -1,389 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoRegistrationEventRecordMapper">
<select id="selectByRegistrationEventAndPeriod" resultType="com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord">
SELECT
*
FROM `gao_registration_event_record`
WHERE
`registration_event_id` = #{registrationEventId}
AND `deleted_at` IS NULL
<if test='periodType.name() == "DAY"'>
AND DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d') = CAST(#{periodValue} AS CHAR)
</if>
<if test='periodType.name() == "MONTH"'>
AND DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m') = CAST(#{periodValue} AS CHAR)
</if>
<if test='periodType.name() == "YEAR"'>
AND DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y') = CAST(#{periodValue} AS CHAR)
</if>
ORDER BY `registered_at` DESC
</select>
<select id="countByCustomerIdAndRegistrationEventIdRange" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_registration_event_record`
WHERE
`customer_id` = #{customerId}
AND `registration_event_id` = #{registrationEventId}
AND `registered_at` &gt;= #{beginRegisteredAt}
AND `registered_at` &lt;= #{endRegisteredAt}
AND `deleted_at` IS NULL
</select>
<select id="countByCustomerIdAndRegistrationEventId" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_registration_event_record`
WHERE
`customer_id` = #{customerId}
AND `registration_event_id` = #{registrationEventId}
AND `deleted_at` IS NULL
</select>
<select id="countByRegistrationEventId" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_registration_event_record`
WHERE
`registration_event_id` = #{registrationEventId}
AND `deleted_at` IS NULL
</select>
<select id="statByRegistrationEventAndPeriodType" resultType="com.imyeyu.api.modules.gao.vo.GaoRegistrationEventPeriodStatView">
SELECT
`registration_event_id` AS `registrationEventId`,
<choose>
<when test='periodType.name() == "DAY"'>
CAST(DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d') AS UNSIGNED)
</when>
<when test='periodType.name() == "MONTH"'>
CAST(DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m') AS UNSIGNED)
</when>
<otherwise>
CAST(DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y') AS UNSIGNED)
</otherwise>
</choose> AS `periodValue`,
COUNT(1) AS `count`
FROM `gao_registration_event_record`
WHERE
`registration_event_id` = #{registrationEventId}
AND `deleted_at` IS NULL
GROUP BY
`registration_event_id`,
<choose>
<when test='periodType.name() == "DAY"'>
DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d')
</when>
<when test='periodType.name() == "MONTH"'>
DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m')
</when>
<otherwise>
DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y')
</otherwise>
</choose>
ORDER BY `periodValue` DESC
</select>
<select id="statByCustomerId" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView">
SELECT
r.`customer_id` AS `customerId`,
c.`name` AS `customerName`,
r.`registration_event_id` AS `registrationEventId`,
a.`name` AS `registrationEventName`,
COUNT(1) AS `count`,
MAX(r.`registered_at`) AS `latestRegisteredAt`
FROM `gao_registration_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
LEFT JOIN `gao_registration_event` a ON r.`registration_event_id` = a.`id`
WHERE
r.`customer_id` = #{customerId}
AND r.`deleted_at` IS NULL
GROUP BY r.`customer_id`, c.`name`, r.`registration_event_id`, a.`name`
ORDER BY `latestRegisteredAt` DESC
</select>
<select id="statByCustomerIdAndRange" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView">
SELECT
r.`customer_id` AS `customerId`,
c.`name` AS `customerName`,
r.`registration_event_id` AS `registrationEventId`,
a.`name` AS `registrationEventName`,
COUNT(1) AS `count`,
MAX(r.`registered_at`) AS `latestRegisteredAt`
FROM `gao_registration_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
LEFT JOIN `gao_registration_event` a ON r.`registration_event_id` = a.`id`
WHERE
r.`customer_id` = #{customerId}
AND r.`registered_at` >= #{beginRegisteredAt}
AND r.`registered_at` &lt;= #{endRegisteredAt}
AND r.`deleted_at` IS NULL
GROUP BY r.`customer_id`, c.`name`, r.`registration_event_id`, a.`name`
ORDER BY `latestRegisteredAt` DESC
</select>
<select id="statAllCustomerByRange" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerRegisterStatView">
SELECT
r.`customer_id` AS `customerId`,
c.`name` AS `customerName`,
r.`registration_event_id` AS `registrationEventId`,
a.`name` AS `registrationEventName`,
COUNT(1) AS `count`,
MAX(r.`registered_at`) AS `latestRegisteredAt`
FROM `gao_registration_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
LEFT JOIN `gao_registration_event` a ON r.`registration_event_id` = a.`id`
WHERE
r.`registered_at` >= #{beginRegisteredAt}
AND r.`registered_at` &lt;= #{endRegisteredAt}
AND r.`deleted_at` IS NULL
GROUP BY r.`customer_id`, c.`name`, r.`registration_event_id`, a.`name`
ORDER BY `latestRegisteredAt` DESC
</select>
<select id="statCustomerRegistrationDay" resultType="com.imyeyu.api.modules.gao.vo.GaoCustomerRegistrationDayStatView">
SELECT
r.`customer_id` AS `customerId`,
c.`code` AS `customerCode`,
c.`name` AS `customerName`,
(
SELECT a.`id`
FROM `attachment` a
WHERE
a.`biz_type` = 'GAO_CUSTOMER'
AND a.`biz_id` = c.`id`
AND a.`attach_type` = 'PHOTO'
AND a.`deleted_at` IS NULL
AND (a.`destroy_at` IS NULL OR UNIX_TIMESTAMP() &lt; a.`destroy_at`)
ORDER BY a.`created_at` ASC
LIMIT 1
) AS `customerPhotoAttachmentId`,
CAST(DATE_FORMAT(FROM_UNIXTIME(r.`registered_at` / 1000), '%Y%m%d') AS UNSIGNED) AS `dateValue`,
COUNT(1) AS `dailyCount`,
MAX(r.`registered_at`) AS `latestRegisteredAt`
FROM `gao_registration_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
WHERE
r.`deleted_at` IS NULL
AND c.`deleted_at` IS NULL
<if test="req.beginRegisteredAt != null">
AND r.`registered_at` &gt;= #{req.beginRegisteredAt}
</if>
<if test="req.endRegisteredAt != null">
AND r.`registered_at` &lt;= #{req.endRegisteredAt}
</if>
<if test="req.registrationEventId != null and req.registrationEventId != ''">
AND r.`registration_event_id` = #{req.registrationEventId}
</if>
<if test="req.registrationEventIdList != null and req.registrationEventIdList.size() > 0">
AND r.`registration_event_id` IN
<foreach collection="req.registrationEventIdList" item="registrationEventId" open="(" separator="," close=")">
#{registrationEventId}
</foreach>
</if>
GROUP BY
r.`customer_id`,
c.`code`,
c.`name`,
DATE_FORMAT(FROM_UNIXTIME(r.`registered_at` / 1000), '%Y%m%d')
ORDER BY r.`customer_id` ASC, `dateValue` DESC
</select>
<select id="statDailyCountByCustomerIdAndRegistrationEventIdRange" resultType="com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordDailyStatView">
SELECT
CAST(DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d') AS UNSIGNED) AS `dateValue`,
COUNT(1) AS `dailyCount`
FROM `gao_registration_event_record`
WHERE
`customer_id` = #{customerId}
AND `registration_event_id` = #{registrationEventId}
AND `registered_at` >= #{beginRegisteredAt}
AND `registered_at` &lt;= #{endRegisteredAt}
AND `deleted_at` IS NULL
GROUP BY DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d')
ORDER BY `dateValue` ASC
</select>
<select id="statDailyCountByRegistrationEventIdRange" resultType="com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordDailyStatView">
SELECT
CAST(DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d') AS UNSIGNED) AS `dateValue`,
COUNT(1) AS `dailyCount`
FROM `gao_registration_event_record`
WHERE
`registration_event_id` = #{registrationEventId}
AND `registered_at` >= #{beginRegisteredAt}
AND `registered_at` &lt;= #{endRegisteredAt}
AND `deleted_at` IS NULL
GROUP BY DATE_FORMAT(FROM_UNIXTIME(`registered_at` / 1000), '%Y%m%d')
ORDER BY `dateValue` ASC
</select>
<select id="countBeforeByCustomerIdAndRegistrationEventId" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_registration_event_record`
WHERE
`customer_id` = #{customerId}
AND `registration_event_id` = #{registrationEventId}
AND `registered_at` &lt; #{beginRegisteredAt}
AND `deleted_at` IS NULL
</select>
<select id="countBeforeByRegistrationEventId" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_registration_event_record`
WHERE
`registration_event_id` = #{registrationEventId}
AND `registered_at` &lt; #{beginRegisteredAt}
AND `deleted_at` IS NULL
</select>
<select id="selectLatestByCustomerIdListAndRegistrationEventId" resultType="com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord">
SELECT
r.*
FROM `gao_registration_event_record` r
WHERE
r.`registration_event_id` = #{registrationEventId}
AND r.`deleted_at` IS NULL
AND r.`customer_id` IN
<foreach collection="customerIdList" item="customerId" open="(" separator="," close=")">
#{customerId}
</foreach>
AND NOT EXISTS (
SELECT
1
FROM `gao_registration_event_record` newer
WHERE
newer.`customer_id` = r.`customer_id`
AND newer.`registration_event_id` = r.`registration_event_id`
AND newer.`deleted_at` IS NULL
AND (
newer.`registered_at` > r.`registered_at`
OR (newer.`registered_at` = r.`registered_at` AND newer.`created_at` > r.`created_at`)
OR (newer.`registered_at` = r.`registered_at` AND newer.`created_at` = r.`created_at` AND newer.`id` > r.`id`)
)
)
ORDER BY r.`registered_at` DESC, r.`created_at` DESC
</select>
<select id="selectLatestByCustomerId" resultType="com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord">
SELECT
r.*
FROM `gao_registration_event_record` r
WHERE
r.`customer_id` = #{customerId}
AND r.`deleted_at` IS NULL
AND NOT EXISTS (
SELECT
1
FROM `gao_registration_event_record` newer
WHERE
newer.`customer_id` = r.`customer_id`
AND newer.`registration_event_id` = r.`registration_event_id`
AND newer.`deleted_at` IS NULL
AND (
newer.`registered_at` > r.`registered_at`
OR (newer.`registered_at` = r.`registered_at` AND newer.`created_at` > r.`created_at`)
OR (newer.`registered_at` = r.`registered_at` AND newer.`created_at` = r.`created_at` AND newer.`id` > r.`id`)
)
)
ORDER BY r.`registered_at` DESC, r.`created_at` DESC
</select>
<sql id="rangeWhere">
r.`registered_at` &gt;= #{req.beginRegisteredAt}
AND r.`registered_at` &lt;= #{req.endRegisteredAt}
AND r.`deleted_at` IS NULL
<if test="req.customerId != null and req.customerId != ''">
AND r.`customer_id` = #{req.customerId}
</if>
<if test="req.registrationEventId != null and req.registrationEventId != ''">
AND r.`registration_event_id` = #{req.registrationEventId}
</if>
<if test="req.registrationEventIdList != null and req.registrationEventIdList.size() > 0">
AND r.`registration_event_id` IN
<foreach collection="req.registrationEventIdList" item="registrationEventId" open="(" separator="," close=")">
#{registrationEventId}
</foreach>
</if>
<if test="req.keyword != null and req.keyword != ''">
AND (
c.`code` LIKE CONCAT('%', #{req.keyword}, '%')
OR c.`name` LIKE CONCAT('%', #{req.keyword}, '%')
OR e.`name` LIKE CONCAT('%', #{req.keyword}, '%')
OR r.`remark` LIKE CONCAT('%', #{req.keyword}, '%')
OR u.`name` LIKE CONCAT('%', #{req.keyword}, '%')
OR u.`nick` LIKE CONCAT('%', #{req.keyword}, '%')
OR r.`operator_user_id` LIKE CONCAT('%', #{req.keyword}, '%')
)
</if>
</sql>
<sql id="rangeFrom">
FROM `gao_registration_event_record` r
LEFT JOIN `gao_customer` c ON r.`customer_id` = c.`id`
LEFT JOIN `gao_registration_event` e ON r.`registration_event_id` = e.`id`
LEFT JOIN `user` u ON r.`operator_user_id` = u.`id`
</sql>
<select id="selectByRange" resultType="com.imyeyu.api.modules.gao.entity.GaoRegistrationEventRecord">
SELECT
r.*
<include refid="rangeFrom"/>
WHERE
<include refid="rangeWhere"/>
ORDER BY r.`registered_at` DESC, r.`created_at` DESC
</select>
<select id="selectCalendarByRange" resultType="com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordCalendarView">
SELECT
r.`id` AS `id`,
r.`customer_id` AS `customerId`,
c.`code` AS `customerCode`,
c.`name` AS `customerName`,
r.`registration_event_id` AS `registrationEventId`,
r.`registered_at` AS `registeredAt`
<include refid="rangeFrom"/>
WHERE
<include refid="rangeWhere"/>
ORDER BY r.`registered_at` DESC, r.`created_at` DESC
</select>
<select id="countByRange" resultType="java.lang.Long">
SELECT
COUNT(1)
<include refid="rangeFrom"/>
WHERE
<include refid="rangeWhere"/>
</select>
<select id="selectPageByRange" resultType="com.imyeyu.api.modules.gao.vo.GaoRegistrationEventRecordListItemView">
SELECT
r.`id` AS `id`,
r.`customer_id` AS `customerId`,
c.`name` AS `customerName`,
(
SELECT a.`id`
FROM `attachment` a
WHERE
a.`biz_type` = 'GAO_CUSTOMER'
AND a.`biz_id` = c.`id`
AND a.`attach_type` = 'PHOTO'
AND a.`deleted_at` IS NULL
AND (a.`destroy_at` IS NULL OR UNIX_TIMESTAMP() &lt; a.`destroy_at`)
ORDER BY a.`created_at` ASC
LIMIT 1
) AS `customerPhotoAttachmentId`,
r.`registration_event_id` AS `registrationEventId`,
e.`name` AS `registrationEventName`,
r.`registered_at` AS `registeredAt`
<include refid="rangeFrom"/>
WHERE
<include refid="rangeWhere"/>
ORDER BY r.`registered_at` DESC, r.`created_at` DESC
LIMIT #{offset}, #{size}
</select>
</mapper>
@@ -6,7 +6,7 @@
* *
FROM `user` FROM `user`
WHERE WHERE
1 = 1 TRUE
<if test="idList != null and !idList.isEmpty()"> <if test="idList != null and !idList.isEmpty()">
AND `id` IN AND `id` IN
<foreach collection="idList" item="item" separator="," open="(" close=")"> <foreach collection="idList" item="item" separator="," open="(" close=")">
@@ -14,7 +14,7 @@
</foreach> </foreach>
</if> </if>
<if test="idList == null or idList.isEmpty()"> <if test="idList == null or idList.isEmpty()">
AND 1 = 0 AND FALSE
</if> </if>
AND `deleted_at` IS NULL AND `deleted_at` IS NULL
</select> </select>