订单支付成功时,事务化写入 USDT 收入流水。

归集明细成功时,事务化写入 USDT 支出流水。
使用唯一幂等键防止订单重扫、归集重试产生重复流水。
新增按应用、币种、时间范围以及日/月/年维度的统计接口。
管理员和商户接口均改为只读,移除流水新增、修改、删除入口。
商户查询由后端强制限定当前用户。
This commit is contained in:
lu7213 committed 2026-10-13 10:32:18 -04:00
1 parent 8cc7bd0c17
commit 0ff174e872
15 files changed
+375 -252

No files matched your search

@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.IUsdtOrdersService;
import com.ruoyi.system.service.WalletLedgerPostingService;
import com.ruoyi.system.service.TronServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -17,7 +18,6 @@ import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
/**
* 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。
@@ -30,6 +30,8 @@ public class TronPaymentTask {
private IUsdtOrdersService orders;
@Autowired
private TronServiceProvider tronServiceProvider;
@Autowired
private WalletLedgerPostingService ledgerPostingService;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
@@ -55,13 +57,9 @@ public class TronPaymentTask {
if (value.compareTo(order.getActualAmount().setScale(6, RoundingMode.DOWN)) != 0) continue;
String hash = tx.getString("transaction_id");
if (hash == null || hash.trim().isEmpty()) continue;
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0)
continue;
order.setBlockTransactionId(hash);
order.setStatus(2L);
order.setUpdatedAt(new Date());
orders.updateById(order);
break;
if (ledgerPostingService.settlePaidOrder(order.getId(), hash)) {
break;
}
}
} catch (Exception e) {
// 单笔订单查询失败不能中断其他订单,日志中禁止输出凭证和钱包私钥。
@@ -5,11 +5,9 @@ import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.select.Ids;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.WalletAddressLedger;
import com.ruoyi.system.domain.WalletAddressLedgerPlus;
import com.ruoyi.system.domain.vo.WalletLedgerStatisticsQuery;
import com.ruoyi.system.service.IWalletAddressLedgerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -29,34 +27,6 @@ public class WalletAddressLedgerController extends BaseController
{
@Autowired
private IWalletAddressLedgerService walletAddressLedgerService;
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:getByIds')")
@PostMapping("/getByIds")
public AjaxResult getByIds(@RequestBody Ids ids)
{
List<WalletAddressLedgerPlus> list = walletAddressLedgerService.getByIds(ids.getLongIds(),false,WalletAddressLedgerPlus::getWalletAddress,WalletAddressLedgerPlus::getId);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:user-getByIds')")
@PostMapping("/user/getByIds")
public AjaxResult userGetByIds(@RequestBody Ids ids)
{
List<WalletAddressLedgerPlus> list = walletAddressLedgerService.getByIds(ids.getLongIds(),true,WalletAddressLedgerPlus::getUserId,WalletAddressLedgerPlus::getWalletAddress,WalletAddressLedgerPlus::getId);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:select')")
@GetMapping("/select")
public AjaxResult select(String keyword)
{
List<SelectItem> list = walletAddressLedgerService.select(keyword,false);
return AjaxResult.success(list);
}
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:user-select')")
@GetMapping("/user/select")
public AjaxResult userSelect(String keyword)
{
List<SelectItem> list = walletAddressLedgerService.select(keyword,true);
return AjaxResult.success(list);
}
/**
* 查询钱包地址资金流水列表
*/
@@ -110,61 +80,16 @@ public class WalletAddressLedgerController extends BaseController
{
return AjaxResult.success(walletAddressLedgerService.selectWalletAddressLedgerById(id,true));
}
/**
* 新增钱包地址资金流水
*/
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:add')")
@Log(title = "钱包地址资金流水", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody WalletAddressLedger walletAddressLedger)
{
return toAjax(walletAddressLedgerService.insertWalletAddressLedger(walletAddressLedger,false));
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:list')")
@GetMapping("/statistics")
public AjaxResult statistics(WalletLedgerStatisticsQuery query) {
return AjaxResult.success(walletAddressLedgerService.statistics(query, false));
}
/**
* 新增钱包地址资金流水
*/
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:user-add')")
@Log(title = "钱包地址资金流水", businessType = BusinessType.INSERT)
@PostMapping("/user")
public AjaxResult userAdd(@RequestBody WalletAddressLedger walletAddressLedger)
{
return toAjax(walletAddressLedgerService.insertWalletAddressLedger(walletAddressLedger,true));
}
/**
* 修改钱包地址资金流水
*/
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:edit')")
@Log(title = "钱包地址资金流水", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody WalletAddressLedger walletAddressLedger)
{
return toAjax(walletAddressLedgerService.updateWalletAddressLedger(walletAddressLedger,false));
}
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:user-edit')")
@Log(title = "钱包地址资金流水", businessType = BusinessType.UPDATE)
@PutMapping("/user")
public AjaxResult userEdit(@RequestBody WalletAddressLedger walletAddressLedger)
{
return toAjax(walletAddressLedgerService.updateWalletAddressLedger(walletAddressLedger,true));
}
/**
* 删除钱包地址资金流水
*/
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:remove')")
@Log(title = "钱包地址资金流水", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(walletAddressLedgerService.deleteWalletAddressLedgerByIds(ids,false));
}
/**
* 删除钱包地址资金流水
*/
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:user-remove')")
@Log(title = "钱包地址资金流水", businessType = BusinessType.DELETE)
@DeleteMapping("/user/{ids}")
public AjaxResult userRemove(@PathVariable Long[] ids)
{
return toAjax(walletAddressLedgerService.deleteWalletAddressLedgerByIds(ids,true));
@PreAuthorize("@ss.hasPermi('system:walletAddressLedger:user-list')")
@GetMapping("/user/statistics")
public AjaxResult userStatistics(WalletLedgerStatisticsQuery query) {
return AjaxResult.success(walletAddressLedgerService.statistics(query, true));
}
}
@@ -0,0 +1,32 @@
package com.ruoyi.system.domain.vo;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
/** 钱包流水统计查询条件。 */
public class WalletLedgerStatisticsQuery {
private Long appId;
private Long userId;
private String currency;
private String granularity;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date beginTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
public Long getAppId() { return appId; }
public void setAppId(Long appId) { this.appId = appId; }
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public String getCurrency() { return currency; }
public void setCurrency(String currency) { this.currency = currency; }
public String getGranularity() { return granularity; }
public void setGranularity(String granularity) { this.granularity = granularity; }
public Date getBeginTime() { return beginTime; }
public void setBeginTime(Date beginTime) { this.beginTime = beginTime; }
public Date getEndTime() { return endTime; }
public void setEndTime(Date endTime) { this.endTime = endTime; }
}
@@ -0,0 +1,20 @@
package com.ruoyi.system.domain.vo;
import java.util.List;
/** 钱包流水统计响应。 */
public class WalletLedgerStatisticsVo {
private List<WalletLedgerSummaryVo> summaries;
private List<WalletLedgerTrendVo> trends;
public WalletLedgerStatisticsVo(List<WalletLedgerSummaryVo> summaries,
List<WalletLedgerTrendVo> trends) {
this.summaries = summaries;
this.trends = trends;
}
public List<WalletLedgerSummaryVo> getSummaries() { return summaries; }
public void setSummaries(List<WalletLedgerSummaryVo> summaries) { this.summaries = summaries; }
public List<WalletLedgerTrendVo> getTrends() { return trends; }
public void setTrends(List<WalletLedgerTrendVo> trends) { this.trends = trends; }
}
@@ -0,0 +1,23 @@
package com.ruoyi.system.domain.vo;
import java.math.BigDecimal;
/** 单币种钱包流水汇总。 */
public class WalletLedgerSummaryVo {
private String currency;
private BigDecimal incomeAmount;
private BigDecimal expenseAmount;
private BigDecimal netAmount;
private Long count;
public String getCurrency() { return currency; }
public void setCurrency(String currency) { this.currency = currency; }
public BigDecimal getIncomeAmount() { return incomeAmount; }
public void setIncomeAmount(BigDecimal incomeAmount) { this.incomeAmount = incomeAmount; }
public BigDecimal getExpenseAmount() { return expenseAmount; }
public void setExpenseAmount(BigDecimal expenseAmount) { this.expenseAmount = expenseAmount; }
public BigDecimal getNetAmount() { return netAmount; }
public void setNetAmount(BigDecimal netAmount) { this.netAmount = netAmount; }
public Long getCount() { return count; }
public void setCount(Long count) { this.count = count; }
}
@@ -0,0 +1,11 @@
package com.ruoyi.system.domain.vo;
import java.math.BigDecimal;
/** 钱包流水趋势点。 */
public class WalletLedgerTrendVo extends WalletLedgerSummaryVo {
private String period;
public String getPeriod() { return period; }
public void setPeriod(String period) { this.period = period; }
}
@@ -15,6 +15,13 @@ import com.ruoyi.system.domain.UsdtOrdersPlus;
*/
public interface UsdtOrdersMapper extends BaseMapper<UsdtOrdersPlus>
{
UsdtOrdersPlus selectByIdForUpdate(@Param("id") Long id);
int countPaidByTransactionId(@Param("transactionId") String transactionId,
@Param("excludeOrderId") Long excludeOrderId);
int markOrderPaid(@Param("id") Long id, @Param("transactionId") String transactionId,
@Param("updatedAt") java.util.Date updatedAt);
/**
* 查询订单
*
@@ -6,6 +6,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import com.ruoyi.system.domain.WalletAddressLedger;
import com.ruoyi.system.domain.WalletAddressLedgerPlus;
import com.ruoyi.system.domain.vo.WalletLedgerStatisticsQuery;
import com.ruoyi.system.domain.vo.WalletLedgerSummaryVo;
import com.ruoyi.system.domain.vo.WalletLedgerTrendVo;
/**
* 钱包地址资金流水Mapper接口
@@ -31,6 +34,13 @@ public interface WalletAddressLedgerMapper extends BaseMapper<WalletAddressLedge
*/
public List<WalletAddressLedger> selectWalletAddressLedgerList(WalletAddressLedger walletAddressLedger);
/** 由系统业务链路幂等写入流水,重复幂等键不产生新记录。 */
int insertSystemLedgerIgnoreDuplicate(WalletAddressLedger walletAddressLedger);
List<WalletLedgerSummaryVo> selectStatisticsSummary(WalletLedgerStatisticsQuery query);
List<WalletLedgerTrendVo> selectStatisticsTrend(WalletLedgerStatisticsQuery query);
/**
* 新增钱包地址资金流水
*
@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.system.domain.WalletAddressLedger;
import com.ruoyi.system.domain.WalletAddressLedgerPlus;
import com.ruoyi.system.domain.vo.WalletLedgerStatisticsQuery;
import com.ruoyi.system.domain.vo.WalletLedgerStatisticsVo;
import java.util.List;
import java.util.Map;
@@ -34,37 +36,7 @@ public interface IWalletAddressLedgerService extends IService<WalletAddressLedge
*/
public List<WalletAddressLedger> selectWalletAddressLedgerList(WalletAddressLedger walletAddressLedger,boolean isUser);
/**
* 新增钱包地址资金流水
*
* @param walletAddressLedger 钱包地址资金流水
* @return 结果
*/
public int insertWalletAddressLedger(WalletAddressLedger walletAddressLedger,boolean isUser);
/**
* 修改钱包地址资金流水
*
* @param walletAddressLedger 钱包地址资金流水
* @return 结果
*/
public int updateWalletAddressLedger(WalletAddressLedger walletAddressLedger,boolean isUser);
/**
* 批量删除钱包地址资金流水
*
* @param ids 需要删除的钱包地址资金流水ID
* @return 结果
*/
public int deleteWalletAddressLedgerByIds(Long[] ids,boolean isUser);
/**
* 删除钱包地址资金流水信息
*
* @param id 钱包地址资金流水ID
* @return 结果
*/
public int deleteWalletAddressLedgerById(Long id,boolean isUser);
WalletLedgerStatisticsVo statistics(WalletLedgerStatisticsQuery query, boolean isUser);
List<WalletAddressLedgerPlus> getByIds(List<Long> ids,boolean isUser, SFunction<WalletAddressLedgerPlus, ?>... columns);
@@ -76,16 +48,4 @@ public interface IWalletAddressLedgerService extends IService<WalletAddressLedge
Map<Long, WalletAddressLedgerPlus> getMapByIds(List<Long> ids);
/**
* @param field sum 字段
* @param where 条件
* @param tClass 返回类型
* @param <T>
* @return
*/
<T> T sum(String field, String where, Class<T> tClass);
Long count(String where);
<T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass);
}
@@ -37,6 +37,7 @@ public class UsdtAggregationWorkflowService {
private final UsdtAggregationTaskItemMapper itemMapper;
private final WalletOperationEstimateService estimateService;
private final WalletSigningService walletSigningService;
private final WalletLedgerPostingService ledgerPostingService;
public UsdtAggregationWorkflowService(IAppsService appsService,
IWalletAddressService walletService,
@@ -45,7 +46,8 @@ public class UsdtAggregationWorkflowService {
UsdtAggregationTaskMapper taskMapper,
UsdtAggregationTaskItemMapper itemMapper,
WalletOperationEstimateService estimateService,
WalletSigningService walletSigningService) {
WalletSigningService walletSigningService,
WalletLedgerPostingService ledgerPostingService) {
this.appsService = appsService;
this.walletService = walletService;
this.taskService = taskService;
@@ -54,6 +56,7 @@ public class UsdtAggregationWorkflowService {
this.itemMapper = itemMapper;
this.estimateService = estimateService;
this.walletSigningService = walletSigningService;
this.ledgerPostingService = ledgerPostingService;
}
@Transactional(rollbackFor = Exception.class)
@@ -198,11 +201,9 @@ public class UsdtAggregationWorkflowService {
String tx = session.execute(wallet, (tron, api, current) ->
tron.usdtTransWithBroadcastRetry(api, current.getToken(),
item.getDistTokenAddress(), item.getOpeAmount(), MAX_ATTEMPTS));
item.setStatus(1L);
item.setRemark("执行成功;同一签名交易最多广播 " + MAX_ATTEMPTS
+ " 次;交易哈希:" + tx);
item.setUpdatedAt(DateUtils.getNowDate());
itemService.updateById(item);
String successRemark = "执行成功;同一签名交易最多广播 " + MAX_ATTEMPTS
+ " 次;交易哈希:" + tx;
ledgerPostingService.completeAggregationItem(item, wallet, tx, successRemark);
return true;
} catch (Exception ex) {
markFailed(item, "执行失败;同一签名交易已最多广播 " + MAX_ATTEMPTS
@@ -0,0 +1,119 @@
package com.ruoyi.system.service;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.domain.WalletAddressLedger;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.mapper.UsdtOrdersMapper;
import com.ruoyi.system.mapper.WalletAddressLedgerMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* 系统业务流水入账服务。
* 链上广播必须在调用本服务前完成,本服务只负责数据库状态与流水的原子落库。
*/
@Service
public class WalletLedgerPostingService {
private static final long STATUS_PENDING = 1L;
private static final long STATUS_PAID = 2L;
private final UsdtOrdersMapper ordersMapper;
private final WalletAddressLedgerMapper ledgerMapper;
private final IWalletAddressService walletService;
private final IUsdtAggregationTaskItemService aggregationItemService;
public WalletLedgerPostingService(UsdtOrdersMapper ordersMapper,
WalletAddressLedgerMapper ledgerMapper,
IWalletAddressService walletService,
IUsdtAggregationTaskItemService aggregationItemService) {
this.ordersMapper = ordersMapper;
this.ledgerMapper = ledgerMapper;
this.walletService = walletService;
this.aggregationItemService = aggregationItemService;
}
/** 将待支付订单结算为成功,同一订单重复扫描不会重复产生流水。 */
@Transactional(rollbackFor = Exception.class)
public boolean settlePaidOrder(Long orderId, String transactionId) {
UsdtOrdersPlus order = ordersMapper.selectByIdForUpdate(orderId);
if (order == null) {
throw new CustomException("订单不存在");
}
if (Long.valueOf(STATUS_PAID).equals(order.getStatus())) {
return transactionId.equals(order.getBlockTransactionId());
}
if (!Long.valueOf(STATUS_PENDING).equals(order.getStatus())) {
return false;
}
if (ordersMapper.countPaidByTransactionId(transactionId, orderId) > 0) {
return false;
}
WalletAddressPlus wallet = walletService.getByTokenAndAppId(order.getToken(), order.getAppId());
Date now = DateUtils.getNowDate();
WalletAddressLedger ledger = baseLedger(now);
ledger.setTradeNo(order.getTradeId());
ledger.setIdempotencyKey("ORDER_RECEIVE:" + order.getId() + ":USDT");
ledger.setAppId(order.getAppId());
ledger.setUserId(order.getUserId());
ledger.setWalletAddressId(wallet == null ? null : wallet.getId());
ledger.setWalletAddress(order.getToken());
ledger.setCurrency("USDT");
ledger.setBusinessType("ORDER_RECEIVE");
ledger.setDirection(1);
ledger.setAmount(order.getActualAmount());
ledger.setOrderId(order.getId());
ledger.setMerchantOrderId(order.getOrderId());
ledger.setTradeId(order.getTradeId());
ledger.setTransactionId(transactionId);
ledger.setSourceType("ORDER");
ledger.setRemark("订单支付成功");
ledgerMapper.insertSystemLedgerIgnoreDuplicate(ledger);
return ordersMapper.markOrderPaid(order.getId(), transactionId, now) == 1;
}
/** 将已广播成功的归集明细与对应支出流水原子落库。 */
@Transactional(rollbackFor = Exception.class)
public void completeAggregationItem(UsdtAggregationTaskItemPlus item,
WalletAddressPlus wallet, String transactionId, String successRemark) {
Date now = DateUtils.getNowDate();
WalletAddressLedger ledger = baseLedger(now);
ledger.setTradeNo("AGG-" + item.getParentId() + "-" + item.getId());
ledger.setIdempotencyKey("AGGREGATION_OUT:" + item.getId() + ":USDT");
ledger.setAppId(item.getAppId());
ledger.setUserId(item.getUserId());
ledger.setWalletAddressId(wallet.getId());
ledger.setWalletAddress(item.getTokenAddress());
ledger.setCounterpartyAddress(item.getDistTokenAddress());
ledger.setCurrency("USDT");
ledger.setBusinessType("AGGREGATION_OUT");
ledger.setDirection(2);
ledger.setAmount(item.getOpeAmount());
ledger.setAggregationTaskId(item.getParentId());
ledger.setAggregationItemId(item.getId());
ledger.setTransactionId(transactionId);
ledger.setSourceType("AGGREGATION");
ledger.setRemark("USDT归集成功");
ledgerMapper.insertSystemLedgerIgnoreDuplicate(ledger);
item.setStatus(1L);
item.setRemark(successRemark);
item.setUpdatedAt(now);
if (!aggregationItemService.updateById(item)) {
throw new CustomException("归集明细状态更新失败");
}
}
private WalletAddressLedger baseLedger(Date now) {
WalletAddressLedger ledger = new WalletAddressLedger();
ledger.setStatus(1);
ledger.setCreatedAt(now);
ledger.setUpdatedAt(now);
return ledger;
}
}
@@ -1,19 +1,18 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WalletAddressLedger;
import com.ruoyi.system.domain.WalletAddressLedgerPlus;
import com.ruoyi.system.domain.vo.WalletLedgerStatisticsQuery;
import com.ruoyi.system.domain.vo.WalletLedgerStatisticsVo;
import com.ruoyi.system.mapper.WalletAddressLedgerMapper;
import com.ruoyi.system.service.IWalletAddressLedgerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
@@ -28,8 +27,6 @@ public class WalletAddressLedgerServiceImpl extends ServiceImpl<WalletAddressLed
{
@Autowired
private WalletAddressLedgerMapper walletAddressLedgerMapper;
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<WalletAddressLedgerPlus> getByIds(List<Long> ids ,boolean isUser, SFunction<WalletAddressLedgerPlus, ?>... columns) {
@@ -122,48 +119,33 @@ public class WalletAddressLedgerServiceImpl extends ServiceImpl<WalletAddressLed
return this.list(lambdaQueryWrapper);
}
public <T> T sum(String field, String where, Class<T> tClass) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(" sum(" + field + ") as total ");
stringBuffer.append(" from wallet_address_ledger ");
if (StringUtils.isNotBlank(where)) {
stringBuffer.append(" where ");
stringBuffer.append(where);
@Override
public WalletLedgerStatisticsVo statistics(WalletLedgerStatisticsQuery query, boolean isUser) {
WalletLedgerStatisticsQuery safeQuery = query == null
? new WalletLedgerStatisticsQuery() : query;
String granularity = safeQuery.getGranularity();
if (granularity == null || granularity.trim().isEmpty()) {
safeQuery.setGranularity("DAY");
} else {
granularity = granularity.trim().toUpperCase(Locale.ENGLISH);
if (!Arrays.asList("DAY", "MONTH", "YEAR").contains(granularity)) {
throw new CustomException("统计粒度仅支持 DAY、MONTH、YEAR");
}
safeQuery.setGranularity(granularity);
}
T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass);
return result;
}
public Long count(String where) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(" count(1)");
stringBuffer.append(" from ");
stringBuffer.append(" wallet_address_ledger ");
if (StringUtils.isNotBlank(where)) {
stringBuffer.append(" where ");
stringBuffer.append(where);
if (safeQuery.getCurrency() != null && !safeQuery.getCurrency().trim().isEmpty()) {
String currency = safeQuery.getCurrency().trim().toUpperCase(Locale.ENGLISH);
if (!Arrays.asList("USDT", "TRX").contains(currency)) {
throw new CustomException("币种仅支持 USDT、TRX");
}
safeQuery.setCurrency(currency);
}
Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class);
return result;
}
public <T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(select);
stringBuffer.append(" from ");
stringBuffer.append(" wallet_address_ledger ");
if (StringUtils.isNotBlank(where)) {
stringBuffer.append(" where ");
stringBuffer.append(where);
if (isUser) {
safeQuery.setUserId(SecurityUtils.getUserId());
}
stringBuffer.append(" group by ");
stringBuffer.append(groupby);
List result = jdbcTemplate.queryForList(stringBuffer.toString());
List<T> tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass);
return tList;
return new WalletLedgerStatisticsVo(
walletAddressLedgerMapper.selectStatisticsSummary(safeQuery),
walletAddressLedgerMapper.selectStatisticsTrend(safeQuery));
}
/**
* 查询钱包地址资金流水
@@ -175,6 +157,9 @@ public class WalletAddressLedgerServiceImpl extends ServiceImpl<WalletAddressLed
public WalletAddressLedger selectWalletAddressLedgerById(Long id,boolean isUser)
{
WalletAddressLedger vo = walletAddressLedgerMapper.selectWalletAddressLedgerById(id);
if (vo == null) {
throw new CustomException("流水记录不存在");
}
if(isUser){
checkUser(vo);
}
@@ -203,68 +188,4 @@ public class WalletAddressLedgerServiceImpl extends ServiceImpl<WalletAddressLed
return list;
}
/**
* 新增钱包地址资金流水
*
* @param walletAddressLedger 钱包地址资金流水
* @return 结果
*/
@Override
public int insertWalletAddressLedger(WalletAddressLedger walletAddressLedger,boolean isUser)
{
walletAddressLedger.setCreatedAt(DateUtils.getNowDate());
walletAddressLedger.setUpdatedAt(DateUtils.getNowDate());
if(isUser){
walletAddressLedger.setUserId(SecurityUtils.getUserId());
}
return walletAddressLedgerMapper.insertWalletAddressLedger(walletAddressLedger);
}
/**
* 修改钱包地址资金流水
*
* @param walletAddressLedger 钱包地址资金流水
* @return 结果
*/
@Override
public int updateWalletAddressLedger(WalletAddressLedger walletAddressLedger,boolean isUser)
{
walletAddressLedger.setUpdatedAt(DateUtils.getNowDate());
if(isUser){
checkUser(walletAddressLedger);
}
return walletAddressLedgerMapper.updateWalletAddressLedger(walletAddressLedger);
}
/**
* 批量删除钱包地址资金流水
*
* @param ids 需要删除的钱包地址资金流水ID
* @return 结果
*/
@Override
public int deleteWalletAddressLedgerByIds(Long[] ids,boolean isUser)
{
if(isUser){
List<WalletAddressLedgerPlus> list= getByIds(Arrays.asList(ids),false,WalletAddressLedgerPlus::getUserId,WalletAddressLedgerPlus::getId);
checkUserPlus(list);
}
return walletAddressLedgerMapper.deleteWalletAddressLedgerByIds(ids);
}
/**
* 删除钱包地址资金流水信息
*
* @param id 钱包地址资金流水ID
* @return 结果
*/
@Override
public int deleteWalletAddressLedgerById(Long id,boolean isUser)
{
if(isUser){
WalletAddressLedgerPlus vo = getById(id,WalletAddressLedgerPlus::getUserId,WalletAddressLedgerPlus::getId);
checkUser(vo);
}
return walletAddressLedgerMapper.deleteWalletAddressLedgerById(id);
}
}
@@ -50,6 +50,29 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where id = #{id}
</select>
<select id="selectByIdForUpdate" resultType="com.ruoyi.system.domain.UsdtOrdersPlus">
select id, trade_id, order_id, block_transaction_id, actual_amount, amount, token,
status, notify_url, redirect_url, callback_num, callback_confirm, created_at,
updated_at, deleted_at, app_id, settlement_status, user_id, order_type
from orders
where id = #{id}
for update
</select>
<select id="countPaidByTransactionId" resultType="int">
select count(1)
from orders
where block_transaction_id = #{transactionId}
and status = 2
and id != #{excludeOrderId}
</select>
<update id="markOrderPaid">
update orders
set block_transaction_id = #{transactionId}, status = 2, updated_at = #{updatedAt}
where id = #{id} and status = 1
</update>
<insert id="insertUsdtOrders" parameterType="UsdtOrders" useGeneratedKeys="true" keyProperty="id">
insert into orders
<trim prefix="(" suffix=")" suffixOverrides=",">
@@ -86,7 +86,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="errorMessage != null and errorMessage != ''"> and error_message = #{errorMessage}</if>
<if test="createdAt != null "> and created_at = #{createdAt}</if>
<if test="updatedAt != null "> and updated_at = #{updatedAt}</if>
<if test="params.beginTime != null and params.beginTime != ''">
and created_at &gt;= #{params.beginTime}
</if>
<if test="params.endTime != null and params.endTime != ''">
and created_at &lt;= #{params.endTime}
</if>
</where>
order by created_at desc, id desc
</select>
<select id="selectWalletAddressLedgerById" parameterType="Long" resultMap="WalletAddressLedgerResult">
@@ -174,6 +181,61 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</trim>
</insert>
<insert id="insertSystemLedgerIgnoreDuplicate" parameterType="WalletAddressLedger">
insert into wallet_address_ledger
(trade_no, idempotency_key, app_id, user_id, wallet_address_id,
wallet_address, counterparty_address, currency, business_type, direction,
amount, order_id, merchant_order_id, trade_id, aggregation_task_id,
aggregation_item_id, transaction_id, status, source_type, remark,
created_at, updated_at)
values
(#{tradeNo}, #{idempotencyKey}, #{appId}, #{userId}, #{walletAddressId},
#{walletAddress}, #{counterpartyAddress}, #{currency}, #{businessType}, #{direction},
#{amount}, #{orderId}, #{merchantOrderId}, #{tradeId}, #{aggregationTaskId},
#{aggregationItemId}, #{transactionId}, #{status}, #{sourceType}, #{remark},
#{createdAt}, #{updatedAt})
on duplicate key update id = id
</insert>
<sql id="statisticsConditions">
status = 1
<if test="appId != null">and app_id = #{appId}</if>
<if test="userId != null">and user_id = #{userId}</if>
<if test="currency != null and currency != ''">and currency = #{currency}</if>
<if test="beginTime != null">and created_at &gt;= #{beginTime}</if>
<if test="endTime != null">and created_at &lt;= #{endTime}</if>
</sql>
<select id="selectStatisticsSummary" resultType="com.ruoyi.system.domain.vo.WalletLedgerSummaryVo">
select currency,
coalesce(sum(case when direction = 1 then amount else 0 end), 0) as incomeAmount,
coalesce(sum(case when direction = 2 then amount else 0 end), 0) as expenseAmount,
coalesce(sum(case when direction = 1 then amount else -amount end), 0) as netAmount,
count(1) as count
from wallet_address_ledger
where <include refid="statisticsConditions"/>
group by currency
order by currency
</select>
<select id="selectStatisticsTrend" resultType="com.ruoyi.system.domain.vo.WalletLedgerTrendVo">
select
<choose>
<when test="granularity == 'YEAR'">date_format(created_at, '%Y')</when>
<when test="granularity == 'MONTH'">date_format(created_at, '%Y-%m')</when>
<otherwise>date_format(created_at, '%Y-%m-%d')</otherwise>
</choose> as period,
currency,
coalesce(sum(case when direction = 1 then amount else 0 end), 0) as incomeAmount,
coalesce(sum(case when direction = 2 then amount else 0 end), 0) as expenseAmount,
coalesce(sum(case when direction = 1 then amount else -amount end), 0) as netAmount,
count(1) as count
from wallet_address_ledger
where <include refid="statisticsConditions"/>
group by period, currency
order by period, currency
</select>
<update id="updateWalletAddressLedger" parameterType="WalletAddressLedger">
update wallet_address_ledger
<trim prefix="SET" suffixOverrides=",">
+11
View File
@@ -0,0 +1,11 @@
-- 钱包流水幂等与报表查询索引。
-- 执行前请先通过 SHOW INDEX FROM wallet_address_ledger 核对生产库是否已有等价索引。
ALTER TABLE `wallet_address_ledger`
MODIFY COLUMN `amount` DECIMAL(30,6) NOT NULL COMMENT '变动金额,始终为正数',
MODIFY COLUMN `balance_before` DECIMAL(30,6) NULL COMMENT '操作前链上余额',
MODIFY COLUMN `balance_after` DECIMAL(30,6) NULL COMMENT '操作后链上余额',
MODIFY COLUMN `fee_amount` DECIMAL(30,6) NULL COMMENT '实际手续费',
MODIFY COLUMN `burned_trx` DECIMAL(30,6) NULL COMMENT '资源不足燃烧的TRX',
ADD UNIQUE KEY `uk_wallet_ledger_idempotency` (`idempotency_key`),
ADD KEY `idx_wallet_ledger_app_time` (`app_id`, `created_at`),
ADD KEY `idx_wallet_ledger_address_time` (`wallet_address`, `created_at`);