package com.ruoyi.system.rental; import static com.ruoyi.system.rental.RentalValues.*; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.tron.trident.core.ApiWrapper; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Map; /** 下单、冻结、取消与业务回调入队;外部接口与登录接口复用同一套事务规则。 */ @Service public class RentalOrders { private final RentalStore store; private final RentalFunds funds; private final ObjectMapper json; public RentalOrders(RentalStore store, RentalFunds funds, ObjectMapper json) { this.store = store; this.funds = funds; this.json = json; } public static void address(String address) { try { require( address.startsWith("T") && ApiWrapper.parseAddress(address).size() == 21, "地址不合法"); } catch (Exception ex) { throw new IllegalArgumentException("TRON地址校验失败"); } } @Transactional(rollbackFor = Exception.class) public Map create(long appId, long user, Map request) { // 锁应用行使同应用幂等竞争顺序化;不能仅依靠先查后插。 Map app = store.get("app", appId, true); require( number(app, "user_id") == user && "ACTIVE".equals(text(app, "status")), "应用无权限或已禁用"); String merchant = input(request, "merchant_order_no", 64); String receiver = input(request, "receiver_address", 64); address(receiver); Map existing = store.one( "SELECT * FROM rent_order WHERE app_id=? AND merchant_order_no=?", appId, merchant); long packageId; if (request.containsKey("package_id") && !text(request, "package_id").isEmpty()) { packageId = number(request, "package_id"); } else if (existing != null) { // 默认套餐变更后,幂等重试仍关联原订单版本,不重新扣款。 packageId = number(existing, "package_id"); } else { Map binding = store.one("SELECT package_id FROM rent_user_package" + " WHERE user_id=? AND status='ACTIVE' AND default_slot=1", number(app, "user_id")); require(binding != null, "该应用所属用户尚未设置默认套餐,请联系管理员绑定,或选择已绑定套餐"); packageId = number(binding, "package_id"); } String notify = text(request, "notify_url").trim(); if (notify.isEmpty()) { notify = text(app, "notify_url"); } if (!notify.isEmpty()) { RentalHttp.checkUrl(notify); } String hash = RentalCrypto.sha256( encode( map( "package_id", packageId, "receiver_address", receiver, "notify_url", notify))); // 兼容旧订单请求摘要;只有显式指定租期时才附加租期,重试不得改变租期。 if (request.containsKey("duration_seconds")) { hash = RentalCrypto.sha256(hash + ":" + number(request, "duration_seconds")); } // 保留未提交资源数量的旧摘要;同单号不能更改资源数量重新冻结资金。 if (request.containsKey("resource_quantity")) { hash = RentalCrypto.sha256(hash + ":resource_quantity:" + number(request, "resource_quantity")); } if (existing != null) { require(hash.equals(text(existing, "request_hash")), "同一商户订单号参数不一致"); return existing; } Map product = store.get("package", packageId, true); validatePackage(product); require("ACTIVE".equals(text(product, "status")), "套餐未上架"); Map binding = store.one("SELECT * FROM rent_user_package" + " WHERE user_id=? AND package_id=? AND status='ACTIVE' AND default_slot=1 FOR UPDATE", number(app, "user_id"), packageId); require(binding != null, "该套餐未绑定到应用所属用户或绑定已停用"); if (request.containsKey("network")) { require(text(product, "network").equals(text(request, "network")), "套餐网络与请求不符"); } product.put("binding_id", binding.get("id")); product.put("binding_user_id", app.get("user_id")); if (request.containsKey("resource_type")) { require( text(product, "resource_type").equals(text(request, "resource_type")), "资源类型与套餐不符"); } product = RentalPricing.price(product, request); if (request.containsKey("expected_amount")) { require(amount(product, "sale_amount").compareTo(amount(request, "expected_amount")) == 0, "套餐价格已变更,请重新获取报价后确认"); } Map account = funds.account(user, network(text(product, "network"))); account = store.get("account", number(account, "id"), true); require("ACTIVE".equals(text(account, "status")), "租赁账户已冻结"); BigDecimal gross = amount(product, "supplier_amount"); BigDecimal fee = gross.multiply(new BigDecimal(text(product, "supplier_fee_percent"))) .movePointLeft(2) .setScale(6, RoundingMode.HALF_UP); Map order = map( "order_no", id("RO"), "app_id", appId, "merchant_order_no", merchant, "request_hash", hash, "package_id", packageId, "billing_mode", text(product, "billing_mode").isEmpty() ? "DURATION" : text(product, "billing_mode"), "network", text(product, "network"), "receiver_address", receiver, "resource_type", text(product, "resource_type"), "resource_quantity", number(product, "resource_quantity"), "redundancy_percent", product.get("redundancy_percent"), "target_resource_quantity", target( number(product, "resource_quantity"), new BigDecimal(text(product, "redundancy_percent"))), "duration_seconds", number(product, "duration_seconds"), "sale_amount", amount(product, "sale_amount"), "supplier_amount", gross, "supplier_fee_percent", product.get("supplier_fee_percent"), "supplier_fee_amount", fee, "supplier_net_amount", gross.subtract(fee), "package_snapshot", encode(product), "status", "WAITING", "payer_account_id", number(account, "id"), "fund_status", "HELD", "dispatch_deadline", after(300), "reclaim_status", "NOT_STARTED", "notify_url", notify.isEmpty() ? null : notify); long id = store.insert("order", order); order.put("id", id); funds.hold(order); store.event("ORDER", id, "CREATE", user, "创建订单并冻结内部USDT"); return store.get("order", id, false); } public static void validatePackage(Map row) { network(text(row, "network")); resource(text(row, "resource_type")); target(number(row, "resource_quantity"), new BigDecimal(text(row, "redundancy_percent"))); BigDecimal sale = amount(row, "sale_amount"); BigDecimal gross = amount(row, "supplier_amount"); BigDecimal percent = new BigDecimal(text(row, "supplier_fee_percent")); BigDecimal fee = gross.multiply(percent).movePointLeft(2).setScale(6, RoundingMode.HALF_UP); require( (text(row, "billing_mode").isEmpty() || "DURATION".equals(text(row, "billing_mode")) || "PER_ORDER".equals(text(row, "billing_mode"))) && sale.signum() > 0 && gross.signum() > 0 && gross.compareTo(sale) <= 0 && percent.signum() > 0 && percent.compareTo(new BigDecimal("100")) < 0 && fee.signum() > 0 && fee.compareTo(gross) < 0, "套餐售价或供应商费率无效"); require( number(row, "duration_seconds") > 0 && number(row, "fee_limit_sun") > 0 && number(row, "delegate_lock") == 0, "首版仅支持非锁定委托,租期和本地费用预算必须为正"); require(row.get("rules") != null && !text(row, "rules").isEmpty(), "必须配置套餐规则"); } @Transactional(rollbackFor = Exception.class) public void cancel(long orderId, long user) { Map order = store.get("order", orderId, true); Map app = store.get("app", number(order, "app_id"), false); require(number(app, "user_id") == user, "无订单权限"); if ("CANCELLED".equals(text(order, "status"))) { return; } require( "WAITING".equals(text(order, "status")) && store.one("SELECT id FROM rent_task WHERE order_id=? LIMIT 1", orderId) == null, "已创建执行任务,不可取消或重派"); funds.release(order); store.update("order", orderId, map("status", "CANCELLED")); webhook(order, "CANCELLED", "ORDER:" + orderId + ":CANCELLED"); store.event("ORDER", orderId, "CANCEL", user, "未派单取消"); } public void webhook(Map order, String type, String key) { long orderId = number(order, "id"); if (store.one("SELECT id FROM rent_webhook WHERE event_key=?", key) != null) { return; } Map last = store.one( "SELECT COALESCE(MAX(order_event_sequence),0) AS seq FROM rent_webhook" + " WHERE order_id=?", orderId); long seq = number(last, "seq") + 1; String event = id("WH"); store.insert( "webhook", map( "event_no", event, "order_id", orderId, "event_type", type, "event_key", key, "order_event_sequence", seq, "payload", encode( map( "event_no", event, "event_type", type, "order_event_sequence", seq, "order_no", text(order, "order_no"), "merchant_order_no", text(order, "merchant_order_no"), "network", text(order, "network"), "resource_type", text(order, "resource_type"), "resource_quantity", number(order, "resource_quantity"), "amount", text(order, "sale_amount"), "refunded_amount", text(order, "refunded_amount"))), "status", "PENDING", "next_attempt_at", now())); } public String encode(Object value) { try { return json.writeValueAsString(value); } catch (Exception ex) { throw new IllegalArgumentException("业务数据序列化失败"); } } }