Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
445da5f093 | ||
|
|
8f4a839b2f | ||
|
|
bd3f10fe60 | ||
|
|
169fd257a9 | ||
|
|
b62c7f2495 | ||
|
|
bc901e2f0b | ||
|
|
74dd150469 |
@@ -11,7 +11,7 @@
|
||||
|
||||
<groupId>com.imyeyu.timiserverapi</groupId>
|
||||
<artifactId>TimiServerAPI</artifactId>
|
||||
<version>1.0.68</version>
|
||||
<version>1.0.70</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>TimiServerAPI</name>
|
||||
<description>imyeyu.com API</description>
|
||||
|
||||
@@ -21,6 +21,7 @@ import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.SQLException;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -32,18 +33,14 @@ import java.util.List;
|
||||
*/
|
||||
@Configuration
|
||||
@MapperScan(basePackages = {
|
||||
"com.imyeyu.api.modules.git.mapper",
|
||||
"com.imyeyu.api.modules.gao.mapper",
|
||||
"com.imyeyu.api.modules.bill.mapper",
|
||||
"com.imyeyu.api.modules.user.mapper",
|
||||
"com.imyeyu.api.modules.blog.mapper",
|
||||
"com.imyeyu.api.modules.lyric.mapper",
|
||||
"com.imyeyu.api.modules.mirror.mapper",
|
||||
"com.imyeyu.api.modules.system.mapper",
|
||||
"com.imyeyu.api.modules.common.mapper",
|
||||
"com.imyeyu.api.modules.app.mapper",
|
||||
"com.imyeyu.api.modules.journal.mapper",
|
||||
"com.imyeyu.api.modules.minecraft.mapper"
|
||||
}, sqlSessionFactoryRef = "timiServerSqlSessionFactory")
|
||||
public class TimiServerDBConfig {
|
||||
|
||||
@@ -59,6 +56,9 @@ public class TimiServerDBConfig {
|
||||
dataSource.setMinimumIdle(10);
|
||||
dataSource.setMaximumPoolSize(100);
|
||||
dataSource.setConnectionTestQuery("SELECT 1");
|
||||
// 日统计按后端时区划分日期
|
||||
String offset = OffsetDateTime.now().getOffset().getId();
|
||||
dataSource.setConnectionInitSql("SET time_zone = '%s'".formatted("Z".equals(offset) ? "+00:00" : offset));
|
||||
|
||||
dataSource.setMaxLifetime(Time.S * 180);
|
||||
dataSource.setIdleTimeout(Time.S * 120);
|
||||
|
||||
@@ -56,6 +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,
|
||||
|
||||
+8
@@ -316,6 +316,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
|
||||
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.required");
|
||||
}
|
||||
Attachment tempFile = mapper.selectRaw(tempFileId);
|
||||
if (tempFile == null) {
|
||||
// 临时文件不存在或已过期,按业务错误拒绝,避免空指针变成 500
|
||||
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
|
||||
}
|
||||
tempFile.setBizType(bizType);
|
||||
tempFile.setBizId(bizId);
|
||||
tempFile.setAttachType(item.getAttachType());
|
||||
@@ -334,6 +338,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
|
||||
// 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录
|
||||
Attachment current = mapper.selectRaw(item.getId());
|
||||
Attachment tempFile = mapper.selectRaw(tempFileId);
|
||||
if (current == null || tempFile == null) {
|
||||
// 附件或临时文件已被清理,按业务错误拒绝
|
||||
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
|
||||
}
|
||||
// 源文件版本已变化,旧缩略图全部失效
|
||||
variantService.deleteBySourceId(current.getId());
|
||||
// 删除旧 GridFS 文件
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -153,6 +155,12 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
|
||||
|
||||
POINT_REDEEM_SKU_MANAGE("POINT_REDEEM_SKU:MANAGE", "积分兑换 SKU 配置管理", true, true),
|
||||
|
||||
RECYCLE_EXCHANGE_CONFIG_MANAGE("RECYCLE_EXCHANGE:CONFIG_MANAGE", "回收兑换配置管理", true, true),
|
||||
|
||||
RECYCLE_ACCOUNT_READ("RECYCLE_ACCOUNT:READ", "回收物额度查询", true, true),
|
||||
|
||||
RECYCLE_ACCOUNT_ADJUST("RECYCLE_ACCOUNT:ADJUST", "回收物额度调整", true, true),
|
||||
|
||||
STAT_READ("STAT:READ", "统计读取", false, false),
|
||||
|
||||
DATA_EXPORT("DATA_EXPORT", "数据导出", true, 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()), "客户不属于当前门店");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleConfigService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleItemRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeRuleRequest;
|
||||
import com.imyeyu.spring.annotation.AOPLog;
|
||||
import com.imyeyu.spring.annotation.RequestRateLimit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.imyeyu.spring.bean.PageResult;
|
||||
|
||||
/// 回收物和兑换规则接口
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/config")
|
||||
public class GaoRecycleConfigController {
|
||||
|
||||
private final GaoRecycleConfigService service;
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/items")
|
||||
public PageResult<GaoRecycleItem> items(@RequestParam(required = false) String storeId,
|
||||
@RequestParam(required = false) GaoRecycleItem.Status status,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
|
||||
return service.items(storeId, status, keyword, offset, limit);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/item/detail")
|
||||
public GaoRecycleItem itemDetail(@RequestParam(required = false) String storeId, @RequestParam String id) {
|
||||
return service.itemDetail(storeId, id);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/item/save")
|
||||
public GaoRecycleItem saveItem(@RequestBody GaoRecycleItemRequest item) {
|
||||
return service.saveItem(item);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/rules")
|
||||
public PageResult<GaoRecycleExchangeRule> rules(@RequestParam(required = false) String storeId,
|
||||
@RequestParam(required = false) GaoRecycleExchangeRule.Status status,
|
||||
@RequestParam(required = false) String recycleItemId,
|
||||
@RequestParam(required = false) String skuId,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
|
||||
return service.rules(storeId, status, recycleItemId, skuId, keyword, offset, limit);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/rule/detail")
|
||||
public GaoRecycleExchangeRule ruleDetail(@RequestParam(required = false) String storeId, @RequestParam String id) {
|
||||
return service.ruleDetail(storeId, id);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/rule/save")
|
||||
public GaoRecycleExchangeRule saveRule(@RequestBody GaoRecycleExchangeRuleRequest rule) {
|
||||
return service.saveRule(rule);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.RECYCLE_EXCHANGE_CONFIG_MANAGE)
|
||||
@PostMapping("/rule/delete")
|
||||
public void deleteRule(@RequestParam(required = false) String storeId, @RequestParam String id) {
|
||||
service.deleteRule(storeId, id);
|
||||
}
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/rules/active")
|
||||
public PageResult<GaoRecycleExchangeRule> activeRules(@RequestParam(required = false) String storeId,
|
||||
@RequestParam(required = false) String recycleItemId,
|
||||
@RequestParam(required = false) String skuId,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "20") int limit) {
|
||||
return service.rules(storeId, GaoRecycleExchangeRule.Status.ACTIVE, recycleItemId, skuId, keyword, offset, limit);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeQueryService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeViewService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeDetail;
|
||||
import com.imyeyu.spring.annotation.AOPLog;
|
||||
import com.imyeyu.spring.annotation.RequestRateLimit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/// 回收兑换查询接口
|
||||
///
|
||||
/// 兑换单列表已并入交易订单查询,这里只保留详情
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/exchange")
|
||||
public class GaoRecycleExchangeQueryController {
|
||||
|
||||
private final GaoRecycleExchangeQueryService service;
|
||||
private final GaoRecycleExchangeViewService viewService;
|
||||
|
||||
/// 查询兑换单详情
|
||||
///
|
||||
/// @param id 兑换单 ID
|
||||
/// @return 兑换单详情
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/detail")
|
||||
public GaoRecycleExchangeDetail detail(@RequestParam String id) {
|
||||
GaoRecycleExchangeDetail detail = service.detail(id);
|
||||
viewService.fill(detail.getExchange());
|
||||
viewService.fillActions(detail.getActionList());
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeWriteService;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleExchangeViewService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeCreateRequest;
|
||||
import com.imyeyu.spring.annotation.AOPLog;
|
||||
import com.imyeyu.spring.annotation.RequestRateLimit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/// 回收兑换交易接口
|
||||
///
|
||||
/// 兑换权益的领取、核销与冲正统一由 `/gao/order/fulfillment` 承载,
|
||||
/// 这里只保留开单,取消统一通过订单接口处理。
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/exchange")
|
||||
public class GaoRecycleExchangeWriteController {
|
||||
private final GaoRecycleExchangeWriteService service;
|
||||
private final GaoRecycleExchangeViewService viewService;
|
||||
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_CREATE)
|
||||
@PostMapping("/create")
|
||||
public GaoRecycleExchange create(@RequestBody GaoRecycleExchangeCreateRequest request) {
|
||||
return viewService.fill(service.create(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecyclePaymentService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import com.imyeyu.api.bean.PermissionMatchMode;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderTransactionView;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.bean.ModuleCode;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付接口
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/payment")
|
||||
public class GaoRecyclePaymentController {
|
||||
private final GaoRecyclePaymentService service;
|
||||
private final PermissionChecker permissions;
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_CREATE)
|
||||
@PostMapping("/create")
|
||||
public GaoRecyclePayment create(@RequestBody GaoRecyclePaymentRequest request) { return service.create(request); }
|
||||
|
||||
@RequireGaoPermission(value = {GaoPermissionCode.FUND_RECEIVE_CREATE, GaoPermissionCode.FUND_RECEIVE_VERIFY}, mode = PermissionMatchMode.ALL)
|
||||
@PostMapping("/create-and-verify")
|
||||
public GaoRecyclePayment createAndVerify(@RequestBody GaoRecyclePaymentRequest request) { return service.createAndVerify(request); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
|
||||
@PostMapping("/list")
|
||||
public List<GaoRecyclePayment> list(@RequestParam String orderId) { return service.list(orderId); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
|
||||
@PostMapping("/search")
|
||||
public List<GaoRecyclePayment> search(@RequestParam(required = false) String storeId,
|
||||
@RequestParam(required = false) String customerId, @RequestParam(required = false) String orderId, @RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) Long beginAt, @RequestParam(required = false) Long endAt,
|
||||
@RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "21") int limit) {
|
||||
return service.search(storeId, customerId, orderId, status, beginAt, endAt, offset, limit);
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECORD_READ)
|
||||
@PostMapping("/transactions")
|
||||
public List<GaoOrderTransactionView> transactions(@RequestParam String orderId) {
|
||||
return service.transactions(orderId, permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.FUND_RECORD_READ.getValue()), permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.FUND_RECORD_READ.getValue()));
|
||||
}
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_VERIFY)
|
||||
@PostMapping("/verify")
|
||||
public GaoRecyclePayment verify(@RequestBody GaoRecyclePaymentRequest request) { return service.verify(request.getPaymentId()); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_VERIFY)
|
||||
@PostMapping("/reject")
|
||||
public GaoRecyclePayment reject(@RequestBody GaoRecyclePaymentRequest request) { return service.release(request, true); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_RECEIVE_CREATE)
|
||||
@PostMapping("/cancel")
|
||||
public GaoRecyclePayment cancel(@RequestBody GaoRecyclePaymentRequest request) { return service.release(request, false); }
|
||||
|
||||
@RequireGaoPermission(GaoPermissionCode.FUND_REVOKE)
|
||||
@PostMapping("/revoke")
|
||||
public GaoRecyclePayment revoke(@RequestBody GaoRecyclePaymentRequest request) { return service.revoke(request); }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.service.GaoRecycleStatService;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleStatView;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView;
|
||||
import com.imyeyu.spring.annotation.AOPLog;
|
||||
import com.imyeyu.spring.annotation.RequestRateLimit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// GAO 回收统计接口
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/gao/recycle/stat")
|
||||
public class GaoRecycleStatController {
|
||||
private final GaoRecycleStatService service;
|
||||
|
||||
/// 按业务时间统计回收物收到、退回及净数量
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param startAt 区间起点,包含
|
||||
/// @param endAt 区间终点,不包含
|
||||
/// @return 回收统计
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/recycle")
|
||||
public List<GaoRecycleStatView> recycle(@RequestParam(required = false) String storeId,
|
||||
@RequestParam long startAt, @RequestParam long endAt) {
|
||||
return service.recycle(storeId, startAt, endAt);
|
||||
}
|
||||
|
||||
/// 按业务时间统计兑换、核销和冲正数量
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param startAt 区间起点,包含
|
||||
/// @param endAt 区间终点,不包含
|
||||
/// @return 兑换统计
|
||||
@AOPLog
|
||||
@RequestRateLimit
|
||||
@RequireGaoPermission(GaoPermissionCode.SALES_ORDER_READ)
|
||||
@PostMapping("/exchange")
|
||||
public List<GaoRecycleExchangeStatView> exchange(@RequestParam(required = false) String storeId,
|
||||
@RequestParam long startAt, @RequestParam long endAt) {
|
||||
return service.exchange(storeId, startAt, endAt);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
package com.imyeyu.api.modules.gao.controller;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换单
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleExchange extends UUIDEntity {
|
||||
|
||||
/// 状态
|
||||
public enum Status {
|
||||
|
||||
/// 待领取,尚有可领取权益
|
||||
PENDING,
|
||||
|
||||
/// 已完成,权益全部领取完毕
|
||||
COMPLETED,
|
||||
|
||||
/// 已撤销
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 客户 ID
|
||||
private String customerId;
|
||||
|
||||
/// 请求幂等号
|
||||
private String requestNo;
|
||||
|
||||
/// 请求摘要
|
||||
private String requestFingerprint;
|
||||
|
||||
/// 规则 ID
|
||||
private String ruleId;
|
||||
|
||||
/// 生成的销售订单 ID
|
||||
private String salesOrderId;
|
||||
|
||||
/// 创建时兑换模板快照
|
||||
private JsonNode ruleSnapshot;
|
||||
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 回收物当前是否允许小数数量
|
||||
@Transient
|
||||
private Boolean allowDecimalQuantity;
|
||||
|
||||
/// 回收物当前图片
|
||||
@Transient
|
||||
private List<Attachment> recycleItemAttachments;
|
||||
|
||||
/// 回收物名称快照
|
||||
private String recycleNameSnapshot;
|
||||
|
||||
/// 回收物单位快照
|
||||
private String recycleUnitSnapshot;
|
||||
|
||||
/// 规则回收数量快照
|
||||
private BigDecimal ruleRecycleQuantity;
|
||||
|
||||
/// 模板份数,自由创建时为空
|
||||
private Integer multiple;
|
||||
|
||||
/// 模板预设回收数量 = 规则回收数量 × 份数,自由创建时为空
|
||||
private BigDecimal defaultRecycleQuantity;
|
||||
|
||||
/// 实际回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 状态
|
||||
private Status status;
|
||||
|
||||
/// 操作人 ID
|
||||
private String operatorUserId;
|
||||
|
||||
/// 业务发生时间
|
||||
private Long occurredAt;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// 客户资料,展示用,由控制器批量填充
|
||||
@Transient
|
||||
private GaoCustomer customer;
|
||||
|
||||
/// 操作人,展示用,由控制器批量填充
|
||||
@Transient
|
||||
private User operator;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/// 回收兑换操作记录
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleExchangeAction extends UUIDEntity {
|
||||
/// 撤销后门店最终保留的回收物数量
|
||||
private BigDecimal retainedRecycleQuantity;
|
||||
|
||||
/// 操作类型。兑换权益的核销与冲正由履约单承载,兑换单只剩撤销。
|
||||
public enum ActionType {
|
||||
|
||||
/// 撤销
|
||||
CANCEL
|
||||
}
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 兑换单 ID
|
||||
private String exchangeId;
|
||||
|
||||
/// 请求幂等号
|
||||
private String requestNo;
|
||||
|
||||
/// 请求摘要
|
||||
private String requestFingerprint;
|
||||
|
||||
/// 操作类型
|
||||
private ActionType actionType;
|
||||
|
||||
/// 操作人 ID
|
||||
private String operatorUserId;
|
||||
|
||||
/// 业务发生时间
|
||||
private Long occurredAt;
|
||||
|
||||
/// 原因
|
||||
private String reason;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// 操作人,展示用,由控制器批量填充
|
||||
@Transient
|
||||
private User operator;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换规则
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleExchangeRule extends UUIDEntity {
|
||||
/// 兑换模板明细
|
||||
@Transient
|
||||
private List<GaoRecycleExchangeRuleItem> itemList;
|
||||
|
||||
/// 状态
|
||||
public enum Status {
|
||||
|
||||
/// 启用
|
||||
ACTIVE,
|
||||
|
||||
/// 停用
|
||||
INACTIVE
|
||||
}
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 单份模板回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 状态
|
||||
private Status status;
|
||||
|
||||
/// 排序值
|
||||
private Integer sort;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// 回收物名称,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String recycleName;
|
||||
|
||||
/// 回收物计量单位,展示用,由服务批量填充
|
||||
@Transient
|
||||
private String recycleUnit;
|
||||
|
||||
/// 回收物图片,展示用
|
||||
@Transient
|
||||
private List<Attachment> recycleItemAttachments;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 回收兑换模板明细
|
||||
@Data
|
||||
public class GaoRecycleExchangeRuleItem {
|
||||
|
||||
private String id;
|
||||
private String ruleId;
|
||||
private String skuId;
|
||||
private String skuUnitId;
|
||||
private BigDecimal exchangeQuantity;
|
||||
private Integer sort;
|
||||
private Long createdAt;
|
||||
/// 展示用产品名称
|
||||
private String productName;
|
||||
/// 展示用 SKU 名称
|
||||
private String skuName;
|
||||
/// 展示用规格摘要
|
||||
private String specSummary;
|
||||
/// 展示用单位名称
|
||||
private String unitName;
|
||||
/// 展示用 SKU 编码
|
||||
private String skuCode;
|
||||
/// 展示用产品类型
|
||||
private String productType;
|
||||
/// true 为启用库存管理
|
||||
private Boolean stockEnabled;
|
||||
/// true 为允许小数数量
|
||||
private Boolean allowDecimalQuantity;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/// 回收物类型
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecycleItem extends UUIDEntity {
|
||||
|
||||
/// 状态
|
||||
public enum Status {
|
||||
|
||||
/// 启用
|
||||
ACTIVE,
|
||||
|
||||
/// 停用
|
||||
INACTIVE
|
||||
}
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 名称
|
||||
private String name;
|
||||
|
||||
/// 回收计量单位
|
||||
private String unitName;
|
||||
|
||||
/// 是否允许小数数量
|
||||
private Boolean allowDecimalQuantity;
|
||||
|
||||
/// 状态
|
||||
private Status status;
|
||||
|
||||
/// 图片附件
|
||||
@Transient
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.imyeyu.api.modules.gao.entity;
|
||||
|
||||
import com.imyeyu.spring.entity.UUIDEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付记录
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoRecyclePayment extends UUIDEntity {
|
||||
|
||||
/// 支付状态
|
||||
public enum Status {PENDING, VERIFIED, REJECTED, CANCELLED, REVOKED}
|
||||
|
||||
private String storeId;
|
||||
private String customerId;
|
||||
private String orderId;
|
||||
private String recycleItemId;
|
||||
private String requestNo;
|
||||
/// 请求内容摘要
|
||||
private String requestFingerprint;
|
||||
private BigDecimal quantity;
|
||||
private Status status;
|
||||
private String sourcePaymentId;
|
||||
private String operatorUserId;
|
||||
private String verifierUserId;
|
||||
private Long occurredAt;
|
||||
private Long verifiedAt;
|
||||
private String reason;
|
||||
private Boolean returnedToCustomer;
|
||||
/// 支付附件
|
||||
@Transient
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 带方向的数量,支付为正、冲正为负
|
||||
///
|
||||
/// 冲正记录本身也是 VERIFIED,直接按 quantity 求和会把冲正重复计入,
|
||||
/// 统计与页面统一用这个字段累加。
|
||||
@Transient
|
||||
private BigDecimal signedQuantity;
|
||||
/// 关联兑换单及客户展示信息
|
||||
@Transient
|
||||
private String recycleExchangeId;
|
||||
@Transient
|
||||
private String recycleName;
|
||||
@Transient
|
||||
private String recycleUnit;
|
||||
@Transient
|
||||
private GaoCustomer customer;
|
||||
@Transient
|
||||
private User operator;
|
||||
@Transient
|
||||
private User verifier;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import 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);
|
||||
|
||||
@@ -12,6 +12,8 @@ public interface GaoProductEditMapper {
|
||||
|
||||
int countSkuReferences(@Param("skuId") String skuId);
|
||||
|
||||
int countRecycleReferences(@Param("skuId") String skuId);
|
||||
|
||||
int countUnitReferences(@Param("unitId") String unitId);
|
||||
|
||||
int countMigrationPrecisionLoss(@Param("skuId") String skuId, @Param("targetUnitId") String targetUnitId,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收配置数据访问
|
||||
public interface GaoRecycleConfigMapper {
|
||||
/// 查询模板明细
|
||||
/// @param ruleId 模板 ID
|
||||
/// @return 模板明细
|
||||
@Select("SELECT * FROM gao_recycle_exchange_rule_item WHERE rule_id=#{ruleId} ORDER BY sort, id")
|
||||
List<GaoRecycleExchangeRuleItem> ruleItems(@Param("ruleId") String ruleId);
|
||||
|
||||
/// 批量查询模板明细
|
||||
/// @param ids 模板 ID 列表
|
||||
/// @return 模板明细
|
||||
@Select("<script>SELECT * FROM gao_recycle_exchange_rule_item WHERE rule_id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> ORDER BY sort, id</script>")
|
||||
List<GaoRecycleExchangeRuleItem> ruleItemsByIds(@Param("ids") Collection<String> ids);
|
||||
|
||||
/// 新增模板明细
|
||||
/// @param item 模板明细
|
||||
@Insert("INSERT INTO gao_recycle_exchange_rule_item (id,rule_id,sku_id,sku_unit_id,exchange_quantity,sort,created_at) VALUES (#{id},#{ruleId},#{skuId},#{skuUnitId},#{exchangeQuantity},#{sort},#{createdAt})")
|
||||
void insertRuleItem(GaoRecycleExchangeRuleItem item);
|
||||
|
||||
/// 删除模板明细
|
||||
/// @param ruleId 模板 ID
|
||||
@Delete("DELETE FROM gao_recycle_exchange_rule_item WHERE rule_id=#{ruleId}")
|
||||
void deleteRuleItems(@Param("ruleId") String ruleId);
|
||||
|
||||
/// 删除模板
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 模板 ID
|
||||
/// @return 删除数量
|
||||
@Delete("DELETE FROM gao_recycle_exchange_rule WHERE store_id=#{storeId} AND id=#{id}")
|
||||
int deleteRule(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 分页查询回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param status 状态,为空不过滤
|
||||
/// @param keyword 名称关键字,为空不过滤
|
||||
/// @param offset 分页偏移量
|
||||
/// @param limit 分页数量
|
||||
/// @return 回收物结果
|
||||
@Select("SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} "
|
||||
+ "AND (#{status} IS NULL OR status = #{status}) "
|
||||
+ "AND (#{keyword} IS NULL OR name LIKE CONCAT('%', #{keyword}, '%')) "
|
||||
+ "ORDER BY created_at DESC LIMIT #{offset}, #{limit}")
|
||||
List<GaoRecycleItem> items(@Param("storeId") String storeId, @Param("status") String status, @Param("keyword") String keyword,
|
||||
@Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
/// 统计回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param status 状态,为空不过滤
|
||||
/// @param keyword 名称关键字,为空不过滤
|
||||
/// @return 统计回收物结果
|
||||
@Select("SELECT COUNT(*) FROM gao_recycle_item WHERE store_id = #{storeId} "
|
||||
+ "AND (#{status} IS NULL OR status = #{status}) "
|
||||
+ "AND (#{keyword} IS NULL OR name LIKE CONCAT('%', #{keyword}, '%'))")
|
||||
long countItems(@Param("storeId") String storeId, @Param("status") String status, @Param("keyword") String keyword);
|
||||
|
||||
/// 按 ID 批量查询回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param idList 回收物 ID 列表
|
||||
/// @return 回收物结果
|
||||
@Select("<script>SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} AND id IN "
|
||||
+ "<foreach collection='idList' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>")
|
||||
List<GaoRecycleItem> itemsByIdList(@Param("storeId") String storeId, @Param("idList") Collection<String> idList);
|
||||
|
||||
/// 查询回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 记录 ID
|
||||
/// @return 回收物结果
|
||||
@Select("SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} AND id = #{id}")
|
||||
GaoRecycleItem itemById(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 锁定回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 记录 ID
|
||||
/// @return 锁定回收物结果
|
||||
@Select("SELECT * FROM gao_recycle_item WHERE store_id = #{storeId} AND id = #{id} FOR UPDATE")
|
||||
GaoRecycleItem item(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 创建回收物
|
||||
///
|
||||
/// @param item 回收物
|
||||
@Insert("INSERT INTO gao_recycle_item (id, store_id, name, unit_name, allow_decimal_quantity, status, remark, created_at) VALUES (#{id}, #{storeId}, #{name}, #{unitName}, #{allowDecimalQuantity}, #{status}, #{remark}, #{createdAt})")
|
||||
void insertItem(GaoRecycleItem item);
|
||||
|
||||
/// 更新回收物
|
||||
///
|
||||
/// @param item 回收物
|
||||
@Update("UPDATE gao_recycle_item SET name=#{name}, unit_name=#{unitName}, allow_decimal_quantity=#{allowDecimalQuantity}, status=#{status}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
|
||||
void updateItem(GaoRecycleItem item);
|
||||
|
||||
/// 分页查询兑换规则
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param status 规则状态,为空不过滤
|
||||
/// @param recycleItemId 回收物 ID,为空不过滤
|
||||
/// @param skuId 兑换 SKU ID,为空不过滤
|
||||
/// @param keyword 回收物名称关键字,为空不过滤
|
||||
/// @param offset 分页偏移量
|
||||
/// @param limit 分页数量
|
||||
/// @return 兑换规则结果
|
||||
@Select("SELECT rule.* FROM gao_recycle_exchange_rule rule WHERE rule.store_id = #{storeId} "
|
||||
+ "AND (#{status} IS NULL OR rule.status = #{status}) "
|
||||
+ "AND (#{recycleItemId} IS NULL OR rule.recycle_item_id = #{recycleItemId}) "
|
||||
+ "AND (#{skuId} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_exchange_rule_item ri WHERE ri.rule_id=rule.id AND ri.sku_id=#{skuId})) "
|
||||
+ "AND (#{keyword} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_item item WHERE item.id = rule.recycle_item_id AND item.name LIKE CONCAT('%', #{keyword}, '%'))) "
|
||||
+ "ORDER BY rule.sort, rule.created_at DESC LIMIT #{offset}, #{limit}")
|
||||
List<GaoRecycleExchangeRule> rules(@Param("storeId") String storeId, @Param("status") String status, @Param("recycleItemId") String recycleItemId,
|
||||
@Param("skuId") String skuId, @Param("keyword") String keyword, @Param("offset") int offset, @Param("limit") int limit);
|
||||
|
||||
/// 统计兑换规则
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param status 规则状态,为空不过滤
|
||||
/// @param recycleItemId 回收物 ID,为空不过滤
|
||||
/// @param skuId 兑换 SKU ID,为空不过滤
|
||||
/// @param keyword 回收物名称关键字,为空不过滤
|
||||
/// @return 统计兑换规则结果
|
||||
@Select("SELECT COUNT(*) FROM gao_recycle_exchange_rule rule WHERE rule.store_id = #{storeId} "
|
||||
+ "AND (#{status} IS NULL OR rule.status = #{status}) "
|
||||
+ "AND (#{recycleItemId} IS NULL OR rule.recycle_item_id = #{recycleItemId}) "
|
||||
+ "AND (#{skuId} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_exchange_rule_item ri WHERE ri.rule_id=rule.id AND ri.sku_id=#{skuId})) "
|
||||
+ "AND (#{keyword} IS NULL OR EXISTS (SELECT 1 FROM gao_recycle_item item WHERE item.id = rule.recycle_item_id AND item.name LIKE CONCAT('%', #{keyword}, '%')))")
|
||||
long countRules(@Param("storeId") String storeId, @Param("status") String status, @Param("recycleItemId") String recycleItemId,
|
||||
@Param("skuId") String skuId, @Param("keyword") String keyword);
|
||||
|
||||
/// 查询兑换规则
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 记录 ID
|
||||
/// @return 兑换规则结果
|
||||
@Select("SELECT * FROM gao_recycle_exchange_rule WHERE store_id = #{storeId} AND id = #{id}")
|
||||
GaoRecycleExchangeRule ruleById(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 锁定兑换规则
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 记录 ID
|
||||
/// @return 锁定兑换规则结果
|
||||
@Select("SELECT * FROM gao_recycle_exchange_rule WHERE store_id = #{storeId} AND id = #{id} FOR UPDATE")
|
||||
GaoRecycleExchangeRule rule(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 创建兑换规则
|
||||
///
|
||||
/// @param rule 兑换规则
|
||||
@Insert("INSERT INTO gao_recycle_exchange_rule (id, store_id, recycle_item_id, recycle_quantity, status, sort, remark, created_at) VALUES (#{id}, #{storeId}, #{recycleItemId}, #{recycleQuantity}, #{status}, #{sort}, #{remark}, #{createdAt})")
|
||||
void insertRule(GaoRecycleExchangeRule rule);
|
||||
|
||||
/// 更新兑换规则
|
||||
///
|
||||
/// @param rule 兑换规则
|
||||
@Update("UPDATE gao_recycle_exchange_rule SET recycle_item_id=#{recycleItemId}, recycle_quantity=#{recycleQuantity}, status=#{status}, sort=#{sort}, remark=#{remark}, updated_at=#{updatedAt} WHERE store_id=#{storeId} AND id=#{id}")
|
||||
void updateRule(GaoRecycleExchangeRule rule);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换查询
|
||||
public interface GaoRecycleExchangeQueryMapper {
|
||||
|
||||
/// 查询兑换单
|
||||
///
|
||||
/// @param id 记录 ID
|
||||
/// @return 兑换单结果
|
||||
@Select("SELECT * FROM gao_recycle_exchange WHERE id = #{id}")
|
||||
GaoRecycleExchange detail(String id);
|
||||
|
||||
/// 查询兑换操作记录
|
||||
///
|
||||
/// @param id 记录 ID
|
||||
/// @return 兑换操作记录结果
|
||||
@Select("SELECT * FROM gao_recycle_exchange_action WHERE exchange_id = #{id} ORDER BY created_at, id")
|
||||
List<GaoRecycleExchangeAction> actions(String id);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.spring.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
/// 回收兑换写入查询
|
||||
public interface GaoRecycleExchangeWriteMapper extends BaseMapper<GaoRecycleExchange, String> {
|
||||
@Update("UPDATE gao_recycle_exchange SET status=#{status}, updated_at=#{updatedAt} WHERE sales_order_id=#{orderId} AND status IN ('PENDING','COMPLETED')")
|
||||
int updateByOrderStatus(@Param("orderId") String orderId, @Param("status") String status, @Param("updatedAt") long updatedAt);
|
||||
@Select("SELECT id FROM gao_store WHERE id = #{id} FOR UPDATE")
|
||||
String lockStore(String id);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange WHERE store_id=#{storeId} AND request_no=#{requestNo}")
|
||||
GaoRecycleExchange byRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange WHERE store_id=#{storeId} AND id=#{id} FOR UPDATE")
|
||||
GaoRecycleExchange lockExchange(@Param("storeId") String storeId, @Param("id") String id);
|
||||
|
||||
/// 不加锁按 ID 取单,只用于动作请求未带门店时反查归属门店;一致性仍由后续 lockExchange 保证
|
||||
@Select("SELECT * FROM gao_recycle_exchange WHERE id=#{id}")
|
||||
GaoRecycleExchange byId(@Param("id") String id);
|
||||
|
||||
/// 按生成的销售订单反查兑换单快照,订单详情用于跳转与展示回收物
|
||||
///
|
||||
/// @param orderId 销售订单 ID
|
||||
/// @return 兑换单,只填 ID 与回收物名称、单位快照
|
||||
@Select("SELECT id, recycle_name_snapshot, recycle_unit_snapshot FROM gao_recycle_exchange WHERE sales_order_id=#{orderId} LIMIT 1")
|
||||
GaoRecycleExchange snapshotByOrderId(@Param("orderId") String orderId);
|
||||
|
||||
@Select("SELECT * FROM gao_recycle_exchange_action WHERE store_id=#{storeId} AND request_no=#{requestNo}")
|
||||
GaoRecycleExchangeAction actionByRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
|
||||
@Insert("INSERT INTO gao_recycle_exchange_action (id,store_id,exchange_id,request_no,request_fingerprint,action_type,operator_user_id,occurred_at,created_at,reason,remark,retained_recycle_quantity) VALUES (#{id},#{storeId},#{exchangeId},#{requestNo},#{requestFingerprint},#{actionType},#{operatorUserId},#{occurredAt},#{createdAt},#{reason},#{remark},#{retainedRecycleQuantity})")
|
||||
void insertAction(GaoRecycleExchangeAction action);
|
||||
|
||||
/// 撤销兑换单。待领取和已完成都允许撤销,撤销后不能再领取
|
||||
///
|
||||
/// @param id 兑换单 ID
|
||||
/// @param updatedAt 更新时间
|
||||
/// @return 影响行数
|
||||
@Update("UPDATE gao_recycle_exchange SET status = 'CANCELLED', updated_at = #{updatedAt} WHERE id = #{id} AND status IN ('PENDING', 'COMPLETED')")
|
||||
int cancel(@Param("id") String id, @Param("updatedAt") long updatedAt);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import com.imyeyu.spring.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付查询
|
||||
public interface GaoRecyclePaymentMapper extends BaseMapper<GaoRecyclePayment, String> {
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE id=#{id} FOR UPDATE")
|
||||
GaoRecyclePayment lock(@Param("id") String id);
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE id=#{id}")
|
||||
GaoRecyclePayment byId(@Param("id") String id);
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE store_id=#{storeId} AND request_no=#{requestNo}")
|
||||
GaoRecyclePayment byRequest(@Param("storeId") String storeId, @Param("requestNo") String requestNo);
|
||||
@Select("SELECT COALESCE(SUM(quantity),0) FROM gao_recycle_payment WHERE order_id=#{orderId} AND status IN ('PENDING','VERIFIED') AND source_payment_id IS NULL")
|
||||
BigDecimal occupied(@Param("orderId") String orderId);
|
||||
@Select("SELECT COALESCE(SUM(quantity),0) FROM gao_recycle_payment WHERE order_id=#{orderId} AND status='VERIFIED' AND source_payment_id IS NULL")
|
||||
BigDecimal paid(@Param("orderId") String orderId);
|
||||
@Select("SELECT * FROM gao_recycle_payment WHERE order_id=#{orderId} ORDER BY created_at, id")
|
||||
List<GaoRecyclePayment> list(@Param("orderId") String orderId);
|
||||
@Select({"<script>",
|
||||
"SELECT p.*, e.id AS recycleExchangeId, e.recycle_name_snapshot AS recycleName, e.recycle_unit_snapshot AS recycleUnit",
|
||||
"FROM gao_recycle_payment p LEFT JOIN gao_recycle_exchange e ON e.sales_order_id = p.order_id WHERE 1=1",
|
||||
"<if test='storeId != null'> AND p.store_id = #{storeId}</if>",
|
||||
"<if test='customerId != null and customerId != ""'> 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);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换提醒查询
|
||||
public interface GaoRecycleReminderMapper {
|
||||
|
||||
/// 查询存在待核销回收物支付的门店
|
||||
/// @return 门店 ID 列表
|
||||
@Select("SELECT DISTINCT store_id FROM gao_recycle_payment WHERE status = 'PENDING' AND source_payment_id IS NULL")
|
||||
List<String> selectPendingStoreIds();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.imyeyu.api.modules.gao.mapper;
|
||||
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleStatView;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// 回收统计 Mapper
|
||||
public interface GaoRecycleStatMapper {
|
||||
/// 按操作业务时间统计收到和退回数量
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param startAt 区间起点,包含
|
||||
/// @param endAt 区间终点,不包含
|
||||
/// @return 回收统计
|
||||
List<GaoRecycleStatView> selectRecycleStats(@Param("storeId") String storeId,
|
||||
@Param("startAt") long startAt, @Param("endAt") long endAt);
|
||||
|
||||
/// 按业务时间统计兑换、核销和冲正数量
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param startAt 区间起点,包含
|
||||
/// @param endAt 区间终点,不包含
|
||||
/// @return 兑换统计
|
||||
List<GaoRecycleExchangeStatView> selectExchangeStats(@Param("storeId") String storeId,
|
||||
@Param("startAt") long startAt, @Param("endAt") long endAt);
|
||||
}
|
||||
@@ -32,6 +32,8 @@ public interface GaoOrderFulfillmentService extends BaseService<GaoOrderFulfillm
|
||||
/// 按销售订单查询履约历史
|
||||
List<GaoOrderFulfillment> listBySalesOrderId(String salesOrderId);
|
||||
|
||||
/// 按回收兑换单查询履约历史
|
||||
|
||||
/// 查询销售订单仍占用权益的履约单数量
|
||||
long countPendingBySalesOrderId(String salesOrderId);
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleAccountMapper;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
import java.util.Objects;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillmentItem;
|
||||
|
||||
/// 客户回收物额度服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleAccountService {
|
||||
private final GaoRecycleAccountMapper mapper;
|
||||
private final UserLoginService login;
|
||||
|
||||
/// 按实际履约产生客户额度,规则结果写入流水快照
|
||||
public void addFromFulfillment(String store, String customer, String fulfillmentId, List<GaoOrderFulfillmentItem> items) {
|
||||
Map<String, BigDecimal> quantities = new TreeMap<>();
|
||||
for (GaoOrderFulfillmentItem item : items) {
|
||||
for (Map<String, Object> yield : mapper.yields(store, item.getSkuId())) {
|
||||
String recycleId = (String) yield.get("recycle_item_id");
|
||||
BigDecimal quantity = item.getBaseQuantity().multiply((BigDecimal) yield.get("quantity_per_base"))
|
||||
.setScale(3, java.math.RoundingMode.DOWN);
|
||||
// 换算不足 0.001 时不计入,避免整笔履约核销因为精度失败
|
||||
if (quantity.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
quantities.merge(recycleId, quantity, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
for (var entry : quantities.entrySet()) {
|
||||
change(store, customer, entry.getKey(), entry.getValue(), BigDecimal.ZERO, "FULFILLMENT_YIELD", fulfillmentId, "yield:" + fulfillmentId + ":" + entry.getKey(), null);
|
||||
}
|
||||
}
|
||||
|
||||
/// 撤回原履约产生的额度,不追溯历史履约
|
||||
public void revokeFulfillment(String store, String customer, String sourceId, String reverseId) {
|
||||
for (Map<String, Object> row : mapper.yieldsByFulfillment(sourceId)) {
|
||||
String item = (String) row.get("recycle_item_id");
|
||||
BigDecimal value = (BigDecimal) row.get("balance_delta");
|
||||
change(store, customer, item, value.negate(), BigDecimal.ZERO, "FULFILLMENT_REVOKE", reverseId, "yield-revoke:" + reverseId + ":" + item, null);
|
||||
}
|
||||
}
|
||||
|
||||
/// 原子变更额度与预占并写入流水
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param customerId 客户 ID
|
||||
/// @param recycleItemId 回收物 ID
|
||||
/// @param balanceDelta 额度变化量
|
||||
/// @param reservedDelta 预占变化量
|
||||
/// @param bizType 业务类型
|
||||
/// @param bizId 业务 ID
|
||||
/// @param requestNo 幂等号
|
||||
/// @param reason 原因
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void change(String storeId, String customerId, String recycleItemId, BigDecimal balanceDelta, BigDecimal reservedDelta, String bizType, String bizId, String requestNo, String reason) {
|
||||
TimiException.required(storeId, "门店不能为空");
|
||||
TimiException.required(customerId, "客户不能为空");
|
||||
TimiException.required(recycleItemId, "回收物不能为空");
|
||||
TimiException.required(balanceDelta, "额度变化不能为空");
|
||||
TimiException.required(reservedDelta, "预占变化不能为空");
|
||||
TimiException.requiredTrue(!(3 < balanceDelta.stripTrailingZeros().scale()) && !(3 < reservedDelta.stripTrailingZeros().scale()), "额度最多保留三位小数");
|
||||
TimiException.requiredTrue(!(15 < balanceDelta.precision() - balanceDelta.scale()) && !(15 < reservedDelta.precision() - reservedDelta.scale()), "额度超出范围");
|
||||
TimiException.required(requestNo, "请求号不能为空");
|
||||
TimiException.requiredTrue(!requestNo.isBlank() && !(128 < requestNo.length()), "请求号无效");
|
||||
TimiException.requiredTrue(bizType != null && !bizType.isBlank() && !(32 < bizType.length()) && bizId != null && !bizId.isBlank() && !(36 < bizId.length()), "额度业务信息无效");
|
||||
long now = Time.now();
|
||||
mapper.ensure(UUID.randomUUID().toString(), storeId, customerId, recycleItemId, now);
|
||||
Map<String, Object> account = mapper.lock(storeId, customerId, recycleItemId);
|
||||
TimiException.required(account, "额度账户不存在");
|
||||
Map<String, Object> existing = mapper.findRequest(storeId, requestNo);
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(Objects.equals(customerId, existing.get("customer_id")) && Objects.equals(recycleItemId, existing.get("recycle_item_id"))
|
||||
&& Objects.equals(bizType, existing.get("biz_type")) && Objects.equals(bizId, existing.get("biz_id"))
|
||||
&& balanceDelta.compareTo((BigDecimal) existing.get("balance_delta")) == 0
|
||||
&& reservedDelta.compareTo((BigDecimal) existing.get("reserved_delta")) == 0
|
||||
&& Objects.equals(reason, existing.get("reason")), "额度流水请求号对应内容不一致");
|
||||
return;
|
||||
}
|
||||
String id = (String) account.get("id");
|
||||
TimiException.requiredTrue(mapper.change(id, balanceDelta, reservedDelta, now) == 1, "可用回收物额度不足");
|
||||
mapper.ledger(UUID.randomUUID().toString(), id, bizType, bizId, requestNo, balanceDelta, reservedDelta, login.getRequireLoginUserId(), reason, now);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.system.audit.AuditOperation;
|
||||
import com.imyeyu.api.modules.system.audit.OperationAudit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProduct;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleItemRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeRuleRequest;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import com.imyeyu.spring.bean.PageResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/// 回收物与兑换规则配置服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleConfigService {
|
||||
private final GaoRecycleConfigMapper mapper;
|
||||
private final AttachmentService attachmentService;
|
||||
private final GaoProductSkuMapper skuMapper;
|
||||
private final GaoProductSkuUnitMapper unitMapper;
|
||||
private final GaoProductSkuService skuService;
|
||||
private final GaoProductService productService;
|
||||
private final GaoStoreScopeService scope;
|
||||
|
||||
/// 分页查询回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param status 状态,为空查询全部
|
||||
/// @param keyword 名称关键字,为空不过滤
|
||||
/// @param offset 偏移量
|
||||
/// @param limit 页大小
|
||||
/// @return 回收物分页结果
|
||||
public PageResult<GaoRecycleItem> items(String storeId, GaoRecycleItem.Status status, String keyword, int offset, int limit) {
|
||||
storeId = resolvePageStore(storeId, offset, limit);
|
||||
String statusName = status == null ? null : status.name();
|
||||
String keywordText = blankToNull(keyword);
|
||||
PageResult<GaoRecycleItem> result = new PageResult<>();
|
||||
result.setTotal(mapper.countItems(storeId, statusName, keywordText));
|
||||
List<GaoRecycleItem> items = mapper.items(storeId, statusName, keywordText, offset, limit);
|
||||
if (!items.isEmpty()) {
|
||||
Map<String, List<Attachment>> photos = attachmentService.mapByBizIdList(
|
||||
Attachment.BizType.GAO_RECYCLE_ITEM, items.stream().map(GaoRecycleItem::getId).toList());
|
||||
items.forEach(item -> item.setAttachmentList(photos.getOrDefault(item.getId(), List.of())));
|
||||
}
|
||||
result.setList(items);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 查询回收物详情
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 回收物 ID
|
||||
/// @return 回收物详情
|
||||
public GaoRecycleItem itemDetail(String storeId, String id) {
|
||||
TimiException.required(id, "回收物 ID 不能为空");
|
||||
String resolved = scope.resolveStoreId(storeId);
|
||||
TimiException.required(resolved, "门店不能为空");
|
||||
GaoRecycleItem item = mapper.itemById(resolved, id);
|
||||
TimiException.required(item, "回收物不存在");
|
||||
item.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, id));
|
||||
return item;
|
||||
}
|
||||
|
||||
/// 分页查询兑换规则
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param status 规则状态,为空查询全部
|
||||
/// @param recycleItemId 回收物 ID,为空不过滤
|
||||
/// @param skuId 兑换 SKU ID,为空不过滤
|
||||
/// @param keyword 回收物名称关键字,为空不过滤
|
||||
/// @param offset 偏移量
|
||||
/// @param limit 页大小
|
||||
/// @return 规则分页结果
|
||||
@Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||
public PageResult<GaoRecycleExchangeRule> rules(String storeId, GaoRecycleExchangeRule.Status status, String recycleItemId, String skuId, String keyword, int offset, int limit) {
|
||||
storeId = resolvePageStore(storeId, offset, limit);
|
||||
String statusName = status == null ? null : status.name();
|
||||
String itemId = blankToNull(recycleItemId);
|
||||
String exchangeSkuId = blankToNull(skuId);
|
||||
String keywordText = blankToNull(keyword);
|
||||
PageResult<GaoRecycleExchangeRule> result = new PageResult<>();
|
||||
result.setTotal(mapper.countRules(storeId, statusName, itemId, exchangeSkuId, keywordText));
|
||||
List<GaoRecycleExchangeRule> list = mapper.rules(storeId, statusName, itemId, exchangeSkuId, keywordText, offset, limit);
|
||||
fillRuleDisplay(storeId, list);
|
||||
result.setList(list);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 查询兑换规则详情
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param id 规则 ID
|
||||
/// @return 兑换规则详情
|
||||
@Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||
public GaoRecycleExchangeRule ruleDetail(String storeId, String id) {
|
||||
TimiException.required(id, "规则 ID 不能为空");
|
||||
String resolved = scope.resolveStoreId(storeId);
|
||||
TimiException.required(resolved, "门店不能为空");
|
||||
GaoRecycleExchangeRule rule = mapper.ruleById(resolved, id);
|
||||
TimiException.required(rule, "兑换规则不存在");
|
||||
fillRuleDisplay(resolved, List.of(rule));
|
||||
return rule;
|
||||
}
|
||||
|
||||
private String resolvePageStore(String storeId, int offset, int limit) {
|
||||
TimiException.requiredTrue(-1 < offset && 0 < limit && !(100 < limit), "分页参数无效");
|
||||
String resolved = scope.resolveStoreId(storeId);
|
||||
TimiException.required(resolved, "门店不能为空");
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private String blankToNull(String value) {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
|
||||
/// 填充规则的回收物、产品、SKU 与业务单位展示字段
|
||||
///
|
||||
/// 规则只存 ID,列表页需要名称才能直接渲染;这里按页内 ID 批量回查,避免逐条查询。
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param ruleList 规则列表
|
||||
private void fillRuleDisplay(String storeId, List<GaoRecycleExchangeRule> ruleList) {
|
||||
if (ruleList == null || ruleList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> itemIdList = distinct(ruleList.stream().map(GaoRecycleExchangeRule::getRecycleItemId).toList());
|
||||
Map<String, List<Attachment>> itemPhotos = itemIdList.isEmpty() ? Map.of()
|
||||
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIdList);
|
||||
Map<String, GaoRecycleItem> itemMap = itemIdList.isEmpty()
|
||||
? Map.of()
|
||||
: mapper.itemsByIdList(storeId, itemIdList).stream().collect(Collectors.toMap(GaoRecycleItem::getId, Function.identity()));
|
||||
Map<String, List<GaoRecycleExchangeRuleItem>> ruleItems = mapper.ruleItemsByIds(ruleList.stream().map(GaoRecycleExchangeRule::getId).toList()).stream().collect(Collectors.groupingBy(GaoRecycleExchangeRuleItem::getRuleId));
|
||||
List<String> skuIdList = distinct(ruleItems.values().stream().flatMap(List::stream).map(GaoRecycleExchangeRuleItem::getSkuId).toList());
|
||||
Map<String, GaoProductSku> skuMap = skuIdList.isEmpty()
|
||||
? Map.of()
|
||||
: skuService.listByIdList(skuIdList).stream().collect(Collectors.toMap(GaoProductSku::getId, Function.identity()));
|
||||
List<String> productIdList = distinct(skuMap.values().stream().map(GaoProductSku::getProductId).toList());
|
||||
Map<String, GaoProduct> productMap = productIdList.isEmpty()
|
||||
? Map.of()
|
||||
: productService.listByIdList(productIdList).stream().collect(Collectors.toMap(GaoProduct::getId, Function.identity()));
|
||||
Map<String, String> unitNameMap = skuIdList.isEmpty()
|
||||
? Map.of()
|
||||
: unitMapper.selectBySkuIdList(skuIdList).stream()
|
||||
.collect(Collectors.toMap(unit -> unit.getSkuId() + ":" + unit.getId(), GaoProductSkuUnit::getName, (left, right) -> left));
|
||||
for (GaoRecycleExchangeRule rule : ruleList) {
|
||||
rule.setItemList(ruleItems.getOrDefault(rule.getId(), List.of()));
|
||||
for (GaoRecycleExchangeRuleItem entry : rule.getItemList()) {
|
||||
GaoProductSku selected = skuMap.get(entry.getSkuId());
|
||||
GaoProduct selectedProduct = selected == null ? null : productMap.get(selected.getProductId());
|
||||
entry.setProductName(selectedProduct == null ? null : selectedProduct.getName());
|
||||
entry.setSkuName(selected == null ? null : selected.getName());
|
||||
entry.setSpecSummary(selected == null ? null : selected.getSpecSummary());
|
||||
entry.setUnitName(unitNameMap.get(entry.getSkuId() + ":" + entry.getSkuUnitId()));
|
||||
entry.setSkuCode(selected == null ? null : selected.getCode());
|
||||
entry.setStockEnabled(selected == null ? null : selected.getStockEnabled());
|
||||
entry.setAllowDecimalQuantity(selected == null ? null : selected.getAllowDecimalQuantity());
|
||||
entry.setProductType(selectedProduct == null || selectedProduct.getProductType() == null ? null : selectedProduct.getProductType().name());
|
||||
}
|
||||
GaoRecycleItem item = rule.getRecycleItemId() == null ? null : itemMap.get(rule.getRecycleItemId());
|
||||
rule.setRecycleName(item == null ? null : item.getName());
|
||||
rule.setRecycleUnit(item == null ? null : item.getUnitName());
|
||||
rule.setRecycleItemAttachments(rule.getRecycleItemId() == null ? List.of() : itemPhotos.getOrDefault(rule.getRecycleItemId(), List.of()));
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> distinct(Collection<String> sourceIdList) {
|
||||
return sourceIdList.stream()
|
||||
.filter(value -> value != null && !value.isBlank())
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// 保存回收物配置
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
@OperationAudit(AuditOperation.GAO_RECYCLE_ITEM_SAVE)
|
||||
public GaoRecycleItem saveItem(GaoRecycleItemRequest request) {
|
||||
TimiException.required(request, "回收物不能为空");
|
||||
GaoRecycleItem item = new GaoRecycleItem();
|
||||
BeanUtils.copyProperties(request, item);
|
||||
String storeId = scope.resolveStoreId(item.getStoreId());
|
||||
TimiException.required(storeId, "门店不能为空");
|
||||
item.setStoreId(storeId);
|
||||
TimiException.required(item.getName(), "回收物名称不能为空");
|
||||
TimiException.required(item.getUnitName(), "回收物单位不能为空");
|
||||
TimiException.required(item.getStatus(), "回收物状态不能为空");
|
||||
TimiException.requiredTrue(!item.getName().isBlank() && !item.getUnitName().isBlank()
|
||||
&& !(128 < item.getName().length()) && !(32 < item.getUnitName().length()), "回收物名称或单位过长");
|
||||
if (item.getId() == null) {
|
||||
if (item.getAllowDecimalQuantity() == null) item.setAllowDecimalQuantity(true);
|
||||
item.setId(UUID.randomUUID().toString());
|
||||
item.setCreatedAt(Time.now());
|
||||
mapper.insertItem(item);
|
||||
} else {
|
||||
GaoRecycleItem existing = mapper.item(storeId, item.getId());
|
||||
TimiException.required(existing, "回收物不存在");
|
||||
if (item.getAllowDecimalQuantity() == null) item.setAllowDecimalQuantity(existing.getAllowDecimalQuantity());
|
||||
item.setUpdatedAt(Time.now());
|
||||
mapper.updateItem(item);
|
||||
}
|
||||
if (request.getAttachmentList() != null) {
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, item.getId(), request.getAttachmentList());
|
||||
item.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_ITEM, item.getId()));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
/// 保存兑换规则
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
@OperationAudit(AuditOperation.GAO_RECYCLE_RULE_SAVE)
|
||||
public GaoRecycleExchangeRule saveRule(GaoRecycleExchangeRuleRequest request) {
|
||||
TimiException.required(request, "兑换规则不能为空");
|
||||
GaoRecycleExchangeRule rule = new GaoRecycleExchangeRule();
|
||||
BeanUtils.copyProperties(request, rule);
|
||||
String storeId = scope.resolveStoreId(rule.getStoreId());
|
||||
TimiException.required(storeId, "门店不能为空");
|
||||
rule.setStoreId(storeId);
|
||||
TimiException.required(rule.getRecycleItemId(), "回收物不能为空");
|
||||
if (rule.getId() != null) {
|
||||
TimiException.required(mapper.rule(storeId, rule.getId()), "规则不存在");
|
||||
}
|
||||
TimiException.required(rule.getStatus(), "规则状态不能为空");
|
||||
GaoRecycleItem item = mapper.item(storeId, rule.getRecycleItemId());
|
||||
TimiException.required(item, "回收物不存在");
|
||||
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
|
||||
TimiException.requiredTrue(item.getStatus() == GaoRecycleItem.Status.ACTIVE, "回收物已停用");
|
||||
}
|
||||
List<GaoRecycleExchangeRuleItem> items = request.getItemList();
|
||||
TimiException.requiredTrue(items != null && !items.isEmpty(), "兑换模板明细不能为空");
|
||||
Set<String> keys = new HashSet<>();
|
||||
TimiException.requiredTrue(items.stream().noneMatch(java.util.Objects::isNull), "兑换模板明细不能为空");
|
||||
List<GaoRecycleExchangeRuleItem> ordered = items.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeRuleItem::getSkuId, java.util.Comparator.nullsFirst(String::compareTo))).toList();
|
||||
for (GaoRecycleExchangeRuleItem entry : ordered) {
|
||||
TimiException.required(entry, "兑换模板明细不能为空");
|
||||
TimiException.required(entry.getSkuId(), "SKU 不能为空");
|
||||
TimiException.required(entry.getSkuUnitId(), "单位不能为空");
|
||||
TimiException.requiredTrue(keys.add(entry.getSkuId() + "|" + entry.getSkuUnitId()), "同一模板内 SKU 和单位不能重复");
|
||||
GaoProductSku sku = skuMapper.selectForUpdate(entry.getSkuId());
|
||||
TimiException.required(sku, "SKU 不存在");
|
||||
TimiException.requiredTrue(storeId.equals(sku.getStoreId()), "SKU 不属于当前门店");
|
||||
GaoProduct product = productService.get(sku.getProductId());
|
||||
TimiException.required(product, "产品不存在");
|
||||
TimiException.requiredTrue(storeId.equals(product.getStoreId()), "产品不属于当前门店");
|
||||
GaoProductSkuUnit unit = skuService.listUnitBySkuId(sku.getId()).stream().filter(value -> entry.getSkuUnitId().equals(value.getId())).findFirst().orElse(null);
|
||||
TimiException.required(unit, "SKU 单位不存在");
|
||||
if (rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE) {
|
||||
TimiException.requiredTrue(product.getStatus() == GaoProduct.Status.ACTIVE && sku.getStatus() == GaoProductSku.Status.ACTIVE && Boolean.TRUE.equals(unit.getAllowSale()), "产品、SKU 或单位不可用");
|
||||
}
|
||||
validateQuantity(entry.getExchangeQuantity());
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < entry.getExchangeQuantity().stripTrailingZeros().scale()), "兑换数量不允许小数");
|
||||
TimiException.required(unit.getBaseQuantityPerUnit(), "单位换算系数不能为空");
|
||||
BigDecimal base = entry.getExchangeQuantity().multiply(unit.getBaseQuantityPerUnit());
|
||||
TimiException.requiredTrue(0 < base.signum() && !(3 < base.stripTrailingZeros().scale()) && !(15 < base.precision() - base.scale()), "基础数量超出精度或范围");
|
||||
}
|
||||
validateQuantity(rule.getRecycleQuantity());
|
||||
if (rule.getSort() == null) {
|
||||
rule.setSort(0);
|
||||
}
|
||||
if (rule.getId() == null) {
|
||||
rule.setId(UUID.randomUUID().toString());
|
||||
rule.setCreatedAt(Time.now());
|
||||
mapper.insertRule(rule);
|
||||
} else {
|
||||
rule.setUpdatedAt(Time.now());
|
||||
mapper.updateRule(rule);
|
||||
}
|
||||
mapper.deleteRuleItems(rule.getId());
|
||||
int position = 0;
|
||||
for (GaoRecycleExchangeRuleItem entry : items) {
|
||||
entry.setId(UUID.randomUUID().toString());
|
||||
entry.setRuleId(rule.getId());
|
||||
entry.setSort(position++);
|
||||
entry.setCreatedAt(Time.now());
|
||||
mapper.insertRuleItem(entry);
|
||||
}
|
||||
fillRuleDisplay(storeId, List.of(rule));
|
||||
return rule;
|
||||
}
|
||||
|
||||
/// 删除兑换模板
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void deleteRule(String storeId, String id) {
|
||||
String resolved = scope.resolveStoreId(storeId);
|
||||
TimiException.required(resolved, "门店不能为空");
|
||||
TimiException.required(mapper.rule(resolved, id), "规则不存在");
|
||||
mapper.deleteRuleItems(id);
|
||||
mapper.deleteRule(resolved, id);
|
||||
}
|
||||
|
||||
private void validateQuantity(BigDecimal quantity) {
|
||||
TimiException.required(quantity, "数量不能为空");
|
||||
TimiException.requiredTrue(0 < quantity.signum() && !(3 < quantity.stripTrailingZeros().scale())
|
||||
&& !(15 < quantity.precision() - quantity.scale()), "数量必须大于零且符合精度范围");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeQueryMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeDetail;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/// 回收兑换查询服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleExchangeQueryService {
|
||||
|
||||
private final GaoRecycleExchangeQueryMapper mapper;
|
||||
private final GaoRecycleConfigMapper configMapper;
|
||||
private final GaoStoreScopeService scopeService;
|
||||
private final AttachmentService attachmentService;
|
||||
|
||||
/// 查询兑换单、权益明细、操作记录和附件
|
||||
///
|
||||
/// 库存随履约走,兑换单本身不产生库存流水,所以详情里没有流水列表。
|
||||
///
|
||||
/// @param id 兑换单 ID
|
||||
/// @return 兑换单详情
|
||||
/// @throws TimiException 兑换单不存在或超出门店范围
|
||||
public GaoRecycleExchangeDetail detail(String id) {
|
||||
TimiException.required(id, "兑换单 ID 不能为空");
|
||||
GaoRecycleExchange exchange = mapper.detail(id);
|
||||
TimiException.required(exchange, "兑换单不存在");
|
||||
scopeService.checkStoreId(exchange.getStoreId());
|
||||
if (exchange.getRecycleItemId() != null) {
|
||||
GaoRecycleItem item = configMapper.itemById(exchange.getStoreId(), exchange.getRecycleItemId());
|
||||
if (item != null) exchange.setAllowDecimalQuantity(item.getAllowDecimalQuantity());
|
||||
}
|
||||
GaoRecycleExchangeDetail detail = new GaoRecycleExchangeDetail();
|
||||
detail.setExchange(exchange);
|
||||
List<GaoRecycleExchangeAction> actions = mapper.actions(id);
|
||||
detail.setActionList(actions);
|
||||
Map<String, List<Attachment>> attachments = new HashMap<>();
|
||||
for (GaoRecycleExchangeAction action : actions) {
|
||||
attachments.put(action.getId(), attachmentService.listByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId()));
|
||||
}
|
||||
detail.setActionAttachments(attachments);
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.api.modules.user.service.UserService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/// 回收兑换展示数据填充
|
||||
///
|
||||
/// 兑换单只落客户 ID 与操作人 ID,客户资料、头像和操作人昵称在响应前批量补齐,
|
||||
/// 调用方拿到单据就能直接渲染,不需要再逐条回查。
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleExchangeViewService {
|
||||
|
||||
private final AttachmentService attachmentService;
|
||||
private final GaoCustomerService customerService;
|
||||
private final UserService userService;
|
||||
|
||||
/// 填充兑换单的客户资料与操作人
|
||||
///
|
||||
/// @param exchangeList 兑换单列表
|
||||
public void fill(List<GaoRecycleExchange> exchangeList) {
|
||||
if (exchangeList == null || exchangeList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> customerIdList = distinct(exchangeList.stream().map(GaoRecycleExchange::getCustomerId).toList());
|
||||
Map<String, GaoCustomer> customerMap = customerIdList.isEmpty() ? Map.of() : customerService.mapByIdList(customerIdList);
|
||||
Map<String, List<Attachment>> customerPhotoMap = customerIdList.isEmpty()
|
||||
? Map.of()
|
||||
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList, GaoCustomer.AttachType.PHOTO.name());
|
||||
Map<String, User> userMap = userMap(exchangeList.stream().map(GaoRecycleExchange::getOperatorUserId).toList());
|
||||
List<String> itemIdList = distinct(exchangeList.stream().map(GaoRecycleExchange::getRecycleItemId).toList());
|
||||
Map<String, List<Attachment>> itemPhotos = itemIdList.isEmpty() ? Map.of()
|
||||
: attachmentService.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_ITEM, itemIdList);
|
||||
for (GaoRecycleExchange exchange : exchangeList) {
|
||||
exchange.setRecycleItemAttachments(exchange.getRecycleItemId() == null ? List.of() : itemPhotos.getOrDefault(exchange.getRecycleItemId(), List.of()));
|
||||
GaoCustomer customer = exchange.getCustomerId() == null ? null : customerMap.get(exchange.getCustomerId());
|
||||
if (customer != null) {
|
||||
customer.setAttachmentList(customerPhotoMap.getOrDefault(customer.getId(), List.of()));
|
||||
}
|
||||
exchange.setCustomer(customer);
|
||||
exchange.setOperator(exchange.getOperatorUserId() == null ? null : userMap.get(exchange.getOperatorUserId()));
|
||||
}
|
||||
}
|
||||
|
||||
/// 填充单条兑换单,写操作返回体用
|
||||
///
|
||||
/// @param exchange 兑换单
|
||||
/// @return 原对象
|
||||
public GaoRecycleExchange fill(GaoRecycleExchange exchange) {
|
||||
fill(List.of(exchange));
|
||||
return exchange;
|
||||
}
|
||||
|
||||
/// 填充操作记录的操作人
|
||||
///
|
||||
/// @param actionList 操作记录列表
|
||||
public void fillActions(List<GaoRecycleExchangeAction> actionList) {
|
||||
if (actionList == null || actionList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, User> userMap = userMap(actionList.stream().map(GaoRecycleExchangeAction::getOperatorUserId).toList());
|
||||
for (GaoRecycleExchangeAction action : actionList) {
|
||||
action.setOperator(action.getOperatorUserId() == null ? null : userMap.get(action.getOperatorUserId()));
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, User> userMap(Collection<String> sourceIdList) {
|
||||
List<String> userIdList = distinct(sourceIdList);
|
||||
return userIdList.isEmpty() ? Map.of() : userService.mapByIdList(userIdList);
|
||||
}
|
||||
|
||||
private List<String> distinct(Collection<String> sourceIdList) {
|
||||
return sourceIdList.stream()
|
||||
.filter(value -> value != null && !value.isBlank())
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.imyeyu.api.bean.ModuleCode;
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProduct;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoProductStockRecord;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoPackageOrderCreateData;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderCancelRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeItemRequest;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductSkuUnitMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoProductStockRecordMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleConfigMapper;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleExchangeWriteMapper;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeActionRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoStockChangeItem;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentItemRequest;
|
||||
import com.imyeyu.api.modules.user.service.PermissionChecker;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.api.modules.system.audit.AuditOperation;
|
||||
import com.imyeyu.api.modules.system.audit.OperationAudit;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
/// 回收兑换交易
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleExchangeWriteService {
|
||||
private final GaoRecycleExchangeWriteMapper mapper;
|
||||
private final GaoRecycleConfigMapper configMapper;
|
||||
private final GaoProductSkuMapper skuMapper;
|
||||
private final GaoProductMapper productMapper;
|
||||
private final GaoProductSkuUnitMapper unitMapper;
|
||||
private final GaoProductSkuService skuService;
|
||||
private final GaoCustomerService customerService;
|
||||
private final GaoStoreScopeService scope;
|
||||
private final GaoProductStockService stockService;
|
||||
private final GaoProductStockRecordMapper stockRecordMapper;
|
||||
private final AttachmentService attachmentService;
|
||||
private final UserLoginService login;
|
||||
private final PermissionChecker permissions;
|
||||
private final ObjectMapper jackson;
|
||||
private final ObjectProvider<GaoOrderFulfillmentService> fulfillmentServiceProvider;
|
||||
private final GaoSalesOrderService salesOrderService;
|
||||
private final GaoRecyclePaymentService recyclePaymentService;
|
||||
private final GaoRecyclePhysicalService physicalService;
|
||||
|
||||
/// 创建回收兑换权益
|
||||
///
|
||||
/// @param request 创建请求
|
||||
/// @return 兑换单
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
@OperationAudit(AuditOperation.GAO_RECYCLE_EXCHANGE_CREATE)
|
||||
public GaoRecycleExchange create(GaoRecycleExchangeCreateRequest request) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
return createItems(request);
|
||||
}
|
||||
|
||||
private GaoRecycleExchange createItems(GaoRecycleExchangeCreateRequest request) {
|
||||
String store = scope.resolveStoreId(request.getStoreId());
|
||||
TimiException.required(store, "门店不能为空");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.required(request.getCustomerId(), "客户不能为空");
|
||||
String fp = fingerprint(request.getCustomerId(), request.getRuleId(), request.getRecycleItemId(), request.getMultiple(), number(request.getRecycleQuantity()), request.getItemList(), request.getOccurredAt(), request.getRemark(), attachments(request.getAttachmentList()), Boolean.TRUE.equals(request.getVerifyPayment()));
|
||||
BigDecimal paymentQuantity = request.getPaymentQuantity();
|
||||
boolean fulfillAll = Boolean.TRUE.equals(request.getFulfillAll());
|
||||
if (paymentQuantity != null || fulfillAll) {
|
||||
fp = fingerprint(fp, number(paymentQuantity == null ? BigDecimal.ZERO : paymentQuantity), fulfillAll, attachments(request.getFulfillmentAttachmentList()));
|
||||
}
|
||||
if (request.getPaymentAttachmentList() != null && !request.getPaymentAttachmentList().isEmpty()) {
|
||||
fp = fingerprint(fp, attachments(request.getPaymentAttachmentList()));
|
||||
}
|
||||
TimiException.required(mapper.lockStore(store), "门店不存在");
|
||||
GaoRecycleExchange previous = mapper.byRequest(store, request.getRequestNo());
|
||||
if (previous != null) {
|
||||
TimiException.requiredTrue(fp.equals(previous.getRequestFingerprint()), "请求号对应的内容不一致");
|
||||
return previous;
|
||||
}
|
||||
GaoCustomer customer = customerService.get(request.getCustomerId());
|
||||
TimiException.required(customer, "客户不存在");
|
||||
TimiException.requiredTrue(store.equals(customer.getStoreId()), "客户不属于当前门店");
|
||||
boolean free = request.getRuleId() == null || request.getRuleId().isBlank();
|
||||
boolean canAdjust = permissions.hasAny(ModuleCode.GAO, GaoPermissionCode.SALES_ORDER_PRICE_OVERRIDE.getValue());
|
||||
TimiException.requiredTrue(!free || canAdjust, "缺少自由创建兑换单权限");
|
||||
GaoRecycleExchangeRule rule = free ? null : configMapper.rule(store, request.getRuleId());
|
||||
TimiException.requiredTrue(free || rule != null && rule.getStatus() == GaoRecycleExchangeRule.Status.ACTIVE, "兑换模板不存在或已停用");
|
||||
int multiple = free ? 1 : request.getMultiple() == null ? 1 : request.getMultiple();
|
||||
TimiException.requiredTrue(0 < multiple, "兑换份数必须大于零");
|
||||
String itemId = request.getRecycleItemId() == null ? free ? null : rule.getRecycleItemId() : request.getRecycleItemId();
|
||||
TimiException.required(itemId, "回收物不能为空");
|
||||
GaoRecycleItem item = configMapper.item(store, itemId);
|
||||
TimiException.requiredTrue(item != null && item.getStatus() == GaoRecycleItem.Status.ACTIVE, "回收物不存在或已停用");
|
||||
BigDecimal preset = free ? null : quantity(rule.getRecycleQuantity().multiply(BigDecimal.valueOf(multiple)));
|
||||
BigDecimal actual = quantity(request.getRecycleQuantity() == null ? preset : request.getRecycleQuantity());
|
||||
if (!free && (!itemId.equals(rule.getRecycleItemId()) || actual.compareTo(preset) != 0)) {
|
||||
TimiException.requiredTrue(canAdjust, "缺少兑换数量调整权限");
|
||||
}
|
||||
List<GaoRecycleExchangeRuleItem> defaults = free ? List.of() : configMapper.ruleItems(rule.getId());
|
||||
TimiException.requiredTrue(free || !defaults.isEmpty(), "兑换模板没有明细");
|
||||
List<GaoRecycleExchangeItemRequest> inputs = request.getItemList();
|
||||
if (inputs == null || inputs.isEmpty()) {
|
||||
inputs = new ArrayList<>();
|
||||
for (GaoRecycleExchangeRuleItem source : defaults) {
|
||||
GaoRecycleExchangeItemRequest input = new GaoRecycleExchangeItemRequest();
|
||||
input.setSkuId(source.getSkuId());
|
||||
input.setSkuUnitId(source.getSkuUnitId());
|
||||
input.setQuantity(quantity(source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple))));
|
||||
inputs.add(input);
|
||||
}
|
||||
}
|
||||
TimiException.requiredTrue(!inputs.isEmpty(), "兑换明细不能为空");
|
||||
Map<String, BigDecimal> expected = new HashMap<>();
|
||||
Map<String, BigDecimal> maxUnitBySku = new HashMap<>();
|
||||
for (GaoRecycleExchangeRuleItem source : defaults.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeRuleItem::getSkuId).thenComparing(GaoRecycleExchangeRuleItem::getSkuUnitId)).toList()) {
|
||||
GaoProductSkuUnit unit = unitMapper.select(source.getSkuUnitId());
|
||||
TimiException.requiredTrue(unit != null && source.getSkuId().equals(unit.getSkuId()), "模板单位无效");
|
||||
expected.merge(source.getSkuId(), source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple)).multiply(unit.getBaseQuantityPerUnit()), BigDecimal::add);
|
||||
maxUnitBySku.merge(source.getSkuId(), unit.getBaseQuantityPerUnit(), BigDecimal::max);
|
||||
}
|
||||
Map<String, BigDecimal> actualBySku = new HashMap<>();
|
||||
Set<String> unique = new HashSet<>();
|
||||
List<GaoSalesOrderItem> entries = new ArrayList<>();
|
||||
long now = Time.now();
|
||||
for (GaoRecycleExchangeItemRequest input : inputs) {
|
||||
TimiException.required(input, "兑换明细不能为空");
|
||||
TimiException.required(input.getSkuId(), "SKU 不能为空");
|
||||
TimiException.required(input.getSkuUnitId(), "单位不能为空");
|
||||
}
|
||||
for (GaoRecycleExchangeItemRequest input : inputs.stream().sorted(java.util.Comparator.comparing(GaoRecycleExchangeItemRequest::getSkuId).thenComparing(GaoRecycleExchangeItemRequest::getSkuUnitId)).toList()) {
|
||||
TimiException.required(input, "兑换明细不能为空");
|
||||
TimiException.required(input.getSkuId(), "SKU 不能为空");
|
||||
TimiException.required(input.getSkuUnitId(), "单位不能为空");
|
||||
TimiException.requiredTrue(unique.add(input.getSkuId() + "|" + input.getSkuUnitId()), "同一 SKU 和单位不能重复");
|
||||
var selection = skuService.getSellableSkuUnit(store, input.getSkuId(), input.getSkuUnitId());
|
||||
GaoProduct product = selection.getProduct();
|
||||
GaoProductSku sku = selection.getSku();
|
||||
GaoProductSkuUnit unit = selection.getUnit();
|
||||
if (!free && !canAdjust) {
|
||||
BigDecimal maximum = maxUnitBySku.get(sku.getId());
|
||||
TimiException.requiredTrue(maximum != null && 0 <= maximum.compareTo(unit.getBaseQuantityPerUnit()), "兑换权益单位不能高于模板单位");
|
||||
}
|
||||
BigDecimal value = quantity(input.getQuantity());
|
||||
TimiException.requiredTrue(Boolean.TRUE.equals(sku.getAllowDecimalQuantity()) || !(0 < value.stripTrailingZeros().scale()), "兑换数量不允许小数");
|
||||
BigDecimal base = quantity(value.multiply(unit.getBaseQuantityPerUnit()));
|
||||
actualBySku.merge(sku.getId(), base, BigDecimal::add);
|
||||
GaoSalesOrderItem entry = new GaoSalesOrderItem();
|
||||
entry.setSkuId(sku.getId());
|
||||
entry.setSkuUnitId(unit.getId());
|
||||
entry.setProductIdSnapshot(product.getId());
|
||||
entry.setProductNameSnapshot(product.getName());
|
||||
entry.setSkuCodeSnapshot(sku.getCode());
|
||||
entry.setSkuNameSnapshot(sku.getName());
|
||||
entry.setSpecSummarySnapshot(sku.getSpecSummary());
|
||||
entry.setSkuSpecSnapshot(skuService.getSkuSpecSnapshot(sku));
|
||||
entry.setUnitSnapshot(unit.getName());
|
||||
entry.setBaseQuantityPerUnitSnapshot(unit.getBaseQuantityPerUnit());
|
||||
entry.setQuantity(value);
|
||||
entry.setBaseQuantity(base);
|
||||
// 订单创建要求履约数量非空,兑换单场景一律从零开始
|
||||
entry.setReservedBaseQuantity(BigDecimal.ZERO);
|
||||
entry.setFulfilledBaseQuantity(BigDecimal.ZERO);
|
||||
entry.setAllowDecimalQuantity(sku.getAllowDecimalQuantity());
|
||||
entry.setItemType(GaoSalesOrderItem.ItemType.RECYCLE_ENTITLEMENT);
|
||||
entry.setSort(entries.size());
|
||||
entries.add(entry);
|
||||
}
|
||||
if (!free && !canAdjust) {
|
||||
TimiException.requiredTrue(defaults.size() == inputs.size(), "兑换明细必须与模板一致");
|
||||
for (GaoRecycleExchangeRuleItem source : defaults) {
|
||||
BigDecimal required = source.getExchangeQuantity().multiply(BigDecimal.valueOf(multiple));
|
||||
TimiException.requiredTrue(inputs.stream().anyMatch(input -> source.getSkuId().equals(input.getSkuId()) && source.getSkuUnitId().equals(input.getSkuUnitId()) && input.getQuantity() != null && required.compareTo(input.getQuantity()) == 0), "兑换明细必须与模板一致");
|
||||
}
|
||||
TimiException.requiredTrue(expected.size() == actualBySku.size(), "兑换商品与模板不一致");
|
||||
for (var entry : expected.entrySet()) {
|
||||
TimiException.requiredTrue(actualBySku.containsKey(entry.getKey()) && entry.getValue().compareTo(actualBySku.get(entry.getKey())) == 0, "兑换数量与模板不一致");
|
||||
}
|
||||
}
|
||||
GaoRecycleExchange result = new GaoRecycleExchange();
|
||||
result.setId(UUID.randomUUID().toString());
|
||||
result.setStoreId(store);
|
||||
result.setCustomerId(customer.getId());
|
||||
result.setRequestNo(request.getRequestNo());
|
||||
result.setRequestFingerprint(fp);
|
||||
result.setRuleId(free ? null : rule.getId());
|
||||
if (!free) {
|
||||
rule.setItemList(defaults);
|
||||
result.setRuleSnapshot(jackson.valueToTree(rule));
|
||||
}
|
||||
result.setRecycleItemId(item.getId());
|
||||
result.setRecycleNameSnapshot(item.getName());
|
||||
result.setRecycleUnitSnapshot(item.getUnitName());
|
||||
result.setRuleRecycleQuantity(free ? null : rule.getRecycleQuantity());
|
||||
result.setMultiple(free ? null : multiple);
|
||||
result.setDefaultRecycleQuantity(preset);
|
||||
result.setRecycleQuantity(actual);
|
||||
result.setStatus(GaoRecycleExchange.Status.PENDING);
|
||||
result.setOperatorUserId(login.getRequireLoginUserId());
|
||||
result.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
result.setRemark(request.getRemark());
|
||||
result.setCreatedAt(now);
|
||||
GaoPackageOrderCreateData orderData = new GaoPackageOrderCreateData();
|
||||
orderData.setStoreId(store);
|
||||
orderData.setCustomerId(customer.getId());
|
||||
orderData.setRequestNo("recycle:" + result.getId());
|
||||
orderData.setPurchasedAt(result.getOccurredAt());
|
||||
orderData.setOperatorUserId(result.getOperatorUserId());
|
||||
orderData.setRemark(result.getRemark());
|
||||
orderData.setItemList(entries);
|
||||
result.setSalesOrderId(salesOrderService.createRecycleOrder(orderData, item.getId(), actual).getId());
|
||||
mapper.insert(result);
|
||||
attachmentService.updateByBizId(Attachment.BizType.GAO_SALES_ORDER, result.getSalesOrderId(), request.getAttachmentList());
|
||||
BigDecimal paid = paymentQuantity == null ? (Boolean.TRUE.equals(request.getVerifyPayment()) ? actual : BigDecimal.ZERO) : paymentQuantity;
|
||||
TimiException.requiredTrue(0 <= paid.signum() && !(3 < paid.stripTrailingZeros().scale()) && 0 <= actual.compareTo(paid), "已回收数量无效或超过应回收数量");
|
||||
TimiException.requiredTrue(!Boolean.TRUE.equals(request.getVerifyPayment()) || paymentQuantity == null || actual.compareTo(paid) == 0, "全部回收数量必须等于应回收数量");
|
||||
TimiException.requiredTrue(!fulfillAll || actual.compareTo(paid) == 0, "全部履约前必须全部回收并核销");
|
||||
if (0 < paid.signum()) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.FUND_RECEIVE_CREATE.getValue(), GaoPermissionCode.FUND_RECEIVE_VERIFY.getValue());
|
||||
GaoRecyclePaymentRequest payment = new GaoRecyclePaymentRequest();
|
||||
payment.setOrderId(result.getSalesOrderId());
|
||||
payment.setRequestNo("recycle:create:" + result.getId());
|
||||
payment.setQuantity(paid);
|
||||
payment.setOccurredAt(request.getOccurredAt());
|
||||
payment.setAttachmentList(request.getPaymentAttachmentList());
|
||||
recyclePaymentService.createAndVerify(payment);
|
||||
}
|
||||
if (fulfillAll) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue(), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY.getValue());
|
||||
GaoOrderFulfillmentCreateRequest fulfillment = new GaoOrderFulfillmentCreateRequest();
|
||||
fulfillment.setSalesOrderId(result.getSalesOrderId());
|
||||
fulfillment.setRequestNo("recycle:fulfill:" + result.getId());
|
||||
fulfillment.setDeliveredAt(request.getOccurredAt());
|
||||
fulfillment.setAttachmentList(request.getFulfillmentAttachmentList());
|
||||
List<GaoOrderFulfillmentItemRequest> fulfillmentItems = new ArrayList<>();
|
||||
for (GaoSalesOrderItem entry : salesOrderService.listItemByOrderId(result.getSalesOrderId())) {
|
||||
GaoOrderFulfillmentItemRequest fulfillmentItem = new GaoOrderFulfillmentItemRequest();
|
||||
fulfillmentItem.setSourceOrderItemId(entry.getId());
|
||||
fulfillmentItem.setSkuUnitId(entry.getSkuUnitId());
|
||||
fulfillmentItem.setQuantity(entry.getQuantity());
|
||||
fulfillmentItems.add(fulfillmentItem);
|
||||
}
|
||||
fulfillment.setItemList(fulfillmentItems);
|
||||
fulfillmentServiceProvider.getObject().createAndVerify(fulfillment);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecycleExchange cancelFromOrder(GaoRecycleExchangeActionRequest request, GaoSalesOrderCancelRequest orderRequest) {
|
||||
return cancelInternal(request, orderRequest);
|
||||
}
|
||||
|
||||
private GaoRecycleExchange cancelInternal(GaoRecycleExchangeActionRequest request, GaoSalesOrderCancelRequest orderRequest) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
TimiException.required(request.getExchangeId(), "兑换单不能为空");
|
||||
TimiException.required(request.getRequestNo(), "请求号不能为空");
|
||||
TimiException.requiredTrue(!request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
GaoRecycleExchange snapshot = mapper.byId(request.getExchangeId());
|
||||
TimiException.required(snapshot, "兑换单不存在");
|
||||
scope.checkStoreId(snapshot.getStoreId());
|
||||
String store = snapshot.getStoreId();
|
||||
String fingerprint = fingerprint(request.getExchangeId(), GaoRecycleExchangeAction.ActionType.CANCEL, request.getOccurredAt(), request.getReason(), request.getRemark(), number(request.getRetainedRecycleQuantity()), request.getFulfillmentRevokeList(), request.getPaymentRevokeList(), attachments(request.getAttachmentList()));
|
||||
TimiException.required(mapper.lockStore(store), "门店不存在");
|
||||
GaoRecycleExchangeAction existing = mapper.actionByRequest(store, request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应的操作内容不一致");
|
||||
return mapper.lockExchange(store, existing.getExchangeId());
|
||||
}
|
||||
TimiException.required(snapshot.getSalesOrderId(), "兑换订单不存在");
|
||||
salesOrderService.getForUpdate(snapshot.getSalesOrderId());
|
||||
GaoRecycleExchange exchange = mapper.lockExchange(store, request.getExchangeId());
|
||||
TimiException.required(exchange, "兑换单不存在");
|
||||
// 已完成只代表权益领完,回收物归属仍需能修正,所以也允许撤销
|
||||
TimiException.requiredTrue(exchange.getStatus() == GaoRecycleExchange.Status.PENDING || exchange.getStatus() == GaoRecycleExchange.Status.COMPLETED, "兑换单状态不允许撤销");
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "撤销原因不能为空");
|
||||
TimiException.required(exchange.getSalesOrderId(), "兑换订单不存在");
|
||||
var lockedOrder = salesOrderService.getForUpdate(exchange.getSalesOrderId());
|
||||
if (request.getPaymentRevokeList() != null && !request.getPaymentRevokeList().isEmpty()) {
|
||||
permissions.checkAll(ModuleCode.GAO, GaoPermissionCode.FUND_REVOKE.getValue());
|
||||
Set<String> allowed = new HashSet<>();
|
||||
for (var payment : recyclePaymentService.list(exchange.getSalesOrderId())) {
|
||||
allowed.add(payment.getId());
|
||||
}
|
||||
Set<String> selected = new HashSet<>();
|
||||
for (GaoRecyclePaymentRequest payment : request.getPaymentRevokeList()) {
|
||||
TimiException.required(payment, "支付冲正请求不能为空");
|
||||
TimiException.requiredTrue(allowed.contains(payment.getPaymentId()) && selected.add(payment.getPaymentId()), "支付记录不属于兑换订单或重复选择");
|
||||
if (payment.getReason() == null || payment.getReason().isBlank()) payment.setReason(request.getReason());
|
||||
recyclePaymentService.revoke(payment);
|
||||
}
|
||||
}
|
||||
BigDecimal received = physicalService.balance(exchange.getSalesOrderId());
|
||||
BigDecimal retained = request.getRetainedRecycleQuantity() == null ? received : request.getRetainedRecycleQuantity();
|
||||
TimiException.requiredTrue(0 <= retained.signum() && 0 <= received.compareTo(retained) && !(3 < retained.stripTrailingZeros().scale()), "保留回收物数量超过实际收到数量");
|
||||
GaoSalesOrderCancelRequest cancelOrder = orderRequest == null ? new GaoSalesOrderCancelRequest() : orderRequest;
|
||||
cancelOrder.setSalesOrderId(exchange.getSalesOrderId());
|
||||
cancelOrder.setRequestNo(request.getRequestNo());
|
||||
cancelOrder.setReason(request.getReason());
|
||||
if (orderRequest == null) cancelOrder.setAttachmentList(request.getAttachmentList());
|
||||
if (orderRequest == null) cancelOrder.setFulfillmentRevokeList(request.getFulfillmentRevokeList());
|
||||
salesOrderService.cancel(cancelOrder);
|
||||
long now = Time.now();
|
||||
GaoRecycleExchangeAction action = new GaoRecycleExchangeAction();
|
||||
action.setId(UUID.randomUUID().toString());
|
||||
BigDecimal remainingReturn = received.subtract(retained);
|
||||
for (var payment : recyclePaymentService.list(exchange.getSalesOrderId())) {
|
||||
if (payment.getSourcePaymentId() != null || remainingReturn.signum() == 0) continue;
|
||||
BigDecimal available = physicalService.paymentBalance(exchange.getSalesOrderId(), payment.getId());
|
||||
BigDecimal returned = remainingReturn.min(available);
|
||||
if (0 < returned.signum()) {
|
||||
physicalService.record(lockedOrder, "EXCHANGE_CANCEL", action.getId(), payment.getId(), false, returned, request.getOccurredAt());
|
||||
remainingReturn = remainingReturn.subtract(returned);
|
||||
}
|
||||
}
|
||||
TimiException.requiredTrue(remainingReturn.signum() == 0, "回收实物退回数量不一致");
|
||||
action.setStoreId(store);
|
||||
action.setExchangeId(exchange.getId());
|
||||
action.setRequestNo(request.getRequestNo());
|
||||
action.setRequestFingerprint(fingerprint);
|
||||
action.setActionType(GaoRecycleExchangeAction.ActionType.CANCEL);
|
||||
action.setOperatorUserId(login.getRequireLoginUserId());
|
||||
action.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
action.setCreatedAt(now);
|
||||
action.setReason(request.getReason());
|
||||
action.setRemark(request.getRemark());
|
||||
action.setRetainedRecycleQuantity(retained);
|
||||
mapper.insertAction(action);
|
||||
if (orderRequest == null) attachmentService.updateByBizId(Attachment.BizType.GAO_RECYCLE_EXCHANGE_REVOKE, action.getId(), request.getAttachmentList());
|
||||
TimiException.requiredTrue(mapper.cancel(exchange.getId(), now) == 1, "兑换单状态已变更");
|
||||
exchange.setStatus(GaoRecycleExchange.Status.CANCELLED);
|
||||
exchange.setUpdatedAt(now);
|
||||
return exchange;
|
||||
}
|
||||
|
||||
/// 校验数量范围和精度
|
||||
///
|
||||
/// @param value 数量
|
||||
/// @return 已校验数量
|
||||
private BigDecimal quantity(BigDecimal value) {
|
||||
TimiException.required(value, "数量不能为空");
|
||||
TimiException.requiredTrue(0 < value.signum() && !(3 < value.stripTrailingZeros().scale()) && !(15 < value.precision() - value.scale()), "数量超出精度或范围");
|
||||
return value;
|
||||
}
|
||||
|
||||
/// 规范化数量以计算请求摘要
|
||||
///
|
||||
/// @param value 数量
|
||||
/// @return 规范化数量,可为空
|
||||
private String number(BigDecimal value) {
|
||||
return value == null ? null : value.stripTrailingZeros().toPlainString();
|
||||
}
|
||||
|
||||
/// 提取并排序附件标识,确保附件顺序不影响幂等判断
|
||||
///
|
||||
/// @param list 附件列表
|
||||
/// @return 附件标识列表
|
||||
private List<String> attachments(List<Attachment> list) {
|
||||
if (list == null) {
|
||||
return List.of();
|
||||
}
|
||||
return list.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(a -> String.valueOf(a.getId()) + ":" + a.getTempFileId() + ":" + a.getAttachType())
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// 计算原始请求摘要
|
||||
///
|
||||
/// @param values 请求内容
|
||||
/// @return 摘要
|
||||
private String fingerprint(Object... values) {
|
||||
try {
|
||||
byte[] bytes = jackson.writeValueAsString(values).getBytes(StandardCharsets.UTF_8);
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("计算请求摘要失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecyclePayment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecyclePaymentMapper;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecyclePaymentRequest;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoOrderTransactionView;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.common.service.AttachmentService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.imyeyu.api.modules.user.service.UserLoginService;
|
||||
import com.imyeyu.api.modules.user.service.UserService;
|
||||
import com.imyeyu.api.modules.user.entity.User;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Objects;
|
||||
import java.util.HexFormat;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/// 回收物支付服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecyclePaymentService {
|
||||
private final GaoRecyclePaymentMapper mapper;
|
||||
private final GaoRecycleAccountService accounts;
|
||||
private final GaoSalesOrderService orders;
|
||||
private final GaoStoreScopeService scope;
|
||||
private final UserLoginService login;
|
||||
private final AttachmentService attachments;
|
||||
private final ObjectMapper jackson;
|
||||
private final GaoFundRecordService funds;
|
||||
private final GaoRecyclePhysicalService physical;
|
||||
private final GaoCustomerService customers;
|
||||
private final UserService users;
|
||||
|
||||
/// 判断订单回收物支付是否已结清
|
||||
public boolean isSettled(GaoSalesOrder order) {
|
||||
return order.getRecycleRequiredQuantity() != null && 0 <= mapper.paid(order.getId()).compareTo(order.getRecycleRequiredQuantity());
|
||||
}
|
||||
|
||||
/// 查询订单的回收物支付记录
|
||||
public List<GaoRecyclePayment> list(String orderId) {
|
||||
GaoSalesOrder order = orders.get(orderId);
|
||||
TimiException.required(order, "订单不存在");
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
List<GaoRecyclePayment> payments = mapper.list(orderId);
|
||||
fillAttachments(payments);
|
||||
fillCustomers(payments);
|
||||
fillUsers(payments);
|
||||
return payments;
|
||||
}
|
||||
|
||||
/// 按门店和筛选条件分页查询回收流水。
|
||||
public List<GaoRecyclePayment> search(String storeId, String customerId, String orderId, String status, Long beginAt, Long endAt, int offset, int limit) {
|
||||
TimiException.requiredTrue(0 <= offset && 0 < limit && limit <= 101, "分页参数无效");
|
||||
String resolvedStoreId = scope.resolveStoreId(storeId);
|
||||
List<GaoRecyclePayment> payments = mapper.search(resolvedStoreId, customerId, orderId, status, beginAt, endAt, offset, limit);
|
||||
fillAttachments(payments);
|
||||
fillCustomers(payments);
|
||||
fillUsers(payments);
|
||||
return payments;
|
||||
}
|
||||
|
||||
/// 批量回填人员的展示信息。
|
||||
private void fillUsers(List<GaoRecyclePayment> payments) {
|
||||
var ids = payments.stream().flatMap(payment -> java.util.stream.Stream.of(payment.getOperatorUserId(), payment.getVerifierUserId()))
|
||||
.filter(id -> id != null && !id.isBlank()).distinct().toList();
|
||||
if (ids.isEmpty()) return;
|
||||
var userMap = users.mapByIdList(ids);
|
||||
for (GaoRecyclePayment payment : payments) {
|
||||
payment.setOperator(payment.getOperatorUserId() == null ? null : displayUser(userMap.get(payment.getOperatorUserId())));
|
||||
payment.setVerifier(payment.getVerifierUserId() == null ? null : displayUser(userMap.get(payment.getVerifierUserId())));
|
||||
}
|
||||
}
|
||||
|
||||
private User displayUser(User source) {
|
||||
if (source == null) return null;
|
||||
User user = new User();
|
||||
user.setId(source.getId());
|
||||
user.setName(source.getName());
|
||||
user.setNick(source.getNick());
|
||||
return user;
|
||||
}
|
||||
|
||||
private void fillCustomers(List<GaoRecyclePayment> payments) {
|
||||
List<String> ids = payments.stream().map(GaoRecyclePayment::getCustomerId).filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) return;
|
||||
var customerMap = customers.mapByIdList(ids);
|
||||
var photoMap = attachments.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, ids);
|
||||
for (GaoRecyclePayment payment : payments) {
|
||||
var customer = customerMap.get(payment.getCustomerId());
|
||||
if (customer == null) continue;
|
||||
customer.setAttachmentList(photoMap.getOrDefault(customer.getId(), List.of()));
|
||||
payment.setCustomer(customer);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按授权范围聚合订单交易
|
||||
public List<GaoOrderTransactionView> transactions(String orderId, boolean fundAllowed, boolean recycleAllowed) {
|
||||
GaoSalesOrder order = orders.get(orderId);
|
||||
TimiException.required(order, "订单不存在");
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
List<GaoOrderTransactionView> result = new ArrayList<>();
|
||||
List<com.imyeyu.api.modules.gao.entity.GaoFundRecord> fundRecords = fundAllowed ? funds.listByBizId(orderId) : List.of();
|
||||
var fundAttachments = fundRecords.isEmpty() ? java.util.Map.<String, List<Attachment>>of()
|
||||
: attachments.mapByBizIdList(Attachment.BizType.GAO_FUND_RECORD, fundRecords.stream().map(com.imyeyu.api.modules.gao.entity.GaoFundRecord::getId).toList());
|
||||
for (var fund : fundRecords) {
|
||||
fund.setAttachmentList(fundAttachments.getOrDefault(fund.getId(), List.of()));
|
||||
GaoOrderTransactionView item = new GaoOrderTransactionView();
|
||||
item.setType("FUND");
|
||||
item.setOccurredAt(fund.getOccurredAt());
|
||||
item.setFundRecord(fund);
|
||||
result.add(item);
|
||||
}
|
||||
if (recycleAllowed) for (var payment : list(orderId)) {
|
||||
GaoOrderTransactionView item = new GaoOrderTransactionView();
|
||||
item.setType("RECYCLE_PAYMENT");
|
||||
item.setOccurredAt(payment.getOccurredAt());
|
||||
item.setRecyclePayment(payment);
|
||||
result.add(item);
|
||||
}
|
||||
result.sort(Comparator.comparing(GaoOrderTransactionView::getOccurredAt, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 登记支付并预占额度
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment create(GaoRecyclePaymentRequest request) {
|
||||
return createInternal(request, null);
|
||||
}
|
||||
|
||||
private GaoRecyclePayment createInternal(GaoRecyclePaymentRequest request, String exchangeId) {
|
||||
TimiException.required(request, "支付请求不能为空");
|
||||
TimiException.required(request.getOrderId(), "订单不能为空");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.requiredTrue(request.getQuantity() != null && 0 < request.getQuantity().signum() && !(3 < request.getQuantity().stripTrailingZeros().scale()) && !(15 < request.getQuantity().precision() - request.getQuantity().scale()), "支付数量无效");
|
||||
GaoSalesOrder order = orders.getForUpdate(request.getOrderId());
|
||||
TimiException.required(order, "订单不存在");
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
String fingerprint = fingerprint("CREATE", request.getOrderId(), request.getQuantity().stripTrailingZeros().toPlainString(), request.getOccurredAt(), exchangeId, attachmentKeys(request.getAttachmentList()));
|
||||
GaoRecyclePayment existing = mapper.byRequest(order.getStoreId(), request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应支付内容不一致");
|
||||
return existing;
|
||||
}
|
||||
List<Attachment> sourceAttachments = exchangeId == null ? request.getAttachmentList() : attachments.listByBizId(Attachment.BizType.GAO_SALES_ORDER, order.getId());
|
||||
TimiException.requiredTrue(hasPhoto(sourceAttachments), "支付必须上传照片");
|
||||
TimiException.requiredTrue(order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE && order.getStatus() != GaoSalesOrder.Status.CANCELLED && order.getRecycleItemId() != null && order.getRecycleRequiredQuantity() != null, "订单不支持回收物支付");
|
||||
TimiException.requiredTrue(0 <= order.getRecycleRequiredQuantity().compareTo(mapper.occupied(order.getId()).add(request.getQuantity())), "支付数量超过未结算数量");
|
||||
long now = Time.now();
|
||||
GaoRecyclePayment payment = new GaoRecyclePayment();
|
||||
payment.setId(UUID.randomUUID().toString());
|
||||
payment.setStoreId(order.getStoreId());
|
||||
payment.setCustomerId(order.getCustomerId());
|
||||
payment.setOrderId(order.getId());
|
||||
payment.setRecycleItemId(order.getRecycleItemId());
|
||||
payment.setRequestNo(request.getRequestNo());
|
||||
payment.setRequestFingerprint(fingerprint);
|
||||
payment.setQuantity(request.getQuantity());
|
||||
payment.setStatus(GaoRecyclePayment.Status.PENDING);
|
||||
payment.setOperatorUserId(login.getRequireLoginUserId());
|
||||
payment.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
payment.setCreatedAt(now);
|
||||
mapper.insert(payment);
|
||||
if (exchangeId == null) {
|
||||
attachments.updateByBizId(Attachment.BizType.GAO_RECYCLE_PAYMENT, payment.getId(), request.getAttachmentList());
|
||||
} else {
|
||||
for (Attachment source : sourceAttachments) {
|
||||
Attachment clone = attachments.clone(source.getId());
|
||||
clone.setBizType(Attachment.BizType.GAO_RECYCLE_PAYMENT);
|
||||
clone.setBizId(payment.getId());
|
||||
attachments.update(clone);
|
||||
}
|
||||
}
|
||||
accounts.change(order.getStoreId(), order.getCustomerId(), order.getRecycleItemId(), BigDecimal.ZERO, payment.getQuantity(), "PAYMENT_RESERVE", payment.getId(), "recycle:reserve:" + payment.getId(), null);
|
||||
return payment;
|
||||
}
|
||||
|
||||
/// 撤销或拒绝待核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment release(GaoRecyclePaymentRequest request, boolean reject) {
|
||||
return releaseInternal(request, reject, !reject);
|
||||
}
|
||||
|
||||
private GaoRecyclePayment releaseInternal(GaoRecyclePaymentRequest request, boolean reject, boolean onlyOperator) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "操作原因不能为空");
|
||||
GaoRecyclePayment snapshot = mapper.byId(request.getPaymentId());
|
||||
TimiException.required(snapshot, "支付记录不存在");
|
||||
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
GaoRecyclePayment payment = mapper.lock(snapshot.getId());
|
||||
TimiException.requiredTrue(payment.getStatus() == GaoRecyclePayment.Status.PENDING, "支付状态不允许撤销");
|
||||
if (onlyOperator) TimiException.requiredTrue(login.getRequireLoginUserId().equals(payment.getOperatorUserId()), "只能撤销自己提交的支付");
|
||||
accounts.change(payment.getStoreId(), payment.getCustomerId(), payment.getRecycleItemId(), BigDecimal.ZERO, payment.getQuantity().negate(), "PAYMENT_RELEASE", payment.getId(), "recycle:release:" + payment.getId(), request.getReason());
|
||||
GaoRecyclePayment.Status target = reject ? GaoRecyclePayment.Status.REJECTED : GaoRecyclePayment.Status.CANCELLED;
|
||||
TimiException.requiredTrue(mapper.status(payment.getId(), GaoRecyclePayment.Status.PENDING, target, login.getRequireLoginUserId(), Time.now(), request.getReason()) == 1, "支付状态已变更");
|
||||
return mapper.byId(payment.getId());
|
||||
}
|
||||
|
||||
/// 冲正已核销回收物支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment revoke(GaoRecyclePaymentRequest request) {
|
||||
TimiException.required(request, "请求不能为空");
|
||||
TimiException.requiredTrue(request.getRequestNo() != null && !request.getRequestNo().isBlank() && !(128 < request.getRequestNo().length()), "请求号无效");
|
||||
TimiException.requiredTrue(request.getReason() != null && !request.getReason().isBlank(), "冲正原因不能为空");
|
||||
TimiException.required(request.getReturnedToCustomer(), "必须确认回收物是否退还");
|
||||
GaoRecyclePayment snapshot = mapper.byId(request.getPaymentId());
|
||||
TimiException.required(snapshot, "支付记录不存在");
|
||||
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
GaoRecyclePayment source = mapper.lock(snapshot.getId());
|
||||
String fingerprint = fingerprint("REVOKE", request.getPaymentId(), request.getOccurredAt(), request.getReason(), request.getReturnedToCustomer(), attachmentKeys(request.getAttachmentList()));
|
||||
GaoRecyclePayment existing = mapper.byRequest(order.getStoreId(), request.getRequestNo());
|
||||
if (existing != null) {
|
||||
TimiException.requiredTrue(fingerprint.equals(existing.getRequestFingerprint()), "请求号对应冲正内容不一致");
|
||||
return existing;
|
||||
}
|
||||
TimiException.requiredTrue(source.getStatus() == GaoRecyclePayment.Status.VERIFIED && source.getSourcePaymentId() == null, "支付状态不允许冲正");
|
||||
TimiException.requiredTrue(hasPhoto(request.getAttachmentList()), "支付冲正必须上传照片");
|
||||
long now = Time.now();
|
||||
GaoRecyclePayment reverse = new GaoRecyclePayment();
|
||||
reverse.setId(UUID.randomUUID().toString());
|
||||
reverse.setStoreId(source.getStoreId());
|
||||
reverse.setCustomerId(source.getCustomerId());
|
||||
reverse.setOrderId(source.getOrderId());
|
||||
reverse.setRecycleItemId(source.getRecycleItemId());
|
||||
reverse.setRequestNo(request.getRequestNo());
|
||||
reverse.setRequestFingerprint(fingerprint);
|
||||
reverse.setQuantity(source.getQuantity());
|
||||
reverse.setStatus(GaoRecyclePayment.Status.VERIFIED);
|
||||
reverse.setSourcePaymentId(source.getId());
|
||||
reverse.setOperatorUserId(login.getRequireLoginUserId());
|
||||
reverse.setVerifierUserId(reverse.getOperatorUserId());
|
||||
reverse.setOccurredAt(request.getOccurredAt() == null ? now : request.getOccurredAt());
|
||||
reverse.setVerifiedAt(now);
|
||||
reverse.setReason(request.getReason());
|
||||
reverse.setReturnedToCustomer(request.getReturnedToCustomer());
|
||||
reverse.setCreatedAt(now);
|
||||
mapper.insert(reverse);
|
||||
accounts.change(source.getStoreId(), source.getCustomerId(), source.getRecycleItemId(), source.getQuantity(), BigDecimal.ZERO, "PAYMENT_REVOKE", reverse.getId(), "recycle:revoke:" + source.getId(), request.getReason());
|
||||
if (Boolean.TRUE.equals(request.getReturnedToCustomer())) {
|
||||
physical.returnPayment(order, source.getId(), reverse.getId(), reverse.getOccurredAt());
|
||||
}
|
||||
attachments.updateByBizId(Attachment.BizType.GAO_RECYCLE_PAYMENT, reverse.getId(), request.getAttachmentList());
|
||||
TimiException.requiredTrue(mapper.status(source.getId(), GaoRecyclePayment.Status.VERIFIED, GaoRecyclePayment.Status.REVOKED, login.getRequireLoginUserId(), now, request.getReason()) == 1, "支付状态已变更");
|
||||
refresh(order);
|
||||
reverse.setSignedQuantity(reverse.getQuantity().negate());
|
||||
return reverse;
|
||||
}
|
||||
|
||||
/// 随订单取消待核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void cancelPendingByOrderId(String orderId, String reason) {
|
||||
for (GaoRecyclePayment payment : mapper.list(orderId)) {
|
||||
if (payment.getStatus() != GaoRecyclePayment.Status.PENDING) continue;
|
||||
GaoRecyclePaymentRequest request = new GaoRecyclePaymentRequest();
|
||||
request.setPaymentId(payment.getId());
|
||||
request.setReason(reason);
|
||||
releaseInternal(request, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 创建并核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment createAndVerify(GaoRecyclePaymentRequest request) {
|
||||
GaoRecyclePayment payment = create(request);
|
||||
if (payment.getStatus() == GaoRecyclePayment.Status.VERIFIED) return payment;
|
||||
return verify(payment.getId());
|
||||
}
|
||||
|
||||
/// 使用兑换单凭证创建并核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment createAndVerifyFromExchange(GaoRecyclePaymentRequest request, String exchangeId) {
|
||||
GaoRecyclePayment payment = createInternal(request, exchangeId);
|
||||
if (payment.getStatus() == GaoRecyclePayment.Status.VERIFIED) return payment;
|
||||
return verify(payment.getId());
|
||||
}
|
||||
|
||||
/// 核销支付
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public GaoRecyclePayment verify(String paymentId) {
|
||||
GaoRecyclePayment snapshot = mapper.byId(paymentId);
|
||||
TimiException.required(snapshot, "支付记录不存在");
|
||||
GaoSalesOrder order = orders.getForUpdate(snapshot.getOrderId());
|
||||
scope.checkStoreId(order.getStoreId());
|
||||
GaoRecyclePayment payment = mapper.lock(paymentId);
|
||||
TimiException.requiredTrue(order.getStatus() != GaoSalesOrder.Status.CANCELLED && payment.getStatus() == GaoRecyclePayment.Status.PENDING, "支付状态不允许核销");
|
||||
accounts.change(payment.getStoreId(), payment.getCustomerId(), payment.getRecycleItemId(), payment.getQuantity().negate(), payment.getQuantity().negate(), "PAYMENT_VERIFY", payment.getId(), "recycle:verify:" + payment.getId(), null);
|
||||
physical.record(order, "PAYMENT_VERIFY", payment.getId(), payment.getId(), true, payment.getQuantity(), payment.getOccurredAt());
|
||||
TimiException.requiredTrue(mapper.status(paymentId, GaoRecyclePayment.Status.PENDING, GaoRecyclePayment.Status.VERIFIED, login.getRequireLoginUserId(), Time.now(), null) == 1, "支付状态已变更");
|
||||
refresh(order);
|
||||
return mapper.byId(paymentId);
|
||||
}
|
||||
|
||||
private void refresh(GaoSalesOrder order) {
|
||||
BigDecimal paid = mapper.paid(order.getId());
|
||||
order.setPaymentStatus(0 <= paid.compareTo(order.getRecycleRequiredQuantity()) ? GaoSalesOrder.PaymentStatus.PAID
|
||||
: (0 < paid.signum() ? GaoSalesOrder.PaymentStatus.PARTIALLY_PAID : GaoSalesOrder.PaymentStatus.UNPAID));
|
||||
orders.updatePayment(order);
|
||||
}
|
||||
|
||||
private List<String> attachmentKeys(List<Attachment> list) {
|
||||
if (list == null) return List.of();
|
||||
return list.stream().filter(Objects::nonNull)
|
||||
.map(a -> String.valueOf(a.getId()) + ":" + a.getTempFileId() + ":" + a.getAttachType()).sorted().toList();
|
||||
}
|
||||
|
||||
private boolean hasPhoto(List<Attachment> list) {
|
||||
return list != null && list.stream().anyMatch(item -> item != null && (item.getAttachType() == null || "PHOTO".equalsIgnoreCase(item.getAttachType())));
|
||||
}
|
||||
|
||||
private void fillAttachments(List<GaoRecyclePayment> payments) {
|
||||
if (payments.isEmpty()) return;
|
||||
var map = attachments.mapByBizIdList(Attachment.BizType.GAO_RECYCLE_PAYMENT, payments.stream().map(GaoRecyclePayment::getId).toList());
|
||||
for (GaoRecyclePayment payment : payments) {
|
||||
payment.setAttachmentList(map.getOrDefault(payment.getId(), List.of()));
|
||||
payment.setSignedQuantity(payment.getSourcePaymentId() == null ? payment.getQuantity() : payment.getQuantity().negate());
|
||||
}
|
||||
}
|
||||
|
||||
private String fingerprint(Object... values) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(jackson.writeValueAsString(values).getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("计算支付请求摘要失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecyclePhysicalMapper;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
/// 回收实物流转服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecyclePhysicalService {
|
||||
private final GaoRecyclePhysicalMapper mapper;
|
||||
private final ObjectProvider<GaoSalesOrderService> orders;
|
||||
|
||||
/// 记录门店收到或退回的回收物
|
||||
///
|
||||
/// @param order 兑换订单
|
||||
/// @param sourceType 来源类型
|
||||
/// @param sourceId 来源记录 ID
|
||||
/// @param incoming true 为收到,false 为退回
|
||||
/// @param quantity 实物数量
|
||||
/// @param occurredAt 业务发生时间
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void record(GaoSalesOrder order, String sourceType, String sourceId, String paymentId, boolean incoming, BigDecimal quantity, Long occurredAt) {
|
||||
TimiException.required(order, "订单不能为空");
|
||||
TimiException.requiredTrue(quantity != null && 0 < quantity.signum(), "实物数量必须大于零");
|
||||
orders.getObject().getForUpdate(order.getId());
|
||||
if (!incoming) TimiException.requiredTrue(0 <= mapper.paymentBalance(order.getId(), paymentId).compareTo(quantity), "退回数量超过该笔支付实际保留数量");
|
||||
long now = Time.now();
|
||||
mapper.insert(UUID.randomUUID().toString(), order.getStoreId(), order.getCustomerId(), order.getId(), order.getRecycleItemId(), paymentId, sourceType, sourceId, incoming ? "IN" : "OUT", quantity, occurredAt == null ? now : occurredAt, now);
|
||||
}
|
||||
|
||||
/// 查询某笔支付尚未退回的实物数量
|
||||
public BigDecimal paymentBalance(String orderId, String paymentId) {
|
||||
return mapper.paymentBalance(orderId, paymentId);
|
||||
}
|
||||
|
||||
/// 冲正时将该笔支付尚未退回的实物全部退还
|
||||
@Transactional(TimiServerDBConfig.ROLLBACKER)
|
||||
public void returnPayment(GaoSalesOrder order, String paymentId, String sourceId, Long occurredAt) {
|
||||
orders.getObject().getForUpdate(order.getId());
|
||||
BigDecimal remaining = mapper.paymentBalance(order.getId(), paymentId);
|
||||
if (0 < remaining.signum()) record(order, "PAYMENT_REVOKE", sourceId, paymentId, false, remaining, occurredAt);
|
||||
}
|
||||
|
||||
/// 查询订单当前实物保留数量,调用方须先锁定订单
|
||||
public BigDecimal balance(String orderId) {
|
||||
return mapper.balance(orderId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.imyeyu.api.modules.gao.service;
|
||||
|
||||
import com.imyeyu.api.modules.gao.mapper.GaoRecycleStatMapper;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView;
|
||||
import com.imyeyu.api.modules.gao.vo.GaoRecycleStatView;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换统计服务
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GaoRecycleStatService {
|
||||
|
||||
private final GaoRecycleStatMapper mapper;
|
||||
private final GaoStoreScopeService storeScopeService;
|
||||
|
||||
/// 按业务时间统计回收物
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param startAt 区间起点,包含
|
||||
/// @param endAt 区间终点,不包含
|
||||
/// @return 回收统计
|
||||
public List<GaoRecycleStatView> recycle(String storeId, long startAt, long endAt) {
|
||||
return mapper.selectRecycleStats(resolveStore(storeId, startAt, endAt), startAt, endAt);
|
||||
}
|
||||
|
||||
/// 按业务时间统计兑换
|
||||
///
|
||||
/// @param storeId 门店 ID
|
||||
/// @param startAt 区间起点,包含
|
||||
/// @param endAt 区间终点,不包含
|
||||
/// @return 兑换统计
|
||||
public List<GaoRecycleExchangeStatView> exchange(String storeId, long startAt, long endAt) {
|
||||
return mapper.selectExchangeStats(resolveStore(storeId, startAt, endAt), startAt, endAt);
|
||||
}
|
||||
|
||||
private String resolveStore(String storeId, long startAt, long endAt) {
|
||||
String resolved = storeScopeService.resolveStoreId(storeId);
|
||||
TimiException.required(resolved, "请选择门店");
|
||||
TimiException.requiredTrue(startAt < endAt, "统计时间区间无效");
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,9 @@ public interface GaoSalesOrderService extends BaseService<GaoSalesOrder, String>
|
||||
/// 由套餐购买流程创建套餐订单
|
||||
GaoSalesOrder createPackageOrder(GaoPackageOrderCreateData data);
|
||||
|
||||
/// 创建回收兑换订单
|
||||
GaoSalesOrder 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,
|
||||
|
||||
+1
@@ -270,6 +270,7 @@ public class GaoProductSkuServiceImplement extends AbstractEntityService<GaoProd
|
||||
GaoProductSkuBaseUnitMigrationRequest migrationRequest = request.getBaseUnitMigrationRequest();
|
||||
BigDecimal migrationRatio = null;
|
||||
if (baseUnitChanged) {
|
||||
TimiException.requiredTrue(0 == editMapper.countRecycleReferences(sku.getId()), "SKU 存在回收兑换规则或交易,不能迁移基础单位");
|
||||
migrationRatio = validateBaseUnitMigration(oldBaseUnit, requestedBaseUnit, migrationRequest, sku.getId());
|
||||
} else if (migrationRequest != null) {
|
||||
throw new TimiException(TimiCode.ERROR, "新旧基础单位相同,不需要提交基础单位迁移比例");
|
||||
|
||||
+4
@@ -40,6 +40,7 @@ import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -634,6 +635,9 @@ 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.ORDER_REVOKE) {
|
||||
TimiException.requiredTrue(Objects.equals(item.getSourceRecordId(), record.getSourceRecordId()), "requestNo 对应冲正来源不一致");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+85
-20
@@ -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());
|
||||
// 订单取消立即失去有效消费资格,不等待退款完成
|
||||
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());
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换状态操作请求
|
||||
@Data
|
||||
public class GaoRecycleExchangeActionRequest {
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 兑换单 ID
|
||||
private String exchangeId;
|
||||
|
||||
/// 请求幂等号
|
||||
private String requestNo;
|
||||
|
||||
/// 业务发生时间
|
||||
private Long occurredAt;
|
||||
|
||||
/// 操作原因
|
||||
private String reason;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// 撤销后门店实际保留的回收物数量,未填写时保留全部
|
||||
private BigDecimal retainedRecycleQuantity;
|
||||
|
||||
/// 撤销时按整单冲正的履约列表
|
||||
private List<GaoOrderFulfillmentRevokeRequest> fulfillmentRevokeList;
|
||||
|
||||
/// 取消时选择冲正的回收物支付
|
||||
private List<GaoRecyclePaymentRequest> paymentRevokeList;
|
||||
|
||||
/// 附件列表
|
||||
private List<Attachment> attachmentList;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收兑换创建请求
|
||||
@Data
|
||||
public class GaoRecycleExchangeCreateRequest {
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 客户 ID
|
||||
private String customerId;
|
||||
|
||||
/// 规则 ID
|
||||
private String ruleId;
|
||||
|
||||
/// 回收物 ID,自由创建时使用
|
||||
private String recycleItemId;
|
||||
|
||||
/// 兑换权益明细
|
||||
private List<GaoRecycleExchangeItemRequest> itemList;
|
||||
|
||||
/// 请求幂等号
|
||||
private String requestNo;
|
||||
|
||||
/// true 为创建时确认收到全部回收物并核销
|
||||
private Boolean verifyPayment;
|
||||
|
||||
/// 本次创建时回收并核销的数量,零表示不核销
|
||||
private BigDecimal paymentQuantity;
|
||||
|
||||
/// 回收凭证照片
|
||||
private List<Attachment> paymentAttachmentList;
|
||||
|
||||
/// true 为全部产品立即履约并核销
|
||||
private Boolean fulfillAll;
|
||||
|
||||
/// 履约凭证照片
|
||||
private List<Attachment> fulfillmentAttachmentList;
|
||||
|
||||
/// 规则倍数
|
||||
private Integer multiple;
|
||||
|
||||
/// 实际回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 业务发生时间
|
||||
private Long occurredAt;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
|
||||
/// 附件列表
|
||||
private List<Attachment> attachmentList;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchange;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeAction;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/// 回收兑换详情
|
||||
@Data
|
||||
public class GaoRecycleExchangeDetail {
|
||||
|
||||
/// 兑换单,含权益明细
|
||||
private GaoRecycleExchange exchange;
|
||||
|
||||
/// 操作记录
|
||||
private List<GaoRecycleExchangeAction> actionList;
|
||||
|
||||
/// 附件列表
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 操作记录附件,按操作 ID 分组
|
||||
private Map<String, List<Attachment>> actionAttachments;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 兑换权益明细请求
|
||||
@Data
|
||||
public class GaoRecycleExchangeItemRequest {
|
||||
/// SKU ID
|
||||
private String skuId;
|
||||
/// SKU 单位 ID
|
||||
private String skuUnitId;
|
||||
/// 兑换数量
|
||||
private BigDecimal quantity;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRule;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleExchangeRuleItem;
|
||||
|
||||
/// 回收兑换规则配置请求
|
||||
@Data
|
||||
public class GaoRecycleExchangeRuleRequest {
|
||||
/// 兑换模板明细
|
||||
private List<GaoRecycleExchangeRuleItem> itemList;
|
||||
/// 规则 ID,创建时为空
|
||||
private String id;
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 单份回收数量
|
||||
private BigDecimal recycleQuantity;
|
||||
|
||||
/// 状态
|
||||
private GaoRecycleExchangeRule.Status status;
|
||||
|
||||
/// 排序
|
||||
private Integer sort;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 兑换业务数量统计
|
||||
@Data
|
||||
public class GaoRecycleExchangeStatView {
|
||||
/// SKU ID
|
||||
private String skuId;
|
||||
|
||||
/// 业务单位 ID
|
||||
private String skuUnitId;
|
||||
|
||||
/// 产品名称快照
|
||||
private String productName;
|
||||
|
||||
/// 业务单位快照
|
||||
private String unit;
|
||||
|
||||
/// 创建数量
|
||||
private BigDecimal createdQuantity;
|
||||
|
||||
/// 核销数量
|
||||
private BigDecimal verifiedQuantity;
|
||||
|
||||
/// 冲正数量
|
||||
private BigDecimal revokedQuantity;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.gao.entity.GaoRecycleItem;
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
/// 回收物配置请求
|
||||
@Data
|
||||
public class GaoRecycleItemRequest {
|
||||
/// 配置 ID,创建时为空
|
||||
private String id;
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
/// 回收物名称
|
||||
private String name;
|
||||
|
||||
/// 回收单位
|
||||
private String unitName;
|
||||
|
||||
/// 是否允许小数数量
|
||||
private Boolean allowDecimalQuantity;
|
||||
|
||||
/// 状态
|
||||
private GaoRecycleItem.Status status;
|
||||
|
||||
/// 图片附件
|
||||
private List<Attachment> attachmentList;
|
||||
|
||||
/// 备注
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import com.imyeyu.api.modules.common.entity.Attachment;
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/// 回收物支付请求
|
||||
@Data
|
||||
public class GaoRecyclePaymentRequest {
|
||||
private String orderId;
|
||||
private String paymentId;
|
||||
private String requestNo;
|
||||
private BigDecimal quantity;
|
||||
private Long occurredAt;
|
||||
private String reason;
|
||||
private Boolean returnedToCustomer;
|
||||
private List<Attachment> attachmentList;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.imyeyu.api.modules.gao.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// 回收物按业务时间统计
|
||||
@Data
|
||||
public class GaoRecycleStatView {
|
||||
/// 回收物 ID
|
||||
private String recycleItemId;
|
||||
|
||||
/// 回收物名称快照
|
||||
private String recycleName;
|
||||
|
||||
/// 回收物单位快照
|
||||
private String recycleUnit;
|
||||
|
||||
/// 收到数量
|
||||
private BigDecimal receivedQuantity;
|
||||
|
||||
/// 退回数量
|
||||
private BigDecimal returnedQuantity;
|
||||
|
||||
/// 净回收数量
|
||||
private BigDecimal netQuantity;
|
||||
}
|
||||
@@ -15,6 +15,12 @@ import java.util.List;
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GaoSalesOrderPage extends BasePage {
|
||||
|
||||
/// true 为允许查询普通订单
|
||||
private Boolean orderAllowed;
|
||||
|
||||
/// true 为允许查询回收兑换订单
|
||||
private Boolean recycleAllowed;
|
||||
|
||||
/// 门店 ID
|
||||
private String storeId;
|
||||
|
||||
|
||||
@@ -85,6 +85,10 @@ public enum AuditOperation {
|
||||
GAO_POINT_RULE_UPDATE(Logger.Module.GAO),
|
||||
GAO_POINT_RULE_SORT(Logger.Module.GAO),
|
||||
GAO_POINT_RULE_DELETE(Logger.Module.GAO),
|
||||
GAO_RECYCLE_ITEM_SAVE(Logger.Module.GAO),
|
||||
GAO_RECYCLE_RULE_SAVE(Logger.Module.GAO),
|
||||
GAO_RECYCLE_EXCHANGE_CREATE(Logger.Module.GAO),
|
||||
GAO_RECYCLE_EXCHANGE_ACTION(Logger.Module.GAO),
|
||||
GAO_POINT_REDEEM_SKU_CREATE(Logger.Module.GAO),
|
||||
GAO_POINT_REDEEM_SKU_UPDATE(Logger.Module.GAO),
|
||||
GAO_POINT_REDEEM_SKU_DISABLE(Logger.Module.GAO),
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
CREATE TABLE `gao_recycle_item` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`name` VARCHAR(128) NOT NULL,
|
||||
`unit_name` VARCHAR(32) NOT NULL,
|
||||
`product_id` VARCHAR(36) NULL,
|
||||
`sku_id` VARCHAR(36) NULL,
|
||||
`status` VARCHAR(32) NOT NULL,
|
||||
`remark` TEXT NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
`updated_at` BIGINT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY (`store_id`, `status`, `created_at`)
|
||||
) COMMENT='GAO 回收兑换数据';
|
||||
|
||||
CREATE TABLE `gao_recycle_exchange_rule` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`sku_id` VARCHAR(36) NOT NULL,
|
||||
`sku_unit_id` VARCHAR(36) NOT NULL,
|
||||
`exchange_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`status` VARCHAR(32) NOT NULL,
|
||||
`sort` INT NOT NULL,
|
||||
`remark` TEXT NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
`updated_at` BIGINT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY (`store_id`, `status`, `recycle_item_id`, `sort`),
|
||||
KEY (`store_id`, `sku_id`, `sku_unit_id`)
|
||||
) COMMENT='GAO 回收兑换数据';
|
||||
|
||||
CREATE TABLE `gao_recycle_exchange` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`customer_id` VARCHAR(36) NOT NULL,
|
||||
`request_no` VARCHAR(128) NOT NULL,
|
||||
`request_fingerprint` VARCHAR(64) NOT NULL,
|
||||
`rule_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_name_snapshot` VARCHAR(128) NOT NULL,
|
||||
`recycle_unit_snapshot` VARCHAR(32) NOT NULL,
|
||||
`source_product_id_snapshot` VARCHAR(36) NULL,
|
||||
`source_sku_id_snapshot` VARCHAR(36) NULL,
|
||||
`rule_recycle_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`rule_exchange_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`multiple` INT NOT NULL,
|
||||
`default_recycle_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`default_exchange_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`recycle_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`exchange_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`product_id_snapshot` VARCHAR(36) NOT NULL,
|
||||
`sku_id_snapshot` VARCHAR(36) NOT NULL,
|
||||
`sku_unit_id_snapshot` VARCHAR(36) NOT NULL,
|
||||
`product_name_snapshot` VARCHAR(128) NOT NULL,
|
||||
`product_type_snapshot` VARCHAR(32) NOT NULL,
|
||||
`sku_code_snapshot` VARCHAR(128) NULL,
|
||||
`sku_name_snapshot` VARCHAR(128) NULL,
|
||||
`spec_summary_snapshot` VARCHAR(512) NULL,
|
||||
`unit_snapshot` VARCHAR(32) NOT NULL,
|
||||
`sku_spec_snapshot` JSON NULL,
|
||||
`base_quantity_per_unit_snapshot` DECIMAL(18,6) NOT NULL,
|
||||
`base_quantity` DECIMAL(18,3) NOT NULL,
|
||||
`allow_decimal_snapshot` TINYINT(1) NOT NULL,
|
||||
`stock_enabled_snapshot` TINYINT(1) NOT NULL,
|
||||
`status` VARCHAR(32) NOT NULL,
|
||||
`operator_user_id` VARCHAR(36) NOT NULL,
|
||||
`occurred_at` BIGINT NOT NULL,
|
||||
`remark` TEXT NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
`updated_at` BIGINT NULL,
|
||||
`deleted_at` BIGINT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY (`store_id`, `request_no`),
|
||||
KEY (`store_id`, `customer_id`, `status`, `occurred_at`),
|
||||
KEY (`store_id`, `status`, `created_at`),
|
||||
KEY (`store_id`, `recycle_item_id`, `occurred_at`),
|
||||
KEY (`store_id`, `sku_id_snapshot`, `occurred_at`)
|
||||
) COMMENT='GAO 回收兑换数据';
|
||||
|
||||
CREATE TABLE `gao_recycle_exchange_action` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`exchange_id` VARCHAR(36) NOT NULL,
|
||||
`request_no` VARCHAR(128) NOT NULL,
|
||||
`request_fingerprint` VARCHAR(64) NOT NULL,
|
||||
`action_type` VARCHAR(32) NOT NULL,
|
||||
`operator_user_id` VARCHAR(36) NOT NULL,
|
||||
`occurred_at` BIGINT NOT NULL,
|
||||
`reason` TEXT NULL,
|
||||
`remark` TEXT NULL,
|
||||
`recycle_returned` TINYINT(1) NULL,
|
||||
`stock_returned` TINYINT(1) NULL,
|
||||
`stock_record_id` VARCHAR(36) NULL,
|
||||
`source_stock_record_id` VARCHAR(36) NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY (`store_id`, `request_no`),
|
||||
UNIQUE KEY (`exchange_id`, `action_type`),
|
||||
KEY (`exchange_id`, `created_at`)
|
||||
) COMMENT='GAO 回收兑换数据';
|
||||
@@ -0,0 +1,188 @@
|
||||
-- 回收业务重构:客户额度账户 + 回收物支付 + 兑换单生成销售订单
|
||||
--
|
||||
-- V87 已在生产执行、回收功能未启用且没有有效数据,本脚本把 V87 的回收模型替换成额度账户模型:
|
||||
-- 商品明细并入生成的销售订单,回收物改为按客户维护的额度账户,支付独立核销。
|
||||
--
|
||||
-- 未发版的 V89/V91/V92/V93 已并入本脚本:回收物单头去掉来源产品列并补小数数量开关,
|
||||
-- 兑换单去掉来源产品快照,rule_recycle_quantity 保留不删
|
||||
--
|
||||
-- rule_recycle_quantity 与 rule_snapshot 中的 recycleQuantity 故意冗余:
|
||||
-- 兑换单详情页读的是列而不是快照,删除会导致来源行取值为空
|
||||
|
||||
-- 回收物单头:不再关联来源产品,产出关系改由 gao_recycle_product_yield 按 SKU 描述
|
||||
-- 同一回收物可由多个 SKU 产生,单头再挂产品既不足以表达也会误导配置人员
|
||||
-- allow_decimal_quantity 由回收物自己决定是否允许小数数量
|
||||
ALTER TABLE `gao_recycle_item`
|
||||
DROP COLUMN `product_id`,
|
||||
DROP COLUMN `sku_id`,
|
||||
ADD COLUMN `allow_decimal_quantity` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许小数数量';
|
||||
|
||||
-- 模板明细:一份模板可兑换多条 SKU
|
||||
CREATE TABLE `gao_recycle_exchange_rule_item` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`rule_id` VARCHAR(36) NOT NULL,
|
||||
`sku_id` VARCHAR(36) NOT NULL,
|
||||
`sku_unit_id` VARCHAR(36) NOT NULL,
|
||||
`exchange_quantity` DECIMAL(18,3) NOT NULL COMMENT '单份模板兑换的业务单位数量',
|
||||
`sort` INT NOT NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_recycle_rule_sku_unit` (`rule_id`, `sku_id`, `sku_unit_id`)
|
||||
) COMMENT='GAO 回收兑换模板明细';
|
||||
|
||||
-- store_id_2 是 (store_id, sku_id, sku_unit_id) 的自动命名(已在生产库 information_schema 确认)
|
||||
-- DROP INDEX IF EXISTS 保证索引名不一致时不会中断迁移,列删掉后索引本身也会自动收缩
|
||||
ALTER TABLE `gao_recycle_exchange_rule` DROP INDEX IF EXISTS `store_id_2`;
|
||||
ALTER TABLE `gao_recycle_exchange_rule`
|
||||
DROP COLUMN `sku_id`,
|
||||
DROP COLUMN `sku_unit_id`,
|
||||
DROP COLUMN `exchange_quantity`;
|
||||
|
||||
-- 兑换单:商品明细下沉到销售订单,这里只留回收物与支付条件
|
||||
-- store_id_5 是 (store_id, sku_id_snapshot, occurred_at) 的自动命名(已在生产库 information_schema 确认)
|
||||
ALTER TABLE `gao_recycle_exchange` DROP INDEX IF EXISTS `store_id_5`;
|
||||
ALTER TABLE `gao_recycle_exchange`
|
||||
DROP COLUMN `source_product_id_snapshot`,
|
||||
DROP COLUMN `source_sku_id_snapshot`,
|
||||
DROP COLUMN `rule_exchange_quantity`,
|
||||
DROP COLUMN `default_exchange_quantity`,
|
||||
DROP COLUMN `exchange_quantity`,
|
||||
DROP COLUMN `product_id_snapshot`,
|
||||
DROP COLUMN `sku_id_snapshot`,
|
||||
DROP COLUMN `sku_unit_id_snapshot`,
|
||||
DROP COLUMN `product_name_snapshot`,
|
||||
DROP COLUMN `product_type_snapshot`,
|
||||
DROP COLUMN `sku_code_snapshot`,
|
||||
DROP COLUMN `sku_name_snapshot`,
|
||||
DROP COLUMN `spec_summary_snapshot`,
|
||||
DROP COLUMN `unit_snapshot`,
|
||||
DROP COLUMN `sku_spec_snapshot`,
|
||||
DROP COLUMN `base_quantity_per_unit_snapshot`,
|
||||
DROP COLUMN `base_quantity`,
|
||||
DROP COLUMN `allow_decimal_snapshot`,
|
||||
DROP COLUMN `stock_enabled_snapshot`,
|
||||
MODIFY COLUMN `rule_id` VARCHAR(36) NULL COMMENT '模板 ID,自由创建时为空',
|
||||
MODIFY COLUMN `rule_recycle_quantity` DECIMAL(18,3) NULL COMMENT '模板单份回收数量',
|
||||
MODIFY COLUMN `multiple` INT NULL COMMENT '模板份数,自由创建时为空',
|
||||
MODIFY COLUMN `default_recycle_quantity` DECIMAL(18,3) NULL COMMENT '模板预设回收数量',
|
||||
MODIFY COLUMN `recycle_quantity` DECIMAL(18,3) NOT NULL COMMENT '约定支付回收物数量',
|
||||
MODIFY COLUMN `status` VARCHAR(32) NOT NULL COMMENT 'PENDING 待领取,COMPLETED 已完成,CANCELLED 已取消',
|
||||
ADD COLUMN `sales_order_id` VARCHAR(36) NULL COMMENT '生成的销售订单 ID' AFTER `rule_id`,
|
||||
ADD COLUMN `rule_snapshot` JSON NULL COMMENT '创建时模板快照,自由创建时为空' AFTER `sales_order_id`,
|
||||
ADD UNIQUE KEY `uk_recycle_exchange_order` (`sales_order_id`);
|
||||
|
||||
-- 兑换订单:记录约定支付的回收物与数量,订单本身仍是标准销售订单
|
||||
ALTER TABLE `gao_sales_order`
|
||||
ADD COLUMN `recycle_item_id` VARCHAR(36) NULL COMMENT '回收物 ID,仅回收兑换订单' AFTER `sale_amount`,
|
||||
ADD COLUMN `recycle_required_quantity` DECIMAL(18,3) NULL COMMENT '约定支付回收物数量,仅回收兑换订单',
|
||||
ADD KEY `idx_gao_sales_order_recycle` (`store_id`, `recycle_item_id`);
|
||||
|
||||
-- 操作记录:兑换单只剩取消
|
||||
ALTER TABLE `gao_recycle_exchange_action`
|
||||
DROP COLUMN `recycle_returned`,
|
||||
DROP COLUMN `stock_returned`,
|
||||
DROP COLUMN `stock_record_id`,
|
||||
DROP COLUMN `source_stock_record_id`,
|
||||
MODIFY COLUMN `action_type` VARCHAR(32) NOT NULL COMMENT 'CANCEL',
|
||||
ADD COLUMN `retained_recycle_quantity` DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '取消后门店保留的回收物数量';
|
||||
|
||||
-- 产品回收产物:每个 SKU 基础单位产生多少回收物
|
||||
CREATE TABLE `gao_recycle_product_yield` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`sku_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`quantity_per_base` DECIMAL(18,6) NOT NULL COMMENT '每个 SKU 基础单位产生的回收物数量',
|
||||
`created_at` BIGINT NOT NULL,
|
||||
`updated_at` BIGINT NULL,
|
||||
`deleted_at` BIGINT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_recycle_yield_sku_item` (`store_id`, `sku_id`, `recycle_item_id`),
|
||||
KEY `idx_recycle_yield_sku` (`store_id`, `sku_id`, `deleted_at`)
|
||||
) COMMENT='GAO 产品回收物产出配置';
|
||||
|
||||
-- 客户额度账户:按门店、客户、回收物类型隔离
|
||||
CREATE TABLE `gao_recycle_account` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`customer_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`balance` DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '额度余额',
|
||||
`reserved` DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '支付预占',
|
||||
`created_at` BIGINT NOT NULL,
|
||||
`updated_at` BIGINT NULL,
|
||||
`deleted_at` BIGINT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_recycle_account` (`store_id`, `customer_id`, `recycle_item_id`)
|
||||
) COMMENT='GAO 客户回收物额度账户';
|
||||
|
||||
-- 额度流水:不可变,记录前后值与来源
|
||||
CREATE TABLE `gao_recycle_ledger` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`account_id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`customer_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`biz_type` VARCHAR(32) NOT NULL COMMENT 'FULFILLMENT_YIELD 履约产生,ADJUST 人工调整,PAYMENT_RESERVE 支付预占,PAYMENT_RELEASE 释放预占,PAYMENT_VERIFY 支付核销,PAYMENT_REVOKE 冲正返还',
|
||||
`biz_id` VARCHAR(36) NULL COMMENT '来源业务 ID',
|
||||
`request_no` VARCHAR(128) NOT NULL,
|
||||
`balance_delta` DECIMAL(18,3) NOT NULL DEFAULT 0,
|
||||
`reserved_delta` DECIMAL(18,3) NOT NULL DEFAULT 0,
|
||||
`balance_after` DECIMAL(18,3) NOT NULL,
|
||||
`reserved_after` DECIMAL(18,3) NOT NULL,
|
||||
`operator_user_id` VARCHAR(36) NULL,
|
||||
`reason` TEXT NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_recycle_ledger_request` (`store_id`, `request_no`),
|
||||
KEY `idx_recycle_ledger_customer` (`store_id`, `customer_id`, `created_at`),
|
||||
KEY `idx_recycle_ledger_biz` (`biz_type`, `biz_id`)
|
||||
) COMMENT='GAO 回收物额度流水';
|
||||
|
||||
-- 回收物支付:一笔订单可分批提交
|
||||
CREATE TABLE `gao_recycle_payment` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`customer_id` VARCHAR(36) NOT NULL,
|
||||
`order_id` VARCHAR(36) NOT NULL COMMENT '兑换生成的销售订单 ID',
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`request_no` VARCHAR(128) NOT NULL,
|
||||
`request_fingerprint` VARCHAR(64) NOT NULL,
|
||||
`quantity` DECIMAL(18,3) NOT NULL,
|
||||
`status` VARCHAR(32) NOT NULL COMMENT 'PENDING 待核销,VERIFIED 已核销,REJECTED 已拒绝,CANCELLED 已撤销,REVOKED 已冲正',
|
||||
`source_payment_id` VARCHAR(36) NULL COMMENT '冲正指向的原支付',
|
||||
`operator_user_id` VARCHAR(36) NOT NULL,
|
||||
`verifier_user_id` VARCHAR(36) NULL,
|
||||
`occurred_at` BIGINT NOT NULL,
|
||||
`verified_at` BIGINT NULL,
|
||||
`reason` TEXT NULL,
|
||||
`returned_to_customer` TINYINT(1) NULL COMMENT '冲正时实物是否已退还客户',
|
||||
`created_at` BIGINT NOT NULL,
|
||||
`updated_at` BIGINT NULL,
|
||||
`deleted_at` BIGINT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_recycle_payment_request` (`store_id`, `request_no`),
|
||||
KEY `idx_recycle_payment_order` (`order_id`, `created_at`),
|
||||
KEY `idx_recycle_payment_source` (`source_payment_id`)
|
||||
) COMMENT='GAO 回收物支付记录';
|
||||
|
||||
-- 回收实物流转:收取与退还分方向记录
|
||||
CREATE TABLE `gao_recycle_physical_record` (
|
||||
`id` VARCHAR(36) NOT NULL,
|
||||
`store_id` VARCHAR(36) NOT NULL,
|
||||
`customer_id` VARCHAR(36) NOT NULL,
|
||||
`order_id` VARCHAR(36) NOT NULL,
|
||||
`recycle_item_id` VARCHAR(36) NOT NULL,
|
||||
`payment_id` VARCHAR(36) NULL COMMENT '关联支付,取消退还时用于去重',
|
||||
`source_type` VARCHAR(32) NOT NULL COMMENT 'PAYMENT_VERIFY 支付核销收取,PAYMENT_REVOKE 支付冲正退还,EXCHANGE_CANCEL 取消退还',
|
||||
`source_id` VARCHAR(36) NOT NULL,
|
||||
`direction` VARCHAR(8) NOT NULL COMMENT 'IN 门店收到,OUT 退还客户',
|
||||
`quantity` DECIMAL(18,3) NOT NULL,
|
||||
`occurred_at` BIGINT NOT NULL,
|
||||
`created_at` BIGINT NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
-- 同一来源只允许一条记录,防止重放或并发重复登记实物
|
||||
UNIQUE KEY `uk_recycle_physical_source` (`source_type`, `source_id`, `payment_id`),
|
||||
KEY `idx_recycle_physical_order` (`order_id`, `direction`),
|
||||
KEY `idx_recycle_physical_payment` (`payment_id`)
|
||||
) COMMENT='GAO 回收实物流转记录';
|
||||
@@ -0,0 +1,104 @@
|
||||
-- 将旧回收业务授权迁移至统一的订单、履约和支付权限
|
||||
CREATE TEMPORARY TABLE `gao_permission_mapping` (
|
||||
`old_code` VARCHAR(50) NOT NULL,
|
||||
`new_code` VARCHAR(50) NOT NULL,
|
||||
PRIMARY KEY (`old_code`, `new_code`)
|
||||
);
|
||||
|
||||
INSERT INTO `gao_permission_mapping` (`old_code`, `new_code`) VALUES
|
||||
('RECYCLE_EXCHANGE:QUERY', 'SALES_ORDER:READ'),
|
||||
('RECYCLE_EXCHANGE:QUERY', 'ORDER_FULFILLMENT:READ'),
|
||||
('RECYCLE_EXCHANGE:CREATE', 'SALES_ORDER:CREATE'),
|
||||
('RECYCLE_EXCHANGE:CREATE', 'ORDER_FULFILLMENT:CREATE'),
|
||||
('RECYCLE_EXCHANGE:CANCEL', 'SALES_ORDER:CANCEL'),
|
||||
('RECYCLE_EXCHANGE:QUANTITY_ADJUST', 'SALES_ORDER:PRICE_OVERRIDE'),
|
||||
('RECYCLE_EXCHANGE:VERIFY', 'ORDER_FULFILLMENT:VERIFY'),
|
||||
('RECYCLE_EXCHANGE:REVOKE', 'ORDER_FULFILLMENT:REVOKE'),
|
||||
('RECYCLE_PAYMENT:READ', 'FUND_RECORD:READ'),
|
||||
('RECYCLE_PAYMENT:CREATE', 'FUND_RECEIVE:CREATE'),
|
||||
('RECYCLE_PAYMENT:VERIFY', 'FUND_RECEIVE:VERIFY'),
|
||||
('RECYCLE_PAYMENT:REVOKE', 'FUND:REVOKE');
|
||||
|
||||
-- 目标内建权限通常已经存在;旧库缺失时先创建,启动后由内建权限初始化补齐名称
|
||||
INSERT INTO `permission` (`id`, `module_code`, `code`, `builtin`, `protected_permission`, `owner_type`, `created_at`)
|
||||
SELECT UUID(), 'GAO', mapping.`new_code`, TRUE, TRUE, 'MODULE', UNIX_TIMESTAMP() * 1000
|
||||
FROM (SELECT DISTINCT `new_code` FROM `gao_permission_mapping`) mapping
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `permission` target WHERE target.`module_code` = 'GAO' AND target.`code` = mapping.`new_code`
|
||||
);
|
||||
|
||||
-- 使用新的多语言记录,避免覆盖被其他数据共享的名称及旧缓存
|
||||
CREATE TEMPORARY TABLE `gao_permission_names` (
|
||||
`code` VARCHAR(50) NOT NULL PRIMARY KEY,
|
||||
`name` VARCHAR(50) NOT NULL,
|
||||
`lang_id` VARCHAR(36) NOT NULL
|
||||
);
|
||||
INSERT INTO `gao_permission_names` (`code`, `name`, `lang_id`) VALUES
|
||||
('SALES_ORDER:READ', '销售订单读取', UUID()),
|
||||
('SALES_ORDER:CREATE', '销售订单创建', UUID()),
|
||||
('SALES_ORDER:CANCEL', '销售订单取消', UUID()),
|
||||
('ORDER_FULFILLMENT:READ', '统一履约读取', UUID()),
|
||||
('ORDER_FULFILLMENT:CREATE', '统一履约创建', UUID()),
|
||||
('ORDER_FULFILLMENT:VERIFY', '统一履约核销', UUID()),
|
||||
('ORDER_FULFILLMENT:REVOKE', '统一履约冲正', UUID()),
|
||||
('SALES_ORDER:PRICE_OVERRIDE', '订单交易条件调整', UUID()),
|
||||
('ORDER_FULFILLMENT:UNSETTLED', '订单未结清履约', UUID()),
|
||||
('FUND_RECORD:READ', '支付记录读取', UUID()),
|
||||
('FUND_RECEIVE:CREATE', '支付登记', UUID()),
|
||||
('FUND_RECEIVE:VERIFY', '支付核销', UUID()),
|
||||
('FUND:REVOKE', '支付冲正', UUID());
|
||||
INSERT INTO `multilingual` (`id`, `zh_cn`, `created_at`)
|
||||
SELECT names.`lang_id`, names.`name`, UNIX_TIMESTAMP() * 1000
|
||||
FROM `gao_permission_names` names
|
||||
JOIN `permission` permission ON permission.`module_code` = 'GAO' AND permission.`code` = names.`code` AND permission.`deleted_at` IS NULL;
|
||||
UPDATE `permission` permission
|
||||
JOIN `gao_permission_names` names ON names.`code` = permission.`code`
|
||||
SET permission.`name_lang_id` = names.`lang_id`
|
||||
WHERE permission.`module_code` = 'GAO' AND permission.`deleted_at` IS NULL;
|
||||
DROP TEMPORARY TABLE `gao_permission_names`;
|
||||
|
||||
-- 仅迁移有效授权,不恢复已撤销的旧授权
|
||||
INSERT INTO `role_permission` (`id`, `role_id`, `permission_id`, `created_at`)
|
||||
SELECT UUID(), source.`role_id`, target.`id`, UNIX_TIMESTAMP() * 1000
|
||||
FROM (
|
||||
SELECT DISTINCT rp.`role_id`, mapping.`new_code`
|
||||
FROM `role_permission` rp
|
||||
JOIN `permission` old_permission ON old_permission.`id` = rp.`permission_id` AND old_permission.`module_code` = 'GAO' AND old_permission.`deleted_at` IS NULL
|
||||
JOIN `gao_permission_mapping` mapping ON mapping.`old_code` = old_permission.`code`
|
||||
WHERE rp.`deleted_at` IS NULL
|
||||
) source
|
||||
JOIN `permission` target ON target.`module_code` = 'GAO' AND target.`code` = source.`new_code` AND target.`deleted_at` IS NULL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `role_permission` existing
|
||||
WHERE existing.`role_id` = source.`role_id` AND existing.`permission_id` = target.`id` AND existing.`deleted_at` IS NULL
|
||||
);
|
||||
|
||||
INSERT INTO `role_permission_delegation` (`id`, `role_id`, `permission_id`, `created_at`)
|
||||
SELECT UUID(), source.`role_id`, target.`id`, UNIX_TIMESTAMP() * 1000
|
||||
FROM (
|
||||
SELECT DISTINCT delegation.`role_id`, mapping.`new_code`
|
||||
FROM `role_permission_delegation` delegation
|
||||
JOIN `permission` old_permission ON old_permission.`id` = delegation.`permission_id` AND old_permission.`module_code` = 'GAO' AND old_permission.`deleted_at` IS NULL
|
||||
JOIN `gao_permission_mapping` mapping ON mapping.`old_code` = old_permission.`code`
|
||||
WHERE delegation.`deleted_at` IS NULL
|
||||
) source
|
||||
JOIN `permission` target ON target.`module_code` = 'GAO' AND target.`code` = source.`new_code` AND target.`deleted_at` IS NULL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `role_permission_delegation` existing
|
||||
WHERE existing.`role_id` = source.`role_id` AND existing.`permission_id` = target.`id` AND existing.`deleted_at` IS NULL
|
||||
);
|
||||
|
||||
-- 保留授权历史;只有所有目标权限可用时才隐藏旧权限
|
||||
CREATE TEMPORARY TABLE `gao_migrated_codes` (`old_code` VARCHAR(50) PRIMARY KEY);
|
||||
INSERT INTO `gao_migrated_codes` (`old_code`)
|
||||
SELECT mapping.`old_code`
|
||||
FROM `gao_permission_mapping` mapping
|
||||
LEFT JOIN `permission` target ON target.`module_code` = 'GAO' AND target.`code` = mapping.`new_code` AND target.`deleted_at` IS NULL
|
||||
GROUP BY mapping.`old_code`
|
||||
HAVING COUNT(*) = COUNT(target.`id`);
|
||||
UPDATE `permission` old_permission
|
||||
JOIN `gao_migrated_codes` migrated ON migrated.`old_code` = old_permission.`code`
|
||||
SET old_permission.`deleted_at` = UNIX_TIMESTAMP() * 1000
|
||||
WHERE old_permission.`module_code` = 'GAO' AND old_permission.`deleted_at` IS NULL;
|
||||
DROP TEMPORARY TABLE `gao_migrated_codes`;
|
||||
DROP TEMPORARY TABLE `gao_permission_mapping`;
|
||||
@@ -41,6 +41,8 @@
|
||||
</select>
|
||||
<sql id="queryWhere">
|
||||
1 = 1
|
||||
<if test="orderAllowed != null and !orderAllowed">AND EXISTS (SELECT 1 FROM `gao_sales_order` o WHERE o.`id` = `gao_order_fulfillment`.`sales_order_id` AND o.`order_type` = 'RECYCLE')</if>
|
||||
<if test="recycleAllowed != null and !recycleAllowed">AND EXISTS (SELECT 1 FROM `gao_sales_order` o WHERE o.`id` = `gao_order_fulfillment`.`sales_order_id` AND o.`order_type` != 'RECYCLE')</if>
|
||||
<if test="storeId != null and storeId != ''">AND `store_id` = #{storeId}</if>
|
||||
<if test="salesOrderId != null and salesOrderId != ''">AND `sales_order_id` = #{salesOrderId}</if>
|
||||
<if test="customerId != null and customerId != ''">AND `customer_id` = #{customerId}</if>
|
||||
@@ -60,7 +62,9 @@
|
||||
SELECT COUNT(1) FROM `gao_order_fulfillment` WHERE <include refid="queryWhere"/>
|
||||
</select>
|
||||
<select id="selectByQuery" resultType="com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment">
|
||||
SELECT * FROM `gao_order_fulfillment`
|
||||
SELECT `gao_order_fulfillment`.*,
|
||||
(SELECT o.`order_type` FROM `gao_sales_order` o WHERE o.`id` = `gao_order_fulfillment`.`sales_order_id`) AS `orderType`
|
||||
FROM `gao_order_fulfillment`
|
||||
WHERE <include refid="queryWhere"/>
|
||||
ORDER BY `delivered_at` DESC, `created_at` DESC
|
||||
LIMIT #{offset}, #{limit}
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
FROM `gao_sales_order` o
|
||||
<include refid="orderReminderJoins"/>
|
||||
WHERE o.`deleted_at` IS NULL
|
||||
AND o.`order_type` <> 'RECYCLE'
|
||||
AND o.`status` IN ('ACTIVE', 'FULFILLED')
|
||||
AND o.`payment_status` IN ('UNPAID', 'PARTIALLY_PAID')
|
||||
ORDER BY o.`store_id`, c.`name`, o.`customer_id`, o.`purchased_at`, o.`order_no`
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
<sql id="orderProductFilter">
|
||||
AND o.`deleted_at` IS NULL
|
||||
AND o.`order_type` <> 'RECYCLE'
|
||||
AND i.`deleted_at` IS NULL
|
||||
AND o.`status` <> 'CANCELLED'
|
||||
<if test="storeId != null and storeId != ''">AND o.`store_id` = #{storeId}</if>
|
||||
@@ -78,6 +79,8 @@
|
||||
THEN CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END ELSE 0 END), 0) AS `directBaseQuantity`,
|
||||
COALESCE(SUM(CASE WHEN i.`item_type` = 'PACKAGE_ENTITLEMENT'
|
||||
THEN CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END ELSE 0 END), 0) AS `packageBaseQuantity`,
|
||||
COALESCE(SUM(CASE WHEN i.`item_type` = 'RECYCLE_ENTITLEMENT'
|
||||
THEN CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END ELSE 0 END), 0) AS `recycleBaseQuantity`,
|
||||
COALESCE(SUM(CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END), 0) AS `baseQuantity`
|
||||
FROM `gao_order_fulfillment` f
|
||||
INNER JOIN `gao_order_fulfillment_item` fi ON fi.`fulfillment_id` = f.`id`
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
(SELECT COUNT(*) FROM `gao_order_fulfillment_item` WHERE `product_id_snapshot` = #{productId}) +
|
||||
(SELECT COUNT(*) FROM `gao_product_stock_record` WHERE `product_id_snapshot` = #{productId}) +
|
||||
(SELECT COUNT(*) FROM `gao_package_config_item` WHERE `product_id_snapshot` = #{productId}) +
|
||||
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `product_id_snapshot` = #{productId})
|
||||
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `product_id_snapshot` = #{productId}) +
|
||||
(SELECT COUNT(*) FROM `gao_recycle_product_yield` y JOIN `gao_product_sku` s ON s.`id` = y.`sku_id` WHERE s.`product_id` = #{productId}) +
|
||||
(SELECT COUNT(*) FROM `gao_recycle_exchange_rule_item` ri JOIN `gao_product_sku` s ON s.`id` = ri.`sku_id` WHERE s.`product_id` = #{productId})
|
||||
</select>
|
||||
<select id="countSkuReferences" resultType="int">
|
||||
SELECT
|
||||
@@ -16,7 +18,9 @@
|
||||
(SELECT COUNT(*) FROM `gao_product_stock_record` WHERE `sku_id` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_package_config_item` WHERE `sku_id` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_point_redeem_sku` WHERE `sku_id` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_id_snapshot` = #{skuId})
|
||||
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_id_snapshot` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_recycle_product_yield` WHERE `sku_id` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_recycle_exchange_rule_item` WHERE `sku_id` = #{skuId})
|
||||
</select>
|
||||
<select id="countUnitReferences" resultType="int">
|
||||
SELECT
|
||||
@@ -25,7 +29,14 @@
|
||||
(SELECT COUNT(*) FROM `gao_product_stock_record` WHERE `sku_unit_id` = #{unitId}) +
|
||||
(SELECT COUNT(*) FROM `gao_package_config_item` WHERE `sku_unit_id` = #{unitId}) +
|
||||
(SELECT COUNT(*) FROM `gao_point_redeem_sku` WHERE `sku_unit_id` = #{unitId}) +
|
||||
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_unit_id_snapshot` = #{unitId})
|
||||
(SELECT COUNT(*) FROM `gao_point_redemption` WHERE `sku_unit_id_snapshot` = #{unitId}) +
|
||||
(SELECT COUNT(*) FROM `gao_recycle_exchange_rule_item` WHERE `sku_unit_id` = #{unitId})
|
||||
</select>
|
||||
<select id="countRecycleReferences" resultType="int">
|
||||
SELECT (SELECT COUNT(*) FROM `gao_recycle_product_yield` WHERE `sku_id` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_recycle_exchange_rule_item` WHERE `sku_id` = #{skuId}) +
|
||||
(SELECT COUNT(*) FROM `gao_sales_order_item` i JOIN `gao_sales_order` o ON o.`id` = i.`sales_order_id`
|
||||
WHERE i.`sku_id` = #{skuId} AND o.`order_type` = 'RECYCLE')
|
||||
</select>
|
||||
<select id="countMigrationPrecisionLoss" resultType="int">
|
||||
SELECT COUNT(*) FROM (
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoProductSkuChartMapper">
|
||||
<sql id="skuOrderProductFilter">
|
||||
AND o.`deleted_at` IS NULL
|
||||
AND o.`order_type` <> 'RECYCLE'
|
||||
AND i.`deleted_at` IS NULL
|
||||
AND o.`status` <> 'CANCELLED'
|
||||
AND o.`store_id` = #{storeId}
|
||||
@@ -97,6 +98,8 @@
|
||||
THEN CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END ELSE 0 END), 0) AS `directBaseQuantity`,
|
||||
COALESCE(SUM(CASE WHEN i.`item_type` = 'PACKAGE_ENTITLEMENT'
|
||||
THEN CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END ELSE 0 END), 0) AS `packageBaseQuantity`,
|
||||
COALESCE(SUM(CASE WHEN i.`item_type` = 'RECYCLE_ENTITLEMENT'
|
||||
THEN CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END ELSE 0 END), 0) AS `recycleBaseQuantity`,
|
||||
COALESCE(SUM(CASE WHEN f.`source_fulfillment_id` IS NULL THEN fi.`base_quantity` ELSE -fi.`base_quantity` END), 0) AS `baseQuantity`
|
||||
FROM `gao_order_fulfillment` f
|
||||
INNER JOIN `gao_order_fulfillment_item` fi ON fi.`fulfillment_id` = f.`id`
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
|
||||
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoRecycleStatMapper">
|
||||
<select id="selectRecycleStats" resultType="com.imyeyu.api.modules.gao.vo.GaoRecycleStatView">
|
||||
SELECT t.recycle_item_id AS recycleItemId, t.recycle_name AS recycleName,
|
||||
t.recycle_unit AS recycleUnit, SUM(t.received) AS receivedQuantity,
|
||||
SUM(t.returned) AS returnedQuantity, SUM(t.received - t.returned) AS netQuantity
|
||||
FROM (
|
||||
SELECT e.recycle_item_id, e.recycle_name_snapshot AS recycle_name,
|
||||
e.recycle_unit_snapshot AS recycle_unit,
|
||||
CASE WHEN p.direction = 'IN' THEN p.quantity ELSE 0 END AS received,
|
||||
CASE WHEN p.direction = 'OUT' THEN p.quantity ELSE 0 END AS returned
|
||||
FROM gao_recycle_physical_record p
|
||||
JOIN gao_recycle_exchange e ON e.sales_order_id = p.order_id AND e.store_id = p.store_id
|
||||
WHERE p.store_id = #{storeId} AND p.occurred_at >= #{startAt} AND p.occurred_at < #{endAt}
|
||||
) t
|
||||
GROUP BY t.recycle_item_id, t.recycle_name, t.recycle_unit
|
||||
</select>
|
||||
<select id="selectExchangeStats" resultType="com.imyeyu.api.modules.gao.vo.GaoRecycleExchangeStatView">
|
||||
SELECT t.sku_id AS skuId, t.sku_unit_id AS skuUnitId, t.product_name AS productName,
|
||||
t.unit_name AS unit, SUM(t.created) AS createdQuantity,
|
||||
SUM(t.verified) AS verifiedQuantity, SUM(t.revoked) AS revokedQuantity
|
||||
FROM (
|
||||
SELECT oi.sku_id, oi.sku_unit_id, oi.product_name_snapshot AS product_name,
|
||||
oi.unit_snapshot AS unit_name,
|
||||
oi.quantity AS created, 0 AS verified, 0 AS revoked
|
||||
FROM gao_recycle_exchange e
|
||||
JOIN gao_sales_order_item oi ON oi.sales_order_id = e.sales_order_id
|
||||
AND oi.item_type = 'RECYCLE_ENTITLEMENT' AND oi.deleted_at IS NULL
|
||||
WHERE e.store_id = #{storeId} AND e.occurred_at >= #{startAt} AND e.occurred_at < #{endAt}
|
||||
UNION ALL
|
||||
SELECT oi.sku_id, oi.sku_unit_id, oi.product_name_snapshot, oi.unit_snapshot,
|
||||
0, CASE WHEN f.source_fulfillment_id IS NULL THEN i.base_quantity / oi.base_quantity_per_unit_snapshot ELSE 0 END,
|
||||
CASE WHEN f.source_fulfillment_id IS NOT NULL THEN i.base_quantity / oi.base_quantity_per_unit_snapshot ELSE 0 END
|
||||
FROM gao_order_fulfillment f
|
||||
JOIN gao_recycle_exchange e ON e.sales_order_id = f.sales_order_id AND e.store_id = f.store_id
|
||||
JOIN gao_order_fulfillment_item i ON i.fulfillment_id = f.id
|
||||
JOIN gao_sales_order_item oi ON oi.id = i.source_order_item_id AND oi.sales_order_id = f.sales_order_id
|
||||
WHERE f.store_id = #{storeId}
|
||||
AND ((f.source_fulfillment_id IS NULL AND f.status IN ('VERIFIED', 'REVOKED'))
|
||||
OR (f.source_fulfillment_id IS NOT NULL AND f.status = 'VERIFIED'))
|
||||
AND f.delivered_at >= #{startAt} AND f.delivered_at < #{endAt}
|
||||
) t
|
||||
GROUP BY t.sku_id, t.sku_unit_id, t.product_name, t.unit_name
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -3,6 +3,7 @@
|
||||
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoSalesOrderChartMapper">
|
||||
<sql id="orderFilter">
|
||||
AND o.`deleted_at` IS NULL
|
||||
AND o.`order_type` <> 'RECYCLE'
|
||||
AND o.`store_id` = #{storeId}
|
||||
<if test="customerId != null and customerId != ''">AND o.`customer_id` = #{customerId}</if>
|
||||
<if test="orderType != null">AND o.`order_type` = #{orderType}</if>
|
||||
@@ -218,6 +219,7 @@
|
||||
|
||||
<sql id="repeatOrderFilter">
|
||||
AND o.`deleted_at` IS NULL
|
||||
AND o.`order_type` <> 'RECYCLE'
|
||||
AND o.`store_id` = #{storeId}
|
||||
<if test="customerId != null and customerId != ''">AND o.`customer_id` = #{customerId}</if>
|
||||
<if test="orderType != null">AND o.`order_type` = #{orderType}</if>
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
</select>
|
||||
<sql id="queryWhere">
|
||||
o.`deleted_at` IS NULL
|
||||
<if test="orderAllowed != null and !orderAllowed">AND o.`order_type` = 'RECYCLE'</if>
|
||||
<if test="recycleAllowed != null and !recycleAllowed">AND o.`order_type` <> 'RECYCLE'</if>
|
||||
<if test="storeId != null and storeId != ''">AND o.`store_id` = #{storeId}</if>
|
||||
<if test="customerId != null and customerId != ''">AND o.`customer_id` = #{customerId}</if>
|
||||
<if test="fulfillableSkuId != null and fulfillableSkuId != ''">
|
||||
@@ -86,7 +88,17 @@
|
||||
SELECT COUNT(1) FROM `gao_sales_order` o LEFT JOIN `gao_customer` c ON c.`id` = o.`customer_id` WHERE <include refid="queryWhere"/>
|
||||
</select>
|
||||
<select id="selectByQuery" resultType="com.imyeyu.api.modules.gao.entity.GaoSalesOrder">
|
||||
SELECT o.* FROM `gao_sales_order` o LEFT JOIN `gao_customer` c ON c.`id` = o.`customer_id` WHERE <include refid="queryWhere"/>
|
||||
SELECT o.*,
|
||||
(SELECT SUM(p.`quantity`) FROM `gao_recycle_payment` p
|
||||
WHERE p.`order_id` = o.`id` AND p.`status` = 'PENDING') AS `recyclePendingQuantity`,
|
||||
<!-- 回收物名称与单位取兑换单创建时的快照,回收物改名后历史订单仍显示当时的名称 -->
|
||||
e.`id` AS `recycleExchangeId`,
|
||||
e.`recycle_name_snapshot` AS `recycleItemName`,
|
||||
e.`recycle_unit_snapshot` AS `recycleUnit`
|
||||
FROM `gao_sales_order` o
|
||||
LEFT JOIN `gao_customer` c ON c.`id` = o.`customer_id`
|
||||
LEFT JOIN `gao_recycle_exchange` e ON e.`sales_order_id` = o.`id`
|
||||
WHERE <include refid="queryWhere"/>
|
||||
ORDER BY o.`purchased_at` DESC, o.`created_at` DESC
|
||||
LIMIT #{offset}, #{limit}
|
||||
</select>
|
||||
|
||||
Reference in New Issue
Block a user