Merge pull request 'v1.0.57' (#69) from dev into master

Reviewed-on: #69
This commit was merged in pull request #69.
This commit is contained in:
2026-10-05 08:10:57 +00:00
19 changed files with 746 additions and 18 deletions
+1 -1
View File
@@ -11,7 +11,7 @@
<groupId>com.imyeyu.timiserverapi</groupId>
<artifactId>TimiServerAPI</artifactId>
<version>1.0.56</version>
<version>1.0.57</version>
<packaging>jar</packaging>
<name>TimiServerAPI</name>
<description>imyeyu.com API</description>
@@ -149,6 +149,17 @@ public class GaoProductController {
productService.disable(id);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.PRODUCT_UPDATE)
@PostMapping("/delete")
public void delete(@RequestParam String id) {
GaoProduct product = productService.get(id);
TimiException.required(product, "not found product");
storeScopeService.checkStoreId(product.getStoreId());
productService.destroy(id);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.PRODUCT_READ)
@@ -221,6 +232,21 @@ public class GaoProductController {
return spec.getId();
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.PRODUCT_UPDATE)
@PostMapping("/spec/update")
public void specUpdate(@RequestBody GaoProductSpec request) {
TimiException.required(request, "not found product spec");
TimiException.required(request.getId(), "not found product spec.id");
String productId = specService.getProductIdBySpecId(request.getId());
TimiException.required(productId, "产品规格不存在");
GaoProduct product = productService.get(productId);
TimiException.required(product, "not found product");
storeScopeService.checkStoreId(product.getStoreId());
specService.updateSpec(request);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.PRODUCT_UPDATE)
@@ -236,6 +262,21 @@ public class GaoProductController {
return value.getId();
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.PRODUCT_UPDATE)
@PostMapping("/spec/value/update")
public void specValueUpdate(@RequestBody GaoProductSpecValue request) {
TimiException.required(request, "not found product spec value");
TimiException.required(request.getId(), "not found product spec value.id");
String productId = specService.getProductIdBySpecValueId(request.getId());
TimiException.required(productId, "产品规格值不存在");
GaoProduct product = productService.get(productId);
TimiException.required(product, "not found product");
storeScopeService.checkStoreId(product.getStoreId());
specService.updateValue(request);
}
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.PRODUCT_READ)
@@ -1,6 +1,7 @@
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;
@@ -77,6 +78,10 @@ public class GaoProductSku extends UUIDEntity {
@Transient
private List<GaoProductSkuUnit> unitList;
/// 基础单位迁移请求,仅用于 SKU 更新,不映射数据库列
@Transient
private GaoProductSkuBaseUnitMigrationRequest baseUnitMigrationRequest;
/// SKU 附件列表
@Transient
private List<Attachment> attachmentList;
@@ -0,0 +1,74 @@
package com.imyeyu.api.modules.gao.mapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
/// 产品编辑、引用检查与单位迁移 Mapper
public interface GaoProductEditMapper {
int countProductReferences(@Param("productId") String productId);
int countSkuReferences(@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);
int updateProductStockRecordSnapshots(@Param("productId") String productId, @Param("productName") String productName);
int updateProductPackageSnapshots(@Param("productId") String productId, @Param("productName") String productName);
int updateProductRedemptionSnapshots(@Param("productId") String productId, @Param("productName") String productName);
int updateSkuOrderSnapshots(@Param("skuId") String skuId, @Param("skuCode") String skuCode,
@Param("skuName") String skuName, @Param("specSummary") String specSummary,
@Param("skuSpecSnapshot") JsonNode skuSpecSnapshot);
int updateSkuFulfillmentSnapshots(@Param("skuId") String skuId, @Param("skuCode") String skuCode,
@Param("skuName") String skuName, @Param("specSummary") String specSummary,
@Param("skuSpecSnapshot") JsonNode skuSpecSnapshot);
int updateSkuStockRecordSnapshots(@Param("skuId") String skuId, @Param("skuCode") String skuCode,
@Param("skuName") String skuName, @Param("specSummary") String specSummary,
@Param("skuSpecSnapshot") JsonNode skuSpecSnapshot);
int updateSkuPackageSnapshots(@Param("skuId") String skuId, @Param("skuCode") String skuCode,
@Param("skuName") String skuName, @Param("specSummary") String specSummary);
int updateSkuRedemptionSnapshots(@Param("skuId") String skuId, @Param("skuCode") String skuCode,
@Param("skuName") String skuName, @Param("skuSpecSnapshot") JsonNode skuSpecSnapshot);
int updateUnitOrderSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName);
int updateUnitFulfillmentSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName);
int updateUnitStockRecordSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName);
int updateUnitPackageSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName);
int updateUnitRedemptionSnapshots(@Param("unitId") String unitId, @Param("unitName") String unitName);
int scaleSkuMinimumStock(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleProductStock(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleSalesOrderItems(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleFulfillmentItems(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scaleStockRecords(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scalePackageConfigItems(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scalePointRedemptions(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
int scalePointRedemptionReturns(@Param("skuId") String skuId, @Param("ratio") BigDecimal ratio);
}
@@ -24,4 +24,7 @@ public interface GaoProductSpecMapper extends BaseMapper<GaoProductSpec, String>
/// 查询规格项所属产品
String selectProductIdBySpecId(@Param("specId") String specId);
/// 更新规格名称和排序
int updateSpec(GaoProductSpec spec);
}
@@ -18,4 +18,7 @@ public interface GaoProductSpecValueMapper extends BaseMapper<GaoProductSpecValu
/// 按规格项查询规格值
List<GaoProductSpecValue> selectBySpecIdList(@Param("specIdList") Collection<String> specIdList);
/// 更新规格值名称和排序
int updateValue(GaoProductSpecValue value);
}
@@ -59,6 +59,9 @@ public interface GaoProductSkuService extends BaseService<GaoProductSku, String>
/// @return SKU 规格结构快照;无规格时返回空数组
JsonNode getSkuSpecSnapshot(GaoProductSku sku);
/// 按当前 SKU 规格资料刷新所有历史快照
void refreshSpecHistorySnapshots(String productId);
/// 停用 SKU
void disable(String id);
}
@@ -17,9 +17,21 @@ public interface GaoProductSpecService {
/// 查询规格项所属产品 ID
String getProductIdBySpecId(String specId);
/// 查询规格值所属产品 ID
String getProductIdBySpecValueId(String specValueId);
/// 创建规格项
void createSpec(GaoProductSpec spec);
/// 修正规格名称和排序
void updateSpec(GaoProductSpec spec);
/// 创建规格值
void createValue(GaoProductSpecValue value);
/// 修正规格值名称和排序
void updateValue(GaoProductSpecValue value);
/// 删除产品下的规格数据,仅用于产品物理删除
void destroyByProductId(String productId);
}
@@ -46,6 +46,8 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
private static final String SMS_TEMPLATE_ID = "2725097";
private static final String ZONE_ID = "Asia/Shanghai";
private static final String INTERNAL_TEMPLATE_NAME = "GaoOrderReminder.ftl";
private static final int MAX_SMS_CUSTOMER_NAME_COUNT = 6;
private static final int MAX_SMS_CUSTOMER_COUNT = 99;
private final GaoOrderReminderMapper mapper;
private final GaoUserMapper gaoUserMapper;
@@ -262,10 +264,15 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
nameMap.putIfAbsent(order.getCustomerId(), displayCustomerName(order.getCustomerName()));
}
List<String> nameList = new ArrayList<>(nameMap.values());
if (nameList.size() <= 2) {
return String.join("、", nameList);
int customerCount = nameList.size();
int displayCount = Math.min(customerCount, MAX_SMS_CUSTOMER_NAME_COUNT);
String customerNames = String.join("、", nameList.subList(0, displayCount));
if (MAX_SMS_CUSTOMER_NAME_COUNT < customerCount) {
String customerCountText = MAX_SMS_CUSTOMER_COUNT < customerCount
? "%d+".formatted(MAX_SMS_CUSTOMER_COUNT) : String.valueOf(customerCount);
return "%s等 %s 位客户".formatted(customerNames, customerCountText);
}
return "%s、%s等 %d 位".formatted(nameList.getFirst(), nameList.get(1), nameList.size());
return customerNames;
}
/// 获取待核销收款金额
@@ -9,7 +9,9 @@ import com.imyeyu.api.modules.gao.entity.GaoProductSpec;
import com.imyeyu.api.modules.gao.entity.GaoProductSpecValue;
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductStock;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.mapper.GaoProductMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductEditMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductStockMapper;
import com.imyeyu.api.modules.gao.service.GaoProductCategoryService;
import com.imyeyu.api.modules.gao.service.GaoProductService;
@@ -17,6 +19,7 @@ import com.imyeyu.api.modules.gao.service.GaoProductSkuService;
import com.imyeyu.api.modules.gao.service.GaoProductSpecService;
import com.imyeyu.api.modules.gao.vo.GaoProductPage;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAuditContext;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.api.util.PinyinUtil;
@@ -38,6 +41,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@@ -50,6 +54,7 @@ import java.util.stream.Collectors;
public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct, String> implements GaoProductService {
private final GaoProductMapper mapper;
private final GaoProductEditMapper editMapper;
private final GaoProductStockMapper stockMapper;
private final AttachmentService attachmentService;
private final ObjectProvider<GaoProductCategoryService> categoryServiceProvider;
@@ -111,7 +116,7 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
super.create(product);
Map<String, String> specValueIdMap = saveSpecs(product, product.getSpecList());
normalizeSkuSpecValueIds(product.getSkuList(), specValueIdMap);
saveSkus(product, product.getSkuList());
saveSkus(product, product.getSkuList(), true);
attachmentService.updateByBizId(Attachment.BizType.GAO_PRODUCT, product.getId(), product.getAttachmentList());
}
@@ -123,6 +128,23 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
TimiException.required(request.getId(), "not found product.id");
GaoProduct product = get(request.getId());
TimiException.required(product, "not found product");
product = mapper.selectForUpdate(product.getId());
TimiException.required(product, "not found product");
String oldName = product.getName();
String storeId = product.getStoreId();
List<GaoProductSku> existingSkuList = skuServiceProvider.getObject().listByProductId(product.getId());
boolean hasHistory = editMapper.countProductReferences(product.getId()) > 0
|| existingSkuList.stream()
.anyMatch(item -> editMapper.countSkuReferences(item.getId()) > 0
|| stockMapper.selectByStoreIdAndSkuIdList(storeId, List.of(item.getId())).stream()
.anyMatch(stock -> isNonZero(stock.getOnHandQuantity()) || isNonZero(stock.getReservedQuantity())));
if (hasHistory && isHistoricalCorrectionOnly(product, request, existingSkuList)) {
OperationAuditContext.skipSuccessAudit();
}
if (hasHistory && (request.getProductType() != null && request.getProductType() != product.getProductType()
|| request.getStockEnabled() != null && !request.getStockEnabled().equals(product.getStockEnabled()))) {
throw new TimiException(TimiCode.ERROR, "产品已有历史业务记录,不能修改产品类型或库存管理属性");
}
if (request.getProductType() == GaoProduct.ProductType.SERVICE && product.getProductType() != GaoProduct.ProductType.SERVICE) {
verifyNoReservedStock(product);
}
@@ -138,13 +160,128 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
prepare(product, product.getId());
super.update(product);
if (request.getSkuList() != null) {
saveSkus(product, request.getSkuList());
saveSkus(product, request.getSkuList(), false);
}
if (!oldName.equals(product.getName())) {
editMapper.updateProductOrderSnapshots(product.getId(), product.getName());
editMapper.updateProductFulfillmentSnapshots(product.getId(), product.getName());
editMapper.updateProductStockRecordSnapshots(product.getId(), product.getName());
editMapper.updateProductPackageSnapshots(product.getId(), product.getName());
editMapper.updateProductRedemptionSnapshots(product.getId(), product.getName());
}
if (request.getAttachmentList() != null) {
attachmentService.updateByBizId(Attachment.BizType.GAO_PRODUCT, product.getId(), request.getAttachmentList());
}
}
private boolean isHistoricalCorrectionOnly(GaoProduct current, GaoProduct request, List<GaoProductSku> currentSkuList) {
if (!Objects.equals(current.getCategoryId(), request.getCategoryId())
|| TimiJava.defaultIfNull(request.getProductType(), current.getProductType()) != current.getProductType()
|| !Objects.equals(TimiJava.defaultIfNull(request.getStockEnabled(), current.getStockEnabled()), current.getStockEnabled())
|| TimiJava.defaultIfNull(request.getStatus(), current.getStatus()) != current.getStatus()
|| !Objects.equals(TimiJava.defaultIfNull(request.getSort(), current.getSort()), current.getSort())
|| !sameText(current.getRemark(), request.getRemark())) {
return false;
}
if (request.getAttachmentList() != null && !sameAttachmentList(
attachmentService.listByBizId(Attachment.BizType.GAO_PRODUCT, current.getId()), request.getAttachmentList())) {
return false;
}
if (request.getSkuList() == null) {
return true;
}
if (request.getSkuList().size() != currentSkuList.size()) {
return false;
}
Map<String, GaoProductSku> currentById = currentSkuList.stream()
.collect(Collectors.toMap(GaoProductSku::getId, item -> item));
Set<String> requestedIdSet = new HashSet<>();
for (GaoProductSku requested : request.getSkuList()) {
GaoProductSku existing = requested.getId() == null ? null : currentById.get(requested.getId());
if (existing == null || !requestedIdSet.add(requested.getId())
|| !isHistoricalSkuCorrectionOnly(existing, requested)) {
return false;
}
}
return true;
}
private boolean isHistoricalSkuCorrectionOnly(GaoProductSku current, GaoProductSku request) {
if (!Objects.equals(normalizeText(current.getBarcode()), normalizeText(request.getBarcode()))
|| !Objects.equals(TimiJava.defaultIfNull(request.getStockEnabled(), current.getStockEnabled()), current.getStockEnabled())
|| !Objects.equals(TimiJava.defaultIfNull(request.getAllowDecimalQuantity(), current.getAllowDecimalQuantity()), current.getAllowDecimalQuantity())
|| !Objects.equals(current.getMinStockQuantity(), request.getMinStockQuantity())
|| 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;
}
List<String> currentSpecValueIdList = current.getSpecValueIdList();
List<String> requestSpecValueIdList = request.getSpecValueIdList();
if (requestSpecValueIdList != null && !new HashSet<>(currentSpecValueIdList).equals(new HashSet<>(requestSpecValueIdList))) {
return false;
}
return request.getUnitList() == null || isHistoricalUnitNameCorrectionOnly(current.getUnitList(), request.getUnitList());
}
private boolean isHistoricalUnitNameCorrectionOnly(List<GaoProductSkuUnit> currentList, List<GaoProductSkuUnit> requestList) {
if (requestList.size() != currentList.size()) {
return false;
}
Map<String, GaoProductSkuUnit> currentById = currentList.stream()
.collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item));
Set<String> requestedIdSet = new HashSet<>();
for (GaoProductSkuUnit requested : requestList) {
GaoProductSkuUnit existing = requested.getId() == null ? null : currentById.get(requested.getId());
if (existing == null || !requestedIdSet.add(requested.getId())
|| !Objects.equals(existing.getBaseQuantityPerUnit(), requested.getBaseQuantityPerUnit())
|| !Objects.equals(existing.getSalePrice(), requested.getSalePrice())
|| !Objects.equals(existing.getIsBase(), requested.getIsBase())
|| !Objects.equals(existing.getAllowPurchase(), requested.getAllowPurchase())
|| !Objects.equals(existing.getAllowSale(), requested.getAllowSale())
|| !Objects.equals(existing.getSort(), requested.getSort())) {
return false;
}
}
return true;
}
private boolean sameAttachmentList(List<Attachment> currentList, List<Attachment> requestList) {
if (currentList == null || requestList == null || currentList.size() != requestList.size()) {
return false;
}
for (int index = 0; index < currentList.size(); index++) {
Attachment current = currentList.get(index);
Attachment requested = requestList.get(index);
if (!Objects.equals(current.getId(), requested.getId())
|| !Objects.equals(current.getBizType(), requested.getBizType())
|| !Objects.equals(current.getBizId(), requested.getBizId())
|| !Objects.equals(current.getAttachType(), requested.getAttachType())
|| !Objects.equals(current.getMongoId(), requested.getMongoId())
|| !Objects.equals(current.getTitle(), requested.getTitle())
|| !Objects.equals(current.getName(), requested.getName())
|| !Objects.equals(current.getMimeType(), requested.getMimeType())
|| !Objects.equals(current.getMetadata(), requested.getMetadata())
|| !Objects.equals(current.getSize(), requested.getSize())
|| !Objects.equals(current.getMd5(), requested.getMd5())
|| !Objects.equals(current.getIsDestroyed(), requested.getIsDestroyed())
|| !Objects.equals(current.getDestroyAt(), requested.getDestroyAt())) {
return false;
}
}
return true;
}
private boolean sameText(String current, String request) {
return Objects.equals(normalizeText(current), normalizeText(request));
}
private String normalizeText(String value) {
return value == null ? null : value.trim();
}
private void verifyNoReservedStock(GaoProduct product) {
List<String> skuIdList = skuServiceProvider.getObject().listByProductId(product.getId()).stream()
.map(GaoProductSku::getId)
@@ -158,6 +295,10 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
TimiException.requiredTrue(!hasReservedStock, "当前产品存在预占库存,不能切换为服务产品,请先完成或取消相关订单");
}
private boolean isNonZero(BigDecimal value) {
return value != null && BigDecimal.ZERO.compareTo(value) != 0;
}
@OperationAudit(AuditOperation.GAO_PRODUCT_DISABLE)
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
@@ -177,8 +318,17 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
}
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void destroy(String id) {
throw new TimiException(TimiCode.ERROR, "已建立产品库的产品不允许物理删除");
GaoProduct product = mapper.selectForUpdate(id);
TimiException.required(product, "not found product");
TimiException.requiredTrue(editMapper.countProductReferences(id) == 0, "产品存在历史业务记录,不能物理移除");
for (GaoProductSku sku : skuServiceProvider.getObject().listByProductId(id)) {
skuServiceProvider.getObject().destroy(sku.getId());
}
specServiceProvider.getObject().destroyByProductId(id);
attachmentService.updateByBizId(Attachment.BizType.GAO_PRODUCT, id, List.of());
super.destroy(id);
}
private void prepare(GaoProduct product, String excludeId) {
@@ -201,18 +351,35 @@ public class GaoProductServiceImplement extends AbstractEntityService<GaoProduct
product.setUpdatedBy(userLoginService.getRequireLoginUserId());
}
private void saveSkus(GaoProduct product, List<com.imyeyu.api.modules.gao.entity.GaoProductSku> skuList) {
private void saveSkus(GaoProduct product, List<com.imyeyu.api.modules.gao.entity.GaoProductSku> skuList, boolean createDefault) {
List<com.imyeyu.api.modules.gao.entity.GaoProductSku> sourceList = skuList;
if (sourceList == null || sourceList.isEmpty()) {
if ((sourceList == null || sourceList.isEmpty()) && createDefault) {
com.imyeyu.api.modules.gao.entity.GaoProductSku sku = new com.imyeyu.api.modules.gao.entity.GaoProductSku();
sku.setProductId(product.getId()); sku.setCode(product.getCode()); sku.setName(product.getName());
com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit unit = new com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit();
unit.setName("件"); unit.setIsBase(true); unit.setBaseQuantityPerUnit(BigDecimal.ONE);
sku.setUnitList(List.of(unit)); sourceList = List.of(sku);
} else if (sourceList == null) {
sourceList = List.of();
}
List<com.imyeyu.api.modules.gao.entity.GaoProductSku> existingList = skuServiceProvider.getObject().listByProductId(product.getId());
Map<String, com.imyeyu.api.modules.gao.entity.GaoProductSku> existingById = existingList.stream()
.collect(Collectors.toMap(com.imyeyu.api.modules.gao.entity.GaoProductSku::getId, item -> item));
Set<String> retainedIdSet = new HashSet<>();
for (com.imyeyu.api.modules.gao.entity.GaoProductSku source : sourceList) {
source.setProductId(product.getId());
if (source.getId() == null) skuServiceProvider.getObject().create(source); else skuServiceProvider.getObject().update(source);
if (source.getId() == null) {
skuServiceProvider.getObject().create(source);
} else {
TimiException.required(existingById.get(source.getId()), "SKU 不存在或不属于当前产品");
retainedIdSet.add(source.getId());
skuServiceProvider.getObject().update(source);
}
}
for (com.imyeyu.api.modules.gao.entity.GaoProductSku existing : existingList) {
if (!retainedIdSet.contains(existing.getId())) {
skuServiceProvider.getObject().destroy(existing.getId());
}
}
}
@@ -11,16 +11,22 @@ import com.imyeyu.api.modules.gao.entity.GaoProduct;
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuSpecValue;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.entity.GaoProductStock;
import com.imyeyu.api.modules.gao.entity.GaoProductSpec;
import com.imyeyu.api.modules.gao.entity.GaoProductSpecValue;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductEditMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductStockMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuSpecValueMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSpecMapper;
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.vo.GaoProductSkuBaseUnitMigrationRequest;
import com.imyeyu.api.modules.gao.vo.GaoProductSkuUnitSelection;
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;
@@ -55,11 +61,14 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
private static final BigDecimal ONE = BigDecimal.ONE;
private final GaoProductSkuMapper mapper;
private final GaoProductEditMapper editMapper;
private final GaoProductStockMapper stockMapper;
private final GaoProductSkuUnitMapper unitMapper;
private final GaoProductSkuSpecValueMapper skuSpecValueMapper;
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;
@@ -190,6 +199,19 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
return result;
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void refreshSpecHistorySnapshots(String productId) {
TimiException.required(productId, "not found productId");
for (GaoProductSku sku : mapper.selectByProductId(productId)) {
JsonNode snapshot = getSkuSpecSnapshot(sku);
editMapper.updateSkuOrderSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), snapshot);
editMapper.updateSkuFulfillmentSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), snapshot);
editMapper.updateSkuStockRecordSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), snapshot);
editMapper.updateSkuRedemptionSnapshots(sku.getId(), sku.getCode(), sku.getName(), snapshot);
}
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(GaoProductSku sku) {
@@ -205,8 +227,32 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
public void update(GaoProductSku request) {
TimiException.required(request, "not found product sku");
TimiException.required(request.getId(), "not found product sku.id");
GaoProductSku sku = get(request.getId());
GaoProductSku sku = mapper.selectForUpdate(request.getId());
TimiException.required(sku, "not found product sku");
List<GaoProductSkuUnit> existingUnitList = unitMapper.selectBySkuId(sku.getId());
int referenceCount = editMapper.countSkuReferences(sku.getId());
List<String> existingSpecValueIds = currentSpecValueIds(sku.getId());
if (referenceCount > 0 && request.getSpecValueIdList() != null
&& !new HashSet<>(existingSpecValueIds).equals(new HashSet<>(request.getSpecValueIdList()))) {
throw new TimiException(TimiCode.ERROR, "SKU 已有历史业务记录,不能更换规格组合;请新建 SKU");
}
if (referenceCount > 0 && request.getStockEnabled() != null && !request.getStockEnabled().equals(sku.getStockEnabled())) {
throw new TimiException(TimiCode.ERROR, "SKU 已有历史业务记录,不能修改库存管理属性");
}
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) {
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);
}
sku.setCode(TimiJava.defaultIfNull(request.getCode(), sku.getCode()));
sku.setBarcode(request.getBarcode());
sku.setName(TimiJava.defaultIfNull(request.getName(), sku.getName()));
@@ -218,18 +264,49 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
sku.setSort(TimiJava.defaultIfNull(request.getSort(), sku.getSort()));
sku.setRemark(request.getRemark());
sku.setSpecValueIdList(request.getSpecValueIdList() == null ? currentSpecValueIds(sku.getId()) : request.getSpecValueIdList());
sku.setUnitList(request.getUnitList() == null ? unitMapper.selectBySkuId(sku.getId()) : request.getUnitList());
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) {
saveSpecValues(sku.getId(), sku.getSpecValueIdList());
}
if (request.getUnitList() != null) {
saveUnits(sku.getId(), sku.getUnitList(), unitMapper.selectBySkuId(sku.getId()));
saveUnits(sku.getId(), sku.getUnitList(), existingUnitList);
}
if (request.getAttachmentList() != null) {
attachmentService.updateByBizId(Attachment.BizType.GAO_PRODUCT_SKU, sku.getId(), request.getAttachmentList());
}
JsonNode skuSpecSnapshot = getSkuSpecSnapshot(sku);
editMapper.updateSkuOrderSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), skuSpecSnapshot);
editMapper.updateSkuFulfillmentSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), skuSpecSnapshot);
editMapper.updateSkuStockRecordSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary(), skuSpecSnapshot);
editMapper.updateSkuPackageSnapshots(sku.getId(), sku.getCode(), sku.getName(), sku.getSpecSummary());
editMapper.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)
@@ -249,8 +326,24 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
}
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void destroy(String id) {
throw new TimiException(TimiCode.ERROR, "已建立 SKU 的产品不允许物理删除");
GaoProductSku sku = mapper.selectForUpdate(id);
TimiException.required(sku, "not found product sku");
TimiException.requiredTrue(editMapper.countSkuReferences(id) == 0, "SKU 存在历史业务记录,不能物理移除");
List<GaoProductStock> stockList = stockMapper.selectByStoreIdAndSkuIdList(sku.getStoreId(), List.of(id));
TimiException.requiredTrue(stockList.stream().allMatch(stock -> isZero(stock.getOnHandQuantity()) && isZero(stock.getReservedQuantity())),
"SKU 存在库存或预占库存,不能物理移除");
for (GaoProductSkuUnit unit : unitMapper.selectBySkuId(id)) {
TimiException.requiredTrue(editMapper.countUnitReferences(unit.getId()) == 0, "SKU 单位存在历史业务引用,不能物理移除 SKU");
unitMapper.destroy(unit.getId());
}
skuSpecValueMapper.deleteBySkuId(id);
for (GaoProductStock stock : stockList) {
stockMapper.destroy(stock.getId());
}
attachmentService.updateByBizId(Attachment.BizType.GAO_PRODUCT_SKU, id, List.of());
super.destroy(id);
}
private void prepare(GaoProductSku sku, String excludeId) {
@@ -326,6 +419,7 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
unit.setBaseQuantityPerUnit(TimiJava.defaultIfNull(source.getBaseQuantityPerUnit(), ONE));
TimiException.requiredTrue(0 < unit.getBaseQuantityPerUnit().signum(), "基础单位数量系数必须大于 0");
TimiException.requiredTrue(6 >= unit.getBaseQuantityPerUnit().scale(), "基础单位数量系数最多保留六位小数");
TimiException.requiredTrue(12 >= unit.getBaseQuantityPerUnit().precision() - unit.getBaseQuantityPerUnit().scale(), "基础单位数量系数超出最大值");
if (source.getSalePrice() != null) {
TimiException.requiredTrue(0 <= source.getSalePrice(), "单位建议售价不能为负数");
}
@@ -345,6 +439,69 @@ 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,
List<GaoProductSkuUnit> existingUnitList) {
Map<String, GaoProductSkuUnit> existingById = existingUnitList.stream()
.collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item));
for (GaoProductSkuUnit requested : requestedUnitList) {
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, "已保存单位的换算系数不能直接修改;切换基础单位时请提交迁移比例");
}
}
}
private boolean isZero(BigDecimal value) {
return value == null || BigDecimal.ZERO.compareTo(value) == 0;
}
private void saveUnits(String skuId, List<GaoProductSkuUnit> unitList, List<GaoProductSkuUnit> existingUnitList) {
Map<String, GaoProductSkuUnit> existingById = existingUnitList.stream().collect(Collectors.toMap(GaoProductSkuUnit::getId, item -> item));
Set<String> retainedIdSet = new HashSet<>();
@@ -368,10 +525,21 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
} else {
retainedIdSet.add(existing.getId());
TimiException.requiredTrue(1 == unitMapper.updateUnit(unit), "SKU 单位更新失败");
if (!existing.getName().equals(unit.getName())) {
editMapper.updateUnitOrderSnapshots(existing.getId(), unit.getName());
editMapper.updateUnitFulfillmentSnapshots(existing.getId(), unit.getName());
editMapper.updateUnitStockRecordSnapshots(existing.getId(), unit.getName());
editMapper.updateUnitPackageSnapshots(existing.getId(), unit.getName());
editMapper.updateUnitRedemptionSnapshots(existing.getId(), unit.getName());
}
}
}
for (GaoProductSkuUnit existing : existingUnitList) {
if (!retainedIdSet.contains(existing.getId())) {
TimiException.requiredTrue(editMapper.countUnitReferences(existing.getId()) == 0, "SKU 单位存在历史业务引用,不能物理移除");
unitMapper.destroy(existing.getId());
}
}
TimiException.requiredTrue(existingUnitList.stream().allMatch(existing -> retainedIdSet.contains(existing.getId())),
"已保存的 SKU 单位不能删除,请关闭允许销售和允许采购");
}
private void saveSpecValues(String skuId, List<String> specValueIdList) {
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.gao.service.implement;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.gao.entity.GaoProduct;
import com.imyeyu.api.modules.gao.entity.GaoProductSpec;
import com.imyeyu.api.modules.gao.entity.GaoProductSpecValue;
@@ -7,10 +8,13 @@ import com.imyeyu.api.modules.gao.mapper.GaoProductSpecMapper;
import com.imyeyu.api.modules.gao.mapper.GaoProductSpecValueMapper;
import com.imyeyu.api.modules.gao.service.GaoProductService;
import com.imyeyu.api.modules.gao.service.GaoProductSpecService;
import com.imyeyu.api.modules.gao.service.GaoProductSkuService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
@@ -27,6 +31,7 @@ public class GaoProductSpecServiceImplement implements GaoProductSpecService {
private final GaoProductSpecMapper specMapper;
private final GaoProductSpecValueMapper valueMapper;
private final GaoProductService productService;
private final ObjectProvider<GaoProductSkuService> skuServiceProvider;
@Override
public List<GaoProductSpec> listByProductId(String productId) {
@@ -41,6 +46,12 @@ public class GaoProductSpecServiceImplement implements GaoProductSpecService {
return specMapper.selectProductIdBySpecId(specId);
}
@Override
public String getProductIdBySpecValueId(String specValueId) {
GaoProductSpecValue value = valueMapper.selectById(specValueId);
return value == null ? null : specMapper.selectProductIdBySpecId(value.getSpecId());
}
@Override
public void createSpec(GaoProductSpec spec) {
TimiException.required(spec, "not found product spec");
@@ -51,6 +62,28 @@ public class GaoProductSpecServiceImplement implements GaoProductSpecService {
specMapper.insert(spec);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void updateSpec(GaoProductSpec request) {
TimiException.required(request, "not found product spec");
TimiException.required(request.getId(), "not found product spec.id");
String productId = specMapper.selectProductIdBySpecId(request.getId());
TimiException.required(productId, "产品规格不存在");
GaoProductSpec existing = specMapper.selectByProductId(productId).stream()
.filter(item -> item.getId().equals(request.getId())).findFirst().orElseThrow();
String name = requiredText(request.getName(), "规格名称不能为空");
Integer sort = TimiJava.defaultIfNull(request.getSort(), existing.getSort());
if (existing.getName().equals(name) && existing.getSort().equals(sort)) {
return;
}
GaoProductSpec spec = new GaoProductSpec();
spec.setId(request.getId());
spec.setName(name);
spec.setSort(sort);
TimiException.requiredTrue(1 == specMapper.updateSpec(spec), "产品规格更新失败");
skuServiceProvider.getObject().refreshSpecHistorySnapshots(productId);
}
@Override
public void createValue(GaoProductSpecValue value) {
TimiException.required(value, "not found product spec value");
@@ -61,5 +94,40 @@ public class GaoProductSpecServiceImplement implements GaoProductSpecService {
valueMapper.insert(value);
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void updateValue(GaoProductSpecValue request) {
TimiException.required(request, "not found product spec value");
TimiException.required(request.getId(), "not found product spec value.id");
GaoProductSpecValue existing = valueMapper.selectById(request.getId());
TimiException.required(existing, "产品规格值不存在");
String productId = specMapper.selectProductIdBySpecId(existing.getSpecId());
TimiException.required(productId, "产品规格不存在");
String name = requiredText(request.getName(), "规格值名称不能为空");
Integer sort = TimiJava.defaultIfNull(request.getSort(), existing.getSort());
if (existing.getName().equals(name) && existing.getSort().equals(sort)) {
return;
}
GaoProductSpecValue value = new GaoProductSpecValue();
value.setId(existing.getId());
value.setSpecId(existing.getSpecId());
value.setName(name);
value.setSort(sort);
TimiException.requiredTrue(1 == valueMapper.updateValue(value), "产品规格值更新失败");
skuServiceProvider.getObject().refreshSpecHistorySnapshots(productId);
}
@Override
public void destroyByProductId(String productId) {
List<GaoProductSpec> specList = specMapper.selectByProductId(productId);
List<String> specIdList = specList.stream().map(GaoProductSpec::getId).toList();
for (GaoProductSpecValue value : valueMapper.selectBySpecIdList(specIdList)) {
valueMapper.destroy(value.getId());
}
for (GaoProductSpec spec : specList) {
specMapper.destroy(spec.getId());
}
}
private String requiredText(String value, String message) { TimiException.required(value, message); String result = value.trim(); TimiException.requiredTrue(!result.isEmpty(), message); return result; }
}
@@ -0,0 +1,19 @@
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;
}
@@ -42,12 +42,15 @@ public class OperationAuditAspect {
Logger logger = new Logger(operation.getModule(), operation.name());
logger.setContent(payloadSerializer.serializeArguments(arguments));
long startNanos = System.nanoTime();
boolean previousAuditState = OperationAuditContext.begin();
try {
Object result = joinPoint.proceed();
logger.setLevel(Logger.Level.INFO);
logger.setResult(payloadSerializer.serializeResult(result, arguments));
logger.setDuration(duration(startNanos));
record(logger);
if (!OperationAuditContext.isSuccessAuditSkipped()) {
record(logger);
}
return result;
} catch (TimiException e) {
logger.setLevel(Logger.Level.WARN);
@@ -62,6 +65,8 @@ public class OperationAuditAspect {
log.error("业务操作失败: {}", operation.name(), e);
record(logger);
throw e;
} finally {
OperationAuditContext.end(previousAuditState);
}
}
@@ -0,0 +1,45 @@
package com.imyeyu.api.modules.system.audit;
/// 当前线程中的操作审计上下文
///
/// @author Codex
/// @since 2026-09-30
public final class OperationAuditContext {
private static final ThreadLocal<Boolean> SKIP_SUCCESS_AUDIT = ThreadLocal.withInitial(() -> false);
private OperationAuditContext() {
}
/// 开始一次审计操作并返回外层状态
///
/// @return 外层是否跳过成功审计
public static boolean begin() {
boolean previous = SKIP_SUCCESS_AUDIT.get();
SKIP_SUCCESS_AUDIT.set(false);
return previous;
}
/// 跳过当前操作的成功审计
public static void skipSuccessAudit() {
SKIP_SUCCESS_AUDIT.set(true);
}
/// 判断当前操作是否跳过成功审计
///
/// @return 是否跳过
public static boolean isSuccessAuditSkipped() {
return SKIP_SUCCESS_AUDIT.get();
}
/// 恢复外层审计状态
///
/// @param previous 外层是否跳过成功审计
public static void end(boolean previous) {
if (previous) {
SKIP_SUCCESS_AUDIT.set(true);
} else {
SKIP_SUCCESS_AUDIT.remove();
}
}
}
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoProductEditMapper">
<select id="countProductReferences" resultType="int">
SELECT
(SELECT COUNT(*) FROM `gao_sales_order_item` WHERE `product_id_snapshot` = #{productId}) +
(SELECT COUNT(*) FROM `gao_order_fulfillment_item` WHERE `product_id_snapshot` = #{productId}) +
(SELECT COUNT(*) FROM `gao_product_stock_record` WHERE `product_id_snapshot` = #{productId}) +
(SELECT COUNT(*) FROM `gao_package_config_item` WHERE `product_id_snapshot` = #{productId}) +
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `product_id_snapshot` = #{productId})
</select>
<select id="countSkuReferences" resultType="int">
SELECT
(SELECT COUNT(*) FROM `gao_sales_order_item` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_order_fulfillment_item` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_product_stock_record` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_package_config_item` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_point_redeem_sku` WHERE `sku_id` = #{skuId}) +
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_id_snapshot` = #{skuId})
</select>
<select id="countUnitReferences" resultType="int">
SELECT
(SELECT COUNT(*) FROM `gao_sales_order_item` WHERE `sku_unit_id` = #{unitId}) +
(SELECT COUNT(*) FROM `gao_order_fulfillment_item` WHERE `sku_unit_id` = #{unitId}) +
(SELECT COUNT(*) FROM `gao_product_stock_record` WHERE `sku_unit_id` = #{unitId}) +
(SELECT COUNT(*) FROM `gao_package_config_item` WHERE `sku_unit_id` = #{unitId}) +
(SELECT COUNT(*) FROM `gao_point_redeem_sku` WHERE `sku_unit_id` = #{unitId}) +
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_unit_id_snapshot` = #{unitId})
</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>
<update id="updateProductPackageSnapshots">UPDATE `gao_package_config_item` SET `product_name_snapshot`=#{productName} WHERE `product_id_snapshot`=#{productId}</update>
<update id="updateProductRedemptionSnapshots">UPDATE `gao_point_redemption` SET `product_name_snapshot`=#{productName} WHERE `product_id_snapshot`=#{productId}</update>
<update id="updateSkuOrderSnapshots">UPDATE `gao_sales_order_item` SET `sku_code_snapshot`=#{skuCode}, `sku_name_snapshot`=#{skuName}, `spec_summary_snapshot`=#{specSummary}, `sku_spec_snapshot`=#{skuSpecSnapshot} WHERE `sku_id`=#{skuId}</update>
<update id="updateSkuFulfillmentSnapshots">UPDATE `gao_order_fulfillment_item` SET `sku_code_snapshot`=#{skuCode}, `sku_name_snapshot`=#{skuName}, `spec_summary_snapshot`=#{specSummary}, `sku_spec_snapshot`=#{skuSpecSnapshot} WHERE `sku_id`=#{skuId}</update>
<update id="updateSkuStockRecordSnapshots">UPDATE `gao_product_stock_record` SET `sku_code_snapshot`=#{skuCode}, `sku_name_snapshot`=#{skuName}, `spec_summary_snapshot`=#{specSummary}, `sku_spec_snapshot`=#{skuSpecSnapshot} WHERE `sku_id`=#{skuId}</update>
<update id="updateSkuPackageSnapshots">UPDATE `gao_package_config_item` SET `sku_code_snapshot`=#{skuCode}, `sku_name_snapshot`=#{skuName}, `spec_summary_snapshot`=#{specSummary} WHERE `sku_id`=#{skuId}</update>
<update id="updateSkuRedemptionSnapshots">UPDATE `gao_point_redemption` SET `sku_code_snapshot`=#{skuCode}, `sku_name_snapshot`=#{skuName}, `sku_spec_snapshot`=#{skuSpecSnapshot} WHERE `sku_id_snapshot`=#{skuId}</update>
<update id="updateUnitOrderSnapshots">UPDATE `gao_sales_order_item` SET `unit_snapshot`=#{unitName} WHERE `sku_unit_id`=#{unitId}</update>
<update id="updateUnitFulfillmentSnapshots">UPDATE `gao_order_fulfillment_item` SET `unit_snapshot`=#{unitName} WHERE `sku_unit_id`=#{unitId}</update>
<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>
@@ -5,4 +5,5 @@
<select id="selectByProductIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoProductSpec">SELECT * FROM `gao_product_spec` WHERE `deleted_at` IS NULL <choose><when test="productIdList != null and !productIdList.isEmpty()">AND `product_id` IN <foreach collection="productIdList" item="id" open="(" separator="," close=")">#{id}</foreach></when><otherwise>AND FALSE</otherwise></choose> ORDER BY `product_id`, `sort`, `created_at`</select>
<select id="selectProductIdBySpecValueId" resultType="string">SELECT `s`.`product_id` FROM `gao_product_spec_value` `v` INNER JOIN `gao_product_spec` `s` ON `s`.`id`=`v`.`spec_id` AND `s`.`deleted_at` IS NULL WHERE `v`.`id`=#{specValueId} AND `v`.`deleted_at` IS NULL</select>
<select id="selectProductIdBySpecId" resultType="string">SELECT `product_id` FROM `gao_product_spec` WHERE `id`=#{specId} AND `deleted_at` IS NULL</select>
<update id="updateSpec">UPDATE `gao_product_spec` SET `name`=#{name},`sort`=#{sort},`updated_at`=FLOOR(UNIX_TIMESTAMP(NOW(3))*1000) WHERE `id`=#{id} AND `deleted_at` IS NULL</update>
</mapper>
@@ -3,4 +3,5 @@
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoProductSpecValueMapper">
<select id="selectById" resultType="com.imyeyu.api.modules.gao.entity.GaoProductSpecValue">SELECT * FROM `gao_product_spec_value` WHERE `id` = #{id} AND `deleted_at` IS NULL</select>
<select id="selectBySpecIdList" resultType="com.imyeyu.api.modules.gao.entity.GaoProductSpecValue">SELECT * FROM `gao_product_spec_value` WHERE `deleted_at` IS NULL <choose><when test="specIdList != null and !specIdList.isEmpty()">AND `spec_id` IN <foreach collection="specIdList" item="id" open="(" separator="," close=")">#{id}</foreach></when><otherwise>AND FALSE</otherwise></choose> ORDER BY `spec_id`, `sort`, `created_at`</select>
<update id="updateValue">UPDATE `gao_product_spec_value` SET `name`=#{name},`sort`=#{sort},`updated_at`=FLOOR(UNIX_TIMESTAMP(NOW(3))*1000) WHERE `id`=#{id} AND `deleted_at` IS NULL</update>
</mapper>
@@ -1,5 +1,4 @@
<div class="gao-order-reminder">
<h2>订单状态提醒</h2>
<p>以下订单存在待处理事项,请及时处理。</p>
<#list customerList as customer>
<h3>客户:${customer.name?html}</h3>