Compare commits

...
42 Commits
Author SHA1 Message Date
timi b800069c82 Merge pull request 'v1.0.76' (#88) from dev into master
Reviewed-on: #88
2026-11-17 08:40:24 +00:00
Timi 82110e36b7 v1.0.76
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 16:37:51 +08:00
Timi 5604edc00b fix(app): lost update log for point to native package 2026-11-17 16:37:33 +08:00
timi 79059e7818 Merge pull request 'v1.0.75' (#87) from dev into master
Reviewed-on: #87
2026-11-17 07:56:50 +00:00
Timi 7294e9050d v1.0.75
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 15:55:08 +08:00
Timi 7d87ca7a86 fix(app): host update 2026-11-17 15:55:08 +08:00
timi 4b943e887d Merge pull request 'v1.0.74' (#86) from dev into master
Reviewed-on: #86
2026-11-17 06:55:28 +00:00
Timi 6b2841274d v1.0.74
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 14:55:12 +08:00
Timi d5ccfbb231 fix(system): delete app release fail 2026-11-17 14:54:58 +08:00
timi 359eac8985 Merge pull request 'v1.0.73' (#85) from dev into master
Reviewed-on: #85
2026-11-17 06:27:05 +00:00
Timi 96750730d3 v1.0.73
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 14:26:22 +08:00
Timi 725503152e fix(attach): lost file name for download 2026-11-17 14:26:09 +08:00
timi 1531c2498b Merge pull request 'v1.0.72' (#84) from dev into master
Reviewed-on: #84
2026-11-17 03:55:12 +00:00
Timi 5233ac7eef v1.0.72
CI / build-deploy (pull_request) Successful in 35s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 11:51:44 +08:00
Timi 343406efc7 feat(app): response apk package 2026-11-17 11:51:44 +08:00
Timi ee33284a2c feat(gao): support customer birthdate followup reminder 2026-11-16 16:23:00 +08:00
Timi 32bfdaa116 fix(gao): allow CI update log 2026-11-15 17:15:34 +08:00
Timi 7bbd217bdd feat(gao): no modification product base unit 2026-11-14 16:31:43 +08:00
Timi 1349b3c069 fix(gao): order remind url 2026-11-14 15:49:55 +08:00
Timi 8c0845d610 fix(system): fix apk recent update log 2026-11-14 15:05:56 +08:00
timi 60e80dda87 Merge pull request 'v1.0.71' (#83) from dev into master
Reviewed-on: #83
2026-11-13 17:11:48 +00:00
Timi 4ae8b1dda8 v1.0.71
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-14 01:05:20 +08:00
Timi f0c586ace8 feat(gao recycle): customer recycle list 2026-11-14 01:05:02 +08:00
Timi 43e7a509c2 feat(gao recycle): support quick fulfillment for recycle order 2026-11-13 19:05:52 +08:00
Timi a14a9a5581 feat(system): app update log api 2026-11-13 15:04:29 +08:00
timi 445da5f093 Merge pull request 'v1.0.70' (#82) from dev into master
Reviewed-on: #82
2026-11-12 09:44:54 +00:00
Timi 8f4a839b2f v1.0.70
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-11-12 17:44:23 +08:00
Timi bd3f10fe60 fix: db timezone 2026-11-12 17:44:03 +08:00
Timi 169fd257a9 feat: recycle system 2026-11-12 17:37:05 +08:00
timi b62c7f2495 Merge pull request 'v1.0.69' (#81) from dev into master
Reviewed-on: #81
2026-11-08 12:05:57 +00:00
Timi bc901e2f0b v1.0.69
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-08 20:04:59 +08:00
Timi 74dd150469 add recycle 2026-11-08 18:50:53 +08:00
timi 2b7c94e7c3 Merge pull request 'v1.0.68' (#80) from dev into master
Reviewed-on: #80
2026-11-07 18:03:08 +00:00
Timi 03a4d4a8ff v1.0.68
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-08 02:02:47 +08:00
Timi 7d8172e063 feat: can fulfillment sku order filter 2026-11-08 01:39:42 +08:00
Timi e5a065fbaf fix: gray permille for appVersion 2026-11-08 00:46:46 +08:00
timi 470b586085 Merge pull request 'v1.0.67' (#79) from dev into master
Reviewed-on: #79
2026-11-06 16:05:40 +00:00
Timi a8c04cf342 v1.0.67
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-11-07 00:05:23 +08:00
Timi 669118c0f8 fix attach create response fail 2026-11-07 00:05:11 +08:00
timi 3d0f9b9d1b Merge pull request 'v1.0.66' (#78) from dev into master
Reviewed-on: #78
2026-11-06 15:59:05 +00:00
Timi b2cbe15d8b v1.0.66
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-11-06 23:58:41 +08:00
Timi a5426ce894 add APP_RELEASE attach 2026-11-06 23:58:29 +08:00
113 changed files with 5173 additions and 336 deletions
+6 -1
View File
@@ -11,7 +11,7 @@
<groupId>com.imyeyu.timiserverapi</groupId> <groupId>com.imyeyu.timiserverapi</groupId>
<artifactId>TimiServerAPI</artifactId> <artifactId>TimiServerAPI</artifactId>
<version>1.0.65</version> <version>1.0.76</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>TimiServerAPI</name> <name>TimiServerAPI</name>
<description>imyeyu.com API</description> <description>imyeyu.com API</description>
@@ -219,6 +219,11 @@
<artifactId>tinypinyin</artifactId> <artifactId>tinypinyin</artifactId>
<version>2.0.3</version> <version>2.0.3</version>
</dependency> </dependency>
<dependency>
<groupId>cn.6tail</groupId>
<artifactId>lunar</artifactId>
<version>1.7.8</version>
</dependency>
<dependency> <dependency>
<groupId>com.hankcs</groupId> <groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId> <artifactId>hanlp</artifactId>
@@ -24,4 +24,13 @@ public interface SettingEnum {
String getDefaultValue(); String getDefaultValue();
Setting.ValueType getValueType(); Setting.ValueType getValueType();
/// 配置作用域
///
/// 业务级配置由业务对象自己维护,启动时不初始化记录
///
/// @return 配置作用域
default Setting.Scope getScope() {
return Setting.Scope.SYSTEM;
}
} }
@@ -21,6 +21,7 @@ import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -32,18 +33,14 @@ import java.util.List;
*/ */
@Configuration @Configuration
@MapperScan(basePackages = { @MapperScan(basePackages = {
"com.imyeyu.api.modules.git.mapper",
"com.imyeyu.api.modules.gao.mapper", "com.imyeyu.api.modules.gao.mapper",
"com.imyeyu.api.modules.bill.mapper",
"com.imyeyu.api.modules.user.mapper", "com.imyeyu.api.modules.user.mapper",
"com.imyeyu.api.modules.blog.mapper",
"com.imyeyu.api.modules.lyric.mapper", "com.imyeyu.api.modules.lyric.mapper",
"com.imyeyu.api.modules.mirror.mapper", "com.imyeyu.api.modules.mirror.mapper",
"com.imyeyu.api.modules.system.mapper", "com.imyeyu.api.modules.system.mapper",
"com.imyeyu.api.modules.common.mapper", "com.imyeyu.api.modules.common.mapper",
"com.imyeyu.api.modules.app.mapper", "com.imyeyu.api.modules.app.mapper",
"com.imyeyu.api.modules.journal.mapper", "com.imyeyu.api.modules.journal.mapper",
"com.imyeyu.api.modules.minecraft.mapper"
}, sqlSessionFactoryRef = "timiServerSqlSessionFactory") }, sqlSessionFactoryRef = "timiServerSqlSessionFactory")
public class TimiServerDBConfig { public class TimiServerDBConfig {
@@ -59,6 +56,9 @@ public class TimiServerDBConfig {
dataSource.setMinimumIdle(10); dataSource.setMinimumIdle(10);
dataSource.setMaximumPoolSize(100); dataSource.setMaximumPoolSize(100);
dataSource.setConnectionTestQuery("SELECT 1"); dataSource.setConnectionTestQuery("SELECT 1");
// 日统计按后端时区划分日期
String offset = OffsetDateTime.now().getOffset().getId();
dataSource.setConnectionInitSql("SET time_zone = '%s'".formatted("Z".equals(offset) ? "+00:00" : offset));
dataSource.setMaxLifetime(Time.S * 180); dataSource.setMaxLifetime(Time.S * 180);
dataSource.setIdleTimeout(Time.S * 120); dataSource.setIdleTimeout(Time.S * 120);
@@ -3,6 +3,7 @@ package com.imyeyu.api.modules.app.controller;
import com.imyeyu.api.modules.app.service.AppVersionService; import com.imyeyu.api.modules.app.service.AppVersionService;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckRequest; import com.imyeyu.api.modules.app.vo.AppUpdateCheckRequest;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckResponse; import com.imyeyu.api.modules.app.vo.AppUpdateCheckResponse;
import com.imyeyu.api.modules.app.vo.AppUpdateNotesResponse;
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 lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -39,4 +40,17 @@ public class AppUpdateController {
public AppUpdateCheckResponse check(@RequestBody AppUpdateCheckRequest req) { public AppUpdateCheckResponse check(@RequestBody AppUpdateCheckRequest req) {
return service.check(req); return service.check(req);
} }
/// 查询更新日志
///
/// 返回当前运行版本到目标版本之间的变更说明,供版本历史页使用
/// 目标版本与 check 用同一套规则解析,包含灰度与兼容区间,保证「有日志」和「能更新」一致
///
/// @param req 插件上报信息,version_name 为当前运行版本
/// @return 更新日志
@RequestRateLimit
@PostMapping("/notes")
public AppUpdateNotesResponse notes(@RequestBody AppUpdateCheckRequest req) {
return service.notes(req);
}
} }
@@ -8,6 +8,8 @@ import com.imyeyu.api.modules.app.mapper.AppProductMapper;
import com.imyeyu.api.modules.app.mapper.AppReleaseMapper; import com.imyeyu.api.modules.app.mapper.AppReleaseMapper;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckRequest; import com.imyeyu.api.modules.app.vo.AppUpdateCheckRequest;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckResponse; import com.imyeyu.api.modules.app.vo.AppUpdateCheckResponse;
import com.imyeyu.api.modules.app.vo.AppUpdateNote;
import com.imyeyu.api.modules.app.vo.AppUpdateNotesResponse;
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.java.TimiJava; import com.imyeyu.java.TimiJava;
@@ -17,6 +19,8 @@ import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.zip.CRC32; import java.util.zip.CRC32;
@@ -38,6 +42,18 @@ public class AppVersionService {
/// 内置包版本标识 /// 内置包版本标识
public static final String BUILTIN_VERSION = "builtin"; public static final String BUILTIN_VERSION = "builtin";
/// 首个能处理外壳安装包的 Web 包版本
///
/// 更早的包不认识 shell 标记,只会把 url 当热更 zip 交给插件解压,拿到 APK 必然失败。
/// 通道指向原生包时,低于这个版本的设备改为下发热更包,先把它升到能自升级为止
public static final String SHELL_AWARE_VERSION = "1.3.2";
/// 更新日志最多返回的版本条数
public static final int MAX_NOTES = 20;
/// 已是最新时展示的版本条数
public static final int TAIL_NOTES = 3;
/// 灰度基数 /// 灰度基数
private static final long GRAY_BASE = 10000L; private static final long GRAY_BASE = 10000L;
@@ -51,54 +67,145 @@ public class AppVersionService {
/// @param req 插件上报信息 /// @param req 插件上报信息
/// @return 插件协议响应,无更新时回显当前版本 /// @return 插件协议响应,无更新时回显当前版本
public AppUpdateCheckResponse check(AppUpdateCheckRequest req) { public AppUpdateCheckResponse check(AppUpdateCheckRequest req) {
String currentVersion = TimiJava.isEmpty(req.getVersionName()) ? BUILTIN_VERSION : req.getVersionName(); String currentVersion = currentVersion(req);
AppProduct product = productMapper.selectByAppKey(req.getAppId(), parsePlatform(req.getPlatform())); AppProduct product = resolveProduct(req);
if (product == null || !Boolean.TRUE.equals(product.getEnabled())) { if (product == null) {
log.warn("应用不存在或已停用,appId={}", req.getAppId());
return AppUpdateCheckResponse.none(currentVersion); return AppUpdateCheckResponse.none(currentVersion);
} }
if (!TimiJava.isEmpty(product.getUpdateKey()) && !product.getUpdateKey().equals(req.getKey())) { AppRelease release = resolveChannelRelease(product, req);
log.warn("更新密钥不匹配,appId={}", req.getAppId()); if (release == null) {
return AppUpdateCheckResponse.none(currentVersion);
}
String channelCode = TimiJava.isEmpty(req.getChannel()) ? DEFAULT_CHANNEL : req.getChannel();
AppChannel channel = channelMapper.selectByProductAndCode(product.getId(), channelCode);
if (channel == null || TimiJava.isEmpty(channel.getReleaseId())) {
return AppUpdateCheckResponse.none(currentVersion);
}
AppRelease release = releaseMapper.select(channel.getReleaseId());
if (release == null || release.getStatus() != AppRelease.Status.PUBLISHED) {
return AppUpdateCheckResponse.none(currentVersion); return AppUpdateCheckResponse.none(currentVersion);
} }
int currentCode = parseInt(req.getVersionCode(), 0); int currentCode = parseInt(req.getVersionCode(), 0);
if (release.getKind() == AppRelease.Kind.NATIVE) { if (release.getKind() == AppRelease.Kind.NATIVE) {
return resolveNative(release, currentCode, currentVersion); // 低于外壳升级能力的包拿不动安装包,先补热更,否则它会把 APK 当 zip 解
boolean shellAware = 0 <= compareVersion(currentVersion, SHELL_AWARE_VERSION);
AppRelease nativeTarget = shellAware ? resolveNative(release, currentCode) : null;
if (nativeTarget != null) {
return buildResponse(nativeTarget, Boolean.TRUE.equals(nativeTarget.getMandatory()), true);
} }
return resolveBundle(release, product, currentCode, currentVersion, req.getDeviceId()); // 装不了安装包,或壳已经是最新:热更不能因为通道被原生包占着就断流
AppRelease bundle = resolveLatestBundle(product, currentCode, currentVersion, req.getDeviceId());
return bundle == null
? AppUpdateCheckResponse.none(currentVersion)
: buildResponse(bundle, false, false);
}
AppRelease target = resolveBundle(release, product, currentCode, currentVersion, req.getDeviceId());
return target == null
? AppUpdateCheckResponse.none(currentVersion)
: buildResponse(target, false, false);
} }
/// 原生包更新判断 /// 查询更新日志
/// ///
/// @param release 发布记录 /// 区间上界取通道当前版本,不走灰度与兼容区间判断。
/// 原因:客户端拿不到原生 versionCode,也无法保证命中灰度分桶,套用检查更新的判定会让日志
/// 大面积为空。日志是「这个产品最近发了什么」,不是「你这台设备能装什么」,分发决策仍由 check 负责
///
/// 有更新时返回 (当前版本, 通道版本] 区间;已是最新时区间为空,改为返回最近 TAIL_NOTES 个版本,
/// 否则更新完就看不到任何说明
///
/// @param req 插件上报信息
/// @return 变更说明,按版本号从新到旧
public AppUpdateNotesResponse notes(AppUpdateCheckRequest req) {
String currentVersion = currentVersion(req);
AppProduct product = resolveProduct(req);
if (product == null) {
return new AppUpdateNotesResponse(null, Collections.emptyList());
}
AppRelease target = resolveChannelRelease(product, req);
// 安装包不属于更新日志:通道指向原生包时,改用最新发布的热更包做上界
if (target == null || target.getKind() == AppRelease.Kind.NATIVE) {
target = latestPublishedBundle(product);
}
if (target == null) {
return new AppUpdateNotesResponse(null, Collections.emptyList());
}
// 当前版本不低于通道版本:已是最新,或回滚后反而超前
boolean upToDate = 0 <= compareVersion(currentVersion, target.getVersionName());
List<AppUpdateNote> notes = new ArrayList<>();
for (AppRelease item : releaseMapper.selectPublished(product.getId(), AppRelease.Kind.BUNDLE)) {
// 上界恒定:不展示比通道版本更新的记录
if (0 < compareVersion(item.getVersionName(), target.getVersionName())) {
continue;
}
// 有更新时才设下界,已是最新则不限
if (!upToDate && 0 >= compareVersion(item.getVersionName(), currentVersion)) {
continue;
}
notes.add(new AppUpdateNote(item.getVersionName(), item.getNote(), item.getPublishedAt()));
}
// 按版本号倒序,最新的在最前
notes.sort((a, b) -> compareVersion(b.getVersion(), a.getVersion()));
int limit = upToDate ? TAIL_NOTES : MAX_NOTES;
List<AppUpdateNote> limited = limit < notes.size() ? notes.subList(0, limit) : notes;
return new AppUpdateNotesResponse(target.getVersionName(), limited);
}
/// 取当前运行的 Web 包版本
///
/// @param req 插件上报信息
/// @return 版本号,未上报时为内置包标识
private String currentVersion(AppUpdateCheckRequest req) {
return TimiJava.isEmpty(req.getVersionName()) ? BUILTIN_VERSION : req.getVersionName();
}
/// 解析并校验产品
///
/// @param req 插件上报信息
/// @return 产品,不存在、已停用或密钥不匹配时为 null
private AppProduct resolveProduct(AppUpdateCheckRequest req) {
AppProduct product = productMapper.selectByAppKey(req.getAppId(), parsePlatform(req.getPlatform()));
if (product == null || !Boolean.TRUE.equals(product.getEnabled())) {
log.warn("应用不存在或已停用,appId={}", req.getAppId());
return null;
}
if (!TimiJava.isEmpty(product.getUpdateKey()) && !product.getUpdateKey().equals(req.getKey())) {
log.warn("更新密钥不匹配,appId={}", req.getAppId());
return null;
}
return product;
}
/// 取通道当前指向的发布记录
///
/// @param product 产品
/// @param req 插件上报信息
/// @return 发布记录,通道为空或指向的记录不可用时为 null
private AppRelease resolveChannelRelease(AppProduct product, AppUpdateCheckRequest req) {
String channelCode = TimiJava.isEmpty(req.getChannel()) ? DEFAULT_CHANNEL : req.getChannel();
AppChannel channel = channelMapper.selectByProductAndCode(product.getId(), channelCode);
if (channel == null || TimiJava.isEmpty(channel.getReleaseId())) {
return null;
}
AppRelease release = releaseMapper.select(channel.getReleaseId());
if (release == null || release.getStatus() != AppRelease.Status.PUBLISHED) {
return null;
}
return release;
}
/// 原生包是否需要更新
///
/// @param release 通道当前发布记录
/// @param currentCode 当前原生 versionCode /// @param currentCode 当前原生 versionCode
/// @param currentVersion 当前版本名 /// @return 需要更新时返回发布记录,否则返回 null
/// @return 更新响应 private AppRelease resolveNative(AppRelease release, int currentCode) {
private AppUpdateCheckResponse resolveNative(AppRelease release, int currentCode, String currentVersion) {
if (release.getVersionCode() == null || release.getVersionCode() <= currentCode) { if (release.getVersionCode() == null || release.getVersionCode() <= currentCode) {
return AppUpdateCheckResponse.none(currentVersion); return null;
} }
return buildResponse(release, Boolean.TRUE.equals(release.getMandatory())); return release;
} }
/// 热更包更新判断 /// 热更包是否需要更新
/// ///
/// @param release 发布记录 /// @param release 通道当前发布记录
/// @param product 产品 /// @param product 产品
/// @param currentCode 当前原生 versionCode /// @param currentCode 当前原生 versionCode
/// @param currentVersion 当前 Web 包版本 /// @param currentVersion 当前 Web 包版本
/// @param deviceId 设备标识 /// @param deviceId 设备标识
/// @return 更新响应 /// @return 需要更新时返回发布记录,否则返回 null
private AppUpdateCheckResponse resolveBundle( private AppRelease resolveBundle(
AppRelease release, AppRelease release,
AppProduct product, AppProduct product,
int currentCode, int currentCode,
@@ -107,23 +214,79 @@ public class AppVersionService {
) { ) {
// 原生版本不在兼容区间内,装了会崩 // 原生版本不在兼容区间内,装了会崩
if (release.getMinVersionCode() != null && currentCode < release.getMinVersionCode()) { if (release.getMinVersionCode() != null && currentCode < release.getMinVersionCode()) {
return AppUpdateCheckResponse.none(currentVersion); return null;
} }
if (release.getMaxVersionCode() != null && release.getMaxVersionCode() < currentCode) { if (release.getMaxVersionCode() != null && release.getMaxVersionCode() < currentCode) {
return AppUpdateCheckResponse.none(currentVersion); return null;
} }
// 已是最新,或低于当前版本时不做降级 // 已是最新,或低于当前版本时不做降级
if (release.getVersionName().equals(currentVersion)) { if (release.getVersionName().equals(currentVersion)) {
return AppUpdateCheckResponse.none(currentVersion); return null;
} }
if (0 < compareVersion(currentVersion, release.getVersionName())) { if (0 < compareVersion(currentVersion, release.getVersionName())) {
return AppUpdateCheckResponse.none(currentVersion); return null;
} }
// 灰度分桶不能含 releaseId,否则每次发版都会重排用户 // 灰度分桶不能含 releaseId,否则每次发版都会重排用户
if (!hitGray(release.getGrayPermille(), deviceId, product.getAppKey())) { if (!hitGray(release.getGrayPermille(), deviceId, product.getAppKey())) {
return AppUpdateCheckResponse.none(currentVersion); return null;
} }
return buildResponse(release, false); return release;
}
/// 查询设备此刻可用的最新热更包
///
/// 通道指向原生包时用它兜底:通道是单指针,原生包一上线热更就停发,
/// 而低于 SHELL_AWARE_VERSION 的设备又拿不动安装包,只能靠这里把它先升上去。
/// 只认 PUBLISHED 且版本高于当前包的记录,不会降级,最坏情况是多升一次。
///
/// @param product 产品
/// @param currentCode 当前原生 versionCode
/// @param currentVersion 当前 Web 包版本
/// @param deviceId 设备标识
/// @return 可用热更包,没有则返回 null
private AppRelease resolveLatestBundle(
AppProduct product,
int currentCode,
String currentVersion,
String deviceId
) {
AppRelease latest = null;
for (AppRelease item : releaseMapper.selectPublished(product.getId(), AppRelease.Kind.BUNDLE)) {
if (item.getMinVersionCode() != null && currentCode < item.getMinVersionCode()) {
continue;
}
if (item.getMaxVersionCode() != null && item.getMaxVersionCode() < currentCode) {
continue;
}
// 同级或更低不下发,避免把设备降回去
if (0 >= compareVersion(item.getVersionName(), currentVersion)) {
continue;
}
if (!hitGray(item.getGrayPermille(), deviceId, product.getAppKey())) {
continue;
}
if (latest == null || 0 < compareVersion(item.getVersionName(), latest.getVersionName())) {
latest = item;
}
}
return latest;
}
/// 取最近一次发布的热更包
///
/// 通道指向原生包时,更新日志没有「通道版本」可用,改用这里兜底。
/// 日志是「这个产品最近发了什么」,与设备能不能装无关,所以不套灰度与兼容区间
///
/// @param product 产品
/// @return 版本最高的已发布热更包,没有则返回 null
private AppRelease latestPublishedBundle(AppProduct product) {
AppRelease latest = null;
for (AppRelease item : releaseMapper.selectPublished(product.getId(), AppRelease.Kind.BUNDLE)) {
if (latest == null || 0 < compareVersion(item.getVersionName(), latest.getVersionName())) {
latest = item;
}
}
return latest;
} }
/// 判断设备是否命中灰度 /// 判断设备是否命中灰度
@@ -146,15 +309,18 @@ public class AppVersionService {
/// 构造更新响应 /// 构造更新响应
/// ///
/// note 为历史构建号时不下发,避免客户端把它当成更新说明展示
///
/// @param release 发布记录 /// @param release 发布记录
/// @param mandatory true 为强制更新 /// @param mandatory true 为强制更新
/// @param shell true 为外壳安装包,客户端需要下载后覆盖安装
/// @return 更新响应 /// @return 更新响应
private AppUpdateCheckResponse buildResponse(AppRelease release, boolean mandatory) { private AppUpdateCheckResponse buildResponse(AppRelease release, boolean mandatory, boolean shell) {
String url = ServletUriComponentsBuilder.fromCurrentContextPath() String url = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/attachment/download/") .path("/attach/download/")
.path(release.getAttachmentId()) .path(release.getAttachmentId())
.toUriString(); .toUriString();
return new AppUpdateCheckResponse(release.getVersionName(), url, release.getSha256(), mandatory); return new AppUpdateCheckResponse(release.getVersionName(), url, release.getSha256(), mandatory, shell, release.getNote());
} }
/// 比较版本号 /// 比较版本号
@@ -233,10 +399,8 @@ public class AppVersionService {
} }
checkCompatibility(release); checkCompatibility(release);
Long now = System.currentTimeMillis(); Long now = System.currentTimeMillis();
String fromReleaseId = channel.getReleaseId(); // 发布不指定灰度按全量处理:草稿默认是 0,直接沿用会让所有设备都拿不到包
if (grayPermille != null) { release.setGrayPermille(grayPermille == null ? (int) GRAY_BASE : grayPermille);
release.setGrayPermille(grayPermille);
}
release.setStatus(AppRelease.Status.PUBLISHED); release.setStatus(AppRelease.Status.PUBLISHED);
if (release.getPublishedAt() == null) { if (release.getPublishedAt() == null) {
release.setPublishedAt(now); release.setPublishedAt(now);
@@ -266,8 +430,7 @@ public class AppVersionService {
throw new IllegalArgumentException("目标发布不存在"); throw new IllegalArgumentException("目标发布不存在");
} }
Long now = System.currentTimeMillis(); Long now = System.currentTimeMillis();
String fromReleaseId = channel.getReleaseId(); target.setGrayPermille((int) GRAY_BASE);
target.setGrayPermille(10000);
target.setStatus(AppRelease.Status.PUBLISHED); target.setStatus(AppRelease.Status.PUBLISHED);
target.setUpdatedAt(now); target.setUpdatedAt(now);
releaseMapper.updateSelective(target); releaseMapper.updateSelective(target);
@@ -370,7 +533,7 @@ public class AppVersionService {
if (release.getStatus() == AppRelease.Status.PUBLISHED) { if (release.getStatus() == AppRelease.Status.PUBLISHED) {
throw new IllegalArgumentException("已发布的版本不能删除,请先撤回"); throw new IllegalArgumentException("已发布的版本不能删除,请先撤回");
} }
releaseMapper.destroy(releaseId); releaseMapper.delete(releaseId);
log("APP_RELEASE_DELETE", releaseId); log("APP_RELEASE_DELETE", releaseId);
} }
@@ -28,11 +28,22 @@ public class AppUpdateCheckResponse {
/// 是否为强制更新 /// 是否为强制更新
protected Boolean mandatory; protected Boolean mandatory;
/// 是否为外壳安装包
///
/// 客户端据此判断走热更还是下载安装包。字段名不能叫 kind:
/// Capgo 插件把 kind 视为错误响应的标记,收到后会直接判为检查失败
protected Boolean shell;
/// 变更说明,供 App 展示更新日志
///
/// 字段名不能叫 message:Capgo 插件把 message 当作错误信息,收到会直接判为检查失败
protected String note;
/// 构建无更新响应,version 与当前一致时插件不会下载 /// 构建无更新响应,version 与当前一致时插件不会下载
/// ///
/// @param currentVersion 当前运行的 Web 包版本 /// @param currentVersion 当前运行的 Web 包版本
/// @return 无更新响应 /// @return 无更新响应
public static AppUpdateCheckResponse none(String currentVersion) { public static AppUpdateCheckResponse none(String currentVersion) {
return new AppUpdateCheckResponse(currentVersion, "", null, false); return new AppUpdateCheckResponse(currentVersion, "", null, false, null, null);
} }
} }
@@ -0,0 +1,23 @@
package com.imyeyu.api.modules.app.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
///
/// 单条版本变更说明
///
/// @author Codex
/// @since 2026-11-13
@Data
@AllArgsConstructor
public class AppUpdateNote {
/// 版本号
protected String version;
/// 变更说明,来自发布记录的 note
protected String note;
/// 首次发布时间
protected Long publishedAt;
}
@@ -0,0 +1,24 @@
package com.imyeyu.api.modules.app.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
///
/// 应用更新日志响应
///
/// 供 App 的版本历史页使用,返回当前运行版本到目标版本之间的全部变更说明
///
/// @author Codex
/// @since 2026-11-13
@Data
@AllArgsConstructor
public class AppUpdateNotesResponse {
/// 目标版本号,为空表示当前没有可更新到的版本
protected String version;
/// 变更说明,按版本号从新到旧
protected List<AppUpdateNote> notes;
}
@@ -1,7 +1,7 @@
package com.imyeyu.api.modules.common.controller; package com.imyeyu.api.modules.common.controller;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode; import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode;
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.AttachmentVariantService; import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import com.imyeyu.api.modules.common.service.TempFileService; import com.imyeyu.api.modules.common.service.TempFileService;
@@ -68,6 +68,8 @@ public class AttachmentController {
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Attachment create(Attachment attachment) { public Attachment create(Attachment attachment) {
service.create(attachment); service.create(attachment);
attachment.setFile(null);
attachment.setInputStream(null);
return attachment; return attachment;
} }
@@ -258,7 +260,9 @@ public class AttachmentController {
} }
private void setDownloadHeader(Attachment attachment) throws UnsupportedEncodingException { private void setDownloadHeader(Attachment attachment) throws UnsupportedEncodingException {
if (attachment != null && TimiSpring.getRequest().getRequestURI().endsWith("/download") && attachment.getName() != null) { // 路径带 /download 就强制下载:/download/{id} 的结尾是 id,用 endsWith 匹配不到
boolean download = TimiSpring.getRequest().getRequestURI().contains("/download");
if (attachment != null && download && attachment.getName() != null) {
TimiSpring.getResponse().setHeader("Content-Disposition", Network.getFileDownloadHeader(attachment.getName())); TimiSpring.getResponse().setHeader("Content-Disposition", Network.getFileDownloadHeader(attachment.getName()));
} }
} }
@@ -56,13 +56,23 @@ public class Attachment extends UUIDEntity {
GAO_POINT_REDEMPTION_RETURN, GAO_POINT_REDEMPTION_RETURN,
GAO_RECYCLE_ITEM,
GAO_RECYCLE_EXCHANGE,
GAO_RECYCLE_EXCHANGE_REVOKE,
GAO_RECYCLE_PAYMENT,
GAO_CUSTOMER_FOLLOW_UP_REMINDER, GAO_CUSTOMER_FOLLOW_UP_REMINDER,
GAO_DATA_EXPORT, GAO_DATA_EXPORT,
TEMP_FILE, TEMP_FILE,
MIRROR MIRROR,
APP_RELEASE
} }
protected BizType bizType; protected BizType bizType;
@@ -77,6 +77,19 @@ public class Setting extends UUIDEntity {
JSON_OBJECT JSON_OBJECT
} }
/// 配置作用域
///
/// @author Codex
/// @since 2026-11-16
public enum Scope {
/// 系统级,bizId 固定为全零 UUID,启动时自动初始化
SYSTEM,
/// 业务级,bizId 为业务对象 ID,启动时不初始化
BUSINESS
}
@JsonView(ResponseView.Public.class) @JsonView(ResponseView.Public.class)
private String bizType; private String bizType;
@@ -316,6 +316,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.required"); throw new TimiException(TimiCode.ERROR, "exception.attachment.file.required");
} }
Attachment tempFile = mapper.selectRaw(tempFileId); Attachment tempFile = mapper.selectRaw(tempFileId);
if (tempFile == null) {
// 临时文件不存在或已过期,按业务错误拒绝,避免空指针变成 500
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
}
tempFile.setBizType(bizType); tempFile.setBizType(bizType);
tempFile.setBizId(bizId); tempFile.setBizId(bizId);
tempFile.setAttachType(item.getAttachType()); tempFile.setAttachType(item.getAttachType());
@@ -334,6 +338,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
// 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录 // 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录
Attachment current = mapper.selectRaw(item.getId()); Attachment current = mapper.selectRaw(item.getId());
Attachment tempFile = mapper.selectRaw(tempFileId); Attachment tempFile = mapper.selectRaw(tempFileId);
if (current == null || tempFile == null) {
// 附件或临时文件已被清理,按业务错误拒绝
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
}
// 源文件版本已变化,旧缩略图全部失效 // 源文件版本已变化,旧缩略图全部失效
variantService.deleteBySourceId(current.getId()); variantService.deleteBySourceId(current.getId());
// 删除旧 GridFS 文件 // 删除旧 GridFS 文件
@@ -89,10 +89,12 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
SALES_ORDER_CANCEL("SALES_ORDER:CANCEL", "销售订单取消", true, true), SALES_ORDER_CANCEL("SALES_ORDER:CANCEL", "销售订单取消", true, true),
SALES_ORDER_PRICE_OVERRIDE("SALES_ORDER:PRICE_OVERRIDE", "销售订单价格修改", true, true), SALES_ORDER_PRICE_OVERRIDE("SALES_ORDER:PRICE_OVERRIDE", "订单交易条件调整", true, true),
ORDER_FULFILLMENT_CREATE("ORDER_FULFILLMENT:CREATE", "统一履约创建", true, true), ORDER_FULFILLMENT_CREATE("ORDER_FULFILLMENT:CREATE", "统一履约创建", true, true),
ORDER_FULFILLMENT_UNSETTLED("ORDER_FULFILLMENT:UNSETTLED", "订单未结清履约", true, true),
ORDER_FULFILLMENT_READ("ORDER_FULFILLMENT:READ", "统一履约读取", true, true), ORDER_FULFILLMENT_READ("ORDER_FULFILLMENT:READ", "统一履约读取", true, true),
ORDER_FULFILLMENT_VERIFY("ORDER_FULFILLMENT:VERIFY", "统一履约核销", true, true), ORDER_FULFILLMENT_VERIFY("ORDER_FULFILLMENT:VERIFY", "统一履约核销", true, true),
@@ -119,15 +121,15 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
CUSTOMER_PACKAGE_GIFT_CREATE("CUSTOMER_PACKAGE:GIFT_CREATE", "客户套餐创建赠送", true, true), CUSTOMER_PACKAGE_GIFT_CREATE("CUSTOMER_PACKAGE:GIFT_CREATE", "客户套餐创建赠送", true, true),
FUND_RECORD_READ("FUND_RECORD:READ", "资金流水读取", true, true), FUND_RECORD_READ("FUND_RECORD:READ", "支付记录读取", true, true),
FUND_RECEIVE_CREATE("FUND_RECEIVE:CREATE", "线下收款创建", true, true), FUND_RECEIVE_CREATE("FUND_RECEIVE:CREATE", "支付登记", true, true),
FUND_RECEIVE_VERIFY("FUND_RECEIVE:VERIFY", "线下收款核销", true, true), FUND_RECEIVE_VERIFY("FUND_RECEIVE:VERIFY", "支付核销", true, true),
FUND_REFUND("FUND:REFUND", "套餐退款", true, true), FUND_REFUND("FUND:REFUND", "套餐退款", true, true),
FUND_REVOKE("FUND:REVOKE", "资金流水冲正", true, true), FUND_REVOKE("FUND:REVOKE", "支付冲正", true, true),
POINT_ACCOUNT_READ("POINT_ACCOUNT:READ", "客户积分账户读取", true, true), POINT_ACCOUNT_READ("POINT_ACCOUNT:READ", "客户积分账户读取", true, true),
@@ -153,6 +155,12 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
POINT_REDEEM_SKU_MANAGE("POINT_REDEEM_SKU:MANAGE", "积分兑换 SKU 配置管理", true, true), POINT_REDEEM_SKU_MANAGE("POINT_REDEEM_SKU:MANAGE", "积分兑换 SKU 配置管理", true, true),
RECYCLE_EXCHANGE_CONFIG_MANAGE("RECYCLE_EXCHANGE:CONFIG_MANAGE", "回收兑换配置管理", true, true),
RECYCLE_ACCOUNT_READ("RECYCLE_ACCOUNT:READ", "回收物额度查询", true, true),
RECYCLE_ACCOUNT_ADJUST("RECYCLE_ACCOUNT:ADJUST", "回收物额度调整", true, true),
STAT_READ("STAT:READ", "统计读取", false, false), STAT_READ("STAT:READ", "统计读取", false, false),
DATA_EXPORT("DATA_EXPORT", "数据导出", true, false), DATA_EXPORT("DATA_EXPORT", "数据导出", true, false),
@@ -0,0 +1,40 @@
package com.imyeyu.api.modules.gao.bean;
import com.imyeyu.api.annotation.SettingBizType;
import com.imyeyu.api.bean.SettingEnum;
import com.imyeyu.api.modules.common.entity.Setting;
import lombok.AllArgsConstructor;
import lombok.Getter;
/// GAO 门店配置
///
/// 门店级配置,bizId 为门店 ID
/// 启动时的内建配置初始化只覆盖系统级配置,门店配置查不到记录时按默认值兜底
///
/// @author Codex
/// @since 2026-11-15
@Getter
@SettingBizType("GAO_STORE")
@AllArgsConstructor
public enum GaoStoreSetting implements SettingEnum {
/// 客户生日提醒开关
CUSTOMER_BIRTHDAY_REMINDER_ENABLED(Boolean.FALSE.toString(), Setting.ValueType.BOOLEAN, "true 为启用客户生日提醒"),
/// 客户生日提醒负责人
CUSTOMER_BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID(null, Setting.ValueType.STRING, "客户生日提醒的负责人用户 ID");
final String defaultValue;
final Setting.ValueType valueType;
final String description;
/// 门店配置属于业务级配置,bizId 为门店 ID,启动时不初始化记录
///
/// @return 业务级作用域
@Override
public Setting.Scope getScope() {
return Setting.Scope.BUSINESS;
}
}
@@ -3,12 +3,16 @@ package com.imyeyu.api.modules.gao.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.bean.PermissionMatchMode; import com.imyeyu.api.bean.PermissionMatchMode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment; import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.service.GaoCustomerService; import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService; import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentActionRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentActionRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest;
@@ -48,6 +52,8 @@ import java.util.stream.Stream;
public class GaoOrderFulfillmentController { public class GaoOrderFulfillmentController {
private final GaoOrderFulfillmentService service; private final GaoOrderFulfillmentService service;
private final GaoSalesOrderService salesOrderService;
private final PermissionChecker permissionChecker;
private final GaoStoreScopeService storeScopeService; private final GaoStoreScopeService storeScopeService;
private final AttachmentService attachmentService; private final AttachmentService attachmentService;
private final GaoCustomerService customerService; private final GaoCustomerService customerService;
@@ -60,6 +66,8 @@ public class GaoOrderFulfillmentController {
public PageResult<GaoOrderFulfillment> list(@RequestBody GaoOrderFulfillmentPage page) { public PageResult<GaoOrderFulfillment> list(@RequestBody GaoOrderFulfillmentPage page) {
TimiException.required(page, "not found fulfillment page"); TimiException.required(page, "not found fulfillment page");
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId())); page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
page.setOrderAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_READ.getValue()));
page.setRecycleAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_READ.getValue()));
PageResult<GaoOrderFulfillment> result = service.pageByQuery(page); PageResult<GaoOrderFulfillment> result = service.pageByQuery(page);
fillTransient(result.getList()); fillTransient(result.getList());
return result; return result;
@@ -67,19 +75,20 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_READ)
@PostMapping("/detail") @PostMapping("/detail")
public GaoOrderFulfillment detail(@RequestParam String id) { public GaoOrderFulfillment detail(@RequestParam String id) {
GaoOrderFulfillment result = service.detail(id); GaoOrderFulfillment result = service.detail(id);
checkSource(result, GaoPermissionCode.ORDER_FULFILLMENT_READ, GaoPermissionCode.ORDER_FULFILLMENT_READ);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/create") @PostMapping("/create")
public GaoOrderFulfillment create(@RequestBody GaoOrderFulfillmentCreateRequest request) { public GaoOrderFulfillment create(@RequestBody GaoOrderFulfillmentCreateRequest request) {
TimiException.required(request, "not found fulfillment request");
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue());
GaoOrderFulfillment result = service.create(request); GaoOrderFulfillment result = service.create(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -87,9 +96,11 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(value = { GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY }, mode = PermissionMatchMode.ALL)
@PostMapping("/create-and-verify") @PostMapping("/create-and-verify")
public GaoOrderFulfillment createAndVerify(@RequestBody GaoOrderFulfillmentCreateRequest request) { public GaoOrderFulfillment createAndVerify(@RequestBody GaoOrderFulfillmentCreateRequest request) {
TimiException.required(request, "not found fulfillment request");
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue());
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY.getValue());
GaoOrderFulfillment result = service.createAndVerify(request); GaoOrderFulfillment result = service.createAndVerify(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -135,9 +146,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
@PostMapping("/prepare-stock") @PostMapping("/prepare-stock")
public GaoOrderFulfillment prepareStock(@RequestBody GaoOrderFulfillmentPrepareStockRequest request) { public GaoOrderFulfillment prepareStock(@RequestBody GaoOrderFulfillmentPrepareStockRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
GaoOrderFulfillment result = service.prepareStock(request); GaoOrderFulfillment result = service.prepareStock(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -145,9 +157,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
@PostMapping("/verify") @PostMapping("/verify")
public GaoOrderFulfillment verify(@RequestBody GaoOrderFulfillmentActionRequest request) { public GaoOrderFulfillment verify(@RequestBody GaoOrderFulfillmentActionRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
GaoOrderFulfillment result = service.verify(request); GaoOrderFulfillment result = service.verify(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -155,9 +168,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
@PostMapping("/reject") @PostMapping("/reject")
public GaoOrderFulfillment reject(@RequestBody GaoOrderFulfillmentActionRequest request) { public GaoOrderFulfillment reject(@RequestBody GaoOrderFulfillmentActionRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
GaoOrderFulfillment result = service.reject(request); GaoOrderFulfillment result = service.reject(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -165,9 +179,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/cancel") @PostMapping("/cancel")
public GaoOrderFulfillment cancel(@RequestBody GaoOrderFulfillmentActionRequest request) { public GaoOrderFulfillment cancel(@RequestBody GaoOrderFulfillmentActionRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_CREATE);
GaoOrderFulfillment result = service.cancel(request); GaoOrderFulfillment result = service.cancel(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -175,9 +190,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_REVOKE)
@PostMapping("/revoke") @PostMapping("/revoke")
public GaoOrderFulfillment revoke(@RequestBody GaoOrderFulfillmentRevokeRequest request) { public GaoOrderFulfillment revoke(@RequestBody GaoOrderFulfillmentRevokeRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_REVOKE, GaoPermissionCode.ORDER_FULFILLMENT_REVOKE);
GaoOrderFulfillment result = service.revoke(request); GaoOrderFulfillment result = service.revoke(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -188,11 +204,24 @@ public class GaoOrderFulfillmentController {
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_RETURN) @RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_RETURN)
@PostMapping("/return") @PostMapping("/return")
public GaoOrderFulfillment returnGoods(@RequestBody GaoOrderFulfillmentReturnRequest request) { public GaoOrderFulfillment returnGoods(@RequestBody GaoOrderFulfillmentReturnRequest request) {
TimiException.required(request, "履约退货请求不能为空");
GaoOrderFulfillment source = service.detail(request.getFulfillmentId());
TimiException.requiredTrue(!isRecycleOrder(source.getSalesOrderId()), "回收兑换履约请通过冲正处理");
GaoOrderFulfillment result = service.returnGoods(request); GaoOrderFulfillment result = service.returnGoods(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
} }
private void checkSource(GaoOrderFulfillment fulfillment, GaoPermissionCode order, GaoPermissionCode recycle) {
permissionChecker.checkAll(ModuleCode.GAO, (isRecycleOrder(fulfillment.getSalesOrderId()) ? recycle : order).getValue());
}
private boolean isRecycleOrder(String id) {
if (id == null || id.isBlank()) return false;
GaoSalesOrder order = salesOrderService.detail(id);
return order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE;
}
private void fillTransient(List<GaoOrderFulfillment> fulfillmentList) { private void fillTransient(List<GaoOrderFulfillment> fulfillmentList) {
if (fulfillmentList == null || fulfillmentList.isEmpty()) { if (fulfillmentList == null || fulfillmentList.isEmpty()) {
return; return;
@@ -0,0 +1,141 @@
package com.imyeyu.api.modules.gao.controller;
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.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleAccountMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoRecycleAccountService;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.GaoRecycleAccountAdjustRequest;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.imyeyu.utils.Time;
/// 客户回收物额度接口
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/recycle/account")
public class GaoRecycleAccountController {
private final GaoRecycleAccountMapper mapper;
private final GaoRecycleAccountService service;
private final GaoStoreScopeService scope;
private final GaoCustomerService customerService;
private final AttachmentService attachmentService;
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/yield/list")
public List<Map<String, Object>> yields(@RequestParam String storeId, @RequestParam String skuId) {
scope.checkStoreId(storeId);
List<Map<String, Object>> rows = mapper.yieldList(storeId, skuId);
List<String> itemIds = rows.stream().map(row -> (String) row.get("recycleItemId")).filter(java.util.Objects::nonNull).distinct().toList();
if (!itemIds.isEmpty()) {
Map<String, List<Attachment>> attachments = attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIds);
rows.forEach(row -> row.put("attachmentList", attachments.getOrDefault(row.get("recycleItemId"), List.of())));
}
return rows;
}
/// 产品详情里配置产出回收物用的批量查询,一次返回该产品所有 SKU 的产出行
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/yield/product/list")
public List<Map<String, Object>> yieldsByProduct(@RequestParam String storeId, @RequestParam String productId) {
scope.checkStoreId(storeId);
return mapper.yieldListByProduct(storeId, productId);
}
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/yield/save")
public void saveYield(@RequestParam String storeId, @RequestParam String skuId, @RequestParam String recycleItemId, @RequestParam BigDecimal quantityPerBase) {
scope.checkStoreId(storeId);
// 额度按三位小数记账,比例精度高于额度会让换算结果必然超出精度
TimiException.requiredTrue(0 < quantityPerBase.signum() && !(3 < quantityPerBase.stripTrailingZeros().scale())
&& !(12 < quantityPerBase.precision() - quantityPerBase.scale()), "产物数量比例最多保留三位小数");
TimiException.requiredTrue(mapper.validYield(storeId, skuId, recycleItemId) == 1, "商品或回收物不属于当前门店");
mapper.saveYield(UUID.randomUUID().toString(), storeId, skuId, recycleItemId, quantityPerBase, Time.now());
}
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/yield/delete")
public void deleteYield(@RequestParam String storeId, @RequestParam String skuId, @RequestParam String recycleItemId) {
scope.checkStoreId(storeId);
mapper.deleteYield(storeId, skuId, recycleItemId, Time.now());
}
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_READ)
@PostMapping("/list")
public List<Map<String, Object>> list(@RequestParam String storeId, @RequestParam String customerId) {
checkCustomer(storeId, customerId);
return mapper.listAccounts(storeId, customerId);
}
/// 按客户分页返回额度,汇总按回收物分别计算,避免混加不同单位。
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_READ)
@PostMapping("/customers")
public Map<String, Object> customers(@RequestParam String storeId, @RequestParam(required = false) String recycleItemId,
@RequestParam(required = false) String keyword, @RequestParam(required = false) List<String> customerIds, @RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
scope.checkStoreId(storeId);
int safeOffset = Math.max(0, offset);
int safeLimit = Math.max(1, Math.min(limit, 100));
List<String> ids = mapper.customerPage(storeId, recycleItemId, keyword, customerIds, safeOffset, safeLimit);
List<Map<String, Object>> rows = new java.util.ArrayList<>();
if (!ids.isEmpty()) {
Map<String, GaoCustomer> customers = customerService.mapByIdList(ids);
Map<String, List<Attachment>> photos = attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, ids, GaoCustomer.AttachType.PHOTO.name());
List<Map<String, Object>> accounts = mapper.customerAccounts(storeId, ids, recycleItemId);
for (String id : ids) {
GaoCustomer customer = customers.get(id);
if (customer == null) continue;
customer.setAttachmentList(photos.getOrDefault(id, List.of()));
rows.add(Map.of("customer", customer, "accounts", accounts.stream().filter(account -> id.equals(account.get("customerId"))).toList()));
}
}
return Map.of("list", rows, "total", mapper.customerCount(storeId, recycleItemId, keyword, customerIds), "totals", mapper.accountTotals(storeId, keyword, customerIds));
}
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_READ)
@PostMapping("/items")
public List<Map<String, Object>> accountItems(@RequestParam String storeId) {
scope.checkStoreId(storeId);
List<Map<String, Object>> items = mapper.accountItems(storeId);
List<String> ids = items.stream().map(item -> (String) item.get("id")).filter(java.util.Objects::nonNull).toList();
if (!ids.isEmpty()) {
Map<String, List<Attachment>> attachments = attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, ids);
items.forEach(item -> item.put("attachmentList", attachments.getOrDefault(item.get("id"), List.of())));
}
return items;
}
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_READ)
@PostMapping("/ledger")
public List<Map<String, Object>> ledger(@RequestParam String storeId, @RequestParam String customerId) {
checkCustomer(storeId, customerId);
return mapper.listLedger(storeId, customerId);
}
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_ADJUST)
@PostMapping("/adjust")
public void adjust(@RequestBody GaoRecycleAccountAdjustRequest request) {
TimiException.required(request, "请求不能为空");
checkCustomer(request.getStoreId(), request.getCustomerId());
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "调整原因不能为空");
TimiException.requiredTrue(request.getQuantity() != null && request.getQuantity().signum() != 0, "调整数量不能为零");
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
TimiException.requiredTrue(mapper.validItem(request.getStoreId(), request.getRecycleItemId()) == 1, "回收物不属于当前门店");
String bizId = UUID.nameUUIDFromBytes(request.getRequestNo().getBytes(java.nio.charset.StandardCharsets.UTF_8)).toString();
service.change(request.getStoreId(), request.getCustomerId(), request.getRecycleItemId(), request.getQuantity(), BigDecimal.ZERO, "MANUAL", bizId, request.getRequestNo(), request.getReason());
}
private void checkCustomer(String storeId, String customerId) {
scope.checkStoreId(storeId);
GaoCustomer customer = customerService.get(customerId);
TimiException.requiredTrue(customer != null && storeId.equals(customer.getStoreId()), "客户不属于当前门店");
}
}
@@ -0,0 +1,103 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
import com.imyeyu.api.modules.gao.service.GaoRecycleConfigService;
import com.imyeyu.api.modules.gao.vo.GaoRecycleItemRequest;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeRuleRequest;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
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 com.imyeyu.spring.bean.PageResult;
/// 回收物和兑换规则接口
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/recycle/config")
public class GaoRecycleConfigController {
private final GaoRecycleConfigService service;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/items")
public PageResult<GaoRecycleItem> items(@RequestParam(required = false) String storeId,
@RequestParam(required = false) GaoRecycleItem.Status status,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
return service.items(storeId, status, keyword, offset, limit);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/item/detail")
public GaoRecycleItem itemDetail(@RequestParam(required = false) String storeId, @RequestParam String id) {
return service.itemDetail(storeId, id);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/item/save")
public GaoRecycleItem saveItem(@RequestBody GaoRecycleItemRequest item) {
return service.saveItem(item);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/rules")
public PageResult<GaoRecycleExchangeRule> rules(@RequestParam(required = false) String storeId,
@RequestParam(required = false) GaoRecycleExchangeRule.Status status,
@RequestParam(required = false) String recycleItemId,
@RequestParam(required = false) String skuId,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
return service.rules(storeId, status, recycleItemId, skuId, keyword, offset, limit);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/rule/detail")
public GaoRecycleExchangeRule ruleDetail(@RequestParam(required = false) String storeId, @RequestParam String id) {
return service.ruleDetail(storeId, id);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/rule/save")
public GaoRecycleExchangeRule saveRule(@RequestBody GaoRecycleExchangeRuleRequest rule) {
return service.saveRule(rule);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
@PostMapping("/rule/delete")
public void deleteRule(@RequestParam(required = false) String storeId, @RequestParam String id) {
service.deleteRule(storeId, id);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
@PostMapping("/rules/active")
public PageResult<GaoRecycleExchangeRule> activeRules(@RequestParam(required = false) String storeId,
@RequestParam(required = false) String recycleItemId,
@RequestParam(required = false) String skuId,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
return service.rules(storeId, GaoRecycleExchangeRule.Status.ACTIVE, recycleItemId, skuId, keyword, offset, limit);
}
}
@@ -0,0 +1,41 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeQueryService;
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeViewService;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeDetail;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/// 回收兑换查询接口
///
/// 兑换单列表已并入交易订单查询,这里只保留详情
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/recycle/exchange")
public class GaoRecycleExchangeQueryController {
private final GaoRecycleExchangeQueryService service;
private final GaoRecycleExchangeViewService viewService;
/// 查询兑换单详情
///
/// @param id 兑换单 ID
/// @return 兑换单详情
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
@PostMapping("/detail")
public GaoRecycleExchangeDetail detail(@RequestParam String id) {
GaoRecycleExchangeDetail detail = service.detail(id);
viewService.fill(detail.getExchange());
viewService.fillActions(detail.getActionList());
return detail;
}
}
@@ -0,0 +1,35 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeWriteService;
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeViewService;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeCreateRequest;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
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.RestController;
/// 回收兑换交易接口
///
/// 兑换权益的领取、核销与冲正统一由 `/gao/order/fulfillment` 承载,
/// 这里只保留开单,取消统一通过订单接口处理。
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/recycle/exchange")
public class GaoRecycleExchangeWriteController {
private final GaoRecycleExchangeWriteService service;
private final GaoRecycleExchangeViewService viewService;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_CREATE)
@PostMapping("/create")
public GaoRecycleExchange create(@RequestBody GaoRecycleExchangeCreateRequest request) {
return viewService.fill(service.create(request));
}
}
@@ -0,0 +1,70 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
import com.imyeyu.api.modules.gao.service.GaoRecyclePaymentService;
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
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.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import com.imyeyu.api.bean.PermissionMatchMode;
import com.imyeyu.api.modules.gao.vo.GaoOrderTransactionView;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.bean.ModuleCode;
import java.util.List;
/// 回收物支付接口
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/recycle/payment")
public class GaoRecyclePaymentController {
private final GaoRecyclePaymentService service;
private final PermissionChecker permissions;
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_CREATE)
@PostMapping("/create")
public GaoRecyclePayment create(@RequestBody GaoRecyclePaymentRequest request) { return service.create(request); }
@RequireGaoPermission(value = {GaoPermissionCode.FUND_RECEIVE_CREATE, GaoPermissionCode.FUND_RECEIVE_VERIFY}, mode = PermissionMatchMode.ALL)
@PostMapping("/create-and-verify")
public GaoRecyclePayment createAndVerify(@RequestBody GaoRecyclePaymentRequest request) { return service.createAndVerify(request); }
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
@PostMapping("/list")
public List<GaoRecyclePayment> list(@RequestParam String orderId) { return service.list(orderId); }
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
@PostMapping("/search")
public List<GaoRecyclePayment> search(@RequestParam(required = false) String storeId,
@RequestParam(required = false) String customerId, @RequestParam(required = false) String orderId, @RequestParam(required = false) String status,
@RequestParam(required = false) Long beginAt, @RequestParam(required = false) Long endAt,
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "21") int limit) {
return service.search(storeId, customerId, orderId, status, beginAt, endAt, offset, limit);
}
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
@PostMapping("/transactions")
public List<GaoOrderTransactionView> transactions(@RequestParam String orderId) {
return service.transactions(orderId, permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.FUND_RECORD_READ.getValue()), permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.FUND_RECORD_READ.getValue()));
}
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_VERIFY)
@PostMapping("/verify")
public GaoRecyclePayment verify(@RequestBody GaoRecyclePaymentRequest request) { return service.verify(request.getPaymentId()); }
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_VERIFY)
@PostMapping("/reject")
public GaoRecyclePayment reject(@RequestBody GaoRecyclePaymentRequest request) { return service.release(request, true); }
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_CREATE)
@PostMapping("/cancel")
public GaoRecyclePayment cancel(@RequestBody GaoRecyclePaymentRequest request) { return service.release(request, false); }
@RequireGaoPermission(GaoPermissionCode.FUND_REVOKE)
@PostMapping("/revoke")
public GaoRecyclePayment revoke(@RequestBody GaoRecyclePaymentRequest request) { return service.revoke(request); }
}
@@ -0,0 +1,54 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.service.GaoRecycleStatService;
import com.imyeyu.api.modules.gao.vo.GaoRecycleStatView;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/// GAO 回收统计接口
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/recycle/stat")
public class GaoRecycleStatController {
private final GaoRecycleStatService service;
/// 按业务时间统计回收物收到、退回及净数量
///
/// @param storeId 门店 ID
/// @param startAt 区间起点,包含
/// @param endAt 区间终点,不包含
/// @return 回收统计
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
@PostMapping("/recycle")
public List<GaoRecycleStatView> recycle(@RequestParam(required = false) String storeId,
@RequestParam long startAt, @RequestParam long endAt) {
return service.recycle(storeId, startAt, endAt);
}
/// 按业务时间统计兑换、核销和冲正数量
///
/// @param storeId 门店 ID
/// @param startAt 区间起点,包含
/// @param endAt 区间终点,不包含
/// @return 兑换统计
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
@PostMapping("/exchange")
public List<GaoRecycleExchangeStatView> exchange(@RequestParam(required = false) String storeId,
@RequestParam long startAt, @RequestParam long endAt) {
return service.exchange(storeId, startAt, endAt);
}
}
@@ -1,11 +1,15 @@
package com.imyeyu.api.modules.gao.controller; package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.bean.PermissionMatchMode; import com.imyeyu.api.bean.PermissionMatchMode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoFundRecord; import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder; import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService; import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService;
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeWriteService;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeActionRequest;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService; import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest; import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest;
@@ -43,7 +47,9 @@ import org.springframework.web.bind.annotation.RestController;
public class GaoSalesOrderController { public class GaoSalesOrderController {
private final GaoSalesOrderService service; private final GaoSalesOrderService service;
private final PermissionChecker permissionChecker;
private final GaoOrderPaymentService paymentService; private final GaoOrderPaymentService paymentService;
private final GaoRecycleExchangeWriteService recycleExchangeWriteService;
private final GaoStoreScopeService storeScopeService; private final GaoStoreScopeService storeScopeService;
private final UserService userService; private final UserService userService;
@@ -54,6 +60,8 @@ public class GaoSalesOrderController {
public PageResult<GaoSalesOrder> list(@RequestBody GaoSalesOrderPage page) { public PageResult<GaoSalesOrder> list(@RequestBody GaoSalesOrderPage page) {
TimiException.required(page, "not found sales order page"); TimiException.required(page, "not found sales order page");
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId())); page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
page.setOrderAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_READ.getValue()));
page.setRecycleAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_READ.getValue()));
return service.pageByQuery(page); return service.pageByQuery(page);
} }
@@ -64,6 +72,8 @@ public class GaoSalesOrderController {
public GaoSalesOrderReceivableStatView summary(@RequestBody GaoSalesOrderPage page) { public GaoSalesOrderReceivableStatView summary(@RequestBody GaoSalesOrderPage page) {
TimiException.required(page, "not found sales order summary page"); TimiException.required(page, "not found sales order summary page");
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId())); page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
page.setOrderAllowed(true);
page.setRecycleAllowed(false);
return service.summary(page); return service.summary(page);
} }
@@ -83,6 +93,7 @@ public class GaoSalesOrderController {
@PostMapping("/detail") @PostMapping("/detail")
public GaoSalesOrder detail(@RequestParam String id) { public GaoSalesOrder detail(@RequestParam String id) {
GaoSalesOrder result = service.detail(id); GaoSalesOrder result = service.detail(id);
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_READ.getValue());
if (TimiJava.isNotEmpty(result.getCancelOperatorUserId())) { if (TimiJava.isNotEmpty(result.getCancelOperatorUserId())) {
result.setCancelOperator(userService.get(result.getCancelOperatorUserId())); result.setCancelOperator(userService.get(result.getCancelOperatorUserId()));
} }
@@ -106,6 +117,7 @@ public class GaoSalesOrderController {
public GaoSalesOrder update(@RequestBody GaoSalesOrderUpdateRequest request) { public GaoSalesOrder update(@RequestBody GaoSalesOrderUpdateRequest request) {
TimiException.required(request, "not found sales order update request"); TimiException.required(request, "not found sales order update request");
TimiException.required(request.getId(), "not found sales order.id"); TimiException.required(request.getId(), "not found sales order.id");
TimiException.requiredTrue(service.detail(request.getId()).getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单请通过兑换接口管理");
return service.updateRemarkAndAttachments(request); return service.updateRemarkAndAttachments(request);
} }
@@ -114,6 +126,16 @@ public class GaoSalesOrderController {
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_CANCEL) @RequireGaoPermission(GaoPermissionCode.SALES_ORDER_CANCEL)
@PostMapping("/cancel") @PostMapping("/cancel")
public GaoSalesOrder cancel(@RequestBody GaoSalesOrderCancelRequest request) { public GaoSalesOrder cancel(@RequestBody GaoSalesOrderCancelRequest request) {
TimiException.required(request, "订单取消请求不能为空");
GaoSalesOrder order = service.detail(request.getSalesOrderId());
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && order.getStatus() != GaoSalesOrder.Status.CANCELLED) {
GaoRecycleExchangeActionRequest action = new GaoRecycleExchangeActionRequest();
action.setExchangeId(order.getRecycleExchangeId());
action.setRequestNo(request.getRequestNo());
action.setReason(request.getReason());
recycleExchangeWriteService.cancelFromOrder(action, request);
return service.detail(request.getSalesOrderId());
}
return service.cancel(request); return service.cancel(request);
} }
@@ -0,0 +1,71 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.gao.entity.GaoStore;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.service.GaoStoreSettingService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
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.RestController;
import java.util.List;
import java.util.Map;
/// GAO 门店配置接口
///
/// 门店配置固定读写当前登录用户所属门店,不接受请求指定门店
/// 权限使用核心设置权限的读写,不额外引入 GAO 门店权限
///
/// @author Codex
/// @since 2026-11-15
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/store/setting")
public class GaoStoreSettingController {
private final GaoStoreSettingService service;
private final GaoStoreService storeService;
private final UserLoginService userLoginService;
/// 查询当前门店配置
///
/// 未配置的项返回默认值,不会创建记录
///
/// @param codeList 配置代码列表,为空返回全部
/// @return 配置代码与配置的映射
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.SETTING_READ)
@PostMapping("/map")
public Map<String, Setting> map(@RequestBody(required = false) List<String> codeList) {
return service.mapSetting(requireCurrentStoreId(), codeList);
}
/// 保存当前门店配置
///
/// @param settingList 配置列表
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.SETTING_UPDATE)
@PostMapping("/update")
public void update(@RequestBody List<Setting> settingList) {
service.updateSetting(requireCurrentStoreId(), settingList);
}
/// 获取当前登录用户所属门店 ID
///
/// @return 门店 ID
private String requireCurrentStoreId() {
GaoStore store = storeService.getByUserId(userLoginService.getRequireLoginUserId());
TimiException.required(store, "当前用户不属于任何门店");
return store.getId();
}
}
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.gao.entity; package com.imyeyu.api.modules.gao.entity;
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.entity.User;
import com.imyeyu.spring.annotation.table.Transient; import com.imyeyu.spring.annotation.table.Transient;
@@ -28,6 +29,16 @@ public class GaoCustomerFollowUpReminder extends UUIDEntity {
COMPLETED COMPLETED
} }
/// 提醒来源
public enum Source {
/// 手动创建
MANUAL,
/// 系统创建
SYSTEM
}
/// 通知渠道 /// 通知渠道
public enum NotifyChannel { public enum NotifyChannel {
@@ -56,6 +67,15 @@ public class GaoCustomerFollowUpReminder extends UUIDEntity {
/// 提醒状态 /// 提醒状态
private Status status; private Status status;
/// 来源
private Source source;
/// 系统创建的幂等键,格式为 业务类型:业务维度,手动创建为空
private String sourceKey;
/// 系统创建的扩展信息快照
private JsonNode metadata;
/// true 为发送站内通知 /// true 为发送站内通知
private Boolean internalNotifyEnabled; private Boolean internalNotifyEnabled;
@@ -118,4 +118,8 @@ public class GaoOrderFulfillment implements IDEntity<String>, Creatable, Updatab
/// 附件 /// 附件
@Transient @Transient
private List<Attachment> attachmentList; private List<Attachment> attachmentList;
/// 来源订单类型,列表展示用,来自销售订单
@Transient
private String orderType;
} }
@@ -1,7 +1,6 @@
package com.imyeyu.api.modules.gao.entity; package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.gao.vo.GaoProductSkuBaseUnitMigrationRequest;
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;
@@ -78,9 +77,9 @@ public class GaoProductSku extends UUIDEntity {
@Transient @Transient
private List<GaoProductSkuUnit> unitList; private List<GaoProductSkuUnit> unitList;
/// 基础单位迁移请求,仅用于 SKU 更新,不映射数据库列 /// true 为允许修改基础单位与单位换算系数;SKU 产生业务记录或库存后锁定
@Transient @Transient
private GaoProductSkuBaseUnitMigrationRequest baseUnitMigrationRequest; private Boolean unitEditable;
/// SKU 附件列表 /// SKU 附件列表
@Transient @Transient
@@ -0,0 +1,101 @@
package com.imyeyu.api.modules.gao.entity;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.util.List;
/// 回收兑换单
@Data
@EqualsAndHashCode(callSuper = true)
public class GaoRecycleExchange extends UUIDEntity {
/// 状态
public enum Status {
/// 待领取,尚有可领取权益
PENDING,
/// 已完成,权益全部领取完毕
COMPLETED,
/// 已撤销
CANCELLED
}
/// 门店 ID
private String storeId;
/// 客户 ID
private String customerId;
/// 请求幂等号
private String requestNo;
/// 请求摘要
private String requestFingerprint;
/// 规则 ID
private String ruleId;
/// 生成的销售订单 ID
private String salesOrderId;
/// 创建时兑换模板快照
private JsonNode ruleSnapshot;
/// 回收物 ID
private String recycleItemId;
/// 回收物当前是否允许小数数量
@Transient
private Boolean allowDecimalQuantity;
/// 回收物当前图片
@Transient
private List<Attachment> recycleItemAttachments;
/// 回收物名称快照
private String recycleNameSnapshot;
/// 回收物单位快照
private String recycleUnitSnapshot;
/// 规则回收数量快照
private BigDecimal ruleRecycleQuantity;
/// 模板份数,自由创建时为空
private Integer multiple;
/// 模板预设回收数量 = 规则回收数量 × 份数,自由创建时为空
private BigDecimal defaultRecycleQuantity;
/// 实际回收数量
private BigDecimal recycleQuantity;
/// 状态
private Status status;
/// 操作人 ID
private String operatorUserId;
/// 业务发生时间
private Long occurredAt;
/// 备注
private String remark;
/// 客户资料,展示用,由控制器批量填充
@Transient
private GaoCustomer customer;
/// 操作人,展示用,由控制器批量填充
@Transient
private User operator;
}
@@ -0,0 +1,54 @@
package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
/// 回收兑换操作记录
@Data
@EqualsAndHashCode(callSuper = true)
public class GaoRecycleExchangeAction extends UUIDEntity {
/// 撤销后门店最终保留的回收物数量
private BigDecimal retainedRecycleQuantity;
/// 操作类型。兑换权益的核销与冲正由履约单承载,兑换单只剩撤销。
public enum ActionType {
/// 撤销
CANCEL
}
/// 门店 ID
private String storeId;
/// 兑换单 ID
private String exchangeId;
/// 请求幂等号
private String requestNo;
/// 请求摘要
private String requestFingerprint;
/// 操作类型
private ActionType actionType;
/// 操作人 ID
private String operatorUserId;
/// 业务发生时间
private Long occurredAt;
/// 原因
private String reason;
/// 备注
private String remark;
/// 操作人,展示用,由控制器批量填充
@Transient
private User operator;
}
@@ -0,0 +1,59 @@
package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
import com.imyeyu.api.modules.common.entity.Attachment;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.util.List;
/// 回收兑换规则
@Data
@EqualsAndHashCode(callSuper = true)
public class GaoRecycleExchangeRule extends UUIDEntity {
/// 兑换模板明细
@Transient
private List<GaoRecycleExchangeRuleItem> itemList;
/// 状态
public enum Status {
/// 启用
ACTIVE,
/// 停用
INACTIVE
}
/// 门店 ID
private String storeId;
/// 回收物 ID
private String recycleItemId;
/// 单份模板回收数量
private BigDecimal recycleQuantity;
/// 状态
private Status status;
/// 排序值
private Integer sort;
/// 备注
private String remark;
/// 回收物名称,展示用,由服务批量填充
@Transient
private String recycleName;
/// 回收物计量单位,展示用,由服务批量填充
@Transient
private String recycleUnit;
/// 回收物图片,展示用
@Transient
private List<Attachment> recycleItemAttachments;
}
@@ -0,0 +1,34 @@
package com.imyeyu.api.modules.gao.entity;
import lombok.Data;
import java.math.BigDecimal;
/// 回收兑换模板明细
@Data
public class GaoRecycleExchangeRuleItem {
private String id;
private String ruleId;
private String skuId;
private String skuUnitId;
private BigDecimal exchangeQuantity;
private Integer sort;
private Long createdAt;
/// 展示用产品名称
private String productName;
/// 展示用 SKU 名称
private String skuName;
/// 展示用规格摘要
private String specSummary;
/// 展示用单位名称
private String unitName;
/// 展示用 SKU 编码
private String skuCode;
/// 展示用产品类型
private String productType;
/// true 为启用库存管理
private Boolean stockEnabled;
/// true 为允许小数数量
private Boolean allowDecimalQuantity;
}
@@ -0,0 +1,46 @@
package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.spring.entity.UUIDEntity;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.spring.annotation.table.Transient;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
/// 回收物类型
@Data
@EqualsAndHashCode(callSuper = true)
public class GaoRecycleItem extends UUIDEntity {
/// 状态
public enum Status {
/// 启用
ACTIVE,
/// 停用
INACTIVE
}
/// 门店 ID
private String storeId;
/// 名称
private String name;
/// 回收计量单位
private String unitName;
/// 是否允许小数数量
private Boolean allowDecimalQuantity;
/// 状态
private Status status;
/// 图片附件
@Transient
private List<Attachment> attachmentList;
/// 备注
private String remark;
}
@@ -0,0 +1,60 @@
package com.imyeyu.api.modules.gao.entity;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.user.entity.User;
import java.math.BigDecimal;
import java.util.List;
/// 回收物支付记录
@Data
@EqualsAndHashCode(callSuper = true)
public class GaoRecyclePayment extends UUIDEntity {
/// 支付状态
public enum Status {PENDING, VERIFIED, REJECTED, CANCELLED, REVOKED}
private String storeId;
private String customerId;
private String orderId;
private String recycleItemId;
private String requestNo;
/// 请求内容摘要
private String requestFingerprint;
private BigDecimal quantity;
private Status status;
private String sourcePaymentId;
private String operatorUserId;
private String verifierUserId;
private Long occurredAt;
private Long verifiedAt;
private String reason;
private Boolean returnedToCustomer;
/// 支付附件
@Transient
private List<Attachment> attachmentList;
/// 带方向的数量,支付为正、冲正为负
///
/// 冲正记录本身也是 VERIFIED,直接按 quantity 求和会把冲正重复计入,
/// 统计与页面统一用这个字段累加。
@Transient
private BigDecimal signedQuantity;
/// 关联兑换单及客户展示信息
@Transient
private String recycleExchangeId;
@Transient
private String recycleName;
@Transient
private String recycleUnit;
@Transient
private GaoCustomer customer;
@Transient
private User operator;
@Transient
private User verifier;
}
@@ -8,6 +8,7 @@ import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import java.util.List; import java.util.List;
import java.math.BigDecimal;
/// GAO 销售订单 /// GAO 销售订单
/// ///
@@ -24,7 +25,10 @@ public class GaoSalesOrder extends UUIDEntity {
PACKAGE, PACKAGE,
/// 直接产品订单 /// 直接产品订单
DIRECT_PRODUCT DIRECT_PRODUCT,
/// 回收兑换订单
RECYCLE
} }
/// 订单状态 /// 订单状态
@@ -78,6 +82,32 @@ public class GaoSalesOrder extends UUIDEntity {
/// 订单类型 /// 订单类型
private OrderType orderType; private OrderType orderType;
/// 回收物 ID
private String recycleItemId;
/// 需核销回收物数量
private BigDecimal recycleRequiredQuantity;
/// 回收物名称,展示用,仅回收兑换订单填充
@Transient
private String recycleItemName;
/// 回收物计量单位,展示用,仅回收兑换订单填充
@Transient
private String recycleUnit;
/// 对应兑换单 ID,展示用,仅回收兑换订单填充
@Transient
private String recycleExchangeId;
/// 已核销回收物数量,列表展示用
@Transient
private BigDecimal recycleVerifiedQuantity;
/// 待核销回收物数量,列表展示用
@Transient
private BigDecimal recyclePendingQuantity;
/// 订单状态 /// 订单状态
private Status status; private Status status;
@@ -25,7 +25,10 @@ public class GaoSalesOrderItem extends UUIDEntity {
DIRECT_PRODUCT, DIRECT_PRODUCT,
/// 套餐权益 /// 套餐权益
PACKAGE_ENTITLEMENT PACKAGE_ENTITLEMENT,
/// 回收兑换权益
RECYCLE_ENTITLEMENT
} }
/// 销售订单 ID /// 销售订单 ID
@@ -1,5 +1,6 @@
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.GaoCustomerFollowUpReminder; import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPage; import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPage;
import com.imyeyu.spring.mapper.BaseMapper; import com.imyeyu.spring.mapper.BaseMapper;
@@ -50,4 +51,18 @@ public interface GaoCustomerFollowUpReminderMapper extends BaseMapper<GaoCustome
/// @return 受影响行数 /// @return 受影响行数
int bindSmsNotifyDetailId(@Param("idList") Collection<String> idList, int bindSmsNotifyDetailId(@Param("idList") Collection<String> idList,
@Param("smsNotifyDetailId") String smsNotifyDetailId); @Param("smsNotifyDetailId") String smsNotifyDetailId);
/// 查询指定门店的生日候选客户
///
/// 回填判断生日所需的字段,生日月日由调用方按历法计算,不在此处过滤
///
/// @param storeIdList 门店 ID 列表
/// @return 生日候选客户
List<GaoCustomer> selectBirthdayCandidate(@Param("storeIdList") Collection<String> storeIdList);
/// 创建系统提醒,幂等键冲突时跳过
///
/// @param reminder 提醒
/// @return 受影响行数,0 为幂等键已存在
int insertIgnore(GaoCustomerFollowUpReminder reminder);
} }
@@ -14,37 +14,27 @@ import java.util.List;
/// @since 2026-09-02 /// @since 2026-09-02
public interface GaoOrderFulfillmentMapper extends BaseMapper<GaoOrderFulfillment, String> { public interface GaoOrderFulfillmentMapper extends BaseMapper<GaoOrderFulfillment, String> {
/// 按门店和幂等号查询履约单
GaoOrderFulfillment selectByRequestNo(@Param("storeId") String storeId, @Param("requestNo") String requestNo); GaoOrderFulfillment selectByRequestNo(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
/// 按批量幂等号前缀查询履约单
List<GaoOrderFulfillment> selectByRequestNoPrefix(@Param("storeId") String storeId, @Param("requestNoPrefix") String requestNoPrefix); List<GaoOrderFulfillment> selectByRequestNoPrefix(@Param("storeId") String storeId, @Param("requestNoPrefix") String requestNoPrefix);
/// 按 ID 查询履约单
GaoOrderFulfillment selectById(@Param("id") String id); GaoOrderFulfillment selectById(@Param("id") String id);
/// 按 ID 批量查询履约单
List<GaoOrderFulfillment> selectByIdList(@Param("idList") Collection<String> idList); List<GaoOrderFulfillment> selectByIdList(@Param("idList") Collection<String> idList);
/// 锁定履约单
GaoOrderFulfillment selectForUpdate(@Param("id") String id); GaoOrderFulfillment selectForUpdate(@Param("id") String id);
/// 按订单查询履约单
List<GaoOrderFulfillment> selectBySalesOrderId(@Param("salesOrderId") String salesOrderId); List<GaoOrderFulfillment> selectBySalesOrderId(@Param("salesOrderId") String salesOrderId);
/// 按冲正来源查询履约单
GaoOrderFulfillment selectBySourceFulfillmentId(@Param("sourceFulfillmentId") String sourceFulfillmentId); GaoOrderFulfillment selectBySourceFulfillmentId(@Param("sourceFulfillmentId") String sourceFulfillmentId);
/// 统计订单中仍占用权益的履约单
long countPendingBySalesOrderId(@Param("salesOrderId") String salesOrderId); long countPendingBySalesOrderId(@Param("salesOrderId") String salesOrderId);
/// 按条件统计履约单
long countByQuery(GaoOrderFulfillmentPage page); long countByQuery(GaoOrderFulfillmentPage page);
/// 按条件查询履约单
List<GaoOrderFulfillment> selectByQuery(GaoOrderFulfillmentPage page); List<GaoOrderFulfillment> selectByQuery(GaoOrderFulfillmentPage page);
/// 更新履约状态
int updateStatus(@Param("id") String id, @Param("status") GaoOrderFulfillment.Status status, int updateStatus(@Param("id") String id, @Param("status") GaoOrderFulfillment.Status status,
@Param("verifierUserId") String verifierUserId, @Param("verifiedAt") Long verifiedAt, @Param("verifierUserId") String verifierUserId, @Param("verifiedAt") Long verifiedAt,
@Param("reason") String reason); @Param("reason") String reason);
@@ -3,9 +3,7 @@ package com.imyeyu.api.modules.gao.mapper;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal; /// 产品编辑与引用检查 Mapper
/// 产品编辑、引用检查与单位迁移 Mapper
public interface GaoProductEditMapper { public interface GaoProductEditMapper {
int countProductReferences(@Param("productId") String productId); int countProductReferences(@Param("productId") String productId);
@@ -14,9 +12,6 @@ public interface GaoProductEditMapper {
int countUnitReferences(@Param("unitId") String unitId); int countUnitReferences(@Param("unitId") String unitId);
int countMigrationPrecisionLoss(@Param("skuId") String skuId, @Param("targetUnitId") String targetUnitId,
@Param("ratio") BigDecimal ratio);
int updateProductOrderSnapshots(@Param("productId") String productId, @Param("productName") String productName); int updateProductOrderSnapshots(@Param("productId") String productId, @Param("productName") String productName);
int updateProductFulfillmentSnapshots(@Param("productId") String productId, @Param("productName") String productName); int updateProductFulfillmentSnapshots(@Param("productId") String productId, @Param("productName") String productName);
@@ -55,20 +50,4 @@ public interface GaoProductEditMapper {
int updateUnitRedemptionSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName); int updateUnitRedemptionSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName);
int scaleSkuMinimumStock(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleProductStock(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleSalesOrderItems(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleFulfillmentItems(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleStockRecords(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scalePackageConfigItems(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scalePointRedemptions(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scalePointRedemptionReturns(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
} }
@@ -36,4 +36,10 @@ public interface GaoProductSkuMapper extends BaseMapper<GaoProductSku, String> {
/// 锁定 SKU /// 锁定 SKU
GaoProductSku selectForUpdate(@Param("id") String id); GaoProductSku selectForUpdate(@Param("id") String id);
/// 批量查询已产生业务记录或库存的 SKU ID
///
/// @param idList SKU ID 集合
/// @return 已产生业务记录或库存的 SKU ID 列表
List<String> selectReferencedSkuIdList(@Param("idList") Collection<String> idList);
} }
@@ -0,0 +1,88 @@
package com.imyeyu.api.modules.gao.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.math.BigDecimal;
import java.util.Map;
import java.util.List;
/// 回收物额度账户与流水
public interface GaoRecycleAccountMapper {
@Select("SELECT COUNT(*) FROM gao_recycle_item WHERE store_id=#{store} AND id=#{item}")
int validItem(@Param("store") String store, @Param("item") String item);
@Select("SELECT COUNT(*) FROM gao_product_sku s JOIN gao_recycle_item r ON r.store_id=s.store_id WHERE s.store_id=#{store} AND s.id=#{sku} AND r.id=#{item}")
int validYield(@Param("store") String store, @Param("sku") String sku, @Param("item") String item);
@Insert("INSERT INTO gao_recycle_product_yield (id,store_id,sku_id,recycle_item_id,quantity_per_base,created_at) VALUES (#{id},#{store},#{sku},#{item},#{quantity},#{now}) ON DUPLICATE KEY UPDATE quantity_per_base=VALUES(quantity_per_base),updated_at=VALUES(created_at),deleted_at=NULL")
void saveYield(@Param("id") String id, @Param("store") String store, @Param("sku") String sku, @Param("item") String item, @Param("quantity") BigDecimal quantity, @Param("now") long now);
@Update("UPDATE gao_recycle_product_yield SET deleted_at=#{now}, updated_at=#{now} WHERE store_id=#{store} AND sku_id=#{sku} AND recycle_item_id=#{item} AND deleted_at IS NULL")
void deleteYield(@Param("store") String store, @Param("sku") String sku, @Param("item") String item, @Param("now") long now);
@Select("SELECT a.id, a.customer_id AS customerId, a.recycle_item_id AS recycleItemId, a.balance, a.reserved, " +
"i.name AS recycleName, i.unit_name AS recycleUnit, a.created_at AS createdAt, a.updated_at AS updatedAt " +
"FROM gao_recycle_account a LEFT JOIN gao_recycle_item i ON i.id = a.recycle_item_id " +
"WHERE a.store_id=#{store} AND a.customer_id=#{customer} AND a.deleted_at IS NULL ORDER BY a.recycle_item_id")
List<Map<String, Object>> listAccounts(@Param("store") String store, @Param("customer") String customer);
/// 按客户分页,筛选条件与汇总使用相同的有效账户范围。
@Select("<script>SELECT a.customer_id FROM gao_recycle_account a JOIN gao_customer c ON c.id=a.customer_id AND c.store_id=a.store_id AND c.deleted_at IS NULL WHERE a.store_id=#{store} AND a.deleted_at IS NULL AND a.balance > 0 <if test='customers != null and !customers.isEmpty()'> AND a.customer_id IN <foreach collection='customers' item='customer' open='(' separator=',' close=')'>#{customer}</foreach> </if> <if test='keyword != null and keyword != &quot;&quot;'> AND (c.name LIKE CONCAT('%',#{keyword},'%') OR c.code LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_full LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_initial LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_mixed LIKE CONCAT('%',#{keyword},'%')) </if> <if test='item != null and item != &quot;&quot;'> AND a.recycle_item_id=#{item} </if> GROUP BY a.customer_id ORDER BY a.customer_id LIMIT #{limit} OFFSET #{offset}</script>")
List<String> customerPage(@Param("store") String store, @Param("item") String item, @Param("keyword") String keyword, @Param("customers") List<String> customers, @Param("offset") int offset, @Param("limit") int limit);
@Select("<script>SELECT COUNT(DISTINCT a.customer_id) FROM gao_recycle_account a JOIN gao_customer c ON c.id=a.customer_id AND c.store_id=a.store_id AND c.deleted_at IS NULL WHERE a.store_id=#{store} AND a.deleted_at IS NULL AND a.balance > 0 <if test='customers != null and !customers.isEmpty()'> AND a.customer_id IN <foreach collection='customers' item='customer' open='(' separator=',' close=')'>#{customer}</foreach> </if> <if test='keyword != null and keyword != &quot;&quot;'> AND (c.name LIKE CONCAT('%',#{keyword},'%') OR c.code LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_full LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_initial LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_mixed LIKE CONCAT('%',#{keyword},'%')) </if> <if test='item != null and item != &quot;&quot;'> AND a.recycle_item_id=#{item} </if></script>")
long customerCount(@Param("store") String store, @Param("item") String item, @Param("keyword") String keyword, @Param("customers") List<String> customers);
@Select("<script>SELECT a.customer_id AS customerId, a.recycle_item_id AS recycleItemId, a.balance, a.reserved, i.name AS recycleName, i.unit_name AS recycleUnit FROM gao_recycle_account a LEFT JOIN gao_recycle_item i ON i.id=a.recycle_item_id AND i.store_id=a.store_id WHERE a.store_id=#{store} AND a.deleted_at IS NULL AND a.balance > 0 AND a.customer_id IN <foreach collection='customers' item='customer' open='(' separator=',' close=')'>#{customer}</foreach> <if test='item != null and item != &quot;&quot;'> AND a.recycle_item_id=#{item} </if> ORDER BY a.recycle_item_id</script>")
List<Map<String, Object>> customerAccounts(@Param("store") String store, @Param("customers") List<String> customers, @Param("item") String item);
@Select("<script>SELECT a.recycle_item_id AS recycleItemId, i.name AS recycleName, i.unit_name AS recycleUnit, SUM(a.balance) AS balance, SUM(a.reserved) AS reserved FROM gao_recycle_account a JOIN gao_customer c ON c.id=a.customer_id AND c.store_id=a.store_id AND c.deleted_at IS NULL LEFT JOIN gao_recycle_item i ON i.id=a.recycle_item_id AND i.store_id=a.store_id WHERE a.store_id=#{store} AND a.deleted_at IS NULL AND a.balance > 0 <if test='customers != null and !customers.isEmpty()'> AND a.customer_id IN <foreach collection='customers' item='customer' open='(' separator=',' close=')'>#{customer}</foreach> </if> <if test='keyword != null and keyword != &quot;&quot;'> AND (c.name LIKE CONCAT('%',#{keyword},'%') OR c.code LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_full LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_initial LIKE CONCAT('%',#{keyword},'%') OR c.name_pinyin_mixed LIKE CONCAT('%',#{keyword},'%')) </if> GROUP BY a.recycle_item_id, i.name, i.unit_name ORDER BY i.name, a.recycle_item_id</script>")
List<Map<String, Object>> accountTotals(@Param("store") String store, @Param("keyword") String keyword, @Param("customers") List<String> customers);
/// 额度查询权限可用的回收物选项。
@Select("SELECT id, name, unit_name AS unitName, status FROM gao_recycle_item WHERE store_id=#{store} ORDER BY name, id")
List<Map<String, Object>> accountItems(@Param("store") String store);
@Select("SELECT id, account_id AS accountId, store_id AS storeId, customer_id AS customerId, recycle_item_id AS recycleItemId, " +
"biz_type AS bizType, biz_id AS bizId, request_no AS requestNo, balance_delta AS balanceDelta, reserved_delta AS reservedDelta, " +
"balance_after AS balanceAfter, reserved_after AS reservedAfter, operator_user_id AS operatorUserId, reason, created_at AS createdAt " +
"FROM gao_recycle_ledger WHERE store_id=#{store} AND customer_id=#{customer} ORDER BY created_at DESC LIMIT 100")
List<Map<String, Object>> listLedger(@Param("store") String store, @Param("customer") String customer);
@Select("SELECT recycle_item_id,quantity_per_base FROM gao_recycle_product_yield WHERE store_id=#{store} AND sku_id=#{sku} AND deleted_at IS NULL ORDER BY recycle_item_id")
List<Map<String, Object>> yields(@Param("store") String store, @Param("sku") String sku);
/// 配置页需要的字段用驼峰返回,同时带上回收物名称与单位
@Select("SELECT y.recycle_item_id AS recycleItemId, y.quantity_per_base AS quantityPerBase, " +
"i.name AS recycleName, i.unit_name AS recycleUnit, i.allow_decimal_quantity AS allowDecimalQuantity " +
"FROM gao_recycle_product_yield y LEFT JOIN gao_recycle_item i ON i.id = y.recycle_item_id " +
"WHERE y.store_id=#{store} AND y.sku_id=#{sku} AND y.deleted_at IS NULL ORDER BY y.recycle_item_id")
List<Map<String, Object>> yieldList(@Param("store") String store, @Param("sku") String sku);
/// 产品维度的产出配置:一个产品下所有 SKU 的产出行,按 SKU 排序返回
@Select("SELECT y.sku_id AS skuId, y.recycle_item_id AS recycleItemId, y.quantity_per_base AS quantityPerBase, " +
"i.name AS recycleName, i.unit_name AS recycleUnit, s.name AS skuName, s.spec_summary AS skuSpecSummary " +
"FROM gao_recycle_product_yield y " +
"JOIN gao_product_sku s ON s.id = y.sku_id AND s.deleted_at IS NULL " +
"LEFT JOIN gao_recycle_item i ON i.id = y.recycle_item_id " +
"WHERE y.store_id=#{store} AND s.product_id=#{product} AND y.deleted_at IS NULL " +
"ORDER BY s.sort, s.name, y.recycle_item_id")
List<Map<String, Object>> yieldListByProduct(@Param("store") String store, @Param("product") String product);
@Select("SELECT recycle_item_id,balance_delta FROM gao_recycle_ledger WHERE biz_type='FULFILLMENT_YIELD' AND biz_id=#{biz} ORDER BY recycle_item_id")
List<Map<String, Object>> yieldsByFulfillment(@Param("biz") String biz);
@Insert("INSERT IGNORE INTO gao_recycle_account (id,store_id,customer_id,recycle_item_id,balance,reserved,created_at) VALUES (#{id},#{store},#{customer},#{item},0,0,#{now})")
void ensure(@Param("id") String id, @Param("store") String store, @Param("customer") String customer, @Param("item") String item, @Param("now") long now);
@Select("SELECT id,balance,reserved FROM gao_recycle_account WHERE store_id=#{store} AND customer_id=#{customer} AND recycle_item_id=#{item} FOR UPDATE")
Map<String, Object> lock(@Param("store") String store, @Param("customer") String customer, @Param("item") String item);
@Select("SELECT customer_id,recycle_item_id,biz_type,biz_id,balance_delta,reserved_delta,reason FROM gao_recycle_ledger WHERE store_id=#{store} AND request_no=#{request} FOR UPDATE")
Map<String, Object> findRequest(@Param("store") String store, @Param("request") String request);
@Update("UPDATE gao_recycle_account SET balance=balance+#{balance},reserved=reserved+#{reserved},updated_at=#{now} WHERE id=#{id} AND balance+#{balance} >= 0 AND reserved+#{reserved} >= 0 AND reserved+#{reserved} <= balance+#{balance}")
int change(@Param("id") String id, @Param("balance") BigDecimal balance, @Param("reserved") BigDecimal reserved, @Param("now") long now);
@Insert("INSERT INTO gao_recycle_ledger (id,account_id,store_id,customer_id,recycle_item_id,biz_type,biz_id,request_no,balance_delta,reserved_delta,balance_after,reserved_after,operator_user_id,reason,created_at) SELECT #{id},id,store_id,customer_id,recycle_item_id,#{type},#{biz},#{request},#{balance},#{reserved},balance,reserved,#{operator},#{reason},#{now} FROM gao_recycle_account WHERE id=#{account}")
void ledger(@Param("id") String id, @Param("account") String account, @Param("type") String type, @Param("biz") String biz, @Param("request") String request, @Param("balance") BigDecimal balance, @Param("reserved") BigDecimal reserved, @Param("operator") String operator, @Param("reason") String reason, @Param("now") long now);
}
@@ -0,0 +1,170 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.Collection;
import java.util.List;
/// 回收配置数据访问
public interface GaoRecycleConfigMapper {
/// 查询模板明细
/// @param ruleId 模板 ID
/// @return 模板明细
@Select("SELECT * FROM gao_recycle_exchange_rule_item WHERE rule_id=#{ruleId} ORDER BY sort, id")
List<GaoRecycleExchangeRuleItem> ruleItems(@Param("ruleId") String ruleId);
/// 批量查询模板明细
/// @param ids 模板 ID 列表
/// @return 模板明细
@Select("<script>SELECT * FROM gao_recycle_exchange_rule_item WHERE rule_id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> ORDER BY sort, id</script>")
List<GaoRecycleExchangeRuleItem> ruleItemsByIds(@Param("ids") Collection<String> ids);
/// 新增模板明细
/// @param item 模板明细
@Insert("INSERT INTO gao_recycle_exchange_rule_item (id,rule_id,sku_id,sku_unit_id,exchange_quantity,sort,created_at) VALUES (#{id},#{ruleId},#{skuId},#{skuUnitId},#{exchangeQuantity},#{sort},#{createdAt})")
void insertRuleItem(GaoRecycleExchangeRuleItem item);
/// 删除模板明细
/// @param ruleId 模板 ID
@Delete("DELETE FROM gao_recycle_exchange_rule_item WHERE rule_id=#{ruleId}")
void deleteRuleItems(@Param("ruleId") String ruleId);
/// 删除模板
/// @param storeId 门店 ID
/// @param id 模板 ID
/// @return 删除数量
@Delete("DELETE FROM gao_recycle_exchange_rule WHERE store_id=#{storeId} AND id=#{id}")
int deleteRule(@Param("storeId") String storeId, @Param("id") String id);
/// 分页查询回收物
///
/// @param storeId 门店 ID
/// @param status 状态,为空不过滤
/// @param keyword 名称关键字,为空不过滤
/// @param offset 分页偏移量
/// @param limit 分页数量
/// @return 回收物结果
@Select("SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} "
+ "AND (#{status} IS NULL OR status = #{status}) "
+ "AND (#{keyword} IS NULL OR name LIKE CONCAT('%', #{keyword}, '%')) "
+ "ORDER BY created_at DESC LIMIT #{offset}, #{limit}")
List<GaoRecycleItem> items(@Param("storeId") String storeId, @Param("status") String status, @Param("keyword") String keyword,
@Param("offset") int offset, @Param("limit") int limit);
/// 统计回收物
///
/// @param storeId 门店 ID
/// @param status 状态,为空不过滤
/// @param keyword 名称关键字,为空不过滤
/// @return 统计回收物结果
@Select("SELECT COUNT(*) FROM gao_recycle_item WHERE store_id = #{storeId} "
+ "AND (#{status} IS NULL OR status = #{status}) "
+ "AND (#{keyword} IS NULL OR name LIKE CONCAT('%', #{keyword}, '%'))")
long countItems(@Param("storeId") String storeId, @Param("status") String status, @Param("keyword") String keyword);
/// 按 ID 批量查询回收物
///
/// @param storeId 门店 ID
/// @param idList 回收物 ID 列表
/// @return 回收物结果
@Select("<script>SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} AND id IN "
+ "<foreach collection='idList' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>")
List<GaoRecycleItem> itemsByIdList(@Param("storeId") String storeId, @Param("idList") Collection<String> idList);
/// 查询回收物
///
/// @param storeId 门店 ID
/// @param id 记录 ID
/// @return 回收物结果
@Select("SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} AND id = #{id}")
GaoRecycleItem itemById(@Param("storeId") String storeId, @Param("id") String id);
/// 锁定回收物
///
/// @param storeId 门店 ID
/// @param id 记录 ID
/// @return 锁定回收物结果
@Select("SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} AND id = #{id} FOR UPDATE")
GaoRecycleItem item(@Param("storeId") String storeId, @Param("id") String id);
/// 创建回收物
///
/// @param item 回收物
@Insert("INSERT INTO gao_recycle_item (id, store_id, name, unit_name, allow_decimal_quantity, status, remark, created_at) VALUES (#{id}, #{storeId}, #{name}, #{unitName}, #{allowDecimalQuantity}, #{status}, #{remark}, #{createdAt})")
void insertItem(GaoRecycleItem item);
/// 更新回收物
///
/// @param item 回收物
@Update("UPDATE gao_recycle_item SET name=#{name}, unit_name=#{unitName}, allow_decimal_quantity=#{allowDecimalQuantity}, status=#{status}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
void updateItem(GaoRecycleItem item);
/// 分页查询兑换规则
///
/// @param storeId 门店 ID
/// @param status 规则状态,为空不过滤
/// @param recycleItemId 回收物 ID,为空不过滤
/// @param skuId 兑换 SKU ID,为空不过滤
/// @param keyword 回收物名称关键字,为空不过滤
/// @param offset 分页偏移量
/// @param limit 分页数量
/// @return 兑换规则结果
@Select("SELECT rule.* FROM gao_recycle_exchange_rule rule WHERE rule.store_id = #{storeId} "
+ "AND (#{status} IS NULL OR rule.status = #{status}) "
+ "AND (#{recycleItemId} IS NULL OR rule.recycle_item_id = #{recycleItemId}) "
+ "AND (#{skuId} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_exchange_rule_item ri WHERE ri.rule_id=rule.id AND ri.sku_id=#{skuId})) "
+ "AND (#{keyword} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_item item WHERE item.id = rule.recycle_item_id AND item.name LIKE CONCAT('%', #{keyword}, '%'))) "
+ "ORDER BY rule.sort, rule.created_at DESC LIMIT #{offset}, #{limit}")
List<GaoRecycleExchangeRule> rules(@Param("storeId") String storeId, @Param("status") String status, @Param("recycleItemId") String recycleItemId,
@Param("skuId") String skuId, @Param("keyword") String keyword, @Param("offset") int offset, @Param("limit") int limit);
/// 统计兑换规则
///
/// @param storeId 门店 ID
/// @param status 规则状态,为空不过滤
/// @param recycleItemId 回收物 ID,为空不过滤
/// @param skuId 兑换 SKU ID,为空不过滤
/// @param keyword 回收物名称关键字,为空不过滤
/// @return 统计兑换规则结果
@Select("SELECT COUNT(*) FROM gao_recycle_exchange_rule rule WHERE rule.store_id = #{storeId} "
+ "AND (#{status} IS NULL OR rule.status = #{status}) "
+ "AND (#{recycleItemId} IS NULL OR rule.recycle_item_id = #{recycleItemId}) "
+ "AND (#{skuId} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_exchange_rule_item ri WHERE ri.rule_id=rule.id AND ri.sku_id=#{skuId})) "
+ "AND (#{keyword} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_item item WHERE item.id = rule.recycle_item_id AND item.name LIKE CONCAT('%', #{keyword}, '%')))")
long countRules(@Param("storeId") String storeId, @Param("status") String status, @Param("recycleItemId") String recycleItemId,
@Param("skuId") String skuId, @Param("keyword") String keyword);
/// 查询兑换规则
///
/// @param storeId 门店 ID
/// @param id 记录 ID
/// @return 兑换规则结果
@Select("SELECT * FROM gao_recycle_exchange_rule WHERE store_id = #{storeId} AND id = #{id}")
GaoRecycleExchangeRule ruleById(@Param("storeId") String storeId, @Param("id") String id);
/// 锁定兑换规则
///
/// @param storeId 门店 ID
/// @param id 记录 ID
/// @return 锁定兑换规则结果
@Select("SELECT * FROM gao_recycle_exchange_rule WHERE store_id = #{storeId} AND id = #{id} FOR UPDATE")
GaoRecycleExchangeRule rule(@Param("storeId") String storeId, @Param("id") String id);
/// 创建兑换规则
///
/// @param rule 兑换规则
@Insert("INSERT INTO gao_recycle_exchange_rule (id, store_id, recycle_item_id, recycle_quantity, status, sort, remark, created_at) VALUES (#{id}, #{storeId}, #{recycleItemId}, #{recycleQuantity}, #{status}, #{sort}, #{remark}, #{createdAt})")
void insertRule(GaoRecycleExchangeRule rule);
/// 更新兑换规则
///
/// @param rule 兑换规则
@Update("UPDATE gao_recycle_exchange_rule SET recycle_item_id=#{recycleItemId}, recycle_quantity=#{recycleQuantity}, status=#{status}, sort=#{sort}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
void updateRule(GaoRecycleExchangeRule rule);
}
@@ -0,0 +1,25 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/// 回收兑换查询
public interface GaoRecycleExchangeQueryMapper {
/// 查询兑换单
///
/// @param id 记录 ID
/// @return 兑换单结果
@Select("SELECT * FROM gao_recycle_exchange WHERE id = #{id}")
GaoRecycleExchange detail(String id);
/// 查询兑换操作记录
///
/// @param id 记录 ID
/// @return 兑换操作记录结果
@Select("SELECT * FROM gao_recycle_exchange_action WHERE exchange_id = #{id} ORDER BY created_at, id")
List<GaoRecycleExchangeAction> actions(String id);
}
@@ -0,0 +1,49 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/// 回收兑换写入查询
public interface GaoRecycleExchangeWriteMapper extends BaseMapper<GaoRecycleExchange, String> {
@Update("UPDATE gao_recycle_exchange SET status=#{status}, updated_at=#{updatedAt} WHERE sales_order_id=#{orderId} AND status IN ('PENDING','COMPLETED')")
int updateByOrderStatus(@Param("orderId") String orderId, @Param("status") String status, @Param("updatedAt") long updatedAt);
@Select("SELECT id FROM gao_store WHERE id = #{id} FOR UPDATE")
String lockStore(String id);
@Select("SELECT * FROM gao_recycle_exchange WHERE store_id=#{storeId} AND request_no=#{requestNo}")
GaoRecycleExchange byRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
@Select("SELECT * FROM gao_recycle_exchange WHERE store_id=#{storeId} AND id=#{id} FOR UPDATE")
GaoRecycleExchange lockExchange(@Param("storeId") String storeId, @Param("id") String id);
/// 不加锁按 ID 取单,只用于动作请求未带门店时反查归属门店;一致性仍由后续 lockExchange 保证
@Select("SELECT * FROM gao_recycle_exchange WHERE id=#{id}")
GaoRecycleExchange byId(@Param("id") String id);
/// 按生成的销售订单反查兑换单快照,订单详情用于跳转与展示回收物
///
/// @param orderId 销售订单 ID
/// @return 兑换单,只填 ID 与回收物名称、单位快照
@Select("SELECT id, recycle_name_snapshot, recycle_unit_snapshot FROM gao_recycle_exchange WHERE sales_order_id=#{orderId} LIMIT 1")
GaoRecycleExchange snapshotByOrderId(@Param("orderId") String orderId);
@Select("SELECT * FROM gao_recycle_exchange_action WHERE store_id=#{storeId} AND request_no=#{requestNo}")
GaoRecycleExchangeAction actionByRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
@Insert("INSERT INTO gao_recycle_exchange_action (id,store_id,exchange_id,request_no,request_fingerprint,action_type,operator_user_id,occurred_at,created_at,reason,remark,retained_recycle_quantity) VALUES (#{id},#{storeId},#{exchangeId},#{requestNo},#{requestFingerprint},#{actionType},#{operatorUserId},#{occurredAt},#{createdAt},#{reason},#{remark},#{retainedRecycleQuantity})")
void insertAction(GaoRecycleExchangeAction action);
/// 撤销兑换单。待领取和已完成都允许撤销,撤销后不能再领取
///
/// @param id 兑换单 ID
/// @param updatedAt 更新时间
/// @return 影响行数
@Update("UPDATE gao_recycle_exchange SET status = 'CANCELLED', updated_at = #{updatedAt} WHERE id = #{id} AND status IN ('PENDING', 'COMPLETED')")
int cancel(@Param("id") String id, @Param("updatedAt") long updatedAt);
}
@@ -0,0 +1,41 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
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.math.BigDecimal;
import java.util.List;
/// 回收物支付查询
public interface GaoRecyclePaymentMapper extends BaseMapper<GaoRecyclePayment, String> {
@Select("SELECT * FROM gao_recycle_payment WHERE id=#{id} FOR UPDATE")
GaoRecyclePayment lock(@Param("id") String id);
@Select("SELECT * FROM gao_recycle_payment WHERE id=#{id}")
GaoRecyclePayment byId(@Param("id") String id);
@Select("SELECT * FROM gao_recycle_payment WHERE store_id=#{storeId} AND request_no=#{requestNo}")
GaoRecyclePayment byRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
@Select("SELECT COALESCE(SUM(quantity),0) FROM gao_recycle_payment WHERE order_id=#{orderId} AND status IN ('PENDING','VERIFIED') AND source_payment_id IS NULL")
BigDecimal occupied(@Param("orderId") String orderId);
@Select("SELECT COALESCE(SUM(quantity),0) FROM gao_recycle_payment WHERE order_id=#{orderId} AND status='VERIFIED' AND source_payment_id IS NULL")
BigDecimal paid(@Param("orderId") String orderId);
@Select("SELECT * FROM gao_recycle_payment WHERE order_id=#{orderId} ORDER BY created_at, id")
List<GaoRecyclePayment> list(@Param("orderId") String orderId);
@Select({"<script>",
"SELECT p.*, e.id AS recycleExchangeId, e.recycle_name_snapshot AS recycleName, e.recycle_unit_snapshot AS recycleUnit",
"FROM gao_recycle_payment p LEFT JOIN gao_recycle_exchange e ON e.sales_order_id = p.order_id WHERE 1=1",
"<if test='storeId != null'> AND p.store_id = #{storeId}</if>",
"<if test='customerId != null and customerId != &quot;&quot;'> AND p.customer_id = #{customerId}</if>",
"<if test='orderId != null and orderId != &quot;&quot;'> AND p.order_id = #{orderId}</if>",
"<if test='status != null and status != &quot;&quot;'> AND p.status = #{status}</if>",
"<if test='beginAt != null'> AND p.occurred_at &gt;= #{beginAt}</if>",
"<if test='endAt != null'> AND p.occurred_at &lt;= #{endAt}</if>",
"ORDER BY p.occurred_at DESC, p.created_at DESC, p.id DESC LIMIT #{offset}, #{limit}",
"</script>"})
List<GaoRecyclePayment> search(@Param("storeId") String storeId, @Param("customerId") String customerId, @Param("orderId") String orderId,
@Param("status") String status, @Param("beginAt") Long beginAt, @Param("endAt") Long endAt,
@Param("offset") int offset, @Param("limit") int limit);
@Update("UPDATE gao_recycle_payment SET status=#{status}, verifier_user_id=#{user}, verified_at=#{time}, reason=#{reason}, updated_at=#{time} WHERE id=#{id} AND status=#{expected}")
int status(@Param("id") String id, @Param("expected") GaoRecyclePayment.Status expected, @Param("status") GaoRecyclePayment.Status status, @Param("user") String user, @Param("time") long time, @Param("reason") String reason);
}
@@ -0,0 +1,22 @@
package com.imyeyu.api.modules.gao.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.math.BigDecimal;
/// 回收实物流转查询
public interface GaoRecyclePhysicalMapper {
@Select("SELECT COALESCE(SUM(CASE WHEN direction='IN' THEN quantity ELSE -quantity END),0) FROM gao_recycle_physical_record WHERE order_id=#{orderId}")
BigDecimal balance(@Param("orderId") String orderId);
@Select("SELECT COALESCE(SUM(CASE WHEN direction='IN' THEN quantity ELSE -quantity END),0) FROM gao_recycle_physical_record WHERE order_id=#{orderId} AND payment_id=#{paymentId}")
BigDecimal paymentBalance(@Param("orderId") String orderId, @Param("paymentId") String paymentId);
@Insert("INSERT INTO gao_recycle_physical_record (id,store_id,customer_id,order_id,recycle_item_id,payment_id,source_type,source_id,direction,quantity,occurred_at,created_at) VALUES (#{id},#{storeId},#{customerId},#{orderId},#{itemId},#{paymentId},#{sourceType},#{sourceId},#{direction},#{quantity},#{occurredAt},#{createdAt})")
void insert(@Param("id") String id, @Param("storeId") String storeId, @Param("customerId") String customerId,
@Param("orderId") String orderId, @Param("itemId") String itemId, @Param("paymentId") String paymentId, @Param("sourceType") String sourceType,
@Param("sourceId") String sourceId, @Param("direction") String direction, @Param("quantity") BigDecimal quantity,
@Param("occurredAt") long occurredAt, @Param("createdAt") long createdAt);
}
@@ -0,0 +1,14 @@
package com.imyeyu.api.modules.gao.mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/// 回收兑换提醒查询
public interface GaoRecycleReminderMapper {
/// 查询存在待核销回收物支付的门店
/// @return 门店 ID 列表
@Select("SELECT DISTINCT store_id FROM gao_recycle_payment WHERE status = 'PENDING' AND source_payment_id IS NULL")
List<String> selectPendingStoreIds();
}
@@ -0,0 +1,28 @@
package com.imyeyu.api.modules.gao.mapper;
import com.imyeyu.api.modules.gao.vo.GaoRecycleStatView;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/// 回收统计 Mapper
public interface GaoRecycleStatMapper {
/// 按操作业务时间统计收到和退回数量
///
/// @param storeId 门店 ID
/// @param startAt 区间起点,包含
/// @param endAt 区间终点,不包含
/// @return 回收统计
List<GaoRecycleStatView> selectRecycleStats(@Param("storeId") String storeId,
@Param("startAt") long startAt, @Param("endAt") long endAt);
/// 按业务时间统计兑换、核销和冲正数量
///
/// @param storeId 门店 ID
/// @param startAt 区间起点,包含
/// @param endAt 区间终点,不包含
/// @return 兑换统计
List<GaoRecycleExchangeStatView> selectExchangeStats(@Param("storeId") String storeId,
@Param("startAt") long startAt, @Param("endAt") long endAt);
}
@@ -37,7 +37,7 @@ public interface GaoSalesOrderMapper extends BaseMapper<GaoSalesOrder, String> {
/// 查询客户仍可履约的 SKU 订单行 /// 查询客户仍可履约的 SKU 订单行
List<GaoQuickFulfillmentSourceRow> selectQuickFulfillmentSourceRows(@Param("storeId") String storeId, List<GaoQuickFulfillmentSourceRow> selectQuickFulfillmentSourceRows(@Param("storeId") String storeId,
@Param("customerId") String customerId, @Param("skuIdList") List<String> skuIdList, @Param("customerId") String customerId, @Param("skuIdList") List<String> skuIdList,
@Param("salesOrderIdList") List<String> salesOrderIdList, @Param("allowUnpaid") boolean allowUnpaid); @Param("salesOrderIdList") List<String> salesOrderIdList, @Param("allowUnpaid") boolean allowUnpaid, @Param("allowUnsettledRecycle") boolean allowUnsettledRecycle);
/// 按条件汇总订单金额 /// 按条件汇总订单金额
GaoSalesOrderReceivableStatView selectSummaryByQuery(GaoSalesOrderPage page); GaoSalesOrderReceivableStatView selectSummaryByQuery(GaoSalesOrderPage page);
@@ -23,6 +23,12 @@ public interface GaoStoreMapper extends BaseMapper<GaoStore, String> {
@Select("SELECT * FROM `gao_store` WHERE `auto_closed_day` = TRUE AND `status` = 'ACTIVE' " + NOT_DELETE) @Select("SELECT * FROM `gao_store` WHERE `auto_closed_day` = TRUE AND `status` = 'ACTIVE' " + NOT_DELETE)
List<GaoStore> selectAllByAutoClosedDay(); List<GaoStore> selectAllByAutoClosedDay();
/// 查询可用门店
///
/// @return 门店列表
@Select("SELECT * FROM `gao_store` WHERE `status` = 'ACTIVE' " + NOT_DELETE)
List<GaoStore> selectAllActivated();
/// 查询用户所属的可用门店 /// 查询用户所属的可用门店
/// ///
/// @param userId 用户 ID /// @param userId 用户 ID
@@ -0,0 +1,16 @@
package com.imyeyu.api.modules.gao.service;
/// GAO 客户生日提醒生成服务
///
/// @author Codex
/// @since 2026-11-15
public interface GaoCustomerBirthdayReminderService {
/// 生成当天需要创建的生日提醒
///
/// 按门店配置筛选启用生日提醒的门店,为 7 天后过生日的客户提前创建跟进提醒
/// 提醒时间取生日当天,站内通知和短信在生日当天发出
///
/// @return 实际创建数量
int generate();
}
@@ -1,8 +1,10 @@
package com.imyeyu.api.modules.gao.service; package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder; import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPage; import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPageResult; import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPageResult;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.spring.service.BaseService; import com.imyeyu.spring.service.BaseService;
/// GAO 客户跟进提醒服务 /// GAO 客户跟进提醒服务
@@ -34,6 +36,19 @@ public interface GaoCustomerFollowUpReminderService extends BaseService<GaoCusto
/// @param id 跟进提醒 ID /// @param id 跟进提醒 ID
void complete(String id); void complete(String id);
/// 为系统创建的提醒创建站内通知
///
/// 定时任务没有登录用户,站内通知的发送人使用系统用户
///
/// @param reminder 提醒,必须已持久化
/// @param subject 通知主题
/// @param content 通知正文
/// @param contentType 正文类型
/// @param responsibleUser 负责人
/// @return 通知详情 ID
String createSystemInternalNotify(GaoCustomerFollowUpReminder reminder, String subject, String content,
NotifyDetail.ContentType contentType, User responsibleUser);
/// 创建当天的短信聚合批次 /// 创建当天的短信聚合批次
void createSmsBatch(); void createSmsBatch();
} }
@@ -32,6 +32,8 @@ public interface GaoOrderFulfillmentService extends BaseService<GaoOrderFulfillm
/// 按销售订单查询履约历史 /// 按销售订单查询履约历史
List<GaoOrderFulfillment> listBySalesOrderId(String salesOrderId); List<GaoOrderFulfillment> listBySalesOrderId(String salesOrderId);
/// 按回收兑换单查询履约历史
/// 查询销售订单仍占用权益的履约单数量 /// 查询销售订单仍占用权益的履约单数量
long countPendingBySalesOrderId(String salesOrderId); long countPendingBySalesOrderId(String salesOrderId);
@@ -0,0 +1,96 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleAccountMapper;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;
import java.util.List;
import java.util.TreeMap;
import java.util.Objects;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillmentItem;
/// 客户回收物额度服务
@Service
@RequiredArgsConstructor
public class GaoRecycleAccountService {
private final GaoRecycleAccountMapper mapper;
private final UserLoginService login;
/// 按实际履约产生客户额度,规则结果写入流水快照
public void addFromFulfillment(String store, String customer, String fulfillmentId, List<GaoOrderFulfillmentItem> items) {
Map<String, BigDecimal> quantities = new TreeMap<>();
for (GaoOrderFulfillmentItem item : items) {
for (Map<String, Object> yield : mapper.yields(store, item.getSkuId())) {
String recycleId = (String) yield.get("recycle_item_id");
BigDecimal quantity = item.getBaseQuantity().multiply((BigDecimal) yield.get("quantity_per_base"))
.setScale(3, java.math.RoundingMode.DOWN);
// 换算不足 0.001 时不计入,避免整笔履约核销因为精度失败
if (quantity.signum() <= 0) {
continue;
}
quantities.merge(recycleId, quantity, BigDecimal::add);
}
}
for (var entry : quantities.entrySet()) {
change(store, customer, entry.getKey(), entry.getValue(), BigDecimal.ZERO, "FULFILLMENT_YIELD", fulfillmentId, "yield:" + fulfillmentId + ":" + entry.getKey(), null);
}
}
/// 撤回原履约产生的额度,不追溯历史履约
public void revokeFulfillment(String store, String customer, String sourceId, String reverseId) {
for (Map<String, Object> row : mapper.yieldsByFulfillment(sourceId)) {
String item = (String) row.get("recycle_item_id");
BigDecimal value = (BigDecimal) row.get("balance_delta");
change(store, customer, item, value.negate(), BigDecimal.ZERO, "FULFILLMENT_REVOKE", reverseId, "yield-revoke:" + reverseId + ":" + item, null);
}
}
/// 原子变更额度与预占并写入流水
///
/// @param storeId 门店 ID
/// @param customerId 客户 ID
/// @param recycleItemId 回收物 ID
/// @param balanceDelta 额度变化量
/// @param reservedDelta 预占变化量
/// @param bizType 业务类型
/// @param bizId 业务 ID
/// @param requestNo 幂等号
/// @param reason 原因
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void change(String storeId, String customerId, String recycleItemId, BigDecimal balanceDelta, BigDecimal reservedDelta, String bizType, String bizId, String requestNo, String reason) {
TimiException.required(storeId, "门店不能为空");
TimiException.required(customerId, "客户不能为空");
TimiException.required(recycleItemId, "回收物不能为空");
TimiException.required(balanceDelta, "额度变化不能为空");
TimiException.required(reservedDelta, "预占变化不能为空");
TimiException.requiredTrue(!(3 < balanceDelta.stripTrailingZeros().scale()) && !(3 < reservedDelta.stripTrailingZeros().scale()), "额度最多保留三位小数");
TimiException.requiredTrue(!(15 < balanceDelta.precision() - balanceDelta.scale()) && !(15 < reservedDelta.precision() - reservedDelta.scale()), "额度超出范围");
TimiException.required(requestNo, "请求号不能为空");
TimiException.requiredTrue(!requestNo.isBlank() && !(128 < requestNo.length()), "请求号无效");
TimiException.requiredTrue(bizType != null && !bizType.isBlank() && !(32 < bizType.length()) && bizId != null && !bizId.isBlank() && !(36 < bizId.length()), "额度业务信息无效");
long now = Time.now();
mapper.ensure(UUID.randomUUID().toString(), storeId, customerId, recycleItemId, now);
Map<String, Object> account = mapper.lock(storeId, customerId, recycleItemId);
TimiException.required(account, "额度账户不存在");
Map<String, Object> existing = mapper.findRequest(storeId, requestNo);
if (existing != null) {
TimiException.requiredTrue(Objects.equals(customerId, existing.get("customer_id")) && Objects.equals(recycleItemId, existing.get("recycle_item_id"))
&& Objects.equals(bizType, existing.get("biz_type")) && Objects.equals(bizId, existing.get("biz_id"))
&& balanceDelta.compareTo((BigDecimal) existing.get("balance_delta")) == 0
&& reservedDelta.compareTo((BigDecimal) existing.get("reserved_delta")) == 0
&& Objects.equals(reason, existing.get("reason")), "额度流水请求号对应内容不一致");
return;
}
String id = (String) account.get("id");
TimiException.requiredTrue(mapper.change(id, balanceDelta, reservedDelta, now) == 1, "可用回收物额度不足");
mapper.ledger(UUID.randomUUID().toString(), id, bizType, bizId, requestNo, balanceDelta, reservedDelta, login.getRequireLoginUserId(), reason, now);
}
}
@@ -0,0 +1,319 @@
package com.imyeyu.api.modules.gao.service;
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.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.gao.entity.GaoProduct;
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
import com.imyeyu.api.modules.gao.vo.GaoRecycleItemRequest;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeRuleRequest;
import org.springframework.beans.BeanUtils;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Time;
import com.imyeyu.spring.bean.PageResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/// 回收物与兑换规则配置服务
@Service
@RequiredArgsConstructor
public class GaoRecycleConfigService {
private final GaoRecycleConfigMapper mapper;
private final AttachmentService attachmentService;
private final GaoProductSkuMapper skuMapper;
private final GaoProductSkuUnitMapper unitMapper;
private final GaoProductSkuService skuService;
private final GaoProductService productService;
private final GaoStoreScopeService scope;
/// 分页查询回收物
///
/// @param storeId 门店 ID
/// @param status 状态,为空查询全部
/// @param keyword 名称关键字,为空不过滤
/// @param offset 偏移量
/// @param limit 页大小
/// @return 回收物分页结果
public PageResult<GaoRecycleItem> items(String storeId, GaoRecycleItem.Status status, String keyword, int offset, int limit) {
storeId = resolvePageStore(storeId, offset, limit);
String statusName = status == null ? null : status.name();
String keywordText = blankToNull(keyword);
PageResult<GaoRecycleItem> result = new PageResult<>();
result.setTotal(mapper.countItems(storeId, statusName, keywordText));
List<GaoRecycleItem> items = mapper.items(storeId, statusName, keywordText, offset, limit);
if (!items.isEmpty()) {
Map<String, List<Attachment>> photos = attachmentService.mapByBizIdList(
Attachment.BizType.GAO_RECYCLE_ITEM, items.stream().map(GaoRecycleItem::getId).toList());
items.forEach(item -> item.setAttachmentList(photos.getOrDefault(item.getId(), List.of())));
}
result.setList(items);
return result;
}
/// 查询回收物详情
///
/// @param storeId 门店 ID
/// @param id 回收物 ID
/// @return 回收物详情
public GaoRecycleItem itemDetail(String storeId, String id) {
TimiException.required(id, "回收物 ID 不能为空");
String resolved = scope.resolveStoreId(storeId);
TimiException.required(resolved, "门店不能为空");
GaoRecycleItem item = mapper.itemById(resolved, id);
TimiException.required(item, "回收物不存在");
item.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, id));
return item;
}
/// 分页查询兑换规则
///
/// @param storeId 门店 ID
/// @param status 规则状态,为空查询全部
/// @param recycleItemId 回收物 ID,为空不过滤
/// @param skuId 兑换 SKU ID,为空不过滤
/// @param keyword 回收物名称关键字,为空不过滤
/// @param offset 偏移量
/// @param limit 页大小
/// @return 规则分页结果
@Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true, isolation = Isolation.REPEATABLE_READ)
public PageResult<GaoRecycleExchangeRule> rules(String storeId, GaoRecycleExchangeRule.Status status, String recycleItemId, String skuId, String keyword, int offset, int limit) {
storeId = resolvePageStore(storeId, offset, limit);
String statusName = status == null ? null : status.name();
String itemId = blankToNull(recycleItemId);
String exchangeSkuId = blankToNull(skuId);
String keywordText = blankToNull(keyword);
PageResult<GaoRecycleExchangeRule> result = new PageResult<>();
result.setTotal(mapper.countRules(storeId, statusName, itemId, exchangeSkuId, keywordText));
List<GaoRecycleExchangeRule> list = mapper.rules(storeId, statusName, itemId, exchangeSkuId, keywordText, offset, limit);
fillRuleDisplay(storeId, list);
result.setList(list);
return result;
}
/// 查询兑换规则详情
///
/// @param storeId 门店 ID
/// @param id 规则 ID
/// @return 兑换规则详情
@Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true, isolation = Isolation.REPEATABLE_READ)
public GaoRecycleExchangeRule ruleDetail(String storeId, String id) {
TimiException.required(id, "规则 ID 不能为空");
String resolved = scope.resolveStoreId(storeId);
TimiException.required(resolved, "门店不能为空");
GaoRecycleExchangeRule rule = mapper.ruleById(resolved, id);
TimiException.required(rule, "兑换规则不存在");
fillRuleDisplay(resolved, List.of(rule));
return rule;
}
private String resolvePageStore(String storeId, int offset, int limit) {
TimiException.requiredTrue(-1 < offset && 0 < limit && !(100 < limit), "分页参数无效");
String resolved = scope.resolveStoreId(storeId);
TimiException.required(resolved, "门店不能为空");
return resolved;
}
private String blankToNull(String value) {
return value == null || value.isBlank() ? null : value.trim();
}
/// 填充规则的回收物、产品、SKU 与业务单位展示字段
///
/// 规则只存 ID,列表页需要名称才能直接渲染;这里按页内 ID 批量回查,避免逐条查询。
///
/// @param storeId 门店 ID
/// @param ruleList 规则列表
private void fillRuleDisplay(String storeId, List<GaoRecycleExchangeRule> ruleList) {
if (ruleList == null || ruleList.isEmpty()) {
return;
}
List<String> itemIdList = distinct(ruleList.stream().map(GaoRecycleExchangeRule::getRecycleItemId).toList());
Map<String, List<Attachment>> itemPhotos = itemIdList.isEmpty() ? Map.of()
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIdList);
Map<String, GaoRecycleItem> itemMap = itemIdList.isEmpty()
? Map.of()
: mapper.itemsByIdList(storeId, itemIdList).stream().collect(Collectors.toMap(GaoRecycleItem::getId, Function.identity()));
Map<String, List<GaoRecycleExchangeRuleItem>> ruleItems = mapper.ruleItemsByIds(ruleList.stream().map(GaoRecycleExchangeRule::getId).toList()).stream().collect(Collectors.groupingBy(GaoRecycleExchangeRuleItem::getRuleId));
List<String> skuIdList = distinct(ruleItems.values().stream().flatMap(List::stream).map(GaoRecycleExchangeRuleItem::getSkuId).toList());
Map<String, GaoProductSku> skuMap = skuIdList.isEmpty()
? Map.of()
: skuService.listByIdList(skuIdList).stream().collect(Collectors.toMap(GaoProductSku::getId, Function.identity()));
List<String> productIdList = distinct(skuMap.values().stream().map(GaoProductSku::getProductId).toList());
Map<String, GaoProduct> productMap = productIdList.isEmpty()
? Map.of()
: productService.listByIdList(productIdList).stream().collect(Collectors.toMap(GaoProduct::getId, Function.identity()));
Map<String, String> unitNameMap = skuIdList.isEmpty()
? Map.of()
: unitMapper.selectBySkuIdList(skuIdList).stream()
.collect(Collectors.toMap(unit -> unit.getSkuId() + ":" + unit.getId(), GaoProductSkuUnit::getName, (left, right) -> left));
for (GaoRecycleExchangeRule rule : ruleList) {
rule.setItemList(ruleItems.getOrDefault(rule.getId(), List.of()));
for (GaoRecycleExchangeRuleItem entry : rule.getItemList()) {
GaoProductSku selected = skuMap.get(entry.getSkuId());
GaoProduct selectedProduct = selected == null ? null : productMap.get(selected.getProductId());
entry.setProductName(selectedProduct == null ? null : selectedProduct.getName());
entry.setSkuName(selected == null ? null : selected.getName());
entry.setSpecSummary(selected == null ? null : selected.getSpecSummary());
entry.setUnitName(unitNameMap.get(entry.getSkuId() + ":" + entry.getSkuUnitId()));
entry.setSkuCode(selected == null ? null : selected.getCode());
entry.setStockEnabled(selected == null ? null : selected.getStockEnabled());
entry.setAllowDecimalQuantity(selected == null ? null : selected.getAllowDecimalQuantity());
entry.setProductType(selectedProduct == null || selectedProduct.getProductType() == null ? null : selectedProduct.getProductType().name());
}
GaoRecycleItem item = rule.getRecycleItemId() == null ? null : itemMap.get(rule.getRecycleItemId());
rule.setRecycleName(item == null ? null : item.getName());
rule.setRecycleUnit(item == null ? null : item.getUnitName());
rule.setRecycleItemAttachments(rule.getRecycleItemId() == null ? List.of() : itemPhotos.getOrDefault(rule.getRecycleItemId(), List.of()));
}
}
private List<String> distinct(Collection<String> sourceIdList) {
return sourceIdList.stream()
.filter(value -> value != null && !value.isBlank())
.distinct()
.toList();
}
/// 保存回收物配置
@Transactional(TimiServerDBConfig.ROLLBACKER)
@OperationAudit(AuditOperation.GAO_RECYCLE_ITEM_SAVE)
public GaoRecycleItem saveItem(GaoRecycleItemRequest request) {
TimiException.required(request, "回收物不能为空");
GaoRecycleItem item = new GaoRecycleItem();
BeanUtils.copyProperties(request, item);
String storeId = scope.resolveStoreId(item.getStoreId());
TimiException.required(storeId, "门店不能为空");
item.setStoreId(storeId);
TimiException.required(item.getName(), "回收物名称不能为空");
TimiException.required(item.getUnitName(), "回收物单位不能为空");
TimiException.required(item.getStatus(), "回收物状态不能为空");
TimiException.requiredTrue(!item.getName().isBlank() && !item.getUnitName().isBlank()
&& !(128 < item.getName().length()) && !(32 < item.getUnitName().length()), "回收物名称或单位过长");
if (item.getId() == null) {
if (item.getAllowDecimalQuantity() == null) item.setAllowDecimalQuantity(true);
item.setId(UUID.randomUUID().toString());
item.setCreatedAt(Time.now());
mapper.insertItem(item);
} else {
GaoRecycleItem existing = mapper.item(storeId, item.getId());
TimiException.required(existing, "回收物不存在");
if (item.getAllowDecimalQuantity() == null) item.setAllowDecimalQuantity(existing.getAllowDecimalQuantity());
item.setUpdatedAt(Time.now());
mapper.updateItem(item);
}
if (request.getAttachmentList() != null) {
attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, item.getId(), request.getAttachmentList());
item.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, item.getId()));
}
return item;
}
/// 保存兑换规则
@Transactional(TimiServerDBConfig.ROLLBACKER)
@OperationAudit(AuditOperation.GAO_RECYCLE_RULE_SAVE)
public GaoRecycleExchangeRule saveRule(GaoRecycleExchangeRuleRequest request) {
TimiException.required(request, "兑换规则不能为空");
GaoRecycleExchangeRule rule = new GaoRecycleExchangeRule();
BeanUtils.copyProperties(request, rule);
String storeId = scope.resolveStoreId(rule.getStoreId());
TimiException.required(storeId, "门店不能为空");
rule.setStoreId(storeId);
TimiException.required(rule.getRecycleItemId(), "回收物不能为空");
if (rule.getId() != null) {
TimiException.required(mapper.rule(storeId, rule.getId()), "规则不存在");
}
TimiException.required(rule.getStatus(), "规则状态不能为空");
GaoRecycleItem item = mapper.item(storeId, rule.getRecycleItemId());
TimiException.required(item, "回收物不存在");
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
TimiException.requiredTrue(item.getStatus() == GaoRecycleItem.Status.ACTIVE, "回收物已停用");
}
List<GaoRecycleExchangeRuleItem> items = request.getItemList();
TimiException.requiredTrue(items != null && !items.isEmpty(), "兑换模板明细不能为空");
Set<String> keys = new HashSet<>();
TimiException.requiredTrue(items.stream().noneMatch(java.util.Objects::isNull), "兑换模板明细不能为空");
List<GaoRecycleExchangeRuleItem> ordered = items.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeRuleItem::getSkuId, java.util.Comparator.nullsFirst(String::compareTo))).toList();
for (GaoRecycleExchangeRuleItem entry : ordered) {
TimiException.required(entry, "兑换模板明细不能为空");
TimiException.required(entry.getSkuId(), "SKU 不能为空");
TimiException.required(entry.getSkuUnitId(), "单位不能为空");
TimiException.requiredTrue(keys.add(entry.getSkuId() + "|" + entry.getSkuUnitId()), "同一模板内 SKU 和单位不能重复");
GaoProductSku sku = skuMapper.selectForUpdate(entry.getSkuId());
TimiException.required(sku, "SKU 不存在");
TimiException.requiredTrue(storeId.equals(sku.getStoreId()), "SKU 不属于当前门店");
GaoProduct product = productService.get(sku.getProductId());
TimiException.required(product, "产品不存在");
TimiException.requiredTrue(storeId.equals(product.getStoreId()), "产品不属于当前门店");
GaoProductSkuUnit unit = skuService.listUnitBySkuId(sku.getId()).stream().filter(value -> entry.getSkuUnitId().equals(value.getId())).findFirst().orElse(null);
TimiException.required(unit, "SKU 单位不存在");
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
TimiException.requiredTrue(product.getStatus() == GaoProduct.Status.ACTIVE && sku.getStatus() == GaoProductSku.Status.ACTIVE && Boolean.TRUE.equals(unit.getAllowSale()), "产品、SKU 或单位不可用");
}
validateQuantity(entry.getExchangeQuantity());
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < entry.getExchangeQuantity().stripTrailingZeros().scale()), "兑换数量不允许小数");
TimiException.required(unit.getBaseQuantityPerUnit(), "单位换算系数不能为空");
BigDecimal base = entry.getExchangeQuantity().multiply(unit.getBaseQuantityPerUnit());
TimiException.requiredTrue(0 < base.signum() && !(3 < base.stripTrailingZeros().scale()) && !(15 < base.precision() - base.scale()), "基础数量超出精度或范围");
}
validateQuantity(rule.getRecycleQuantity());
if (rule.getSort() == null) {
rule.setSort(0);
}
if (rule.getId() == null) {
rule.setId(UUID.randomUUID().toString());
rule.setCreatedAt(Time.now());
mapper.insertRule(rule);
} else {
rule.setUpdatedAt(Time.now());
mapper.updateRule(rule);
}
mapper.deleteRuleItems(rule.getId());
int position = 0;
for (GaoRecycleExchangeRuleItem entry : items) {
entry.setId(UUID.randomUUID().toString());
entry.setRuleId(rule.getId());
entry.setSort(position++);
entry.setCreatedAt(Time.now());
mapper.insertRuleItem(entry);
}
fillRuleDisplay(storeId, List.of(rule));
return rule;
}
/// 删除兑换模板
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void deleteRule(String storeId, String id) {
String resolved = scope.resolveStoreId(storeId);
TimiException.required(resolved, "门店不能为空");
TimiException.required(mapper.rule(resolved, id), "规则不存在");
mapper.deleteRuleItems(id);
mapper.deleteRule(resolved, id);
}
private void validateQuantity(BigDecimal quantity) {
TimiException.required(quantity, "数量不能为空");
TimiException.requiredTrue(0 < quantity.signum() && !(3 < quantity.stripTrailingZeros().scale())
&& !(15 < quantity.precision() - quantity.scale()), "数量必须大于零且符合精度范围");
}
}
@@ -0,0 +1,56 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeQueryMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeDetail;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/// 回收兑换查询服务
@Service
@RequiredArgsConstructor
public class GaoRecycleExchangeQueryService {
private final GaoRecycleExchangeQueryMapper mapper;
private final GaoRecycleConfigMapper configMapper;
private final GaoStoreScopeService scopeService;
private final AttachmentService attachmentService;
/// 查询兑换单、权益明细、操作记录和附件
///
/// 库存随履约走,兑换单本身不产生库存流水,所以详情里没有流水列表。
///
/// @param id 兑换单 ID
/// @return 兑换单详情
/// @throws TimiException 兑换单不存在或超出门店范围
public GaoRecycleExchangeDetail detail(String id) {
TimiException.required(id, "兑换单 ID 不能为空");
GaoRecycleExchange exchange = mapper.detail(id);
TimiException.required(exchange, "兑换单不存在");
scopeService.checkStoreId(exchange.getStoreId());
if (exchange.getRecycleItemId() != null) {
GaoRecycleItem item = configMapper.itemById(exchange.getStoreId(), exchange.getRecycleItemId());
if (item != null) exchange.setAllowDecimalQuantity(item.getAllowDecimalQuantity());
}
GaoRecycleExchangeDetail detail = new GaoRecycleExchangeDetail();
detail.setExchange(exchange);
List<GaoRecycleExchangeAction> actions = mapper.actions(id);
detail.setActionList(actions);
Map<String, List<Attachment>> attachments = new HashMap<>();
for (GaoRecycleExchangeAction action : actions) {
attachments.put(action.getId(), attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId()));
}
detail.setActionAttachments(attachments);
return detail;
}
}
@@ -0,0 +1,89 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/// 回收兑换展示数据填充
///
/// 兑换单只落客户 ID 与操作人 ID,客户资料、头像和操作人昵称在响应前批量补齐,
/// 调用方拿到单据就能直接渲染,不需要再逐条回查。
@Service
@RequiredArgsConstructor
public class GaoRecycleExchangeViewService {
private final AttachmentService attachmentService;
private final GaoCustomerService customerService;
private final UserService userService;
/// 填充兑换单的客户资料与操作人
///
/// @param exchangeList 兑换单列表
public void fill(List<GaoRecycleExchange> exchangeList) {
if (exchangeList == null || exchangeList.isEmpty()) {
return;
}
List<String> customerIdList = distinct(exchangeList.stream().map(GaoRecycleExchange::getCustomerId).toList());
Map<String, GaoCustomer> customerMap = customerIdList.isEmpty() ? Map.of() : customerService.mapByIdList(customerIdList);
Map<String, List<Attachment>> customerPhotoMap = customerIdList.isEmpty()
? Map.of()
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList, GaoCustomer.AttachType.PHOTO.name());
Map<String, User> userMap = userMap(exchangeList.stream().map(GaoRecycleExchange::getOperatorUserId).toList());
List<String> itemIdList = distinct(exchangeList.stream().map(GaoRecycleExchange::getRecycleItemId).toList());
Map<String, List<Attachment>> itemPhotos = itemIdList.isEmpty() ? Map.of()
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIdList);
for (GaoRecycleExchange exchange : exchangeList) {
exchange.setRecycleItemAttachments(exchange.getRecycleItemId() == null ? List.of() : itemPhotos.getOrDefault(exchange.getRecycleItemId(), List.of()));
GaoCustomer customer = exchange.getCustomerId() == null ? null : customerMap.get(exchange.getCustomerId());
if (customer != null) {
customer.setAttachmentList(customerPhotoMap.getOrDefault(customer.getId(), List.of()));
}
exchange.setCustomer(customer);
exchange.setOperator(exchange.getOperatorUserId() == null ? null : userMap.get(exchange.getOperatorUserId()));
}
}
/// 填充单条兑换单,写操作返回体用
///
/// @param exchange 兑换单
/// @return 原对象
public GaoRecycleExchange fill(GaoRecycleExchange exchange) {
fill(List.of(exchange));
return exchange;
}
/// 填充操作记录的操作人
///
/// @param actionList 操作记录列表
public void fillActions(List<GaoRecycleExchangeAction> actionList) {
if (actionList == null || actionList.isEmpty()) {
return;
}
Map<String, User> userMap = userMap(actionList.stream().map(GaoRecycleExchangeAction::getOperatorUserId).toList());
for (GaoRecycleExchangeAction action : actionList) {
action.setOperator(action.getOperatorUserId() == null ? null : userMap.get(action.getOperatorUserId()));
}
}
private Map<String, User> userMap(Collection<String> sourceIdList) {
List<String> userIdList = distinct(sourceIdList);
return userIdList.isEmpty() ? Map.of() : userService.mapByIdList(userIdList);
}
private List<String> distinct(Collection<String> sourceIdList) {
return sourceIdList.stream()
.filter(value -> value != null && !value.isBlank())
.distinct()
.toList();
}
}
@@ -0,0 +1,415 @@
package com.imyeyu.api.modules.gao.service;
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.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoProduct;
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.entity.GaoProductStockRecord;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem;
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderCancelRequest;
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeItemRequest;
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
import com.imyeyu.api.modules.gao.mapper.GaoProductMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductStockRecordMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeWriteMapper;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeActionRequest;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoStockChangeItem;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentItemRequest;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
/// 回收兑换交易
@Service
@RequiredArgsConstructor
public class GaoRecycleExchangeWriteService {
private final GaoRecycleExchangeWriteMapper mapper;
private final GaoRecycleConfigMapper configMapper;
private final GaoProductSkuMapper skuMapper;
private final GaoProductMapper productMapper;
private final GaoProductSkuUnitMapper unitMapper;
private final GaoProductSkuService skuService;
private final GaoCustomerService customerService;
private final GaoStoreScopeService scope;
private final GaoProductStockService stockService;
private final GaoProductStockRecordMapper stockRecordMapper;
private final AttachmentService attachmentService;
private final UserLoginService login;
private final PermissionChecker permissions;
private final ObjectMapper jackson;
private final ObjectProvider<GaoOrderFulfillmentService> fulfillmentServiceProvider;
private final GaoSalesOrderService salesOrderService;
private final GaoRecyclePaymentService recyclePaymentService;
private final GaoRecyclePhysicalService physicalService;
/// 创建回收兑换权益
///
/// @param request 创建请求
/// @return 兑换单
@Transactional(TimiServerDBConfig.ROLLBACKER)
@OperationAudit(AuditOperation.GAO_RECYCLE_EXCHANGE_CREATE)
public GaoRecycleExchange create(GaoRecycleExchangeCreateRequest request) {
TimiException.required(request, "请求不能为空");
return createItems(request);
}
private GaoRecycleExchange createItems(GaoRecycleExchangeCreateRequest request) {
String store = scope.resolveStoreId(request.getStoreId());
TimiException.required(store, "门店不能为空");
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
TimiException.required(request.getCustomerId(), "客户不能为空");
String fp = fingerprint(request.getCustomerId(), request.getRuleId(), request.getRecycleItemId(), request.getMultiple(), number(request.getRecycleQuantity()), request.getItemList(), request.getOccurredAt(), request.getRemark(), attachments(request.getAttachmentList()), Boolean.TRUE.equals(request.getVerifyPayment()));
BigDecimal paymentQuantity = request.getPaymentQuantity();
boolean fulfillAll = Boolean.TRUE.equals(request.getFulfillAll());
if (paymentQuantity != null || fulfillAll) {
fp = fingerprint(fp, number(paymentQuantity == null ? BigDecimal.ZERO : paymentQuantity), fulfillAll, attachments(request.getFulfillmentAttachmentList()));
}
if (request.getPaymentAttachmentList() != null && !request.getPaymentAttachmentList().isEmpty()) {
fp = fingerprint(fp, attachments(request.getPaymentAttachmentList()));
}
TimiException.required(mapper.lockStore(store), "门店不存在");
GaoRecycleExchange previous = mapper.byRequest(store, request.getRequestNo());
if (previous != null) {
TimiException.requiredTrue(fp.equals(previous.getRequestFingerprint()), "请求号对应的内容不一致");
return previous;
}
GaoCustomer customer = customerService.get(request.getCustomerId());
TimiException.required(customer, "客户不存在");
TimiException.requiredTrue(store.equals(customer.getStoreId()), "客户不属于当前门店");
boolean free = request.getRuleId() == null || request.getRuleId().isBlank();
boolean canAdjust = permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_PRICE_OVERRIDE.getValue());
TimiException.requiredTrue(!free || canAdjust, "缺少自由创建兑换单权限");
GaoRecycleExchangeRule rule = free ? null : configMapper.rule(store, request.getRuleId());
TimiException.requiredTrue(free || rule != null && rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE, "兑换模板不存在或已停用");
int multiple = free ? 1 : request.getMultiple() == null ? 1 : request.getMultiple();
TimiException.requiredTrue(0 < multiple, "兑换份数必须大于零");
String itemId = request.getRecycleItemId() == null ? free ? null : rule.getRecycleItemId() : request.getRecycleItemId();
TimiException.required(itemId, "回收物不能为空");
GaoRecycleItem item = configMapper.item(store, itemId);
TimiException.requiredTrue(item != null && item.getStatus() == GaoRecycleItem.Status.ACTIVE, "回收物不存在或已停用");
BigDecimal preset = free ? null : quantity(rule.getRecycleQuantity().multiply(BigDecimal.valueOf(multiple)));
BigDecimal actual = quantity(request.getRecycleQuantity() == null ? preset : request.getRecycleQuantity());
if (!free && (!itemId.equals(rule.getRecycleItemId()) || actual.compareTo(preset) != 0)) {
TimiException.requiredTrue(canAdjust, "缺少兑换数量调整权限");
}
List<GaoRecycleExchangeRuleItem> defaults = free ? List.of() : configMapper.ruleItems(rule.getId());
TimiException.requiredTrue(free || !defaults.isEmpty(), "兑换模板没有明细");
List<GaoRecycleExchangeItemRequest> inputs = request.getItemList();
if (inputs == null || inputs.isEmpty()) {
inputs = new ArrayList<>();
for (GaoRecycleExchangeRuleItem source : defaults) {
GaoRecycleExchangeItemRequest input = new GaoRecycleExchangeItemRequest();
input.setSkuId(source.getSkuId());
input.setSkuUnitId(source.getSkuUnitId());
input.setQuantity(quantity(source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple))));
inputs.add(input);
}
}
TimiException.requiredTrue(!inputs.isEmpty(), "兑换明细不能为空");
Map<String, BigDecimal> expected = new HashMap<>();
Map<String, BigDecimal> maxUnitBySku = new HashMap<>();
for (GaoRecycleExchangeRuleItem source : defaults.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeRuleItem::getSkuId).thenComparing(GaoRecycleExchangeRuleItem::getSkuUnitId)).toList()) {
GaoProductSkuUnit unit = unitMapper.select(source.getSkuUnitId());
TimiException.requiredTrue(unit != null && source.getSkuId().equals(unit.getSkuId()), "模板单位无效");
expected.merge(source.getSkuId(), source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple)).multiply(unit.getBaseQuantityPerUnit()), BigDecimal::add);
maxUnitBySku.merge(source.getSkuId(), unit.getBaseQuantityPerUnit(), BigDecimal::max);
}
Map<String, BigDecimal> actualBySku = new HashMap<>();
Set<String> unique = new HashSet<>();
List<GaoSalesOrderItem> entries = new ArrayList<>();
long now = Time.now();
for (GaoRecycleExchangeItemRequest input : inputs) {
TimiException.required(input, "兑换明细不能为空");
TimiException.required(input.getSkuId(), "SKU 不能为空");
TimiException.required(input.getSkuUnitId(), "单位不能为空");
}
for (GaoRecycleExchangeItemRequest input : inputs.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeItemRequest::getSkuId).thenComparing(GaoRecycleExchangeItemRequest::getSkuUnitId)).toList()) {
TimiException.required(input, "兑换明细不能为空");
TimiException.required(input.getSkuId(), "SKU 不能为空");
TimiException.required(input.getSkuUnitId(), "单位不能为空");
TimiException.requiredTrue(unique.add(input.getSkuId() + "|" + input.getSkuUnitId()), "同一 SKU 和单位不能重复");
var selection = skuService.getSellableSkuUnit(store, input.getSkuId(), input.getSkuUnitId());
GaoProduct product = selection.getProduct();
GaoProductSku sku = selection.getSku();
GaoProductSkuUnit unit = selection.getUnit();
if (!free && !canAdjust) {
BigDecimal maximum = maxUnitBySku.get(sku.getId());
TimiException.requiredTrue(maximum != null && 0 <= maximum.compareTo(unit.getBaseQuantityPerUnit()), "兑换权益单位不能高于模板单位");
}
BigDecimal value = quantity(input.getQuantity());
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < value.stripTrailingZeros().scale()), "兑换数量不允许小数");
BigDecimal base = quantity(value.multiply(unit.getBaseQuantityPerUnit()));
actualBySku.merge(sku.getId(), base, BigDecimal::add);
GaoSalesOrderItem entry = new GaoSalesOrderItem();
entry.setSkuId(sku.getId());
entry.setSkuUnitId(unit.getId());
entry.setProductIdSnapshot(product.getId());
entry.setProductNameSnapshot(product.getName());
entry.setSkuCodeSnapshot(sku.getCode());
entry.setSkuNameSnapshot(sku.getName());
entry.setSpecSummarySnapshot(sku.getSpecSummary());
entry.setSkuSpecSnapshot(skuService.getSkuSpecSnapshot(sku));
entry.setUnitSnapshot(unit.getName());
entry.setBaseQuantityPerUnitSnapshot(unit.getBaseQuantityPerUnit());
entry.setQuantity(value);
entry.setBaseQuantity(base);
// 订单创建要求履约数量非空,兑换单场景一律从零开始
entry.setReservedBaseQuantity(BigDecimal.ZERO);
entry.setFulfilledBaseQuantity(BigDecimal.ZERO);
entry.setAllowDecimalQuantity(sku.getAllowDecimalQuantity());
entry.setItemType(GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT);
entry.setSort(entries.size());
entries.add(entry);
}
if (!free && !canAdjust) {
TimiException.requiredTrue(defaults.size() == inputs.size(), "兑换明细必须与模板一致");
for (GaoRecycleExchangeRuleItem source : defaults) {
BigDecimal required = source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple));
TimiException.requiredTrue(inputs.stream().anyMatch(input -> source.getSkuId().equals(input.getSkuId()) && source.getSkuUnitId().equals(input.getSkuUnitId()) && input.getQuantity() != null && required.compareTo(input.getQuantity()) == 0), "兑换明细必须与模板一致");
}
TimiException.requiredTrue(expected.size() == actualBySku.size(), "兑换商品与模板不一致");
for (var entry : expected.entrySet()) {
TimiException.requiredTrue(actualBySku.containsKey(entry.getKey()) && entry.getValue().compareTo(actualBySku.get(entry.getKey())) == 0, "兑换数量与模板不一致");
}
}
GaoRecycleExchange result = new GaoRecycleExchange();
result.setId(UUID.randomUUID().toString());
result.setStoreId(store);
result.setCustomerId(customer.getId());
result.setRequestNo(request.getRequestNo());
result.setRequestFingerprint(fp);
result.setRuleId(free ? null : rule.getId());
if (!free) {
rule.setItemList(defaults);
result.setRuleSnapshot(jackson.valueToTree(rule));
}
result.setRecycleItemId(item.getId());
result.setRecycleNameSnapshot(item.getName());
result.setRecycleUnitSnapshot(item.getUnitName());
result.setRuleRecycleQuantity(free ? null : rule.getRecycleQuantity());
result.setMultiple(free ? null : multiple);
result.setDefaultRecycleQuantity(preset);
result.setRecycleQuantity(actual);
result.setStatus(GaoRecycleExchange.Status.PENDING);
result.setOperatorUserId(login.getRequireLoginUserId());
result.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
result.setRemark(request.getRemark());
result.setCreatedAt(now);
GaoPackageOrderCreateData orderData = new GaoPackageOrderCreateData();
orderData.setStoreId(store);
orderData.setCustomerId(customer.getId());
orderData.setRequestNo("recycle:" + result.getId());
orderData.setPurchasedAt(result.getOccurredAt());
orderData.setOperatorUserId(result.getOperatorUserId());
orderData.setRemark(result.getRemark());
orderData.setItemList(entries);
result.setSalesOrderId(salesOrderService.createRecycleOrder(orderData, item.getId(), actual).getId());
mapper.insert(result);
attachmentService.updateByBizId(Attachment.BizType.GAO_SALES_ORDER, result.getSalesOrderId(), request.getAttachmentList());
BigDecimal paid = paymentQuantity == null ? (Boolean.TRUE.equals(request.getVerifyPayment()) ? actual : BigDecimal.ZERO) : paymentQuantity;
TimiException.requiredTrue(0 <= paid.signum() && !(3 < paid.stripTrailingZeros().scale()) && 0 <= actual.compareTo(paid), "已回收数量无效或超过应回收数量");
TimiException.requiredTrue(!Boolean.TRUE.equals(request.getVerifyPayment()) || paymentQuantity == null || actual.compareTo(paid) == 0, "全部回收数量必须等于应回收数量");
TimiException.requiredTrue(!fulfillAll || actual.compareTo(paid) == 0, "全部履约前必须全部回收并核销");
if (0 < paid.signum()) {
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.FUND_RECEIVE_CREATE.getValue(), GaoPermissionCode.FUND_RECEIVE_VERIFY.getValue());
GaoRecyclePaymentRequest payment = new GaoRecyclePaymentRequest();
payment.setOrderId(result.getSalesOrderId());
payment.setRequestNo("recycle:create:" + result.getId());
payment.setQuantity(paid);
payment.setOccurredAt(request.getOccurredAt());
payment.setAttachmentList(request.getPaymentAttachmentList());
recyclePaymentService.createAndVerify(payment);
}
if (fulfillAll) {
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue(), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY.getValue());
GaoOrderFulfillmentCreateRequest fulfillment = new GaoOrderFulfillmentCreateRequest();
fulfillment.setSalesOrderId(result.getSalesOrderId());
fulfillment.setRequestNo("recycle:fulfill:" + result.getId());
fulfillment.setDeliveredAt(request.getOccurredAt());
fulfillment.setAttachmentList(request.getFulfillmentAttachmentList());
List<GaoOrderFulfillmentItemRequest> fulfillmentItems = new ArrayList<>();
for (GaoSalesOrderItem entry : salesOrderService.listItemByOrderId(result.getSalesOrderId())) {
GaoOrderFulfillmentItemRequest fulfillmentItem = new GaoOrderFulfillmentItemRequest();
fulfillmentItem.setSourceOrderItemId(entry.getId());
fulfillmentItem.setSkuUnitId(entry.getSkuUnitId());
fulfillmentItem.setQuantity(entry.getQuantity());
fulfillmentItems.add(fulfillmentItem);
}
fulfillment.setItemList(fulfillmentItems);
fulfillmentServiceProvider.getObject().createAndVerify(fulfillment);
}
return result;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecycleExchange cancelFromOrder(GaoRecycleExchangeActionRequest request, GaoSalesOrderCancelRequest orderRequest) {
return cancelInternal(request, orderRequest);
}
private GaoRecycleExchange cancelInternal(GaoRecycleExchangeActionRequest request, GaoSalesOrderCancelRequest orderRequest) {
TimiException.required(request, "请求不能为空");
TimiException.required(request.getExchangeId(), "兑换单不能为空");
TimiException.required(request.getRequestNo(), "请求号不能为空");
TimiException.requiredTrue(!request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
GaoRecycleExchange snapshot = mapper.byId(request.getExchangeId());
TimiException.required(snapshot, "兑换单不存在");
scope.checkStoreId(snapshot.getStoreId());
String store = snapshot.getStoreId();
String fingerprint = fingerprint(request.getExchangeId(), GaoRecycleExchangeAction.ActionType.CANCEL, request.getOccurredAt(), request.getReason(), request.getRemark(), number(request.getRetainedRecycleQuantity()), request.getFulfillmentRevokeList(), request.getPaymentRevokeList(), attachments(request.getAttachmentList()));
TimiException.required(mapper.lockStore(store), "门店不存在");
GaoRecycleExchangeAction existing = mapper.actionByRequest(store, request.getRequestNo());
if (existing != null) {
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应的操作内容不一致");
return mapper.lockExchange(store, existing.getExchangeId());
}
TimiException.required(snapshot.getSalesOrderId(), "兑换订单不存在");
salesOrderService.getForUpdate(snapshot.getSalesOrderId());
GaoRecycleExchange exchange = mapper.lockExchange(store, request.getExchangeId());
TimiException.required(exchange, "兑换单不存在");
// 已完成只代表权益领完,回收物归属仍需能修正,所以也允许撤销
TimiException.requiredTrue(exchange.getStatus() == GaoRecycleExchange.Status.PENDING || exchange.getStatus() == GaoRecycleExchange.Status.COMPLETED, "兑换单状态不允许撤销");
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "撤销原因不能为空");
TimiException.required(exchange.getSalesOrderId(), "兑换订单不存在");
var lockedOrder = salesOrderService.getForUpdate(exchange.getSalesOrderId());
if (request.getPaymentRevokeList() != null && !request.getPaymentRevokeList().isEmpty()) {
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.FUND_REVOKE.getValue());
Set<String> allowed = new HashSet<>();
for (var payment : recyclePaymentService.list(exchange.getSalesOrderId())) {
allowed.add(payment.getId());
}
Set<String> selected = new HashSet<>();
for (GaoRecyclePaymentRequest payment : request.getPaymentRevokeList()) {
TimiException.required(payment, "支付冲正请求不能为空");
TimiException.requiredTrue(allowed.contains(payment.getPaymentId()) && selected.add(payment.getPaymentId()), "支付记录不属于兑换订单或重复选择");
if (payment.getReason() == null || payment.getReason().isBlank()) payment.setReason(request.getReason());
recyclePaymentService.revoke(payment);
}
}
BigDecimal received = physicalService.balance(exchange.getSalesOrderId());
BigDecimal retained = request.getRetainedRecycleQuantity() == null ? received : request.getRetainedRecycleQuantity();
TimiException.requiredTrue(0 <= retained.signum() && 0 <= received.compareTo(retained) && !(3 < retained.stripTrailingZeros().scale()), "保留回收物数量超过实际收到数量");
GaoSalesOrderCancelRequest cancelOrder = orderRequest == null ? new GaoSalesOrderCancelRequest() : orderRequest;
cancelOrder.setSalesOrderId(exchange.getSalesOrderId());
cancelOrder.setRequestNo(request.getRequestNo());
cancelOrder.setReason(request.getReason());
if (orderRequest == null) cancelOrder.setAttachmentList(request.getAttachmentList());
if (orderRequest == null) cancelOrder.setFulfillmentRevokeList(request.getFulfillmentRevokeList());
salesOrderService.cancel(cancelOrder);
long now = Time.now();
GaoRecycleExchangeAction action = new GaoRecycleExchangeAction();
action.setId(UUID.randomUUID().toString());
BigDecimal remainingReturn = received.subtract(retained);
for (var payment : recyclePaymentService.list(exchange.getSalesOrderId())) {
if (payment.getSourcePaymentId() != null || remainingReturn.signum() == 0) continue;
BigDecimal available = physicalService.paymentBalance(exchange.getSalesOrderId(), payment.getId());
BigDecimal returned = remainingReturn.min(available);
if (0 < returned.signum()) {
physicalService.record(lockedOrder, "EXCHANGE_CANCEL", action.getId(), payment.getId(), false, returned, request.getOccurredAt());
remainingReturn = remainingReturn.subtract(returned);
}
}
TimiException.requiredTrue(remainingReturn.signum() == 0, "回收实物退回数量不一致");
action.setStoreId(store);
action.setExchangeId(exchange.getId());
action.setRequestNo(request.getRequestNo());
action.setRequestFingerprint(fingerprint);
action.setActionType(GaoRecycleExchangeAction.ActionType.CANCEL);
action.setOperatorUserId(login.getRequireLoginUserId());
action.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
action.setCreatedAt(now);
action.setReason(request.getReason());
action.setRemark(request.getRemark());
action.setRetainedRecycleQuantity(retained);
mapper.insertAction(action);
if (orderRequest == null) attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId(), request.getAttachmentList());
TimiException.requiredTrue(mapper.cancel(exchange.getId(), now) == 1, "兑换单状态已变更");
exchange.setStatus(GaoRecycleExchange.Status.CANCELLED);
exchange.setUpdatedAt(now);
return exchange;
}
/// 校验数量范围和精度
///
/// @param value 数量
/// @return 已校验数量
private BigDecimal quantity(BigDecimal value) {
TimiException.required(value, "数量不能为空");
TimiException.requiredTrue(0 < value.signum() && !(3 < value.stripTrailingZeros().scale()) && !(15 < value.precision() - value.scale()), "数量超出精度或范围");
return value;
}
/// 规范化数量以计算请求摘要
///
/// @param value 数量
/// @return 规范化数量,可为空
private String number(BigDecimal value) {
return value == null ? null : value.stripTrailingZeros().toPlainString();
}
/// 提取并排序附件标识,确保附件顺序不影响幂等判断
///
/// @param list 附件列表
/// @return 附件标识列表
private List<String> attachments(List<Attachment> list) {
if (list == null) {
return List.of();
}
return list.stream()
.filter(Objects::nonNull)
.map(a -> String.valueOf(a.getId()) + ":" + a.getTempFileId() + ":" + a.getAttachType())
.sorted()
.toList();
}
/// 计算原始请求摘要
///
/// @param values 请求内容
/// @return 摘要
private String fingerprint(Object... values) {
try {
byte[] bytes = jackson.writeValueAsString(values).getBytes(StandardCharsets.UTF_8);
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (Exception e) {
throw new IllegalStateException("计算请求摘要失败", e);
}
}
}
@@ -0,0 +1,339 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.mapper.GaoRecyclePaymentMapper;
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderTransactionView;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import java.util.HexFormat;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
/// 回收物支付服务
@Service
@RequiredArgsConstructor
public class GaoRecyclePaymentService {
private final GaoRecyclePaymentMapper mapper;
private final GaoRecycleAccountService accounts;
private final GaoSalesOrderService orders;
private final GaoStoreScopeService scope;
private final UserLoginService login;
private final AttachmentService attachments;
private final ObjectMapper jackson;
private final GaoFundRecordService funds;
private final GaoRecyclePhysicalService physical;
private final GaoCustomerService customers;
private final UserService users;
/// 判断订单回收物支付是否已结清
public boolean isSettled(GaoSalesOrder order) {
return order.getRecycleRequiredQuantity() != null && 0 <= mapper.paid(order.getId()).compareTo(order.getRecycleRequiredQuantity());
}
/// 查询订单的回收物支付记录
public List<GaoRecyclePayment> list(String orderId) {
GaoSalesOrder order = orders.get(orderId);
TimiException.required(order, "订单不存在");
scope.checkStoreId(order.getStoreId());
List<GaoRecyclePayment> payments = mapper.list(orderId);
fillAttachments(payments);
fillCustomers(payments);
fillUsers(payments);
return payments;
}
/// 按门店和筛选条件分页查询回收流水。
public List<GaoRecyclePayment> search(String storeId, String customerId, String orderId, String status, Long beginAt, Long endAt, int offset, int limit) {
TimiException.requiredTrue(0 <= offset && 0 < limit && limit <= 101, "分页参数无效");
String resolvedStoreId = scope.resolveStoreId(storeId);
List<GaoRecyclePayment> payments = mapper.search(resolvedStoreId, customerId, orderId, status, beginAt, endAt, offset, limit);
fillAttachments(payments);
fillCustomers(payments);
fillUsers(payments);
return payments;
}
/// 批量回填人员的展示信息。
private void fillUsers(List<GaoRecyclePayment> payments) {
var ids = payments.stream().flatMap(payment -> java.util.stream.Stream.of(payment.getOperatorUserId(), payment.getVerifierUserId()))
.filter(id -> id != null && !id.isBlank()).distinct().toList();
if (ids.isEmpty()) return;
var userMap = users.mapByIdList(ids);
for (GaoRecyclePayment payment : payments) {
payment.setOperator(payment.getOperatorUserId() == null ? null : displayUser(userMap.get(payment.getOperatorUserId())));
payment.setVerifier(payment.getVerifierUserId() == null ? null : displayUser(userMap.get(payment.getVerifierUserId())));
}
}
private User displayUser(User source) {
if (source == null) return null;
User user = new User();
user.setId(source.getId());
user.setName(source.getName());
user.setNick(source.getNick());
return user;
}
private void fillCustomers(List<GaoRecyclePayment> payments) {
List<String> ids = payments.stream().map(GaoRecyclePayment::getCustomerId).filter(Objects::nonNull).distinct().toList();
if (ids.isEmpty()) return;
var customerMap = customers.mapByIdList(ids);
var photoMap = attachments.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, ids);
for (GaoRecyclePayment payment : payments) {
var customer = customerMap.get(payment.getCustomerId());
if (customer == null) continue;
customer.setAttachmentList(photoMap.getOrDefault(customer.getId(), List.of()));
payment.setCustomer(customer);
}
}
/// 按授权范围聚合订单交易
public List<GaoOrderTransactionView> transactions(String orderId, boolean fundAllowed, boolean recycleAllowed) {
GaoSalesOrder order = orders.get(orderId);
TimiException.required(order, "订单不存在");
scope.checkStoreId(order.getStoreId());
List<GaoOrderTransactionView> result = new ArrayList<>();
List<com.imyeyu.api.modules.gao.entity.GaoFundRecord> fundRecords = fundAllowed ? funds.listByBizId(orderId) : List.of();
var fundAttachments = fundRecords.isEmpty() ? java.util.Map.<String, List<Attachment>>of()
: attachments.mapByBizIdList(Attachment.BizType.GAO_FUND_RECORD, fundRecords.stream().map(com.imyeyu.api.modules.gao.entity.GaoFundRecord::getId).toList());
for (var fund : fundRecords) {
fund.setAttachmentList(fundAttachments.getOrDefault(fund.getId(), List.of()));
GaoOrderTransactionView item = new GaoOrderTransactionView();
item.setType("FUND");
item.setOccurredAt(fund.getOccurredAt());
item.setFundRecord(fund);
result.add(item);
}
if (recycleAllowed) for (var payment : list(orderId)) {
GaoOrderTransactionView item = new GaoOrderTransactionView();
item.setType("RECYCLE_PAYMENT");
item.setOccurredAt(payment.getOccurredAt());
item.setRecyclePayment(payment);
result.add(item);
}
result.sort(Comparator.comparing(GaoOrderTransactionView::getOccurredAt, Comparator.nullsLast(Comparator.reverseOrder())));
return result;
}
/// 登记支付并预占额度
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecyclePayment create(GaoRecyclePaymentRequest request) {
return createInternal(request, null);
}
private GaoRecyclePayment createInternal(GaoRecyclePaymentRequest request, String exchangeId) {
TimiException.required(request, "支付请求不能为空");
TimiException.required(request.getOrderId(), "订单不能为空");
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
TimiException.requiredTrue(request.getQuantity() != null && 0 < request.getQuantity().signum() && !(3 < request.getQuantity().stripTrailingZeros().scale()) && !(15 < request.getQuantity().precision() - request.getQuantity().scale()), "支付数量无效");
GaoSalesOrder order = orders.getForUpdate(request.getOrderId());
TimiException.required(order, "订单不存在");
scope.checkStoreId(order.getStoreId());
String fingerprint = fingerprint("CREATE", request.getOrderId(), request.getQuantity().stripTrailingZeros().toPlainString(), request.getOccurredAt(), exchangeId, attachmentKeys(request.getAttachmentList()));
GaoRecyclePayment existing = mapper.byRequest(order.getStoreId(), request.getRequestNo());
if (existing != null) {
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应支付内容不一致");
return existing;
}
List<Attachment> sourceAttachments = exchangeId == null ? request.getAttachmentList() : attachments.listByBizId(Attachment.BizType.GAO_SALES_ORDER, order.getId());
TimiException.requiredTrue(hasPhoto(sourceAttachments), "支付必须上传照片");
TimiException.requiredTrue(order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && order.getStatus() != GaoSalesOrder.Status.CANCELLED && order.getRecycleItemId() != null && order.getRecycleRequiredQuantity() != null, "订单不支持回收物支付");
TimiException.requiredTrue(0 <= order.getRecycleRequiredQuantity().compareTo(mapper.occupied(order.getId()).add(request.getQuantity())), "支付数量超过未结算数量");
long now = Time.now();
GaoRecyclePayment payment = new GaoRecyclePayment();
payment.setId(UUID.randomUUID().toString());
payment.setStoreId(order.getStoreId());
payment.setCustomerId(order.getCustomerId());
payment.setOrderId(order.getId());
payment.setRecycleItemId(order.getRecycleItemId());
payment.setRequestNo(request.getRequestNo());
payment.setRequestFingerprint(fingerprint);
payment.setQuantity(request.getQuantity());
payment.setStatus(GaoRecyclePayment.Status.PENDING);
payment.setOperatorUserId(login.getRequireLoginUserId());
payment.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
payment.setCreatedAt(now);
mapper.insert(payment);
if (exchangeId == null) {
attachments.updateByBizId(Attachment.BizType.GAO_RECYCLE_PAYMENT, payment.getId(), request.getAttachmentList());
} else {
for (Attachment source : sourceAttachments) {
Attachment clone = attachments.clone(source.getId());
clone.setBizType(Attachment.BizType.GAO_RECYCLE_PAYMENT);
clone.setBizId(payment.getId());
attachments.update(clone);
}
}
accounts.change(order.getStoreId(), order.getCustomerId(), order.getRecycleItemId(), BigDecimal.ZERO, payment.getQuantity(), "PAYMENT_RESERVE", payment.getId(), "recycle:reserve:" + payment.getId(), null);
return payment;
}
/// 撤销或拒绝待核销支付
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecyclePayment release(GaoRecyclePaymentRequest request, boolean reject) {
return releaseInternal(request, reject, !reject);
}
private GaoRecyclePayment releaseInternal(GaoRecyclePaymentRequest request, boolean reject, boolean onlyOperator) {
TimiException.required(request, "请求不能为空");
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "操作原因不能为空");
GaoRecyclePayment snapshot = mapper.byId(request.getPaymentId());
TimiException.required(snapshot, "支付记录不存在");
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
scope.checkStoreId(order.getStoreId());
GaoRecyclePayment payment = mapper.lock(snapshot.getId());
TimiException.requiredTrue(payment.getStatus() == GaoRecyclePayment.Status.PENDING, "支付状态不允许撤销");
if (onlyOperator) TimiException.requiredTrue(login.getRequireLoginUserId().equals(payment.getOperatorUserId()), "只能撤销自己提交的支付");
accounts.change(payment.getStoreId(), payment.getCustomerId(), payment.getRecycleItemId(), BigDecimal.ZERO, payment.getQuantity().negate(), "PAYMENT_RELEASE", payment.getId(), "recycle:release:" + payment.getId(), request.getReason());
GaoRecyclePayment.Status target = reject ? GaoRecyclePayment.Status.REJECTED : GaoRecyclePayment.Status.CANCELLED;
TimiException.requiredTrue(mapper.status(payment.getId(), GaoRecyclePayment.Status.PENDING, target, login.getRequireLoginUserId(), Time.now(), request.getReason()) == 1, "支付状态已变更");
return mapper.byId(payment.getId());
}
/// 冲正已核销回收物支付
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecyclePayment revoke(GaoRecyclePaymentRequest request) {
TimiException.required(request, "请求不能为空");
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "冲正原因不能为空");
TimiException.required(request.getReturnedToCustomer(), "必须确认回收物是否退还");
GaoRecyclePayment snapshot = mapper.byId(request.getPaymentId());
TimiException.required(snapshot, "支付记录不存在");
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
scope.checkStoreId(order.getStoreId());
GaoRecyclePayment source = mapper.lock(snapshot.getId());
String fingerprint = fingerprint("REVOKE", request.getPaymentId(), request.getOccurredAt(), request.getReason(), request.getReturnedToCustomer(), attachmentKeys(request.getAttachmentList()));
GaoRecyclePayment existing = mapper.byRequest(order.getStoreId(), request.getRequestNo());
if (existing != null) {
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应冲正内容不一致");
return existing;
}
TimiException.requiredTrue(source.getStatus() == GaoRecyclePayment.Status.VERIFIED && source.getSourcePaymentId() == null, "支付状态不允许冲正");
TimiException.requiredTrue(hasPhoto(request.getAttachmentList()), "支付冲正必须上传照片");
long now = Time.now();
GaoRecyclePayment reverse = new GaoRecyclePayment();
reverse.setId(UUID.randomUUID().toString());
reverse.setStoreId(source.getStoreId());
reverse.setCustomerId(source.getCustomerId());
reverse.setOrderId(source.getOrderId());
reverse.setRecycleItemId(source.getRecycleItemId());
reverse.setRequestNo(request.getRequestNo());
reverse.setRequestFingerprint(fingerprint);
reverse.setQuantity(source.getQuantity());
reverse.setStatus(GaoRecyclePayment.Status.VERIFIED);
reverse.setSourcePaymentId(source.getId());
reverse.setOperatorUserId(login.getRequireLoginUserId());
reverse.setVerifierUserId(reverse.getOperatorUserId());
reverse.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
reverse.setVerifiedAt(now);
reverse.setReason(request.getReason());
reverse.setReturnedToCustomer(request.getReturnedToCustomer());
reverse.setCreatedAt(now);
mapper.insert(reverse);
accounts.change(source.getStoreId(), source.getCustomerId(), source.getRecycleItemId(), source.getQuantity(), BigDecimal.ZERO, "PAYMENT_REVOKE", reverse.getId(), "recycle:revoke:" + source.getId(), request.getReason());
if (Boolean.TRUE.equals(request.getReturnedToCustomer())) {
physical.returnPayment(order, source.getId(), reverse.getId(), reverse.getOccurredAt());
}
attachments.updateByBizId(Attachment.BizType.GAO_RECYCLE_PAYMENT, reverse.getId(), request.getAttachmentList());
TimiException.requiredTrue(mapper.status(source.getId(), GaoRecyclePayment.Status.VERIFIED, GaoRecyclePayment.Status.REVOKED, login.getRequireLoginUserId(), now, request.getReason()) == 1, "支付状态已变更");
refresh(order);
reverse.setSignedQuantity(reverse.getQuantity().negate());
return reverse;
}
/// 随订单取消待核销支付
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void cancelPendingByOrderId(String orderId, String reason) {
for (GaoRecyclePayment payment : mapper.list(orderId)) {
if (payment.getStatus() != GaoRecyclePayment.Status.PENDING) continue;
GaoRecyclePaymentRequest request = new GaoRecyclePaymentRequest();
request.setPaymentId(payment.getId());
request.setReason(reason);
releaseInternal(request, false, false);
}
}
/// 创建并核销支付
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecyclePayment createAndVerify(GaoRecyclePaymentRequest request) {
GaoRecyclePayment payment = create(request);
if (payment.getStatus() == GaoRecyclePayment.Status.VERIFIED) return payment;
return verify(payment.getId());
}
/// 使用兑换单凭证创建并核销支付
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecyclePayment createAndVerifyFromExchange(GaoRecyclePaymentRequest request, String exchangeId) {
GaoRecyclePayment payment = createInternal(request, exchangeId);
if (payment.getStatus() == GaoRecyclePayment.Status.VERIFIED) return payment;
return verify(payment.getId());
}
/// 核销支付
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoRecyclePayment verify(String paymentId) {
GaoRecyclePayment snapshot = mapper.byId(paymentId);
TimiException.required(snapshot, "支付记录不存在");
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
scope.checkStoreId(order.getStoreId());
GaoRecyclePayment payment = mapper.lock(paymentId);
TimiException.requiredTrue(order.getStatus() != GaoSalesOrder.Status.CANCELLED && payment.getStatus() == GaoRecyclePayment.Status.PENDING, "支付状态不允许核销");
accounts.change(payment.getStoreId(), payment.getCustomerId(), payment.getRecycleItemId(), payment.getQuantity().negate(), payment.getQuantity().negate(), "PAYMENT_VERIFY", payment.getId(), "recycle:verify:" + payment.getId(), null);
physical.record(order, "PAYMENT_VERIFY", payment.getId(), payment.getId(), true, payment.getQuantity(), payment.getOccurredAt());
TimiException.requiredTrue(mapper.status(paymentId, GaoRecyclePayment.Status.PENDING, GaoRecyclePayment.Status.VERIFIED, login.getRequireLoginUserId(), Time.now(), null) == 1, "支付状态已变更");
refresh(order);
return mapper.byId(paymentId);
}
private void refresh(GaoSalesOrder order) {
BigDecimal paid = mapper.paid(order.getId());
order.setPaymentStatus(0 <= paid.compareTo(order.getRecycleRequiredQuantity()) ? GaoSalesOrder.PaymentStatus.PAID
: (0 < paid.signum() ? GaoSalesOrder.PaymentStatus.PARTIALLY_PAID : GaoSalesOrder.PaymentStatus.UNPAID));
orders.updatePayment(order);
}
private List<String> attachmentKeys(List<Attachment> list) {
if (list == null) return List.of();
return list.stream().filter(Objects::nonNull)
.map(a -> String.valueOf(a.getId()) + ":" + a.getTempFileId() + ":" + a.getAttachType()).sorted().toList();
}
private boolean hasPhoto(List<Attachment> list) {
return list != null && list.stream().anyMatch(item -> item != null && (item.getAttachType() == null || "PHOTO".equalsIgnoreCase(item.getAttachType())));
}
private void fillAttachments(List<GaoRecyclePayment> payments) {
if (payments.isEmpty()) return;
var map = attachments.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_PAYMENT, payments.stream().map(GaoRecyclePayment::getId).toList());
for (GaoRecyclePayment payment : payments) {
payment.setAttachmentList(map.getOrDefault(payment.getId(), List.of()));
payment.setSignedQuantity(payment.getSourcePaymentId() == null ? payment.getQuantity() : payment.getQuantity().negate());
}
}
private String fingerprint(Object... values) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(jackson.writeValueAsString(values).getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
throw new IllegalStateException("计算支付请求摘要失败", e);
}
}
}
@@ -0,0 +1,58 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.mapper.GaoRecyclePhysicalMapper;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.UUID;
/// 回收实物流转服务
@Service
@RequiredArgsConstructor
public class GaoRecyclePhysicalService {
private final GaoRecyclePhysicalMapper mapper;
private final ObjectProvider<GaoSalesOrderService> orders;
/// 记录门店收到或退回的回收物
///
/// @param order 兑换订单
/// @param sourceType 来源类型
/// @param sourceId 来源记录 ID
/// @param incoming true 为收到,false 为退回
/// @param quantity 实物数量
/// @param occurredAt 业务发生时间
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void record(GaoSalesOrder order, String sourceType, String sourceId, String paymentId, boolean incoming, BigDecimal quantity, Long occurredAt) {
TimiException.required(order, "订单不能为空");
TimiException.requiredTrue(quantity != null && 0 < quantity.signum(), "实物数量必须大于零");
orders.getObject().getForUpdate(order.getId());
if (!incoming) TimiException.requiredTrue(0 <= mapper.paymentBalance(order.getId(), paymentId).compareTo(quantity), "退回数量超过该笔支付实际保留数量");
long now = Time.now();
mapper.insert(UUID.randomUUID().toString(), order.getStoreId(), order.getCustomerId(), order.getId(), order.getRecycleItemId(), paymentId, sourceType, sourceId, incoming ? "IN" : "OUT", quantity, occurredAt == null ? now : occurredAt, now);
}
/// 查询某笔支付尚未退回的实物数量
public BigDecimal paymentBalance(String orderId, String paymentId) {
return mapper.paymentBalance(orderId, paymentId);
}
/// 冲正时将该笔支付尚未退回的实物全部退还
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void returnPayment(GaoSalesOrder order, String paymentId, String sourceId, Long occurredAt) {
orders.getObject().getForUpdate(order.getId());
BigDecimal remaining = mapper.paymentBalance(order.getId(), paymentId);
if (0 < remaining.signum()) record(order, "PAYMENT_REVOKE", sourceId, paymentId, false, remaining, occurredAt);
}
/// 查询订单当前实物保留数量,调用方须先锁定订单
public BigDecimal balance(String orderId) {
return mapper.balance(orderId);
}
}
@@ -0,0 +1,46 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleStatMapper;
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView;
import com.imyeyu.api.modules.gao.vo.GaoRecycleStatView;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/// 回收兑换统计服务
@Service
@RequiredArgsConstructor
public class GaoRecycleStatService {
private final GaoRecycleStatMapper mapper;
private final GaoStoreScopeService storeScopeService;
/// 按业务时间统计回收物
///
/// @param storeId 门店 ID
/// @param startAt 区间起点,包含
/// @param endAt 区间终点,不包含
/// @return 回收统计
public List<GaoRecycleStatView> recycle(String storeId, long startAt, long endAt) {
return mapper.selectRecycleStats(resolveStore(storeId, startAt, endAt), startAt, endAt);
}
/// 按业务时间统计兑换
///
/// @param storeId 门店 ID
/// @param startAt 区间起点,包含
/// @param endAt 区间终点,不包含
/// @return 兑换统计
public List<GaoRecycleExchangeStatView> exchange(String storeId, long startAt, long endAt) {
return mapper.selectExchangeStats(resolveStore(storeId, startAt, endAt), startAt, endAt);
}
private String resolveStore(String storeId, long startAt, long endAt) {
String resolved = storeScopeService.resolveStoreId(storeId);
TimiException.required(resolved, "请选择门店");
TimiException.requiredTrue(startAt < endAt, "统计时间区间无效");
return resolved;
}
}
@@ -52,6 +52,9 @@ public interface GaoSalesOrderService extends BaseService<GaoSalesOrder, String>
/// 由套餐购买流程创建套餐订单 /// 由套餐购买流程创建套餐订单
GaoSalesOrder createPackageOrder(GaoPackageOrderCreateData data); GaoSalesOrder createPackageOrder(GaoPackageOrderCreateData data);
/// 创建回收兑换订单
GaoSalesOrder createRecycleOrder(GaoPackageOrderCreateData data, String recycleItemId, java.math.BigDecimal requiredQuantity);
/// 锁定订单 /// 锁定订单
GaoSalesOrder getForUpdate(String id); GaoSalesOrder getForUpdate(String id);
@@ -22,6 +22,11 @@ public interface GaoStoreService extends BaseService<GaoStore, String> {
List<GaoStore> listByAutoClosedDay(); List<GaoStore> listByAutoClosedDay();
/// 查询可用门店
///
/// @return 门店列表
List<GaoStore> listActivated();
/// 按客户端提交的顺序更新排序 /// 按客户端提交的顺序更新排序
/// ///
/// @param idList 门店 ID 列表 /// @param idList 门店 ID 列表
@@ -0,0 +1,42 @@
package com.imyeyu.api.modules.gao.service;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.gao.vo.GaoStoreBirthdayReminderSetting;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/// GAO 门店配置服务
///
/// 门店配置属于业务级配置,bizId 为门店 ID,启动时不初始化记录
///
/// @author Codex
/// @since 2026-11-15
public interface GaoStoreSettingService {
/// 读取门店配置
///
/// 缺少记录的配置项返回带默认值的对象,不落库
///
/// @param storeId 门店 ID
/// @param codeList 配置代码列表,为空返回全部
/// @return 配置代码与配置的映射
Map<String, Setting> mapSetting(String storeId, Collection<String> codeList);
/// 保存门店配置
///
/// 合并写入,未提交的配置项保留
///
/// @param storeId 门店 ID
/// @param settingList 配置列表
void updateSetting(String storeId, List<Setting> settingList);
/// 读取门店生日提醒配置
///
/// 用于定时任务判断是否生成提醒,包含负责人有效性
///
/// @param storeId 门店 ID
/// @return 生日提醒配置
GaoStoreBirthdayReminderSetting getBirthdayReminderSetting(String storeId);
}
@@ -0,0 +1,267 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.entity.GaoStore;
import com.imyeyu.api.modules.gao.mapper.GaoCustomerFollowUpReminderMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerBirthdayReminderService;
import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.service.GaoStoreSettingService;
import com.imyeyu.api.modules.gao.util.LunarDate;
import com.imyeyu.api.modules.gao.vo.GaoStoreBirthdayReminderSetting;
import com.imyeyu.java.TimiJava;
import com.imyeyu.utils.Time;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/// GAO 客户生日提醒生成服务实现
///
/// 定时任务没有登录用户,提醒的 created_by 和站内通知的发送人统一使用系统用户
///
/// @author Codex
/// @since 2026-11-15
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoCustomerBirthdayReminderServiceImplement implements GaoCustomerBirthdayReminderService {
/// 生日提前生成天数,记录提前进入待办列表,提醒时间取生日当天
private static final int ADVANCE_DAYS = 7;
/// 生日当天的提醒时间点,站内通知和短信在该时间点发出
private static final LocalTime REMIND_AT_TIME = LocalTime.of(8, 0);
/// 系统操作人用户 ID
private static final String SYSTEM_USER_ID = TimiJava.ZERO_UUID;
/// 幂等键前缀,完整格式为 BIRTHDAY:年份
private static final String SOURCE_KEY_PREFIX = "BIRTHDAY";
/// 元数据中的业务类型
private static final String METADATA_BIZ_TYPE = "BIRTHDAY";
/// 站内信主题
private static final String INTERNAL_SUBJECT = "客户生日提醒";
/// 站内信模板,正文支持跳转客户详情
private static final String INTERNAL_TEMPLATE_NAME = "GaoCustomerBirthdayReminder.ftl";
/// 客户详情页路径
private static final String CUSTOMER_DETAIL_PATH = "/management/customers";
private static final String ZONE_ID = "Asia/Shanghai";
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("MM-dd");
private final GaoCustomerFollowUpReminderMapper mapper;
private final GaoCustomerFollowUpReminderService followUpReminderService;
private final GaoStoreService storeService;
private final GaoStoreSettingService storeSettingService;
private final ObjectMapper jackson;
private final Configuration freemarkerConfiguration;
/// 生成当天需要创建的生日提醒
///
/// 提前 7 天创建记录让待办提前可见,提醒时间取生日当天 08:00
/// 站内通知和短信跟随提醒时间,在生日当天发出
///
/// @return 实际创建数量
@Override
public int generate() {
ZoneId zoneId = ZoneId.of(ZONE_ID);
LocalDate today = LocalDate.now(zoneId);
LocalDate targetDate = today.plusDays(ADVANCE_DAYS);
long remindAt = targetDate.atTime(REMIND_AT_TIME).atZone(zoneId).toInstant().toEpochMilli();
Map<String, GaoStoreBirthdayReminderSetting> settingMap = loadEnabledSettingMap();
if (settingMap.isEmpty()) {
return 0;
}
List<GaoCustomer> candidateList = mapper.selectBirthdayCandidate(settingMap.keySet());
if (candidateList.isEmpty()) {
return 0;
}
String sourceKey = "%s:%d".formatted(SOURCE_KEY_PREFIX, targetDate.getYear());
int created = 0;
for (GaoCustomer customer : candidateList) {
GaoStoreBirthdayReminderSetting setting = settingMap.get(customer.getStoreId());
if (setting == null) {
continue;
}
if (!LunarDate.isBirthday(targetDate, customer.getBirthdate(), customer.getBirthdateCalendar())) {
continue;
}
GaoCustomerFollowUpReminder reminder = buildReminder(customer, setting, targetDate, remindAt, sourceKey);
if (0 >= mapper.insertIgnore(reminder)) {
continue;
}
created++;
fillInternalNotify(reminder, customer, setting, targetDate);
}
return created;
}
/// 加载启用生日提醒的门店配置
///
/// 负责人不是门店启用中的用户时跳过该门店,避免提醒落到无效用户
///
/// @return 门店 ID 与配置的映射
private Map<String, GaoStoreBirthdayReminderSetting> loadEnabledSettingMap() {
List<GaoStore> storeList = storeService.listActivated();
Map<String, GaoStoreBirthdayReminderSetting> map = new LinkedHashMap<>(storeList.size());
for (GaoStore store : storeList) {
GaoStoreBirthdayReminderSetting setting = storeSettingService.getBirthdayReminderSetting(store.getId());
if (!Boolean.TRUE.equals(setting.getEnabled())) {
continue;
}
if (!Boolean.TRUE.equals(setting.getResponsibleUserValid())) {
log.warn("GAO 客户生日提醒跳过门店 {},负责人 {} 不是门店启用中的用户",
store.getId(), setting.getResponsibleUserId());
continue;
}
map.put(store.getId(), setting);
}
return map;
}
/// 构建生日提醒
///
/// @param customer 客户
/// @param setting 门店配置
/// @param targetDate 生日当天
/// @param remindAt 提醒时间
/// @param sourceKey 幂等键
/// @return 提醒
private GaoCustomerFollowUpReminder buildReminder(GaoCustomer customer, GaoStoreBirthdayReminderSetting setting,
LocalDate targetDate, long remindAt, String sourceKey) {
GaoCustomerFollowUpReminder reminder = new GaoCustomerFollowUpReminder();
reminder.setId(UUID.randomUUID().toString());
reminder.setStoreId(customer.getStoreId());
reminder.setCustomerId(customer.getId());
reminder.setResponsibleUserId(setting.getResponsibleUserId());
reminder.setContent(buildContent(customer, targetDate));
reminder.setRemindAt(remindAt);
reminder.setStatus(GaoCustomerFollowUpReminder.Status.PENDING);
reminder.setSource(GaoCustomerFollowUpReminder.Source.SYSTEM);
reminder.setSourceKey(sourceKey);
reminder.setMetadata(buildMetadata(customer, targetDate));
reminder.setInternalNotifyEnabled(true);
reminder.setSmsNotifyEnabled(true);
reminder.setCreatedBy(SYSTEM_USER_ID);
reminder.setCreatedAt(Time.now());
return reminder;
}
/// 构建提醒内容
///
/// 记录会提前进入待办列表并跨多天展示,正文不写相对天数,只写生日当天日期
///
/// @param customer 客户
/// @param targetDate 生日当天
/// @return 提醒内容
private String buildContent(GaoCustomer customer, LocalDate targetDate) {
String name = TimiJava.isEmpty(customer.getName()) ? "未知客户" : customer.getName().trim();
String dateText = targetDate.format(DATE_FORMATTER);
if (isLunar(customer)) {
return "客户「%s」生日 %s(%s),请安排关怀"
.formatted(name, dateText, LunarDate.formatLunarMonthDay(targetDate));
}
return "客户「%s」生日 %s,请安排关怀".formatted(name, dateText);
}
/// 构建提醒元数据快照
///
/// @param customer 客户
/// @param targetDate 生日当天
/// @return 元数据
private ObjectNode buildMetadata(GaoCustomer customer, LocalDate targetDate) {
ObjectNode node = jackson.createObjectNode();
node.put("bizType", METADATA_BIZ_TYPE);
node.put("birthdaySolar", targetDate.toString());
boolean lunar = isLunar(customer);
node.put("birthdayCalendar", lunar ? "LUNAR" : "SOLAR");
if (lunar) {
node.put("birthdayLunar", LunarDate.formatLunarMonthDay(targetDate));
node.put("leapMonth", LunarDate.isLeapMonth(targetDate));
}
return node;
}
/// 补齐站内通知
///
/// 正文走模板渲染,比短信更完整,且带客户详情跳转
/// 单条通知失败不影响其余记录生成,提醒本身已经落库
///
/// @param reminder 提醒
/// @param customer 客户
/// @param setting 门店配置
/// @param targetDate 生日当天
private void fillInternalNotify(GaoCustomerFollowUpReminder reminder, GaoCustomer customer,
GaoStoreBirthdayReminderSetting setting, LocalDate targetDate) {
if (!Boolean.TRUE.equals(reminder.getInternalNotifyEnabled()) || setting.getResponsibleUser() == null) {
return;
}
try {
String detailId = followUpReminderService.createSystemInternalNotify(reminder, INTERNAL_SUBJECT,
buildInternalNotifyContent(customer, targetDate), NotifyDetail.ContentType.TIP_TAP,
setting.getResponsibleUser());
if (TimiJava.isEmpty(detailId)) {
return;
}
reminder.setInternalNotifyDetailId(detailId);
mapper.update(reminder);
} catch (Exception e) {
log.error("GAO 客户生日提醒创建站内通知失败,提醒 {}", reminder.getId(), e);
}
}
/// 渲染站内通知正文
///
/// @param customer 客户
/// @param targetDate 生日当天
/// @return 渲染后的正文
private String buildInternalNotifyContent(GaoCustomer customer, LocalDate targetDate) {
Map<String, Object> model = new LinkedHashMap<>();
model.put("customerName", TimiJava.isEmpty(customer.getName()) ? "未知客户" : customer.getName().trim());
model.put("birthdayText", targetDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
model.put("lunarText", isLunar(customer) ? "农历" + LunarDate.formatLunarMonthDay(targetDate) : null);
model.put("telephone", customer.getTelephone());
model.put("disease", customer.getDisease());
model.put("remark", customer.getRemark());
model.put("customerUrl", "%s/%s".formatted(CUSTOMER_DETAIL_PATH, customer.getId()));
try {
Template template = freemarkerConfiguration.getTemplate(INTERNAL_TEMPLATE_NAME);
StringWriter writer = new StringWriter();
template.process(model, writer);
return writer.toString();
} catch (IOException | TemplateException e) {
throw new IllegalStateException("渲染客户生日提醒站内信模板失败", e);
}
}
/// 判断客户是否按农历过生日
///
/// @param customer 客户
/// @return true 为农历生日
private boolean isLunar(GaoCustomer customer) {
return customer.getBirthdateCalendar() == GaoCustomer.BirthdateCalendar.LUNAR;
}
}
@@ -108,6 +108,10 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
Boolean.TRUE.equals(reminder.getSmsNotifyEnabled())); Boolean.TRUE.equals(reminder.getSmsNotifyEnabled()));
reminder.setStatus(GaoCustomerFollowUpReminder.Status.PENDING); reminder.setStatus(GaoCustomerFollowUpReminder.Status.PENDING);
// 来源和系统扩展字段只由系统任务写入,忽略请求值
reminder.setSource(GaoCustomerFollowUpReminder.Source.MANUAL);
reminder.setSourceKey(null);
reminder.setMetadata(null);
reminder.setCreatedBy(userLoginService.getRequireLoginUserId()); reminder.setCreatedBy(userLoginService.getRequireLoginUserId());
reminder.setUpdatedBy(null); reminder.setUpdatedBy(null);
reminder.setCompletedBy(null); reminder.setCompletedBy(null);
@@ -116,7 +120,9 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
attachmentService.updateByBizId(Attachment.BizType.GAO_CUSTOMER_FOLLOW_UP_REMINDER, attachmentService.updateByBizId(Attachment.BizType.GAO_CUSTOMER_FOLLOW_UP_REMINDER,
reminder.getId(), reminder.getAttachmentList()); reminder.getId(), reminder.getAttachmentList());
if (Boolean.TRUE.equals(reminder.getInternalNotifyEnabled())) { if (Boolean.TRUE.equals(reminder.getInternalNotifyEnabled())) {
reminder.setInternalNotifyDetailId(createInternalNotify(reminder, customer, responsibleUser)); reminder.setInternalNotifyDetailId(createInternalNotify(reminder, "客户跟进提醒",
buildInternalContent(customer, reminder), NotifyDetail.ContentType.TEXT,
responsibleUser, userLoginService.getRequireLoginUserId()));
super.update(reminder); super.update(reminder);
} }
reminder.resolveNotifyChannelList(); reminder.resolveNotifyChannelList();
@@ -194,6 +200,27 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
super.delete(id); super.delete(id);
} }
/// 为系统创建的提醒创建站内通知
///
/// @param reminder 提醒
/// @param subject 通知主题
/// @param content 通知正文
/// @param contentType 正文类型
/// @param responsibleUser 负责人
/// @return 通知详情 ID
@Override
public String createSystemInternalNotify(GaoCustomerFollowUpReminder reminder, String subject, String content,
NotifyDetail.ContentType contentType, User responsibleUser) {
TimiException.required(reminder, "未找到客户跟进提醒");
TimiException.required(reminder.getId(), "未找到客户跟进提醒 ID");
TimiException.required(subject, "未找到通知主题");
TimiException.required(content, "未找到通知内容");
TimiException.required(responsibleUser, "未找到负责人用户");
return createInternalNotify(reminder, subject, content,
TimiJava.defaultIfNull(contentType, NotifyDetail.ContentType.TEXT),
responsibleUser, TimiJava.ZERO_UUID);
}
/// 创建当天的短信聚合批次 /// 创建当天的短信聚合批次
@Override @Override
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@@ -352,7 +379,9 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
NotifyDetail detail = TimiJava.isEmpty(reminder.getInternalNotifyDetailId()) NotifyDetail detail = TimiJava.isEmpty(reminder.getInternalNotifyDetailId())
? null : notifyDetailService.get(reminder.getInternalNotifyDetailId()); ? null : notifyDetailService.get(reminder.getInternalNotifyDetailId());
if (!oldInternalEnabled || detail == null || detail.getStatus() == NotifyDetail.Status.CANCEL) { if (!oldInternalEnabled || detail == null || detail.getStatus() == NotifyDetail.Status.CANCEL) {
reminder.setInternalNotifyDetailId(createInternalNotify(reminder, customer, responsibleUser)); reminder.setInternalNotifyDetailId(createInternalNotify(reminder, "客户跟进提醒",
buildInternalContent(customer, reminder), NotifyDetail.ContentType.TEXT,
responsibleUser, userLoginService.getRequireLoginUserId()));
return; return;
} }
if (detail.getMsgType() == NotifyDetail.MsgType.INTERNAL if (detail.getMsgType() == NotifyDetail.MsgType.INTERNAL
@@ -367,17 +396,20 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
/// 创建站内通知 /// 创建站内通知
/// ///
/// @param reminder 跟进提醒 /// @param reminder 跟进提醒
/// @param customer 客户 /// @param subject 通知主题
/// @param content 通知正文
/// @param contentType 正文类型
/// @param responsibleUser 负责人 /// @param responsibleUser 负责人
/// @param operatorUserId 操作人用户 ID
/// @return 通知详情 ID /// @return 通知详情 ID
private String createInternalNotify(GaoCustomerFollowUpReminder reminder, GaoCustomer customer, private String createInternalNotify(GaoCustomerFollowUpReminder reminder, String subject, String content,
User responsibleUser) { NotifyDetail.ContentType contentType, User responsibleUser, String operatorUserId) {
NotifyDetail detail = new NotifyDetail(); NotifyDetail detail = new NotifyDetail();
detail.setMsgType(NotifyDetail.MsgType.INTERNAL); detail.setMsgType(NotifyDetail.MsgType.INTERNAL);
detail.setSubject("客户跟进提醒"); detail.setSubject(subject);
detail.setContent(buildInternalContent(customer, reminder)); detail.setContent(content);
detail.setContentType(NotifyDetail.ContentType.TEXT); detail.setContentType(contentType);
detail.setSendFrom(userLoginService.getRequireLoginUserId()); detail.setSendFrom(operatorUserId);
detail.setSendTo(responsibleUser.getId()); detail.setSendTo(responsibleUser.getId());
detail.setSendAt(reminder.getRemindAt()); detail.setSendAt(reminder.getRemindAt());
detail.setTimeoutAt(reminder.getRemindAt() + Time.D); detail.setTimeoutAt(reminder.getRemindAt() + Time.D);
@@ -397,7 +429,7 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
notify.setBizType(NOTIFY_BIZ_TYPE); notify.setBizType(NOTIFY_BIZ_TYPE);
notify.setBizRemindedType(INTERNAL_NOTIFY_TYPE); notify.setBizRemindedType(INTERNAL_NOTIFY_TYPE);
notify.setBizRemindedKey(reminder.getId()); notify.setBizRemindedKey(reminder.getId());
notify.setCreatedBy(userLoginService.getRequireLoginUserId()); notify.setCreatedBy(operatorUserId);
notify.setDetailList(List.of(detail)); notify.setDetailList(List.of(detail));
notifyService.create(notify); notifyService.create(notify);
} else { } else {
@@ -415,7 +447,7 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
private String buildInternalContent(GaoCustomer customer, GaoCustomerFollowUpReminder reminder) { private String buildInternalContent(GaoCustomer customer, GaoCustomerFollowUpReminder reminder) {
String content = reminder.getContent(); String content = reminder.getContent();
String summary = content.length() <= 100 ? content : content.substring(0, 100) + "..."; String summary = content.length() <= 100 ? content : content.substring(0, 100) + "...";
return "客户「%s」跟进提醒:%s\n提醒 ID:%s".formatted(customer.getName(), summary, reminder.getId()); return "客户「%s」跟进提醒:%s".formatted(customer.getName(), summary);
} }
/// 取消尚未生效的站内通知 /// 取消尚未生效的站内通知
@@ -20,6 +20,7 @@ import com.imyeyu.api.modules.gao.mapper.GaoOrderFulfillmentMapper;
import com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper; import com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper;
import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderMapper; import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderMapper;
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService; import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoRecycleAccountService;
import com.imyeyu.api.modules.gao.service.GaoCustomerService; import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoProductService; import com.imyeyu.api.modules.gao.service.GaoProductService;
import com.imyeyu.api.modules.gao.service.GaoProductStockService; import com.imyeyu.api.modules.gao.service.GaoProductStockService;
@@ -88,6 +89,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
private static final BigDecimal ZERO = BigDecimal.ZERO; private static final BigDecimal ZERO = BigDecimal.ZERO;
private final GaoOrderFulfillmentMapper mapper; private final GaoOrderFulfillmentMapper mapper;
private final GaoRecycleAccountService recycleAccountService;
private final GaoOrderFulfillmentItemMapper itemMapper; private final GaoOrderFulfillmentItemMapper itemMapper;
private final GaoCustomerMapper customerMapper; private final GaoCustomerMapper customerMapper;
private final GaoSalesOrderMapper salesOrderMapper; private final GaoSalesOrderMapper salesOrderMapper;
@@ -191,7 +193,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
TimiException.required(request, "快速履约客户查询请求不能为空"); TimiException.required(request, "快速履约客户查询请求不能为空");
GaoCustomer customer = getQuickFulfillmentCustomer(request.getCustomerId(), false); GaoCustomer customer = getQuickFulfillmentCustomer(request.getCustomerId(), false);
List<GaoQuickFulfillmentSourceRow> sourceRows = salesOrderMapper.selectQuickFulfillmentSourceRows( List<GaoQuickFulfillmentSourceRow> sourceRows = salesOrderMapper.selectQuickFulfillmentSourceRows(
customer.getStoreId(), customer.getId(), null, null, canQuickFulfillUnpaidOrder()); customer.getStoreId(), customer.getId(), null, null, canQuickFulfillUnpaidOrder(), canQuickFulfillUnsettledRecycle());
if (sourceRows == null || sourceRows.isEmpty()) { if (sourceRows == null || sourceRows.isEmpty()) {
return List.of(); return List.of();
} }
@@ -233,7 +235,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
List<String> skuIdList = normalizedIdList(request.getSkuIdList(), "skuIdList"); List<String> skuIdList = normalizedIdList(request.getSkuIdList(), "skuIdList");
TimiException.requiredTrue(!skuIdList.isEmpty(), "至少选择一个 SKU"); TimiException.requiredTrue(!skuIdList.isEmpty(), "至少选择一个 SKU");
List<GaoQuickFulfillmentSourceRow> sourceRows = salesOrderMapper.selectQuickFulfillmentSourceRows( List<GaoQuickFulfillmentSourceRow> sourceRows = salesOrderMapper.selectQuickFulfillmentSourceRows(
customer.getStoreId(), customer.getId(), skuIdList, null, canQuickFulfillUnpaidOrder()); customer.getStoreId(), customer.getId(), skuIdList, null, canQuickFulfillUnpaidOrder(), canQuickFulfillUnsettledRecycle());
Map<String, GaoQuickFulfillmentSourceOrderView> orderMap = new LinkedHashMap<>(); Map<String, GaoQuickFulfillmentSourceOrderView> orderMap = new LinkedHashMap<>();
for (GaoQuickFulfillmentSourceRow row : sourceRows) { for (GaoQuickFulfillmentSourceRow row : sourceRows) {
GaoQuickFulfillmentSourceOrderView order = orderMap.computeIfAbsent(row.getSalesOrderId(), key -> { GaoQuickFulfillmentSourceOrderView order = orderMap.computeIfAbsent(row.getSalesOrderId(), key -> {
@@ -242,6 +244,10 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
view.setOrderNo(row.getOrderNo()); view.setOrderNo(row.getOrderNo());
view.setOrderType(row.getOrderType()); view.setOrderType(row.getOrderType());
view.setPaymentStatus(row.getPaymentStatus()); view.setPaymentStatus(row.getPaymentStatus());
view.setRecycleRequiredQuantity(row.getRecycleRequiredQuantity());
view.setRecycleVerifiedQuantity(row.getRecycleVerifiedQuantity());
view.setRecycleItemName(row.getRecycleItemName());
view.setRecycleUnit(row.getRecycleUnit());
view.setPackageName(row.getPackageName()); view.setPackageName(row.getPackageName());
view.setSaleAmount(row.getSaleAmount()); view.setSaleAmount(row.getSaleAmount());
view.setPaidAmount(row.getPaidAmount()); view.setPaidAmount(row.getPaidAmount());
@@ -333,7 +339,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
List<String> skuIdList = requestItemList.stream().map(GaoQuickFulfillmentCreateItemRequest::getSkuId).toList(); List<String> skuIdList = requestItemList.stream().map(GaoQuickFulfillmentCreateItemRequest::getSkuId).toList();
List<GaoQuickFulfillmentSourceRow> sourceRows = salesOrderMapper.selectQuickFulfillmentSourceRows( List<GaoQuickFulfillmentSourceRow> sourceRows = salesOrderMapper.selectQuickFulfillmentSourceRows(
customer.getStoreId(), customerId, skuIdList, lockOrderIdList, canQuickFulfillUnpaidOrder()); customer.getStoreId(), customerId, skuIdList, lockOrderIdList, canQuickFulfillUnpaidOrder(), canQuickFulfillUnsettledRecycle());
TimiException.requiredTrue(sourceRows != null && !sourceRows.isEmpty(), "所选订单没有可履约 SKU"); TimiException.requiredTrue(sourceRows != null && !sourceRows.isEmpty(), "所选订单没有可履约 SKU");
Map<String, GaoQuickFulfillmentSourceRow> sourceRowMap = new HashMap<>(); Map<String, GaoQuickFulfillmentSourceRow> sourceRowMap = new HashMap<>();
for (GaoQuickFulfillmentSourceRow sourceRow : sourceRows) { for (GaoQuickFulfillmentSourceRow sourceRow : sourceRows) {
@@ -536,6 +542,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
} }
TimiException.requiredTrue(1 == mapper.updateStatus(fulfillment.getId(), GaoOrderFulfillment.Status.VERIFIED, TimiException.requiredTrue(1 == mapper.updateStatus(fulfillment.getId(), GaoOrderFulfillment.Status.VERIFIED,
verifierUserId, Time.now(), request.getReason()), "履约状态已变化"); verifierUserId, Time.now(), request.getReason()), "履约状态已变化");
recycleAccountService.addFromFulfillment(order.getStoreId(), order.getCustomerId(), fulfillment.getId(), fulfillmentItemList);
salesOrderService.refreshFulfillmentStatus(order); salesOrderService.refreshFulfillmentStatus(order);
return detail(fulfillment.getId()); return detail(fulfillment.getId());
} }
@@ -667,6 +674,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
TimiException.requiredTrue(1 == mapper.updateStatus(source.getId(), GaoOrderFulfillment.Status.REVOKED, TimiException.requiredTrue(1 == mapper.updateStatus(source.getId(), GaoOrderFulfillment.Status.REVOKED,
operatorUserId, Time.now(), reason), "原履约状态已变化"); operatorUserId, Time.now(), reason), "原履约状态已变化");
attachmentService.updateByBizId(Attachment.BizType.GAO_ORDER_FULFILLMENT, reverse.getId(), request.getAttachmentList()); attachmentService.updateByBizId(Attachment.BizType.GAO_ORDER_FULFILLMENT, reverse.getId(), request.getAttachmentList());
recycleAccountService.revokeFulfillment(order.getStoreId(), order.getCustomerId(), source.getId(), reverse.getId());
salesOrderService.refreshFulfillmentStatus(order); salesOrderService.refreshFulfillmentStatus(order);
return detail(reverse.getId()); return detail(reverse.getId());
} }
@@ -740,6 +748,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
stockRequestNo(returned, "RETURN"), operatorUserId); stockRequestNo(returned, "RETURN"), operatorUserId);
} }
attachmentService.updateByBizId(Attachment.BizType.GAO_ORDER_FULFILLMENT, returned.getId(), request.getAttachmentList()); attachmentService.updateByBizId(Attachment.BizType.GAO_ORDER_FULFILLMENT, returned.getId(), request.getAttachmentList());
recycleAccountService.revokeFulfillment(order.getStoreId(), order.getCustomerId(), source.getId(), returned.getId());
salesOrderService.refreshFulfillmentStatus(order); salesOrderService.refreshFulfillmentStatus(order);
return detail(returned.getId()); return detail(returned.getId());
} }
@@ -818,8 +827,11 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
GaoSalesOrderItem source = salesOrderService.getItemForUpdate(requestItem.getSourceOrderItemId()); GaoSalesOrderItem source = salesOrderService.getItemForUpdate(requestItem.getSourceOrderItemId());
TimiException.required(source, "not found sales order item"); TimiException.required(source, "not found sales order item");
TimiException.requiredTrue(order.getId().equals(source.getSalesOrderId()), "订单明细不属于当前订单"); TimiException.requiredTrue(order.getId().equals(source.getSalesOrderId()), "订单明细不属于当前订单");
GaoSalesOrderItem.ItemType expectedItemType = order.getOrderType() == GaoSalesOrder.OrderType.PACKAGE GaoSalesOrderItem.ItemType expectedItemType = switch (order.getOrderType()) {
? GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT : GaoSalesOrderItem.ItemType.DIRECT_PRODUCT; case PACKAGE -> GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT;
case RECYCLE -> GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT;
case DIRECT_PRODUCT -> GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
};
TimiException.requiredTrue(source.getItemType() == expectedItemType, "订单项类型与订单类型不匹配"); TimiException.requiredTrue(source.getItemType() == expectedItemType, "订单项类型与订单类型不匹配");
if (requestItem.getSkuUnitId().equals(source.getSkuUnitId())) { if (requestItem.getSkuUnitId().equals(source.getSkuUnitId())) {
result.add(toSourceByOrderSnapshot(order, source, requestItem.getQuantity(), checkAvailable)); result.add(toSourceByOrderSnapshot(order, source, requestItem.getQuantity(), checkAvailable));
@@ -905,8 +917,11 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
private void validateSourceOrderItem(GaoSalesOrder order, GaoSalesOrderItem source) { private void validateSourceOrderItem(GaoSalesOrder order, GaoSalesOrderItem source) {
TimiException.required(source, "not found sales order item"); TimiException.required(source, "not found sales order item");
TimiException.requiredTrue(order.getId().equals(source.getSalesOrderId()), "订单明细不属于当前订单"); TimiException.requiredTrue(order.getId().equals(source.getSalesOrderId()), "订单明细不属于当前订单");
GaoSalesOrderItem.ItemType expectedItemType = order.getOrderType() == GaoSalesOrder.OrderType.PACKAGE GaoSalesOrderItem.ItemType expectedItemType = switch (order.getOrderType()) {
? GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT : GaoSalesOrderItem.ItemType.DIRECT_PRODUCT; case PACKAGE -> GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT;
case RECYCLE -> GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT;
case DIRECT_PRODUCT -> GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
};
TimiException.requiredTrue(source.getItemType() == expectedItemType, "订单项类型与订单类型不匹配"); TimiException.requiredTrue(source.getItemType() == expectedItemType, "订单项类型与订单类型不匹配");
} }
@@ -1069,9 +1084,12 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
return customer; return customer;
} }
/// 判断当前用户是否拥有未全额收款订单履约例外 /// 判断是否允许未结清回收订单履约
/// private boolean canQuickFulfillUnsettledRecycle() {
/// @return true 为允许查询未全额收款订单 return permissionChecker.hasAny(ModuleCode.GAO, com.imyeyu.api.modules.gao.bean.GaoPermissionCode.ORDER_FULFILLMENT_UNSETTLED.getValue());
}
/// 判断是否允许未全额收款订单履约
private boolean canQuickFulfillUnpaidOrder() { private boolean canQuickFulfillUnpaidOrder() {
return roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name()); return roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name());
} }
@@ -65,6 +65,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
TimiException.required(request.getAmount(), "收款金额不能为空"); TimiException.required(request.getAmount(), "收款金额不能为空");
TimiException.requiredTrue(0 < request.getAmount(), "收款金额必须大于 0"); TimiException.requiredTrue(0 < request.getAmount(), "收款金额必须大于 0");
GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId()); GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId());
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
String requestNo = requiredText(request.getRequestNo(), "not found requestNo"); String requestNo = requiredText(request.getRequestNo(), "not found requestNo");
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo); GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
if (existing != null) { if (existing != null) {
@@ -112,6 +113,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
GaoFundRecord snapshot = fundRecordService.detail(fundRecordId); GaoFundRecord snapshot = fundRecordService.detail(fundRecordId);
TimiException.requiredTrue(snapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金"); TimiException.requiredTrue(snapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金");
GaoSalesOrder order = orderService.getForUpdate(snapshot.getBizId()); GaoSalesOrder order = orderService.getForUpdate(snapshot.getBizId());
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
GaoFundRecord record = lockOrderRecord(fundRecordId); GaoFundRecord record = lockOrderRecord(fundRecordId);
TimiException.requiredTrue(order.getId().equals(record.getBizId()), "资金流水所属订单已变化"); TimiException.requiredTrue(order.getId().equals(record.getBizId()), "资金流水所属订单已变化");
TimiException.requiredTrue(record.getOperationType() == GaoFundRecord.OperationType.RECEIVE && record.getStatus() == GaoFundRecord.Status.PENDING, "收款记录不是待核销状态"); TimiException.requiredTrue(record.getOperationType() == GaoFundRecord.OperationType.RECEIVE && record.getStatus() == GaoFundRecord.Status.PENDING, "收款记录不是待核销状态");
@@ -172,6 +174,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
GaoFundRecord snapshot = fundRecordService.detail(request.getFundRecordId()); GaoFundRecord snapshot = fundRecordService.detail(request.getFundRecordId());
TimiException.requiredTrue(snapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金"); TimiException.requiredTrue(snapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金");
GaoSalesOrder order = orderService.getForUpdate(snapshot.getBizId()); GaoSalesOrder order = orderService.getForUpdate(snapshot.getBizId());
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
GaoFundRecord record = lockOrderRecord(request.getFundRecordId()); GaoFundRecord record = lockOrderRecord(request.getFundRecordId());
TimiException.requiredTrue(order.getId().equals(record.getBizId()), "资金流水所属订单已变化"); TimiException.requiredTrue(order.getId().equals(record.getBizId()), "资金流水所属订单已变化");
TimiException.requiredTrue(record.getOperationType() == GaoFundRecord.OperationType.RECEIVE && record.getStatus() == GaoFundRecord.Status.PENDING, "收款记录不是待核销状态"); TimiException.requiredTrue(record.getOperationType() == GaoFundRecord.OperationType.RECEIVE && record.getStatus() == GaoFundRecord.Status.PENDING, "收款记录不是待核销状态");
@@ -204,6 +207,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
TimiException.requiredTrue(0 < request.getAmount(), "退款金额必须大于 0"); TimiException.requiredTrue(0 < request.getAmount(), "退款金额必须大于 0");
String reason = requiredText(request.getReason(), "退款原因不能为空"); String reason = requiredText(request.getReason(), "退款原因不能为空");
GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId()); GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId());
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
String requestNo = requiredText(request.getRequestNo(), "not found requestNo"); String requestNo = requiredText(request.getRequestNo(), "not found requestNo");
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo); GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
if (existing != null) { if (existing != null) {
@@ -234,6 +238,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
public GaoFundRecord confirmNoRefund(GaoOrderPaymentNoRefundRequest request) { public GaoFundRecord confirmNoRefund(GaoOrderPaymentNoRefundRequest request) {
TimiException.required(request, "not found no refund request"); TimiException.required(request, "not found no refund request");
GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId()); GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId());
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
String requestNo = requiredText(request.getRequestNo(), "not found requestNo"); String requestNo = requiredText(request.getRequestNo(), "not found requestNo");
String reason = requiredText(request.getReason(), "确认无需退款原因不能为空"); String reason = requiredText(request.getReason(), "确认无需退款原因不能为空");
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo); GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
@@ -267,6 +272,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
TimiException.requiredTrue(sourceSnapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金"); TimiException.requiredTrue(sourceSnapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金");
TimiException.required(sourceSnapshot.getBizId(), "not found salesOrderId"); TimiException.required(sourceSnapshot.getBizId(), "not found salesOrderId");
GaoSalesOrder order = orderService.getForUpdate(sourceSnapshot.getBizId()); GaoSalesOrder order = orderService.getForUpdate(sourceSnapshot.getBizId());
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
GaoFundRecord source = lockOrderRecord(request.getFundRecordId()); GaoFundRecord source = lockOrderRecord(request.getFundRecordId());
TimiException.requiredTrue(order.getId().equals(source.getBizId()), "资金流水所属订单已变化"); TimiException.requiredTrue(order.getId().equals(source.getBizId()), "资金流水所属订单已变化");
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo); GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
@@ -7,6 +7,7 @@ import com.imyeyu.api.modules.common.service.NotifyService;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder; import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.entity.GaoUser; import com.imyeyu.api.modules.gao.entity.GaoUser;
import com.imyeyu.api.modules.gao.mapper.GaoOrderReminderMapper; import com.imyeyu.api.modules.gao.mapper.GaoOrderReminderMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleReminderMapper;
import com.imyeyu.api.modules.gao.mapper.GaoUserMapper; import com.imyeyu.api.modules.gao.mapper.GaoUserMapper;
import com.imyeyu.api.modules.gao.service.GaoOrderReminderService; import com.imyeyu.api.modules.gao.service.GaoOrderReminderService;
import com.imyeyu.api.modules.gao.vo.GaoOrderReminderCustomer; import com.imyeyu.api.modules.gao.vo.GaoOrderReminderCustomer;
@@ -50,6 +51,7 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
private static final int MAX_SMS_CUSTOMER_COUNT = 99; private static final int MAX_SMS_CUSTOMER_COUNT = 99;
private final GaoOrderReminderMapper mapper; private final GaoOrderReminderMapper mapper;
private final GaoRecycleReminderMapper recycleReminderMapper;
private final GaoUserMapper gaoUserMapper; private final GaoUserMapper gaoUserMapper;
private final UserService userService; private final UserService userService;
private final NotifyService notifyService; private final NotifyService notifyService;
@@ -68,7 +70,11 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
Map<String, Map<String, ReminderEntry>> storeEntryMap = new LinkedHashMap<>(); Map<String, Map<String, ReminderEntry>> storeEntryMap = new LinkedHashMap<>();
mergeCustomers(storeEntryMap, mapper.selectReceiveVerifyCustomers(), "核销收款"); mergeCustomers(storeEntryMap, mapper.selectReceiveVerifyCustomers(), "核销收款");
mergeCustomers(storeEntryMap, mapper.selectFulfillmentVerifyCustomers(), "核销履约"); mergeCustomers(storeEntryMap, mapper.selectFulfillmentVerifyCustomers(), "核销履约");
sendStoreReminders(storeEntryMap, ReminderType.VERIFY.name()); Set<String> recycleStoreIds = new LinkedHashSet<>(recycleReminderMapper.selectPendingStoreIds());
for (String storeId : recycleStoreIds) {
storeEntryMap.computeIfAbsent(storeId, key -> new LinkedHashMap<>());
}
sendStoreReminders(storeEntryMap, ReminderType.VERIFY.name(), recycleStoreIds);
} }
/// 按提醒类型发送订单提醒 /// 按提醒类型发送订单提醒
@@ -81,7 +87,7 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
} }
Map<String, Map<String, ReminderEntry>> storeEntryMap = new LinkedHashMap<>(); Map<String, Map<String, ReminderEntry>> storeEntryMap = new LinkedHashMap<>();
mergeCustomers(storeEntryMap, customerList, reminderType.label); mergeCustomers(storeEntryMap, customerList, reminderType.label);
sendStoreReminders(storeEntryMap, reminderType.name()); sendStoreReminders(storeEntryMap, reminderType.name(), Set.of());
} }
/// 合并同一门店下同一订单的多个提醒事项 /// 合并同一门店下同一订单的多个提醒事项
@@ -115,9 +121,9 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
/// ///
/// @param storeEntryMap 门店提醒映射 /// @param storeEntryMap 门店提醒映射
/// @param reminderType 提醒类型 /// @param reminderType 提醒类型
private void sendStoreReminders(Map<String, Map<String, ReminderEntry>> storeEntryMap, String reminderType) { private void sendStoreReminders(Map<String, Map<String, ReminderEntry>> storeEntryMap, String reminderType, Set<String> recycleStoreIds) {
for (Map.Entry<String, Map<String, ReminderEntry>> entry : storeEntryMap.entrySet()) { for (Map.Entry<String, Map<String, ReminderEntry>> entry : storeEntryMap.entrySet()) {
sendStoreReminder(entry.getKey(), new ArrayList<>(entry.getValue().values()), reminderType); sendStoreReminder(entry.getKey(), new ArrayList<>(entry.getValue().values()), reminderType, recycleStoreIds.contains(entry.getKey()));
} }
} }
@@ -126,14 +132,17 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
/// @param storeId 门店 ID /// @param storeId 门店 ID
/// @param entryList 订单提醒列表 /// @param entryList 订单提醒列表
/// @param reminderType 提醒类型 /// @param reminderType 提醒类型
private void sendStoreReminder(String storeId, List<ReminderEntry> entryList, String reminderType) { private void sendStoreReminder(String storeId, List<ReminderEntry> entryList, String reminderType, boolean recyclePending) {
String customerNames = formatCustomerNames(entryList); String customerNames = formatCustomerNames(entryList);
String action = entryList.stream() String action = entryList.stream()
.flatMap(entry -> entry.actionSet().stream()) .flatMap(entry -> entry.actionSet().stream())
.distinct() .distinct()
.collect(Collectors.joining("、")); .collect(Collectors.joining("、"));
String smsContent = "您的客户 %s 的订单需要 %s,请留意订单状态。".formatted(customerNames, action); String smsContent = "您的客户 %s 的订单需要 %s,请留意订单状态。".formatted(customerNames, action);
String internalContent = buildInternalContent(entryList); String internalContent = entryList.isEmpty() ? "" : buildInternalContent(entryList);
if (recyclePending) {
internalContent += "<p>门店有待核销的回收物支付,请在订单中处理</p>";
}
List<GaoUser> managerList = gaoUserMapper.selectEnabledStoreManagers(storeId); List<GaoUser> managerList = gaoUserMapper.selectEnabledStoreManagers(storeId);
if (managerList == null || managerList.isEmpty()) { if (managerList == null || managerList.isEmpty()) {
@@ -156,10 +165,12 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
notify.setBizType(NOTIFY_BIZ_TYPE); notify.setBizType(NOTIFY_BIZ_TYPE);
notify.setBizRemindedType(reminderType); notify.setBizRemindedType(reminderType);
notify.setBizRemindedKey(remindedKey); notify.setBizRemindedKey(remindedKey);
notify.setDetailList(List.of( List<NotifyDetail> detailList = new ArrayList<>();
createInternalDetail(manager.getUserId(), internalContent, sendAt), detailList.add(createInternalDetail(manager.getUserId(), internalContent, sendAt));
createSmsDetail(user.getPhoneNo(), customerNames, action, smsContent, sendAt) if (!entryList.isEmpty()) {
)); detailList.add(createSmsDetail(user.getPhoneNo(), customerNames, action, smsContent, sendAt));
}
notify.setDetailList(detailList);
notifyService.createIfAbsent(notify); notifyService.createIfAbsent(notify);
} catch (Exception e) { } catch (Exception e) {
log.error("GAO 订单提醒发送失败: storeId[{}], userId[{}], reminderType[{}]", storeId, log.error("GAO 订单提醒发送失败: storeId[{}], userId[{}], reminderType[{}]", storeId,
@@ -214,7 +214,6 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
|| TimiJava.defaultIfNull(request.getStatus(), current.getStatus()) != current.getStatus() || TimiJava.defaultIfNull(request.getStatus(), current.getStatus()) != current.getStatus()
|| !Objects.equals(TimiJava.defaultIfNull(request.getSort(), current.getSort()), current.getSort()) || !Objects.equals(TimiJava.defaultIfNull(request.getSort(), current.getSort()), current.getSort())
|| !sameText(current.getRemark(), request.getRemark()) || !sameText(current.getRemark(), request.getRemark())
|| request.getBaseUnitMigrationRequest() != null
|| request.getAttachmentList() != null && !sameAttachmentList(current.getAttachmentList(), request.getAttachmentList())) { || request.getAttachmentList() != null && !sameAttachmentList(current.getAttachmentList(), request.getAttachmentList())) {
return false; return false;
} }
@@ -24,13 +24,10 @@ import com.imyeyu.api.modules.gao.mapper.GaoProductSpecValueMapper;
import com.imyeyu.api.modules.gao.service.GaoProductService; import com.imyeyu.api.modules.gao.service.GaoProductService;
import com.imyeyu.api.modules.gao.service.GaoProductSkuService; import com.imyeyu.api.modules.gao.service.GaoProductSkuService;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.GaoProductSkuBaseUnitMigrationRequest;
import com.imyeyu.api.modules.gao.vo.GaoProductSkuUnitSelection; import com.imyeyu.api.modules.gao.vo.GaoProductSkuUnitSelection;
import com.imyeyu.api.modules.gao.vo.GaoProductSkuFulfillmentView; import com.imyeyu.api.modules.gao.vo.GaoProductSkuFulfillmentView;
import com.imyeyu.api.modules.system.audit.AuditOperation; import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit; import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiCode;
@@ -73,7 +70,6 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
private final GaoProductSpecMapper specMapper; private final GaoProductSpecMapper specMapper;
private final GaoProductSpecValueMapper valueMapper; private final GaoProductSpecValueMapper valueMapper;
private final AttachmentService attachmentService; private final AttachmentService attachmentService;
private final LoggerService loggerService;
private final ObjectProvider<GaoProductService> productServiceProvider; private final ObjectProvider<GaoProductService> productServiceProvider;
private final UserLoginService userLoginService; private final UserLoginService userLoginService;
@@ -266,16 +262,14 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
GaoProductSkuUnit oldBaseUnit = existingUnitList.stream().filter(unit -> Boolean.TRUE.equals(unit.getIsBase())).findFirst().orElseThrow(); GaoProductSkuUnit oldBaseUnit = existingUnitList.stream().filter(unit -> Boolean.TRUE.equals(unit.getIsBase())).findFirst().orElseThrow();
List<GaoProductSkuUnit> requestedUnitList = request.getUnitList() == null ? existingUnitList : request.getUnitList(); List<GaoProductSkuUnit> requestedUnitList = request.getUnitList() == null ? existingUnitList : request.getUnitList();
GaoProductSkuUnit requestedBaseUnit = requestedUnitList.stream().filter(unit -> Boolean.TRUE.equals(unit.getIsBase())).findFirst().orElse(null); GaoProductSkuUnit requestedBaseUnit = requestedUnitList.stream().filter(unit -> Boolean.TRUE.equals(unit.getIsBase())).findFirst().orElse(null);
boolean baseUnitChanged = requestedBaseUnit == null || !oldBaseUnit.getId().equals(requestedBaseUnit.getId()); TimiException.required(requestedBaseUnit, "SKU 必须指定基础单位");
GaoProductSkuBaseUnitMigrationRequest migrationRequest = request.getBaseUnitMigrationRequest(); boolean baseUnitChanged = !oldBaseUnit.getId().equals(requestedBaseUnit.getId());
BigDecimal migrationRatio = null; boolean unitConversionChanged = request.getUnitList() != null && isUnitConversionChanged(request.getUnitList(), existingUnitList);
if (baseUnitChanged) { if (baseUnitChanged || unitConversionChanged) {
migrationRatio = validateBaseUnitMigration(oldBaseUnit, requestedBaseUnit, migrationRequest, sku.getId()); TimiException.requiredTrue(0 == referenceCount, "SKU 已有历史业务记录,不能更换基础单位或调整换算系数;如需调整请新建 SKU");
} else if (migrationRequest != null) { List<GaoProductStock> stockList = stockMapper.selectByStoreIdAndSkuIdList(sku.getStoreId(), List.of(sku.getId()));
throw new TimiException(TimiCode.ERROR, "新旧基础单位相同,不需要提交基础单位迁移比例"); TimiException.requiredTrue(stockList.stream().allMatch(stock -> isZero(stock.getOnHandQuantity()) && isZero(stock.getReservedQuantity())),
} "SKU 存在库存数量,不能更换基础单位或调整换算系数");
if (request.getUnitList() != null && !baseUnitChanged) {
validateUnitConversionUnchanged(request.getUnitList(), existingUnitList);
} }
sku.setCode(TimiJava.defaultIfNull(request.getCode(), sku.getCode())); sku.setCode(TimiJava.defaultIfNull(request.getCode(), sku.getCode()));
sku.setBarcode(request.getBarcode()); sku.setBarcode(request.getBarcode());
@@ -289,21 +283,6 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
sku.setRemark(request.getRemark()); sku.setRemark(request.getRemark());
sku.setSpecValueIdList(request.getSpecValueIdList() == null ? currentSpecValueIds(sku.getId()) : request.getSpecValueIdList()); sku.setSpecValueIdList(request.getSpecValueIdList() == null ? currentSpecValueIds(sku.getId()) : request.getSpecValueIdList());
sku.setUnitList(requestedUnitList); sku.setUnitList(requestedUnitList);
if (migrationRatio != null) {
applyBaseUnitMigration(sku, oldBaseUnit, requestedBaseUnit, existingUnitList, migrationRequest, migrationRatio);
stockMapper.selectForUpdate(sku.getStoreId(), sku.getId());
if (editMapper.countMigrationPrecisionLoss(sku.getId(), requestedBaseUnit.getId(), migrationRatio) > 0) {
throw new TimiException(TimiCode.ERROR, "基础单位迁移会产生超出字段精度的数量,未执行任何变更");
}
editMapper.scaleSkuMinimumStock(sku.getId(), migrationRatio);
editMapper.scaleProductStock(sku.getId(), migrationRatio);
editMapper.scaleSalesOrderItems(sku.getId(), migrationRatio);
editMapper.scaleFulfillmentItems(sku.getId(), migrationRatio);
editMapper.scaleStockRecords(sku.getId(), migrationRatio);
editMapper.scalePackageConfigItems(sku.getId(), migrationRatio);
editMapper.scalePointRedemptions(sku.getId(), migrationRatio);
editMapper.scalePointRedemptionReturns(sku.getId(), migrationRatio);
}
prepare(sku, sku.getId()); prepare(sku, sku.getId());
super.update(sku); super.update(sku);
if (request.getSpecValueIdList() != null) { if (request.getSpecValueIdList() != null) {
@@ -321,16 +300,6 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
editMapper.updateSkuStockRecordSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), skuSpecSnapshot); editMapper.updateSkuStockRecordSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), skuSpecSnapshot);
editMapper.updateSkuPackageSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary()); editMapper.updateSkuPackageSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary());
editMapper.updateSkuRedemptionSnapshots(sku.getId(), sku.getCode(), sku.getName(), skuSpecSnapshot); editMapper.updateSkuRedemptionSnapshots(sku.getId(), sku.getCode(), sku.getName(), skuSpecSnapshot);
if (migrationRatio != null) {
GaoProductSkuUnit migratedTarget = unitMapper.selectBySkuId(sku.getId()).stream()
.filter(unit -> unit.getIsBase() && unit.getName().equals(requestedBaseUnit.getName().trim()))
.findFirst().orElseThrow();
Logger migrationLog = new Logger(Logger.Module.GAO, Logger.Level.INFO, "GAO_PRODUCT_SKU_BASE_UNIT_MIGRATION");
migrationLog.setContent("skuId=%s;oldBaseUnitId=%s;oldBaseUnitName=%s;newBaseUnitId=%s;newBaseUnitName=%s;oldToNewBaseRatio=%s".formatted(
sku.getId(), oldBaseUnit.getId(), oldBaseUnit.getName(), migratedTarget.getId(), migratedTarget.getName(), migrationRatio.toPlainString()));
migrationLog.setResult(sku.getId());
loggerService.createSync(migrationLog);
}
} }
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@@ -464,53 +433,8 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
return result; return result;
} }
private BigDecimal validateBaseUnitMigration(GaoProductSkuUnit oldBaseUnit, GaoProductSkuUnit newBaseUnit, /// 判断已保存单位的换算系数是否被修改
GaoProductSkuBaseUnitMigrationRequest request, String skuId) { private boolean isUnitConversionChanged(List<GaoProductSkuUnit> requestedUnitList,
TimiException.required(request, "切换基础单位时必须提交新旧基础单位换算比例");
TimiException.required(newBaseUnit, "SKU 必须指定新的基础单位");
TimiException.requiredTrue(newBaseUnit.getIsBase(), "迁移目标必须是新的基础单位");
TimiException.required(newBaseUnit.getName(), "新基础单位名称不能为空");
boolean targetMatches = request.getTargetUnitId() != null && !request.getTargetUnitId().isBlank()
? request.getTargetUnitId().equals(newBaseUnit.getId())
: request.getTargetUnitName() != null && request.getTargetUnitName().trim().equals(newBaseUnit.getName().trim());
TimiException.requiredTrue(targetMatches, "基础单位迁移目标与 SKU 单位列表不一致");
BigDecimal ratio = request.getOldToNewBaseRatio();
TimiException.required(ratio, "基础单位迁移比例不能为空");
TimiException.requiredTrue(0 < ratio.signum(), "基础单位迁移比例必须大于 0");
TimiException.requiredTrue(6 >= ratio.scale(), "基础单位迁移比例最多保留六位小数");
TimiException.requiredTrue(12 >= ratio.precision() - ratio.scale(), "基础单位迁移比例超出最大值");
return ratio;
}
private void applyBaseUnitMigration(GaoProductSku sku, GaoProductSkuUnit oldBaseUnit,
GaoProductSkuUnit newBaseUnit, List<GaoProductSkuUnit> existingUnitList,
GaoProductSkuBaseUnitMigrationRequest request, BigDecimal ratio) {
Map<String, GaoProductSkuUnit> existingById = existingUnitList.stream()
.collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item));
for (GaoProductSkuUnit unit : sku.getUnitList()) {
boolean target = newBaseUnit.getId() != null
? newBaseUnit.getId().equals(unit.getId())
: newBaseUnit.getName().trim().equals(unit.getName().trim());
if (target) {
unit.setBaseQuantityPerUnit(ONE);
continue;
}
GaoProductSkuUnit existing = unit.getId() == null ? null : existingById.get(unit.getId());
BigDecimal oldFactor = existing == null
? TimiJava.defaultIfNull(unit.getBaseQuantityPerUnit(), ONE)
: existing.getBaseQuantityPerUnit();
BigDecimal newFactor = oldFactor.multiply(ratio).stripTrailingZeros();
TimiException.requiredTrue(6 >= Math.max(newFactor.scale(), 0), "单位换算系数迁移后超过六位小数,请调整换算比例");
unit.setBaseQuantityPerUnit(newFactor);
}
if (sku.getMinStockQuantity() != null) {
BigDecimal migratedMinimumStock = sku.getMinStockQuantity().multiply(ratio).stripTrailingZeros();
TimiException.requiredTrue(3 >= Math.max(migratedMinimumStock.scale(), 0), "最低库存迁移后超过三位小数,请调整换算比例");
sku.setMinStockQuantity(migratedMinimumStock);
}
}
private void validateUnitConversionUnchanged(List<GaoProductSkuUnit> requestedUnitList,
List<GaoProductSkuUnit> existingUnitList) { List<GaoProductSkuUnit> existingUnitList) {
Map<String, GaoProductSkuUnit> existingById = existingUnitList.stream() Map<String, GaoProductSkuUnit> existingById = existingUnitList.stream()
.collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item)); .collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item));
@@ -518,9 +442,10 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
GaoProductSkuUnit existing = requested.getId() == null ? null : existingById.get(requested.getId()); GaoProductSkuUnit existing = requested.getId() == null ? null : existingById.get(requested.getId());
BigDecimal requestedFactor = TimiJava.defaultIfNull(requested.getBaseQuantityPerUnit(), ONE); BigDecimal requestedFactor = TimiJava.defaultIfNull(requested.getBaseQuantityPerUnit(), ONE);
if (existing != null && existing.getBaseQuantityPerUnit().compareTo(requestedFactor) != 0) { if (existing != null && existing.getBaseQuantityPerUnit().compareTo(requestedFactor) != 0) {
throw new TimiException(TimiCode.ERROR, "已保存单位的换算系数不能直接修改;切换基础单位时请提交迁移比例"); return true;
} }
} }
return false;
} }
private boolean isZero(BigDecimal value) { private boolean isZero(BigDecimal value) {
@@ -589,10 +514,12 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
.stream() .stream()
.collect(Collectors.groupingBy(GaoProductSkuSpecValue::getSkuId, Collectors.mapping(GaoProductSkuSpecValue::getSpecValueId, Collectors.toList()))); .collect(Collectors.groupingBy(GaoProductSkuSpecValue::getSkuId, Collectors.mapping(GaoProductSkuSpecValue::getSpecValueId, Collectors.toList())));
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_PRODUCT_SKU, skuIdList); Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(Attachment.BizType.GAO_PRODUCT_SKU, skuIdList);
Set<String> referencedSkuIdSet = new HashSet<>(mapper.selectReferencedSkuIdList(skuIdList));
for (GaoProductSku sku : skuList) { for (GaoProductSku sku : skuList) {
sku.setUnitList(unitMap.getOrDefault(sku.getId(), List.of())); sku.setUnitList(unitMap.getOrDefault(sku.getId(), List.of()));
sku.setSpecValueIdList(specValueIdMap.getOrDefault(sku.getId(), List.of())); sku.setSpecValueIdList(specValueIdMap.getOrDefault(sku.getId(), List.of()));
sku.setAttachmentList(attachmentMap.getOrDefault(sku.getId(), List.of())); sku.setAttachmentList(attachmentMap.getOrDefault(sku.getId(), List.of()));
sku.setUnitEditable(!referencedSkuIdSet.contains(sku.getId()));
} }
} }
@@ -40,6 +40,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@@ -634,6 +635,9 @@ public class GaoProductStockServiceImplement implements GaoProductStockService {
GaoProductStockRecord record = recordMap.get(item.getSkuId()); GaoProductStockRecord record = recordMap.get(item.getSkuId());
TimiException.required(record, "requestNo 对应库存操作内容不一致"); TimiException.required(record, "requestNo 对应库存操作内容不一致");
TimiException.requiredTrue(item.getBaseQuantity().compareTo(record.getBaseQuantity()) == 0, "requestNo 对应库存操作内容不一致"); TimiException.requiredTrue(item.getBaseQuantity().compareTo(record.getBaseQuantity()) == 0, "requestNo 对应库存操作内容不一致");
if (operationType == GaoProductStockRecord.OperationType.ORDER_REVOKE) {
TimiException.requiredTrue(Objects.equals(item.getSourceRecordId(), record.getSourceRecordId()), "requestNo 对应冲正来源不一致");
}
} }
} }
@@ -5,17 +5,18 @@ 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.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.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.entity.GaoFundRecord; import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment; import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.entity.GaoProduct; import com.imyeyu.api.modules.gao.entity.GaoProduct;
import com.imyeyu.api.modules.gao.entity.GaoProductSku; import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit; import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder; import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem; import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem;
import com.imyeyu.api.modules.gao.entity.GaoStore; import com.imyeyu.api.modules.gao.entity.GaoStore;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeWriteMapper;
import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderItemMapper; import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderItemMapper;
import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderMapper; import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerService; import com.imyeyu.api.modules.gao.service.GaoCustomerService;
@@ -25,22 +26,21 @@ import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService; import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService;
import com.imyeyu.api.modules.gao.service.GaoOrderStraightThroughService; import com.imyeyu.api.modules.gao.service.GaoOrderStraightThroughService;
import com.imyeyu.api.modules.gao.service.GaoPointTriggerService; import com.imyeyu.api.modules.gao.service.GaoPointTriggerService;
import com.imyeyu.api.modules.gao.service.GaoProductService;
import com.imyeyu.api.modules.gao.service.GaoProductSkuService; import com.imyeyu.api.modules.gao.service.GaoProductSkuService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService; import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.service.GaoStoreService; import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductCustomerRow; import com.imyeyu.api.modules.gao.vo.GaoCustomerProductCustomerRow;
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductCustomerView; import com.imyeyu.api.modules.gao.vo.GaoCustomerProductCustomerView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductPage; import com.imyeyu.api.modules.gao.vo.GaoCustomerProductPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductSummaryView; import com.imyeyu.api.modules.gao.vo.GaoCustomerProductSummaryView;
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductView; import com.imyeyu.api.modules.gao.vo.GaoCustomerProductView;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest; import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentReturnRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentReturnRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderPaymentRefundRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderPaymentRefundRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderPaymentRevokeRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderPaymentRevokeRequest;
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
import com.imyeyu.api.modules.gao.vo.GaoProductSkuUnitSelection; import com.imyeyu.api.modules.gao.vo.GaoProductSkuUnitSelection;
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderCancelRequest; import com.imyeyu.api.modules.gao.vo.GaoSalesOrderCancelRequest;
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderItemRequest; import com.imyeyu.api.modules.gao.vo.GaoSalesOrderItemRequest;
@@ -50,7 +50,6 @@ import com.imyeyu.api.modules.gao.vo.GaoSalesOrderUpdateRequest;
import com.imyeyu.api.modules.system.audit.AuditOperation; import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit; import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.user.service.PermissionChecker; import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiCode;
@@ -58,9 +57,9 @@ import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.bean.PageResult; 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 org.springframework.beans.factory.ObjectProvider;
import com.imyeyu.utils.Time; import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -87,17 +86,16 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
private static final BigDecimal ZERO = BigDecimal.ZERO; private static final BigDecimal ZERO = BigDecimal.ZERO;
// 过渡兼容:旧事件登记系统已收款,但新订单可能仍为零有效收款,暂时允许店长发起履约;过渡结束改为 false 并删除此分支
private static final boolean ALLOW_STORE_MANAGER_ZERO_PAYMENT_FULFILLMENT = true;
private final GaoSalesOrderMapper mapper; private final GaoSalesOrderMapper mapper;
private final GaoRecycleExchangeWriteMapper recycleExchangeMapper;
private final GaoSalesOrderItemMapper itemMapper; private final GaoSalesOrderItemMapper itemMapper;
private final GaoProductSkuUnitMapper skuUnitMapper;
private final GaoFundRecordService fundRecordService; private final GaoFundRecordService fundRecordService;
private final ObjectProvider<GaoOrderFulfillmentService> fulfillmentServiceProvider; private final ObjectProvider<GaoOrderFulfillmentService> fulfillmentServiceProvider;
private final ObjectProvider<GaoOrderPaymentService> paymentServiceProvider; private final ObjectProvider<GaoOrderPaymentService> paymentServiceProvider;
private final ObjectProvider<com.imyeyu.api.modules.gao.service.GaoRecyclePaymentService> recyclePaymentServiceProvider;
private final ObjectProvider<GaoOrderStraightThroughService> straightThroughServiceProvider; private final ObjectProvider<GaoOrderStraightThroughService> straightThroughServiceProvider;
private final GaoCustomerService customerService; private final GaoCustomerService customerService;
private final GaoProductService productService;
private final GaoProductSkuService skuService; private final GaoProductSkuService skuService;
private final GaoStoreService storeService; private final GaoStoreService storeService;
private final GaoStoreScopeService storeScopeService; private final GaoStoreScopeService storeScopeService;
@@ -105,7 +103,6 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
private final GaoPointTriggerService pointTriggerService; private final GaoPointTriggerService pointTriggerService;
private final AttachmentService attachmentService; private final AttachmentService attachmentService;
private final PermissionChecker permissionChecker; private final PermissionChecker permissionChecker;
private final RoleChecker roleChecker;
private final UserLoginService userLoginService; private final UserLoginService userLoginService;
@Override @Override
@@ -120,6 +117,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
result.setTotal(mapper.countByQuery(page)); result.setTotal(mapper.countByQuery(page));
List<GaoSalesOrder> list = mapper.selectByQuery(page); List<GaoSalesOrder> list = mapper.selectByQuery(page);
fillItemList(list); fillItemList(list);
fillFilteredSkuBaseUnit(list, page.getFulfillableSkuId());
fillCustomer(list); fillCustomer(list);
result.setList(list); result.setList(list);
return result; return result;
@@ -218,6 +216,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
order.setSourceEventRecord(eventRecordService.get(order.getSourceEventRecordId())); order.setSourceEventRecord(eventRecordService.get(order.getSourceEventRecordId()));
} }
order.setUnpaidAmount(safe(order.getSaleAmount()) - safe(order.getPaidAmount())); order.setUnpaidAmount(safe(order.getSaleAmount()) - safe(order.getPaidAmount()));
fillRecycleItem(order);
return order; return order;
} }
@@ -314,6 +313,33 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
data.getSaleAmount(), data.getItemList()); data.getSaleAmount(), data.getItemList());
} }
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public GaoSalesOrder createRecycleOrder(GaoPackageOrderCreateData data, String recycleItemId, BigDecimal requiredQuantity) {
TimiException.required(data, "订单数据不能为空");
String requestNo = requiredText(data.getRequestNo(), "请求号不能为空");
String storeId = requiredText(data.getStoreId(), "门店不能为空");
TimiException.required(recycleItemId, "回收物不能为空");
TimiException.requiredTrue(requiredQuantity != null && 0 < requiredQuantity.signum(), "回收物数量必须大于零");
storeScopeService.checkStoreId(storeId);
GaoSalesOrder existing = mapper.selectByRequestNo(storeId, requestNo);
if (existing != null) {
TimiException.requiredTrue(existing.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && data.getCustomerId().equals(existing.getCustomerId()) && recycleItemId.equals(existing.getRecycleItemId()) && requiredQuantity.compareTo(existing.getRecycleRequiredQuantity()) == 0, "请求号对应订单内容不一致");
List<GaoSalesOrderItem> saved = itemMapper.selectBySalesOrderId(existing.getId());
TimiException.requiredTrue(data.getItemList() != null && saved.size() == data.getItemList().size(), "请求号对应订单明细不一致");
for (GaoSalesOrderItem requested : data.getItemList()) {
TimiException.requiredTrue(saved.stream().anyMatch(item -> item.getItemType() == GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT && java.util.Objects.equals(item.getSkuId(), requested.getSkuId()) && java.util.Objects.equals(item.getSkuUnitId(), requested.getSkuUnitId()) && item.getQuantity().compareTo(requested.getQuantity()) == 0), "请求号对应订单明细不一致");
}
return detail(existing.getId());
}
GaoCustomer customer = customerService.get(data.getCustomerId());
TimiException.required(customer, "客户不存在");
TimiException.requiredTrue(storeId.equals(customer.getStoreId()), "客户不属于当前门店");
return createOrder(storeId, customer.getId(), GaoSalesOrder.OrderType.RECYCLE, requestNo,
TimiJava.defaultIfNull(data.getPurchasedAt(), Time.now()), data.getOperatorUserId(), data.getRemark(),
0, data.getItemList(), recycleItemId, requiredQuantity);
}
@OperationAudit(AuditOperation.GAO_SALES_ORDER_CANCEL) @OperationAudit(AuditOperation.GAO_SALES_ORDER_CANCEL)
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
@@ -445,10 +471,15 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
String childCancelReason = "随订单取消:%s".formatted(reason); String childCancelReason = "随订单取消:%s".formatted(reason);
fulfillmentService.cancelPendingBySalesOrderId(order.getId(), childCancelReason); fulfillmentService.cancelPendingBySalesOrderId(order.getId(), childCancelReason);
paymentService.cancelPendingBySalesOrderId(order.getId(), childCancelReason); paymentService.cancelPendingBySalesOrderId(order.getId(), childCancelReason);
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE) {
recyclePaymentServiceProvider.getObject().cancelPendingByOrderId(order.getId(), childCancelReason);
}
order = getForUpdate(order.getId()); order = getForUpdate(order.getId());
String userId = userLoginService.getRequireLoginUserId(); String userId = userLoginService.getRequireLoginUserId();
GaoSalesOrder.RefundStatus refundStatus = safe(order.getPaidAmount()) == 0 ? GaoSalesOrder.RefundStatus.REFUNDED : GaoSalesOrder.RefundStatus.PENDING; GaoSalesOrder.RefundStatus refundStatus = order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE
? GaoSalesOrder.RefundStatus.NOT_REQUIRED
: safe(order.getPaidAmount()) == 0 ? GaoSalesOrder.RefundStatus.REFUNDED : GaoSalesOrder.RefundStatus.PENDING;
Long cancelledAt = Time.now(); Long cancelledAt = Time.now();
TimiException.requiredTrue(1 == mapper.cancelIf(order.getId(), order.getStatus(), GaoSalesOrder.Status.CANCELLED, TimiException.requiredTrue(1 == mapper.cancelIf(order.getId(), order.getStatus(), GaoSalesOrder.Status.CANCELLED,
cancelledAt, userId, reason, refundStatus), "订单状态已变化"); cancelledAt, userId, reason, refundStatus), "订单状态已变化");
@@ -464,7 +495,9 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
} }
order = getForUpdate(order.getId()); order = getForUpdate(order.getId());
// 订单取消立即失去有效消费资格,不等待退款完成 // 订单取消立即失去有效消费资格,不等待退款完成
if (order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE) {
pointTriggerService.revokeBySalesOrder(order, reason); pointTriggerService.revokeBySalesOrder(order, reason);
}
return order; return order;
} }
@@ -511,6 +544,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
@Override @Override
public void recomputePaymentStatus(GaoSalesOrder order) { public void recomputePaymentStatus(GaoSalesOrder order) {
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不能按资金金额计算支付状态");
long saleAmount = safeLong(order.getSaleAmount()); long saleAmount = safeLong(order.getSaleAmount());
long paidAmount = safeLong(order.getPaidAmount()); long paidAmount = safeLong(order.getPaidAmount());
long pendingAmount = safeLong(order.getPendingPaidAmount()); long pendingAmount = safeLong(order.getPendingPaidAmount());
@@ -526,11 +560,16 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
@Override @Override
public void checkFulfillmentPermission(GaoSalesOrder order) { public void checkFulfillmentPermission(GaoSalesOrder order) {
TimiException.required(order, "not found sales order"); TimiException.required(order, "not found sales order");
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE) {
if (recyclePaymentServiceProvider.getObject().isSettled(order) || permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_UNSETTLED.getValue())) {
return;
}
TimiException.requiredTrue(false, "回收物尚未结清,不能发起履约");
}
if (safe(order.getSaleAmount()) == 0 || safe(order.getPaidAmount()) == safe(order.getSaleAmount())) { if (safe(order.getSaleAmount()) == 0 || safe(order.getPaidAmount()) == safe(order.getSaleAmount())) {
return; return;
} }
if (ALLOW_STORE_MANAGER_ZERO_PAYMENT_FULFILLMENT) { if (permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_UNSETTLED.getValue())) {
roleChecker.checkAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name());
return; return;
} }
TimiException.requiredTrue(false, "订单未全额收款,不能发起履约"); TimiException.requiredTrue(false, "订单未全额收款,不能发起履约");
@@ -580,6 +619,24 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
mapper.updateStatus(order.getId(), status); mapper.updateStatus(order.getId(), status);
order.setStatus(status); order.setStatus(status);
} }
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE) {
recycleExchangeMapper.updateByOrderStatus(order.getId(), fulfilled ? "COMPLETED" : "PENDING", Time.now());
}
}
/// 填充回收物名称与单位,回收订单要在订单页展示应付回收物
///
/// @param order 销售订单
private void fillRecycleItem(GaoSalesOrder order) {
if (order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE || order.getRecycleItemId() == null) {
return;
}
GaoRecycleExchange exchange = recycleExchangeMapper.snapshotByOrderId(order.getId());
if (exchange != null) {
order.setRecycleExchangeId(exchange.getId());
order.setRecycleItemName(exchange.getRecycleNameSnapshot());
order.setRecycleUnit(exchange.getRecycleUnitSnapshot());
}
} }
@Override @Override
@@ -689,10 +746,19 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
private GaoSalesOrder createOrder(String storeId, String customerId, GaoSalesOrder.OrderType orderType, String requestNo, private GaoSalesOrder createOrder(String storeId, String customerId, GaoSalesOrder.OrderType orderType, String requestNo,
Long purchasedAt, String operatorUserId, String remark, long saleAmount, List<GaoSalesOrderItem> itemList) { Long purchasedAt, String operatorUserId, String remark, long saleAmount, List<GaoSalesOrderItem> itemList) {
return createOrder(storeId, customerId, orderType, requestNo, purchasedAt, operatorUserId, remark, saleAmount, itemList, null, null);
}
private GaoSalesOrder createOrder(String storeId, String customerId, GaoSalesOrder.OrderType orderType, String requestNo,
Long purchasedAt, String operatorUserId, String remark, long saleAmount, List<GaoSalesOrderItem> itemList,
String recycleItemId, BigDecimal recycleRequiredQuantity) {
TimiException.requiredTrue(itemList != null && !itemList.isEmpty(), "销售订单至少需要一个订单明细"); TimiException.requiredTrue(itemList != null && !itemList.isEmpty(), "销售订单至少需要一个订单明细");
TimiException.requiredTrue(0 <= saleAmount, "成交价不能为负数"); TimiException.requiredTrue(0 <= saleAmount, "成交价不能为负数");
GaoSalesOrderItem.ItemType expectedItemType = orderType == GaoSalesOrder.OrderType.PACKAGE GaoSalesOrderItem.ItemType expectedItemType = switch (orderType) {
? GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT : GaoSalesOrderItem.ItemType.DIRECT_PRODUCT; case PACKAGE -> GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT;
case DIRECT_PRODUCT -> GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
case RECYCLE -> GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT;
};
Set<String> skuUnitKeySet = new HashSet<>(); Set<String> skuUnitKeySet = new HashSet<>();
long lineAmountSum = 0L; long lineAmountSum = 0L;
for (GaoSalesOrderItem item : itemList) { for (GaoSalesOrderItem item : itemList) {
@@ -718,7 +784,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
"订单项履约数量不能为负数"); "订单项履约数量不能为负数");
TimiException.requiredTrue(item.getReservedBaseQuantity().add(item.getFulfilledBaseQuantity()).compareTo(item.getBaseQuantity()) <= 0, TimiException.requiredTrue(item.getReservedBaseQuantity().add(item.getFulfilledBaseQuantity()).compareTo(item.getBaseQuantity()) <= 0,
"订单项履约数量不能超过购买数量"); "订单项履约数量不能超过购买数量");
if (expectedItemType == GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT) { if (expectedItemType != GaoSalesOrderItem.ItemType.DIRECT_PRODUCT) {
TimiException.requiredNull(item.getUnitPrice(), "套餐订单项不能填写单价"); TimiException.requiredNull(item.getUnitPrice(), "套餐订单项不能填写单价");
TimiException.requiredNull(item.getLineAmount(), "套餐订单项不能填写行金额"); TimiException.requiredNull(item.getLineAmount(), "套餐订单项不能填写行金额");
} else { } else {
@@ -732,8 +798,10 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
TimiException.requiredTrue(lineAmountSum == saleAmount, "直接产品订单行金额合计必须等于成交价"); TimiException.requiredTrue(lineAmountSum == saleAmount, "直接产品订单行金额合计必须等于成交价");
} }
GaoSalesOrder order = newOrder(storeId, customerId, orderType, requestNo, purchasedAt, operatorUserId, remark); GaoSalesOrder order = newOrder(storeId, customerId, orderType, requestNo, purchasedAt, operatorUserId, remark);
order.setRecycleItemId(recycleItemId);
order.setRecycleRequiredQuantity(recycleRequiredQuantity);
order.setSaleAmount(saleAmount); order.setSaleAmount(saleAmount);
boolean paidAtCreate = saleAmount == 0; boolean paidAtCreate = saleAmount == 0 && orderType != GaoSalesOrder.OrderType.RECYCLE;
order.setPaymentStatus(paidAtCreate ? GaoSalesOrder.PaymentStatus.PAID : GaoSalesOrder.PaymentStatus.UNPAID); order.setPaymentStatus(paidAtCreate ? GaoSalesOrder.PaymentStatus.PAID : GaoSalesOrder.PaymentStatus.UNPAID);
if (paidAtCreate) { if (paidAtCreate) {
order.setPaidAt(Time.now()); order.setPaidAt(Time.now());
@@ -801,6 +869,27 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
fillItemAttachments(itemList); fillItemAttachments(itemList);
} }
/// 为筛选出的 SKU 填充基础单位,整页只查询一次
///
/// @param orderList 当前页订单
/// @param skuId 筛选的 SKU ID
private void fillFilteredSkuBaseUnit(List<GaoSalesOrder> orderList, String skuId) {
if (orderList == null || orderList.isEmpty() || skuId == null || skuId.isBlank()) {
return;
}
String baseUnitName = skuUnitMapper.selectBySkuId(skuId).stream()
.filter(unit -> Boolean.TRUE.equals(unit.getIsBase()))
.map(GaoProductSkuUnit::getName)
.findFirst().orElse(null);
for (GaoSalesOrder order : orderList) {
for (GaoSalesOrderItem item : order.getItemList()) {
if (skuId.equals(item.getSkuId())) {
item.setBaseUnitName(baseUnitName);
}
}
}
}
/// 填充订单项履约余额投影 /// 填充订单项履约余额投影
/// ///
/// @param item 订单项 /// @param item 订单项
@@ -200,6 +200,14 @@ public class GaoStoreServiceImplement extends AbstractEntityService<GaoStore, St
return mapper.selectAllByAutoClosedDay(); return mapper.selectAllByAutoClosedDay();
} }
/// 查询可用门店
///
/// @return 门店列表
@Override
public List<GaoStore> listActivated() {
return mapper.selectAllActivated();
}
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@OperationAudit(AuditOperation.GAO_STORE_SORT) @OperationAudit(AuditOperation.GAO_STORE_SORT)
@Override @Override
@@ -0,0 +1,217 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.common.service.SettingService;
import com.imyeyu.api.modules.gao.bean.GaoStoreSetting;
import com.imyeyu.api.modules.gao.entity.GaoUser;
import com.imyeyu.api.modules.gao.mapper.GaoUserMapper;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.service.GaoStoreSettingService;
import com.imyeyu.api.modules.gao.vo.GaoStoreBirthdayReminderSetting;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
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.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/// GAO 门店配置服务实现
///
/// @author Codex
/// @since 2026-11-15
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoStoreSettingServiceImplement implements GaoStoreSettingService {
/// 门店配置的业务类型
private static final String BIZ_TYPE = GaoStoreSetting.CUSTOMER_BIRTHDAY_REMINDER_ENABLED.getBizType();
private final SettingService settingService;
private final GaoStoreService storeService;
private final GaoUserMapper gaoUserMapper;
private final UserService userService;
/// 读取门店配置
///
/// @param storeId 门店 ID
/// @param codeList 配置代码列表
/// @return 配置代码与配置的映射
@Override
public Map<String, Setting> mapSetting(String storeId, Collection<String> codeList) {
TimiException.required(storeId, "未找到门店 ID");
Map<String, Setting> dbMap = new LinkedHashMap<>();
for (Setting dbSetting : settingService.listByBizId(BIZ_TYPE, storeId)) {
dbMap.put(dbSetting.getCode(), dbSetting);
}
Map<String, Setting> result = new LinkedHashMap<>(GaoStoreSetting.values().length);
for (GaoStoreSetting key : GaoStoreSetting.values()) {
if (TimiJava.isNotEmpty(codeList) && !codeList.contains(key.name())) {
continue;
}
Setting dbSetting = dbMap.get(key.name());
result.put(key.name(), dbSetting == null ? buildDefaultSetting(key) : dbSetting);
}
return result;
}
/// 保存门店配置
///
/// @param storeId 门店 ID
/// @param settingList 配置列表
@Override
@OperationAudit(AuditOperation.GAO_STORE_SETTING_UPDATE)
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void updateSetting(String storeId, List<Setting> settingList) {
TimiException.required(storeId, "未找到门店 ID");
TimiException.required(storeService.get(storeId), "未找到门店");
Map<String, Setting> mergedMap = new LinkedHashMap<>();
for (Setting dbSetting : settingService.listByBizId(BIZ_TYPE, storeId)) {
mergedMap.put(dbSetting.getCode(), dbSetting);
}
for (Setting request : TimiJava.safeIterable(settingList)) {
TimiException.required(request, "未找到配置项");
GaoStoreSetting key = requireKey(request.getCode());
Setting merged = mergedMap.get(key.name());
if (merged == null) {
merged = buildDefaultSetting(key);
mergedMap.put(key.name(), merged);
}
merged.setValue(request.getValue());
}
validateBirthdayReminder(storeId, mergedMap);
List<Setting> saveList = new ArrayList<>(mergedMap.values());
for (Setting item : saveList) {
GaoStoreSetting key = requireKey(item.getCode());
item.setBizType(BIZ_TYPE);
item.setBizId(storeId);
item.setCode(key.name());
item.setDescription(key.getDescription());
item.setValueType(key.getValueType());
// 门店配置固定私有,不接受前端控制
item.setIsPrivate(true);
}
settingService.updateByBizId(BIZ_TYPE, storeId, saveList);
}
/// 读取门店生日提醒配置
///
/// @param storeId 门店 ID
/// @return 生日提醒配置
@Override
public GaoStoreBirthdayReminderSetting getBirthdayReminderSetting(String storeId) {
GaoStoreBirthdayReminderSetting setting = new GaoStoreBirthdayReminderSetting();
setting.setStoreId(storeId);
if (TimiJava.isEmpty(storeId)) {
setting.setEnabled(false);
setting.setResponsibleUserValid(false);
return setting;
}
setting.setEnabled(readBoolean(storeId, GaoStoreSetting.CUSTOMER_BIRTHDAY_REMINDER_ENABLED));
String responsibleUserId = readString(storeId, GaoStoreSetting.CUSTOMER_BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID);
setting.setResponsibleUserId(responsibleUserId);
User responsibleUser = TimiJava.isEmpty(responsibleUserId) ? null : userService.get(responsibleUserId);
setting.setResponsibleUser(responsibleUser);
setting.setResponsibleUserValid(responsibleUser != null && isStoreEnabledUser(storeId, responsibleUserId));
return setting;
}
/// 校验生日提醒的配置组合
///
/// 启用时必须存在有效负责人,否则提醒会落到无效用户
///
/// @param storeId 门店 ID
/// @param settingMap 合并后的配置
private void validateBirthdayReminder(String storeId, Map<String, Setting> settingMap) {
Setting enabledSetting = settingMap.get(GaoStoreSetting.CUSTOMER_BIRTHDAY_REMINDER_ENABLED.name());
if (enabledSetting == null || !enabledSetting.isTrue()) {
return;
}
Setting responsibleSetting = settingMap.get(
GaoStoreSetting.CUSTOMER_BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID.name());
String responsibleUserId = responsibleSetting == null ? null : responsibleSetting.asString();
TimiException.required(responsibleUserId, "启用生日提醒时必须指定负责人");
TimiException.requiredTrue(isStoreEnabledUser(storeId, responsibleUserId),
"负责人不是当前门店启用中的 GAO 用户");
}
/// 按配置代码查找配置项
///
/// @param code 配置代码
/// @return 配置项
private GaoStoreSetting requireKey(String code) {
GaoStoreSetting key = Arrays.stream(GaoStoreSetting.values())
.filter(item -> item.name().equals(code))
.findFirst()
.orElse(null);
TimiException.required(key, "不支持的配置项 %s".formatted(code));
return key;
}
/// 构建带默认值的配置对象
///
/// @param key 配置项
/// @return 配置
private Setting buildDefaultSetting(GaoStoreSetting key) {
Setting setting = new Setting();
setting.setBizType(BIZ_TYPE);
setting.setCode(key.name());
setting.setDescription(key.getDescription());
setting.setValue(key.getDefaultValue());
setting.setValueType(key.getValueType());
setting.setIsPrivate(true);
return setting;
}
/// 读取布尔配置,缺少记录时使用默认值
///
/// @param storeId 门店 ID
/// @param key 配置项
/// @return 配置值
private boolean readBoolean(String storeId, GaoStoreSetting key) {
Setting dbSetting = settingService.getByCode(BIZ_TYPE, storeId, key.name());
if (dbSetting == null) {
return Boolean.parseBoolean(key.getDefaultValue());
}
return dbSetting.isTrue();
}
/// 读取字符串配置,缺少记录或空值时使用默认值
///
/// @param storeId 门店 ID
/// @param key 配置项
/// @return 配置值
private String readString(String storeId, GaoStoreSetting key) {
Setting dbSetting = settingService.getByCode(BIZ_TYPE, storeId, key.name());
String value = dbSetting == null ? null : dbSetting.asString();
return TimiJava.isEmpty(value) ? key.getDefaultValue() : value;
}
/// 判断用户是否为目标门店启用中的 GAO 用户
///
/// @param storeId 门店 ID
/// @param userId 用户 ID
/// @return true 为启用中的门店用户
private boolean isStoreEnabledUser(String storeId, String userId) {
if (TimiJava.isEmpty(userId)) {
return false;
}
GaoUser example = new GaoUser();
example.setStoreId(storeId);
example.setUserId(userId);
example.setEnabled(true);
return gaoUserMapper.selectByExample(example) != null;
}
}
@@ -0,0 +1,35 @@
package com.imyeyu.api.modules.gao.task;
import com.imyeyu.api.modules.gao.service.GaoCustomerBirthdayReminderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/// GAO 客户生日提醒定时任务
///
/// @author Codex
/// @since 2026-11-15
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoCustomerBirthdayReminderTask {
private static final String ZONE_ID = "Asia/Shanghai";
private final GaoCustomerBirthdayReminderService service;
/// 每天早上七点生成生日提醒
///
/// 为 7 天后过生日的客户提前创建记录,提醒时间取生日当天八点
/// 站内通知在生日当天八点发送,短信由生日当天八点开始的短信批次任务聚合
/// cron 可通过 gao.customer.birthday-reminder.cron 覆盖,便于开发环境验证
@Scheduled(cron = "${gao.customer.birthday-reminder.cron:0 0 7 * * ?}", zone = ZONE_ID)
public void generate() {
try {
service.generate();
} catch (Exception e) {
log.error("GAO 客户生日提醒生成失败", e);
}
}
}
@@ -0,0 +1,93 @@
package com.imyeyu.api.modules.gao.util;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.LunarYear;
import com.nlf.calendar.Solar;
import java.time.LocalDate;
/// 农历生日工具
///
/// 数据库只保存公历出生日期,农历客户的农历月日由公历反推
///
/// @author Codex
/// @since 2026-11-15
public final class LunarDate {
private LunarDate() {
}
/// 判断目标公历日期是否为客户生日
///
/// 公历客户按公历月日匹配,2 月 29 日在平年按 2 月 28 日提醒
/// 农历客户按农历月日匹配,闰月生日在当年没有该闰月时按普通月提醒,保证每年最多提醒一次
///
/// @param target 目标公历日期
/// @param birthdate 客户出生日期,公历
/// @param calendar 出生日期录入历法
/// @return true 为目标客户的生日
public static boolean isBirthday(LocalDate target, LocalDate birthdate, GaoCustomer.BirthdateCalendar calendar) {
if (target == null || birthdate == null) {
return false;
}
if (calendar == GaoCustomer.BirthdateCalendar.LUNAR) {
return isLunarBirthday(target, birthdate);
}
int monthValue = birthdate.getMonthValue();
int dayOfMonth = birthdate.getDayOfMonth();
if (monthValue == 2 && dayOfMonth == 29) {
return target.getMonthValue() == 2 && target.getDayOfMonth() == (target.isLeapYear() ? 29 : 28);
}
return target.getMonthValue() == monthValue && target.getDayOfMonth() == dayOfMonth;
}
/// 判断目标公历日期是否命中农历生日
///
/// @param target 目标公历日期
/// @param birthdate 客户出生日期
/// @return true 为农历生日
private static boolean isLunarBirthday(LocalDate target, LocalDate birthdate) {
Lunar birthLunar = toLunar(birthdate);
Lunar targetLunar = toLunar(target);
int birthMonth = Math.abs(birthLunar.getMonth());
if (birthMonth != Math.abs(targetLunar.getMonth()) || birthLunar.getDay() != targetLunar.getDay()) {
return false;
}
// 农历月为负数表示闰月
boolean birthLeap = 0 > birthLunar.getMonth();
boolean targetLeap = 0 > targetLunar.getMonth();
if (!birthLeap) {
// 普通月生日,闰月的同月同日不算生日
return !targetLeap;
}
// 闰月生日,当年存在该闰月时只认闰月,否则按普通月提醒
boolean hasLeapMonth = birthMonth == LunarYear.fromYear(target.getYear()).getLeapMonth();
return hasLeapMonth == targetLeap;
}
/// 公历转换为农历
///
/// @param date 公历日期
/// @return 农历
public static Lunar toLunar(LocalDate date) {
return Solar.fromYmd(date.getYear(), date.getMonthValue(), date.getDayOfMonth()).getLunar();
}
/// 格式化为农历月日
///
/// @param date 公历日期
/// @return 农历月日,如「冬月初八」「闰五月初一」
public static String formatLunarMonthDay(LocalDate date) {
Lunar lunar = toLunar(date);
return "%s月%s".formatted(lunar.getMonthInChinese(), lunar.getDayInChinese());
}
/// 判断公历日期所在年的农历是否闰月
///
/// @param date 公历日期
/// @return true 为闰月
public static boolean isLeapMonth(LocalDate date) {
return 0 > toLunar(date).getMonth();
}
}
@@ -14,6 +14,7 @@ public class GaoOrderFulfillmentItemRequest {
/// 来源销售订单明细 ID /// 来源销售订单明细 ID
private String sourceOrderItemId; private String sourceOrderItemId;
/// 本次实际履约 SKU 单位 ID /// 本次实际履约 SKU 单位 ID
private String skuUnitId; private String skuUnitId;
@@ -15,6 +15,12 @@ import java.util.List;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class GaoOrderFulfillmentPage extends BasePage { public class GaoOrderFulfillmentPage extends BasePage {
/// true 为允许查询订单履约,仅服务端设置
private Boolean orderAllowed;
/// true 为允许查询回收履约,仅服务端设置
private Boolean recycleAllowed;
/// 门店 ID /// 门店 ID
private String storeId; private String storeId;
@@ -0,0 +1,18 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
import lombok.Data;
/// 订单交易记录
@Data
public class GaoOrderTransactionView {
/// 交易来源
private String type;
/// 业务发生时间
private Long occurredAt;
/// 资金流水
private GaoFundRecord fundRecord;
/// 回收物支付
private GaoRecyclePayment recyclePayment;
}
@@ -26,6 +26,9 @@ public class GaoProductFulfillmentDailyStatView {
/// 套餐权益履约数量,基础单位 /// 套餐权益履约数量,基础单位
private BigDecimal packageBaseQuantity; private BigDecimal packageBaseQuantity;
/// 回收兑换履约数量,基础单位
private BigDecimal recycleBaseQuantity;
/// 履约基础单位数量 /// 履约基础单位数量
private BigDecimal baseQuantity; private BigDecimal baseQuantity;
} }
@@ -1,19 +0,0 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.math.BigDecimal;
/// SKU 基础单位迁移请求
@Data
public class GaoProductSkuBaseUnitMigrationRequest {
/// 新基础单位 ID;切换到本次新增单位时允许为空
private String targetUnitId;
/// 新基础单位名称;按 ID 定位失败时用于匹配本次提交的新单位
private String targetUnitName;
/// 1 个旧基础单位等于的新基础单位数量
private BigDecimal oldToNewBaseRatio;
}
@@ -38,6 +38,9 @@ public class GaoProductSkuFulfillmentDailyStatView {
/// 套餐权益履约数量,基础单位 /// 套餐权益履约数量,基础单位
private BigDecimal packageBaseQuantity; private BigDecimal packageBaseQuantity;
/// 回收兑换履约数量,基础单位
private BigDecimal recycleBaseQuantity;
/// 履约基础单位数量 /// 履约基础单位数量
private BigDecimal baseQuantity; private BigDecimal baseQuantity;
} }
@@ -4,6 +4,7 @@ import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import lombok.Data; import lombok.Data;
import java.util.List; import java.util.List;
import java.math.BigDecimal;
/// 快速履约来源订单 /// 快速履约来源订单
@Data @Data
@@ -18,6 +19,15 @@ public class GaoQuickFulfillmentSourceOrderView {
/// 订单类型 /// 订单类型
private GaoSalesOrder.OrderType orderType; private GaoSalesOrder.OrderType orderType;
/// 回收物名称
private String recycleItemName;
/// 回收物单位
private String recycleUnit;
/// 应回收数量
private BigDecimal recycleRequiredQuantity;
/// 已核销回收数量
private BigDecimal recycleVerifiedQuantity;
/// 收款状态 /// 收款状态
private GaoSalesOrder.PaymentStatus paymentStatus; private GaoSalesOrder.PaymentStatus paymentStatus;
@@ -15,6 +15,15 @@ public class GaoQuickFulfillmentSourceRow {
private String orderNo; private String orderNo;
/// 来源订单类型 /// 来源订单类型
private GaoSalesOrder.OrderType orderType; private GaoSalesOrder.OrderType orderType;
/// 回收物名称
private String recycleItemName;
/// 回收物单位
private String recycleUnit;
/// 应回收数量
private BigDecimal recycleRequiredQuantity;
/// 已核销回收数量
private BigDecimal recycleVerifiedQuantity;
/// 收款状态 /// 收款状态
private GaoSalesOrder.PaymentStatus paymentStatus; private GaoSalesOrder.PaymentStatus paymentStatus;
/// 套餐名称快照 /// 套餐名称快照
@@ -0,0 +1,15 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.math.BigDecimal;
/// 人工调整客户回收物额度
@Data
public class GaoRecycleAccountAdjustRequest {
private String storeId;
private String customerId;
private String recycleItemId;
private String requestNo;
private BigDecimal quantity;
private String reason;
}
@@ -0,0 +1,42 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.common.entity.Attachment;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/// 回收兑换状态操作请求
@Data
public class GaoRecycleExchangeActionRequest {
/// 门店 ID
private String storeId;
/// 兑换单 ID
private String exchangeId;
/// 请求幂等号
private String requestNo;
/// 业务发生时间
private Long occurredAt;
/// 操作原因
private String reason;
/// 备注
private String remark;
/// 撤销后门店实际保留的回收物数量,未填写时保留全部
private BigDecimal retainedRecycleQuantity;
/// 撤销时按整单冲正的履约列表
private List<GaoOrderFulfillmentRevokeRequest> fulfillmentRevokeList;
/// 取消时选择冲正的回收物支付
private List<GaoRecyclePaymentRequest> paymentRevokeList;
/// 附件列表
private List<Attachment> attachmentList;
}
@@ -0,0 +1,60 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.common.entity.Attachment;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/// 回收兑换创建请求
@Data
public class GaoRecycleExchangeCreateRequest {
/// 门店 ID
private String storeId;
/// 客户 ID
private String customerId;
/// 规则 ID
private String ruleId;
/// 回收物 ID,自由创建时使用
private String recycleItemId;
/// 兑换权益明细
private List<GaoRecycleExchangeItemRequest> itemList;
/// 请求幂等号
private String requestNo;
/// true 为创建时确认收到全部回收物并核销
private Boolean verifyPayment;
/// 本次创建时回收并核销的数量,零表示不核销
private BigDecimal paymentQuantity;
/// 回收凭证照片
private List<Attachment> paymentAttachmentList;
/// true 为全部产品立即履约并核销
private Boolean fulfillAll;
/// 履约凭证照片
private List<Attachment> fulfillmentAttachmentList;
/// 规则倍数
private Integer multiple;
/// 实际回收数量
private BigDecimal recycleQuantity;
/// 业务发生时间
private Long occurredAt;
/// 备注
private String remark;
/// 附件列表
private List<Attachment> attachmentList;
}
@@ -0,0 +1,26 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
import lombok.Data;
import java.util.List;
import java.util.Map;
/// 回收兑换详情
@Data
public class GaoRecycleExchangeDetail {
/// 兑换单,含权益明细
private GaoRecycleExchange exchange;
/// 操作记录
private List<GaoRecycleExchangeAction> actionList;
/// 附件列表
private List<Attachment> attachmentList;
/// 操作记录附件,按操作 ID 分组
private Map<String, List<Attachment>> actionAttachments;
}
@@ -0,0 +1,15 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.math.BigDecimal;
/// 兑换权益明细请求
@Data
public class GaoRecycleExchangeItemRequest {
/// SKU ID
private String skuId;
/// SKU 单位 ID
private String skuUnitId;
/// 兑换数量
private BigDecimal quantity;
}
@@ -0,0 +1,35 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
/// 回收兑换规则配置请求
@Data
public class GaoRecycleExchangeRuleRequest {
/// 兑换模板明细
private List<GaoRecycleExchangeRuleItem> itemList;
/// 规则 ID,创建时为空
private String id;
/// 门店 ID
private String storeId;
/// 回收物 ID
private String recycleItemId;
/// 单份回收数量
private BigDecimal recycleQuantity;
/// 状态
private GaoRecycleExchangeRule.Status status;
/// 排序
private Integer sort;
/// 备注
private String remark;
}
@@ -0,0 +1,30 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.math.BigDecimal;
/// 兑换业务数量统计
@Data
public class GaoRecycleExchangeStatView {
/// SKU ID
private String skuId;
/// 业务单位 ID
private String skuUnitId;
/// 产品名称快照
private String productName;
/// 业务单位快照
private String unit;
/// 创建数量
private BigDecimal createdQuantity;
/// 核销数量
private BigDecimal verifiedQuantity;
/// 冲正数量
private BigDecimal revokedQuantity;
}
@@ -0,0 +1,34 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
import com.imyeyu.api.modules.common.entity.Attachment;
import java.util.List;
import lombok.Data;
/// 回收物配置请求
@Data
public class GaoRecycleItemRequest {
/// 配置 ID,创建时为空
private String id;
/// 门店 ID
private String storeId;
/// 回收物名称
private String name;
/// 回收单位
private String unitName;
/// 是否允许小数数量
private Boolean allowDecimalQuantity;
/// 状态
private GaoRecycleItem.Status status;
/// 图片附件
private List<Attachment> attachmentList;
/// 备注
private String remark;
}
@@ -0,0 +1,19 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.common.entity.Attachment;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/// 回收物支付请求
@Data
public class GaoRecyclePaymentRequest {
private String orderId;
private String paymentId;
private String requestNo;
private BigDecimal quantity;
private Long occurredAt;
private String reason;
private Boolean returnedToCustomer;
private List<Attachment> attachmentList;
}
@@ -0,0 +1,27 @@
package com.imyeyu.api.modules.gao.vo;
import lombok.Data;
import java.math.BigDecimal;
/// 回收物按业务时间统计
@Data
public class GaoRecycleStatView {
/// 回收物 ID
private String recycleItemId;
/// 回收物名称快照
private String recycleName;
/// 回收物单位快照
private String recycleUnit;
/// 收到数量
private BigDecimal receivedQuantity;
/// 退回数量
private BigDecimal returnedQuantity;
/// 净回收数量
private BigDecimal netQuantity;
}
@@ -15,6 +15,12 @@ import java.util.List;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class GaoSalesOrderPage extends BasePage { public class GaoSalesOrderPage extends BasePage {
/// true 为允许查询普通订单
private Boolean orderAllowed;
/// true 为允许查询回收兑换订单
private Boolean recycleAllowed;
/// 门店 ID /// 门店 ID
private String storeId; private String storeId;
@@ -24,6 +30,9 @@ public class GaoSalesOrderPage extends BasePage {
/// 套餐配置 ID /// 套餐配置 ID
private String packageConfigId; private String packageConfigId;
/// 筛选存在可履约明细的 SKU ID
private String fulfillableSkuId;
/// 订单类型 /// 订单类型
private GaoSalesOrder.OrderType orderType; private GaoSalesOrder.OrderType orderType;
@@ -0,0 +1,27 @@
package com.imyeyu.api.modules.gao.vo;
import com.imyeyu.api.modules.user.entity.User;
import lombok.Data;
/// GAO 门店客户生日提醒配置
///
/// @author Codex
/// @since 2026-11-15
@Data
public class GaoStoreBirthdayReminderSetting {
/// 门店 ID
private String storeId;
/// true 为启用客户生日提醒
private Boolean enabled;
/// 负责人用户 ID
private String responsibleUserId;
/// 负责人用户
private User responsibleUser;
/// true 为负责人仍是当前门店启用中的 GAO 用户
private Boolean responsibleUserValid;
}
@@ -74,6 +74,7 @@ public enum AuditOperation {
GAO_STORE_UPDATE(Logger.Module.GAO), GAO_STORE_UPDATE(Logger.Module.GAO),
GAO_STORE_DELETE(Logger.Module.GAO), GAO_STORE_DELETE(Logger.Module.GAO),
GAO_STORE_SORT(Logger.Module.GAO), GAO_STORE_SORT(Logger.Module.GAO),
GAO_STORE_SETTING_UPDATE(Logger.Module.GAO),
GAO_CUSTOMER_FOLLOW_UP_REMINDER_CREATE(Logger.Module.GAO), GAO_CUSTOMER_FOLLOW_UP_REMINDER_CREATE(Logger.Module.GAO),
GAO_CUSTOMER_FOLLOW_UP_REMINDER_UPDATE(Logger.Module.GAO), GAO_CUSTOMER_FOLLOW_UP_REMINDER_UPDATE(Logger.Module.GAO),
GAO_CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE(Logger.Module.GAO), GAO_CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE(Logger.Module.GAO),
@@ -85,6 +86,10 @@ public enum AuditOperation {
GAO_POINT_RULE_UPDATE(Logger.Module.GAO), GAO_POINT_RULE_UPDATE(Logger.Module.GAO),
GAO_POINT_RULE_SORT(Logger.Module.GAO), GAO_POINT_RULE_SORT(Logger.Module.GAO),
GAO_POINT_RULE_DELETE(Logger.Module.GAO), GAO_POINT_RULE_DELETE(Logger.Module.GAO),
GAO_RECYCLE_ITEM_SAVE(Logger.Module.GAO),
GAO_RECYCLE_RULE_SAVE(Logger.Module.GAO),
GAO_RECYCLE_EXCHANGE_CREATE(Logger.Module.GAO),
GAO_RECYCLE_EXCHANGE_ACTION(Logger.Module.GAO),
GAO_POINT_REDEEM_SKU_CREATE(Logger.Module.GAO), GAO_POINT_REDEEM_SKU_CREATE(Logger.Module.GAO),
GAO_POINT_REDEEM_SKU_UPDATE(Logger.Module.GAO), GAO_POINT_REDEEM_SKU_UPDATE(Logger.Module.GAO),
GAO_POINT_REDEEM_SKU_DISABLE(Logger.Module.GAO), GAO_POINT_REDEEM_SKU_DISABLE(Logger.Module.GAO),
@@ -41,6 +41,10 @@ public class InitBuiltinSetting implements ApplicationRunner {
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
public void run(ApplicationArguments args) throws Exception { public void run(ApplicationArguments args) throws Exception {
for (SettingEnum item : findSettingEnumList()) { for (SettingEnum item : findSettingEnumList()) {
if (item.getScope() != Setting.Scope.SYSTEM) {
// 业务级配置由业务对象自己维护,启动时不初始化
continue;
}
if (settingService.getSystem(item) == null) { if (settingService.getSystem(item) == null) {
Setting setting = new Setting(); Setting setting = new Setting();
setting.setBizType(item.getBizType()); setting.setBizType(item.getBizType());
@@ -0,0 +1,102 @@
CREATE TABLE `gao_recycle_item` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`name` VARCHAR(128) NOT NULL,
`unit_name` VARCHAR(32) NOT NULL,
`product_id` VARCHAR(36) NULL,
`sku_id` VARCHAR(36) NULL,
`status` VARCHAR(32) NOT NULL,
`remark` TEXT NULL,
`created_at` BIGINT NOT NULL,
`updated_at` BIGINT NULL,
PRIMARY KEY (`id`),
KEY (`store_id`, `status`, `created_at`)
) COMMENT='GAO 回收兑换数据';
CREATE TABLE `gao_recycle_exchange_rule` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`recycle_item_id` VARCHAR(36) NOT NULL,
`recycle_quantity` DECIMAL(18,3) NOT NULL,
`sku_id` VARCHAR(36) NOT NULL,
`sku_unit_id` VARCHAR(36) NOT NULL,
`exchange_quantity` DECIMAL(18,3) NOT NULL,
`status` VARCHAR(32) NOT NULL,
`sort` INT NOT NULL,
`remark` TEXT NULL,
`created_at` BIGINT NOT NULL,
`updated_at` BIGINT NULL,
PRIMARY KEY (`id`),
KEY (`store_id`, `status`, `recycle_item_id`, `sort`),
KEY (`store_id`, `sku_id`, `sku_unit_id`)
) COMMENT='GAO 回收兑换数据';
CREATE TABLE `gao_recycle_exchange` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`customer_id` VARCHAR(36) NOT NULL,
`request_no` VARCHAR(128) NOT NULL,
`request_fingerprint` VARCHAR(64) NOT NULL,
`rule_id` VARCHAR(36) NOT NULL,
`recycle_item_id` VARCHAR(36) NOT NULL,
`recycle_name_snapshot` VARCHAR(128) NOT NULL,
`recycle_unit_snapshot` VARCHAR(32) NOT NULL,
`source_product_id_snapshot` VARCHAR(36) NULL,
`source_sku_id_snapshot` VARCHAR(36) NULL,
`rule_recycle_quantity` DECIMAL(18,3) NOT NULL,
`rule_exchange_quantity` DECIMAL(18,3) NOT NULL,
`multiple` INT NOT NULL,
`default_recycle_quantity` DECIMAL(18,3) NOT NULL,
`default_exchange_quantity` DECIMAL(18,3) NOT NULL,
`recycle_quantity` DECIMAL(18,3) NOT NULL,
`exchange_quantity` DECIMAL(18,3) NOT NULL,
`product_id_snapshot` VARCHAR(36) NOT NULL,
`sku_id_snapshot` VARCHAR(36) NOT NULL,
`sku_unit_id_snapshot` VARCHAR(36) NOT NULL,
`product_name_snapshot` VARCHAR(128) NOT NULL,
`product_type_snapshot` VARCHAR(32) NOT NULL,
`sku_code_snapshot` VARCHAR(128) NULL,
`sku_name_snapshot` VARCHAR(128) NULL,
`spec_summary_snapshot` VARCHAR(512) NULL,
`unit_snapshot` VARCHAR(32) NOT NULL,
`sku_spec_snapshot` JSON NULL,
`base_quantity_per_unit_snapshot` DECIMAL(18,6) NOT NULL,
`base_quantity` DECIMAL(18,3) NOT NULL,
`allow_decimal_snapshot` TINYINT(1) NOT NULL,
`stock_enabled_snapshot` TINYINT(1) NOT NULL,
`status` VARCHAR(32) NOT NULL,
`operator_user_id` VARCHAR(36) NOT NULL,
`occurred_at` BIGINT NOT NULL,
`remark` TEXT NULL,
`created_at` BIGINT NOT NULL,
`updated_at` BIGINT NULL,
`deleted_at` BIGINT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`store_id`, `request_no`),
KEY (`store_id`, `customer_id`, `status`, `occurred_at`),
KEY (`store_id`, `status`, `created_at`),
KEY (`store_id`, `recycle_item_id`, `occurred_at`),
KEY (`store_id`, `sku_id_snapshot`, `occurred_at`)
) COMMENT='GAO 回收兑换数据';
CREATE TABLE `gao_recycle_exchange_action` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`exchange_id` VARCHAR(36) NOT NULL,
`request_no` VARCHAR(128) NOT NULL,
`request_fingerprint` VARCHAR(64) NOT NULL,
`action_type` VARCHAR(32) NOT NULL,
`operator_user_id` VARCHAR(36) NOT NULL,
`occurred_at` BIGINT NOT NULL,
`reason` TEXT NULL,
`remark` TEXT NULL,
`recycle_returned` TINYINT(1) NULL,
`stock_returned` TINYINT(1) NULL,
`stock_record_id` VARCHAR(36) NULL,
`source_stock_record_id` VARCHAR(36) NULL,
`created_at` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`store_id`, `request_no`),
UNIQUE KEY (`exchange_id`, `action_type`),
KEY (`exchange_id`, `created_at`)
) COMMENT='GAO 回收兑换数据';
@@ -0,0 +1,188 @@
-- 回收业务重构:客户额度账户 + 回收物支付 + 兑换单生成销售订单
--
-- V87 已在生产执行、回收功能未启用且没有有效数据,本脚本把 V87 的回收模型替换成额度账户模型:
-- 商品明细并入生成的销售订单,回收物改为按客户维护的额度账户,支付独立核销。
--
-- 未发版的 V89/V91/V92/V93 已并入本脚本:回收物单头去掉来源产品列并补小数数量开关,
-- 兑换单去掉来源产品快照,rule_recycle_quantity 保留不删
--
-- rule_recycle_quantity 与 rule_snapshot 中的 recycleQuantity 故意冗余:
-- 兑换单详情页读的是列而不是快照,删除会导致来源行取值为空
-- 回收物单头:不再关联来源产品,产出关系改由 gao_recycle_product_yield 按 SKU 描述
-- 同一回收物可由多个 SKU 产生,单头再挂产品既不足以表达也会误导配置人员
-- allow_decimal_quantity 由回收物自己决定是否允许小数数量
ALTER TABLE `gao_recycle_item`
DROP COLUMN `product_id`,
DROP COLUMN `sku_id`,
ADD COLUMN `allow_decimal_quantity` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许小数数量';
-- 模板明细:一份模板可兑换多条 SKU
CREATE TABLE `gao_recycle_exchange_rule_item` (
`id` VARCHAR(36) NOT NULL,
`rule_id` VARCHAR(36) NOT NULL,
`sku_id` VARCHAR(36) NOT NULL,
`sku_unit_id` VARCHAR(36) NOT NULL,
`exchange_quantity` DECIMAL(18,3) NOT NULL COMMENT '单份模板兑换的业务单位数量',
`sort` INT NOT NULL,
`created_at` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_recycle_rule_sku_unit` (`rule_id`, `sku_id`, `sku_unit_id`)
) COMMENT='GAO 回收兑换模板明细';
-- store_id_2 是 (store_id, sku_id, sku_unit_id) 的自动命名(已在生产库 information_schema 确认)
-- DROP INDEX IF EXISTS 保证索引名不一致时不会中断迁移,列删掉后索引本身也会自动收缩
ALTER TABLE `gao_recycle_exchange_rule` DROP INDEX IF EXISTS `store_id_2`;
ALTER TABLE `gao_recycle_exchange_rule`
DROP COLUMN `sku_id`,
DROP COLUMN `sku_unit_id`,
DROP COLUMN `exchange_quantity`;
-- 兑换单:商品明细下沉到销售订单,这里只留回收物与支付条件
-- store_id_5 是 (store_id, sku_id_snapshot, occurred_at) 的自动命名(已在生产库 information_schema 确认)
ALTER TABLE `gao_recycle_exchange` DROP INDEX IF EXISTS `store_id_5`;
ALTER TABLE `gao_recycle_exchange`
DROP COLUMN `source_product_id_snapshot`,
DROP COLUMN `source_sku_id_snapshot`,
DROP COLUMN `rule_exchange_quantity`,
DROP COLUMN `default_exchange_quantity`,
DROP COLUMN `exchange_quantity`,
DROP COLUMN `product_id_snapshot`,
DROP COLUMN `sku_id_snapshot`,
DROP COLUMN `sku_unit_id_snapshot`,
DROP COLUMN `product_name_snapshot`,
DROP COLUMN `product_type_snapshot`,
DROP COLUMN `sku_code_snapshot`,
DROP COLUMN `sku_name_snapshot`,
DROP COLUMN `spec_summary_snapshot`,
DROP COLUMN `unit_snapshot`,
DROP COLUMN `sku_spec_snapshot`,
DROP COLUMN `base_quantity_per_unit_snapshot`,
DROP COLUMN `base_quantity`,
DROP COLUMN `allow_decimal_snapshot`,
DROP COLUMN `stock_enabled_snapshot`,
MODIFY COLUMN `rule_id` VARCHAR(36) NULL COMMENT '模板 ID,自由创建时为空',
MODIFY COLUMN `rule_recycle_quantity` DECIMAL(18,3) NULL COMMENT '模板单份回收数量',
MODIFY COLUMN `multiple` INT NULL COMMENT '模板份数,自由创建时为空',
MODIFY COLUMN `default_recycle_quantity` DECIMAL(18,3) NULL COMMENT '模板预设回收数量',
MODIFY COLUMN `recycle_quantity` DECIMAL(18,3) NOT NULL COMMENT '约定支付回收物数量',
MODIFY COLUMN `status` VARCHAR(32) NOT NULL COMMENT 'PENDING 待领取,COMPLETED 已完成,CANCELLED 已取消',
ADD COLUMN `sales_order_id` VARCHAR(36) NULL COMMENT '生成的销售订单 ID' AFTER `rule_id`,
ADD COLUMN `rule_snapshot` JSON NULL COMMENT '创建时模板快照,自由创建时为空' AFTER `sales_order_id`,
ADD UNIQUE KEY `uk_recycle_exchange_order` (`sales_order_id`);
-- 兑换订单:记录约定支付的回收物与数量,订单本身仍是标准销售订单
ALTER TABLE `gao_sales_order`
ADD COLUMN `recycle_item_id` VARCHAR(36) NULL COMMENT '回收物 ID,仅回收兑换订单' AFTER `sale_amount`,
ADD COLUMN `recycle_required_quantity` DECIMAL(18,3) NULL COMMENT '约定支付回收物数量,仅回收兑换订单',
ADD KEY `idx_gao_sales_order_recycle` (`store_id`, `recycle_item_id`);
-- 操作记录:兑换单只剩取消
ALTER TABLE `gao_recycle_exchange_action`
DROP COLUMN `recycle_returned`,
DROP COLUMN `stock_returned`,
DROP COLUMN `stock_record_id`,
DROP COLUMN `source_stock_record_id`,
MODIFY COLUMN `action_type` VARCHAR(32) NOT NULL COMMENT 'CANCEL',
ADD COLUMN `retained_recycle_quantity` DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '取消后门店保留的回收物数量';
-- 产品回收产物:每个 SKU 基础单位产生多少回收物
CREATE TABLE `gao_recycle_product_yield` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`sku_id` VARCHAR(36) NOT NULL,
`recycle_item_id` VARCHAR(36) NOT NULL,
`quantity_per_base` DECIMAL(18,6) NOT NULL COMMENT '每个 SKU 基础单位产生的回收物数量',
`created_at` BIGINT NOT NULL,
`updated_at` BIGINT NULL,
`deleted_at` BIGINT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_recycle_yield_sku_item` (`store_id`, `sku_id`, `recycle_item_id`),
KEY `idx_recycle_yield_sku` (`store_id`, `sku_id`, `deleted_at`)
) COMMENT='GAO 产品回收物产出配置';
-- 客户额度账户:按门店、客户、回收物类型隔离
CREATE TABLE `gao_recycle_account` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`customer_id` VARCHAR(36) NOT NULL,
`recycle_item_id` VARCHAR(36) NOT NULL,
`balance` DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '额度余额',
`reserved` DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '支付预占',
`created_at` BIGINT NOT NULL,
`updated_at` BIGINT NULL,
`deleted_at` BIGINT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_recycle_account` (`store_id`, `customer_id`, `recycle_item_id`)
) COMMENT='GAO 客户回收物额度账户';
-- 额度流水:不可变,记录前后值与来源
CREATE TABLE `gao_recycle_ledger` (
`id` VARCHAR(36) NOT NULL,
`account_id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`customer_id` VARCHAR(36) NOT NULL,
`recycle_item_id` VARCHAR(36) NOT NULL,
`biz_type` VARCHAR(32) NOT NULL COMMENT 'FULFILLMENT_YIELD 履约产生,ADJUST 人工调整,PAYMENT_RESERVE 支付预占,PAYMENT_RELEASE 释放预占,PAYMENT_VERIFY 支付核销,PAYMENT_REVOKE 冲正返还',
`biz_id` VARCHAR(36) NULL COMMENT '来源业务 ID',
`request_no` VARCHAR(128) NOT NULL,
`balance_delta` DECIMAL(18,3) NOT NULL DEFAULT 0,
`reserved_delta` DECIMAL(18,3) NOT NULL DEFAULT 0,
`balance_after` DECIMAL(18,3) NOT NULL,
`reserved_after` DECIMAL(18,3) NOT NULL,
`operator_user_id` VARCHAR(36) NULL,
`reason` TEXT NULL,
`created_at` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_recycle_ledger_request` (`store_id`, `request_no`),
KEY `idx_recycle_ledger_customer` (`store_id`, `customer_id`, `created_at`),
KEY `idx_recycle_ledger_biz` (`biz_type`, `biz_id`)
) COMMENT='GAO 回收物额度流水';
-- 回收物支付:一笔订单可分批提交
CREATE TABLE `gao_recycle_payment` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`customer_id` VARCHAR(36) NOT NULL,
`order_id` VARCHAR(36) NOT NULL COMMENT '兑换生成的销售订单 ID',
`recycle_item_id` VARCHAR(36) NOT NULL,
`request_no` VARCHAR(128) NOT NULL,
`request_fingerprint` VARCHAR(64) NOT NULL,
`quantity` DECIMAL(18,3) NOT NULL,
`status` VARCHAR(32) NOT NULL COMMENT 'PENDING 待核销,VERIFIED 已核销,REJECTED 已拒绝,CANCELLED 已撤销,REVOKED 已冲正',
`source_payment_id` VARCHAR(36) NULL COMMENT '冲正指向的原支付',
`operator_user_id` VARCHAR(36) NOT NULL,
`verifier_user_id` VARCHAR(36) NULL,
`occurred_at` BIGINT NOT NULL,
`verified_at` BIGINT NULL,
`reason` TEXT NULL,
`returned_to_customer` TINYINT(1) NULL COMMENT '冲正时实物是否已退还客户',
`created_at` BIGINT NOT NULL,
`updated_at` BIGINT NULL,
`deleted_at` BIGINT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_recycle_payment_request` (`store_id`, `request_no`),
KEY `idx_recycle_payment_order` (`order_id`, `created_at`),
KEY `idx_recycle_payment_source` (`source_payment_id`)
) COMMENT='GAO 回收物支付记录';
-- 回收实物流转:收取与退还分方向记录
CREATE TABLE `gao_recycle_physical_record` (
`id` VARCHAR(36) NOT NULL,
`store_id` VARCHAR(36) NOT NULL,
`customer_id` VARCHAR(36) NOT NULL,
`order_id` VARCHAR(36) NOT NULL,
`recycle_item_id` VARCHAR(36) NOT NULL,
`payment_id` VARCHAR(36) NULL COMMENT '关联支付,取消退还时用于去重',
`source_type` VARCHAR(32) NOT NULL COMMENT 'PAYMENT_VERIFY 支付核销收取,PAYMENT_REVOKE 支付冲正退还,EXCHANGE_CANCEL 取消退还',
`source_id` VARCHAR(36) NOT NULL,
`direction` VARCHAR(8) NOT NULL COMMENT 'IN 门店收到,OUT 退还客户',
`quantity` DECIMAL(18,3) NOT NULL,
`occurred_at` BIGINT NOT NULL,
`created_at` BIGINT NOT NULL,
PRIMARY KEY (`id`),
-- 同一来源只允许一条记录,防止重放或并发重复登记实物
UNIQUE KEY `uk_recycle_physical_source` (`source_type`, `source_id`, `payment_id`),
KEY `idx_recycle_physical_order` (`order_id`, `direction`),
KEY `idx_recycle_physical_payment` (`payment_id`)
) COMMENT='GAO 回收实物流转记录';
@@ -0,0 +1,104 @@
-- 将旧回收业务授权迁移至统一的订单、履约和支付权限
CREATE TEMPORARY TABLE `gao_permission_mapping` (
`old_code` VARCHAR(50) NOT NULL,
`new_code` VARCHAR(50) NOT NULL,
PRIMARY KEY (`old_code`, `new_code`)
);
INSERT INTO `gao_permission_mapping` (`old_code`, `new_code`) VALUES
('RECYCLE_EXCHANGE:QUERY', 'SALES_ORDER:READ'),
('RECYCLE_EXCHANGE:QUERY', 'ORDER_FULFILLMENT:READ'),
('RECYCLE_EXCHANGE:CREATE', 'SALES_ORDER:CREATE'),
('RECYCLE_EXCHANGE:CREATE', 'ORDER_FULFILLMENT:CREATE'),
('RECYCLE_EXCHANGE:CANCEL', 'SALES_ORDER:CANCEL'),
('RECYCLE_EXCHANGE:QUANTITY_ADJUST', 'SALES_ORDER:PRICE_OVERRIDE'),
('RECYCLE_EXCHANGE:VERIFY', 'ORDER_FULFILLMENT:VERIFY'),
('RECYCLE_EXCHANGE:REVOKE', 'ORDER_FULFILLMENT:REVOKE'),
('RECYCLE_PAYMENT:READ', 'FUND_RECORD:READ'),
('RECYCLE_PAYMENT:CREATE', 'FUND_RECEIVE:CREATE'),
('RECYCLE_PAYMENT:VERIFY', 'FUND_RECEIVE:VERIFY'),
('RECYCLE_PAYMENT:REVOKE', 'FUND:REVOKE');
-- 目标内建权限通常已经存在;旧库缺失时先创建,启动后由内建权限初始化补齐名称
INSERT INTO `permission` (`id`, `module_code`, `code`, `builtin`, `protected_permission`, `owner_type`, `created_at`)
SELECT UUID(), 'GAO', mapping.`new_code`, TRUE, TRUE, 'MODULE', UNIX_TIMESTAMP() * 1000
FROM (SELECT DISTINCT `new_code` FROM `gao_permission_mapping`) mapping
WHERE NOT EXISTS (
SELECT 1 FROM `permission` target WHERE target.`module_code` = 'GAO' AND target.`code` = mapping.`new_code`
);
-- 使用新的多语言记录,避免覆盖被其他数据共享的名称及旧缓存
CREATE TEMPORARY TABLE `gao_permission_names` (
`code` VARCHAR(50) NOT NULL PRIMARY KEY,
`name` VARCHAR(50) NOT NULL,
`lang_id` VARCHAR(36) NOT NULL
);
INSERT INTO `gao_permission_names` (`code`, `name`, `lang_id`) VALUES
('SALES_ORDER:READ', '销售订单读取', UUID()),
('SALES_ORDER:CREATE', '销售订单创建', UUID()),
('SALES_ORDER:CANCEL', '销售订单取消', UUID()),
('ORDER_FULFILLMENT:READ', '统一履约读取', UUID()),
('ORDER_FULFILLMENT:CREATE', '统一履约创建', UUID()),
('ORDER_FULFILLMENT:VERIFY', '统一履约核销', UUID()),
('ORDER_FULFILLMENT:REVOKE', '统一履约冲正', UUID()),
('SALES_ORDER:PRICE_OVERRIDE', '订单交易条件调整', UUID()),
('ORDER_FULFILLMENT:UNSETTLED', '订单未结清履约', UUID()),
('FUND_RECORD:READ', '支付记录读取', UUID()),
('FUND_RECEIVE:CREATE', '支付登记', UUID()),
('FUND_RECEIVE:VERIFY', '支付核销', UUID()),
('FUND:REVOKE', '支付冲正', UUID());
INSERT INTO `multilingual` (`id`, `zh_cn`, `created_at`)
SELECT names.`lang_id`, names.`name`, UNIX_TIMESTAMP() * 1000
FROM `gao_permission_names` names
JOIN `permission` permission ON permission.`module_code` = 'GAO' AND permission.`code` = names.`code` AND permission.`deleted_at` IS NULL;
UPDATE `permission` permission
JOIN `gao_permission_names` names ON names.`code` = permission.`code`
SET permission.`name_lang_id` = names.`lang_id`
WHERE permission.`module_code` = 'GAO' AND permission.`deleted_at` IS NULL;
DROP TEMPORARY TABLE `gao_permission_names`;
-- 仅迁移有效授权,不恢复已撤销的旧授权
INSERT INTO `role_permission` (`id`, `role_id`, `permission_id`, `created_at`)
SELECT UUID(), source.`role_id`, target.`id`, UNIX_TIMESTAMP() * 1000
FROM (
SELECT DISTINCT rp.`role_id`, mapping.`new_code`
FROM `role_permission` rp
JOIN `permission` old_permission ON old_permission.`id` = rp.`permission_id` AND old_permission.`module_code` = 'GAO' AND old_permission.`deleted_at` IS NULL
JOIN `gao_permission_mapping` mapping ON mapping.`old_code` = old_permission.`code`
WHERE rp.`deleted_at` IS NULL
) source
JOIN `permission` target ON target.`module_code` = 'GAO' AND target.`code` = source.`new_code` AND target.`deleted_at` IS NULL
WHERE NOT EXISTS (
SELECT 1 FROM `role_permission` existing
WHERE existing.`role_id` = source.`role_id` AND existing.`permission_id` = target.`id` AND existing.`deleted_at` IS NULL
);
INSERT INTO `role_permission_delegation` (`id`, `role_id`, `permission_id`, `created_at`)
SELECT UUID(), source.`role_id`, target.`id`, UNIX_TIMESTAMP() * 1000
FROM (
SELECT DISTINCT delegation.`role_id`, mapping.`new_code`
FROM `role_permission_delegation` delegation
JOIN `permission` old_permission ON old_permission.`id` = delegation.`permission_id` AND old_permission.`module_code` = 'GAO' AND old_permission.`deleted_at` IS NULL
JOIN `gao_permission_mapping` mapping ON mapping.`old_code` = old_permission.`code`
WHERE delegation.`deleted_at` IS NULL
) source
JOIN `permission` target ON target.`module_code` = 'GAO' AND target.`code` = source.`new_code` AND target.`deleted_at` IS NULL
WHERE NOT EXISTS (
SELECT 1 FROM `role_permission_delegation` existing
WHERE existing.`role_id` = source.`role_id` AND existing.`permission_id` = target.`id` AND existing.`deleted_at` IS NULL
);
-- 保留授权历史;只有所有目标权限可用时才隐藏旧权限
CREATE TEMPORARY TABLE `gao_migrated_codes` (`old_code` VARCHAR(50) PRIMARY KEY);
INSERT INTO `gao_migrated_codes` (`old_code`)
SELECT mapping.`old_code`
FROM `gao_permission_mapping` mapping
LEFT JOIN `permission` target ON target.`module_code` = 'GAO' AND target.`code` = mapping.`new_code` AND target.`deleted_at` IS NULL
GROUP BY mapping.`old_code`
HAVING COUNT(*) = COUNT(target.`id`);
UPDATE `permission` old_permission
JOIN `gao_migrated_codes` migrated ON migrated.`old_code` = old_permission.`code`
SET old_permission.`deleted_at` = UNIX_TIMESTAMP() * 1000
WHERE old_permission.`module_code` = 'GAO' AND old_permission.`deleted_at` IS NULL;
DROP TEMPORARY TABLE `gao_migrated_codes`;
DROP TEMPORARY TABLE `gao_permission_mapping`;

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