update point tier rule

This commit is contained in:
Timi
2026-08-14 18:26:38 +08:00
parent e369a38e2e
commit 9dfca25f8c
12 changed files with 324 additions and 48 deletions
@@ -19,12 +19,12 @@ import com.imyeyu.api.modules.gao.vo.GaoUserInviteValidateRequest;
import com.imyeyu.api.modules.gao.vo.GaoUserInviteValidateResponse;
import com.imyeyu.api.modules.user.entity.Role;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.vo.LoginResponse;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.api.modules.user.service.RoleService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.modules.user.service.UserRoleService;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.api.modules.user.vo.LoginResponse;
import com.imyeyu.java.TimiJava;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.CaptchaValid;
@@ -72,7 +72,7 @@ public class GaoUserController {
}
@AOPLog
@RequestRateLimit(value = 20, inSeconds = 10)
@RequestRateLimit(20)
@PostMapping("/invite/validate")
public GaoUserInviteValidateResponse validateInvite(@RequestBody @Valid GaoUserInviteValidateRequest req) {
return inviteService.validate(req.getCode());
@@ -38,6 +38,26 @@ public class GaoEvent extends UUIDEntity {
DELETED
}
/// 事件数值类型
public enum ValueType {
/// 不携带数值
NONE,
/// 携带整数数值
NUMBER
}
/// 事件数值单位
public enum ValueUnit {
/// 金额分
CENT,
/// 次数
COUNT
}
/// 登记限制类型
///
/// @author 夜雨
@@ -70,6 +90,9 @@ public class GaoEvent extends UUIDEntity {
final Long min;
}
/// 统计图表颜色
private String color;
/// 登记事件名称
private String name;
@@ -79,8 +102,14 @@ public class GaoEvent extends UUIDEntity {
/// 说明
private String description;
/// 统计图表颜色
private String color;
/// 数值类型
private ValueType valueType;
/// 数值单位
private ValueUnit valueUnit;
/// true 为登记时必须提交 numberValue
private Boolean requireValue;
/// 状态
private Status status;
@@ -40,6 +40,15 @@ public class GaoEventRecord extends UUIDEntity {
/// 操作管理员用户 ID
private String operatorUserId;
/// 本次登记提交的积分值
private Long pointValue;
/// 本次登记通过积分规则获得的积分总和
private Long earnedPointValue;
/// 本次登记提交的整数业务数值
private Long numberValue;
/// 备注
private String remark;
@@ -52,10 +61,6 @@ public class GaoEventRecord extends UUIDEntity {
/// 营业日递增序号
private Long businessDayNo;
/// 本次登记提交的积分值,只参与积分触发,不落库
@Transient
private Long pointValue;
@Transient
private GaoCustomer customer;
@@ -42,7 +42,10 @@ public class GaoPointRule extends UUIDEntity {
AFTER_COUNT_EVERY_TIME,
/// 使用登记接口提交的积分值触发
SOURCE_VALUE
SOURCE_VALUE,
/// 按来源事件数值累计分档触发
CUSTOMER_EVENT_VALUE_TIER
}
/// 积分值模式
@@ -52,7 +55,10 @@ public class GaoPointRule extends UUIDEntity {
FIXED,
/// 使用登记接口提交的积分值
SOURCE_VALUE
SOURCE_VALUE,
/// 使用条件配置中的分档积分值
TIER
}
/// 门店 ID
@@ -21,6 +21,28 @@ public interface GaoEventRecordMapper extends BaseMapper<GaoEventRecord, String>
Long count(String storeId, String customerId, String eventId, Long beginAt, Long endAt);
/// 查询事件中已携带数值的登记记录数量
///
/// @param eventId 事件 ID
/// @return 携带数值的登记记录数量
Long countByEventIdAndNumberValue(String eventId);
/// 汇总客户指定来源事件在时间范围内的数值
///
/// @param storeId 门店 ID
/// @param customerId 客户 ID
/// @param eventId 来源事件 ID
/// @param beginAt 起始时间,包含
/// @param endAt 结束时间,不包含
/// @return 数值总和
Long sumNumberValue(@Param("storeId") String storeId, @Param("customerId") String customerId, @Param("eventId") String eventId, @Param("beginAt") Long beginAt, @Param("endAt") Long endAt);
/// 回写登记记录最终获得的积分快照
///
/// @param id 登记记录 ID
/// @param earnedPointValue 获得积分总和
void updateEarnedPointValue(@Param("id") String id, @Param("earnedPointValue") Long earnedPointValue);
/// 按门店和登记日期统计登记记录数
///
/// @param storeId 门店 ID
@@ -87,7 +87,9 @@ public class GaoEventRecordServiceImplement extends AbstractEntityService<GaoEve
String loginUserId = userLoginService.getRequireLoginUserId();
Long registeredAt = TimiJava.defaultIfNull(record.getRegisteredAt(), Time.now());
GaoEvent event = eventService.get(record.getEventId());
TimiException.required(event, "not found event");
TimiException.required(event.getStoreId(), "not found event.storeId");
verifyRecordValue(event, record.getNumberValue());
// 检查权限
checkEventPermission(event);
int registeredDateValue = dateValue(registeredAt);
@@ -119,6 +121,8 @@ public class GaoEventRecordServiceImplement extends AbstractEntityService<GaoEve
dbRecord.setRegisteredDateValue(registeredDateValue);
dbRecord.setBusinessDayNo(businessDayNo);
dbRecord.setPointValue(record.getPointValue());
dbRecord.setNumberValue(record.getNumberValue());
dbRecord.setEarnedPointValue(0L);
super.create(dbRecord);
// 附件
if (i == 0) {
@@ -170,24 +174,17 @@ public class GaoEventRecordServiceImplement extends AbstractEntityService<GaoEve
Logger logger = new Logger(Logger.Module.GAO, "GAO_EVENT_RECORD_UPDATE");
try {
logger.setContent(jackson.writeValueAsString(record));
TimiException.required(record.getCustomerId(), "not found record.customerId");
TimiException.required(record.getEventId(), "not found record.eventId");
GaoEventRecord dbRecord = get(record.getId());
TimiException.required(dbRecord, "not found event record");
TimiException.required(record.getStoreId() == null || record.getStoreId().equals(dbRecord.getStoreId()), "record.storeId invalid");
verifyImmutableRecordFields(record, dbRecord);
record.setRegisteredAt(TimiJava.defaultIfNull(record.getRegisteredAt(), Time.now()));
GaoEvent event = eventService.get(record.getEventId());
GaoEvent event = eventService.get(dbRecord.getEventId());
TimiException.required(event, "not found event");
TimiException.required(event.getStoreId(), "not found event.storeId");
checkEventPermission(event);
checkEventCreatable(record.getCustomerId(), event, record.getRegisteredAt());
GaoCustomer customer = customerService.get(record.getCustomerId());
TimiException.required(customer, "not found customer");
TimiException.requiredTrue(event.getStoreId().equals(customer.getStoreId()), "客户和登记事件不属于同一门店");
int registeredDateValue = dateValue(record.getRegisteredAt());
record.setStoreId(event.getStoreId());
record.setRegisteredDateValue(registeredDateValue);
record.setBusinessDayNo(businessDayService.resolveOpenBusinessDay(event.getStoreId(), registeredDateValue).getBusinessDayNo());
super.update(record);
dbRecord.setRemark(record.getRemark());
super.update(dbRecord);
attachmentService.updateByBizId(Attachment.BizType.GAO_EVENT_RECORD, record.getId(), record.getAttachmentList());
logger.setLevel(Logger.Level.INFO);
logger.setResult(record.getId());
@@ -343,6 +340,26 @@ public class GaoEventRecordServiceImplement extends AbstractEntityService<GaoEve
}
}
private void verifyRecordValue(GaoEvent event, Long numberValue) {
GaoEvent.ValueType valueType = TimiJava.defaultIfNull(event.getValueType(), GaoEvent.ValueType.NONE);
if (numberValue != null) {
TimiException.requiredTrue(0 <= numberValue, "numberValue 不能为负数");
}
if (valueType == GaoEvent.ValueType.NONE) {
TimiException.requiredNull(numberValue, "NONE 事件不能提交 numberValue");
} else if (Boolean.TRUE.equals(event.getRequireValue())) {
TimiException.required(numberValue, "该事件必须提交 numberValue");
}
}
private void verifyImmutableRecordFields(GaoEventRecord request, GaoEventRecord dbRecord) {
TimiException.requiredTrue(request.getCustomerId() == null || request.getCustomerId().equals(dbRecord.getCustomerId()), "登记记录 customerId 创建后不可修改");
TimiException.requiredTrue(request.getEventId() == null || request.getEventId().equals(dbRecord.getEventId()), "登记记录 eventId 创建后不可修改");
TimiException.requiredTrue(request.getRegisteredAt() == null || request.getRegisteredAt().equals(dbRecord.getRegisteredAt()), "登记记录 registeredAt 创建后不可修改");
TimiException.requiredTrue(request.getPointValue() == null || request.getPointValue().equals(dbRecord.getPointValue()), "登记记录 pointValue 创建后不可修改");
TimiException.requiredTrue(request.getNumberValue() == null || request.getNumberValue().equals(dbRecord.getNumberValue()), "登记记录 numberValue 创建后不可修改");
}
private int dateValue(long time) {
LocalDate date = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).toLocalDate();
return Integer.parseInt(DAY_FORMATTER.format(date));
@@ -5,6 +5,7 @@ import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.api.modules.gao.entity.GaoEventRoleRelation;
import com.imyeyu.api.modules.gao.mapper.GaoEventMapper;
import com.imyeyu.api.modules.gao.mapper.GaoEventRecordMapper;
import com.imyeyu.api.modules.gao.mapper.GaoEventRoleRelationMapper;
import com.imyeyu.api.modules.gao.service.GaoEventService;
import com.imyeyu.api.modules.system.entity.Logger;
@@ -45,6 +46,7 @@ public class GaoEventServiceImplement extends AbstractEntityService<GaoEvent, St
private final LoggerService loggerService;
private final GaoEventMapper mapper;
private final GaoEventRecordMapper eventRecordMapper;
private final GaoEventRoleRelationMapper roleRelationMapper;
@Override
@@ -64,6 +66,8 @@ public class GaoEventServiceImplement extends AbstractEntityService<GaoEvent, St
logger.setContent(jackson.writeValueAsString(event));
event.setStatus(TimiJava.defaultIfNull(event.getStatus(), GaoEvent.Status.DRAFT));
event.setValueType(TimiJava.defaultIfNull(event.getValueType(), GaoEvent.ValueType.NONE));
event.setRequireValue(TimiJava.defaultIfNull(event.getRequireValue(), false));
event.setRequirePhoto(TimiJava.defaultIfNull(event.getRequirePhoto(), false));
event.setLimitType(TimiJava.defaultIfNull(event.getLimitType(), GaoEvent.LimitType.NONE));
event.setSort(TimiJava.defaultIfNull(event.getSort(), 0));
@@ -94,17 +98,36 @@ public class GaoEventServiceImplement extends AbstractEntityService<GaoEvent, St
try {
logger.setContent(jackson.writeValueAsString(event));
GaoEvent dbEvent = get(event.getId());
TimiException.required(dbEvent, "not found event");
TimiException.requiredTrue(dbEvent.getStoreId().equals(event.getStoreId()), "event.storeId invalid");
GaoEvent.ValueType oldValueType = dbEvent.getValueType();
GaoEvent.ValueUnit oldValueUnit = dbEvent.getValueUnit();
dbEvent.setName(event.getName());
dbEvent.setDescription(event.getDescription());
dbEvent.setColor(event.getColor());
dbEvent.setStatus(event.getStatus());
dbEvent.setValueType(TimiJava.defaultIfNull(event.getValueType(), oldValueType));
if (event.getValueUnit() != null) {
dbEvent.setValueUnit(event.getValueUnit());
} else if (event.getValueType() != null && event.getValueType() != oldValueType) {
dbEvent.setValueUnit(null);
} else {
dbEvent.setValueUnit(oldValueUnit);
}
if (event.getRequireValue() != null) {
dbEvent.setRequireValue(event.getRequireValue());
} else if (event.getValueType() != null && event.getValueType() != oldValueType) {
dbEvent.setRequireValue(false);
} else {
dbEvent.setRequireValue(dbEvent.getRequireValue());
}
dbEvent.setRequirePhoto(event.getRequirePhoto());
dbEvent.setLimitType(event.getLimitType());
dbEvent.setLimitValue(event.getLimitValue());
dbEvent.setBeginAt(event.getBeginAt());
dbEvent.setEndAt(event.getEndAt());
verifyValueDefinitionChange(dbEvent, oldValueType, oldValueUnit);
verifyEvent(dbEvent);
mapper.update(dbEvent);
saveRoleRelation(event.getId(), event.getRoleCodeList());
@@ -190,6 +213,13 @@ public class GaoEventServiceImplement extends AbstractEntityService<GaoEvent, St
}
private void verifyEvent(GaoEvent event) {
GaoEvent.ValueType valueType = TimiJava.defaultIfNull(event.getValueType(), GaoEvent.ValueType.NONE);
if (valueType == GaoEvent.ValueType.NONE) {
TimiException.requiredNull(event.getValueUnit(), "NONE 事件不能配置数值单位");
TimiException.requiredTrue(!Boolean.TRUE.equals(event.getRequireValue()), "NONE 事件不能要求提交数值");
} else {
TimiException.required(event.getValueUnit(), "NUMBER 事件必须配置数值单位");
}
if (TimiJava.isNotEmpty(event.getLimitType()) && event.getLimitType() != GaoEvent.LimitType.NONE) {
TimiException.requiredTrue(event.getLimitType().getMin() < event.getLimitValue(), "约束值最低 %s".formatted(event.getLimitType().getMin()));
}
@@ -198,6 +228,17 @@ public class GaoEventServiceImplement extends AbstractEntityService<GaoEvent, St
}
}
private void verifyValueDefinitionChange(GaoEvent event, GaoEvent.ValueType oldValueType, GaoEvent.ValueUnit oldValueUnit) {
if (oldValueType == event.getValueType() && oldValueUnit == event.getValueUnit()) {
return;
}
Long count = eventRecordMapper.countByEventIdAndNumberValue(event.getId());
if (0 < TimiJava.defaultIfNull(count, 0L)) {
TimiException.requiredTrue(oldValueUnit == event.getValueUnit(), "事件已有数值登记记录,禁止修改 valueUnit");
TimiException.requiredTrue(event.getValueType() == GaoEvent.ValueType.NUMBER, "事件已有数值登记记录,不能改为 NONE");
}
}
private void saveRoleRelation(String eventId, List<String> roleCodeList) {
List<GaoEventRoleRelation> dbRoleRelationList = roleRelationMapper.selectAllByEventIdList(List.of(eventId));
Set<String> roleCodeSet = TimiJava.defaultIfEmpty(roleCodeList, List.<String>of()).stream().filter(TimiJava::isNotEmpty).collect(Collectors.toSet());
@@ -25,6 +25,8 @@ import java.util.List;
@RequiredArgsConstructor
public class GaoPointRuleServiceImplement extends AbstractEntityService<GaoPointRule, String> implements GaoPointRuleService {
private static final int MAX_TIER_COUNT = 100;
private final GaoPointRuleMapper mapper;
private final GaoEventService eventService;
@@ -116,6 +118,13 @@ public class GaoPointRuleServiceImplement extends AbstractEntityService<GaoPoint
return;
}
if (rule.getTriggerType() == GaoPointRule.TriggerType.CUSTOMER_EVENT_VALUE_TIER) {
TimiException.requiredTrue(rule.getPointMode() == GaoPointRule.PointMode.TIER, "CUSTOMER_EVENT_VALUE_TIER 规则必须使用 TIER 积分值模式");
TimiException.requiredNull(rule.getPointValue(), "TIER 规则不能填写规则级积分值");
verifyTierCondition(rule.getStoreId(), rule.getConditionJson());
return;
}
TimiException.requiredTrue(rule.getPointMode() == GaoPointRule.PointMode.FIXED, "固定触发规则必须使用 FIXED 积分值模式");
TimiException.required(rule.getPointValue(), "not found rule.pointValue");
TimiException.requiredTrue(0 < rule.getPointValue(), "rule.pointValue invalid");
@@ -131,6 +140,63 @@ public class GaoPointRuleServiceImplement extends AbstractEntityService<GaoPoint
}
}
private void verifyTierCondition(String storeId, JsonNode conditionJson) {
JsonNode condition = requireObjectCondition(conditionJson);
JsonNode sourceEventIdNode = condition.get("sourceEventId");
TimiException.requiredTrue(sourceEventIdNode != null && sourceEventIdNode.isTextual() && TimiJava.isNotEmpty(sourceEventIdNode.asText().trim()), "TIER.sourceEventId invalid");
String sourceEventId = sourceEventIdNode.asText().trim();
GaoEvent sourceEvent = eventService.get(sourceEventId);
TimiException.required(sourceEvent, "TIER.sourceEventId 对应事件不存在");
TimiException.requiredTrue(storeId.equals(sourceEvent.getStoreId()), "TIER 来源事件和规则不属于同一门店");
TimiException.requiredTrue(sourceEvent.getValueType() == GaoEvent.ValueType.NUMBER, "TIER 来源事件必须配置为 NUMBER 类型");
JsonNode sourceValueField = condition.get("sourceValueField");
TimiException.requiredTrue(sourceValueField != null && sourceValueField.isTextual() && "numberValue".equals(sourceValueField.asText()), "TIER.sourceValueField 目前只能是 numberValue");
JsonNode window = condition.get("window");
TimiException.requiredTrue(window != null && window.isObject(), "TIER.window 必须是对象");
JsonNode windowType = window.get("type");
TimiException.requiredTrue(windowType != null && windowType.isTextual() && "ROLLING".equals(windowType.asText()), "TIER.window.type 目前只能是 ROLLING");
JsonNode windowAmount = window.get("amount");
TimiException.requiredTrue(windowAmount != null && windowAmount.isIntegralNumber() && 0 < windowAmount.longValue(), "TIER.window.amount invalid");
JsonNode windowUnit = window.get("unit");
TimiException.requiredTrue(windowUnit != null && windowUnit.isTextual() && "YEAR".equals(windowUnit.asText()), "TIER.window.unit 目前只能是 YEAR");
JsonNode tiers = condition.get("tiers");
TimiException.requiredTrue(tiers != null && tiers.isArray() && !tiers.isEmpty(), "TIER.tiers 不能为空");
TimiException.requiredTrue(tiers.size() <= MAX_TIER_COUNT, "TIER.tiers 数量不能超过 %d".formatted(MAX_TIER_COUNT));
Long previousMax = null;
for (int i = 0; i < tiers.size(); i++) {
JsonNode tier = tiers.get(i);
TimiException.requiredTrue(tier != null && tier.isObject(), "TIER.tiers[%d] 必须是对象".formatted(i));
JsonNode minNode = tier.get("min");
TimiException.requiredTrue(minNode != null && minNode.isIntegralNumber() && 0 <= minNode.longValue(), "TIER.tiers[%d].min invalid".formatted(i));
long min = minNode.longValue();
if (i == 0) {
TimiException.requiredTrue(min == 0, "TIER 第一档 min 必须为 0");
} else {
TimiException.requiredTrue(previousMax != null && previousMax < Long.MAX_VALUE && min == previousMax + 1, "TIER 分档必须连续且不能重叠");
}
JsonNode maxNode = tier.get("max");
Long max = null;
if (maxNode != null && !maxNode.isNull()) {
TimiException.requiredTrue(maxNode.isIntegralNumber(), "TIER.tiers[%d].max invalid".formatted(i));
max = maxNode.longValue();
TimiException.requiredTrue(min <= max, "TIER.tiers[%d].min 或 max invalid".formatted(i));
}
if (i < tiers.size() - 1) {
TimiException.requiredTrue(max != null, "除最后一档外 TIER.max 不能为空");
TimiException.requiredTrue(max < Long.MAX_VALUE, "TIER 分档上限过大,无法继续配置下一档");
} else {
TimiException.requiredTrue(max == null, "最后一档 TIER.max 必须为空");
}
JsonNode pointValue = tier.get("pointValue");
TimiException.requiredTrue(pointValue != null && pointValue.isIntegralNumber() && 0 <= pointValue.longValue(), "TIER.tiers[%d].pointValue invalid".formatted(i));
previousMax = max;
}
}
private void verifySourceCondition(JsonNode conditionJson) {
JsonNode condition = conditionJson == null ? null : requireObjectCondition(conditionJson);
Long min = condition == null || condition.get("min") == null || condition.get("min").isNull() ? null : condition.get("min").isIntegralNumber() ? condition.get("min").longValue() : null;
@@ -6,16 +6,16 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoPointLedger;
import com.imyeyu.api.modules.gao.entity.GaoPointRule;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.mapper.GaoPointLedgerMapper;
import com.imyeyu.api.modules.gao.entity.GaoPointLedger;
import com.imyeyu.api.modules.gao.entity.GaoPointRule;
import com.imyeyu.api.modules.gao.mapper.GaoEventRecordMapper;
import com.imyeyu.api.modules.gao.mapper.GaoPointLedgerMapper;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoPointLedgerService;
import com.imyeyu.api.modules.gao.service.GaoPointRuleService;
import com.imyeyu.api.modules.gao.service.GaoPointTriggerService;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.vo.GaoPointAdjustRequest;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
@@ -26,6 +26,9 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -51,26 +54,34 @@ public class GaoPointTriggerServiceImplement implements GaoPointTriggerService {
@Override
public void onEventRecordCreated(GaoEventRecord record) {
TimiException.required(record, "not found event record");
TimiException.required(record.getId(), "not found event record.id");
TimiException.required(record.getStoreId(), "not found record.storeId");
TimiException.required(record.getCustomerId(), "not found record.customerId");
TimiException.required(record.getEventId(), "not found record.eventId");
TimiException.required(record.getRegisteredAt(), "not found record.registeredAt");
List<GaoPointRule> ruleList = ruleService.listActive(record.getStoreId(), record.getEventId(), Time.now());
Long count = null;
long earnedPointValue = 0L;
for (GaoPointRule rule : ruleList) {
Long pointDelta = resolvePointDelta(record, rule, count);
if (pointDelta == null) {
RuleResolution resolution = resolveRule(record, rule, count);
if (resolution == null) {
continue;
}
if (count == null) {
count = eventRecordMapper.count(record.getStoreId(), record.getCustomerId(), record.getEventId(), null, null);
if (rule.getTriggerType() == GaoPointRule.TriggerType.FIRST_TIME || rule.getTriggerType() == GaoPointRule.TriggerType.AFTER_COUNT_EVERY_TIME) {
count = count == null ? count(record) : count;
}
long pointDelta = resolution.pointDelta();
if (0 < pointDelta) {
ledgerService.earn(record, rule, pointDelta, resolution.sourcePayload());
earnedPointValue = Math.addExact(earnedPointValue, pointDelta);
}
JsonNode sourcePayload = sourcePayload(record, rule, pointDelta);
ledgerService.earn(record, rule, pointDelta, sourcePayload);
if (Boolean.TRUE.equals(rule.getExclusive())) {
break;
}
}
record.setEarnedPointValue(earnedPointValue);
eventRecordMapper.updateEarnedPointValue(record.getId(), earnedPointValue);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@@ -104,25 +115,26 @@ public class GaoPointTriggerServiceImplement implements GaoPointTriggerService {
return ledgerService.adjust(request, userLoginService.getRequireLoginUserId());
}
private Long resolvePointDelta(GaoEventRecord record, GaoPointRule rule, Long count) {
private RuleResolution resolveRule(GaoEventRecord record, GaoPointRule rule, Long count) {
return switch (rule.getTriggerType()) {
case EVERY_TIME -> rule.getPointValue();
case EVERY_TIME -> new RuleResolution(rule.getPointValue(), null);
case FIRST_TIME -> {
long currentCount = count == null ? count(record) : count;
yield currentCount == 1 ? rule.getPointValue() : null;
yield currentCount == 1 ? new RuleResolution(rule.getPointValue(), null) : null;
}
case AFTER_COUNT_EVERY_TIME -> {
JsonNode condition = rule.getConditionJson();
long threshold = condition.get("threshold").longValue();
boolean includeCurrent = condition.get("includeCurrent") == null || condition.get("includeCurrent").isNull() || condition.get("includeCurrent").asBoolean();
long currentCount = count == null ? count(record) : count;
yield includeCurrent ? threshold <= currentCount ? rule.getPointValue() : null : threshold < currentCount ? rule.getPointValue() : null;
yield includeCurrent ? threshold <= currentCount ? new RuleResolution(rule.getPointValue(), null) : null : threshold < currentCount ? new RuleResolution(rule.getPointValue(), null) : null;
}
case SOURCE_VALUE -> resolveSourceValue(record, rule);
case CUSTOMER_EVENT_VALUE_TIER -> resolveTier(record, rule);
};
}
private Long resolveSourceValue(GaoEventRecord record, GaoPointRule rule) {
private RuleResolution resolveSourceValue(GaoEventRecord record, GaoPointRule rule) {
if (record.getPointValue() == null) {
return null;
}
@@ -136,17 +148,49 @@ public class GaoPointTriggerServiceImplement implements GaoPointTriggerService {
TimiException.requiredTrue(min == null || min.isNull() || min.longValue() <= pointValue, "pointValue 小于规则最小值");
TimiException.requiredTrue(max == null || max.isNull() || pointValue <= max.longValue(), "pointValue 大于规则最大值");
}
return pointValue;
ObjectNode payload = jackson.createObjectNode();
payload.put("submittedPointValue", pointValue);
payload.put("validatedPointValue", pointValue);
return new RuleResolution(pointValue, payload);
}
private JsonNode sourcePayload(GaoEventRecord record, GaoPointRule rule, long pointDelta) {
if (rule.getTriggerType() != GaoPointRule.TriggerType.SOURCE_VALUE) {
return null;
private RuleResolution resolveTier(GaoEventRecord record, GaoPointRule rule) {
JsonNode condition = rule.getConditionJson();
String sourceEventId = condition.get("sourceEventId").asText();
long amount = condition.get("window").get("amount").longValue();
ZoneId zone = ZoneId.systemDefault();
LocalDate currentDate = Instant.ofEpochMilli(record.getRegisteredAt()).atZone(zone).toLocalDate();
long windowBeginAt = currentDate.minusYears(amount).atStartOfDay(zone).toInstant().toEpochMilli();
long windowEndAt = Math.addExact(record.getRegisteredAt(), 1L);
long sumValue = TimiJava.defaultIfNull(eventRecordMapper.sumNumberValue(record.getStoreId(), record.getCustomerId(), sourceEventId, windowBeginAt, windowEndAt), 0L);
JsonNode matchedTier = null;
for (JsonNode tier : condition.get("tiers")) {
long min = tier.get("min").longValue();
JsonNode maxNode = tier.get("max");
if (min <= sumValue && (maxNode == null || maxNode.isNull() || sumValue <= maxNode.longValue())) {
matchedTier = tier;
break;
}
}
TimiException.required(matchedTier, "TIER 没有匹配的分档");
long pointDelta = matchedTier.get("pointValue").longValue();
ObjectNode payload = jackson.createObjectNode();
payload.put("submittedPointValue", record.getPointValue());
payload.put("validatedPointValue", pointDelta);
return payload;
payload.put("triggerType", GaoPointRule.TriggerType.CUSTOMER_EVENT_VALUE_TIER.name());
payload.put("sourceEventId", sourceEventId);
payload.put("sourceValueField", "numberValue");
payload.put("windowBeginAt", windowBeginAt);
payload.put("windowEndAt", windowEndAt);
payload.put("sumValue", sumValue);
ObjectNode tierPayload = payload.putObject("tier");
tierPayload.put("min", matchedTier.get("min").longValue());
JsonNode maxNode = matchedTier.get("max");
if (maxNode != null && !maxNode.isNull()) {
tierPayload.put("max", maxNode.longValue());
}
tierPayload.put("pointValue", pointDelta);
payload.put("pointDelta", pointDelta);
return new RuleResolution(pointDelta, payload);
}
private long count(GaoEventRecord record) {
@@ -156,4 +200,7 @@ public class GaoPointTriggerServiceImplement implements GaoPointTriggerService {
private String revokeKey(GaoEventRecord record, GaoPointLedger originLedger) {
return "GAO_EVENT_RECORD:%s:LEDGER:%s:REVOKE".formatted(record.getId(), originLedger.getId());
}
private record RuleResolution(Long pointDelta, JsonNode sourcePayload) {
}
}
@@ -0,0 +1,10 @@
ALTER TABLE `gao_event`
ADD COLUMN `value_type` VARCHAR(16) NOT NULL DEFAULT 'NONE' COMMENT '数值类型,NONE 不携带数值,NUMBER 携带整数数值' AFTER `description`,
ADD COLUMN `value_unit` VARCHAR(16) NULL COMMENT '数值单位,CENT 金额分,COUNT 次数' AFTER `value_type`,
ADD COLUMN `require_value` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'true 为登记时必须提交 numberValue' AFTER `value_unit`;
ALTER TABLE `gao_event_record`
ADD COLUMN `point_value` BIGINT NULL COMMENT '本次登记提交的积分值' AFTER `operator_user_id`,
ADD COLUMN `earned_point_value` BIGINT NOT NULL DEFAULT 0 COMMENT '本次登记通过积分规则获得的积分总和' AFTER `point_value`,
ADD COLUMN `number_value` BIGINT NULL COMMENT '本次登记提交的整数业务数值' AFTER `earned_point_value`,
ADD KEY `idx_gao_event_record_value_sum` (`store_id`, `customer_id`, `event_id`, `deleted_at`, `registered_at`);
@@ -26,6 +26,39 @@
AND `deleted_at` IS NULL
</select>
<select id="countByEventIdAndNumberValue" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM `gao_event_record`
WHERE
`event_id` = #{eventId}
AND `number_value` IS NOT NULL
AND `deleted_at` IS NULL
</select>
<select id="sumNumberValue" resultType="java.lang.Long">
SELECT
COALESCE(SUM(`number_value`), 0)
FROM `gao_event_record`
WHERE
`store_id` = #{storeId}
AND `customer_id` = #{customerId}
AND `event_id` = #{eventId}
AND `registered_at` &gt;= #{beginAt}
AND `registered_at` &lt; #{endAt}
AND `deleted_at` IS NULL
</select>
<update id="updateEarnedPointValue">
UPDATE `gao_event_record`
SET
`earned_point_value` = #{earnedPointValue},
`updated_at` = ROUND(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000)
WHERE
`id` = #{id}
AND `deleted_at` IS NULL
</update>
<select id="countByStoreIdAndRegisteredDateValue" resultType="java.lang.Long">
SELECT
COUNT(1)
@@ -10,6 +10,6 @@
AND (`begin_at` IS NULL OR `begin_at` &lt;= #{now})
AND (`end_at` IS NULL OR #{now} &lt;= `end_at`)
AND `deleted_at` IS NULL
ORDER BY `priority` ASC, `created_at` ASC, `id` ASC
ORDER BY `priority`, `created_at`, `id`
</select>
</mapper>