feat: recycle system
This commit is contained in:
@@ -56,10 +56,14 @@ public class Attachment extends UUIDEntity {
|
||||
|
||||
GAO_POINT_REDEMPTION_RETURN,
|
||||
|
||||
GAO_RECYCLE_ITEM,
|
||||
|
||||
GAO_RECYCLE_EXCHANGE,
|
||||
|
||||
GAO_RECYCLE_EXCHANGE_REVOKE,
|
||||
|
||||
GAO_RECYCLE_PAYMENT,
|
||||
|
||||
GAO_CUSTOMER_FOLLOW_UP_REMINDER,
|
||||
|
||||
GAO_DATA_EXPORT,
|
||||
|
||||
@@ -89,10 +89,12 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
|
||||
|
||||
SALES_ORDER_CANCEL("SALES_ORDER:CANCEL", "销售订单取消", true, true),
|
||||
|
||||
SALES_ORDER_PRICE_OVERRIDE("SALES_ORDER:PRICE_OVERRIDE", "销售订单价格修改", true, true),
|
||||
SALES_ORDER_PRICE_OVERRIDE("SALES_ORDER:PRICE_OVERRIDE", "订单交易条件调整", true, true),
|
||||
|
||||
ORDER_FULFILLMENT_CREATE("ORDER_FULFILLMENT:CREATE", "统一履约创建", true, true),
|
||||
|
||||
ORDER_FULFILLMENT_UNSETTLED("ORDER_FULFILLMENT:UNSETTLED", "订单未结清履约", true, true),
|
||||
|
||||
ORDER_FULFILLMENT_READ("ORDER_FULFILLMENT:READ", "统一履约读取", true, true),
|
||||
|
||||
ORDER_FULFILLMENT_VERIFY("ORDER_FULFILLMENT:VERIFY", "统一履约核销", true, true),
|
||||
@@ -119,15 +121,15 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
|
||||
|
||||
CUSTOMER_PACKAGE_GIFT_CREATE("CUSTOMER_PACKAGE:GIFT_CREATE", "客户套餐创建赠送", true, true),
|
||||
|
||||
FUND_RECORD_READ("FUND_RECORD:READ", "资金流水读取", true, true),
|
||||
FUND_RECORD_READ("FUND_RECORD:READ", "支付记录读取", true, true),
|
||||
|
||||
FUND_RECEIVE_CREATE("FUND_RECEIVE:CREATE", "线下收款创建", true, true),
|
||||
FUND_RECEIVE_CREATE("FUND_RECEIVE:CREATE", "支付登记", true, true),
|
||||
|
||||
FUND_RECEIVE_VERIFY("FUND_RECEIVE:VERIFY", "线下收款核销", true, true),
|
||||
FUND_RECEIVE_VERIFY("FUND_RECEIVE:VERIFY", "支付核销", true, true),
|
||||
|
||||
FUND_REFUND("FUND:REFUND", "套餐退款", true, true),
|
||||
|
||||
FUND_REVOKE("FUND:REVOKE", "资金流水冲正", true, true),
|
||||
FUND_REVOKE("FUND:REVOKE", "支付冲正", true, true),
|
||||
|
||||
POINT_ACCOUNT_READ("POINT_ACCOUNT:READ", "客户积分账户读取", true, true),
|
||||
|
||||
@@ -155,17 +157,9 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
|
||||
|
||||
RECYCLE_EXCHANGE_CONFIG_MANAGE("RECYCLE_EXCHANGE:CONFIG_MANAGE", "回收兑换配置管理", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_QUERY("RECYCLE_EXCHANGE:QUERY", "回收兑换查询", true, true),
|
||||
RECYCLE_ACCOUNT_READ("RECYCLE_ACCOUNT:READ", "回收物额度查询", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_CREATE("RECYCLE_EXCHANGE:CREATE", "回收兑换创建", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_QUANTITY_ADJUST("RECYCLE_EXCHANGE:QUANTITY_ADJUST", "回收兑换数量调整", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_VERIFY("RECYCLE_EXCHANGE:VERIFY", "回收兑换核销", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_CANCEL("RECYCLE_EXCHANGE:CANCEL", "回收兑换撤销", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_REVOKE("RECYCLE_EXCHANGE:REVOKE", "回收兑换冲正", true, true),
|
||||
RECYCLE_ACCOUNT_ADJUST("RECYCLE_ACCOUNT:ADJUST", "回收物额度调整", true, true),
|
||||
|
||||
STAT_READ("STAT:READ", "统计读取", false, false),
|
||||
|
||||
|
||||
+37
-8
@@ -3,12 +3,16 @@ package com.imyeyu.api.modules.gao.controller;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.bean.PermissionMatchMode;
|
||||
import com.imyeyu.api.bean.ModuleCode;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
|
||||
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentActionRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest;
|
||||
@@ -48,6 +52,8 @@ import java.util.stream.Stream;
|
||||
public class GaoOrderFulfillmentController {
|
||||
|
||||
private final GaoOrderFulfillmentService service;
|
||||
private final GaoSalesOrderService salesOrderService;
|
||||
private final PermissionChecker permissionChecker;
|
||||
private final GaoStoreScopeService storeScopeService;
|
||||
private final AttachmentService attachmentService;
|
||||
private final GaoCustomerService customerService;
|
||||
@@ -60,6 +66,8 @@ public class GaoOrderFulfillmentController {
|
||||
public PageResult<GaoOrderFulfillment> list(@RequestBody GaoOrderFulfillmentPage page) {
|
||||
TimiException.required(page, "not found fulfillment page");
|
||||
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
|
||||
page.setOrderAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_READ.getValue()));
|
||||
page.setRecycleAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_READ.getValue()));
|
||||
PageResult<GaoOrderFulfillment> result = service.pageByQuery(page);
|
||||
fillTransient(result.getList());
|
||||
return result;
|
||||
@@ -67,19 +75,20 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_READ)
|
||||
@PostMapping("/detail")
|
||||
public GaoOrderFulfillment detail(@RequestParam String id) {
|
||||
GaoOrderFulfillment result = service.detail(id);
|
||||
checkSource(result, GaoPermissionCode.ORDER_FULFILLMENT_READ, GaoPermissionCode.ORDER_FULFILLMENT_READ);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
|
||||
@PostMapping("/create")
|
||||
public GaoOrderFulfillment create(@RequestBody GaoOrderFulfillmentCreateRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue());
|
||||
GaoOrderFulfillment result = service.create(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -87,9 +96,11 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(value = { GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY }, mode = PermissionMatchMode.ALL)
|
||||
@PostMapping("/create-and-verify")
|
||||
public GaoOrderFulfillment createAndVerify(@RequestBody GaoOrderFulfillmentCreateRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue());
|
||||
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY.getValue());
|
||||
GaoOrderFulfillment result = service.createAndVerify(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -135,9 +146,10 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
|
||||
@PostMapping("/prepare-stock")
|
||||
public GaoOrderFulfillment prepareStock(@RequestBody GaoOrderFulfillmentPrepareStockRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
|
||||
GaoOrderFulfillment result = service.prepareStock(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -145,9 +157,10 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
|
||||
@PostMapping("/verify")
|
||||
public GaoOrderFulfillment verify(@RequestBody GaoOrderFulfillmentActionRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
|
||||
GaoOrderFulfillment result = service.verify(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -155,9 +168,10 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
|
||||
@PostMapping("/reject")
|
||||
public GaoOrderFulfillment reject(@RequestBody GaoOrderFulfillmentActionRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
|
||||
GaoOrderFulfillment result = service.reject(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -165,9 +179,10 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
|
||||
@PostMapping("/cancel")
|
||||
public GaoOrderFulfillment cancel(@RequestBody GaoOrderFulfillmentActionRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_CREATE);
|
||||
GaoOrderFulfillment result = service.cancel(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -175,9 +190,10 @@ public class GaoOrderFulfillmentController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_REVOKE)
|
||||
@PostMapping("/revoke")
|
||||
public GaoOrderFulfillment revoke(@RequestBody GaoOrderFulfillmentRevokeRequest request) {
|
||||
TimiException.required(request, "not found fulfillment request");
|
||||
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_REVOKE, GaoPermissionCode.ORDER_FULFILLMENT_REVOKE);
|
||||
GaoOrderFulfillment result = service.revoke(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
@@ -188,11 +204,24 @@ public class GaoOrderFulfillmentController {
|
||||
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_RETURN)
|
||||
@PostMapping("/return")
|
||||
public GaoOrderFulfillment returnGoods(@RequestBody GaoOrderFulfillmentReturnRequest request) {
|
||||
TimiException.required(request, "履约退货请求不能为空");
|
||||
GaoOrderFulfillment source = service.detail(request.getFulfillmentId());
|
||||
TimiException.requiredTrue(!isRecycleOrder(source.getSalesOrderId()), "回收兑换履约请通过冲正处理");
|
||||
GaoOrderFulfillment result = service.returnGoods(request);
|
||||
fillTransient(List.of(result));
|
||||
return result;
|
||||
}
|
||||
|
||||
private void checkSource(GaoOrderFulfillment fulfillment, GaoPermissionCode order, GaoPermissionCode recycle) {
|
||||
permissionChecker.checkAll(ModuleCode.GAO, (isRecycleOrder(fulfillment.getSalesOrderId()) ? recycle : order).getValue());
|
||||
}
|
||||
|
||||
private boolean isRecycleOrder(String id) {
|
||||
if (id == null || id.isBlank()) return false;
|
||||
GaoSalesOrder order = salesOrderService.detail(id);
|
||||
return order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE;
|
||||
}
|
||||
|
||||
private void fillTransient(List<GaoOrderFulfillment> fulfillmentList) {
|
||||
if (fulfillmentList == null || fulfillmentList.isEmpty()) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleAccountMapper;
|
||||
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleAccountService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleAccountAdjustRequest;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import com.imyeyu.utils.Time;
|
||||
|
||||
/// 客户回收物额度接口
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/account")
|
||||
public class GaoRecycleAccountController {
|
||||
private final GaoRecycleAccountMapper mapper;
|
||||
private final GaoRecycleAccountService service;
|
||||
private final GaoStoreScopeService scope;
|
||||
private final GaoCustomerService customerService;
|
||||
private final AttachmentService attachmentService;
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/yield/list")
|
||||
public List<Map<String, Object>> yields(@RequestParam String storeId, @RequestParam String skuId) {
|
||||
scope.checkStoreId(storeId);
|
||||
List<Map<String, Object>> rows = mapper.yieldList(storeId, skuId);
|
||||
List<String> itemIds = rows.stream().map(row -> (String) row.get("recycleItemId")).filter(java.util.Objects::nonNull).distinct().toList();
|
||||
if (!itemIds.isEmpty()) {
|
||||
Map<String, List<Attachment>> attachments = attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIds);
|
||||
rows.forEach(row -> row.put("attachmentList", attachments.getOrDefault(row.get("recycleItemId"), List.of())));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// 产品详情里配置产出回收物用的批量查询,一次返回该产品所有 SKU 的产出行
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/yield/product/list")
|
||||
public List<Map<String, Object>> yieldsByProduct(@RequestParam String storeId, @RequestParam String productId) {
|
||||
scope.checkStoreId(storeId);
|
||||
return mapper.yieldListByProduct(storeId, productId);
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/yield/save")
|
||||
public void saveYield(@RequestParam String storeId, @RequestParam String skuId, @RequestParam String recycleItemId, @RequestParam BigDecimal quantityPerBase) {
|
||||
scope.checkStoreId(storeId);
|
||||
// 额度按三位小数记账,比例精度高于额度会让换算结果必然超出精度
|
||||
TimiException.requiredTrue(0 < quantityPerBase.signum() && !(3 < quantityPerBase.stripTrailingZeros().scale())
|
||||
&& !(12 < quantityPerBase.precision() - quantityPerBase.scale()), "产物数量比例最多保留三位小数");
|
||||
TimiException.requiredTrue(mapper.validYield(storeId, skuId, recycleItemId) == 1, "商品或回收物不属于当前门店");
|
||||
mapper.saveYield(UUID.randomUUID().toString(), storeId, skuId, recycleItemId, quantityPerBase, Time.now());
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/yield/delete")
|
||||
public void deleteYield(@RequestParam String storeId, @RequestParam String skuId, @RequestParam String recycleItemId) {
|
||||
scope.checkStoreId(storeId);
|
||||
mapper.deleteYield(storeId, skuId, recycleItemId, Time.now());
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_READ)
|
||||
@PostMapping("/list")
|
||||
public List<Map<String, Object>> list(@RequestParam String storeId, @RequestParam String customerId) {
|
||||
checkCustomer(storeId, customerId);
|
||||
return mapper.listAccounts(storeId, customerId);
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_READ)
|
||||
@PostMapping("/ledger")
|
||||
public List<Map<String, Object>> ledger(@RequestParam String storeId, @RequestParam String customerId) {
|
||||
checkCustomer(storeId, customerId);
|
||||
return mapper.listLedger(storeId, customerId);
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_ACCOUNT_ADJUST)
|
||||
@PostMapping("/adjust")
|
||||
public void adjust(@RequestBody GaoRecycleAccountAdjustRequest request) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
checkCustomer(request.getStoreId(), request.getCustomerId());
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "调整原因不能为空");
|
||||
TimiException.requiredTrue(request.getQuantity() != null && request.getQuantity().signum() != 0, "调整数量不能为零");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.requiredTrue(mapper.validItem(request.getStoreId(), request.getRecycleItemId()) == 1, "回收物不属于当前门店");
|
||||
String bizId = UUID.nameUUIDFromBytes(request.getRequestNo().getBytes(java.nio.charset.StandardCharsets.UTF_8)).toString();
|
||||
service.change(request.getStoreId(), request.getCustomerId(), request.getRecycleItemId(), request.getQuantity(), BigDecimal.ZERO, "MANUAL", bizId, request.getRequestNo(), request.getReason());
|
||||
}
|
||||
|
||||
private void checkCustomer(String storeId, String customerId) {
|
||||
scope.checkStoreId(storeId);
|
||||
GaoCustomer customer = customerService.get(customerId);
|
||||
TimiException.requiredTrue(customer != null && storeId.equals(customer.getStoreId()), "客户不属于当前门店");
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,15 @@ public class GaoRecycleConfigController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_QUERY)
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/rule/delete")
|
||||
public void deleteRule(@RequestParam(required = false) String storeId, @RequestParam String id) {
|
||||
service.deleteRule(storeId, id);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/rules/active")
|
||||
public PageResult<GaoRecycleExchangeRule> activeRules(@RequestParam(required = false) String storeId,
|
||||
@RequestParam(required = false) String recycleItemId,
|
||||
|
||||
+3
-19
@@ -2,22 +2,20 @@ package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeQueryService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeViewService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeDetail;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangePage;
|
||||
import com.imyeyu.spring.annotation.AOPLog;
|
||||
import com.imyeyu.spring.annotation.RequestRateLimit;
|
||||
import com.imyeyu.spring.bean.PageResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/// 回收兑换查询接口
|
||||
///
|
||||
/// 兑换单列表已并入交易订单查询,这里只保留详情
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/exchange")
|
||||
@@ -26,27 +24,13 @@ public class GaoRecycleExchangeQueryController {
|
||||
private final GaoRecycleExchangeQueryService service;
|
||||
private final GaoRecycleExchangeViewService viewService;
|
||||
|
||||
/// 分页查询兑换单
|
||||
///
|
||||
/// @param page 查询条件
|
||||
/// @return 兑换单分页结果
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_QUERY)
|
||||
@PostMapping("/page")
|
||||
public PageResult<GaoRecycleExchange> page(@RequestBody GaoRecycleExchangePage page) {
|
||||
PageResult<GaoRecycleExchange> result = service.page(page);
|
||||
viewService.fill(result.getList());
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 查询兑换单详情
|
||||
///
|
||||
/// @param id 兑换单 ID
|
||||
/// @return 兑换单详情
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_QUERY)
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/detail")
|
||||
public GaoRecycleExchangeDetail detail(@RequestParam String id) {
|
||||
GaoRecycleExchangeDetail detail = service.detail(id);
|
||||
|
||||
+4
-27
@@ -3,11 +3,9 @@ package com.imyeyu.api.modules.gao.controller;
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeWriteService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeViewService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeActionRequest;
|
||||
import com.imyeyu.spring.annotation.AOPLog;
|
||||
import com.imyeyu.spring.annotation.RequestRateLimit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -17,6 +15,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/// 回收兑换交易接口
|
||||
///
|
||||
/// 兑换权益的领取、核销与冲正统一由 `/gao/order/fulfillment` 承载,
|
||||
/// 这里只保留开单,取消统一通过订单接口处理。
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/exchange")
|
||||
@@ -26,33 +27,9 @@ public class GaoRecycleExchangeWriteController {
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CREATE)
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_CREATE)
|
||||
@PostMapping("/create")
|
||||
public GaoRecycleExchange create(@RequestBody GaoRecycleExchangeCreateRequest request) {
|
||||
return viewService.fill(service.create(request));
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_VERIFY)
|
||||
@PostMapping("/verify")
|
||||
public GaoRecycleExchange verify(@RequestBody GaoRecycleExchangeActionRequest request) {
|
||||
return viewService.fill(service.apply(request, GaoRecycleExchangeAction.ActionType.VERIFY));
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CANCEL)
|
||||
@PostMapping("/cancel")
|
||||
public GaoRecycleExchange cancel(@RequestBody GaoRecycleExchangeActionRequest request) {
|
||||
return viewService.fill(service.apply(request, GaoRecycleExchangeAction.ActionType.CANCEL));
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_REVOKE)
|
||||
@PostMapping("/revoke")
|
||||
public GaoRecycleExchange revoke(@RequestBody GaoRecycleExchangeActionRequest request) {
|
||||
return viewService.fill(service.apply(request, GaoRecycleExchangeAction.ActionType.REVOKE));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecyclePaymentService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import com.imyeyu.api.bean.PermissionMatchMode;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderTransactionView;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.bean.ModuleCode;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付接口
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/payment")
|
||||
public class GaoRecyclePaymentController {
|
||||
private final GaoRecyclePaymentService service;
|
||||
private final PermissionChecker permissions;
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_CREATE)
|
||||
@PostMapping("/create")
|
||||
public GaoRecyclePayment create(@RequestBody GaoRecyclePaymentRequest request) { return service.create(request); }
|
||||
|
||||
@RequireGaoPermission(value = {GaoPermissionCode.FUND_RECEIVE_CREATE, GaoPermissionCode.FUND_RECEIVE_VERIFY}, mode = PermissionMatchMode.ALL)
|
||||
@PostMapping("/create-and-verify")
|
||||
public GaoRecyclePayment createAndVerify(@RequestBody GaoRecyclePaymentRequest request) { return service.createAndVerify(request); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
|
||||
@PostMapping("/list")
|
||||
public List<GaoRecyclePayment> list(@RequestParam String orderId) { return service.list(orderId); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
|
||||
@PostMapping("/search")
|
||||
public List<GaoRecyclePayment> search(@RequestParam(required = false) String storeId,
|
||||
@RequestParam(required = false) String customerId, @RequestParam(required = false) String orderId, @RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) Long beginAt, @RequestParam(required = false) Long endAt,
|
||||
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "21") int limit) {
|
||||
return service.search(storeId, customerId, orderId, status, beginAt, endAt, offset, limit);
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
|
||||
@PostMapping("/transactions")
|
||||
public List<GaoOrderTransactionView> transactions(@RequestParam String orderId) {
|
||||
return service.transactions(orderId, permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.FUND_RECORD_READ.getValue()), permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.FUND_RECORD_READ.getValue()));
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_VERIFY)
|
||||
@PostMapping("/verify")
|
||||
public GaoRecyclePayment verify(@RequestBody GaoRecyclePaymentRequest request) { return service.verify(request.getPaymentId()); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_VERIFY)
|
||||
@PostMapping("/reject")
|
||||
public GaoRecyclePayment reject(@RequestBody GaoRecyclePaymentRequest request) { return service.release(request, true); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_CREATE)
|
||||
@PostMapping("/cancel")
|
||||
public GaoRecyclePayment cancel(@RequestBody GaoRecyclePaymentRequest request) { return service.release(request, false); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_REVOKE)
|
||||
@PostMapping("/revoke")
|
||||
public GaoRecyclePayment revoke(@RequestBody GaoRecyclePaymentRequest request) { return service.revoke(request); }
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public class GaoRecycleStatController {
|
||||
/// @return 回收统计
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_QUERY)
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/recycle")
|
||||
public List<GaoRecycleStatView> recycle(@RequestParam(required = false) String storeId,
|
||||
@RequestParam long startAt, @RequestParam long endAt) {
|
||||
@@ -45,7 +45,7 @@ public class GaoRecycleStatController {
|
||||
/// @return 兑换统计
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_QUERY)
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/exchange")
|
||||
public List<GaoRecycleExchangeStatView> exchange(@RequestParam(required = false) String storeId,
|
||||
@RequestParam long startAt, @RequestParam long endAt) {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.bean.PermissionMatchMode;
|
||||
import com.imyeyu.api.bean.ModuleCode;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeWriteService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeActionRequest;
|
||||
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest;
|
||||
@@ -43,7 +47,9 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class GaoSalesOrderController {
|
||||
|
||||
private final GaoSalesOrderService service;
|
||||
private final PermissionChecker permissionChecker;
|
||||
private final GaoOrderPaymentService paymentService;
|
||||
private final GaoRecycleExchangeWriteService recycleExchangeWriteService;
|
||||
private final GaoStoreScopeService storeScopeService;
|
||||
private final UserService userService;
|
||||
|
||||
@@ -54,6 +60,8 @@ public class GaoSalesOrderController {
|
||||
public PageResult<GaoSalesOrder> list(@RequestBody GaoSalesOrderPage page) {
|
||||
TimiException.required(page, "not found sales order page");
|
||||
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
|
||||
page.setOrderAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_READ.getValue()));
|
||||
page.setRecycleAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_READ.getValue()));
|
||||
return service.pageByQuery(page);
|
||||
}
|
||||
|
||||
@@ -64,6 +72,8 @@ public class GaoSalesOrderController {
|
||||
public GaoSalesOrderReceivableStatView summary(@RequestBody GaoSalesOrderPage page) {
|
||||
TimiException.required(page, "not found sales order summary page");
|
||||
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
|
||||
page.setOrderAllowed(true);
|
||||
page.setRecycleAllowed(false);
|
||||
return service.summary(page);
|
||||
}
|
||||
|
||||
@@ -83,6 +93,7 @@ public class GaoSalesOrderController {
|
||||
@PostMapping("/detail")
|
||||
public GaoSalesOrder detail(@RequestParam String id) {
|
||||
GaoSalesOrder result = service.detail(id);
|
||||
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_READ.getValue());
|
||||
if (TimiJava.isNotEmpty(result.getCancelOperatorUserId())) {
|
||||
result.setCancelOperator(userService.get(result.getCancelOperatorUserId()));
|
||||
}
|
||||
@@ -106,6 +117,7 @@ public class GaoSalesOrderController {
|
||||
public GaoSalesOrder update(@RequestBody GaoSalesOrderUpdateRequest request) {
|
||||
TimiException.required(request, "not found sales order update request");
|
||||
TimiException.required(request.getId(), "not found sales order.id");
|
||||
TimiException.requiredTrue(service.detail(request.getId()).getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单请通过兑换接口管理");
|
||||
return service.updateRemarkAndAttachments(request);
|
||||
}
|
||||
|
||||
@@ -114,6 +126,16 @@ public class GaoSalesOrderController {
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_CANCEL)
|
||||
@PostMapping("/cancel")
|
||||
public GaoSalesOrder cancel(@RequestBody GaoSalesOrderCancelRequest request) {
|
||||
TimiException.required(request, "订单取消请求不能为空");
|
||||
GaoSalesOrder order = service.detail(request.getSalesOrderId());
|
||||
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && order.getStatus() != GaoSalesOrder.Status.CANCELLED) {
|
||||
GaoRecycleExchangeActionRequest action = new GaoRecycleExchangeActionRequest();
|
||||
action.setExchangeId(order.getRecycleExchangeId());
|
||||
action.setRequestNo(request.getRequestNo());
|
||||
action.setReason(request.getReason());
|
||||
recycleExchangeWriteService.cancelFromOrder(action, request);
|
||||
return service.detail(request.getSalesOrderId());
|
||||
}
|
||||
return service.cancel(request);
|
||||
}
|
||||
|
||||
|
||||
@@ -118,4 +118,8 @@ public class GaoOrderFulfillment implements IDEntity<String>, Creatable, Updatab
|
||||
/// 附件
|
||||
@Transient
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 来源订单类型,列表展示用,来自销售订单
|
||||
@Transient
|
||||
private String orderType;
|
||||
}
|
||||
|
||||
@@ -30,10 +30,7 @@ public class GaoProductStockRecord implements IDEntity<String>, Creatable {
|
||||
ORDER_FULFILLMENT,
|
||||
|
||||
/// 积分兑换库存操作
|
||||
POINT_REDEMPTION,
|
||||
|
||||
/// 回收兑换库存操作
|
||||
RECYCLE_EXCHANGE
|
||||
POINT_REDEMPTION
|
||||
}
|
||||
|
||||
/// 库存操作类型
|
||||
@@ -72,18 +69,6 @@ public class GaoProductStockRecord implements IDEntity<String>, Creatable {
|
||||
/// 积分兑换退货入库
|
||||
POINT_REDEMPTION_RETURN_IN,
|
||||
|
||||
/// 回收兑换预占
|
||||
RECYCLE_RESERVE,
|
||||
|
||||
/// 回收兑换释放
|
||||
RECYCLE_RELEASE,
|
||||
|
||||
/// 回收兑换出库
|
||||
RECYCLE_OUT,
|
||||
|
||||
/// 回收兑换冲正入库
|
||||
RECYCLE_REVOKE,
|
||||
|
||||
/// 盘盈
|
||||
STOCKTAKE_GAIN,
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
@@ -8,6 +9,7 @@ import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换单
|
||||
@Data
|
||||
@@ -17,17 +19,14 @@ public class GaoRecycleExchange extends UUIDEntity {
|
||||
/// 状态
|
||||
public enum Status {
|
||||
|
||||
/// 待核销
|
||||
/// 待领取,尚有可领取权益
|
||||
PENDING,
|
||||
|
||||
/// 已核销
|
||||
VERIFIED,
|
||||
/// 已完成,权益全部领取完毕
|
||||
COMPLETED,
|
||||
|
||||
/// 已撤销
|
||||
CANCELLED,
|
||||
|
||||
/// 已冲正
|
||||
REVOKED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
/// 门店 ID
|
||||
@@ -45,84 +44,41 @@ public class GaoRecycleExchange extends UUIDEntity {
|
||||
/// 规则 ID
|
||||
private String ruleId;
|
||||
|
||||
/// 生成的销售订单 ID
|
||||
private String salesOrderId;
|
||||
|
||||
/// 创建时兑换模板快照
|
||||
private JsonNode ruleSnapshot;
|
||||
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 回收物当前是否允许小数数量
|
||||
@Transient
|
||||
private Boolean allowDecimalQuantity;
|
||||
|
||||
/// 回收物当前图片
|
||||
@Transient
|
||||
private List<Attachment> recycleItemAttachments;
|
||||
|
||||
/// 回收物名称快照
|
||||
private String recycleNameSnapshot;
|
||||
|
||||
/// 回收物单位快照
|
||||
private String recycleUnitSnapshot;
|
||||
|
||||
/// 关联产品 ID 快照
|
||||
private String sourceProductIdSnapshot;
|
||||
|
||||
/// 关联 SKU ID 快照
|
||||
private String sourceSkuIdSnapshot;
|
||||
|
||||
/// 规则回收数量快照
|
||||
private BigDecimal ruleRecycleQuantity;
|
||||
|
||||
/// 规则兑换数量快照
|
||||
private BigDecimal ruleExchangeQuantity;
|
||||
|
||||
/// 规则倍数
|
||||
/// 模板份数,自由创建时为空
|
||||
private Integer multiple;
|
||||
|
||||
/// 预设回收数量
|
||||
/// 模板预设回收数量 = 规则回收数量 × 份数,自由创建时为空
|
||||
private BigDecimal defaultRecycleQuantity;
|
||||
|
||||
/// 预设兑换数量
|
||||
private BigDecimal defaultExchangeQuantity;
|
||||
|
||||
/// 回收数量
|
||||
/// 实际回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 兑换数量
|
||||
private BigDecimal exchangeQuantity;
|
||||
|
||||
/// 兑换产品 ID 快照
|
||||
private String productIdSnapshot;
|
||||
|
||||
/// 兑换 SKU ID 快照
|
||||
private String skuIdSnapshot;
|
||||
|
||||
/// 兑换单位 ID 快照
|
||||
private String skuUnitIdSnapshot;
|
||||
|
||||
/// 产品名称快照
|
||||
private String productNameSnapshot;
|
||||
|
||||
/// 产品类型快照
|
||||
private String productTypeSnapshot;
|
||||
|
||||
/// SKU 编码快照
|
||||
private String skuCodeSnapshot;
|
||||
|
||||
/// SKU 名称快照
|
||||
private String skuNameSnapshot;
|
||||
|
||||
/// 规格摘要快照
|
||||
private String specSummarySnapshot;
|
||||
|
||||
/// 业务单位快照
|
||||
private String unitSnapshot;
|
||||
|
||||
/// 规格结构快照
|
||||
private com.fasterxml.jackson.databind.JsonNode skuSpecSnapshot;
|
||||
|
||||
/// 单位换算系数快照
|
||||
private BigDecimal baseQuantityPerUnitSnapshot;
|
||||
|
||||
/// 基础单位数量
|
||||
private BigDecimal baseQuantity;
|
||||
|
||||
/// true 为允许业务数量使用小数
|
||||
private Boolean allowDecimalSnapshot;
|
||||
|
||||
/// true 为启用库存管理
|
||||
private Boolean stockEnabledSnapshot;
|
||||
|
||||
/// 状态
|
||||
private Status status;
|
||||
|
||||
|
||||
@@ -4,24 +4,21 @@ import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/// 回收兑换操作记录
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleExchangeAction extends UUIDEntity {
|
||||
/// 撤销后门店最终保留的回收物数量
|
||||
private BigDecimal retainedRecycleQuantity;
|
||||
|
||||
/// 操作类型
|
||||
/// 操作类型。兑换权益的核销与冲正由履约单承载,兑换单只剩撤销。
|
||||
public enum ActionType {
|
||||
|
||||
/// 核销
|
||||
VERIFY,
|
||||
|
||||
/// 撤销
|
||||
CANCEL,
|
||||
|
||||
/// 冲正
|
||||
REVOKE
|
||||
CANCEL
|
||||
}
|
||||
|
||||
/// 门店 ID
|
||||
@@ -51,18 +48,6 @@ public class GaoRecycleExchangeAction extends UUIDEntity {
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// true 为回收物全部退还客户
|
||||
private Boolean recycleReturned;
|
||||
|
||||
/// true 为商品已退回门店
|
||||
private Boolean stockReturned;
|
||||
|
||||
/// 库存流水 ID
|
||||
private String stockRecordId;
|
||||
|
||||
/// 原出库流水 ID
|
||||
private String sourceStockRecordId;
|
||||
|
||||
/// 操作人,展示用,由控制器批量填充
|
||||
@Transient
|
||||
private User operator;
|
||||
|
||||
@@ -2,15 +2,20 @@ package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换规则
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleExchangeRule extends UUIDEntity {
|
||||
/// 兑换模板明细
|
||||
@Transient
|
||||
private List<GaoRecycleExchangeRuleItem> itemList;
|
||||
|
||||
/// 状态
|
||||
public enum Status {
|
||||
@@ -28,18 +33,9 @@ public class GaoRecycleExchangeRule extends UUIDEntity {
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 回收数量
|
||||
/// 单份模板回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// SKU ID
|
||||
private String skuId;
|
||||
|
||||
/// SKU 单位 ID
|
||||
private String skuUnitId;
|
||||
|
||||
/// 兑换数量
|
||||
private BigDecimal exchangeQuantity;
|
||||
|
||||
/// 状态
|
||||
private Status status;
|
||||
|
||||
@@ -57,35 +53,7 @@ public class GaoRecycleExchangeRule extends UUIDEntity {
|
||||
@Transient
|
||||
private String recycleUnit;
|
||||
|
||||
/// 兑换产品名称,展示用,由服务批量填充
|
||||
/// 回收物图片,展示用
|
||||
@Transient
|
||||
private String productName;
|
||||
|
||||
/// 兑换产品类型,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String productType;
|
||||
|
||||
/// 兑换 SKU 编码,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String skuCode;
|
||||
|
||||
/// 兑换 SKU 名称,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String skuName;
|
||||
|
||||
/// 兑换 SKU 规格摘要,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String specSummary;
|
||||
|
||||
/// 兑换业务单位名称,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String unitName;
|
||||
|
||||
/// 兑换 SKU 是否管理库存,展示用,由服务批量填充
|
||||
@Transient
|
||||
private Boolean stockEnabled;
|
||||
|
||||
/// 兑换 SKU 是否允许小数数量,展示用,由服务批量填充
|
||||
@Transient
|
||||
private Boolean allowDecimalQuantity;
|
||||
private List<Attachment> recycleItemAttachments;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 回收兑换模板明细
|
||||
@Data
|
||||
public class GaoRecycleExchangeRuleItem {
|
||||
|
||||
private String id;
|
||||
private String ruleId;
|
||||
private String skuId;
|
||||
private String skuUnitId;
|
||||
private BigDecimal exchangeQuantity;
|
||||
private Integer sort;
|
||||
private Long createdAt;
|
||||
/// 展示用产品名称
|
||||
private String productName;
|
||||
/// 展示用 SKU 名称
|
||||
private String skuName;
|
||||
/// 展示用规格摘要
|
||||
private String specSummary;
|
||||
/// 展示用单位名称
|
||||
private String unitName;
|
||||
/// 展示用 SKU 编码
|
||||
private String skuCode;
|
||||
/// 展示用产品类型
|
||||
private String productType;
|
||||
/// true 为启用库存管理
|
||||
private Boolean stockEnabled;
|
||||
/// true 为允许小数数量
|
||||
private Boolean allowDecimalQuantity;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@@ -29,23 +31,16 @@ public class GaoRecycleItem extends UUIDEntity {
|
||||
/// 回收计量单位
|
||||
private String unitName;
|
||||
|
||||
/// 关联产品 ID
|
||||
private String productId;
|
||||
|
||||
/// SKU ID
|
||||
private String skuId;
|
||||
/// 是否允许小数数量
|
||||
private Boolean allowDecimalQuantity;
|
||||
|
||||
/// 状态
|
||||
private Status status;
|
||||
|
||||
/// 图片附件
|
||||
@Transient
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// 来源产品名称,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String sourceProductName;
|
||||
|
||||
/// 来源 SKU 名称,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String sourceSkuName;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付记录
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecyclePayment extends UUIDEntity {
|
||||
|
||||
/// 支付状态
|
||||
public enum Status {PENDING, VERIFIED, REJECTED, CANCELLED, REVOKED}
|
||||
|
||||
private String storeId;
|
||||
private String customerId;
|
||||
private String orderId;
|
||||
private String recycleItemId;
|
||||
private String requestNo;
|
||||
/// 请求内容摘要
|
||||
private String requestFingerprint;
|
||||
private BigDecimal quantity;
|
||||
private Status status;
|
||||
private String sourcePaymentId;
|
||||
private String operatorUserId;
|
||||
private String verifierUserId;
|
||||
private Long occurredAt;
|
||||
private Long verifiedAt;
|
||||
private String reason;
|
||||
private Boolean returnedToCustomer;
|
||||
/// 支付附件
|
||||
@Transient
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 带方向的数量,支付为正、冲正为负
|
||||
///
|
||||
/// 冲正记录本身也是 VERIFIED,直接按 quantity 求和会把冲正重复计入,
|
||||
/// 统计与页面统一用这个字段累加。
|
||||
@Transient
|
||||
private BigDecimal signedQuantity;
|
||||
/// 关联兑换单及客户展示信息
|
||||
@Transient
|
||||
private String recycleExchangeId;
|
||||
@Transient
|
||||
private String recycleName;
|
||||
@Transient
|
||||
private String recycleUnit;
|
||||
@Transient
|
||||
private GaoCustomer customer;
|
||||
@Transient
|
||||
private User operator;
|
||||
@Transient
|
||||
private User verifier;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.util.List;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// GAO 销售订单
|
||||
///
|
||||
@@ -24,7 +25,10 @@ public class GaoSalesOrder extends UUIDEntity {
|
||||
PACKAGE,
|
||||
|
||||
/// 直接产品订单
|
||||
DIRECT_PRODUCT
|
||||
DIRECT_PRODUCT,
|
||||
|
||||
/// 回收兑换订单
|
||||
RECYCLE
|
||||
}
|
||||
|
||||
/// 订单状态
|
||||
@@ -78,6 +82,32 @@ public class GaoSalesOrder extends UUIDEntity {
|
||||
/// 订单类型
|
||||
private OrderType orderType;
|
||||
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 需核销回收物数量
|
||||
private BigDecimal recycleRequiredQuantity;
|
||||
|
||||
/// 回收物名称,展示用,仅回收兑换订单填充
|
||||
@Transient
|
||||
private String recycleItemName;
|
||||
|
||||
/// 回收物计量单位,展示用,仅回收兑换订单填充
|
||||
@Transient
|
||||
private String recycleUnit;
|
||||
|
||||
/// 对应兑换单 ID,展示用,仅回收兑换订单填充
|
||||
@Transient
|
||||
private String recycleExchangeId;
|
||||
|
||||
/// 已核销回收物数量,列表展示用
|
||||
@Transient
|
||||
private BigDecimal recycleVerifiedQuantity;
|
||||
|
||||
/// 待核销回收物数量,列表展示用
|
||||
@Transient
|
||||
private BigDecimal recyclePendingQuantity;
|
||||
|
||||
/// 订单状态
|
||||
private Status status;
|
||||
|
||||
|
||||
@@ -25,7 +25,10 @@ public class GaoSalesOrderItem extends UUIDEntity {
|
||||
DIRECT_PRODUCT,
|
||||
|
||||
/// 套餐权益
|
||||
PACKAGE_ENTITLEMENT
|
||||
PACKAGE_ENTITLEMENT,
|
||||
|
||||
/// 回收兑换权益
|
||||
RECYCLE_ENTITLEMENT
|
||||
}
|
||||
|
||||
/// 销售订单 ID
|
||||
|
||||
@@ -14,37 +14,27 @@ import java.util.List;
|
||||
/// @since 2026-09-02
|
||||
public interface GaoOrderFulfillmentMapper extends BaseMapper<GaoOrderFulfillment, String> {
|
||||
|
||||
/// 按门店和幂等号查询履约单
|
||||
GaoOrderFulfillment selectByRequestNo(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
|
||||
/// 按批量幂等号前缀查询履约单
|
||||
List<GaoOrderFulfillment> selectByRequestNoPrefix(@Param("storeId") String storeId, @Param("requestNoPrefix") String requestNoPrefix);
|
||||
|
||||
/// 按 ID 查询履约单
|
||||
GaoOrderFulfillment selectById(@Param("id") String id);
|
||||
|
||||
/// 按 ID 批量查询履约单
|
||||
List<GaoOrderFulfillment> selectByIdList(@Param("idList") Collection<String> idList);
|
||||
|
||||
/// 锁定履约单
|
||||
GaoOrderFulfillment selectForUpdate(@Param("id") String id);
|
||||
|
||||
/// 按订单查询履约单
|
||||
List<GaoOrderFulfillment> selectBySalesOrderId(@Param("salesOrderId") String salesOrderId);
|
||||
|
||||
/// 按冲正来源查询履约单
|
||||
|
||||
GaoOrderFulfillment selectBySourceFulfillmentId(@Param("sourceFulfillmentId") String sourceFulfillmentId);
|
||||
|
||||
/// 统计订单中仍占用权益的履约单
|
||||
long countPendingBySalesOrderId(@Param("salesOrderId") String salesOrderId);
|
||||
|
||||
/// 按条件统计履约单
|
||||
long countByQuery(GaoOrderFulfillmentPage page);
|
||||
|
||||
/// 按条件查询履约单
|
||||
List<GaoOrderFulfillment> selectByQuery(GaoOrderFulfillmentPage page);
|
||||
|
||||
/// 更新履约状态
|
||||
int updateStatus(@Param("id") String id, @Param("status") GaoOrderFulfillment.Status status,
|
||||
@Param("verifierUserId") String verifierUserId, @Param("verifiedAt") Long verifiedAt,
|
||||
@Param("reason") String reason);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物额度账户与流水
|
||||
public interface GaoRecycleAccountMapper {
|
||||
@Select("SELECT COUNT(*) FROM gao_recycle_item WHERE store_id=#{store} AND id=#{item}")
|
||||
int validItem(@Param("store") String store, @Param("item") String item);
|
||||
@Select("SELECT COUNT(*) FROM gao_product_sku s JOIN gao_recycle_item r ON r.store_id=s.store_id WHERE s.store_id=#{store} AND s.id=#{sku} AND r.id=#{item}")
|
||||
int validYield(@Param("store") String store, @Param("sku") String sku, @Param("item") String item);
|
||||
|
||||
@Insert("INSERT INTO gao_recycle_product_yield (id,store_id,sku_id,recycle_item_id,quantity_per_base,created_at) VALUES (#{id},#{store},#{sku},#{item},#{quantity},#{now}) ON DUPLICATE KEY UPDATE quantity_per_base=VALUES(quantity_per_base),updated_at=VALUES(created_at),deleted_at=NULL")
|
||||
void saveYield(@Param("id") String id, @Param("store") String store, @Param("sku") String sku, @Param("item") String item, @Param("quantity") BigDecimal quantity, @Param("now") long now);
|
||||
|
||||
@Update("UPDATE gao_recycle_product_yield SET deleted_at=#{now}, updated_at=#{now} WHERE store_id=#{store} AND sku_id=#{sku} AND recycle_item_id=#{item} AND deleted_at IS NULL")
|
||||
void deleteYield(@Param("store") String store, @Param("sku") String sku, @Param("item") String item, @Param("now") long now);
|
||||
@Select("SELECT a.id, a.customer_id AS customerId, a.recycle_item_id AS recycleItemId, a.balance, a.reserved, " +
|
||||
"i.name AS recycleName, i.unit_name AS recycleUnit, a.created_at AS createdAt, a.updated_at AS updatedAt " +
|
||||
"FROM gao_recycle_account a LEFT JOIN gao_recycle_item i ON i.id = a.recycle_item_id " +
|
||||
"WHERE a.store_id=#{store} AND a.customer_id=#{customer} AND a.deleted_at IS NULL ORDER BY a.recycle_item_id")
|
||||
List<Map<String, Object>> listAccounts(@Param("store") String store, @Param("customer") String customer);
|
||||
|
||||
@Select("SELECT id, account_id AS accountId, store_id AS storeId, customer_id AS customerId, recycle_item_id AS recycleItemId, " +
|
||||
"biz_type AS bizType, biz_id AS bizId, request_no AS requestNo, balance_delta AS balanceDelta, reserved_delta AS reservedDelta, " +
|
||||
"balance_after AS balanceAfter, reserved_after AS reservedAfter, operator_user_id AS operatorUserId, reason, created_at AS createdAt " +
|
||||
"FROM gao_recycle_ledger WHERE store_id=#{store} AND customer_id=#{customer} ORDER BY created_at DESC LIMIT 100")
|
||||
List<Map<String, Object>> listLedger(@Param("store") String store, @Param("customer") String customer);
|
||||
@Select("SELECT recycle_item_id,quantity_per_base FROM gao_recycle_product_yield WHERE store_id=#{store} AND sku_id=#{sku} AND deleted_at IS NULL ORDER BY recycle_item_id")
|
||||
List<Map<String, Object>> yields(@Param("store") String store, @Param("sku") String sku);
|
||||
|
||||
/// 配置页需要的字段用驼峰返回,同时带上回收物名称与单位
|
||||
@Select("SELECT y.recycle_item_id AS recycleItemId, y.quantity_per_base AS quantityPerBase, " +
|
||||
"i.name AS recycleName, i.unit_name AS recycleUnit, i.allow_decimal_quantity AS allowDecimalQuantity " +
|
||||
"FROM gao_recycle_product_yield y LEFT JOIN gao_recycle_item i ON i.id = y.recycle_item_id " +
|
||||
"WHERE y.store_id=#{store} AND y.sku_id=#{sku} AND y.deleted_at IS NULL ORDER BY y.recycle_item_id")
|
||||
List<Map<String, Object>> yieldList(@Param("store") String store, @Param("sku") String sku);
|
||||
|
||||
/// 产品维度的产出配置:一个产品下所有 SKU 的产出行,按 SKU 排序返回
|
||||
@Select("SELECT y.sku_id AS skuId, y.recycle_item_id AS recycleItemId, y.quantity_per_base AS quantityPerBase, " +
|
||||
"i.name AS recycleName, i.unit_name AS recycleUnit, s.name AS skuName, s.spec_summary AS skuSpecSummary " +
|
||||
"FROM gao_recycle_product_yield y " +
|
||||
"JOIN gao_product_sku s ON s.id = y.sku_id AND s.deleted_at IS NULL " +
|
||||
"LEFT JOIN gao_recycle_item i ON i.id = y.recycle_item_id " +
|
||||
"WHERE y.store_id=#{store} AND s.product_id=#{product} AND y.deleted_at IS NULL " +
|
||||
"ORDER BY s.sort, s.name, y.recycle_item_id")
|
||||
List<Map<String, Object>> yieldListByProduct(@Param("store") String store, @Param("product") String product);
|
||||
|
||||
@Select("SELECT recycle_item_id,balance_delta FROM gao_recycle_ledger WHERE biz_type='FULFILLMENT_YIELD' AND biz_id=#{biz} ORDER BY recycle_item_id")
|
||||
List<Map<String, Object>> yieldsByFulfillment(@Param("biz") String biz);
|
||||
@Insert("INSERT IGNORE INTO gao_recycle_account (id,store_id,customer_id,recycle_item_id,balance,reserved,created_at) VALUES (#{id},#{store},#{customer},#{item},0,0,#{now})")
|
||||
void ensure(@Param("id") String id, @Param("store") String store, @Param("customer") String customer, @Param("item") String item, @Param("now") long now);
|
||||
|
||||
@Select("SELECT id,balance,reserved FROM gao_recycle_account WHERE store_id=#{store} AND customer_id=#{customer} AND recycle_item_id=#{item} FOR UPDATE")
|
||||
Map<String, Object> lock(@Param("store") String store, @Param("customer") String customer, @Param("item") String item);
|
||||
|
||||
@Select("SELECT customer_id,recycle_item_id,biz_type,biz_id,balance_delta,reserved_delta,reason FROM gao_recycle_ledger WHERE store_id=#{store} AND request_no=#{request} FOR UPDATE")
|
||||
Map<String, Object> findRequest(@Param("store") String store, @Param("request") String request);
|
||||
|
||||
@Update("UPDATE gao_recycle_account SET balance=balance+#{balance},reserved=reserved+#{reserved},updated_at=#{now} WHERE id=#{id} AND balance+#{balance} >= 0 AND reserved+#{reserved} >= 0 AND reserved+#{reserved} <= balance+#{balance}")
|
||||
int change(@Param("id") String id, @Param("balance") BigDecimal balance, @Param("reserved") BigDecimal reserved, @Param("now") long now);
|
||||
|
||||
@Insert("INSERT INTO gao_recycle_ledger (id,account_id,store_id,customer_id,recycle_item_id,biz_type,biz_id,request_no,balance_delta,reserved_delta,balance_after,reserved_after,operator_user_id,reason,created_at) SELECT #{id},id,store_id,customer_id,recycle_item_id,#{type},#{biz},#{request},#{balance},#{reserved},balance,reserved,#{operator},#{reason},#{now} FROM gao_recycle_account WHERE id=#{account}")
|
||||
void ledger(@Param("id") String id, @Param("account") String account, @Param("type") String type, @Param("biz") String biz, @Param("request") String request, @Param("balance") BigDecimal balance, @Param("reserved") BigDecimal reserved, @Param("operator") String operator, @Param("reason") String reason, @Param("now") long now);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
@@ -11,6 +13,34 @@ import java.util.List;
|
||||
|
||||
/// 回收配置数据访问
|
||||
public interface GaoRecycleConfigMapper {
|
||||
/// 查询模板明细
|
||||
/// @param ruleId 模板 ID
|
||||
/// @return 模板明细
|
||||
@Select("SELECT * FROM gao_recycle_exchange_rule_item WHERE rule_id=#{ruleId} ORDER BY sort, id")
|
||||
List<GaoRecycleExchangeRuleItem> ruleItems(@Param("ruleId") String ruleId);
|
||||
|
||||
/// 批量查询模板明细
|
||||
/// @param ids 模板 ID 列表
|
||||
/// @return 模板明细
|
||||
@Select("<script>SELECT * FROM gao_recycle_exchange_rule_item WHERE rule_id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> ORDER BY sort, id</script>")
|
||||
List<GaoRecycleExchangeRuleItem> ruleItemsByIds(@Param("ids") Collection<String> ids);
|
||||
|
||||
/// 新增模板明细
|
||||
/// @param item 模板明细
|
||||
@Insert("INSERT INTO gao_recycle_exchange_rule_item (id,rule_id,sku_id,sku_unit_id,exchange_quantity,sort,created_at) VALUES (#{id},#{ruleId},#{skuId},#{skuUnitId},#{exchangeQuantity},#{sort},#{createdAt})")
|
||||
void insertRuleItem(GaoRecycleExchangeRuleItem item);
|
||||
|
||||
/// 删除模板明细
|
||||
/// @param ruleId 模板 ID
|
||||
@Delete("DELETE FROM gao_recycle_exchange_rule_item WHERE rule_id=#{ruleId}")
|
||||
void deleteRuleItems(@Param("ruleId") String ruleId);
|
||||
|
||||
/// 删除模板
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 模板 ID
|
||||
/// @return 删除数量
|
||||
@Delete("DELETE FROM gao_recycle_exchange_rule WHERE store_id=#{storeId} AND id=#{id}")
|
||||
int deleteRule(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 分页查询回收物
|
||||
///
|
||||
@@ -66,13 +96,13 @@ public interface GaoRecycleConfigMapper {
|
||||
/// 创建回收物
|
||||
///
|
||||
/// @param item 回收物
|
||||
@Insert("INSERT INTO gao_recycle_item (id, store_id, name, unit_name, product_id, sku_id, status, remark, created_at) VALUES (#{id}, #{storeId}, #{name}, #{unitName}, #{productId}, #{skuId}, #{status}, #{remark}, #{createdAt})")
|
||||
@Insert("INSERT INTO gao_recycle_item (id, store_id, name, unit_name, allow_decimal_quantity, status, remark, created_at) VALUES (#{id}, #{storeId}, #{name}, #{unitName}, #{allowDecimalQuantity}, #{status}, #{remark}, #{createdAt})")
|
||||
void insertItem(GaoRecycleItem item);
|
||||
|
||||
/// 更新回收物
|
||||
///
|
||||
/// @param item 回收物
|
||||
@Update("UPDATE gao_recycle_item SET name=#{name}, unit_name=#{unitName}, product_id=#{productId}, sku_id=#{skuId}, status=#{status}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
|
||||
@Update("UPDATE gao_recycle_item SET name=#{name}, unit_name=#{unitName}, allow_decimal_quantity=#{allowDecimalQuantity}, status=#{status}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
|
||||
void updateItem(GaoRecycleItem item);
|
||||
|
||||
/// 分页查询兑换规则
|
||||
@@ -88,7 +118,7 @@ public interface GaoRecycleConfigMapper {
|
||||
@Select("SELECT rule.* FROM gao_recycle_exchange_rule rule WHERE rule.store_id = #{storeId} "
|
||||
+ "AND (#{status} IS NULL OR rule.status = #{status}) "
|
||||
+ "AND (#{recycleItemId} IS NULL OR rule.recycle_item_id = #{recycleItemId}) "
|
||||
+ "AND (#{skuId} IS NULL OR rule.sku_id = #{skuId}) "
|
||||
+ "AND (#{skuId} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_exchange_rule_item ri WHERE ri.rule_id=rule.id AND ri.sku_id=#{skuId})) "
|
||||
+ "AND (#{keyword} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_item item WHERE item.id = rule.recycle_item_id AND item.name LIKE CONCAT('%', #{keyword}, '%'))) "
|
||||
+ "ORDER BY rule.sort, rule.created_at DESC LIMIT #{offset}, #{limit}")
|
||||
List<GaoRecycleExchangeRule> rules(@Param("storeId") String storeId, @Param("status") String status, @Param("recycleItemId") String recycleItemId,
|
||||
@@ -105,7 +135,7 @@ public interface GaoRecycleConfigMapper {
|
||||
@Select("SELECT COUNT(*) FROM gao_recycle_exchange_rule rule WHERE rule.store_id = #{storeId} "
|
||||
+ "AND (#{status} IS NULL OR rule.status = #{status}) "
|
||||
+ "AND (#{recycleItemId} IS NULL OR rule.recycle_item_id = #{recycleItemId}) "
|
||||
+ "AND (#{skuId} IS NULL OR rule.sku_id = #{skuId}) "
|
||||
+ "AND (#{skuId} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_exchange_rule_item ri WHERE ri.rule_id=rule.id AND ri.sku_id=#{skuId})) "
|
||||
+ "AND (#{keyword} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_item item WHERE item.id = rule.recycle_item_id AND item.name LIKE CONCAT('%', #{keyword}, '%')))")
|
||||
long countRules(@Param("storeId") String storeId, @Param("status") String status, @Param("recycleItemId") String recycleItemId,
|
||||
@Param("skuId") String skuId, @Param("keyword") String keyword);
|
||||
@@ -129,12 +159,12 @@ public interface GaoRecycleConfigMapper {
|
||||
/// 创建兑换规则
|
||||
///
|
||||
/// @param rule 兑换规则
|
||||
@Insert("INSERT INTO gao_recycle_exchange_rule (id, store_id, recycle_item_id, recycle_quantity, sku_id, sku_unit_id, exchange_quantity, status, sort, remark, created_at) VALUES (#{id}, #{storeId}, #{recycleItemId}, #{recycleQuantity}, #{skuId}, #{skuUnitId}, #{exchangeQuantity}, #{status}, #{sort}, #{remark}, #{createdAt})")
|
||||
@Insert("INSERT INTO gao_recycle_exchange_rule (id, store_id, recycle_item_id, recycle_quantity, status, sort, remark, created_at) VALUES (#{id}, #{storeId}, #{recycleItemId}, #{recycleQuantity}, #{status}, #{sort}, #{remark}, #{createdAt})")
|
||||
void insertRule(GaoRecycleExchangeRule rule);
|
||||
|
||||
/// 更新兑换规则
|
||||
///
|
||||
/// @param rule 兑换规则
|
||||
@Update("UPDATE gao_recycle_exchange_rule SET recycle_item_id=#{recycleItemId}, recycle_quantity=#{recycleQuantity}, sku_id=#{skuId}, sku_unit_id=#{skuUnitId}, exchange_quantity=#{exchangeQuantity}, status=#{status}, sort=#{sort}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
|
||||
@Update("UPDATE gao_recycle_exchange_rule SET recycle_item_id=#{recycleItemId}, recycle_quantity=#{recycleQuantity}, status=#{status}, sort=#{sort}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
|
||||
void updateRule(GaoRecycleExchangeRule rule);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangePage;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
@@ -10,9 +9,6 @@ import java.util.List;
|
||||
/// 回收兑换查询
|
||||
public interface GaoRecycleExchangeQueryMapper {
|
||||
|
||||
long count(GaoRecycleExchangePage page);
|
||||
List<GaoRecycleExchange> list(GaoRecycleExchangePage page);
|
||||
|
||||
/// 查询兑换单
|
||||
///
|
||||
/// @param id 记录 ID
|
||||
|
||||
@@ -11,12 +11,11 @@ import org.apache.ibatis.annotations.Update;
|
||||
|
||||
/// 回收兑换写入查询
|
||||
public interface GaoRecycleExchangeWriteMapper extends BaseMapper<GaoRecycleExchange, String> {
|
||||
@Update("UPDATE gao_recycle_exchange SET status=#{status}, updated_at=#{updatedAt} WHERE sales_order_id=#{orderId} AND status IN ('PENDING','COMPLETED')")
|
||||
int updateByOrderStatus(@Param("orderId") String orderId, @Param("status") String status, @Param("updatedAt") long updatedAt);
|
||||
@Select("SELECT id FROM gao_store WHERE id = #{id} FOR UPDATE")
|
||||
String lockStore(String id);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange_rule WHERE store_id=#{storeId} AND id=#{id}")
|
||||
GaoRecycleExchangeRule previewRule(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange WHERE store_id=#{storeId} AND request_no=#{requestNo}")
|
||||
GaoRecycleExchange byRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
|
||||
@@ -27,15 +26,24 @@ public interface GaoRecycleExchangeWriteMapper extends BaseMapper<GaoRecycleExch
|
||||
@Select("SELECT * FROM gao_recycle_exchange WHERE id=#{id}")
|
||||
GaoRecycleExchange byId(@Param("id") String id);
|
||||
|
||||
/// 按生成的销售订单反查兑换单快照,订单详情用于跳转与展示回收物
|
||||
///
|
||||
/// @param orderId 销售订单 ID
|
||||
/// @return 兑换单,只填 ID 与回收物名称、单位快照
|
||||
@Select("SELECT id, recycle_name_snapshot, recycle_unit_snapshot FROM gao_recycle_exchange WHERE sales_order_id=#{orderId} LIMIT 1")
|
||||
GaoRecycleExchange snapshotByOrderId(@Param("orderId") String orderId);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange_action WHERE store_id=#{storeId} AND request_no=#{requestNo}")
|
||||
GaoRecycleExchangeAction actionByRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange_action WHERE exchange_id=#{exchangeId} AND action_type='VERIFY'")
|
||||
GaoRecycleExchangeAction verifyAction(String exchangeId);
|
||||
|
||||
@Insert("INSERT INTO gao_recycle_exchange_action (id,store_id,exchange_id,request_no,request_fingerprint,action_type,operator_user_id,occurred_at,created_at,reason,remark,recycle_returned,stock_returned,stock_record_id,source_stock_record_id) VALUES (#{id},#{storeId},#{exchangeId},#{requestNo},#{requestFingerprint},#{actionType},#{operatorUserId},#{occurredAt},#{createdAt},#{reason},#{remark},#{recycleReturned},#{stockReturned},#{stockRecordId},#{sourceStockRecordId})")
|
||||
@Insert("INSERT INTO gao_recycle_exchange_action (id,store_id,exchange_id,request_no,request_fingerprint,action_type,operator_user_id,occurred_at,created_at,reason,remark,retained_recycle_quantity) VALUES (#{id},#{storeId},#{exchangeId},#{requestNo},#{requestFingerprint},#{actionType},#{operatorUserId},#{occurredAt},#{createdAt},#{reason},#{remark},#{retainedRecycleQuantity})")
|
||||
void insertAction(GaoRecycleExchangeAction action);
|
||||
|
||||
@Update("UPDATE gao_recycle_exchange SET status=#{status}, updated_at=#{updatedAt} WHERE id=#{id} AND status=#{expected}")
|
||||
int updateStatus(@Param("id") String id, @Param("status") GaoRecycleExchange.Status status, @Param("expected") GaoRecycleExchange.Status expected, @Param("updatedAt") long updatedAt);
|
||||
/// 撤销兑换单。待领取和已完成都允许撤销,撤销后不能再领取
|
||||
///
|
||||
/// @param id 兑换单 ID
|
||||
/// @param updatedAt 更新时间
|
||||
/// @return 影响行数
|
||||
@Update("UPDATE gao_recycle_exchange SET status = 'CANCELLED', updated_at = #{updatedAt} WHERE id = #{id} AND status IN ('PENDING', 'COMPLETED')")
|
||||
int cancel(@Param("id") String id, @Param("updatedAt") long updatedAt);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import com.imyeyu.spring.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付查询
|
||||
public interface GaoRecyclePaymentMapper extends BaseMapper<GaoRecyclePayment, String> {
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE id=#{id} FOR UPDATE")
|
||||
GaoRecyclePayment lock(@Param("id") String id);
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE id=#{id}")
|
||||
GaoRecyclePayment byId(@Param("id") String id);
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE store_id=#{storeId} AND request_no=#{requestNo}")
|
||||
GaoRecyclePayment byRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
@Select("SELECT COALESCE(SUM(quantity),0) FROM gao_recycle_payment WHERE order_id=#{orderId} AND status IN ('PENDING','VERIFIED') AND source_payment_id IS NULL")
|
||||
BigDecimal occupied(@Param("orderId") String orderId);
|
||||
@Select("SELECT COALESCE(SUM(quantity),0) FROM gao_recycle_payment WHERE order_id=#{orderId} AND status='VERIFIED' AND source_payment_id IS NULL")
|
||||
BigDecimal paid(@Param("orderId") String orderId);
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE order_id=#{orderId} ORDER BY created_at, id")
|
||||
List<GaoRecyclePayment> list(@Param("orderId") String orderId);
|
||||
@Select({"<script>",
|
||||
"SELECT p.*, e.id AS recycleExchangeId, e.recycle_name_snapshot AS recycleName, e.recycle_unit_snapshot AS recycleUnit",
|
||||
"FROM gao_recycle_payment p LEFT JOIN gao_recycle_exchange e ON e.sales_order_id = p.order_id WHERE 1=1",
|
||||
"<if test='storeId != null'> AND p.store_id = #{storeId}</if>",
|
||||
"<if test='customerId != null and customerId != ""'> AND p.customer_id = #{customerId}</if>",
|
||||
"<if test='orderId != null and orderId != ""'> AND p.order_id = #{orderId}</if>",
|
||||
"<if test='status != null and status != ""'> AND p.status = #{status}</if>",
|
||||
"<if test='beginAt != null'> AND p.occurred_at >= #{beginAt}</if>",
|
||||
"<if test='endAt != null'> AND p.occurred_at <= #{endAt}</if>",
|
||||
"ORDER BY p.occurred_at DESC, p.created_at DESC, p.id DESC LIMIT #{offset}, #{limit}",
|
||||
"</script>"})
|
||||
List<GaoRecyclePayment> search(@Param("storeId") String storeId, @Param("customerId") String customerId, @Param("orderId") String orderId,
|
||||
@Param("status") String status, @Param("beginAt") Long beginAt, @Param("endAt") Long endAt,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
@Update("UPDATE gao_recycle_payment SET status=#{status}, verifier_user_id=#{user}, verified_at=#{time}, reason=#{reason}, updated_at=#{time} WHERE id=#{id} AND status=#{expected}")
|
||||
int status(@Param("id") String id, @Param("expected") GaoRecyclePayment.Status expected, @Param("status") GaoRecyclePayment.Status status, @Param("user") String user, @Param("time") long time, @Param("reason") String reason);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 回收实物流转查询
|
||||
public interface GaoRecyclePhysicalMapper {
|
||||
@Select("SELECT COALESCE(SUM(CASE WHEN direction='IN' THEN quantity ELSE -quantity END),0) FROM gao_recycle_physical_record WHERE order_id=#{orderId}")
|
||||
BigDecimal balance(@Param("orderId") String orderId);
|
||||
|
||||
@Select("SELECT COALESCE(SUM(CASE WHEN direction='IN' THEN quantity ELSE -quantity END),0) FROM gao_recycle_physical_record WHERE order_id=#{orderId} AND payment_id=#{paymentId}")
|
||||
BigDecimal paymentBalance(@Param("orderId") String orderId, @Param("paymentId") String paymentId);
|
||||
|
||||
@Insert("INSERT INTO gao_recycle_physical_record (id,store_id,customer_id,order_id,recycle_item_id,payment_id,source_type,source_id,direction,quantity,occurred_at,created_at) VALUES (#{id},#{storeId},#{customerId},#{orderId},#{itemId},#{paymentId},#{sourceType},#{sourceId},#{direction},#{quantity},#{occurredAt},#{createdAt})")
|
||||
void insert(@Param("id") String id, @Param("storeId") String storeId, @Param("customerId") String customerId,
|
||||
@Param("orderId") String orderId, @Param("itemId") String itemId, @Param("paymentId") String paymentId, @Param("sourceType") String sourceType,
|
||||
@Param("sourceId") String sourceId, @Param("direction") String direction, @Param("quantity") BigDecimal quantity,
|
||||
@Param("occurredAt") long occurredAt, @Param("createdAt") long createdAt);
|
||||
}
|
||||
@@ -7,8 +7,8 @@ import java.util.List;
|
||||
/// 回收兑换提醒查询
|
||||
public interface GaoRecycleReminderMapper {
|
||||
|
||||
/// 查询存在待核销兑换的门店
|
||||
/// 查询存在待核销回收物支付的门店
|
||||
/// @return 门店 ID 列表
|
||||
@Select("SELECT DISTINCT store_id FROM gao_recycle_exchange WHERE status = 'PENDING'")
|
||||
@Select("SELECT DISTINCT store_id FROM gao_recycle_payment WHERE status = 'PENDING' AND source_payment_id IS NULL")
|
||||
List<String> selectPendingStoreIds();
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ public interface GaoOrderFulfillmentService extends BaseService<GaoOrderFulfillm
|
||||
/// 按销售订单查询履约历史
|
||||
List<GaoOrderFulfillment> listBySalesOrderId(String salesOrderId);
|
||||
|
||||
/// 按回收兑换单查询履约历史
|
||||
|
||||
/// 查询销售订单仍占用权益的履约单数量
|
||||
long countPendingBySalesOrderId(String salesOrderId);
|
||||
|
||||
|
||||
@@ -87,16 +87,4 @@ public interface GaoProductStockService {
|
||||
|
||||
/// 为积分兑换退货入库
|
||||
GaoProductStockRecord inForRedemptionReturn(String storeId, String returnId, GaoStockChangeItem item, String requestNo, String operatorUserId);
|
||||
|
||||
/// 回收兑换库存预占
|
||||
List<GaoProductStock> reserveForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId);
|
||||
|
||||
/// 回收兑换库存释放
|
||||
List<GaoProductStock> releaseForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId);
|
||||
|
||||
/// 回收兑换库存出库
|
||||
List<GaoProductStock> outForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId);
|
||||
|
||||
/// 回收兑换库存冲正
|
||||
List<GaoProductStock> revokeForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleAccountMapper;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
import java.util.Objects;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillmentItem;
|
||||
|
||||
/// 客户回收物额度服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleAccountService {
|
||||
private final GaoRecycleAccountMapper mapper;
|
||||
private final UserLoginService login;
|
||||
|
||||
/// 按实际履约产生客户额度,规则结果写入流水快照
|
||||
public void addFromFulfillment(String store, String customer, String fulfillmentId, List<GaoOrderFulfillmentItem> items) {
|
||||
Map<String, BigDecimal> quantities = new TreeMap<>();
|
||||
for (GaoOrderFulfillmentItem item : items) {
|
||||
for (Map<String, Object> yield : mapper.yields(store, item.getSkuId())) {
|
||||
String recycleId = (String) yield.get("recycle_item_id");
|
||||
BigDecimal quantity = item.getBaseQuantity().multiply((BigDecimal) yield.get("quantity_per_base"))
|
||||
.setScale(3, java.math.RoundingMode.DOWN);
|
||||
// 换算不足 0.001 时不计入,避免整笔履约核销因为精度失败
|
||||
if (quantity.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
quantities.merge(recycleId, quantity, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
for (var entry : quantities.entrySet()) {
|
||||
change(store, customer, entry.getKey(), entry.getValue(), BigDecimal.ZERO, "FULFILLMENT_YIELD", fulfillmentId, "yield:" + fulfillmentId + ":" + entry.getKey(), null);
|
||||
}
|
||||
}
|
||||
|
||||
/// 撤回原履约产生的额度,不追溯历史履约
|
||||
public void revokeFulfillment(String store, String customer, String sourceId, String reverseId) {
|
||||
for (Map<String, Object> row : mapper.yieldsByFulfillment(sourceId)) {
|
||||
String item = (String) row.get("recycle_item_id");
|
||||
BigDecimal value = (BigDecimal) row.get("balance_delta");
|
||||
change(store, customer, item, value.negate(), BigDecimal.ZERO, "FULFILLMENT_REVOKE", reverseId, "yield-revoke:" + reverseId + ":" + item, null);
|
||||
}
|
||||
}
|
||||
|
||||
/// 原子变更额度与预占并写入流水
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param customerId 客户 ID
|
||||
/// @param recycleItemId 回收物 ID
|
||||
/// @param balanceDelta 额度变化量
|
||||
/// @param reservedDelta 预占变化量
|
||||
/// @param bizType 业务类型
|
||||
/// @param bizId 业务 ID
|
||||
/// @param requestNo 幂等号
|
||||
/// @param reason 原因
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void change(String storeId, String customerId, String recycleItemId, BigDecimal balanceDelta, BigDecimal reservedDelta, String bizType, String bizId, String requestNo, String reason) {
|
||||
TimiException.required(storeId, "门店不能为空");
|
||||
TimiException.required(customerId, "客户不能为空");
|
||||
TimiException.required(recycleItemId, "回收物不能为空");
|
||||
TimiException.required(balanceDelta, "额度变化不能为空");
|
||||
TimiException.required(reservedDelta, "预占变化不能为空");
|
||||
TimiException.requiredTrue(!(3 < balanceDelta.stripTrailingZeros().scale()) && !(3 < reservedDelta.stripTrailingZeros().scale()), "额度最多保留三位小数");
|
||||
TimiException.requiredTrue(!(15 < balanceDelta.precision() - balanceDelta.scale()) && !(15 < reservedDelta.precision() - reservedDelta.scale()), "额度超出范围");
|
||||
TimiException.required(requestNo, "请求号不能为空");
|
||||
TimiException.requiredTrue(!requestNo.isBlank() && !(128 < requestNo.length()), "请求号无效");
|
||||
TimiException.requiredTrue(bizType != null && !bizType.isBlank() && !(32 < bizType.length()) && bizId != null && !bizId.isBlank() && !(36 < bizId.length()), "额度业务信息无效");
|
||||
long now = Time.now();
|
||||
mapper.ensure(UUID.randomUUID().toString(), storeId, customerId, recycleItemId, now);
|
||||
Map<String, Object> account = mapper.lock(storeId, customerId, recycleItemId);
|
||||
TimiException.required(account, "额度账户不存在");
|
||||
Map<String, Object> existing = mapper.findRequest(storeId, requestNo);
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(Objects.equals(customerId, existing.get("customer_id")) && Objects.equals(recycleItemId, existing.get("recycle_item_id"))
|
||||
&& Objects.equals(bizType, existing.get("biz_type")) && Objects.equals(bizId, existing.get("biz_id"))
|
||||
&& balanceDelta.compareTo((BigDecimal) existing.get("balance_delta")) == 0
|
||||
&& reservedDelta.compareTo((BigDecimal) existing.get("reserved_delta")) == 0
|
||||
&& Objects.equals(reason, existing.get("reason")), "额度流水请求号对应内容不一致");
|
||||
return;
|
||||
}
|
||||
String id = (String) account.get("id");
|
||||
TimiException.requiredTrue(mapper.change(id, balanceDelta, reservedDelta, now) == 1, "可用回收物额度不足");
|
||||
mapper.ledger(UUID.randomUUID().toString(), id, bizType, bizId, requestNo, balanceDelta, reservedDelta, login.getRequireLoginUserId(), reason, now);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.system.audit.AuditOperation;
|
||||
import com.imyeyu.api.modules.system.audit.OperationAudit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProduct;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
|
||||
@@ -20,12 +23,15 @@ import com.imyeyu.spring.bean.PageResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -34,6 +40,7 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleConfigService {
|
||||
private final GaoRecycleConfigMapper mapper;
|
||||
private final AttachmentService attachmentService;
|
||||
private final GaoProductSkuMapper skuMapper;
|
||||
private final GaoProductSkuUnitMapper unitMapper;
|
||||
private final GaoProductSkuService skuService;
|
||||
@@ -54,9 +61,13 @@ public class GaoRecycleConfigService {
|
||||
String keywordText = blankToNull(keyword);
|
||||
PageResult<GaoRecycleItem> result = new PageResult<>();
|
||||
result.setTotal(mapper.countItems(storeId, statusName, keywordText));
|
||||
List<GaoRecycleItem> list = mapper.items(storeId, statusName, keywordText, offset, limit);
|
||||
fillItemDisplay(list);
|
||||
result.setList(list);
|
||||
List<GaoRecycleItem> items = mapper.items(storeId, statusName, keywordText, offset, limit);
|
||||
if (!items.isEmpty()) {
|
||||
Map<String, List<Attachment>> photos = attachmentService.mapByBizIdList(
|
||||
Attachment.BizType.GAO_RECYCLE_ITEM, items.stream().map(GaoRecycleItem::getId).toList());
|
||||
items.forEach(item -> item.setAttachmentList(photos.getOrDefault(item.getId(), List.of())));
|
||||
}
|
||||
result.setList(items);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -71,7 +82,7 @@ public class GaoRecycleConfigService {
|
||||
TimiException.required(resolved, "门店不能为空");
|
||||
GaoRecycleItem item = mapper.itemById(resolved, id);
|
||||
TimiException.required(item, "回收物不存在");
|
||||
fillItemDisplay(List.of(item));
|
||||
item.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, id));
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -85,6 +96,7 @@ public class GaoRecycleConfigService {
|
||||
/// @param offset 偏移量
|
||||
/// @param limit 页大小
|
||||
/// @return 规则分页结果
|
||||
@Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||
public PageResult<GaoRecycleExchangeRule> rules(String storeId, GaoRecycleExchangeRule.Status status, String recycleItemId, String skuId, String keyword, int offset, int limit) {
|
||||
storeId = resolvePageStore(storeId, offset, limit);
|
||||
String statusName = status == null ? null : status.name();
|
||||
@@ -104,6 +116,7 @@ public class GaoRecycleConfigService {
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 规则 ID
|
||||
/// @return 兑换规则详情
|
||||
@Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||
public GaoRecycleExchangeRule ruleDetail(String storeId, String id) {
|
||||
TimiException.required(id, "规则 ID 不能为空");
|
||||
String resolved = scope.resolveStoreId(storeId);
|
||||
@@ -125,36 +138,6 @@ public class GaoRecycleConfigService {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
|
||||
/// 填充回收物的来源产品与 SKU 名称,配置列表直接可展示
|
||||
///
|
||||
/// @param itemList 回收物列表
|
||||
private void fillItemDisplay(List<GaoRecycleItem> itemList) {
|
||||
if (itemList == null || itemList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> productIdList = distinct(itemList.stream().map(GaoRecycleItem::getProductId).toList());
|
||||
Map<String, GaoProduct> productMap = productIdList.isEmpty()
|
||||
? Map.of()
|
||||
: productService.listByIdList(productIdList).stream().collect(Collectors.toMap(GaoProduct::getId, Function.identity()));
|
||||
List<String> skuIdList = distinct(itemList.stream().map(GaoRecycleItem::getSkuId).toList());
|
||||
Map<String, GaoProductSku> skuMap = skuIdList.isEmpty()
|
||||
? Map.of()
|
||||
: skuService.listByIdList(skuIdList).stream().collect(Collectors.toMap(GaoProductSku::getId, Function.identity()));
|
||||
for (GaoRecycleItem item : itemList) {
|
||||
// 来源产品与 SKU 都是可选项,空 ID 不能直接拿去查 Map
|
||||
GaoProduct product = item.getProductId() == null ? null : productMap.get(item.getProductId());
|
||||
GaoProductSku sku = item.getSkuId() == null ? null : skuMap.get(item.getSkuId());
|
||||
item.setSourceProductName(product == null ? null : product.getName());
|
||||
item.setSourceSkuName(sku == null ? null : skuDisplayText(sku));
|
||||
}
|
||||
}
|
||||
|
||||
/// SKU 展示文本,规格摘要优先,其次 SKU 名称
|
||||
private String skuDisplayText(GaoProductSku sku) {
|
||||
String specSummary = sku.getSpecSummary();
|
||||
return specSummary == null || specSummary.isBlank() ? sku.getName() : specSummary;
|
||||
}
|
||||
|
||||
/// 填充规则的回收物、产品、SKU 与业务单位展示字段
|
||||
///
|
||||
/// 规则只存 ID,列表页需要名称才能直接渲染;这里按页内 ID 批量回查,避免逐条查询。
|
||||
@@ -166,10 +149,13 @@ public class GaoRecycleConfigService {
|
||||
return;
|
||||
}
|
||||
List<String> itemIdList = distinct(ruleList.stream().map(GaoRecycleExchangeRule::getRecycleItemId).toList());
|
||||
Map<String, List<Attachment>> itemPhotos = itemIdList.isEmpty() ? Map.of()
|
||||
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIdList);
|
||||
Map<String, GaoRecycleItem> itemMap = itemIdList.isEmpty()
|
||||
? Map.of()
|
||||
: mapper.itemsByIdList(storeId, itemIdList).stream().collect(Collectors.toMap(GaoRecycleItem::getId, Function.identity()));
|
||||
List<String> skuIdList = distinct(ruleList.stream().map(GaoRecycleExchangeRule::getSkuId).toList());
|
||||
Map<String, List<GaoRecycleExchangeRuleItem>> ruleItems = mapper.ruleItemsByIds(ruleList.stream().map(GaoRecycleExchangeRule::getId).toList()).stream().collect(Collectors.groupingBy(GaoRecycleExchangeRuleItem::getRuleId));
|
||||
List<String> skuIdList = distinct(ruleItems.values().stream().flatMap(List::stream).map(GaoRecycleExchangeRuleItem::getSkuId).toList());
|
||||
Map<String, GaoProductSku> skuMap = skuIdList.isEmpty()
|
||||
? Map.of()
|
||||
: skuService.listByIdList(skuIdList).stream().collect(Collectors.toMap(GaoProductSku::getId, Function.identity()));
|
||||
@@ -182,19 +168,23 @@ public class GaoRecycleConfigService {
|
||||
: unitMapper.selectBySkuIdList(skuIdList).stream()
|
||||
.collect(Collectors.toMap(unit -> unit.getSkuId() + ":" + unit.getId(), GaoProductSkuUnit::getName, (left, right) -> left));
|
||||
for (GaoRecycleExchangeRule rule : ruleList) {
|
||||
rule.setItemList(ruleItems.getOrDefault(rule.getId(), List.of()));
|
||||
for (GaoRecycleExchangeRuleItem entry : rule.getItemList()) {
|
||||
GaoProductSku selected = skuMap.get(entry.getSkuId());
|
||||
GaoProduct selectedProduct = selected == null ? null : productMap.get(selected.getProductId());
|
||||
entry.setProductName(selectedProduct == null ? null : selectedProduct.getName());
|
||||
entry.setSkuName(selected == null ? null : selected.getName());
|
||||
entry.setSpecSummary(selected == null ? null : selected.getSpecSummary());
|
||||
entry.setUnitName(unitNameMap.get(entry.getSkuId() + ":" + entry.getSkuUnitId()));
|
||||
entry.setSkuCode(selected == null ? null : selected.getCode());
|
||||
entry.setStockEnabled(selected == null ? null : selected.getStockEnabled());
|
||||
entry.setAllowDecimalQuantity(selected == null ? null : selected.getAllowDecimalQuantity());
|
||||
entry.setProductType(selectedProduct == null || selectedProduct.getProductType() == null ? null : selectedProduct.getProductType().name());
|
||||
}
|
||||
GaoRecycleItem item = rule.getRecycleItemId() == null ? null : itemMap.get(rule.getRecycleItemId());
|
||||
GaoProductSku sku = rule.getSkuId() == null ? null : skuMap.get(rule.getSkuId());
|
||||
GaoProduct product = sku == null || sku.getProductId() == null ? null : productMap.get(sku.getProductId());
|
||||
rule.setRecycleName(item == null ? null : item.getName());
|
||||
rule.setRecycleUnit(item == null ? null : item.getUnitName());
|
||||
rule.setProductName(product == null ? null : product.getName());
|
||||
rule.setProductType(product == null || product.getProductType() == null ? null : product.getProductType().name());
|
||||
rule.setSkuCode(sku == null ? null : sku.getCode());
|
||||
rule.setSkuName(sku == null ? null : sku.getName());
|
||||
rule.setSpecSummary(sku == null ? null : sku.getSpecSummary());
|
||||
rule.setStockEnabled(sku == null ? null : sku.getStockEnabled());
|
||||
rule.setAllowDecimalQuantity(sku == null ? null : sku.getAllowDecimalQuantity());
|
||||
rule.setUnitName(rule.getSkuId() == null || rule.getSkuUnitId() == null ? null : unitNameMap.get(rule.getSkuId() + ":" + rule.getSkuUnitId()));
|
||||
rule.setRecycleItemAttachments(rule.getRecycleItemId() == null ? List.of() : itemPhotos.getOrDefault(rule.getRecycleItemId(), List.of()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,31 +210,22 @@ public class GaoRecycleConfigService {
|
||||
TimiException.required(item.getStatus(), "回收物状态不能为空");
|
||||
TimiException.requiredTrue(!item.getName().isBlank() && !item.getUnitName().isBlank()
|
||||
&& !(128 < item.getName().length()) && !(32 < item.getUnitName().length()), "回收物名称或单位过长");
|
||||
// 前端清空来源产品时可能传空串,统一归一化为 null,避免误判为"产品不存在"
|
||||
item.setProductId(blankToNull(item.getProductId()));
|
||||
item.setSkuId(blankToNull(item.getSkuId()));
|
||||
if (item.getSkuId() != null) {
|
||||
TimiException.required(item.getProductId(), "关联 SKU 必须指定产品");
|
||||
}
|
||||
if (item.getProductId() != null) {
|
||||
GaoProduct product = productService.get(item.getProductId());
|
||||
TimiException.required(product, "产品不存在");
|
||||
TimiException.requiredTrue(storeId.equals(product.getStoreId()), "产品不属于当前门店");
|
||||
}
|
||||
if (item.getSkuId() != null) {
|
||||
GaoProductSku sku = skuService.get(item.getSkuId());
|
||||
TimiException.required(sku, "SKU 不存在");
|
||||
TimiException.requiredTrue(storeId.equals(sku.getStoreId()) && item.getProductId().equals(sku.getProductId()), "SKU 不属于指定产品或门店");
|
||||
}
|
||||
if (item.getId() == null) {
|
||||
if (item.getAllowDecimalQuantity() == null) item.setAllowDecimalQuantity(true);
|
||||
item.setId(UUID.randomUUID().toString());
|
||||
item.setCreatedAt(Time.now());
|
||||
mapper.insertItem(item);
|
||||
} else {
|
||||
TimiException.required(mapper.item(storeId, item.getId()), "回收物不存在");
|
||||
GaoRecycleItem existing = mapper.item(storeId, item.getId());
|
||||
TimiException.required(existing, "回收物不存在");
|
||||
if (item.getAllowDecimalQuantity() == null) item.setAllowDecimalQuantity(existing.getAllowDecimalQuantity());
|
||||
item.setUpdatedAt(Time.now());
|
||||
mapper.updateItem(item);
|
||||
}
|
||||
if (request.getAttachmentList() != null) {
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, item.getId(), request.getAttachmentList());
|
||||
item.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, item.getId()));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -259,39 +240,43 @@ public class GaoRecycleConfigService {
|
||||
TimiException.required(storeId, "门店不能为空");
|
||||
rule.setStoreId(storeId);
|
||||
TimiException.required(rule.getRecycleItemId(), "回收物不能为空");
|
||||
TimiException.required(rule.getSkuId(), "SKU 不能为空");
|
||||
GaoProductSku sku = skuMapper.selectForUpdate(rule.getSkuId());
|
||||
TimiException.required(sku, "SKU 不存在");
|
||||
TimiException.requiredTrue(storeId.equals(sku.getStoreId()), "SKU 不属于当前门店");
|
||||
GaoProduct product = productService.get(sku.getProductId());
|
||||
TimiException.required(product, "产品不存在");
|
||||
TimiException.requiredTrue(storeId.equals(product.getStoreId()), "产品不属于当前门店");
|
||||
if (rule.getId() != null) {
|
||||
TimiException.required(mapper.rule(storeId, rule.getId()), "规则不存在");
|
||||
}
|
||||
TimiException.required(rule.getStatus(), "规则状态不能为空");
|
||||
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
|
||||
TimiException.requiredTrue(product.getStatus() == GaoProduct.Status.ACTIVE && sku.getStatus() == GaoProductSku.Status.ACTIVE, "产品或 SKU 不可用");
|
||||
}
|
||||
TimiException.required(rule.getSkuUnitId(), "单位不能为空");
|
||||
GaoProductSkuUnit unit = skuService.listUnitBySkuId(sku.getId()).stream()
|
||||
.filter(value -> rule.getSkuUnitId().equals(value.getId()))
|
||||
.findFirst().orElse(null);
|
||||
TimiException.required(unit, "SKU 单位不存在");
|
||||
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(unit.getAllowSale()), "单位不可用于销售");
|
||||
}
|
||||
GaoRecycleItem item = mapper.item(storeId, rule.getRecycleItemId());
|
||||
TimiException.required(item, "回收物不存在");
|
||||
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
|
||||
TimiException.requiredTrue(item.getStatus() == GaoRecycleItem.Status.ACTIVE, "回收物已停用");
|
||||
}
|
||||
validateQuantity(rule.getRecycleQuantity());
|
||||
validateQuantity(rule.getExchangeQuantity());
|
||||
if (!Boolean.TRUE.equals(sku.getAllowDecimalQuantity())) {
|
||||
TimiException.requiredTrue(!(0 < rule.getExchangeQuantity().stripTrailingZeros().scale()), "兑换数量不允许小数");
|
||||
List<GaoRecycleExchangeRuleItem> items = request.getItemList();
|
||||
TimiException.requiredTrue(items != null && !items.isEmpty(), "兑换模板明细不能为空");
|
||||
Set<String> keys = new HashSet<>();
|
||||
TimiException.requiredTrue(items.stream().noneMatch(java.util.Objects::isNull), "兑换模板明细不能为空");
|
||||
List<GaoRecycleExchangeRuleItem> ordered = items.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeRuleItem::getSkuId, java.util.Comparator.nullsFirst(String::compareTo))).toList();
|
||||
for (GaoRecycleExchangeRuleItem entry : ordered) {
|
||||
TimiException.required(entry, "兑换模板明细不能为空");
|
||||
TimiException.required(entry.getSkuId(), "SKU 不能为空");
|
||||
TimiException.required(entry.getSkuUnitId(), "单位不能为空");
|
||||
TimiException.requiredTrue(keys.add(entry.getSkuId() + "|" + entry.getSkuUnitId()), "同一模板内 SKU 和单位不能重复");
|
||||
GaoProductSku sku = skuMapper.selectForUpdate(entry.getSkuId());
|
||||
TimiException.required(sku, "SKU 不存在");
|
||||
TimiException.requiredTrue(storeId.equals(sku.getStoreId()), "SKU 不属于当前门店");
|
||||
GaoProduct product = productService.get(sku.getProductId());
|
||||
TimiException.required(product, "产品不存在");
|
||||
TimiException.requiredTrue(storeId.equals(product.getStoreId()), "产品不属于当前门店");
|
||||
GaoProductSkuUnit unit = skuService.listUnitBySkuId(sku.getId()).stream().filter(value -> entry.getSkuUnitId().equals(value.getId())).findFirst().orElse(null);
|
||||
TimiException.required(unit, "SKU 单位不存在");
|
||||
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
|
||||
TimiException.requiredTrue(product.getStatus() == GaoProduct.Status.ACTIVE && sku.getStatus() == GaoProductSku.Status.ACTIVE && Boolean.TRUE.equals(unit.getAllowSale()), "产品、SKU 或单位不可用");
|
||||
}
|
||||
validateQuantity(entry.getExchangeQuantity());
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < entry.getExchangeQuantity().stripTrailingZeros().scale()), "兑换数量不允许小数");
|
||||
TimiException.required(unit.getBaseQuantityPerUnit(), "单位换算系数不能为空");
|
||||
BigDecimal base = entry.getExchangeQuantity().multiply(unit.getBaseQuantityPerUnit());
|
||||
TimiException.requiredTrue(0 < base.signum() && !(3 < base.stripTrailingZeros().scale()) && !(15 < base.precision() - base.scale()), "基础数量超出精度或范围");
|
||||
}
|
||||
TimiException.required(unit.getBaseQuantityPerUnit(), "单位换算系数不能为空");
|
||||
TimiException.requiredTrue(0 < unit.getBaseQuantityPerUnit().signum(), "单位换算系数必须大于零");
|
||||
BigDecimal base = rule.getExchangeQuantity().multiply(unit.getBaseQuantityPerUnit());
|
||||
TimiException.requiredTrue(!(3 < base.stripTrailingZeros().scale()) && !(15 < base.precision() - base.scale()), "基础数量超出精度或范围");
|
||||
validateQuantity(rule.getRecycleQuantity());
|
||||
if (rule.getSort() == null) {
|
||||
rule.setSort(0);
|
||||
}
|
||||
@@ -300,13 +285,32 @@ public class GaoRecycleConfigService {
|
||||
rule.setCreatedAt(Time.now());
|
||||
mapper.insertRule(rule);
|
||||
} else {
|
||||
TimiException.required(mapper.rule(storeId, rule.getId()), "规则不存在");
|
||||
rule.setUpdatedAt(Time.now());
|
||||
mapper.updateRule(rule);
|
||||
}
|
||||
mapper.deleteRuleItems(rule.getId());
|
||||
int position = 0;
|
||||
for (GaoRecycleExchangeRuleItem entry : items) {
|
||||
entry.setId(UUID.randomUUID().toString());
|
||||
entry.setRuleId(rule.getId());
|
||||
entry.setSort(position++);
|
||||
entry.setCreatedAt(Time.now());
|
||||
mapper.insertRuleItem(entry);
|
||||
}
|
||||
fillRuleDisplay(storeId, List.of(rule));
|
||||
return rule;
|
||||
}
|
||||
|
||||
/// 删除兑换模板
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void deleteRule(String storeId, String id) {
|
||||
String resolved = scope.resolveStoreId(storeId);
|
||||
TimiException.required(resolved, "门店不能为空");
|
||||
TimiException.required(mapper.rule(resolved, id), "规则不存在");
|
||||
mapper.deleteRuleItems(id);
|
||||
mapper.deleteRule(resolved, id);
|
||||
}
|
||||
|
||||
private void validateQuantity(BigDecimal quantity) {
|
||||
TimiException.required(quantity, "数量不能为空");
|
||||
TimiException.requiredTrue(0 < quantity.signum() && !(3 < quantity.stripTrailingZeros().scale())
|
||||
|
||||
+9
-25
@@ -2,18 +2,16 @@ package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductStockRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeQueryMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeDetail;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangePage;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.spring.bean.PageResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -24,27 +22,13 @@ import java.util.Map;
|
||||
public class GaoRecycleExchangeQueryService {
|
||||
|
||||
private final GaoRecycleExchangeQueryMapper mapper;
|
||||
private final GaoRecycleConfigMapper configMapper;
|
||||
private final GaoStoreScopeService scopeService;
|
||||
private final AttachmentService attachmentService;
|
||||
private final GaoProductStockRecordService stockRecordService;
|
||||
|
||||
/// 分页查询兑换单
|
||||
/// 查询兑换单、权益明细、操作记录和附件
|
||||
///
|
||||
/// @param page 查询条件
|
||||
/// @return 兑换单分页结果
|
||||
/// @throws TimiException 查询条件或门店范围无效
|
||||
public PageResult<GaoRecycleExchange> page(GaoRecycleExchangePage page) {
|
||||
TimiException.required(page, "查询条件不能为空");
|
||||
TimiException.requiredTrue(-1 < page.getIndex() && 0 < page.getSize() && !(100 < page.getSize()), "分页参数无效");
|
||||
page.setStoreId(scopeService.resolveStoreId(page.getStoreId()));
|
||||
TimiException.required(page.getStoreId(), "请选择门店");
|
||||
PageResult<GaoRecycleExchange> result = new PageResult<>();
|
||||
result.setTotal(mapper.count(page));
|
||||
result.setList(mapper.list(page));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 查询兑换单、操作记录、附件和库存流水
|
||||
/// 库存随履约走,兑换单本身不产生库存流水,所以详情里没有流水列表。
|
||||
///
|
||||
/// @param id 兑换单 ID
|
||||
/// @return 兑换单详情
|
||||
@@ -54,19 +38,19 @@ public class GaoRecycleExchangeQueryService {
|
||||
GaoRecycleExchange exchange = mapper.detail(id);
|
||||
TimiException.required(exchange, "兑换单不存在");
|
||||
scopeService.checkStoreId(exchange.getStoreId());
|
||||
if (exchange.getRecycleItemId() != null) {
|
||||
GaoRecycleItem item = configMapper.itemById(exchange.getStoreId(), exchange.getRecycleItemId());
|
||||
if (item != null) exchange.setAllowDecimalQuantity(item.getAllowDecimalQuantity());
|
||||
}
|
||||
GaoRecycleExchangeDetail detail = new GaoRecycleExchangeDetail();
|
||||
detail.setExchange(exchange);
|
||||
List<GaoRecycleExchangeAction> actions = mapper.actions(id);
|
||||
detail.setActionList(actions);
|
||||
detail.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE, id));
|
||||
Map<String, List<Attachment>> attachments = new HashMap<>();
|
||||
List<GaoProductStockRecord> records = new ArrayList<>(stockRecordService.listByBiz(GaoProductStockRecord.BizType.RECYCLE_EXCHANGE, id));
|
||||
for (GaoRecycleExchangeAction action : actions) {
|
||||
attachments.put(action.getId(), attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId()));
|
||||
records.addAll(stockRecordService.listByBiz(GaoProductStockRecord.BizType.RECYCLE_EXCHANGE, action.getId()));
|
||||
}
|
||||
detail.setActionAttachments(attachments);
|
||||
detail.setStockRecordList(records);
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,11 @@ public class GaoRecycleExchangeViewService {
|
||||
? Map.of()
|
||||
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList, GaoCustomer.AttachType.PHOTO.name());
|
||||
Map<String, User> userMap = userMap(exchangeList.stream().map(GaoRecycleExchange::getOperatorUserId).toList());
|
||||
List<String> itemIdList = distinct(exchangeList.stream().map(GaoRecycleExchange::getRecycleItemId).toList());
|
||||
Map<String, List<Attachment>> itemPhotos = itemIdList.isEmpty() ? Map.of()
|
||||
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIdList);
|
||||
for (GaoRecycleExchange exchange : exchangeList) {
|
||||
exchange.setRecycleItemAttachments(exchange.getRecycleItemId() == null ? List.of() : itemPhotos.getOrDefault(exchange.getRecycleItemId(), List.of()));
|
||||
GaoCustomer customer = exchange.getCustomerId() == null ? null : customerMap.get(exchange.getCustomerId());
|
||||
if (customer != null) {
|
||||
customer.setAttachmentList(customerPhotoMap.getOrDefault(customer.getId(), List.of()));
|
||||
|
||||
+236
-164
@@ -11,9 +11,16 @@ import com.imyeyu.api.modules.gao.entity.GaoProduct;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductStockRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderCancelRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeItemRequest;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
|
||||
@@ -24,6 +31,9 @@ import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeWriteMapper;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeActionRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoStockChangeItem;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentItemRequest;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.api.modules.system.audit.AuditOperation;
|
||||
@@ -32,6 +42,7 @@ import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
@@ -41,6 +52,11 @@ import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
/// 回收兑换交易
|
||||
@Service
|
||||
@@ -60,8 +76,12 @@ public class GaoRecycleExchangeWriteService {
|
||||
private final UserLoginService login;
|
||||
private final PermissionChecker permissions;
|
||||
private final ObjectMapper jackson;
|
||||
private final ObjectProvider<GaoOrderFulfillmentService> fulfillmentServiceProvider;
|
||||
private final GaoSalesOrderService salesOrderService;
|
||||
private final GaoRecyclePaymentService recyclePaymentService;
|
||||
private final GaoRecyclePhysicalService physicalService;
|
||||
|
||||
/// 创建回收兑换并预占库存
|
||||
/// 创建回收兑换权益
|
||||
///
|
||||
/// @param request 创建请求
|
||||
/// @return 兑换单
|
||||
@@ -69,232 +89,284 @@ public class GaoRecycleExchangeWriteService {
|
||||
@OperationAudit(AuditOperation.GAO_RECYCLE_EXCHANGE_CREATE)
|
||||
public GaoRecycleExchange create(GaoRecycleExchangeCreateRequest request) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
return createItems(request);
|
||||
}
|
||||
|
||||
private GaoRecycleExchange createItems(GaoRecycleExchangeCreateRequest request) {
|
||||
String store = scope.resolveStoreId(request.getStoreId());
|
||||
TimiException.required(store, "门店不能为空");
|
||||
TimiException.required(request.getRequestNo(), "请求号不能为空");
|
||||
TimiException.requiredTrue(!request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.required(request.getRuleId(), "规则不能为空");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.required(request.getCustomerId(), "客户不能为空");
|
||||
TimiException.requiredTrue(request.getMultiple() != null && 0 < request.getMultiple(), "倍数必须大于零");
|
||||
String fingerprint = fingerprint(request.getCustomerId(), request.getRuleId(), request.getMultiple(), number(request.getRecycleQuantity()), number(request.getExchangeQuantity()), request.getOccurredAt(), request.getRemark(), attachments(request.getAttachmentList()));
|
||||
// 门店锁串行化同门店请求,确保幂等检查和写入之间不发生竞争
|
||||
String fp = fingerprint(request.getCustomerId(), request.getRuleId(), request.getRecycleItemId(), request.getMultiple(), number(request.getRecycleQuantity()), request.getItemList(), request.getOccurredAt(), request.getRemark(), attachments(request.getAttachmentList()), Boolean.TRUE.equals(request.getVerifyPayment()));
|
||||
BigDecimal paymentQuantity = request.getPaymentQuantity();
|
||||
boolean fulfillAll = Boolean.TRUE.equals(request.getFulfillAll());
|
||||
if (paymentQuantity != null || fulfillAll) {
|
||||
fp = fingerprint(fp, number(paymentQuantity == null ? BigDecimal.ZERO : paymentQuantity), fulfillAll, attachments(request.getFulfillmentAttachmentList()));
|
||||
}
|
||||
if (request.getPaymentAttachmentList() != null && !request.getPaymentAttachmentList().isEmpty()) {
|
||||
fp = fingerprint(fp, attachments(request.getPaymentAttachmentList()));
|
||||
}
|
||||
TimiException.required(mapper.lockStore(store), "门店不存在");
|
||||
GaoRecycleExchange existing = mapper.byRequest(store, request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应的内容不一致");
|
||||
return existing;
|
||||
GaoRecycleExchange previous = mapper.byRequest(store, request.getRequestNo());
|
||||
if (previous != null) {
|
||||
TimiException.requiredTrue(fp.equals(previous.getRequestFingerprint()), "请求号对应的内容不一致");
|
||||
return previous;
|
||||
}
|
||||
// 凭证是核销依据,新建必须上传;幂等重放走上面的分支,不受此约束影响
|
||||
TimiException.requiredTrue(request.getAttachmentList() != null && !request.getAttachmentList().isEmpty(), "请上传兑换凭证");
|
||||
GaoCustomer customer = customerService.get(request.getCustomerId());
|
||||
TimiException.required(customer, "客户不存在");
|
||||
TimiException.requiredTrue(store.equals(customer.getStoreId()), "客户不属于当前门店");
|
||||
GaoRecycleExchangeRule preview = mapper.previewRule(store, request.getRuleId());
|
||||
TimiException.required(preview, "兑换规则不存在");
|
||||
GaoProductSku skuPreview = skuMapper.select(preview.getSkuId());
|
||||
TimiException.required(skuPreview, "SKU 不存在");
|
||||
GaoProduct product = productMapper.selectForUpdate(skuPreview.getProductId());
|
||||
TimiException.required(product, "产品不存在");
|
||||
GaoProductSku sku = skuMapper.selectForUpdate(preview.getSkuId());
|
||||
TimiException.required(sku, "SKU 不存在");
|
||||
TimiException.requiredTrue(product.getId().equals(sku.getProductId()), "SKU 产品已变更,请重试");
|
||||
GaoRecycleItem item = configMapper.item(store, preview.getRecycleItemId());
|
||||
GaoRecycleExchangeRule rule = configMapper.rule(store, request.getRuleId());
|
||||
TimiException.required(item, "回收物不存在");
|
||||
TimiException.required(rule, "兑换规则不存在");
|
||||
TimiException.requiredTrue(rule.getSkuId().equals(preview.getSkuId()) && rule.getRecycleItemId().equals(preview.getRecycleItemId()), "规则已变更,请重试");
|
||||
TimiException.requiredTrue(rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE && item.getStatus() == GaoRecycleItem.Status.ACTIVE, "兑换规则或回收物已停用");
|
||||
TimiException.requiredTrue(store.equals(sku.getStoreId()) && sku.getStatus() == GaoProductSku.Status.ACTIVE, "SKU 不可用");
|
||||
TimiException.requiredTrue(store.equals(product.getStoreId()) && product.getStatus() == GaoProduct.Status.ACTIVE, "产品不可用");
|
||||
GaoProductSkuUnit unit = unitMapper.selectForUpdate(rule.getSkuUnitId());
|
||||
TimiException.required(unit, "单位不存在");
|
||||
TimiException.requiredTrue(sku.getId().equals(unit.getSkuId()) && Boolean.TRUE.equals(unit.getAllowSale()), "单位不可用于销售");
|
||||
TimiException.requiredTrue(product.getProductType() != GaoProduct.ProductType.SERVICE || !Boolean.TRUE.equals(sku.getStockEnabled()), "服务不允许管理库存");
|
||||
BigDecimal presetRecycle = quantity(rule.getRecycleQuantity().multiply(BigDecimal.valueOf(request.getMultiple())));
|
||||
BigDecimal presetExchange = quantity(rule.getExchangeQuantity().multiply(BigDecimal.valueOf(request.getMultiple())));
|
||||
BigDecimal actualRecycle = quantity(request.getRecycleQuantity() == null ? presetRecycle : request.getRecycleQuantity());
|
||||
BigDecimal actualExchange = quantity(request.getExchangeQuantity() == null ? presetExchange : request.getExchangeQuantity());
|
||||
if (actualRecycle.compareTo(presetRecycle) != 0 || actualExchange.compareTo(presetExchange) != 0) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.RECYCLE_EXCHANGE_QUANTITY_ADJUST.getValue());
|
||||
boolean free = request.getRuleId() == null || request.getRuleId().isBlank();
|
||||
boolean canAdjust = permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_PRICE_OVERRIDE.getValue());
|
||||
TimiException.requiredTrue(!free || canAdjust, "缺少自由创建兑换单权限");
|
||||
GaoRecycleExchangeRule rule = free ? null : configMapper.rule(store, request.getRuleId());
|
||||
TimiException.requiredTrue(free || rule != null && rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE, "兑换模板不存在或已停用");
|
||||
int multiple = free ? 1 : request.getMultiple() == null ? 1 : request.getMultiple();
|
||||
TimiException.requiredTrue(0 < multiple, "兑换份数必须大于零");
|
||||
String itemId = request.getRecycleItemId() == null ? free ? null : rule.getRecycleItemId() : request.getRecycleItemId();
|
||||
TimiException.required(itemId, "回收物不能为空");
|
||||
GaoRecycleItem item = configMapper.item(store, itemId);
|
||||
TimiException.requiredTrue(item != null && item.getStatus() == GaoRecycleItem.Status.ACTIVE, "回收物不存在或已停用");
|
||||
BigDecimal preset = free ? null : quantity(rule.getRecycleQuantity().multiply(BigDecimal.valueOf(multiple)));
|
||||
BigDecimal actual = quantity(request.getRecycleQuantity() == null ? preset : request.getRecycleQuantity());
|
||||
if (!free && (!itemId.equals(rule.getRecycleItemId()) || actual.compareTo(preset) != 0)) {
|
||||
TimiException.requiredTrue(canAdjust, "缺少兑换数量调整权限");
|
||||
}
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < actualExchange.stripTrailingZeros().scale()), "兑换数量不允许小数");
|
||||
TimiException.required(unit.getBaseQuantityPerUnit(), "单位换算系数不能为空");
|
||||
BigDecimal base = quantity(actualExchange.multiply(unit.getBaseQuantityPerUnit()));
|
||||
List<GaoRecycleExchangeRuleItem> defaults = free ? List.of() : configMapper.ruleItems(rule.getId());
|
||||
TimiException.requiredTrue(free || !defaults.isEmpty(), "兑换模板没有明细");
|
||||
List<GaoRecycleExchangeItemRequest> inputs = request.getItemList();
|
||||
if (inputs == null || inputs.isEmpty()) {
|
||||
inputs = new ArrayList<>();
|
||||
for (GaoRecycleExchangeRuleItem source : defaults) {
|
||||
GaoRecycleExchangeItemRequest input = new GaoRecycleExchangeItemRequest();
|
||||
input.setSkuId(source.getSkuId());
|
||||
input.setSkuUnitId(source.getSkuUnitId());
|
||||
input.setQuantity(quantity(source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple))));
|
||||
inputs.add(input);
|
||||
}
|
||||
}
|
||||
TimiException.requiredTrue(!inputs.isEmpty(), "兑换明细不能为空");
|
||||
Map<String, BigDecimal> expected = new HashMap<>();
|
||||
Map<String, BigDecimal> maxUnitBySku = new HashMap<>();
|
||||
for (GaoRecycleExchangeRuleItem source : defaults.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeRuleItem::getSkuId).thenComparing(GaoRecycleExchangeRuleItem::getSkuUnitId)).toList()) {
|
||||
GaoProductSkuUnit unit = unitMapper.select(source.getSkuUnitId());
|
||||
TimiException.requiredTrue(unit != null && source.getSkuId().equals(unit.getSkuId()), "模板单位无效");
|
||||
expected.merge(source.getSkuId(), source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple)).multiply(unit.getBaseQuantityPerUnit()), BigDecimal::add);
|
||||
maxUnitBySku.merge(source.getSkuId(), unit.getBaseQuantityPerUnit(), BigDecimal::max);
|
||||
}
|
||||
Map<String, BigDecimal> actualBySku = new HashMap<>();
|
||||
Set<String> unique = new HashSet<>();
|
||||
List<GaoSalesOrderItem> entries = new ArrayList<>();
|
||||
long now = Time.now();
|
||||
for (GaoRecycleExchangeItemRequest input : inputs) {
|
||||
TimiException.required(input, "兑换明细不能为空");
|
||||
TimiException.required(input.getSkuId(), "SKU 不能为空");
|
||||
TimiException.required(input.getSkuUnitId(), "单位不能为空");
|
||||
}
|
||||
for (GaoRecycleExchangeItemRequest input : inputs.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeItemRequest::getSkuId).thenComparing(GaoRecycleExchangeItemRequest::getSkuUnitId)).toList()) {
|
||||
TimiException.required(input, "兑换明细不能为空");
|
||||
TimiException.required(input.getSkuId(), "SKU 不能为空");
|
||||
TimiException.required(input.getSkuUnitId(), "单位不能为空");
|
||||
TimiException.requiredTrue(unique.add(input.getSkuId() + "|" + input.getSkuUnitId()), "同一 SKU 和单位不能重复");
|
||||
var selection = skuService.getSellableSkuUnit(store, input.getSkuId(), input.getSkuUnitId());
|
||||
GaoProduct product = selection.getProduct();
|
||||
GaoProductSku sku = selection.getSku();
|
||||
GaoProductSkuUnit unit = selection.getUnit();
|
||||
if (!free && !canAdjust) {
|
||||
BigDecimal maximum = maxUnitBySku.get(sku.getId());
|
||||
TimiException.requiredTrue(maximum != null && 0 <= maximum.compareTo(unit.getBaseQuantityPerUnit()), "兑换权益单位不能高于模板单位");
|
||||
}
|
||||
BigDecimal value = quantity(input.getQuantity());
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < value.stripTrailingZeros().scale()), "兑换数量不允许小数");
|
||||
BigDecimal base = quantity(value.multiply(unit.getBaseQuantityPerUnit()));
|
||||
actualBySku.merge(sku.getId(), base, BigDecimal::add);
|
||||
GaoSalesOrderItem entry = new GaoSalesOrderItem();
|
||||
entry.setSkuId(sku.getId());
|
||||
entry.setSkuUnitId(unit.getId());
|
||||
entry.setProductIdSnapshot(product.getId());
|
||||
entry.setProductNameSnapshot(product.getName());
|
||||
entry.setSkuCodeSnapshot(sku.getCode());
|
||||
entry.setSkuNameSnapshot(sku.getName());
|
||||
entry.setSpecSummarySnapshot(sku.getSpecSummary());
|
||||
entry.setSkuSpecSnapshot(skuService.getSkuSpecSnapshot(sku));
|
||||
entry.setUnitSnapshot(unit.getName());
|
||||
entry.setBaseQuantityPerUnitSnapshot(unit.getBaseQuantityPerUnit());
|
||||
entry.setQuantity(value);
|
||||
entry.setBaseQuantity(base);
|
||||
// 订单创建要求履约数量非空,兑换单场景一律从零开始
|
||||
entry.setReservedBaseQuantity(BigDecimal.ZERO);
|
||||
entry.setFulfilledBaseQuantity(BigDecimal.ZERO);
|
||||
entry.setAllowDecimalQuantity(sku.getAllowDecimalQuantity());
|
||||
entry.setItemType(GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT);
|
||||
entry.setSort(entries.size());
|
||||
entries.add(entry);
|
||||
}
|
||||
if (!free && !canAdjust) {
|
||||
TimiException.requiredTrue(defaults.size() == inputs.size(), "兑换明细必须与模板一致");
|
||||
for (GaoRecycleExchangeRuleItem source : defaults) {
|
||||
BigDecimal required = source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple));
|
||||
TimiException.requiredTrue(inputs.stream().anyMatch(input -> source.getSkuId().equals(input.getSkuId()) && source.getSkuUnitId().equals(input.getSkuUnitId()) && input.getQuantity() != null && required.compareTo(input.getQuantity()) == 0), "兑换明细必须与模板一致");
|
||||
}
|
||||
TimiException.requiredTrue(expected.size() == actualBySku.size(), "兑换商品与模板不一致");
|
||||
for (var entry : expected.entrySet()) {
|
||||
TimiException.requiredTrue(actualBySku.containsKey(entry.getKey()) && entry.getValue().compareTo(actualBySku.get(entry.getKey())) == 0, "兑换数量与模板不一致");
|
||||
}
|
||||
}
|
||||
GaoRecycleExchange result = new GaoRecycleExchange();
|
||||
result.setId(UUID.randomUUID().toString());
|
||||
result.setStoreId(store);
|
||||
result.setCustomerId(customer.getId());
|
||||
result.setRequestNo(request.getRequestNo());
|
||||
result.setRequestFingerprint(fingerprint);
|
||||
result.setRuleId(rule.getId());
|
||||
result.setRequestFingerprint(fp);
|
||||
result.setRuleId(free ? null : rule.getId());
|
||||
if (!free) {
|
||||
rule.setItemList(defaults);
|
||||
result.setRuleSnapshot(jackson.valueToTree(rule));
|
||||
}
|
||||
result.setRecycleItemId(item.getId());
|
||||
result.setRecycleNameSnapshot(item.getName());
|
||||
result.setRecycleUnitSnapshot(item.getUnitName());
|
||||
result.setSourceProductIdSnapshot(item.getProductId());
|
||||
result.setSourceSkuIdSnapshot(item.getSkuId());
|
||||
result.setRuleRecycleQuantity(rule.getRecycleQuantity());
|
||||
result.setRuleExchangeQuantity(rule.getExchangeQuantity());
|
||||
result.setMultiple(request.getMultiple());
|
||||
result.setDefaultRecycleQuantity(presetRecycle);
|
||||
result.setDefaultExchangeQuantity(presetExchange);
|
||||
result.setRecycleQuantity(actualRecycle);
|
||||
result.setExchangeQuantity(actualExchange);
|
||||
result.setProductIdSnapshot(product.getId());
|
||||
result.setProductNameSnapshot(product.getName());
|
||||
result.setProductTypeSnapshot(product.getProductType().name());
|
||||
result.setSkuIdSnapshot(sku.getId());
|
||||
result.setSkuCodeSnapshot(sku.getCode());
|
||||
result.setSkuNameSnapshot(sku.getName());
|
||||
result.setSpecSummarySnapshot(sku.getSpecSummary());
|
||||
result.setSkuSpecSnapshot(skuService.getSkuSpecSnapshot(sku));
|
||||
result.setSkuUnitIdSnapshot(unit.getId());
|
||||
result.setUnitSnapshot(unit.getName());
|
||||
result.setBaseQuantityPerUnitSnapshot(unit.getBaseQuantityPerUnit());
|
||||
result.setBaseQuantity(base);
|
||||
result.setAllowDecimalSnapshot(sku.getAllowDecimalQuantity());
|
||||
result.setStockEnabledSnapshot(sku.getStockEnabled());
|
||||
result.setRuleRecycleQuantity(free ? null : rule.getRecycleQuantity());
|
||||
result.setMultiple(free ? null : multiple);
|
||||
result.setDefaultRecycleQuantity(preset);
|
||||
result.setRecycleQuantity(actual);
|
||||
result.setStatus(GaoRecycleExchange.Status.PENDING);
|
||||
result.setOperatorUserId(login.getRequireLoginUserId());
|
||||
result.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
result.setRemark(request.getRemark());
|
||||
result.setCreatedAt(now);
|
||||
GaoPackageOrderCreateData orderData = new GaoPackageOrderCreateData();
|
||||
orderData.setStoreId(store);
|
||||
orderData.setCustomerId(customer.getId());
|
||||
orderData.setRequestNo("recycle:" + result.getId());
|
||||
orderData.setPurchasedAt(result.getOccurredAt());
|
||||
orderData.setOperatorUserId(result.getOperatorUserId());
|
||||
orderData.setRemark(result.getRemark());
|
||||
orderData.setItemList(entries);
|
||||
result.setSalesOrderId(salesOrderService.createRecycleOrder(orderData, item.getId(), actual).getId());
|
||||
mapper.insert(result);
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE, result.getId(), request.getAttachmentList());
|
||||
if (Boolean.TRUE.equals(result.getStockEnabledSnapshot())) {
|
||||
stockService.reserveForRecycleExchange(store, result.getId(), List.of(stockItem(result)), "recycle:reserve:" + result.getId(), result.getOperatorUserId());
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_SALES_ORDER, result.getSalesOrderId(), request.getAttachmentList());
|
||||
BigDecimal paid = paymentQuantity == null ? (Boolean.TRUE.equals(request.getVerifyPayment()) ? actual : BigDecimal.ZERO) : paymentQuantity;
|
||||
TimiException.requiredTrue(0 <= paid.signum() && !(3 < paid.stripTrailingZeros().scale()) && 0 <= actual.compareTo(paid), "已回收数量无效或超过应回收数量");
|
||||
TimiException.requiredTrue(!Boolean.TRUE.equals(request.getVerifyPayment()) || paymentQuantity == null || actual.compareTo(paid) == 0, "全部回收数量必须等于应回收数量");
|
||||
TimiException.requiredTrue(!fulfillAll || actual.compareTo(paid) == 0, "全部履约前必须全部回收并核销");
|
||||
if (0 < paid.signum()) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.FUND_RECEIVE_CREATE.getValue(), GaoPermissionCode.FUND_RECEIVE_VERIFY.getValue());
|
||||
GaoRecyclePaymentRequest payment = new GaoRecyclePaymentRequest();
|
||||
payment.setOrderId(result.getSalesOrderId());
|
||||
payment.setRequestNo("recycle:create:" + result.getId());
|
||||
payment.setQuantity(paid);
|
||||
payment.setOccurredAt(request.getOccurredAt());
|
||||
payment.setAttachmentList(request.getPaymentAttachmentList());
|
||||
recyclePaymentService.createAndVerify(payment);
|
||||
}
|
||||
if (fulfillAll) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue(), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY.getValue());
|
||||
GaoOrderFulfillmentCreateRequest fulfillment = new GaoOrderFulfillmentCreateRequest();
|
||||
fulfillment.setSalesOrderId(result.getSalesOrderId());
|
||||
fulfillment.setRequestNo("recycle:fulfill:" + result.getId());
|
||||
fulfillment.setDeliveredAt(request.getOccurredAt());
|
||||
fulfillment.setAttachmentList(request.getFulfillmentAttachmentList());
|
||||
List<GaoOrderFulfillmentItemRequest> fulfillmentItems = new ArrayList<>();
|
||||
for (GaoSalesOrderItem entry : salesOrderService.listItemByOrderId(result.getSalesOrderId())) {
|
||||
GaoOrderFulfillmentItemRequest fulfillmentItem = new GaoOrderFulfillmentItemRequest();
|
||||
fulfillmentItem.setSourceOrderItemId(entry.getId());
|
||||
fulfillmentItem.setSkuUnitId(entry.getSkuUnitId());
|
||||
fulfillmentItem.setQuantity(entry.getQuantity());
|
||||
fulfillmentItems.add(fulfillmentItem);
|
||||
}
|
||||
fulfillment.setItemList(fulfillmentItems);
|
||||
fulfillmentServiceProvider.getObject().createAndVerify(fulfillment);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 核销、撤销或冲正兑换单
|
||||
///
|
||||
/// @param request 操作请求
|
||||
/// @param type 操作类型
|
||||
/// @return 更新后的兑换单
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
@OperationAudit(AuditOperation.GAO_RECYCLE_EXCHANGE_ACTION)
|
||||
public GaoRecycleExchange apply(GaoRecycleExchangeActionRequest request, GaoRecycleExchangeAction.ActionType type) {
|
||||
public GaoRecycleExchange cancelFromOrder(GaoRecycleExchangeActionRequest request, GaoSalesOrderCancelRequest orderRequest) {
|
||||
return cancelInternal(request, orderRequest);
|
||||
}
|
||||
|
||||
private GaoRecycleExchange cancelInternal(GaoRecycleExchangeActionRequest request, GaoSalesOrderCancelRequest orderRequest) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
TimiException.required(request.getExchangeId(), "兑换单不能为空");
|
||||
TimiException.required(request.getRequestNo(), "请求号不能为空");
|
||||
TimiException.requiredTrue(!request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
// 门店是兑换单自身的属性,调用方不必重复传:按 ID 取单快照确定门店,
|
||||
// 再用单据门店加锁串行化,越权访问由 checkStoreId 拦住
|
||||
GaoRecycleExchange snapshot = mapper.byId(request.getExchangeId());
|
||||
TimiException.required(snapshot, "兑换单不存在");
|
||||
scope.checkStoreId(snapshot.getStoreId());
|
||||
String store = snapshot.getStoreId();
|
||||
String fingerprint = fingerprint(request.getExchangeId(), type, request.getOccurredAt(), request.getReason(), request.getRemark(), request.getRecycleReturned(), request.getStockReturned(), attachments(request.getAttachmentList()));
|
||||
// 门店锁串行化同门店请求,确保幂等检查和写入之间不发生竞争
|
||||
String fingerprint = fingerprint(request.getExchangeId(), GaoRecycleExchangeAction.ActionType.CANCEL, request.getOccurredAt(), request.getReason(), request.getRemark(), number(request.getRetainedRecycleQuantity()), request.getFulfillmentRevokeList(), request.getPaymentRevokeList(), attachments(request.getAttachmentList()));
|
||||
TimiException.required(mapper.lockStore(store), "门店不存在");
|
||||
GaoRecycleExchangeAction existing = mapper.actionByRequest(store, request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应的操作内容不一致");
|
||||
GaoRecycleExchange previous = mapper.lockExchange(store, existing.getExchangeId());
|
||||
TimiException.required(previous, "兑换单不存在");
|
||||
return previous;
|
||||
return mapper.lockExchange(store, existing.getExchangeId());
|
||||
}
|
||||
TimiException.required(snapshot.getSalesOrderId(), "兑换订单不存在");
|
||||
salesOrderService.getForUpdate(snapshot.getSalesOrderId());
|
||||
GaoRecycleExchange exchange = mapper.lockExchange(store, request.getExchangeId());
|
||||
TimiException.required(exchange, "兑换单不存在");
|
||||
GaoRecycleExchange.Status expected = type == GaoRecycleExchangeAction.ActionType.REVOKE ? GaoRecycleExchange.Status.VERIFIED : GaoRecycleExchange.Status.PENDING;
|
||||
TimiException.requiredTrue(exchange.getStatus() == expected, "兑换单状态不允许此操作");
|
||||
if (type != GaoRecycleExchangeAction.ActionType.VERIFY) {
|
||||
TimiException.required(request.getRecycleReturned(), "必须确认回收物是否退还");
|
||||
}
|
||||
if (type == GaoRecycleExchangeAction.ActionType.REVOKE) {
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "冲正原因不能为空");
|
||||
if (Boolean.TRUE.equals(exchange.getStockEnabledSnapshot())) {
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(request.getStockReturned()), "必须确认商品已退回门店");
|
||||
TimiException.requiredTrue(request.getAttachmentList() != null && request.getAttachmentList().stream().anyMatch(a -> a != null && "PHOTO".equalsIgnoreCase(a.getAttachType())), "库存商品冲正必须上传照片");
|
||||
// 已完成只代表权益领完,回收物归属仍需能修正,所以也允许撤销
|
||||
TimiException.requiredTrue(exchange.getStatus() == GaoRecycleExchange.Status.PENDING || exchange.getStatus() == GaoRecycleExchange.Status.COMPLETED, "兑换单状态不允许撤销");
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "撤销原因不能为空");
|
||||
TimiException.required(exchange.getSalesOrderId(), "兑换订单不存在");
|
||||
var lockedOrder = salesOrderService.getForUpdate(exchange.getSalesOrderId());
|
||||
if (request.getPaymentRevokeList() != null && !request.getPaymentRevokeList().isEmpty()) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.FUND_REVOKE.getValue());
|
||||
Set<String> allowed = new HashSet<>();
|
||||
for (var payment : recyclePaymentService.list(exchange.getSalesOrderId())) {
|
||||
allowed.add(payment.getId());
|
||||
}
|
||||
Set<String> selected = new HashSet<>();
|
||||
for (GaoRecyclePaymentRequest payment : request.getPaymentRevokeList()) {
|
||||
TimiException.required(payment, "支付冲正请求不能为空");
|
||||
TimiException.requiredTrue(allowed.contains(payment.getPaymentId()) && selected.add(payment.getPaymentId()), "支付记录不属于兑换订单或重复选择");
|
||||
if (payment.getReason() == null || payment.getReason().isBlank()) payment.setReason(request.getReason());
|
||||
recyclePaymentService.revoke(payment);
|
||||
}
|
||||
}
|
||||
BigDecimal received = physicalService.balance(exchange.getSalesOrderId());
|
||||
BigDecimal retained = request.getRetainedRecycleQuantity() == null ? received : request.getRetainedRecycleQuantity();
|
||||
TimiException.requiredTrue(0 <= retained.signum() && 0 <= received.compareTo(retained) && !(3 < retained.stripTrailingZeros().scale()), "保留回收物数量超过实际收到数量");
|
||||
GaoSalesOrderCancelRequest cancelOrder = orderRequest == null ? new GaoSalesOrderCancelRequest() : orderRequest;
|
||||
cancelOrder.setSalesOrderId(exchange.getSalesOrderId());
|
||||
cancelOrder.setRequestNo(request.getRequestNo());
|
||||
cancelOrder.setReason(request.getReason());
|
||||
if (orderRequest == null) cancelOrder.setAttachmentList(request.getAttachmentList());
|
||||
if (orderRequest == null) cancelOrder.setFulfillmentRevokeList(request.getFulfillmentRevokeList());
|
||||
salesOrderService.cancel(cancelOrder);
|
||||
long now = Time.now();
|
||||
GaoRecycleExchangeAction action = new GaoRecycleExchangeAction();
|
||||
action.setId(UUID.randomUUID().toString());
|
||||
BigDecimal remainingReturn = received.subtract(retained);
|
||||
for (var payment : recyclePaymentService.list(exchange.getSalesOrderId())) {
|
||||
if (payment.getSourcePaymentId() != null || remainingReturn.signum() == 0) continue;
|
||||
BigDecimal available = physicalService.paymentBalance(exchange.getSalesOrderId(), payment.getId());
|
||||
BigDecimal returned = remainingReturn.min(available);
|
||||
if (0 < returned.signum()) {
|
||||
physicalService.record(lockedOrder, "EXCHANGE_CANCEL", action.getId(), payment.getId(), false, returned, request.getOccurredAt());
|
||||
remainingReturn = remainingReturn.subtract(returned);
|
||||
}
|
||||
}
|
||||
TimiException.requiredTrue(remainingReturn.signum() == 0, "回收实物退回数量不一致");
|
||||
action.setStoreId(store);
|
||||
action.setExchangeId(exchange.getId());
|
||||
action.setRequestNo(request.getRequestNo());
|
||||
action.setRequestFingerprint(fingerprint);
|
||||
action.setActionType(type);
|
||||
action.setActionType(GaoRecycleExchangeAction.ActionType.CANCEL);
|
||||
action.setOperatorUserId(login.getRequireLoginUserId());
|
||||
action.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
action.setCreatedAt(now);
|
||||
action.setReason(request.getReason());
|
||||
action.setRemark(request.getRemark());
|
||||
if (type != GaoRecycleExchangeAction.ActionType.VERIFY) {
|
||||
action.setRecycleReturned(request.getRecycleReturned());
|
||||
}
|
||||
if (type == GaoRecycleExchangeAction.ActionType.REVOKE && Boolean.TRUE.equals(exchange.getStockEnabledSnapshot())) {
|
||||
action.setStockReturned(true);
|
||||
}
|
||||
if (Boolean.TRUE.equals(exchange.getStockEnabledSnapshot())) {
|
||||
GaoStockChangeItem stock = stockItem(exchange);
|
||||
if (type == GaoRecycleExchangeAction.ActionType.VERIFY) {
|
||||
stockService.outForRecycleExchange(store, exchange.getId(), List.of(stock), "recycle:out:" + exchange.getId(), action.getOperatorUserId());
|
||||
GaoProductStockRecord record = stockRecordMapper.selectByBizSku(GaoProductStockRecord.BizType.RECYCLE_EXCHANGE, exchange.getId(), exchange.getSkuIdSnapshot(), GaoProductStockRecord.OperationType.RECYCLE_OUT);
|
||||
TimiException.required(record, "兑换出库流水不存在");
|
||||
action.setStockRecordId(record.getId());
|
||||
} else if (type == GaoRecycleExchangeAction.ActionType.CANCEL) {
|
||||
stockService.releaseForRecycleExchange(store, exchange.getId(), List.of(stock), "recycle:release:" + exchange.getId(), action.getOperatorUserId());
|
||||
GaoProductStockRecord record = stockRecordMapper.selectByBizSku(GaoProductStockRecord.BizType.RECYCLE_EXCHANGE, exchange.getId(), exchange.getSkuIdSnapshot(), GaoProductStockRecord.OperationType.RECYCLE_RELEASE);
|
||||
TimiException.required(record, "兑换释放流水不存在");
|
||||
action.setStockRecordId(record.getId());
|
||||
} else {
|
||||
GaoRecycleExchangeAction verify = mapper.verifyAction(exchange.getId());
|
||||
TimiException.required(verify, "核销记录不存在");
|
||||
TimiException.required(verify.getStockRecordId(), "出库流水不存在");
|
||||
GaoProductStockRecord source = stockRecordMapper.selectForUpdate(verify.getStockRecordId());
|
||||
TimiException.required(source, "出库流水不存在");
|
||||
TimiException.requiredTrue(store.equals(source.getStoreId()) && exchange.getId().equals(source.getBizId()) && exchange.getSkuIdSnapshot().equals(source.getSkuId()) && source.getBizType() == GaoProductStockRecord.BizType.RECYCLE_EXCHANGE && source.getOperationType() == GaoProductStockRecord.OperationType.RECYCLE_OUT && source.getBaseQuantity().compareTo(exchange.getBaseQuantity()) == 0, "出库流水与兑换单不一致");
|
||||
stock.setSourceRecordId(verify.getStockRecordId());
|
||||
action.setSourceStockRecordId(verify.getStockRecordId());
|
||||
stockService.revokeForRecycleExchange(store, action.getId(), List.of(stock), "recycle:revoke:" + exchange.getId(), action.getOperatorUserId());
|
||||
GaoProductStockRecord record = stockRecordMapper.selectByBizSku(GaoProductStockRecord.BizType.RECYCLE_EXCHANGE, action.getId(), exchange.getSkuIdSnapshot(), GaoProductStockRecord.OperationType.RECYCLE_REVOKE);
|
||||
TimiException.required(record, "兑换冲正流水不存在");
|
||||
action.setStockRecordId(record.getId());
|
||||
}
|
||||
}
|
||||
action.setRetainedRecycleQuantity(retained);
|
||||
mapper.insertAction(action);
|
||||
if (type == GaoRecycleExchangeAction.ActionType.REVOKE) {
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId(), request.getAttachmentList());
|
||||
if (Boolean.TRUE.equals(exchange.getStockEnabledSnapshot())) {
|
||||
List<Attachment> saved = attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, List.of(action.getId())).getOrDefault(action.getId(), List.of());
|
||||
TimiException.requiredTrue(saved.stream().anyMatch(a -> "PHOTO".equalsIgnoreCase(a.getAttachType()) && a.getMimeType() != null && a.getMimeType().startsWith("image/")), "库存商品冲正必须上传图片文件");
|
||||
}
|
||||
}
|
||||
GaoRecycleExchange.Status target = switch (type) {
|
||||
case VERIFY -> GaoRecycleExchange.Status.VERIFIED;
|
||||
case CANCEL -> GaoRecycleExchange.Status.CANCELLED;
|
||||
case REVOKE -> GaoRecycleExchange.Status.REVOKED;
|
||||
};
|
||||
TimiException.requiredTrue(mapper.updateStatus(exchange.getId(), target, expected, now) == 1, "兑换单状态已变更");
|
||||
exchange.setStatus(target);
|
||||
if (orderRequest == null) attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId(), request.getAttachmentList());
|
||||
TimiException.requiredTrue(mapper.cancel(exchange.getId(), now) == 1, "兑换单状态已变更");
|
||||
exchange.setStatus(GaoRecycleExchange.Status.CANCELLED);
|
||||
exchange.setUpdatedAt(now);
|
||||
return exchange;
|
||||
}
|
||||
|
||||
/// 根据兑换单快照构建库存变更项
|
||||
///
|
||||
/// @param exchange 兑换单
|
||||
/// @return 库存变更项
|
||||
private GaoStockChangeItem stockItem(GaoRecycleExchange exchange) {
|
||||
GaoStockChangeItem item = new GaoStockChangeItem();
|
||||
item.setSkuId(exchange.getSkuIdSnapshot());
|
||||
item.setSkuUnitId(exchange.getSkuUnitIdSnapshot());
|
||||
item.setProductIdSnapshot(exchange.getProductIdSnapshot());
|
||||
item.setProductNameSnapshot(exchange.getProductNameSnapshot());
|
||||
item.setSkuCodeSnapshot(exchange.getSkuCodeSnapshot());
|
||||
item.setSkuNameSnapshot(exchange.getSkuNameSnapshot());
|
||||
item.setSpecSummarySnapshot(exchange.getSpecSummarySnapshot());
|
||||
item.setUnitSnapshot(exchange.getUnitSnapshot());
|
||||
item.setBaseQuantityPerUnitSnapshot(exchange.getBaseQuantityPerUnitSnapshot());
|
||||
item.setQuantity(exchange.getExchangeQuantity());
|
||||
item.setBaseQuantity(exchange.getBaseQuantity());
|
||||
item.setSkuSpecSnapshot(exchange.getSkuSpecSnapshot());
|
||||
return item;
|
||||
}
|
||||
|
||||
/// 校验数量范围和精度
|
||||
///
|
||||
/// @param value 数量
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecyclePaymentMapper;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderTransactionView;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.api.modules.user.service.UserService;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Objects;
|
||||
import java.util.HexFormat;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/// 回收物支付服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecyclePaymentService {
|
||||
private final GaoRecyclePaymentMapper mapper;
|
||||
private final GaoRecycleAccountService accounts;
|
||||
private final GaoSalesOrderService orders;
|
||||
private final GaoStoreScopeService scope;
|
||||
private final UserLoginService login;
|
||||
private final AttachmentService attachments;
|
||||
private final ObjectMapper jackson;
|
||||
private final GaoFundRecordService funds;
|
||||
private final GaoRecyclePhysicalService physical;
|
||||
private final GaoCustomerService customers;
|
||||
private final UserService users;
|
||||
|
||||
/// 判断订单回收物支付是否已结清
|
||||
public boolean isSettled(GaoSalesOrder order) {
|
||||
return order.getRecycleRequiredQuantity() != null && 0 <= mapper.paid(order.getId()).compareTo(order.getRecycleRequiredQuantity());
|
||||
}
|
||||
|
||||
/// 查询订单的回收物支付记录
|
||||
public List<GaoRecyclePayment> list(String orderId) {
|
||||
GaoSalesOrder order = orders.get(orderId);
|
||||
TimiException.required(order, "订单不存在");
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
List<GaoRecyclePayment> payments = mapper.list(orderId);
|
||||
fillAttachments(payments);
|
||||
fillCustomers(payments);
|
||||
fillUsers(payments);
|
||||
return payments;
|
||||
}
|
||||
|
||||
/// 按门店和筛选条件分页查询回收流水。
|
||||
public List<GaoRecyclePayment> search(String storeId, String customerId, String orderId, String status, Long beginAt, Long endAt, int offset, int limit) {
|
||||
TimiException.requiredTrue(0 <= offset && 0 < limit && limit <= 101, "分页参数无效");
|
||||
String resolvedStoreId = scope.resolveStoreId(storeId);
|
||||
List<GaoRecyclePayment> payments = mapper.search(resolvedStoreId, customerId, orderId, status, beginAt, endAt, offset, limit);
|
||||
fillAttachments(payments);
|
||||
fillCustomers(payments);
|
||||
fillUsers(payments);
|
||||
return payments;
|
||||
}
|
||||
|
||||
/// 批量回填人员的展示信息。
|
||||
private void fillUsers(List<GaoRecyclePayment> payments) {
|
||||
var ids = payments.stream().flatMap(payment -> java.util.stream.Stream.of(payment.getOperatorUserId(), payment.getVerifierUserId()))
|
||||
.filter(id -> id != null && !id.isBlank()).distinct().toList();
|
||||
if (ids.isEmpty()) return;
|
||||
var userMap = users.mapByIdList(ids);
|
||||
for (GaoRecyclePayment payment : payments) {
|
||||
payment.setOperator(payment.getOperatorUserId() == null ? null : displayUser(userMap.get(payment.getOperatorUserId())));
|
||||
payment.setVerifier(payment.getVerifierUserId() == null ? null : displayUser(userMap.get(payment.getVerifierUserId())));
|
||||
}
|
||||
}
|
||||
|
||||
private User displayUser(User source) {
|
||||
if (source == null) return null;
|
||||
User user = new User();
|
||||
user.setId(source.getId());
|
||||
user.setName(source.getName());
|
||||
user.setNick(source.getNick());
|
||||
return user;
|
||||
}
|
||||
|
||||
private void fillCustomers(List<GaoRecyclePayment> payments) {
|
||||
List<String> ids = payments.stream().map(GaoRecyclePayment::getCustomerId).filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) return;
|
||||
var customerMap = customers.mapByIdList(ids);
|
||||
var photoMap = attachments.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, ids);
|
||||
for (GaoRecyclePayment payment : payments) {
|
||||
var customer = customerMap.get(payment.getCustomerId());
|
||||
if (customer == null) continue;
|
||||
customer.setAttachmentList(photoMap.getOrDefault(customer.getId(), List.of()));
|
||||
payment.setCustomer(customer);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按授权范围聚合订单交易
|
||||
public List<GaoOrderTransactionView> transactions(String orderId, boolean fundAllowed, boolean recycleAllowed) {
|
||||
GaoSalesOrder order = orders.get(orderId);
|
||||
TimiException.required(order, "订单不存在");
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
List<GaoOrderTransactionView> result = new ArrayList<>();
|
||||
List<com.imyeyu.api.modules.gao.entity.GaoFundRecord> fundRecords = fundAllowed ? funds.listByBizId(orderId) : List.of();
|
||||
var fundAttachments = fundRecords.isEmpty() ? java.util.Map.<String, List<Attachment>>of()
|
||||
: attachments.mapByBizIdList(Attachment.BizType.GAO_FUND_RECORD, fundRecords.stream().map(com.imyeyu.api.modules.gao.entity.GaoFundRecord::getId).toList());
|
||||
for (var fund : fundRecords) {
|
||||
fund.setAttachmentList(fundAttachments.getOrDefault(fund.getId(), List.of()));
|
||||
GaoOrderTransactionView item = new GaoOrderTransactionView();
|
||||
item.setType("FUND");
|
||||
item.setOccurredAt(fund.getOccurredAt());
|
||||
item.setFundRecord(fund);
|
||||
result.add(item);
|
||||
}
|
||||
if (recycleAllowed) for (var payment : list(orderId)) {
|
||||
GaoOrderTransactionView item = new GaoOrderTransactionView();
|
||||
item.setType("RECYCLE_PAYMENT");
|
||||
item.setOccurredAt(payment.getOccurredAt());
|
||||
item.setRecyclePayment(payment);
|
||||
result.add(item);
|
||||
}
|
||||
result.sort(Comparator.comparing(GaoOrderTransactionView::getOccurredAt, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 登记支付并预占额度
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment create(GaoRecyclePaymentRequest request) {
|
||||
return createInternal(request, null);
|
||||
}
|
||||
|
||||
private GaoRecyclePayment createInternal(GaoRecyclePaymentRequest request, String exchangeId) {
|
||||
TimiException.required(request, "支付请求不能为空");
|
||||
TimiException.required(request.getOrderId(), "订单不能为空");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.requiredTrue(request.getQuantity() != null && 0 < request.getQuantity().signum() && !(3 < request.getQuantity().stripTrailingZeros().scale()) && !(15 < request.getQuantity().precision() - request.getQuantity().scale()), "支付数量无效");
|
||||
GaoSalesOrder order = orders.getForUpdate(request.getOrderId());
|
||||
TimiException.required(order, "订单不存在");
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
String fingerprint = fingerprint("CREATE", request.getOrderId(), request.getQuantity().stripTrailingZeros().toPlainString(), request.getOccurredAt(), exchangeId, attachmentKeys(request.getAttachmentList()));
|
||||
GaoRecyclePayment existing = mapper.byRequest(order.getStoreId(), request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应支付内容不一致");
|
||||
return existing;
|
||||
}
|
||||
List<Attachment> sourceAttachments = exchangeId == null ? request.getAttachmentList() : attachments.listByBizId(Attachment.BizType.GAO_SALES_ORDER, order.getId());
|
||||
TimiException.requiredTrue(hasPhoto(sourceAttachments), "支付必须上传照片");
|
||||
TimiException.requiredTrue(order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && order.getStatus() != GaoSalesOrder.Status.CANCELLED && order.getRecycleItemId() != null && order.getRecycleRequiredQuantity() != null, "订单不支持回收物支付");
|
||||
TimiException.requiredTrue(0 <= order.getRecycleRequiredQuantity().compareTo(mapper.occupied(order.getId()).add(request.getQuantity())), "支付数量超过未结算数量");
|
||||
long now = Time.now();
|
||||
GaoRecyclePayment payment = new GaoRecyclePayment();
|
||||
payment.setId(UUID.randomUUID().toString());
|
||||
payment.setStoreId(order.getStoreId());
|
||||
payment.setCustomerId(order.getCustomerId());
|
||||
payment.setOrderId(order.getId());
|
||||
payment.setRecycleItemId(order.getRecycleItemId());
|
||||
payment.setRequestNo(request.getRequestNo());
|
||||
payment.setRequestFingerprint(fingerprint);
|
||||
payment.setQuantity(request.getQuantity());
|
||||
payment.setStatus(GaoRecyclePayment.Status.PENDING);
|
||||
payment.setOperatorUserId(login.getRequireLoginUserId());
|
||||
payment.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
payment.setCreatedAt(now);
|
||||
mapper.insert(payment);
|
||||
if (exchangeId == null) {
|
||||
attachments.updateByBizId(Attachment.BizType.GAO_RECYCLE_PAYMENT, payment.getId(), request.getAttachmentList());
|
||||
} else {
|
||||
for (Attachment source : sourceAttachments) {
|
||||
Attachment clone = attachments.clone(source.getId());
|
||||
clone.setBizType(Attachment.BizType.GAO_RECYCLE_PAYMENT);
|
||||
clone.setBizId(payment.getId());
|
||||
attachments.update(clone);
|
||||
}
|
||||
}
|
||||
accounts.change(order.getStoreId(), order.getCustomerId(), order.getRecycleItemId(), BigDecimal.ZERO, payment.getQuantity(), "PAYMENT_RESERVE", payment.getId(), "recycle:reserve:" + payment.getId(), null);
|
||||
return payment;
|
||||
}
|
||||
|
||||
/// 撤销或拒绝待核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment release(GaoRecyclePaymentRequest request, boolean reject) {
|
||||
return releaseInternal(request, reject, !reject);
|
||||
}
|
||||
|
||||
private GaoRecyclePayment releaseInternal(GaoRecyclePaymentRequest request, boolean reject, boolean onlyOperator) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "操作原因不能为空");
|
||||
GaoRecyclePayment snapshot = mapper.byId(request.getPaymentId());
|
||||
TimiException.required(snapshot, "支付记录不存在");
|
||||
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
GaoRecyclePayment payment = mapper.lock(snapshot.getId());
|
||||
TimiException.requiredTrue(payment.getStatus() == GaoRecyclePayment.Status.PENDING, "支付状态不允许撤销");
|
||||
if (onlyOperator) TimiException.requiredTrue(login.getRequireLoginUserId().equals(payment.getOperatorUserId()), "只能撤销自己提交的支付");
|
||||
accounts.change(payment.getStoreId(), payment.getCustomerId(), payment.getRecycleItemId(), BigDecimal.ZERO, payment.getQuantity().negate(), "PAYMENT_RELEASE", payment.getId(), "recycle:release:" + payment.getId(), request.getReason());
|
||||
GaoRecyclePayment.Status target = reject ? GaoRecyclePayment.Status.REJECTED : GaoRecyclePayment.Status.CANCELLED;
|
||||
TimiException.requiredTrue(mapper.status(payment.getId(), GaoRecyclePayment.Status.PENDING, target, login.getRequireLoginUserId(), Time.now(), request.getReason()) == 1, "支付状态已变更");
|
||||
return mapper.byId(payment.getId());
|
||||
}
|
||||
|
||||
/// 冲正已核销回收物支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment revoke(GaoRecyclePaymentRequest request) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "冲正原因不能为空");
|
||||
TimiException.required(request.getReturnedToCustomer(), "必须确认回收物是否退还");
|
||||
GaoRecyclePayment snapshot = mapper.byId(request.getPaymentId());
|
||||
TimiException.required(snapshot, "支付记录不存在");
|
||||
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
GaoRecyclePayment source = mapper.lock(snapshot.getId());
|
||||
String fingerprint = fingerprint("REVOKE", request.getPaymentId(), request.getOccurredAt(), request.getReason(), request.getReturnedToCustomer(), attachmentKeys(request.getAttachmentList()));
|
||||
GaoRecyclePayment existing = mapper.byRequest(order.getStoreId(), request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应冲正内容不一致");
|
||||
return existing;
|
||||
}
|
||||
TimiException.requiredTrue(source.getStatus() == GaoRecyclePayment.Status.VERIFIED && source.getSourcePaymentId() == null, "支付状态不允许冲正");
|
||||
TimiException.requiredTrue(hasPhoto(request.getAttachmentList()), "支付冲正必须上传照片");
|
||||
long now = Time.now();
|
||||
GaoRecyclePayment reverse = new GaoRecyclePayment();
|
||||
reverse.setId(UUID.randomUUID().toString());
|
||||
reverse.setStoreId(source.getStoreId());
|
||||
reverse.setCustomerId(source.getCustomerId());
|
||||
reverse.setOrderId(source.getOrderId());
|
||||
reverse.setRecycleItemId(source.getRecycleItemId());
|
||||
reverse.setRequestNo(request.getRequestNo());
|
||||
reverse.setRequestFingerprint(fingerprint);
|
||||
reverse.setQuantity(source.getQuantity());
|
||||
reverse.setStatus(GaoRecyclePayment.Status.VERIFIED);
|
||||
reverse.setSourcePaymentId(source.getId());
|
||||
reverse.setOperatorUserId(login.getRequireLoginUserId());
|
||||
reverse.setVerifierUserId(reverse.getOperatorUserId());
|
||||
reverse.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
reverse.setVerifiedAt(now);
|
||||
reverse.setReason(request.getReason());
|
||||
reverse.setReturnedToCustomer(request.getReturnedToCustomer());
|
||||
reverse.setCreatedAt(now);
|
||||
mapper.insert(reverse);
|
||||
accounts.change(source.getStoreId(), source.getCustomerId(), source.getRecycleItemId(), source.getQuantity(), BigDecimal.ZERO, "PAYMENT_REVOKE", reverse.getId(), "recycle:revoke:" + source.getId(), request.getReason());
|
||||
if (Boolean.TRUE.equals(request.getReturnedToCustomer())) {
|
||||
physical.returnPayment(order, source.getId(), reverse.getId(), reverse.getOccurredAt());
|
||||
}
|
||||
attachments.updateByBizId(Attachment.BizType.GAO_RECYCLE_PAYMENT, reverse.getId(), request.getAttachmentList());
|
||||
TimiException.requiredTrue(mapper.status(source.getId(), GaoRecyclePayment.Status.VERIFIED, GaoRecyclePayment.Status.REVOKED, login.getRequireLoginUserId(), now, request.getReason()) == 1, "支付状态已变更");
|
||||
refresh(order);
|
||||
reverse.setSignedQuantity(reverse.getQuantity().negate());
|
||||
return reverse;
|
||||
}
|
||||
|
||||
/// 随订单取消待核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void cancelPendingByOrderId(String orderId, String reason) {
|
||||
for (GaoRecyclePayment payment : mapper.list(orderId)) {
|
||||
if (payment.getStatus() != GaoRecyclePayment.Status.PENDING) continue;
|
||||
GaoRecyclePaymentRequest request = new GaoRecyclePaymentRequest();
|
||||
request.setPaymentId(payment.getId());
|
||||
request.setReason(reason);
|
||||
releaseInternal(request, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 创建并核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment createAndVerify(GaoRecyclePaymentRequest request) {
|
||||
GaoRecyclePayment payment = create(request);
|
||||
if (payment.getStatus() == GaoRecyclePayment.Status.VERIFIED) return payment;
|
||||
return verify(payment.getId());
|
||||
}
|
||||
|
||||
/// 使用兑换单凭证创建并核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment createAndVerifyFromExchange(GaoRecyclePaymentRequest request, String exchangeId) {
|
||||
GaoRecyclePayment payment = createInternal(request, exchangeId);
|
||||
if (payment.getStatus() == GaoRecyclePayment.Status.VERIFIED) return payment;
|
||||
return verify(payment.getId());
|
||||
}
|
||||
|
||||
/// 核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment verify(String paymentId) {
|
||||
GaoRecyclePayment snapshot = mapper.byId(paymentId);
|
||||
TimiException.required(snapshot, "支付记录不存在");
|
||||
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
GaoRecyclePayment payment = mapper.lock(paymentId);
|
||||
TimiException.requiredTrue(order.getStatus() != GaoSalesOrder.Status.CANCELLED && payment.getStatus() == GaoRecyclePayment.Status.PENDING, "支付状态不允许核销");
|
||||
accounts.change(payment.getStoreId(), payment.getCustomerId(), payment.getRecycleItemId(), payment.getQuantity().negate(), payment.getQuantity().negate(), "PAYMENT_VERIFY", payment.getId(), "recycle:verify:" + payment.getId(), null);
|
||||
physical.record(order, "PAYMENT_VERIFY", payment.getId(), payment.getId(), true, payment.getQuantity(), payment.getOccurredAt());
|
||||
TimiException.requiredTrue(mapper.status(paymentId, GaoRecyclePayment.Status.PENDING, GaoRecyclePayment.Status.VERIFIED, login.getRequireLoginUserId(), Time.now(), null) == 1, "支付状态已变更");
|
||||
refresh(order);
|
||||
return mapper.byId(paymentId);
|
||||
}
|
||||
|
||||
private void refresh(GaoSalesOrder order) {
|
||||
BigDecimal paid = mapper.paid(order.getId());
|
||||
order.setPaymentStatus(0 <= paid.compareTo(order.getRecycleRequiredQuantity()) ? GaoSalesOrder.PaymentStatus.PAID
|
||||
: (0 < paid.signum() ? GaoSalesOrder.PaymentStatus.PARTIALLY_PAID : GaoSalesOrder.PaymentStatus.UNPAID));
|
||||
orders.updatePayment(order);
|
||||
}
|
||||
|
||||
private List<String> attachmentKeys(List<Attachment> list) {
|
||||
if (list == null) return List.of();
|
||||
return list.stream().filter(Objects::nonNull)
|
||||
.map(a -> String.valueOf(a.getId()) + ":" + a.getTempFileId() + ":" + a.getAttachType()).sorted().toList();
|
||||
}
|
||||
|
||||
private boolean hasPhoto(List<Attachment> list) {
|
||||
return list != null && list.stream().anyMatch(item -> item != null && (item.getAttachType() == null || "PHOTO".equalsIgnoreCase(item.getAttachType())));
|
||||
}
|
||||
|
||||
private void fillAttachments(List<GaoRecyclePayment> payments) {
|
||||
if (payments.isEmpty()) return;
|
||||
var map = attachments.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_PAYMENT, payments.stream().map(GaoRecyclePayment::getId).toList());
|
||||
for (GaoRecyclePayment payment : payments) {
|
||||
payment.setAttachmentList(map.getOrDefault(payment.getId(), List.of()));
|
||||
payment.setSignedQuantity(payment.getSourcePaymentId() == null ? payment.getQuantity() : payment.getQuantity().negate());
|
||||
}
|
||||
}
|
||||
|
||||
private String fingerprint(Object... values) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(jackson.writeValueAsString(values).getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("计算支付请求摘要失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecyclePhysicalMapper;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
/// 回收实物流转服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecyclePhysicalService {
|
||||
private final GaoRecyclePhysicalMapper mapper;
|
||||
private final ObjectProvider<GaoSalesOrderService> orders;
|
||||
|
||||
/// 记录门店收到或退回的回收物
|
||||
///
|
||||
/// @param order 兑换订单
|
||||
/// @param sourceType 来源类型
|
||||
/// @param sourceId 来源记录 ID
|
||||
/// @param incoming true 为收到,false 为退回
|
||||
/// @param quantity 实物数量
|
||||
/// @param occurredAt 业务发生时间
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void record(GaoSalesOrder order, String sourceType, String sourceId, String paymentId, boolean incoming, BigDecimal quantity, Long occurredAt) {
|
||||
TimiException.required(order, "订单不能为空");
|
||||
TimiException.requiredTrue(quantity != null && 0 < quantity.signum(), "实物数量必须大于零");
|
||||
orders.getObject().getForUpdate(order.getId());
|
||||
if (!incoming) TimiException.requiredTrue(0 <= mapper.paymentBalance(order.getId(), paymentId).compareTo(quantity), "退回数量超过该笔支付实际保留数量");
|
||||
long now = Time.now();
|
||||
mapper.insert(UUID.randomUUID().toString(), order.getStoreId(), order.getCustomerId(), order.getId(), order.getRecycleItemId(), paymentId, sourceType, sourceId, incoming ? "IN" : "OUT", quantity, occurredAt == null ? now : occurredAt, now);
|
||||
}
|
||||
|
||||
/// 查询某笔支付尚未退回的实物数量
|
||||
public BigDecimal paymentBalance(String orderId, String paymentId) {
|
||||
return mapper.paymentBalance(orderId, paymentId);
|
||||
}
|
||||
|
||||
/// 冲正时将该笔支付尚未退回的实物全部退还
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void returnPayment(GaoSalesOrder order, String paymentId, String sourceId, Long occurredAt) {
|
||||
orders.getObject().getForUpdate(order.getId());
|
||||
BigDecimal remaining = mapper.paymentBalance(order.getId(), paymentId);
|
||||
if (0 < remaining.signum()) record(order, "PAYMENT_REVOKE", sourceId, paymentId, false, remaining, occurredAt);
|
||||
}
|
||||
|
||||
/// 查询订单当前实物保留数量,调用方须先锁定订单
|
||||
public BigDecimal balance(String orderId) {
|
||||
return mapper.balance(orderId);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,9 @@ public interface GaoSalesOrderService extends BaseService<GaoSalesOrder, String>
|
||||
/// 由套餐购买流程创建套餐订单
|
||||
GaoSalesOrder createPackageOrder(GaoPackageOrderCreateData data);
|
||||
|
||||
/// 创建回收兑换订单
|
||||
GaoSalesOrder createRecycleOrder(GaoPackageOrderCreateData data, String recycleItemId, java.math.BigDecimal requiredQuantity);
|
||||
|
||||
/// 锁定订单
|
||||
GaoSalesOrder getForUpdate(String id);
|
||||
|
||||
|
||||
+16
-4
@@ -20,6 +20,7 @@ import com.imyeyu.api.modules.gao.mapper.GaoOrderFulfillmentMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoCustomerMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderMapper;
|
||||
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleAccountService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoProductService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoProductStockService;
|
||||
@@ -88,6 +89,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
private static final BigDecimal ZERO = BigDecimal.ZERO;
|
||||
|
||||
private final GaoOrderFulfillmentMapper mapper;
|
||||
private final GaoRecycleAccountService recycleAccountService;
|
||||
private final GaoOrderFulfillmentItemMapper itemMapper;
|
||||
private final GaoCustomerMapper customerMapper;
|
||||
private final GaoSalesOrderMapper salesOrderMapper;
|
||||
@@ -305,6 +307,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
Map<String, GaoSalesOrder> orderMap = new LinkedHashMap<>();
|
||||
for (String orderId : lockOrderIdList) {
|
||||
GaoSalesOrder order = salesOrderService.getForUpdate(orderId);
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单请使用普通履约入口");
|
||||
TimiException.requiredTrue(customerId.equals(order.getCustomerId()), "来源订单不属于当前客户");
|
||||
TimiException.requiredTrue(customer.getStoreId().equals(order.getStoreId()), "来源订单不属于当前门店");
|
||||
TimiException.requiredTrue(order.getStatus() != GaoSalesOrder.Status.CANCELLED, "已取消订单不能履约");
|
||||
@@ -536,6 +539,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
}
|
||||
TimiException.requiredTrue(1 == mapper.updateStatus(fulfillment.getId(), GaoOrderFulfillment.Status.VERIFIED,
|
||||
verifierUserId, Time.now(), request.getReason()), "履约状态已变化");
|
||||
recycleAccountService.addFromFulfillment(order.getStoreId(), order.getCustomerId(), fulfillment.getId(), fulfillmentItemList);
|
||||
salesOrderService.refreshFulfillmentStatus(order);
|
||||
return detail(fulfillment.getId());
|
||||
}
|
||||
@@ -667,6 +671,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
TimiException.requiredTrue(1 == mapper.updateStatus(source.getId(), GaoOrderFulfillment.Status.REVOKED,
|
||||
operatorUserId, Time.now(), reason), "原履约状态已变化");
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_ORDER_FULFILLMENT, reverse.getId(), request.getAttachmentList());
|
||||
recycleAccountService.revokeFulfillment(order.getStoreId(), order.getCustomerId(), source.getId(), reverse.getId());
|
||||
salesOrderService.refreshFulfillmentStatus(order);
|
||||
return detail(reverse.getId());
|
||||
}
|
||||
@@ -740,6 +745,7 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
stockRequestNo(returned, "RETURN"), operatorUserId);
|
||||
}
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_ORDER_FULFILLMENT, returned.getId(), request.getAttachmentList());
|
||||
recycleAccountService.revokeFulfillment(order.getStoreId(), order.getCustomerId(), source.getId(), returned.getId());
|
||||
salesOrderService.refreshFulfillmentStatus(order);
|
||||
return detail(returned.getId());
|
||||
}
|
||||
@@ -818,8 +824,11 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
GaoSalesOrderItem source = salesOrderService.getItemForUpdate(requestItem.getSourceOrderItemId());
|
||||
TimiException.required(source, "not found sales order item");
|
||||
TimiException.requiredTrue(order.getId().equals(source.getSalesOrderId()), "订单明细不属于当前订单");
|
||||
GaoSalesOrderItem.ItemType expectedItemType = order.getOrderType() == GaoSalesOrder.OrderType.PACKAGE
|
||||
? GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT : GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
|
||||
GaoSalesOrderItem.ItemType expectedItemType = switch (order.getOrderType()) {
|
||||
case PACKAGE -> GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT;
|
||||
case RECYCLE -> GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT;
|
||||
case DIRECT_PRODUCT -> GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
|
||||
};
|
||||
TimiException.requiredTrue(source.getItemType() == expectedItemType, "订单项类型与订单类型不匹配");
|
||||
if (requestItem.getSkuUnitId().equals(source.getSkuUnitId())) {
|
||||
result.add(toSourceByOrderSnapshot(order, source, requestItem.getQuantity(), checkAvailable));
|
||||
@@ -905,8 +914,11 @@ public class GaoOrderFulfillmentServiceImplement extends AbstractEntityService<G
|
||||
private void validateSourceOrderItem(GaoSalesOrder order, GaoSalesOrderItem source) {
|
||||
TimiException.required(source, "not found sales order item");
|
||||
TimiException.requiredTrue(order.getId().equals(source.getSalesOrderId()), "订单明细不属于当前订单");
|
||||
GaoSalesOrderItem.ItemType expectedItemType = order.getOrderType() == GaoSalesOrder.OrderType.PACKAGE
|
||||
? GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT : GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
|
||||
GaoSalesOrderItem.ItemType expectedItemType = switch (order.getOrderType()) {
|
||||
case PACKAGE -> GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT;
|
||||
case RECYCLE -> GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT;
|
||||
case DIRECT_PRODUCT -> GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
|
||||
};
|
||||
TimiException.requiredTrue(source.getItemType() == expectedItemType, "订单项类型与订单类型不匹配");
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -65,6 +65,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
|
||||
TimiException.required(request.getAmount(), "收款金额不能为空");
|
||||
TimiException.requiredTrue(0 < request.getAmount(), "收款金额必须大于 0");
|
||||
GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId());
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
|
||||
String requestNo = requiredText(request.getRequestNo(), "not found requestNo");
|
||||
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
|
||||
if (existing != null) {
|
||||
@@ -112,6 +113,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
|
||||
GaoFundRecord snapshot = fundRecordService.detail(fundRecordId);
|
||||
TimiException.requiredTrue(snapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金");
|
||||
GaoSalesOrder order = orderService.getForUpdate(snapshot.getBizId());
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
|
||||
GaoFundRecord record = lockOrderRecord(fundRecordId);
|
||||
TimiException.requiredTrue(order.getId().equals(record.getBizId()), "资金流水所属订单已变化");
|
||||
TimiException.requiredTrue(record.getOperationType() == GaoFundRecord.OperationType.RECEIVE && record.getStatus() == GaoFundRecord.Status.PENDING, "收款记录不是待核销状态");
|
||||
@@ -172,6 +174,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
|
||||
GaoFundRecord snapshot = fundRecordService.detail(request.getFundRecordId());
|
||||
TimiException.requiredTrue(snapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金");
|
||||
GaoSalesOrder order = orderService.getForUpdate(snapshot.getBizId());
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
|
||||
GaoFundRecord record = lockOrderRecord(request.getFundRecordId());
|
||||
TimiException.requiredTrue(order.getId().equals(record.getBizId()), "资金流水所属订单已变化");
|
||||
TimiException.requiredTrue(record.getOperationType() == GaoFundRecord.OperationType.RECEIVE && record.getStatus() == GaoFundRecord.Status.PENDING, "收款记录不是待核销状态");
|
||||
@@ -204,6 +207,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
|
||||
TimiException.requiredTrue(0 < request.getAmount(), "退款金额必须大于 0");
|
||||
String reason = requiredText(request.getReason(), "退款原因不能为空");
|
||||
GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId());
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
|
||||
String requestNo = requiredText(request.getRequestNo(), "not found requestNo");
|
||||
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
|
||||
if (existing != null) {
|
||||
@@ -234,6 +238,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
|
||||
public GaoFundRecord confirmNoRefund(GaoOrderPaymentNoRefundRequest request) {
|
||||
TimiException.required(request, "not found no refund request");
|
||||
GaoSalesOrder order = orderService.getForUpdate(request.getSalesOrderId());
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
|
||||
String requestNo = requiredText(request.getRequestNo(), "not found requestNo");
|
||||
String reason = requiredText(request.getReason(), "确认无需退款原因不能为空");
|
||||
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
|
||||
@@ -267,6 +272,7 @@ public class GaoOrderPaymentServiceImplement implements GaoOrderPaymentService {
|
||||
TimiException.requiredTrue(sourceSnapshot.getBizType() == GaoFundRecord.BizType.SALES_ORDER, "资金记录不是销售订单资金");
|
||||
TimiException.required(sourceSnapshot.getBizId(), "not found salesOrderId");
|
||||
GaoSalesOrder order = orderService.getForUpdate(sourceSnapshot.getBizId());
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不支持资金操作");
|
||||
GaoFundRecord source = lockOrderRecord(request.getFundRecordId());
|
||||
TimiException.requiredTrue(order.getId().equals(source.getBizId()), "资金流水所属订单已变化");
|
||||
GaoFundRecord existing = fundRecordService.getByRequestNo(order.getStoreId(), requestNo);
|
||||
|
||||
+21
-10
@@ -7,6 +7,7 @@ import com.imyeyu.api.modules.common.service.NotifyService;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoUser;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoOrderReminderMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleReminderMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoUserMapper;
|
||||
import com.imyeyu.api.modules.gao.service.GaoOrderReminderService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderReminderCustomer;
|
||||
@@ -50,6 +51,7 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
|
||||
private static final int MAX_SMS_CUSTOMER_COUNT = 99;
|
||||
|
||||
private final GaoOrderReminderMapper mapper;
|
||||
private final GaoRecycleReminderMapper recycleReminderMapper;
|
||||
private final GaoUserMapper gaoUserMapper;
|
||||
private final UserService userService;
|
||||
private final NotifyService notifyService;
|
||||
@@ -68,7 +70,11 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
|
||||
Map<String, Map<String, ReminderEntry>> storeEntryMap = new LinkedHashMap<>();
|
||||
mergeCustomers(storeEntryMap, mapper.selectReceiveVerifyCustomers(), "核销收款");
|
||||
mergeCustomers(storeEntryMap, mapper.selectFulfillmentVerifyCustomers(), "核销履约");
|
||||
sendStoreReminders(storeEntryMap, ReminderType.VERIFY.name());
|
||||
Set<String> recycleStoreIds = new LinkedHashSet<>(recycleReminderMapper.selectPendingStoreIds());
|
||||
for (String storeId : recycleStoreIds) {
|
||||
storeEntryMap.computeIfAbsent(storeId, key -> new LinkedHashMap<>());
|
||||
}
|
||||
sendStoreReminders(storeEntryMap, ReminderType.VERIFY.name(), recycleStoreIds);
|
||||
}
|
||||
|
||||
/// 按提醒类型发送订单提醒
|
||||
@@ -81,7 +87,7 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
|
||||
}
|
||||
Map<String, Map<String, ReminderEntry>> storeEntryMap = new LinkedHashMap<>();
|
||||
mergeCustomers(storeEntryMap, customerList, reminderType.label);
|
||||
sendStoreReminders(storeEntryMap, reminderType.name());
|
||||
sendStoreReminders(storeEntryMap, reminderType.name(), Set.of());
|
||||
}
|
||||
|
||||
/// 合并同一门店下同一订单的多个提醒事项
|
||||
@@ -115,9 +121,9 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
|
||||
///
|
||||
/// @param storeEntryMap 门店提醒映射
|
||||
/// @param reminderType 提醒类型
|
||||
private void sendStoreReminders(Map<String, Map<String, ReminderEntry>> storeEntryMap, String reminderType) {
|
||||
private void sendStoreReminders(Map<String, Map<String, ReminderEntry>> storeEntryMap, String reminderType, Set<String> recycleStoreIds) {
|
||||
for (Map.Entry<String, Map<String, ReminderEntry>> entry : storeEntryMap.entrySet()) {
|
||||
sendStoreReminder(entry.getKey(), new ArrayList<>(entry.getValue().values()), reminderType);
|
||||
sendStoreReminder(entry.getKey(), new ArrayList<>(entry.getValue().values()), reminderType, recycleStoreIds.contains(entry.getKey()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,14 +132,17 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
|
||||
/// @param storeId 门店 ID
|
||||
/// @param entryList 订单提醒列表
|
||||
/// @param reminderType 提醒类型
|
||||
private void sendStoreReminder(String storeId, List<ReminderEntry> entryList, String reminderType) {
|
||||
private void sendStoreReminder(String storeId, List<ReminderEntry> entryList, String reminderType, boolean recyclePending) {
|
||||
String customerNames = formatCustomerNames(entryList);
|
||||
String action = entryList.stream()
|
||||
.flatMap(entry -> entry.actionSet().stream())
|
||||
.distinct()
|
||||
.collect(Collectors.joining("、"));
|
||||
String smsContent = "您的客户 %s 的订单需要 %s,请留意订单状态。".formatted(customerNames, action);
|
||||
String internalContent = buildInternalContent(entryList);
|
||||
String internalContent = entryList.isEmpty() ? "" : buildInternalContent(entryList);
|
||||
if (recyclePending) {
|
||||
internalContent += "<p>门店有待核销的回收物支付,请在订单中处理</p>";
|
||||
}
|
||||
|
||||
List<GaoUser> managerList = gaoUserMapper.selectEnabledStoreManagers(storeId);
|
||||
if (managerList == null || managerList.isEmpty()) {
|
||||
@@ -156,10 +165,12 @@ public class GaoOrderReminderServiceImplement implements GaoOrderReminderService
|
||||
notify.setBizType(NOTIFY_BIZ_TYPE);
|
||||
notify.setBizRemindedType(reminderType);
|
||||
notify.setBizRemindedKey(remindedKey);
|
||||
notify.setDetailList(List.of(
|
||||
createInternalDetail(manager.getUserId(), internalContent, sendAt),
|
||||
createSmsDetail(user.getPhoneNo(), customerNames, action, smsContent, sendAt)
|
||||
));
|
||||
List<NotifyDetail> detailList = new ArrayList<>();
|
||||
detailList.add(createInternalDetail(manager.getUserId(), internalContent, sendAt));
|
||||
if (!entryList.isEmpty()) {
|
||||
detailList.add(createSmsDetail(user.getPhoneNo(), customerNames, action, smsContent, sendAt));
|
||||
}
|
||||
notify.setDetailList(detailList);
|
||||
notifyService.createIfAbsent(notify);
|
||||
} catch (Exception e) {
|
||||
log.error("GAO 订单提醒发送失败: storeId[{}], userId[{}], reminderType[{}]", storeId,
|
||||
|
||||
+6
-34
@@ -309,34 +309,6 @@ public class GaoProductStockServiceImplement implements GaoProductStockService {
|
||||
return executeInternal(storeId, bizId, items, requestNo, operatorUserId, GaoProductStockRecord.OperationType.ORDER_RETURN_IN, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public List<GaoProductStock> reserveForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId) {
|
||||
return executeInternal(storeId, bizId, items, requestNo, operatorUserId,
|
||||
GaoProductStockRecord.OperationType.RECYCLE_RESERVE, null, null, null, GaoProductStockRecord.BizType.RECYCLE_EXCHANGE);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public List<GaoProductStock> releaseForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId) {
|
||||
return executeInternal(storeId, bizId, items, requestNo, operatorUserId,
|
||||
GaoProductStockRecord.OperationType.RECYCLE_RELEASE, null, null, null, GaoProductStockRecord.BizType.RECYCLE_EXCHANGE);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public List<GaoProductStock> outForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId) {
|
||||
return executeInternal(storeId, bizId, items, requestNo, operatorUserId,
|
||||
GaoProductStockRecord.OperationType.RECYCLE_OUT, null, null, null, GaoProductStockRecord.BizType.RECYCLE_EXCHANGE);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public List<GaoProductStock> revokeForRecycleExchange(String storeId, String bizId, List<GaoStockChangeItem> items, String requestNo, String operatorUserId) {
|
||||
return executeInternal(storeId, bizId, items, requestNo, operatorUserId,
|
||||
GaoProductStockRecord.OperationType.RECYCLE_REVOKE, null, null, null, GaoProductStockRecord.BizType.RECYCLE_EXCHANGE);
|
||||
}
|
||||
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
@Override
|
||||
public GaoProductStockRecord outForRedemption(String storeId, String redemptionId, GaoStockChangeItem item, String requestNo, String operatorUserId) {
|
||||
@@ -609,17 +581,17 @@ public class GaoProductStockServiceImplement implements GaoProductStockService {
|
||||
|
||||
private BigDecimal onHandDelta(GaoProductStockRecord.OperationType operationType, BigDecimal quantity) {
|
||||
return switch (operationType) {
|
||||
case INITIAL_IN, MANUAL_IN, STOCKTAKE_GAIN, ORDER_REVOKE, ORDER_RETURN_IN, POINT_REDEMPTION_RETURN_IN, RECYCLE_REVOKE -> quantity;
|
||||
case MANUAL_OUT, STOCKTAKE_LOSS, ORDER_OUT, POINT_REDEMPTION_OUT, RECYCLE_OUT -> quantity.negate();
|
||||
case ORDER_RESERVE, ORDER_RELEASE, RECYCLE_RESERVE, RECYCLE_RELEASE -> ZERO;
|
||||
case INITIAL_IN, MANUAL_IN, STOCKTAKE_GAIN, ORDER_REVOKE, ORDER_RETURN_IN, POINT_REDEMPTION_RETURN_IN -> quantity;
|
||||
case MANUAL_OUT, STOCKTAKE_LOSS, ORDER_OUT, POINT_REDEMPTION_OUT -> quantity.negate();
|
||||
case ORDER_RESERVE, ORDER_RELEASE -> ZERO;
|
||||
case MANUAL_REVOKE -> throw new TimiException(TimiCode.ERROR, "手工库存冲正必须基于原库存流水");
|
||||
};
|
||||
}
|
||||
|
||||
private BigDecimal reservedDelta(GaoProductStockRecord.OperationType operationType, BigDecimal quantity) {
|
||||
return switch (operationType) {
|
||||
case ORDER_RESERVE, RECYCLE_RESERVE -> quantity;
|
||||
case ORDER_RELEASE, ORDER_OUT, RECYCLE_RELEASE, RECYCLE_OUT -> quantity.negate();
|
||||
case ORDER_RESERVE -> quantity;
|
||||
case ORDER_RELEASE, ORDER_OUT -> quantity.negate();
|
||||
default -> ZERO;
|
||||
};
|
||||
}
|
||||
@@ -663,7 +635,7 @@ public class GaoProductStockServiceImplement implements GaoProductStockService {
|
||||
GaoProductStockRecord record = recordMap.get(item.getSkuId());
|
||||
TimiException.required(record, "requestNo 对应库存操作内容不一致");
|
||||
TimiException.requiredTrue(item.getBaseQuantity().compareTo(record.getBaseQuantity()) == 0, "requestNo 对应库存操作内容不一致");
|
||||
if (operationType == GaoProductStockRecord.OperationType.RECYCLE_REVOKE) {
|
||||
if (operationType == GaoProductStockRecord.OperationType.ORDER_REVOKE) {
|
||||
TimiException.requiredTrue(Objects.equals(item.getSourceRecordId(), record.getSourceRecordId()), "requestNo 对应冲正来源不一致");
|
||||
}
|
||||
}
|
||||
|
||||
+86
-21
@@ -5,18 +5,18 @@ import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProduct;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoStore;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeWriteMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderItemMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoSalesOrderMapper;
|
||||
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
|
||||
@@ -26,22 +26,21 @@ import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoOrderStraightThroughService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoPointTriggerService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoProductService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoProductSkuService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoStoreService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductCustomerRow;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductCustomerView;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductPage;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductSummaryView;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoCustomerProductView;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoDirectProductOrderCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentReturnRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderPaymentRefundRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderPaymentRevokeRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoProductSkuUnitSelection;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderCancelRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderItemRequest;
|
||||
@@ -51,7 +50,6 @@ import com.imyeyu.api.modules.gao.vo.GaoSalesOrderUpdateRequest;
|
||||
import com.imyeyu.api.modules.system.audit.AuditOperation;
|
||||
import com.imyeyu.api.modules.system.audit.OperationAudit;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.modules.user.service.RoleChecker;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
@@ -59,9 +57,9 @@ import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.spring.bean.PageResult;
|
||||
import com.imyeyu.spring.mapper.BaseMapper;
|
||||
import com.imyeyu.spring.service.AbstractEntityService;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -88,18 +86,16 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
|
||||
private static final BigDecimal ZERO = BigDecimal.ZERO;
|
||||
|
||||
// 过渡兼容:旧事件登记系统已收款,但新订单可能仍为零有效收款,暂时允许店长发起履约;过渡结束改为 false 并删除此分支
|
||||
private static final boolean ALLOW_STORE_MANAGER_ZERO_PAYMENT_FULFILLMENT = true;
|
||||
|
||||
private final GaoSalesOrderMapper mapper;
|
||||
private final GaoRecycleExchangeWriteMapper recycleExchangeMapper;
|
||||
private final GaoSalesOrderItemMapper itemMapper;
|
||||
private final GaoProductSkuUnitMapper skuUnitMapper;
|
||||
private final GaoFundRecordService fundRecordService;
|
||||
private final ObjectProvider<GaoOrderFulfillmentService> fulfillmentServiceProvider;
|
||||
private final ObjectProvider<GaoOrderPaymentService> paymentServiceProvider;
|
||||
private final ObjectProvider<com.imyeyu.api.modules.gao.service.GaoRecyclePaymentService> recyclePaymentServiceProvider;
|
||||
private final ObjectProvider<GaoOrderStraightThroughService> straightThroughServiceProvider;
|
||||
private final GaoCustomerService customerService;
|
||||
private final GaoProductService productService;
|
||||
private final GaoProductSkuService skuService;
|
||||
private final GaoStoreService storeService;
|
||||
private final GaoStoreScopeService storeScopeService;
|
||||
@@ -107,7 +103,6 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
private final GaoPointTriggerService pointTriggerService;
|
||||
private final AttachmentService attachmentService;
|
||||
private final PermissionChecker permissionChecker;
|
||||
private final RoleChecker roleChecker;
|
||||
private final UserLoginService userLoginService;
|
||||
|
||||
@Override
|
||||
@@ -221,6 +216,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
order.setSourceEventRecord(eventRecordService.get(order.getSourceEventRecordId()));
|
||||
}
|
||||
order.setUnpaidAmount(safe(order.getSaleAmount()) - safe(order.getPaidAmount()));
|
||||
fillRecycleItem(order);
|
||||
return order;
|
||||
}
|
||||
|
||||
@@ -317,6 +313,33 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
data.getSaleAmount(), data.getItemList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoSalesOrder createRecycleOrder(GaoPackageOrderCreateData data, String recycleItemId, BigDecimal requiredQuantity) {
|
||||
TimiException.required(data, "订单数据不能为空");
|
||||
String requestNo = requiredText(data.getRequestNo(), "请求号不能为空");
|
||||
String storeId = requiredText(data.getStoreId(), "门店不能为空");
|
||||
TimiException.required(recycleItemId, "回收物不能为空");
|
||||
TimiException.requiredTrue(requiredQuantity != null && 0 < requiredQuantity.signum(), "回收物数量必须大于零");
|
||||
storeScopeService.checkStoreId(storeId);
|
||||
GaoSalesOrder existing = mapper.selectByRequestNo(storeId, requestNo);
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(existing.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && data.getCustomerId().equals(existing.getCustomerId()) && recycleItemId.equals(existing.getRecycleItemId()) && requiredQuantity.compareTo(existing.getRecycleRequiredQuantity()) == 0, "请求号对应订单内容不一致");
|
||||
List<GaoSalesOrderItem> saved = itemMapper.selectBySalesOrderId(existing.getId());
|
||||
TimiException.requiredTrue(data.getItemList() != null && saved.size() == data.getItemList().size(), "请求号对应订单明细不一致");
|
||||
for (GaoSalesOrderItem requested : data.getItemList()) {
|
||||
TimiException.requiredTrue(saved.stream().anyMatch(item -> item.getItemType() == GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT && java.util.Objects.equals(item.getSkuId(), requested.getSkuId()) && java.util.Objects.equals(item.getSkuUnitId(), requested.getSkuUnitId()) && item.getQuantity().compareTo(requested.getQuantity()) == 0), "请求号对应订单明细不一致");
|
||||
}
|
||||
return detail(existing.getId());
|
||||
}
|
||||
GaoCustomer customer = customerService.get(data.getCustomerId());
|
||||
TimiException.required(customer, "客户不存在");
|
||||
TimiException.requiredTrue(storeId.equals(customer.getStoreId()), "客户不属于当前门店");
|
||||
return createOrder(storeId, customer.getId(), GaoSalesOrder.OrderType.RECYCLE, requestNo,
|
||||
TimiJava.defaultIfNull(data.getPurchasedAt(), Time.now()), data.getOperatorUserId(), data.getRemark(),
|
||||
0, data.getItemList(), recycleItemId, requiredQuantity);
|
||||
}
|
||||
|
||||
@OperationAudit(AuditOperation.GAO_SALES_ORDER_CANCEL)
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
@Override
|
||||
@@ -448,10 +471,15 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
String childCancelReason = "随订单取消:%s".formatted(reason);
|
||||
fulfillmentService.cancelPendingBySalesOrderId(order.getId(), childCancelReason);
|
||||
paymentService.cancelPendingBySalesOrderId(order.getId(), childCancelReason);
|
||||
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE) {
|
||||
recyclePaymentServiceProvider.getObject().cancelPendingByOrderId(order.getId(), childCancelReason);
|
||||
}
|
||||
|
||||
order = getForUpdate(order.getId());
|
||||
String userId = userLoginService.getRequireLoginUserId();
|
||||
GaoSalesOrder.RefundStatus refundStatus = safe(order.getPaidAmount()) == 0 ? GaoSalesOrder.RefundStatus.REFUNDED : GaoSalesOrder.RefundStatus.PENDING;
|
||||
GaoSalesOrder.RefundStatus refundStatus = order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE
|
||||
? GaoSalesOrder.RefundStatus.NOT_REQUIRED
|
||||
: safe(order.getPaidAmount()) == 0 ? GaoSalesOrder.RefundStatus.REFUNDED : GaoSalesOrder.RefundStatus.PENDING;
|
||||
Long cancelledAt = Time.now();
|
||||
TimiException.requiredTrue(1 == mapper.cancelIf(order.getId(), order.getStatus(), GaoSalesOrder.Status.CANCELLED,
|
||||
cancelledAt, userId, reason, refundStatus), "订单状态已变化");
|
||||
@@ -467,7 +495,9 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
}
|
||||
order = getForUpdate(order.getId());
|
||||
// 订单取消立即失去有效消费资格,不等待退款完成
|
||||
pointTriggerService.revokeBySalesOrder(order, reason);
|
||||
if (order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE) {
|
||||
pointTriggerService.revokeBySalesOrder(order, reason);
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
@@ -514,6 +544,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
|
||||
@Override
|
||||
public void recomputePaymentStatus(GaoSalesOrder order) {
|
||||
TimiException.requiredTrue(order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE, "回收兑换订单不能按资金金额计算支付状态");
|
||||
long saleAmount = safeLong(order.getSaleAmount());
|
||||
long paidAmount = safeLong(order.getPaidAmount());
|
||||
long pendingAmount = safeLong(order.getPendingPaidAmount());
|
||||
@@ -529,11 +560,16 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
@Override
|
||||
public void checkFulfillmentPermission(GaoSalesOrder order) {
|
||||
TimiException.required(order, "not found sales order");
|
||||
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE) {
|
||||
if (recyclePaymentServiceProvider.getObject().isSettled(order) || permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_UNSETTLED.getValue())) {
|
||||
return;
|
||||
}
|
||||
TimiException.requiredTrue(false, "回收物尚未结清,不能发起履约");
|
||||
}
|
||||
if (safe(order.getSaleAmount()) == 0 || safe(order.getPaidAmount()) == safe(order.getSaleAmount())) {
|
||||
return;
|
||||
}
|
||||
if (ALLOW_STORE_MANAGER_ZERO_PAYMENT_FULFILLMENT) {
|
||||
roleChecker.checkAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name());
|
||||
if (permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_UNSETTLED.getValue())) {
|
||||
return;
|
||||
}
|
||||
TimiException.requiredTrue(false, "订单未全额收款,不能发起履约");
|
||||
@@ -583,6 +619,24 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
mapper.updateStatus(order.getId(), status);
|
||||
order.setStatus(status);
|
||||
}
|
||||
if (order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE) {
|
||||
recycleExchangeMapper.updateByOrderStatus(order.getId(), fulfilled ? "COMPLETED" : "PENDING", Time.now());
|
||||
}
|
||||
}
|
||||
|
||||
/// 填充回收物名称与单位,回收订单要在订单页展示应付回收物
|
||||
///
|
||||
/// @param order 销售订单
|
||||
private void fillRecycleItem(GaoSalesOrder order) {
|
||||
if (order.getOrderType() != GaoSalesOrder.OrderType.RECYCLE || order.getRecycleItemId() == null) {
|
||||
return;
|
||||
}
|
||||
GaoRecycleExchange exchange = recycleExchangeMapper.snapshotByOrderId(order.getId());
|
||||
if (exchange != null) {
|
||||
order.setRecycleExchangeId(exchange.getId());
|
||||
order.setRecycleItemName(exchange.getRecycleNameSnapshot());
|
||||
order.setRecycleUnit(exchange.getRecycleUnitSnapshot());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -692,10 +746,19 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
|
||||
private GaoSalesOrder createOrder(String storeId, String customerId, GaoSalesOrder.OrderType orderType, String requestNo,
|
||||
Long purchasedAt, String operatorUserId, String remark, long saleAmount, List<GaoSalesOrderItem> itemList) {
|
||||
return createOrder(storeId, customerId, orderType, requestNo, purchasedAt, operatorUserId, remark, saleAmount, itemList, null, null);
|
||||
}
|
||||
|
||||
private GaoSalesOrder createOrder(String storeId, String customerId, GaoSalesOrder.OrderType orderType, String requestNo,
|
||||
Long purchasedAt, String operatorUserId, String remark, long saleAmount, List<GaoSalesOrderItem> itemList,
|
||||
String recycleItemId, BigDecimal recycleRequiredQuantity) {
|
||||
TimiException.requiredTrue(itemList != null && !itemList.isEmpty(), "销售订单至少需要一个订单明细");
|
||||
TimiException.requiredTrue(0 <= saleAmount, "成交价不能为负数");
|
||||
GaoSalesOrderItem.ItemType expectedItemType = orderType == GaoSalesOrder.OrderType.PACKAGE
|
||||
? GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT : GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
|
||||
GaoSalesOrderItem.ItemType expectedItemType = switch (orderType) {
|
||||
case PACKAGE -> GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT;
|
||||
case DIRECT_PRODUCT -> GaoSalesOrderItem.ItemType.DIRECT_PRODUCT;
|
||||
case RECYCLE -> GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT;
|
||||
};
|
||||
Set<String> skuUnitKeySet = new HashSet<>();
|
||||
long lineAmountSum = 0L;
|
||||
for (GaoSalesOrderItem item : itemList) {
|
||||
@@ -721,7 +784,7 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
"订单项履约数量不能为负数");
|
||||
TimiException.requiredTrue(item.getReservedBaseQuantity().add(item.getFulfilledBaseQuantity()).compareTo(item.getBaseQuantity()) <= 0,
|
||||
"订单项履约数量不能超过购买数量");
|
||||
if (expectedItemType == GaoSalesOrderItem.ItemType.PACKAGE_ENTITLEMENT) {
|
||||
if (expectedItemType != GaoSalesOrderItem.ItemType.DIRECT_PRODUCT) {
|
||||
TimiException.requiredNull(item.getUnitPrice(), "套餐订单项不能填写单价");
|
||||
TimiException.requiredNull(item.getLineAmount(), "套餐订单项不能填写行金额");
|
||||
} else {
|
||||
@@ -735,8 +798,10 @@ public class GaoSalesOrderServiceImplement extends AbstractEntityService<GaoSale
|
||||
TimiException.requiredTrue(lineAmountSum == saleAmount, "直接产品订单行金额合计必须等于成交价");
|
||||
}
|
||||
GaoSalesOrder order = newOrder(storeId, customerId, orderType, requestNo, purchasedAt, operatorUserId, remark);
|
||||
order.setRecycleItemId(recycleItemId);
|
||||
order.setRecycleRequiredQuantity(recycleRequiredQuantity);
|
||||
order.setSaleAmount(saleAmount);
|
||||
boolean paidAtCreate = saleAmount == 0;
|
||||
boolean paidAtCreate = saleAmount == 0 && orderType != GaoSalesOrder.OrderType.RECYCLE;
|
||||
order.setPaymentStatus(paidAtCreate ? GaoSalesOrder.PaymentStatus.PAID : GaoSalesOrder.PaymentStatus.UNPAID);
|
||||
if (paidAtCreate) {
|
||||
order.setPaidAt(Time.now());
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.imyeyu.api.modules.gao.task;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Notify;
|
||||
import com.imyeyu.api.modules.common.entity.NotifyDetail;
|
||||
import com.imyeyu.api.modules.common.service.NotifyService;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleReminderMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoUserMapper;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换核销提醒
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleReminderTask {
|
||||
|
||||
private final GaoRecycleReminderMapper mapper;
|
||||
private final GaoUserMapper userMapper;
|
||||
private final NotifyService notifyService;
|
||||
|
||||
/// 每天提醒门店处理待核销兑换单
|
||||
@Scheduled(cron = "0 0 21 * * ?", zone = "Asia/Shanghai")
|
||||
public void sendReminder() {
|
||||
for (String storeId : mapper.selectPendingStoreIds()) {
|
||||
for (var manager : userMapper.selectEnabledStoreManagers(storeId)) {
|
||||
try {
|
||||
NotifyDetail detail = new NotifyDetail();
|
||||
detail.setMsgType(NotifyDetail.MsgType.INTERNAL);
|
||||
detail.setSubject("回收兑换核销提醒");
|
||||
detail.setContent("<p>门店有待核销的回收兑换单,请及时处理</p>");
|
||||
detail.setContentType(NotifyDetail.ContentType.TIP_TAP);
|
||||
detail.setSendTo(manager.getUserId());
|
||||
detail.setSendAt(Time.now());
|
||||
Notify notify = new Notify();
|
||||
notify.setBizType("GAO_RECYCLE_EXCHANGE_REMINDER");
|
||||
notify.setBizRemindedType("VERIFY");
|
||||
notify.setBizRemindedKey("%s:%s:%s:VERIFY".formatted(LocalDate.now(ZoneId.of("Asia/Shanghai")), storeId, manager.getUserId()));
|
||||
notify.setDetailList(List.of(detail));
|
||||
notifyService.createIfAbsent(notify);
|
||||
} catch (Exception e) {
|
||||
log.error("回收兑换提醒发送失败: storeId[{}], userId[{}]", storeId, manager.getUserId(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ public class GaoOrderFulfillmentItemRequest {
|
||||
/// 来源销售订单明细 ID
|
||||
private String sourceOrderItemId;
|
||||
|
||||
|
||||
/// 本次实际履约 SKU 单位 ID
|
||||
private String skuUnitId;
|
||||
|
||||
|
||||
@@ -15,6 +15,12 @@ import java.util.List;
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoOrderFulfillmentPage extends BasePage {
|
||||
|
||||
/// true 为允许查询订单履约,仅服务端设置
|
||||
private Boolean orderAllowed;
|
||||
|
||||
/// true 为允许查询回收履约,仅服务端设置
|
||||
private Boolean recycleAllowed;
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import lombok.Data;
|
||||
|
||||
/// 订单交易记录
|
||||
@Data
|
||||
public class GaoOrderTransactionView {
|
||||
/// 交易来源
|
||||
private String type;
|
||||
/// 业务发生时间
|
||||
private Long occurredAt;
|
||||
/// 资金流水
|
||||
private GaoFundRecord fundRecord;
|
||||
/// 回收物支付
|
||||
private GaoRecyclePayment recyclePayment;
|
||||
}
|
||||
@@ -26,6 +26,9 @@ public class GaoProductFulfillmentDailyStatView {
|
||||
/// 套餐权益履约数量,基础单位
|
||||
private BigDecimal packageBaseQuantity;
|
||||
|
||||
/// 回收兑换履约数量,基础单位
|
||||
private BigDecimal recycleBaseQuantity;
|
||||
|
||||
/// 履约基础单位数量
|
||||
private BigDecimal baseQuantity;
|
||||
}
|
||||
|
||||
@@ -38,6 +38,9 @@ public class GaoProductSkuFulfillmentDailyStatView {
|
||||
/// 套餐权益履约数量,基础单位
|
||||
private BigDecimal packageBaseQuantity;
|
||||
|
||||
/// 回收兑换履约数量,基础单位
|
||||
private BigDecimal recycleBaseQuantity;
|
||||
|
||||
/// 履约基础单位数量
|
||||
private BigDecimal baseQuantity;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 人工调整客户回收物额度
|
||||
@Data
|
||||
public class GaoRecycleAccountAdjustRequest {
|
||||
private String storeId;
|
||||
private String customerId;
|
||||
private String recycleItemId;
|
||||
private String requestNo;
|
||||
private BigDecimal quantity;
|
||||
private String reason;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.imyeyu.api.modules.gao.vo;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换状态操作请求
|
||||
@@ -27,11 +28,14 @@ public class GaoRecycleExchangeActionRequest {
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// true 为回收物全部退还客户
|
||||
private Boolean recycleReturned;
|
||||
/// 撤销后门店实际保留的回收物数量,未填写时保留全部
|
||||
private BigDecimal retainedRecycleQuantity;
|
||||
|
||||
/// true 为兑换商品已退回门店
|
||||
private Boolean stockReturned;
|
||||
/// 撤销时按整单冲正的履约列表
|
||||
private List<GaoOrderFulfillmentRevokeRequest> fulfillmentRevokeList;
|
||||
|
||||
/// 取消时选择冲正的回收物支付
|
||||
private List<GaoRecyclePaymentRequest> paymentRevokeList;
|
||||
|
||||
/// 附件列表
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
@@ -19,18 +19,36 @@ public class GaoRecycleExchangeCreateRequest {
|
||||
/// 规则 ID
|
||||
private String ruleId;
|
||||
|
||||
/// 回收物 ID,自由创建时使用
|
||||
private String recycleItemId;
|
||||
|
||||
/// 兑换权益明细
|
||||
private List<GaoRecycleExchangeItemRequest> itemList;
|
||||
|
||||
/// 请求幂等号
|
||||
private String requestNo;
|
||||
|
||||
/// true 为创建时确认收到全部回收物并核销
|
||||
private Boolean verifyPayment;
|
||||
|
||||
/// 本次创建时回收并核销的数量,零表示不核销
|
||||
private BigDecimal paymentQuantity;
|
||||
|
||||
/// 回收凭证照片
|
||||
private List<Attachment> paymentAttachmentList;
|
||||
|
||||
/// true 为全部产品立即履约并核销
|
||||
private Boolean fulfillAll;
|
||||
|
||||
/// 履约凭证照片
|
||||
private List<Attachment> fulfillmentAttachmentList;
|
||||
|
||||
/// 规则倍数
|
||||
private Integer multiple;
|
||||
|
||||
/// 实际回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 实际兑换数量
|
||||
private BigDecimal exchangeQuantity;
|
||||
|
||||
/// 业务发生时间
|
||||
private Long occurredAt;
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.imyeyu.api.modules.gao.vo;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductStockRecord;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
@@ -13,7 +12,7 @@ import java.util.Map;
|
||||
@Data
|
||||
public class GaoRecycleExchangeDetail {
|
||||
|
||||
/// 兑换单
|
||||
/// 兑换单,含权益明细
|
||||
private GaoRecycleExchange exchange;
|
||||
|
||||
/// 操作记录
|
||||
@@ -24,7 +23,4 @@ public class GaoRecycleExchangeDetail {
|
||||
|
||||
/// 操作记录附件,按操作 ID 分组
|
||||
private Map<String, List<Attachment>> actionAttachments;
|
||||
|
||||
/// 库存流水
|
||||
private List<GaoProductStockRecord> stockRecordList;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 兑换权益明细请求
|
||||
@Data
|
||||
public class GaoRecycleExchangeItemRequest {
|
||||
/// SKU ID
|
||||
private String skuId;
|
||||
/// SKU 单位 ID
|
||||
private String skuUnitId;
|
||||
/// 兑换数量
|
||||
private BigDecimal quantity;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.java.bean.BasePage;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/// 回收兑换分页条件
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleExchangePage extends BasePage {
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 客户 ID
|
||||
private String customerId;
|
||||
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// SKU ID
|
||||
private String skuId;
|
||||
|
||||
/// 兑换单状态
|
||||
private GaoRecycleExchange.Status status;
|
||||
|
||||
/// 业务时间起点,包含
|
||||
private Long beginAt;
|
||||
|
||||
/// 业务时间终点,包含
|
||||
private Long endAt;
|
||||
}
|
||||
@@ -4,10 +4,14 @@ import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
|
||||
/// 回收兑换规则配置请求
|
||||
@Data
|
||||
public class GaoRecycleExchangeRuleRequest {
|
||||
/// 兑换模板明细
|
||||
private List<GaoRecycleExchangeRuleItem> itemList;
|
||||
/// 规则 ID,创建时为空
|
||||
private String id;
|
||||
|
||||
@@ -20,15 +24,6 @@ public class GaoRecycleExchangeRuleRequest {
|
||||
/// 单份回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 兑换 SKU ID
|
||||
private String skuId;
|
||||
|
||||
/// 兑换单位 ID
|
||||
private String skuUnitId;
|
||||
|
||||
/// 单份兑换数量
|
||||
private BigDecimal exchangeQuantity;
|
||||
|
||||
/// 状态
|
||||
private GaoRecycleExchangeRule.Status status;
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
/// 回收物配置请求
|
||||
@@ -18,15 +20,15 @@ public class GaoRecycleItemRequest {
|
||||
/// 回收单位
|
||||
private String unitName;
|
||||
|
||||
/// 来源产品 ID
|
||||
private String productId;
|
||||
|
||||
/// 来源 SKU ID
|
||||
private String skuId;
|
||||
/// 是否允许小数数量
|
||||
private Boolean allowDecimalQuantity;
|
||||
|
||||
/// 状态
|
||||
private GaoRecycleItem.Status status;
|
||||
|
||||
/// 图片附件
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付请求
|
||||
@Data
|
||||
public class GaoRecyclePaymentRequest {
|
||||
private String orderId;
|
||||
private String paymentId;
|
||||
private String requestNo;
|
||||
private BigDecimal quantity;
|
||||
private Long occurredAt;
|
||||
private String reason;
|
||||
private Boolean returnedToCustomer;
|
||||
private List<Attachment> attachmentList;
|
||||
}
|
||||
@@ -15,6 +15,12 @@ import java.util.List;
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoSalesOrderPage extends BasePage {
|
||||
|
||||
/// true 为允许查询普通订单
|
||||
private Boolean orderAllowed;
|
||||
|
||||
/// true 为允许查询回收兑换订单
|
||||
private Boolean recycleAllowed;
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user