package com.ruoyi.system.rental; import static com.ruoyi.system.rental.RentalValues.*; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.SecurityUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.*; /** 登录业务入口。输入仅提取命令字段,不把客户端对象直接映射为数据库实体。 */ @RestController @RequestMapping("/rental") public class RentalController { private final RentalStore store; private final RentalProvisioning provisioning; private final RentalIdentity identity; private final RentalOrders orders; private final RentalFunds funds; private final RentalReviews reviews; private final RentalTasks tasks; private final RentalChain chain; private final RentalQueries queries; @Value("${rental.deposit-address.nile:}") private String nileDeposit; @Value("${rental.deposit-address.mainnet:}") private String mainDeposit; @org.springframework.beans.factory.annotation.Autowired private RentalReconciliation reconciliation; @org.springframework.beans.factory.annotation.Autowired private RentalPackageBindings packageBindings; /** 同一套餐管理权限负责授权;普通租赁用户不能自行添加绑定。 */ @PostMapping("/package/bind") @PreAuthorize("@ss.hasPermi('rent:package:edit')") public AjaxResult bindPackage(@RequestBody Map body) { require(body.get("enabled") instanceof Boolean && body.get("is_default") instanceof Boolean, "必须明确绑定状态及是否默认"); packageBindings.bind(number(body, "user_id"), number(body, "package_id"), Boolean.TRUE.equals(body.get("enabled")), Boolean.TRUE.equals(body.get("is_default")), user()); return AjaxResult.success(); } @GetMapping("/package/bindings/{userId}") @PreAuthorize("@ss.hasPermi('rent:package:edit')") public AjaxResult userPackageBindings(@PathVariable long userId) { return AjaxResult.success(packageBindings.list(userId)); } @GetMapping("/package/bindings") @PreAuthorize("@ss.hasPermi('rent:portal:view')") public AjaxResult myPackageBindings() { return AjaxResult.success(packageBindings.list(user())); } /** 用户选择器复用套餐管理权限,不额外开放系统用户管理权限。 */ @GetMapping("/package/users") @PreAuthorize("@ss.hasPermi('rent:package:edit')") public AjaxResult packageUsers(@RequestParam(defaultValue = "") String keyword) { require(keyword.length() <= 100, "搜索内容过长"); return AjaxResult.success(store.rows("SELECT user_id,user_name,nick_name FROM sys_user" + " WHERE del_flag='0' AND status='0' AND (user_name LIKE ? OR nick_name LIKE ?)" + " ORDER BY user_id LIMIT 30", "%" + keyword + "%", "%" + keyword + "%")); } @GetMapping("/package/options") @PreAuthorize("@ss.hasPermi('rent:package:edit')") public AjaxResult packageOptions(@RequestParam(defaultValue = "") String keyword) { require(keyword.length() <= 100, "搜索内容过长"); return AjaxResult.success(store.rows("SELECT id,name,network,resource_type,revision FROM rent_package" + " WHERE status='ACTIVE' AND (name LIKE ? OR package_code LIKE ?) ORDER BY id DESC LIMIT 30", "%" + keyword + "%", "%" + keyword + "%")); } public RentalController( RentalStore store, RentalProvisioning provisioning, RentalIdentity identity, RentalOrders orders, RentalFunds funds, RentalReviews reviews, RentalTasks tasks, RentalChain chain, RentalQueries queries) { this.store = store; this.provisioning = provisioning; this.identity = identity; this.orders = orders; this.funds = funds; this.reviews = reviews; this.tasks = tasks; this.chain = chain; this.queries = queries; } private long user() { Long user = SecurityUtils.getUserId(); require(user != null, "请先登录"); return user; } @GetMapping("/mine/{resource}") @PreAuthorize("@ss.hasPermi('rent:portal:view')") public AjaxResult mine( @PathVariable String resource, @RequestParam(defaultValue = "1") int page, @RequestParam(required = false) String status, @RequestParam(required = false) String network, @RequestParam(required = false, name = "resource_type") String resourceType, @RequestParam(required = false) String keyword) { return AjaxResult.success(queries.list(resource, user(), page, status, network, resourceType, keyword)); } /** 本人应用详情;显式选列,禁止返回明文或加密 Secret。 */ @GetMapping("/app/{id}") @PreAuthorize("@ss.hasPermi('rent:portal:view')") public AjaxResult appDetail(@PathVariable long id) { Map app = store.one( "SELECT id,name,status,notify_url,ip_whitelist,created_at,updated_at FROM rent_app WHERE id=? AND user_id=?", id, user()); require(app != null, "应用不存在或无权访问"); // DATETIME(3) 约定存服务器本地时间;统一输出毫秒,避免驱动返回 Timestamp/LocalDateTime 的差异。 for (String field : Arrays.asList("created_at", "updated_at")) { if (app.get(field) != null) { app.put(field, time(app.get(field)).toEpochMilli()); } } List> credentials = store.rows( "SELECT id,api_key,status,expires_at,created_at FROM rent_credential" + " WHERE owner_type='APP' AND owner_id=? ORDER BY id DESC", id); for (Map credential : credentials) { for (String field : Arrays.asList("created_at", "expires_at")) { if (credential.get(field) != null) { credential.put(field, time(credential.get(field)).toEpochMilli()); } } } return AjaxResult.success(map("app", app, "credentials", credentials)); } /** 商户只能维护本人应用,白名单不是商户外部API,避免配置错误后无法修复。 */ @PostMapping("/app/{id}/ip-whitelist") @PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:app:create') or @ss.hasPermi('rent:app:edit')") public AjaxResult updateAppIpWhitelist(@PathVariable long id, @RequestBody Map body) { require(body.containsKey("ip_whitelist"), "缺少IP白名单配置"); provisioning.updateAppIpWhitelist(id, text(body, "ip_whitelist"), user()); return AjaxResult.success(); } /** 运营配置入口与商户入口分离,不能通过提交应用ID越权。 */ @PostMapping("/manage/app/{id}/ip-whitelist") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult manageAppIpWhitelist(@PathVariable long id, @RequestBody Map body) { require(body.containsKey("ip_whitelist"), "缺少IP白名单配置"); provisioning.updateAppIpWhitelist(id, text(body, "ip_whitelist"), null); return AjaxResult.success(); } /** 仅允许删除本人未产生业务关联的空应用。 */ @DeleteMapping("/app/{id}") @PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:app:remove')") public AjaxResult removeApp(@PathVariable long id) { provisioning.deleteApp(id, user()); return AjaxResult.success(); } @GetMapping("/manage/{resource}") @PreAuthorize("@ss.hasPermi('rent:manage:list')") public AjaxResult manage( @PathVariable String resource, @RequestParam(defaultValue = "1") int page, @RequestParam(required = false) String status, @RequestParam(required = false) String network, @RequestParam(required = false, name = "resource_type") String resourceType, @RequestParam(required = false) String keyword) { return AjaxResult.success(queries.list(resource, null, page, status, network, resourceType, keyword)); } @PostMapping("/register/{resource}") @PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:' + #resource + ':create')") public AjaxResult register( @PathVariable String resource, @RequestBody Map body) { return AjaxResult.success(provisioning.create(resource, body, user())); } @PostMapping("/credential/issue") @PreAuthorize("@ss.hasPermi('rent:credential:issue')") public AjaxResult issue(@RequestBody Map body) { return AjaxResult.success( identity.issue(input(body, "owner_type", 8), number(body, "owner_id"), user())); } @PostMapping("/credential/{id}/revoke") @PreAuthorize("@ss.hasPermi('rent:credential:issue')") public AjaxResult revoke(@PathVariable long id) { identity.revoke(id, user()); return AjaxResult.success(); } /** 删除未使用的本人应用凭证,不能绕过历史引用保护。 */ @DeleteMapping("/credential/{id}") @PreAuthorize("@ss.hasPermi('rent:credential:issue')") public AjaxResult removeCredential(@PathVariable long id) { identity.deleteAppCredential(id, user()); return AjaxResult.success(); } /** 本人节点及绑定钱包详情,显式选列保护认证材料。 */ @GetMapping("/node/{id}") @PreAuthorize("@ss.hasPermi('rent:portal:view')") public AjaxResult nodeDetail(@PathVariable long id) { Map node = store.one("SELECT id,node_no,name,status,connection_status,heartbeat_at FROM rent_node WHERE id=? AND user_id=?", id, user()); require(node != null, "节点不存在或无权访问"); if (node.get("heartbeat_at") != null) { node.put("heartbeat_at", time(node.get("heartbeat_at")).toEpochMilli()); } // 按节点查询而非在全量钱包的第一页过滤;显式选列不输出挑战或签名。 List> wallets = store.rows("SELECT id,node_id,network,address,status,ownership_verified_at," + "energy_enabled,bandwidth_enabled,energy_retain_sun,bandwidth_retain_sun FROM rent_wallet WHERE node_id=? ORDER BY id", id); return AjaxResult.success(map("node", node, "wallets", wallets)); } /** 本人离线节点换绑,旧钱包历史关联与新地址合法性在事务内校验。 */ @PostMapping("/wallet/{id}/rebind") @PreAuthorize("@ss.hasPermi('rent:wallet:bind')") public AjaxResult rebindWallet(@PathVariable long id, @RequestBody Map body) { provisioning.rebindWallet(id, body, user()); return AjaxResult.success(); } /** 删除本人尚未完成所有权验证的待审核地址。 */ @DeleteMapping("/wallet/{id}") @PreAuthorize("@ss.hasPermi('rent:wallet:bind')") public AjaxResult removeWallet(@PathVariable long id) { provisioning.deletePendingWallet(id, user()); return AjaxResult.success(); } @PostMapping("/wallet/{id}/challenge") @PreAuthorize("@ss.hasPermi('rent:wallet:bind')") public AjaxResult challenge(@PathVariable long id) { return AjaxResult.success(provisioning.challenge(id, user())); } @PostMapping("/wallet/{id}/prove") @PreAuthorize("@ss.hasPermi('rent:wallet:bind')") public AjaxResult prove(@PathVariable long id, @RequestBody Map body) { provisioning.prove(id, input(body, "nonce", 64), input(body, "signature", 256), user()); return AjaxResult.success(); } @PostMapping("/wallet/{id}/policy") @PreAuthorize("@ss.hasPermi('rent:wallet:bind')") public AjaxResult policy(@PathVariable long id, @RequestBody Map body) { provisioning.policy(id, body, user()); return AjaxResult.success(); } @PostMapping("/package") @PreAuthorize("@ss.hasPermi('rent:package:edit')") public AjaxResult product(@RequestBody Map body) { return AjaxResult.success(provisioning.product(body, user())); } @PostMapping("/status/{resource}/{id}") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult status( @PathVariable String resource, @PathVariable long id, @RequestBody Map body) { provisioning.status( resource, id, input(body, "status", 32), user(), input(body, "reason", 512)); return AjaxResult.success(); } @PostMapping("/order") @PreAuthorize("@ss.hasPermi('rent:order:create')") public AjaxResult order(@RequestBody Map body) { Map order = orders.createByResource(number(body, "app_id"), user(), body); return AjaxResult.success( map( "id", order.get("id"), "order_no", order.get("order_no"), "status", order.get("status"))); } @PostMapping("/order/{id}/cancel") @PreAuthorize("@ss.hasPermi('rent:order:create')") public AjaxResult cancel(@PathVariable long id) { orders.cancel(id, user()); return AjaxResult.success(); } @PostMapping("/account/open") @PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:account:open')") public AjaxResult account(@RequestBody Map body) { return AjaxResult.success(funds.account(user(), input(body, "network", 16))); } @PostMapping("/account/{id}/topup") @PreAuthorize("@ss.hasPermi('rent:account:topup')") public AjaxResult topup(@PathVariable long id, @RequestBody Map body) { Map account = store.get("account", id, false); String network = text(account, "network"); String deposit = "NILE".equals(network) ? nileDeposit : mainDeposit; require(!deposit.isEmpty(), "尚未配置该网络租赁充值收款地址"); java.math.BigDecimal amount = money(body.get("amount")); require(amount.signum() > 0, "充值金额必须大于0"); Map proof = chain.transfer( network, input(body, "tx_id", 64), (int) number(body, "log_index"), deposit, amount); String reason = input(body, "reason", 512); long actor = user(); tasks.tx( () -> { funds.post( id, "TOPUP:" + text(proof, "reference"), "TOPUP", amount, ZERO, ZERO, ZERO, null, null, null, actor, text(proof, "reference"), reason); store.event("ACCOUNT", id, "TOPUP", actor, reason); return null; }); return AjaxResult.success(); } @PostMapping("/order/{id}/refund") @PreAuthorize("@ss.hasPermi('rent:refund:create')") public AjaxResult refund(@PathVariable long id, @RequestBody Map body) { return AjaxResult.success(reviews.refund(id, body, user())); } @PostMapping("/refund/{id}/review") @PreAuthorize("@ss.hasPermi('rent:refund:approve')") public AjaxResult reviewRefund(@PathVariable long id, @RequestBody Map body) { require(body.get("approve") instanceof Boolean, "必须明确审批结果"); reviews.approveRefund(id, Boolean.TRUE.equals(body.get("approve")), user()); return AjaxResult.success(); } @PostMapping("/settlement") @PreAuthorize("@ss.hasPermi('rent:settlement:create')") public AjaxResult settlement(@RequestBody Map body) { require(body.get("order_ids") instanceof List, "缺少来源订单"); List ids = new ArrayList<>(); for (Object value : (List) body.get("order_ids")) { ids.add(Long.valueOf(value.toString())); } return AjaxResult.success(reviews.settlement(ids, user())); } @PostMapping("/settlement/{id}/{action}") @PreAuthorize("@ss.hasPermi('rent:settlement:approve')") public AjaxResult settlementAction( @PathVariable long id, @PathVariable String action, @RequestBody Map body) { String reason = input(body, "reason", 512); long actor = user(); if ("confirm".equals(action)) { Map row = store.get("settlement", id, false), account = store.get("account", number(row, "account_id"), false); Map authorization; require("LEGACY_PAYOUT".equals(text(row, "settlement_mode")), "收益结算不接受链上付款登记,请使用提现功能"); try { authorization = new com.fasterxml.jackson.databind.ObjectMapper() .readValue(text(row, "payment_evidence"), Map.class); } catch (Exception ex) { throw new IllegalArgumentException("缺少原付款授权收款地址"); } Map proof = chain.transfer( text(account, "network"), input(body, "tx_id", 64), (int) number(body, "log_index"), text(authorization, "receiver_address"), amount(row, "amount")); reviews.paid(id, text(proof, "reference"), orders.encode(proof), actor); return AjaxResult.success(); } return AjaxResult.success( tasks.tx( () -> { Map row = reviews.transition(id, action, actor, reason); if ("pay".equals(action) && row.get("payment_evidence") == null) { String receiver = input(body, "receiver_address", 64); RentalOrders.address(receiver); store.update( "settlement", id, map( "payment_evidence", orders.encode( map( "receiver_address", receiver, "payout_no", text(row, "payout_no"))))); row = store.get("settlement", id, false); } return row; })); } @PostMapping("/wallet/{id}/refresh") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult refresh(@PathVariable long id) { tasks.refresh(id); return AjaxResult.success(); } @PostMapping("/task/{id}/verify") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult verify(@PathVariable long id) { tasks.verify(id); return AjaxResult.success(); } @PostMapping("/task/{id}/attach") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult attach(@PathVariable long id, @RequestBody Map body) { tasks.attach(id, input(body, "tx_id", 64), user(), input(body, "reason", 512)); return AjaxResult.success(); } @PostMapping("/order/{id}/resolve") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult resolve(@PathVariable long id, @RequestBody Map body) { tasks.resolveRecovered(id, user(), input(body, "reason", 512)); return AjaxResult.success(); } @PostMapping("/webhook/{id}/retry") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult retryWebhook(@PathVariable long id, @RequestBody Map body) { String reason = input(body, "reason", 512); long actor = user(); tasks.tx( () -> { Map row = store.get("webhook", id, true); require("DEAD".equals(text(row, "status")), "只允许人工重新投递已终止的事件"); store.event( "ORDER", number(row, "order_id"), "RETRY_WEBHOOK", actor, reason + ";原重试次数=" + text(row, "attempt_count")); store.update( "webhook", id, map( "status", "PENDING", "attempt_count", 0, "next_attempt_at", now(), "lock_owner", null, "lock_until", null)); return null; }); return AjaxResult.success(); } @GetMapping("/reconcile") @PreAuthorize("@ss.hasPermi('rent:manage:audit')") public AjaxResult reconcile(@RequestParam(defaultValue = "0") long afterId) { require(afterId >= 0, "核对游标不能为负"); return AjaxResult.success( map( "accounts", reconciliation.check(afterId), "reservations", reconciliation.reservations())); } }