Compare commits

...
8 Commits
Author SHA1 Message Date
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
35 changed files with 1092 additions and 228 deletions
+6 -1
View File
@@ -11,7 +11,7 @@
<groupId>com.imyeyu.timiserverapi</groupId>
<artifactId>TimiServerAPI</artifactId>
<version>1.0.71</version>
<version>1.0.72</version>
<packaging>jar</packaging>
<name>TimiServerAPI</name>
<description>imyeyu.com API</description>
@@ -219,6 +219,11 @@
<artifactId>tinypinyin</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>cn.6tail</groupId>
<artifactId>lunar</artifactId>
<version>1.7.8</version>
</dependency>
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
@@ -24,4 +24,13 @@ public interface SettingEnum {
String getDefaultValue();
Setting.ValueType getValueType();
/// 配置作用域
///
/// 业务级配置由业务对象自己维护,启动时不初始化记录
///
/// @return 配置作用域
default Setting.Scope getScope() {
return Setting.Scope.SYSTEM;
}
}
@@ -45,6 +45,9 @@ public class AppVersionService {
/// 更新日志最多返回的版本条数
public static final int MAX_NOTES = 20;
/// 已是最新时展示的版本条数
public static final int TAIL_NOTES = 3;
/// 灰度基数
private static final long GRAY_BASE = 10000L;
@@ -72,22 +75,25 @@ public class AppVersionService {
AppRelease target = resolveNative(release, currentCode);
return target == null
? AppUpdateCheckResponse.none(currentVersion)
: buildResponse(target, Boolean.TRUE.equals(target.getMandatory()));
: buildResponse(target, Boolean.TRUE.equals(target.getMandatory()), true);
}
AppRelease target = resolveBundle(release, product, currentCode, currentVersion, req.getDeviceId());
return target == null
? AppUpdateCheckResponse.none(currentVersion)
: buildResponse(target, false);
: buildResponse(target, false, false);
}
/// 查询更新日志
///
/// 区间上界取通道当前版本,不再走灰度与兼容区间判断。
/// 区间上界取通道当前版本,不走灰度与兼容区间判断。
/// 原因:客户端拿不到原生 versionCode,也无法保证命中灰度分桶,套用检查更新的判定会让日志
/// 大面积为空。日志是「这个产品最近发了什么」,不是「你这台设备能装什么」,分发决策仍由 check 负责
///
/// 有更新时返回 (当前版本, 通道版本] 区间;已是最新时区间为空,改为返回最近 TAIL_NOTES 个版本,
/// 否则更新完就看不到任何说明
///
/// @param req 插件上报信息
/// @return 当前版本到通道当前版本之间的变更说明
/// @return 变更说明,按版本号从新到旧
public AppUpdateNotesResponse notes(AppUpdateCheckRequest req) {
String currentVersion = currentVersion(req);
AppProduct product = resolveProduct(req);
@@ -99,20 +105,24 @@ public class AppVersionService {
if (target == null || target.getKind() == AppRelease.Kind.NATIVE) {
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(), currentVersion)) {
// 上界恒定:不展示比通道版本更新的记录
if (0 < compareVersion(item.getVersionName(), target.getVersionName())) {
continue;
}
if (0 < compareVersion(item.getVersionName(), target.getVersionName())) {
// 有更新时才设下界,已是最新则不限
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()));
List<AppUpdateNote> limited = MAX_NOTES < notes.size() ? notes.subList(0, MAX_NOTES) : notes;
int limit = upToDate ? TAIL_NOTES : MAX_NOTES;
List<AppUpdateNote> limited = limit < notes.size() ? notes.subList(0, limit) : notes;
return new AppUpdateNotesResponse(target.getVersionName(), limited);
}
@@ -231,13 +241,14 @@ public class AppVersionService {
///
/// @param release 发布记录
/// @param mandatory true 为强制更新
/// @param shell true 为外壳安装包,客户端需要下载后覆盖安装
/// @return 更新响应
private AppUpdateCheckResponse buildResponse(AppRelease release, boolean mandatory) {
private AppUpdateCheckResponse buildResponse(AppRelease release, boolean mandatory, boolean shell) {
String url = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/attach/download/")
.path(release.getAttachmentId())
.toUriString();
return new AppUpdateCheckResponse(release.getVersionName(), url, release.getSha256(), mandatory, release.getNote());
return new AppUpdateCheckResponse(release.getVersionName(), url, release.getSha256(), mandatory, shell, release.getNote());
}
/// 比较版本号
@@ -28,6 +28,12 @@ public class AppUpdateCheckResponse {
/// 是否为强制更新
protected Boolean mandatory;
/// 是否为外壳安装包
///
/// 客户端据此判断走热更还是下载安装包。字段名不能叫 kind:
/// Capgo 插件把 kind 视为错误响应的标记,收到后会直接判为检查失败
protected Boolean shell;
/// 变更说明,供 App 展示更新日志
///
/// 字段名不能叫 message:Capgo 插件把 message 当作错误信息,收到会直接判为检查失败
@@ -38,6 +44,6 @@ public class AppUpdateCheckResponse {
/// @param currentVersion 当前运行的 Web 包版本
/// @return 无更新响应
public static AppUpdateCheckResponse none(String currentVersion) {
return new AppUpdateCheckResponse(currentVersion, "", null, false, null);
return new AppUpdateCheckResponse(currentVersion, "", null, false, null, null);
}
}
@@ -77,6 +77,19 @@ public class Setting extends UUIDEntity {
JSON_OBJECT
}
/// 配置作用域
///
/// @author Codex
/// @since 2026-11-16
public enum Scope {
/// 系统级,bizId 固定为全零 UUID,启动时自动初始化
SYSTEM,
/// 业务级,bizId 为业务对象 ID,启动时不初始化
BUSINESS
}
@JsonView(ResponseView.Public.class)
private String bizType;
@@ -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;
}
}
@@ -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;
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;
@@ -28,6 +29,16 @@ public class GaoCustomerFollowUpReminder extends UUIDEntity {
COMPLETED
}
/// 提醒来源
public enum Source {
/// 手动创建
MANUAL,
/// 系统创建
SYSTEM
}
/// 通知渠道
public enum NotifyChannel {
@@ -56,6 +67,15 @@ public class GaoCustomerFollowUpReminder extends UUIDEntity {
/// 提醒状态
private Status status;
/// 来源
private Source source;
/// 系统创建的幂等键,格式为 业务类型:业务维度,手动创建为空
private String sourceKey;
/// 系统创建的扩展信息快照
private JsonNode metadata;
/// true 为发送站内通知
private Boolean internalNotifyEnabled;
@@ -1,7 +1,6 @@
package com.imyeyu.api.modules.gao.entity;
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.entity.UUIDEntity;
import lombok.Data;
@@ -78,9 +77,9 @@ public class GaoProductSku extends UUIDEntity {
@Transient
private List<GaoProductSkuUnit> unitList;
/// 基础单位迁移请求,仅用于 SKU 更新,不映射数据库列
/// true 为允许修改基础单位与单位换算系数;SKU 产生业务记录或库存后锁定
@Transient
private GaoProductSkuBaseUnitMigrationRequest baseUnitMigrationRequest;
private Boolean unitEditable;
/// SKU 附件列表
@Transient
@@ -1,5 +1,6 @@
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.vo.GaoCustomerFollowUpReminderPage;
import com.imyeyu.spring.mapper.BaseMapper;
@@ -50,4 +51,18 @@ public interface GaoCustomerFollowUpReminderMapper extends BaseMapper<GaoCustome
/// @return 受影响行数
int bindSmsNotifyDetailId(@Param("idList") Collection<String> idList,
@Param("smsNotifyDetailId") String smsNotifyDetailId);
/// 查询指定门店的生日候选客户
///
/// 回填判断生日所需的字段,生日月日由调用方按历法计算,不在此处过滤
///
/// @param storeIdList 门店 ID 列表
/// @return 生日候选客户
List<GaoCustomer> selectBirthdayCandidate(@Param("storeIdList") Collection<String> storeIdList);
/// 创建系统提醒,幂等键冲突时跳过
///
/// @param reminder 提醒
/// @return 受影响行数,0 为幂等键已存在
int insertIgnore(GaoCustomerFollowUpReminder reminder);
}
@@ -3,22 +3,15 @@ package com.imyeyu.api.modules.gao.mapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
/// 产品编辑、引用检查与单位迁移 Mapper
/// 产品编辑与引用检查 Mapper
public interface GaoProductEditMapper {
int countProductReferences(@Param("productId") String productId);
int countSkuReferences(@Param("skuId") String skuId);
int countRecycleReferences(@Param("skuId") String skuId);
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 updateProductFulfillmentSnapshots(@Param("productId") String productId, @Param("productName") String productName);
@@ -57,20 +50,4 @@ public interface GaoProductEditMapper {
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
GaoProductSku selectForUpdate(@Param("id") String id);
/// 批量查询已产生业务记录或库存的 SKU ID
///
/// @param idList SKU ID 集合
/// @return 已产生业务记录或库存的 SKU ID 列表
List<String> selectReferencedSkuIdList(@Param("idList") Collection<String> idList);
}
@@ -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)
List<GaoStore> selectAllByAutoClosedDay();
/// 查询可用门店
///
/// @return 门店列表
@Select("SELECT * FROM `gao_store` WHERE `status` = 'ACTIVE' " + NOT_DELETE)
List<GaoStore> selectAllActivated();
/// 查询用户所属的可用门店
///
/// @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;
import com.imyeyu.api.modules.common.entity.NotifyDetail;
import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPageResult;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.spring.service.BaseService;
/// GAO 客户跟进提醒服务
@@ -34,6 +36,19 @@ public interface GaoCustomerFollowUpReminderService extends BaseService<GaoCusto
/// @param id 跟进提醒 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();
}
@@ -22,6 +22,11 @@ public interface GaoStoreService extends BaseService<GaoStore, String> {
List<GaoStore> listByAutoClosedDay();
/// 查询可用门店
///
/// @return 门店列表
List<GaoStore> listActivated();
/// 按客户端提交的顺序更新排序
///
/// @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()));
reminder.setStatus(GaoCustomerFollowUpReminder.Status.PENDING);
// 来源和系统扩展字段只由系统任务写入,忽略请求值
reminder.setSource(GaoCustomerFollowUpReminder.Source.MANUAL);
reminder.setSourceKey(null);
reminder.setMetadata(null);
reminder.setCreatedBy(userLoginService.getRequireLoginUserId());
reminder.setUpdatedBy(null);
reminder.setCompletedBy(null);
@@ -116,7 +120,9 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
attachmentService.updateByBizId(Attachment.BizType.GAO_CUSTOMER_FOLLOW_UP_REMINDER,
reminder.getId(), reminder.getAttachmentList());
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);
}
reminder.resolveNotifyChannelList();
@@ -194,6 +200,27 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
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
@Transactional(TimiServerDBConfig.ROLLBACKER)
@@ -352,7 +379,9 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
NotifyDetail detail = TimiJava.isEmpty(reminder.getInternalNotifyDetailId())
? null : notifyDetailService.get(reminder.getInternalNotifyDetailId());
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;
}
if (detail.getMsgType() == NotifyDetail.MsgType.INTERNAL
@@ -367,17 +396,20 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
/// 创建站内通知
///
/// @param reminder 跟进提醒
/// @param customer 客户
/// @param subject 通知主题
/// @param content 通知正文
/// @param contentType 正文类型
/// @param responsibleUser 负责人
/// @param operatorUserId 操作人用户 ID
/// @return 通知详情 ID
private String createInternalNotify(GaoCustomerFollowUpReminder reminder, GaoCustomer customer,
User responsibleUser) {
private String createInternalNotify(GaoCustomerFollowUpReminder reminder, String subject, String content,
NotifyDetail.ContentType contentType, User responsibleUser, String operatorUserId) {
NotifyDetail detail = new NotifyDetail();
detail.setMsgType(NotifyDetail.MsgType.INTERNAL);
detail.setSubject("客户跟进提醒");
detail.setContent(buildInternalContent(customer, reminder));
detail.setContentType(NotifyDetail.ContentType.TEXT);
detail.setSendFrom(userLoginService.getRequireLoginUserId());
detail.setSubject(subject);
detail.setContent(content);
detail.setContentType(contentType);
detail.setSendFrom(operatorUserId);
detail.setSendTo(responsibleUser.getId());
detail.setSendAt(reminder.getRemindAt());
detail.setTimeoutAt(reminder.getRemindAt() + Time.D);
@@ -397,7 +429,7 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
notify.setBizType(NOTIFY_BIZ_TYPE);
notify.setBizRemindedType(INTERNAL_NOTIFY_TYPE);
notify.setBizRemindedKey(reminder.getId());
notify.setCreatedBy(userLoginService.getRequireLoginUserId());
notify.setCreatedBy(operatorUserId);
notify.setDetailList(List.of(detail));
notifyService.create(notify);
} else {
@@ -415,7 +447,7 @@ public class GaoCustomerFollowUpReminderServiceImplement extends AbstractEntityS
private String buildInternalContent(GaoCustomer customer, GaoCustomerFollowUpReminder reminder) {
String content = reminder.getContent();
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);
}
/// 取消尚未生效的站内通知
@@ -214,7 +214,6 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
|| TimiJava.defaultIfNull(request.getStatus(), current.getStatus()) != current.getStatus()
|| !Objects.equals(TimiJava.defaultIfNull(request.getSort(), current.getSort()), current.getSort())
|| !sameText(current.getRemark(), request.getRemark())
|| request.getBaseUnitMigrationRequest() != null
|| request.getAttachmentList() != null && !sameAttachmentList(current.getAttachmentList(), request.getAttachmentList())) {
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.GaoProductSkuService;
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.GaoProductSkuFulfillmentView;
import com.imyeyu.api.modules.system.audit.AuditOperation;
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.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
@@ -73,7 +70,6 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
private final GaoProductSpecMapper specMapper;
private final GaoProductSpecValueMapper valueMapper;
private final AttachmentService attachmentService;
private final LoggerService loggerService;
private final ObjectProvider<GaoProductService> productServiceProvider;
private final UserLoginService userLoginService;
@@ -266,17 +262,14 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
GaoProductSkuUnit oldBaseUnit = existingUnitList.stream().filter(unit -> Boolean.TRUE.equals(unit.getIsBase())).findFirst().orElseThrow();
List<GaoProductSkuUnit> requestedUnitList = request.getUnitList() == null ? existingUnitList : request.getUnitList();
GaoProductSkuUnit requestedBaseUnit = requestedUnitList.stream().filter(unit -> Boolean.TRUE.equals(unit.getIsBase())).findFirst().orElse(null);
boolean baseUnitChanged = requestedBaseUnit == null || !oldBaseUnit.getId().equals(requestedBaseUnit.getId());
GaoProductSkuBaseUnitMigrationRequest migrationRequest = request.getBaseUnitMigrationRequest();
BigDecimal migrationRatio = null;
if (baseUnitChanged) {
TimiException.requiredTrue(0 == editMapper.countRecycleReferences(sku.getId()), "SKU 存在回收兑换规则或交易,不能迁移基础单位");
migrationRatio = validateBaseUnitMigration(oldBaseUnit, requestedBaseUnit, migrationRequest, sku.getId());
} else if (migrationRequest != null) {
throw new TimiException(TimiCode.ERROR, "新旧基础单位相同,不需要提交基础单位迁移比例");
}
if (request.getUnitList() != null && !baseUnitChanged) {
validateUnitConversionUnchanged(request.getUnitList(), existingUnitList);
TimiException.required(requestedBaseUnit, "SKU 必须指定基础单位");
boolean baseUnitChanged = !oldBaseUnit.getId().equals(requestedBaseUnit.getId());
boolean unitConversionChanged = request.getUnitList() != null && isUnitConversionChanged(request.getUnitList(), existingUnitList);
if (baseUnitChanged || unitConversionChanged) {
TimiException.requiredTrue(0 == referenceCount, "SKU 已有历史业务记录,不能更换基础单位或调整换算系数;如需调整请新建 SKU");
List<GaoProductStock> stockList = stockMapper.selectByStoreIdAndSkuIdList(sku.getStoreId(), List.of(sku.getId()));
TimiException.requiredTrue(stockList.stream().allMatch(stock -> isZero(stock.getOnHandQuantity()) && isZero(stock.getReservedQuantity())),
"SKU 存在库存数量,不能更换基础单位或调整换算系数");
}
sku.setCode(TimiJava.defaultIfNull(request.getCode(), sku.getCode()));
sku.setBarcode(request.getBarcode());
@@ -290,21 +283,6 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
sku.setRemark(request.getRemark());
sku.setSpecValueIdList(request.getSpecValueIdList() == null ? currentSpecValueIds(sku.getId()) : request.getSpecValueIdList());
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());
super.update(sku);
if (request.getSpecValueIdList() != null) {
@@ -322,16 +300,6 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
editMapper.updateSkuStockRecordSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), skuSpecSnapshot);
editMapper.updateSkuPackageSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary());
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)
@@ -465,53 +433,8 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
return result;
}
private BigDecimal validateBaseUnitMigration(GaoProductSkuUnit oldBaseUnit, GaoProductSkuUnit newBaseUnit,
GaoProductSkuBaseUnitMigrationRequest request, String skuId) {
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,
/// 判断已保存单位的换算系数是否被修改
private boolean isUnitConversionChanged(List<GaoProductSkuUnit> requestedUnitList,
List<GaoProductSkuUnit> existingUnitList) {
Map<String, GaoProductSkuUnit> existingById = existingUnitList.stream()
.collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item));
@@ -519,9 +442,10 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
GaoProductSkuUnit existing = requested.getId() == null ? null : existingById.get(requested.getId());
BigDecimal requestedFactor = TimiJava.defaultIfNull(requested.getBaseQuantityPerUnit(), ONE);
if (existing != null && existing.getBaseQuantityPerUnit().compareTo(requestedFactor) != 0) {
throw new TimiException(TimiCode.ERROR, "已保存单位的换算系数不能直接修改;切换基础单位时请提交迁移比例");
return true;
}
}
return false;
}
private boolean isZero(BigDecimal value) {
@@ -590,10 +514,12 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
.stream()
.collect(Collectors.groupingBy(GaoProductSkuSpecValue::getSkuId, Collectors.mapping(GaoProductSkuSpecValue::getSpecValueId, Collectors.toList())));
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) {
sku.setUnitList(unitMap.getOrDefault(sku.getId(), List.of()));
sku.setSpecValueIdList(specValueIdMap.getOrDefault(sku.getId(), List.of()));
sku.setAttachmentList(attachmentMap.getOrDefault(sku.getId(), List.of()));
sku.setUnitEditable(!referencedSkuIdSet.contains(sku.getId()));
}
}
@@ -200,6 +200,14 @@ public class GaoStoreServiceImplement extends AbstractEntityService<GaoStore, St
return mapper.selectAllByAutoClosedDay();
}
/// 查询可用门店
///
/// @return 门店列表
@Override
public List<GaoStore> listActivated() {
return mapper.selectAllActivated();
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@OperationAudit(AuditOperation.GAO_STORE_SORT)
@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();
}
}
@@ -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;
}
@@ -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_DELETE(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_UPDATE(Logger.Module.GAO),
GAO_CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE(Logger.Module.GAO),
@@ -41,6 +41,10 @@ public class InitBuiltinSetting implements ApplicationRunner {
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void run(ApplicationArguments args) throws Exception {
for (SettingEnum item : findSettingEnumList()) {
if (item.getScope() != Setting.Scope.SYSTEM) {
// 业务级配置由业务对象自己维护,启动时不初始化
continue;
}
if (settingService.getSystem(item) == null) {
Setting setting = new Setting();
setting.setBizType(item.getBizType());
@@ -0,0 +1,17 @@
-- 客户跟进提醒增加来源与幂等键。
-- 手动创建走 MANUAL,定时任务生成走 SYSTEM;未来其他系统提醒复用同一套字段,不再加列。
-- source_key 是系统创建的幂等键,格式为「业务类型:业务维度」,如 BIRTHDAY:2027。
-- metadata 只放展示和追溯用的快照,不参与索引,不能承担幂等职责。
ALTER TABLE `gao_customer_follow_up_reminder`
ADD COLUMN `source` VARCHAR(32) NOT NULL DEFAULT 'MANUAL' COMMENT '来源,MANUAL 手动创建,SYSTEM 系统创建' AFTER `status`,
ADD COLUMN `source_key` VARCHAR(64) NULL COMMENT '系统创建的幂等键,格式为 业务类型:业务维度' AFTER `source`,
ADD COLUMN `metadata` JSON NULL COMMENT '系统创建的扩展信息快照' AFTER `source_key`;
-- 沿用项目现有的软删除唯一索引方案:未删除记录参与唯一约束,已删除记录生成 NULL,允许重新生成。
-- 手动创建的提醒 source_key 为空,MySQL 唯一索引允许多个 NULL,互不冲突。
ALTER TABLE `gao_customer_follow_up_reminder`
ADD COLUMN `active_source_key` VARCHAR(64) GENERATED ALWAYS AS (
CASE WHEN `deleted_at` IS NULL THEN `source_key` ELSE NULL END
) STORED COMMENT '未删除记录的幂等键' INVISIBLE,
ADD UNIQUE KEY `uk_gao_customer_follow_up_reminder_source` (`store_id`, `customer_id`, `active_source_key`),
ADD KEY `idx_gao_customer_follow_up_reminder_source` (`store_id`, `source`, `deleted_at`, `remind_at`);
@@ -75,4 +75,28 @@
AND `sms_notify_enabled` = 1
AND `sms_notify_detail_id` IS NULL
</update>
<select id="selectBirthdayCandidate" resultType="com.imyeyu.api.modules.gao.entity.GaoCustomer">
SELECT `c`.`id`, `c`.`store_id`, `c`.`name`, `c`.`birthdate`, `c`.`birthdate_calendar`
FROM `gao_customer` `c`
WHERE `c`.`deleted_at` IS NULL
AND `c`.`birthdate` IS NOT NULL
AND `c`.`store_id` IN
<foreach collection="storeIdList" item="storeId" separator="," open="(" close=")">
#{storeId}
</foreach>
</select>
<!-- 幂等键冲突说明:uk_gao_customer_follow_up_reminder_source 兜底同门店同客户同来源键只允许一条 -->
<insert id="insertIgnore">
INSERT IGNORE INTO `gao_customer_follow_up_reminder` (
`id`, `store_id`, `customer_id`, `responsible_user_id`, `content`, `remind_at`,
`status`, `source`, `source_key`, `metadata`,
`internal_notify_enabled`, `sms_notify_enabled`, `created_by`, `created_at`
) VALUES (
#{id}, #{storeId}, #{customerId}, #{responsibleUserId}, #{content}, #{remindAt},
#{status}, #{source}, #{sourceKey}, #{metadata},
#{internalNotifyEnabled}, #{smsNotifyEnabled}, #{createdBy}, #{createdAt}
)
</insert>
</mapper>
@@ -32,61 +32,6 @@
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_unit_id_snapshot` = #{unitId}) +
(SELECT COUNT(*) FROM `gao_recycle_exchange_rule_item` WHERE `sku_unit_id` = #{unitId})
</select>
<select id="countRecycleReferences" resultType="int">
SELECT (SELECT COUNT(*) FROM `gao_recycle_product_yield` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_recycle_exchange_rule_item` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_sales_order_item` i JOIN `gao_sales_order` o ON o.`id` = i.`sales_order_id`
WHERE i.`sku_id` = #{skuId} AND o.`order_type` = 'RECYCLE')
</select>
<select id="countMigrationPrecisionLoss" resultType="int">
SELECT COUNT(*) FROM (
SELECT 1 FROM `gao_product_sku` WHERE `id` = #{skuId} AND `min_stock_quantity` IS NOT NULL
AND (`min_stock_quantity` * #{ratio} &lt;&gt; ROUND(`min_stock_quantity` * #{ratio}, 3) OR ABS(`min_stock_quantity` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_product_stock` WHERE `sku_id` = #{skuId}
AND (`on_hand_quantity` * #{ratio} &lt;&gt; ROUND(`on_hand_quantity` * #{ratio}, 3) OR ABS(`on_hand_quantity` * #{ratio}) &gt; 999999999999999.999
OR `reserved_quantity` * #{ratio} &lt;&gt; ROUND(`reserved_quantity` * #{ratio}, 3) OR ABS(`reserved_quantity` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_sales_order_item` WHERE `sku_id` = #{skuId}
AND (`base_quantity` * #{ratio} &lt;&gt; ROUND(`base_quantity` * #{ratio}, 3) OR ABS(`base_quantity` * #{ratio}) &gt; 999999999999999.999
OR `reserved_base_quantity` * #{ratio} &lt;&gt; ROUND(`reserved_base_quantity` * #{ratio}, 3) OR ABS(`reserved_base_quantity` * #{ratio}) &gt; 999999999999999.999
OR `fulfilled_base_quantity` * #{ratio} &lt;&gt; ROUND(`fulfilled_base_quantity` * #{ratio}, 3) OR ABS(`fulfilled_base_quantity` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_order_fulfillment_item` WHERE `sku_id` = #{skuId}
AND (`base_quantity` * #{ratio} &lt;&gt; ROUND(`base_quantity` * #{ratio}, 3) OR ABS(`base_quantity` * #{ratio}) &gt; 999999999999999.999
OR `reserved_base_before` * #{ratio} &lt;&gt; ROUND(`reserved_base_before` * #{ratio}, 3) OR ABS(`reserved_base_before` * #{ratio}) &gt; 999999999999999.999
OR `reserved_base_after` * #{ratio} &lt;&gt; ROUND(`reserved_base_after` * #{ratio}, 3) OR ABS(`reserved_base_after` * #{ratio}) &gt; 999999999999999.999
OR `fulfilled_base_before` * #{ratio} &lt;&gt; ROUND(`fulfilled_base_before` * #{ratio}, 3) OR ABS(`fulfilled_base_before` * #{ratio}) &gt; 999999999999999.999
OR `fulfilled_base_after` * #{ratio} &lt;&gt; ROUND(`fulfilled_base_after` * #{ratio}, 3) OR ABS(`fulfilled_base_after` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_product_stock_record` WHERE `sku_id` = #{skuId}
AND (`base_quantity` * #{ratio} &lt;&gt; ROUND(`base_quantity` * #{ratio}, 3) OR ABS(`base_quantity` * #{ratio}) &gt; 999999999999999.999
OR `on_hand_delta` * #{ratio} &lt;&gt; ROUND(`on_hand_delta` * #{ratio}, 3) OR ABS(`on_hand_delta` * #{ratio}) &gt; 999999999999999.999
OR `reserved_delta` * #{ratio} &lt;&gt; ROUND(`reserved_delta` * #{ratio}, 3) OR ABS(`reserved_delta` * #{ratio}) &gt; 999999999999999.999
OR `on_hand_before` * #{ratio} &lt;&gt; ROUND(`on_hand_before` * #{ratio}, 3) OR ABS(`on_hand_before` * #{ratio}) &gt; 999999999999999.999
OR `on_hand_after` * #{ratio} &lt;&gt; ROUND(`on_hand_after` * #{ratio}, 3) OR ABS(`on_hand_after` * #{ratio}) &gt; 999999999999999.999
OR `reserved_before` * #{ratio} &lt;&gt; ROUND(`reserved_before` * #{ratio}, 3) OR ABS(`reserved_before` * #{ratio}) &gt; 999999999999999.999
OR `reserved_after` * #{ratio} &lt;&gt; ROUND(`reserved_after` * #{ratio}, 3) OR ABS(`reserved_after` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_point_redemption` WHERE `sku_id_snapshot` = #{skuId}
AND (`base_quantity` * #{ratio} &lt;&gt; ROUND(`base_quantity` * #{ratio}, 3) OR ABS(`base_quantity` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_point_redemption_return` r
JOIN `gao_point_redemption` d ON d.`id` = r.`redemption_id`
WHERE d.`sku_id_snapshot` = #{skuId}
AND (r.`base_quantity` * #{ratio} &lt;&gt; ROUND(r.`base_quantity` * #{ratio}, 3) OR ABS(r.`base_quantity` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_product_sku_unit` WHERE `sku_id` = #{skuId} AND `deleted_at` IS NULL
AND (#{targetUnitId} IS NULL OR `id` &lt;&gt; #{targetUnitId})
AND (`base_quantity_per_unit` * #{ratio} &lt;&gt; ROUND(`base_quantity_per_unit` * #{ratio}, 6) OR ABS(`base_quantity_per_unit` * #{ratio}) &gt; 999999999999.999999)
UNION ALL SELECT 1 FROM `gao_sales_order_item` WHERE `sku_id` = #{skuId}
AND (ABS(`base_quantity_per_unit_snapshot` * #{ratio}) &gt; 999999999999.999999 OR `base_quantity_per_unit_snapshot` * #{ratio} &lt;&gt; ROUND(`base_quantity_per_unit_snapshot` * #{ratio}, 6))
UNION ALL SELECT 1 FROM `gao_order_fulfillment_item` WHERE `sku_id` = #{skuId}
AND (ABS(`base_quantity_per_unit_snapshot` * #{ratio}) &gt; 999999999999.999999 OR `base_quantity_per_unit_snapshot` * #{ratio} &lt;&gt; ROUND(`base_quantity_per_unit_snapshot` * #{ratio}, 6))
UNION ALL SELECT 1 FROM `gao_product_stock_record` WHERE `sku_id` = #{skuId}
AND (ABS(`base_quantity_per_unit_snapshot` * #{ratio}) &gt; 999999999999.999999 OR `base_quantity_per_unit_snapshot` * #{ratio} &lt;&gt; ROUND(`base_quantity_per_unit_snapshot` * #{ratio}, 6))
UNION ALL SELECT 1 FROM `gao_package_config_item` WHERE `sku_id` = #{skuId}
AND (ABS(`base_quantity_per_unit_snapshot` * #{ratio}) &gt; 999999999999.999999 OR `base_quantity_per_unit_snapshot` * #{ratio} &lt;&gt; ROUND(`base_quantity_per_unit_snapshot` * #{ratio}, 6))
UNION ALL SELECT 1 FROM `gao_package_config_item` WHERE `sku_id` = #{skuId}
AND (`default_quantity` * `base_quantity_per_unit_snapshot` * #{ratio} &lt;&gt; ROUND(`default_quantity` * `base_quantity_per_unit_snapshot` * #{ratio}, 3)
OR ABS(`default_quantity` * `base_quantity_per_unit_snapshot` * #{ratio}) &gt; 999999999999999.999)
UNION ALL SELECT 1 FROM `gao_point_redemption` WHERE `sku_id_snapshot` = #{skuId}
AND (ABS(`base_quantity_per_unit_snapshot` * #{ratio}) &gt; 999999999999.999999 OR `base_quantity_per_unit_snapshot` * #{ratio} &lt;&gt; ROUND(`base_quantity_per_unit_snapshot` * #{ratio}, 6))
) precision_issue
</select>
<update id="updateProductOrderSnapshots">UPDATE `gao_sales_order_item` SET `product_name_snapshot`=#{productName} WHERE `product_id_snapshot`=#{productId}</update>
<update id="updateProductFulfillmentSnapshots">UPDATE `gao_order_fulfillment_item` SET `product_name_snapshot`=#{productName} WHERE `product_id_snapshot`=#{productId}</update>
<update id="updateProductStockRecordSnapshots">UPDATE `gao_product_stock_record` SET `product_name_snapshot`=#{productName} WHERE `product_id_snapshot`=#{productId}</update>
@@ -102,17 +47,4 @@
<update id="updateUnitStockRecordSnapshots">UPDATE `gao_product_stock_record` SET `unit_snapshot`=#{unitName} WHERE `sku_unit_id`=#{unitId}</update>
<update id="updateUnitPackageSnapshots">UPDATE `gao_package_config_item` SET `unit_snapshot`=#{unitName} WHERE `sku_unit_id`=#{unitId}</update>
<update id="updateUnitRedemptionSnapshots">UPDATE `gao_point_redemption` SET `unit_snapshot`=#{unitName} WHERE `sku_unit_id_snapshot`=#{unitId}</update>
<update id="scaleSkuMinimumStock">UPDATE `gao_product_sku` SET `min_stock_quantity`=`min_stock_quantity`*#{ratio} WHERE `id`=#{skuId} AND `min_stock_quantity` IS NOT NULL</update>
<update id="scaleProductStock">UPDATE `gao_product_stock` SET `on_hand_quantity`=`on_hand_quantity`*#{ratio}, `reserved_quantity`=`reserved_quantity`*#{ratio}, `updated_at`=FLOOR(UNIX_TIMESTAMP(NOW(3))*1000) WHERE `sku_id`=#{skuId}</update>
<update id="scaleSalesOrderItems">UPDATE `gao_sales_order_item` SET `base_quantity`=`base_quantity`*#{ratio}, `reserved_base_quantity`=`reserved_base_quantity`*#{ratio}, `fulfilled_base_quantity`=`fulfilled_base_quantity`*#{ratio}, `base_quantity_per_unit_snapshot`=`base_quantity_per_unit_snapshot`*#{ratio} WHERE `sku_id`=#{skuId}</update>
<update id="scaleFulfillmentItems">UPDATE `gao_order_fulfillment_item` SET `base_quantity`=`base_quantity`*#{ratio}, `reserved_base_before`=`reserved_base_before`*#{ratio}, `reserved_base_after`=`reserved_base_after`*#{ratio}, `fulfilled_base_before`=`fulfilled_base_before`*#{ratio}, `fulfilled_base_after`=`fulfilled_base_after`*#{ratio}, `base_quantity_per_unit_snapshot`=`base_quantity_per_unit_snapshot`*#{ratio} WHERE `sku_id`=#{skuId}</update>
<update id="scaleStockRecords">UPDATE `gao_product_stock_record` SET `base_quantity`=`base_quantity`*#{ratio}, `on_hand_delta`=`on_hand_delta`*#{ratio}, `reserved_delta`=`reserved_delta`*#{ratio}, `on_hand_before`=`on_hand_before`*#{ratio}, `on_hand_after`=`on_hand_after`*#{ratio}, `reserved_before`=`reserved_before`*#{ratio}, `reserved_after`=`reserved_after`*#{ratio}, `base_quantity_per_unit_snapshot`=`base_quantity_per_unit_snapshot`*#{ratio} WHERE `sku_id`=#{skuId}</update>
<update id="scalePackageConfigItems">UPDATE `gao_package_config_item` SET `base_quantity_per_unit_snapshot`=`base_quantity_per_unit_snapshot`*#{ratio} WHERE `sku_id`=#{skuId}</update>
<update id="scalePointRedemptions">UPDATE `gao_point_redemption` SET `base_quantity`=`base_quantity`*#{ratio}, `base_quantity_per_unit_snapshot`=`base_quantity_per_unit_snapshot`*#{ratio} WHERE `sku_id_snapshot`=#{skuId}</update>
<update id="scalePointRedemptionReturns">
UPDATE `gao_point_redemption_return` r
JOIN `gao_point_redemption` d ON d.`id`=r.`redemption_id`
SET r.`base_quantity`=r.`base_quantity`*#{ratio}
WHERE d.`sku_id_snapshot`=#{skuId}
</update>
</mapper>
@@ -26,4 +26,24 @@
<select id="selectForUpdate" resultType="com.imyeyu.api.modules.gao.entity.GaoProductSku">
SELECT * FROM `gao_product_sku` WHERE `id` = #{id} AND `deleted_at` IS NULL FOR UPDATE
</select>
<select id="selectReferencedSkuIdList" resultType="java.lang.String">
SELECT `sku_id` FROM `gao_sales_order_item` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_order_fulfillment_item` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_product_stock_record` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_package_config_item` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_point_redeem_sku` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id_snapshot` FROM `gao_point_redemption` WHERE `sku_id_snapshot` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_recycle_product_yield` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_recycle_exchange_rule_item` WHERE `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
UNION SELECT `sku_id` FROM `gao_product_stock` WHERE (`on_hand_quantity` &lt;&gt; 0 OR `reserved_quantity` &lt;&gt; 0) AND `sku_id` IN
<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}</foreach>
</select>
</mapper>
@@ -0,0 +1,25 @@
<div class="gao-customer-birthday-reminder">
<h3>${customerName?html}</h3>
<p>今天是该客户的生日,请安排关怀。</p>
<ul>
<li><strong>生日:</strong>${birthdayText?html}</li>
<#if lunarText?? && lunarText?has_content>
<li><strong>农历:</strong>${lunarText?html}</li>
</#if>
<#if telephone?? && telephone?has_content>
<li><strong>电话:</strong>${telephone?html}</li>
</#if>
<#if disease?? && disease?has_content>
<li><strong>病症:</strong>${disease?html}</li>
</#if>
<#if remark?? && remark?has_content>
<li><strong>备注:</strong>${remark?html}</li>
</#if>
</ul>
<p>
<a
href="${customerUrl?html}"
style="display: inline-block; padding: 6px 12px; color: #FFFFFF; background-color: #1677FF; text-decoration: none; border-radius: 4px;"
>查看客户详情</a>
</p>
</div>
@@ -12,7 +12,7 @@
</ul>
<p>
<a
href="/management/sales-orders/${order.orderId?html}"
href="/product/sales-orders/${order.orderId?html}"
style="display: inline-block; padding: 6px 12px; color: #FFFFFF; background-color: #1677FF; text-decoration: none; border-radius: 4px;"
>查看订单详情</a>
</p>