feat: add admin panel with multi-chain support and notification system

- Add full admin REST API: auth, API keys, chains, chain tokens, wallets,
  orders, RPC nodes, settings, dashboard stats, notifications
- Add JWT-based admin authentication and API key auth middleware
- Add multi-chain listeners: BSC, ETH, Polygon, Plasma, EVM WebSocket
- Add RPC node health check job with automatic failover
- Add Telegram notification channel for order events
- Add installer for first-run database initialization
- Add new DB models: admin_user, api_key, chain, chain_token,
  rpc_node, settings, notification_channel
- Add order statistics aggregation (daily/monthly/by-chain)
- Serve built admin SPA from embedded www/ assets
- Add comprehensive test coverage for all new features
This commit is contained in:
line-6000
2026-04-22 02:28:31 +08:00
parent 097c716714
commit 6bb47d4b00
247 changed files with 9933 additions and 1279 deletions
+310
View File
@@ -0,0 +1,310 @@
package admin
import (
"crypto/rand"
"encoding/hex"
"errors"
"strconv"
"strings"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/labstack/echo/v4"
)
// CreateApiKeyRequest is the payload for creating an API key.
// A single key is valid for both gateway flows (epay/gmpay); there is
// no gateway_type. PID is auto-generated (incrementing from 1000);
// no manual override.
type CreateApiKeyRequest struct {
Name string `json:"name" validate:"required|maxLen:128" example:"My API Key"`
IpWhitelist string `json:"ip_whitelist" example:""`
NotifyUrl string `json:"notify_url" example:"https://example.com/notify"`
}
// CreateApiKeyResponse is the response for a newly created API key.
type CreateApiKeyResponse struct {
ID uint64 `json:"id" example:"1"`
Name string `json:"name" example:"My API Key"`
Pid string `json:"pid" example:"1003"`
// SecretKey is returned ONCE on creation. After that, fetch via
// GET /api-keys/:id/secret or rotate to generate a new one.
SecretKey string `json:"secret_key" example:"secret123abc456"`
}
// UpdateApiKeyRequest is the payload for updating an API key.
type UpdateApiKeyRequest struct {
Name *string `json:"name" example:"Updated Key Name"`
IpWhitelist *string `json:"ip_whitelist" example:"10.0.0.1,192.168.0.0/24"`
NotifyUrl *string `json:"notify_url" example:"https://example.com/notify"`
}
// ChangeApiKeyStatusRequest is the payload for toggling API key status.
type ChangeApiKeyStatusRequest struct {
// 状态 1=启用 2=禁用
Status int `json:"status" validate:"required|in:1,2" enums:"1,2" example:"1"`
}
// ListApiKeys returns all api_keys rows. SecretKey is stripped by the
// mdb.ApiKey json tag (`json:"-"`).
// @Summary List API keys
// @Description Returns all API keys
// @Tags Admin API Keys
// @Security AdminJWT
// @Produce json
// @Success 200 {object} response.ApiResponse{data=[]mdb.ApiKey}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys [get]
func (c *BaseAdminController) ListApiKeys(ctx echo.Context) error {
rows, err := data.ListApiKeys()
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// CreateApiKey mints a new universal key. PID is auto-incremented from
// the highest existing numeric PID (starting at 1000). Secret is
// randomly generated and returned once.
// @Summary Create API key
// @Description Create a new universal API key. Usable for both gateway flows (epay/gmpay). PID auto-incremented; secret returned once.
// @Tags Admin API Keys
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.CreateApiKeyRequest true "API key payload"
// @Success 200 {object} response.ApiResponse{data=admin.CreateApiKeyResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys [post]
func (c *BaseAdminController) CreateApiKey(ctx echo.Context) error {
req := new(CreateApiKeyRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
// Retry on unique-index violation: two concurrent creates could
// both see the same max PID from NextPid() and race on INSERT.
// The loser re-reads and retries with the now-higher max.
const maxAttempts = 5
secret := randomHex(32)
var row *mdb.ApiKey
for attempt := 0; attempt < maxAttempts; attempt++ {
pid, err := data.NextPid()
if err != nil {
return c.FailJson(ctx, err)
}
row = &mdb.ApiKey{
Name: req.Name,
Pid: strconv.Itoa(pid),
SecretKey: secret,
IpWhitelist: req.IpWhitelist,
NotifyUrl: req.NotifyUrl,
Status: mdb.ApiKeyStatusEnable,
}
err = data.CreateApiKey(row)
if err == nil {
break
}
if attempt == maxAttempts-1 || !isUniqueViolation(err) {
return c.FailJson(ctx, err)
}
}
return c.SucJson(ctx, CreateApiKeyResponse{
ID: row.ID,
Name: row.Name,
Pid: row.Pid,
SecretKey: secret,
})
}
// isUniqueViolation matches the driver-specific strings for a unique-
// index collision across SQLite / MySQL / PostgreSQL. Good enough for
// the PID retry loop; a cleaner approach would be a typed error but
// GORM doesn't surface one portably.
func isUniqueViolation(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "unique") ||
strings.Contains(msg, "duplicate") ||
strings.Contains(msg, "constraint failed")
}
// UpdateApiKey patches name / ip_whitelist / notify_url. Secret rotation
// and enable/disable have their own endpoints.
// @Summary Update API key
// @Description Patch API key name / ip_whitelist / notify_url
// @Tags Admin API Keys
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "API key ID"
// @Param request body admin.UpdateApiKeyRequest true "Fields to update"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys/{id} [patch]
func (c *BaseAdminController) UpdateApiKey(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(UpdateApiKeyRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
fields := map[string]interface{}{}
if req.Name != nil {
fields["name"] = *req.Name
}
if req.IpWhitelist != nil {
fields["ip_whitelist"] = *req.IpWhitelist
}
if req.NotifyUrl != nil {
fields["notify_url"] = *req.NotifyUrl
}
if err := data.UpdateApiKeyFields(id, fields); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// ChangeApiKeyStatus toggles enable/disable.
// @Summary Change API key status
// @Description Toggle enable/disable for an API key (1=enabled, 2=disabled)
// @Tags Admin API Keys
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "API key ID"
// @Param request body admin.ChangeApiKeyStatusRequest true "Status payload"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys/{id}/status [post]
func (c *BaseAdminController) ChangeApiKeyStatus(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(ChangeApiKeyStatusRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
if err := data.UpdateApiKeyFields(id, map[string]interface{}{"status": req.Status}); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// RotateApiKeySecret issues a fresh secret_key. Returned only this time.
// @Summary Rotate API key secret
// @Description Generate a new secret_key. Returned only once.
// @Tags Admin API Keys
// @Security AdminJWT
// @Produce json
// @Param id path int true "API key ID"
// @Success 200 {object} response.ApiResponse{data=admin.RotateSecretResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys/{id}/rotate-secret [post]
func (c *BaseAdminController) RotateApiKeySecret(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
secret := randomHex(32)
if err := data.UpdateApiKeyFields(id, map[string]interface{}{"secret_key": secret}); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, map[string]string{"secret_key": secret})
}
// DeleteApiKey soft-deletes a row. Orders created with this key will
// fail to callback (resolveOrderApiKey returns a clear error) — prefer
// disabling via /status over deletion if there are live orders.
// @Summary Delete API key
// @Description Soft-delete an API key
// @Tags Admin API Keys
// @Security AdminJWT
// @Produce json
// @Param id path int true "API key ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys/{id} [delete]
func (c *BaseAdminController) DeleteApiKey(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
if err := data.DeleteApiKeyByID(id); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// GetApiKeyStats returns usage stats for one key. Currently thin — just
// the stored call_count and last_used_at — since we don't persist per-
// call telemetry. Expanded later if/when we add a request log table.
// @Summary Get API key stats
// @Description Returns usage stats (call_count, last_used_at) for an API key
// @Tags Admin API Keys
// @Security AdminJWT
// @Produce json
// @Param id path int true "API key ID"
// @Success 200 {object} response.ApiResponse{data=admin.ApiKeyStatsResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys/{id}/stats [get]
func (c *BaseAdminController) GetApiKeyStats(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
row, err := data.GetApiKeyByID(id)
if err != nil {
return c.FailJson(ctx, err)
}
if row.ID == 0 {
return c.FailJson(ctx, errors.New("api key not found"))
}
return c.SucJson(ctx, map[string]interface{}{
"call_count": row.CallCount,
"last_used_at": row.LastUsedAt,
})
}
// GetApiKeySecret returns the secret_key for one API key. Requires
// admin JWT authentication.
// @Summary View API key secret
// @Description Returns the secret_key for an API key (admin only)
// @Tags Admin API Keys
// @Security AdminJWT
// @Produce json
// @Param id path int true "API key ID"
// @Success 200 {object} response.ApiResponse{data=map[string]string}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/api-keys/{id}/secret [get]
func (c *BaseAdminController) GetApiKeySecret(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
row, err := data.GetApiKeyByID(id)
if err != nil {
return c.FailJson(ctx, err)
}
if row.ID == 0 {
return c.FailJson(ctx, errors.New("api key not found"))
}
return c.SucJson(ctx, map[string]string{"secret_key": row.SecretKey})
}
func randomHex(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
+157
View File
@@ -0,0 +1,157 @@
package admin
import (
"errors"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
appjwt "github.com/assimon/luuu/util/jwt"
"github.com/labstack/echo/v4"
)
// LoginRequest is the payload for admin login.
type LoginRequest struct {
Username string `json:"username" validate:"required" example:"admin"`
Password string `json:"password" validate:"required" example:"password123"`
}
// LoginResponse is the response for a successful login.
type LoginResponse struct {
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIs..."`
Username string `json:"username" example:"admin"`
UserID uint64 `json:"user_id" example:"1"`
}
// ChangePasswordRequest is the payload for changing admin password.
type ChangePasswordRequest struct {
OldPassword string `json:"old_password" validate:"required" example:"old_pass"`
NewPassword string `json:"new_password" validate:"required|minLen:6" example:"new_pass123"`
}
// MeResponse wraps AdminUser with a default-password flag.
type MeResponse struct {
mdb.AdminUser
PasswordIsDefault bool `json:"password_is_default" example:"true"`
}
// Login verifies credentials, stamps last_login_at, returns a signed JWT.
// @Summary Admin login
// @Description Verify credentials and return a signed JWT token
// @Tags Admin Auth
// @Accept json
// @Produce json
// @Param request body admin.LoginRequest true "Login credentials"
// @Success 200 {object} response.ApiResponse{data=admin.LoginResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/auth/login [post]
func (c *BaseAdminController) Login(ctx echo.Context) error {
req := new(LoginRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
user, err := data.GetAdminUserByUsername(req.Username)
if err != nil {
return c.FailJson(ctx, err)
}
if user.ID == 0 || !data.VerifyPassword(user.PasswordHash, req.Password) {
return c.FailJson(ctx, errors.New("invalid username or password"))
}
if user.Status != mdb.AdminUserStatusEnable {
return c.FailJson(ctx, errors.New("user disabled"))
}
token, err := appjwt.Sign(user.ID, user.Username)
if err != nil {
return c.FailJson(ctx, err)
}
err = data.TouchAdminUserLastLogin(user.ID)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, LoginResponse{
Token: token,
Username: user.Username,
UserID: user.ID,
})
}
// Logout is a no-op stub — tokens are stateless and the frontend
// discards them. Kept for API symmetry with the documented spec.
// @Summary Admin logout
// @Description Logout (no-op, frontend discards token)
// @Tags Admin Auth
// @Security AdminJWT
// @Produce json
// @Success 200 {object} response.ApiResponse
// @Router /admin/api/v1/auth/logout [post]
func (c *BaseAdminController) Logout(ctx echo.Context) error {
return c.SucJson(ctx, nil)
}
// Me returns the currently authenticated admin user profile.
// @Summary Get current admin profile
// @Description Returns the currently authenticated admin user
// @Tags Admin Auth
// @Security AdminJWT
// @Produce json
// @Success 200 {object} response.ApiResponse{data=admin.MeResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/auth/me [get]
func (c *BaseAdminController) Me(ctx echo.Context) error {
uid := currentAdminUserID(ctx)
if uid == 0 {
return c.FailJson(ctx, errors.New("unauthorized"))
}
user, err := data.GetAdminUserByID(uid)
if err != nil {
return c.FailJson(ctx, err)
}
if user.ID == 0 {
return c.FailJson(ctx, errors.New("user not found"))
}
// Warn the frontend when the operator hasn't changed the default
// password so the UI can show a prominent reminder.
isDefault := data.VerifyPassword(user.PasswordHash, "admin")
return c.SucJson(ctx, MeResponse{
AdminUser: *user,
PasswordIsDefault: isDefault,
})
}
// ChangePassword requires the old password, updates to the new one.
// @Summary Change admin password
// @Description Change the current admin user's password
// @Tags Admin Auth
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.ChangePasswordRequest true "Password payload"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/auth/password [post]
func (c *BaseAdminController) ChangePassword(ctx echo.Context) error {
uid := currentAdminUserID(ctx)
if uid == 0 {
return c.FailJson(ctx, errors.New("unauthorized"))
}
req := new(ChangePasswordRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
user, err := data.GetAdminUserByID(uid)
if err != nil {
return c.FailJson(ctx, err)
}
if user.ID == 0 || !data.VerifyPassword(user.PasswordHash, req.OldPassword) {
return c.FailJson(ctx, errors.New("old password incorrect"))
}
if err := data.UpdateAdminUserPassword(uid, req.NewPassword); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
+26
View File
@@ -0,0 +1,26 @@
package admin
import (
"github.com/assimon/luuu/controller"
"github.com/assimon/luuu/middleware"
"github.com/labstack/echo/v4"
)
// Ctrl is the singleton admin controller. Keeps parity with comm.Ctrl.
var Ctrl = &BaseAdminController{}
// BaseAdminController aggregates admin-domain handlers. Split across
// *_controller.go files in this package; all receive methods hang off
// this type so a single router registration is enough.
type BaseAdminController struct {
controller.BaseController
}
// currentAdminUserID returns the admin user id injected by CheckAdminJWT.
// Returns 0 if the middleware is missing (treat as auth bug upstream).
func currentAdminUserID(ctx echo.Context) uint64 {
if v, ok := ctx.Get(middleware.AdminUserIDKey).(uint64); ok {
return v
}
return 0
}
+71
View File
@@ -0,0 +1,71 @@
package admin
import (
"github.com/assimon/luuu/model/data"
"github.com/labstack/echo/v4"
)
// UpdateChainRequest is the payload for updating chain settings.
type UpdateChainRequest struct {
Enabled *bool `json:"enabled" example:"true"`
MinConfirmations *int `json:"min_confirmations" example:"20"`
ScanIntervalSec *int `json:"scan_interval_sec" example:"5"`
DisplayName *string `json:"display_name" example:"Tron"`
}
// ListChains returns the chains table (tron/ethereum/solana seeded; new
// networks like bsc/polygon inserted manually once supported).
// @Summary List chains
// @Description Returns all supported blockchain networks
// @Tags Admin Chains
// @Security AdminJWT
// @Produce json
// @Success 200 {object} response.ApiResponse{data=[]mdb.Chain}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chains [get]
func (c *BaseAdminController) ListChains(ctx echo.Context) error {
rows, err := data.ListChains()
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// UpdateChain toggles enabled / tweaks scan params. Scanners re-read the
// chains table on every poll tick, so changes take effect within one
// cycle without a restart.
// @Summary Update chain
// @Description Toggle enabled / tweak scan params for a chain
// @Tags Admin Chains
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param network path string true "Network name (e.g. tron, ethereum, solana)"
// @Param request body admin.UpdateChainRequest true "Chain settings"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chains/{network} [patch]
func (c *BaseAdminController) UpdateChain(ctx echo.Context) error {
network := ctx.Param("network")
req := new(UpdateChainRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
fields := map[string]interface{}{}
if req.Enabled != nil {
fields["enabled"] = *req.Enabled
}
if req.MinConfirmations != nil {
fields["min_confirmations"] = *req.MinConfirmations
}
if req.ScanIntervalSec != nil {
fields["scan_interval_sec"] = *req.ScanIntervalSec
}
if req.DisplayName != nil {
fields["display_name"] = *req.DisplayName
}
if err := data.UpdateChainFields(network, fields); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
@@ -0,0 +1,181 @@
package admin
import (
"strconv"
"strings"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/labstack/echo/v4"
)
// CreateChainTokenRequest is the payload for creating a chain token.
type CreateChainTokenRequest struct {
Network string `json:"network" validate:"required" example:"tron"`
Symbol string `json:"symbol" validate:"required|maxLen:32" example:"USDT"`
ContractAddress string `json:"contract_address" example:"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"`
Decimals int `json:"decimals" example:"6"`
Enabled *bool `json:"enabled" example:"true"`
MinAmount float64 `json:"min_amount" example:"1.0"`
}
// UpdateChainTokenRequest is the payload for updating a chain token.
type UpdateChainTokenRequest struct {
ContractAddress *string `json:"contract_address" example:"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"`
Decimals *int `json:"decimals" example:"6"`
Enabled *bool `json:"enabled" example:"true"`
MinAmount *float64 `json:"min_amount" example:"1.0"`
}
// ChangeChainTokenStatusRequest is the payload for toggling chain token status.
type ChangeChainTokenStatusRequest struct {
Enabled bool `json:"enabled" example:"true"`
}
// ListChainTokens returns rows, optionally filtered by network.
// @Summary List chain tokens
// @Description Returns chain tokens, optionally filtered by network
// @Tags Admin Chain Tokens
// @Security AdminJWT
// @Produce json
// @Param network query string false "Network filter"
// @Success 200 {object} response.ApiResponse{data=[]mdb.ChainToken}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chain-tokens [get]
func (c *BaseAdminController) ListChainTokens(ctx echo.Context) error {
network := strings.ToLower(strings.TrimSpace(ctx.QueryParam("network")))
rows, err := data.ListChainTokens(network)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// CreateChainToken inserts a new row. Default decimals=6 when 0 passed.
// @Summary Create chain token
// @Description Create a new chain token entry
// @Tags Admin Chain Tokens
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.CreateChainTokenRequest true "Chain token payload"
// @Success 200 {object} response.ApiResponse{data=mdb.ChainToken}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chain-tokens [post]
func (c *BaseAdminController) CreateChainToken(ctx echo.Context) error {
req := new(CreateChainTokenRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
decimals := req.Decimals
if decimals == 0 {
decimals = 6
}
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
row := &mdb.ChainToken{
Network: strings.ToLower(strings.TrimSpace(req.Network)),
Symbol: strings.ToUpper(strings.TrimSpace(req.Symbol)),
ContractAddress: strings.TrimSpace(req.ContractAddress),
Decimals: decimals,
Enabled: enabled,
MinAmount: req.MinAmount,
}
if err := data.CreateChainToken(row); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, row)
}
// UpdateChainToken patches mutable columns.
// @Summary Update chain token
// @Description Patch chain token fields
// @Tags Admin Chain Tokens
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "Chain token ID"
// @Param request body admin.UpdateChainTokenRequest true "Fields to update"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chain-tokens/{id} [patch]
func (c *BaseAdminController) UpdateChainToken(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(UpdateChainTokenRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
fields := map[string]interface{}{}
if req.ContractAddress != nil {
fields["contract_address"] = *req.ContractAddress
}
if req.Decimals != nil {
fields["decimals"] = *req.Decimals
}
if req.Enabled != nil {
fields["enabled"] = *req.Enabled
}
if req.MinAmount != nil {
fields["min_amount"] = *req.MinAmount
}
if err := data.UpdateChainTokenFields(id, fields); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// ChangeChainTokenStatus toggles enable/disable.
// @Summary Change chain token status
// @Description Toggle enable/disable for a chain token
// @Tags Admin Chain Tokens
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "Chain token ID"
// @Param request body admin.ChangeChainTokenStatusRequest true "Status payload"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chain-tokens/{id}/status [post]
func (c *BaseAdminController) ChangeChainTokenStatus(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(ChangeChainTokenStatusRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := data.UpdateChainTokenFields(id, map[string]interface{}{"enabled": req.Enabled}); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// DeleteChainToken soft-deletes the row.
// @Summary Delete chain token
// @Description Soft-delete a chain token
// @Tags Admin Chain Tokens
// @Security AdminJWT
// @Produce json
// @Param id path int true "Chain token ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/chain-tokens/{id} [delete]
func (c *BaseAdminController) DeleteChainToken(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
if err := data.DeleteChainTokenByID(id); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
@@ -0,0 +1,288 @@
package admin
import (
"strconv"
"strings"
"time"
"github.com/assimon/luuu/model/data"
"github.com/labstack/echo/v4"
)
// OverviewResponse is the dashboard top-card response.
type OverviewResponse struct {
TotalAsset float64 `json:"total_asset" example:"12345.6789"`
Volume float64 `json:"volume" example:"100.5"`
OrderCount int64 `json:"order_count" example:"42"`
SuccessRate float64 `json:"success_rate" example:"0.85"`
SevenDayVolume float64 `json:"seven_day_volume" example:"700.25"`
ActiveAddresses int64 `json:"active_addresses" example:"5"`
OnlineChains int64 `json:"online_chains" example:"3"`
}
// OrderStatsResponse is the order statistics response.
type OrderStatsResponse struct {
OrderCount int64 `json:"order_count" example:"100"`
SuccessCount int64 `json:"success_count" example:"85"`
SuccessRate float64 `json:"success_rate" example:"0.85"`
AvgPaymentSeconds float64 `json:"avg_payment_seconds" example:"120.5"`
ExpiredUnpaidCount int64 `json:"expired_unpaid_count" example:"10"`
}
// RpcHealthCheckResponse is the response for a health check probe.
type RpcHealthCheckResponse struct {
// 健康状态 unknown=未知 ok=正常 down=异常
Status string `json:"status" example:"ok" enums:"unknown,ok,down"`
LastLatencyMs int `json:"last_latency_ms" example:"120"`
}
// ApiKeyStatsResponse is the response for API key usage stats.
type ApiKeyStatsResponse struct {
CallCount int64 `json:"call_count" example:"342"`
LastUsedAt string `json:"last_used_at" example:"2026-04-14T08:30:00+00:00"`
}
// RotateSecretResponse is returned when rotating an API key secret.
type RotateSecretResponse struct {
SecretKey string `json:"secret_key" example:"newSecret123abc456"`
}
// BatchImportResult is one row in the batch import response.
type BatchImportResult struct {
Address string `json:"address" example:"TTestTronAddress001"`
OK bool `json:"ok" example:"true"`
Error string `json:"error,omitempty" example:""`
}
// SettingsUpsertResult is one row in the settings upsert response.
type SettingsUpsertResult struct {
Key string `json:"key" example:"rate.api_url"`
OK bool `json:"ok" example:"true"`
Error string `json:"error,omitempty" example:""`
}
// Overview returns the top-card numbers for the dashboard landing page.
// All values are computed with on-demand SQL — no cache — per the design.
// The selected time range (range / start_at / end_at) is applied to
// volume, order_count, success_rate and active_addresses.
// seven_day_volume always covers the rolling past 7 days.
// total_asset and online_chains are time-independent.
// @Summary Dashboard overview
// @Description Returns top-card numbers: total asset, volume, success rate, active addresses, etc. Supports ?range= for filtering.
// @Tags Admin Dashboard
// @Security AdminJWT
// @Produce json
// @Param range query string false "Time range: today, 7d, 30d, custom" default(today)
// @Param start_at query int false "Start time (Unix seconds, for custom range)"
// @Param end_at query int false "End time (Unix seconds, for custom range)"
// @Success 200 {object} response.ApiResponse{data=admin.OverviewResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/dashboard/overview [get]
func (c *BaseAdminController) Overview(ctx echo.Context) error {
start, end := parseRange(ctx)
now := time.Now()
sevenDaysAgo := startOfDay(now).AddDate(0, 0, -6)
totalActual, _ := data.SumPaidActualAmount()
orderCount, successCount, volume, _ := data.PaidStatsInRange(start, end)
var successRate float64
if orderCount > 0 {
successRate = float64(successCount) / float64(orderCount)
}
_, _, sevenDayActual, _ := data.PaidStatsInRange(sevenDaysAgo, now)
activeAddr, _ := data.ActiveAddressCountInRange(start, end)
onlineChains, _ := data.CountEnabledChains()
return c.SucJson(ctx, map[string]interface{}{
"total_asset": totalActual,
"volume": volume,
"order_count": orderCount,
"success_rate": successRate,
"seven_day_volume": sevenDayActual,
"active_addresses": activeAddr,
"online_chains": onlineChains,
})
}
// isHourlyRange returns true when the time window spans ≤ 1 day,
// so callers can choose hourly vs daily granularity.
func isHourlyRange(start, end time.Time) bool {
return end.Sub(start) <= 24*time.Hour
}
// AssetTrend returns per-day actual_amount for paid orders. group_by=
// "total" yields one series; "address" yields rows keyed by
// receive_address for the stacked chart.
// Granularity: hourly when range ≤ 1 day, daily otherwise.
// Missing buckets are always zero-filled.
// @Summary Asset trend
// @Description Returns per-period actual_amount for paid orders. Hourly for ≤1-day ranges, daily otherwise. Missing buckets are zero-filled.
// @Tags Admin Dashboard
// @Security AdminJWT
// @Produce json
// @Param range query string false "Time range: today, 7d, 30d, custom" default(today)
// @Param start_at query int false "Start time (Unix seconds, for custom range)"
// @Param end_at query int false "End time (Unix seconds, for custom range)"
// @Param group_by query string false "Group by: total or address" default(total)
// @Success 200 {object} response.ApiResponse{data=[]data.DailyStat}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/dashboard/asset-trend [get]
func (c *BaseAdminController) AssetTrend(ctx echo.Context) error {
start, end := parseRange(ctx)
groupBy := strings.ToLower(strings.TrimSpace(ctx.QueryParam("group_by")))
hourly := isHourlyRange(start, end)
if groupBy == "address" {
var rows interface{}
var err error
if hourly {
rows, err = data.HourlyAssetByAddress(start, end)
} else {
rows, err = data.DailyAssetByAddress(start, end)
}
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
var rows interface{}
var err error
if hourly {
rows, err = data.HourlyOrderStats(start, end)
} else {
rows, err = data.DailyOrderStats(start, end)
}
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// RevenueTrend mirrors the daily stats view used for revenue charts.
// Same data shape as AssetTrend(group_by=total) but kept as its own
// endpoint so the frontend can evolve each chart independently.
// Granularity: hourly when range ≤ 1 day, daily otherwise.
// Missing buckets are always zero-filled.
// @Summary Revenue trend
// @Description Returns per-period revenue stats for charts. Hourly for ≤1-day ranges, daily otherwise. Missing buckets are zero-filled.
// @Tags Admin Dashboard
// @Security AdminJWT
// @Produce json
// @Param range query string false "Time range: today, 7d, 30d, custom" default(today)
// @Param start_at query int false "Start time (Unix seconds, for custom range)"
// @Param end_at query int false "End time (Unix seconds, for custom range)"
// @Success 200 {object} response.ApiResponse{data=[]data.DailyStat}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/dashboard/revenue-trend [get]
func (c *BaseAdminController) RevenueTrend(ctx echo.Context) error {
start, end := parseRange(ctx)
var rows interface{}
var err error
if isHourlyRange(start, end) {
rows, err = data.HourlyOrderStats(start, end)
} else {
rows, err = data.DailyOrderStats(start, end)
}
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// OrderStats returns aggregate order figures for the selected window:
// total count, success rate, average payment duration (seconds), and
// expired-unpaid count.
// @Summary Order statistics
// @Description Returns aggregate order figures: count, success rate, avg payment time, expired count
// @Tags Admin Dashboard
// @Security AdminJWT
// @Produce json
// @Param range query string false "Time range: today, 7d, 30d, custom" default(today)
// @Param start_at query int false "Start time (Unix seconds, for custom range)"
// @Param end_at query int false "End time (Unix seconds, for custom range)"
// @Success 200 {object} response.ApiResponse{data=admin.OrderStatsResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/dashboard/order-stats [get]
func (c *BaseAdminController) OrderStats(ctx echo.Context) error {
start, end := parseRange(ctx)
total, success, _, err := data.PaidStatsInRange(start, end)
if err != nil {
return c.FailJson(ctx, err)
}
avg, _ := data.AveragePaymentDurationSeconds(start, end)
expired, _ := data.CountExpiredInRange(start, end)
var rate float64
if total > 0 {
rate = float64(success) / float64(total)
}
return c.SucJson(ctx, map[string]interface{}{
"order_count": total,
"success_count": success,
"success_rate": rate,
"avg_payment_seconds": avg,
"expired_unpaid_count": expired,
})
}
// RecentOrders returns the last N orders for the dashboard list card.
// @Summary Recent orders
// @Description Returns the last N orders for the dashboard
// @Tags Admin Dashboard
// @Security AdminJWT
// @Produce json
// @Param limit query int false "Number of orders to return" default(20)
// @Success 200 {object} response.ApiResponse{data=[]mdb.Orders}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/dashboard/recent-orders [get]
func (c *BaseAdminController) RecentOrders(ctx echo.Context) error {
limit := 20
if s := ctx.QueryParam("limit"); s != "" {
if n, err := strconv.Atoi(s); err == nil {
limit = n
}
}
rows, err := data.RecentOrders(limit)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// parseRange maps the ?range=... shorthand to a concrete [start, end].
// Accepted: today / 7d / 30d / custom (with start_at/end_at Unix secs).
// Defaults to today.
func parseRange(ctx echo.Context) (time.Time, time.Time) {
rng := strings.ToLower(strings.TrimSpace(ctx.QueryParam("range")))
now := time.Now()
todayStart := startOfDay(now)
switch rng {
case "7d":
return todayStart.AddDate(0, 0, -6), now
case "30d":
return todayStart.AddDate(0, 0, -29), now
case "custom":
start := todayStart
end := now
if s := ctx.QueryParam("start_at"); s != "" {
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
start = time.Unix(n, 0)
}
}
if s := ctx.QueryParam("end_at"); s != "" {
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
end = time.Unix(n, 0)
}
}
return start, end
default:
return todayStart, now
}
}
func startOfDay(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
@@ -0,0 +1,314 @@
package admin
import (
"encoding/json"
"errors"
"strconv"
"strings"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/assimon/luuu/notify"
"github.com/assimon/luuu/telegram"
"github.com/labstack/echo/v4"
)
// CreateNotificationChannelRequest is the payload for creating a notification channel.
type CreateNotificationChannelRequest struct {
Type string `json:"type" validate:"required|in:telegram,webhook,email" enums:"telegram,webhook,email" example:"telegram"`
Name string `json:"name" validate:"required|maxLen:128" example:"主通知群"`
Config map[string]interface{} `json:"config" validate:"required"`
Events interface{} `json:"events"`
Enabled *bool `json:"enabled" example:"true"`
}
// UpdateNotificationChannelRequest is the payload for updating a notification channel.
type UpdateNotificationChannelRequest struct {
Name *string `json:"name" example:"更新后的名称"`
Config map[string]interface{} `json:"config"`
Events interface{} `json:"events"`
Enabled *bool `json:"enabled" example:"true"`
}
// ChangeChannelStatusRequest is the payload for toggling notification channel status.
type ChangeChannelStatusRequest struct {
Enabled bool `json:"enabled" example:"true"`
}
// ListNotificationChannels lists rows, optionally filtered by type.
// @Summary List notification channels
// @Description Returns notification channels, optionally filtered by type
// @Tags Admin Notifications
// @Security AdminJWT
// @Produce json
// @Param type query string false "Channel type: telegram, webhook, email"
// @Success 200 {object} response.ApiResponse{data=[]mdb.NotificationChannel}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/notification-channels [get]
func (c *BaseAdminController) ListNotificationChannels(ctx echo.Context) error {
channelType := strings.ToLower(strings.TrimSpace(ctx.QueryParam("type")))
rows, err := data.ListNotificationChannels(channelType)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// CreateNotificationChannel validates Config shape per type (only
// telegram is strongly validated today) and inserts a row.
// @Summary Create notification channel
// @Description Create a new notification channel
// @Tags Admin Notifications
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.CreateNotificationChannelRequest true "Channel payload"
// @Success 200 {object} response.ApiResponse{data=mdb.NotificationChannel}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/notification-channels [post]
func (c *BaseAdminController) CreateNotificationChannel(ctx echo.Context) error {
req := new(CreateNotificationChannelRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
req.Type = strings.ToLower(strings.TrimSpace(req.Type))
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
if err := validateChannelConfig(req.Type, req.Config); err != nil {
return c.FailJson(ctx, err)
}
eventsMap, err := normalizeChannelEvents(req.Events)
if err != nil {
return c.FailJson(ctx, err)
}
configJSON, _ := json.Marshal(req.Config)
eventsJSON, _ := json.Marshal(eventsMap)
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
row := &mdb.NotificationChannel{
Type: req.Type,
Name: req.Name,
Config: string(configJSON),
Events: string(eventsJSON),
Enabled: enabled,
}
if err := data.CreateNotificationChannel(row); err != nil {
return c.FailJson(ctx, err)
}
if strings.ToLower(strings.TrimSpace(row.Type)) == mdb.NotificationTypeTelegram {
telegram.ReloadBotAsync("admin create telegram channel")
}
return c.SucJson(ctx, row)
}
// UpdateNotificationChannel patches name/config/events/enabled.
// @Summary Update notification channel
// @Description Patch notification channel fields
// @Tags Admin Notifications
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "Channel ID"
// @Param request body admin.UpdateNotificationChannelRequest true "Fields to update"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/notification-channels/{id} [patch]
func (c *BaseAdminController) UpdateNotificationChannel(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
existing, err := data.GetNotificationChannelByID(id)
if err != nil {
return c.FailJson(ctx, err)
}
isTelegram := existing != nil && existing.ID > 0 && strings.ToLower(strings.TrimSpace(existing.Type)) == mdb.NotificationTypeTelegram
req := new(UpdateNotificationChannelRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
fields := map[string]interface{}{}
if req.Name != nil {
fields["name"] = *req.Name
}
if req.Config != nil {
configJSON, _ := json.Marshal(req.Config)
fields["config"] = string(configJSON)
}
if req.Events != nil {
eventsMap, err := normalizeChannelEvents(req.Events)
if err != nil {
return c.FailJson(ctx, err)
}
eventsJSON, _ := json.Marshal(eventsMap)
fields["events"] = string(eventsJSON)
}
if req.Enabled != nil {
fields["enabled"] = *req.Enabled
}
if err := data.UpdateNotificationChannelFields(id, fields); err != nil {
return c.FailJson(ctx, err)
}
if isTelegram {
telegram.ReloadBotAsync("admin update telegram channel")
}
return c.SucJson(ctx, nil)
}
// ChangeNotificationChannelStatus toggles enabled.
// @Summary Change notification channel status
// @Description Toggle enable/disable for a notification channel
// @Tags Admin Notifications
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "Channel ID"
// @Param request body admin.ChangeChannelStatusRequest true "Status payload"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/notification-channels/{id}/status [post]
func (c *BaseAdminController) ChangeNotificationChannelStatus(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
existing, err := data.GetNotificationChannelByID(id)
if err != nil {
return c.FailJson(ctx, err)
}
isTelegram := existing != nil && existing.ID > 0 && strings.ToLower(strings.TrimSpace(existing.Type)) == mdb.NotificationTypeTelegram
req := new(ChangeChannelStatusRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := data.UpdateNotificationChannelFields(id, map[string]interface{}{"enabled": req.Enabled}); err != nil {
return c.FailJson(ctx, err)
}
if isTelegram {
telegram.ReloadBotAsync("admin change telegram channel status")
}
return c.SucJson(ctx, nil)
}
// DeleteNotificationChannel soft-deletes the row.
// @Summary Delete notification channel
// @Description Soft-delete a notification channel
// @Tags Admin Notifications
// @Security AdminJWT
// @Produce json
// @Param id path int true "Channel ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/notification-channels/{id} [delete]
func (c *BaseAdminController) DeleteNotificationChannel(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
existing, err := data.GetNotificationChannelByID(id)
if err != nil {
return c.FailJson(ctx, err)
}
isTelegram := existing != nil && existing.ID > 0 && strings.ToLower(strings.TrimSpace(existing.Type)) == mdb.NotificationTypeTelegram
if err := data.DeleteNotificationChannelByID(id); err != nil {
return c.FailJson(ctx, err)
}
if isTelegram {
telegram.ReloadBotAsync("admin delete telegram channel")
}
return c.SucJson(ctx, nil)
}
// validateChannelConfig enforces minimum shape. Telegram needs bot_token
// + chat_id; webhook/email kept loose until those senders exist.
func validateChannelConfig(channelType string, cfg map[string]interface{}) error {
if cfg == nil {
return errors.New("config required")
}
if channelType == mdb.NotificationTypeTelegram {
configJSON, _ := json.Marshal(cfg)
if _, err := notify.ParseTelegramConfig(string(configJSON)); err != nil {
return err
}
}
return nil
}
func normalizeChannelEvents(raw interface{}) (map[string]bool, error) {
if raw == nil {
return map[string]bool{}, nil
}
toFlag := func(v interface{}) (bool, error) {
switch t := v.(type) {
case bool:
return t, nil
case float64:
return t != 0, nil
case string:
s := strings.ToLower(strings.TrimSpace(t))
switch s {
case "", "0", "false", "off", "no":
return false, nil
case "1", "true", "on", "yes":
return true, nil
default:
return false, errors.New("invalid boolean string")
}
default:
return false, errors.New("invalid event value type")
}
}
trimKey := func(s string) string {
return strings.TrimSpace(s)
}
out := make(map[string]bool)
switch t := raw.(type) {
case map[string]bool:
for k, v := range t {
k = trimKey(k)
if k == "" {
continue
}
out[k] = v
}
return out, nil
case map[string]interface{}:
for k, v := range t {
k = trimKey(k)
if k == "" {
continue
}
flag, err := toFlag(v)
if err != nil {
return nil, err
}
out[k] = flag
}
return out, nil
case []interface{}:
for _, v := range t {
s, ok := v.(string)
if !ok {
return nil, errors.New("events array must contain strings")
}
s = trimKey(s)
if s == "" {
continue
}
out[s] = true
}
return out, nil
default:
return nil, errors.New("events must be object or string array")
}
}
+393
View File
@@ -0,0 +1,393 @@
package admin
import (
"encoding/csv"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/assimon/luuu/model/request"
"github.com/assimon/luuu/model/service"
"github.com/labstack/echo/v4"
)
// MarkPaidRequest is the payload for manually marking an order as paid.
type MarkPaidRequest struct {
BlockTransactionId string `json:"block_transaction_id" validate:"required" example:"0xabc123def456..."`
}
// OrderListResponse wraps the paginated order list.
type OrderListResponse struct {
List []mdb.Orders `json:"list"`
Total int64 `json:"total" example:"100"`
Page int `json:"page" example:"1"`
PageSize int `json:"page_size" example:"20"`
}
// OrderWithSub embeds a parent order together with its child orders.
type OrderWithSub struct {
mdb.Orders
SubOrders []mdb.Orders `json:"sub_orders"`
}
// OrderWithSubListResponse wraps the paginated list-with-sub result.
type OrderWithSubListResponse struct {
List []OrderWithSub `json:"list"`
Total int64 `json:"total" example:"100"`
Page int `json:"page" example:"1"`
PageSize int `json:"page_size" example:"20"`
}
// ListOrders handles the admin order list with filters + pagination.
// @Summary List orders
// @Description Returns paginated orders with optional filters
// @Tags Admin Orders
// @Security AdminJWT
// @Produce json
// @Param network query string false "Network filter"
// @Param token query string false "Token filter"
// @Param address query string false "Receive address filter"
// @Param keyword query string false "Keyword search (trade_id or order_id)"
// @Param status query int false "Order status filter"
// @Param start_at query int false "Start time (Unix seconds)"
// @Param end_at query int false "End time (Unix seconds)"
// @Param page query int false "Page number" default(1)
// @Param page_size query int false "Page size" default(20)
// @Success 200 {object} response.ApiResponse{data=admin.OrderListResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders [get]
func (c *BaseAdminController) ListOrders(ctx echo.Context) error {
f := parseOrderFilter(ctx)
rows, total, err := data.ListOrders(f)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, map[string]interface{}{
"list": rows,
"total": total,
"page": f.Page,
"page_size": f.PageSize,
})
}
// GetOrder returns full order detail by trade_id.
// @Summary Get order
// @Description Returns full order detail by trade_id
// @Tags Admin Orders
// @Security AdminJWT
// @Produce json
// @Param trade_id path string true "Trade ID"
// @Success 200 {object} response.ApiResponse{data=mdb.Orders}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/{trade_id} [get]
func (c *BaseAdminController) GetOrder(ctx echo.Context) error {
tradeID := ctx.Param("trade_id")
order, err := data.GetOrderInfoByTradeId(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if order.ID == 0 {
return c.FailJson(ctx, errors.New("order not found"))
}
return c.SucJson(ctx, order)
}
// CloseOrder flips a waiting order to expired and releases its lock.
// @Summary Close order
// @Description Manually close a waiting order (mark as expired)
// @Tags Admin Orders
// @Security AdminJWT
// @Produce json
// @Param trade_id path string true "Trade ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/{trade_id}/close [post]
func (c *BaseAdminController) CloseOrder(ctx echo.Context) error {
tradeID := ctx.Param("trade_id")
order, err := data.GetOrderInfoByTradeId(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if order.ID == 0 {
return c.FailJson(ctx, errors.New("order not found"))
}
if order.Status != mdb.StatusWaitPay {
return c.FailJson(ctx, errors.New("order is not waiting payment"))
}
ok, err := data.CloseOrderManually(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if !ok {
return c.FailJson(ctx, errors.New("close failed (concurrent state change)"))
}
// Release the transaction lock so the amount slot becomes reusable.
_ = data.UnLockTransaction(order.Network, order.ReceiveAddress, order.Token, order.ActualAmount)
return c.SucJson(ctx, nil)
}
// MarkOrderPaid manually marks an order paid (operator补单). Uses the
// same OrderProcessing path as on-chain confirmation so downstream
// callback + notification fire normally.
// @Summary Mark order paid
// @Description Manually mark a waiting order as paid (operator补单)
// @Tags Admin Orders
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param trade_id path string true "Trade ID"
// @Param request body admin.MarkPaidRequest true "Block transaction ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/{trade_id}/mark-paid [post]
func (c *BaseAdminController) MarkOrderPaid(ctx echo.Context) error {
tradeID := ctx.Param("trade_id")
req := new(MarkPaidRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
order, err := data.GetOrderInfoByTradeId(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if order.ID == 0 {
return c.FailJson(ctx, errors.New("order not found"))
}
if order.Status != mdb.StatusWaitPay {
return c.FailJson(ctx, errors.New("order is not waiting payment"))
}
err = service.OrderProcessing(&request.OrderProcessingRequest{
ReceiveAddress: order.ReceiveAddress,
Currency: order.Currency,
Token: order.Token,
Network: order.Network,
Amount: order.ActualAmount,
TradeId: order.TradeId,
BlockTransactionId: req.BlockTransactionId,
})
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// ResendCallback requeues the order callback by flipping
// callback_confirm back to NO. The mq worker will grab it on the
// next poll tick.
// @Summary Resend callback
// @Description Re-queue the order callback notification
// @Tags Admin Orders
// @Security AdminJWT
// @Produce json
// @Param trade_id path string true "Trade ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/{trade_id}/resend-callback [post]
func (c *BaseAdminController) ResendCallback(ctx echo.Context) error {
tradeID := ctx.Param("trade_id")
ok, err := data.ReopenOrderCallback(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if !ok {
return c.FailJson(ctx, errors.New("order is not paid (callback not applicable)"))
}
return c.SucJson(ctx, nil)
}
// ExportOrders streams matching orders as CSV. No pagination — the
// caller drives what rows to include via filter params. Capped at
// 10k rows to keep the response bounded.
// @Summary Export orders as CSV
// @Description Stream matching orders as a CSV file (max 10k rows)
// @Tags Admin Orders
// @Security AdminJWT
// @Produce text/csv
// @Param network query string false "Network filter"
// @Param token query string false "Token filter"
// @Param address query string false "Receive address filter"
// @Param keyword query string false "Keyword search"
// @Param status query int false "Order status filter"
// @Param start_at query int false "Start time (Unix seconds)"
// @Param end_at query int false "End time (Unix seconds)"
// @Success 200 {string} string "CSV file"
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/export [get]
func (c *BaseAdminController) ExportOrders(ctx echo.Context) error {
f := parseOrderFilter(ctx)
f.Page = 1
f.PageSize = 10000
rows, _, err := data.ListOrders(f)
if err != nil {
return c.FailJson(ctx, err)
}
resp := ctx.Response()
resp.Header().Set(echo.HeaderContentType, "text/csv; charset=utf-8")
resp.Header().Set(echo.HeaderContentDisposition, "attachment; filename=orders.csv")
resp.WriteHeader(http.StatusOK)
w := csv.NewWriter(resp.Writer)
_ = w.Write([]string{"trade_id", "order_id", "amount", "actual_amount", "currency", "token", "network", "receive_address", "status", "block_transaction_id", "created_at"})
for _, r := range rows {
_ = w.Write([]string{
r.TradeId,
r.OrderId,
fmt.Sprintf("%.4f", r.Amount),
fmt.Sprintf("%.4f", r.ActualAmount),
r.Currency,
r.Token,
r.Network,
r.ReceiveAddress,
strconv.Itoa(r.Status),
r.BlockTransactionId,
r.CreatedAt.ToDateTimeString(),
})
}
w.Flush()
return nil
}
// parseOrderFilter extracts filter + pagination values from the query
// string. Time params are Unix seconds.
func parseOrderFilter(ctx echo.Context) data.OrderListFilter {
f := data.OrderListFilter{
Network: strings.ToLower(strings.TrimSpace(ctx.QueryParam("network"))),
Token: strings.ToUpper(strings.TrimSpace(ctx.QueryParam("token"))),
Address: strings.TrimSpace(ctx.QueryParam("address")),
Keyword: strings.TrimSpace(ctx.QueryParam("keyword")),
}
if s := ctx.QueryParam("status"); s != "" {
if n, err := strconv.Atoi(s); err == nil {
f.Status = n
}
}
if s := ctx.QueryParam("start_at"); s != "" {
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
t := time.Unix(n, 0)
f.StartAt = &t
}
}
if s := ctx.QueryParam("end_at"); s != "" {
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
t := time.Unix(n, 0)
f.EndAt = &t
}
}
if s := ctx.QueryParam("page"); s != "" {
if n, err := strconv.Atoi(s); err == nil {
f.Page = n
}
}
if s := ctx.QueryParam("page_size"); s != "" {
if n, err := strconv.Atoi(s); err == nil {
f.PageSize = n
}
}
if f.Page < 1 {
f.Page = 1
}
if f.PageSize < 1 {
f.PageSize = 20
}
return f
}
// ListOrdersWithSub returns the same paginated order list as ListOrders but
// each row has a sub_orders field containing all child orders under it.
// @Summary List orders with sub-orders
// @Description Returns paginated orders; each item embeds its child orders in sub_orders
// @Tags Admin Orders
// @Security AdminJWT
// @Produce json
// @Param network query string false "Network filter"
// @Param token query string false "Token filter"
// @Param address query string false "Receive address filter"
// @Param keyword query string false "Keyword search (trade_id or order_id)"
// @Param status query int false "Order status filter"
// @Param start_at query int false "Start time (Unix seconds)"
// @Param end_at query int false "End time (Unix seconds)"
// @Param page query int false "Page number" default(1)
// @Param page_size query int false "Page size" default(20)
// @Success 200 {object} response.ApiResponse{data=admin.OrderWithSubListResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/list-with-sub [get]
func (c *BaseAdminController) ListOrdersWithSub(ctx echo.Context) error {
f := parseOrderFilter(ctx)
// Only parent orders at the top level; sub-orders appear nested inside sub_orders.
f.ParentOnly = true
rows, total, err := data.ListOrders(f)
if err != nil {
return c.FailJson(ctx, err)
}
// Batch-fetch all sub-orders for the current page in one query.
tradeIds := make([]string, 0, len(rows))
for _, r := range rows {
tradeIds = append(tradeIds, r.TradeId)
}
subs, err := data.GetSubOrdersByParentTradeIds(tradeIds)
if err != nil {
return c.FailJson(ctx, err)
}
// Group sub-orders by parent_trade_id.
subMap := make(map[string][]mdb.Orders, len(subs))
for _, s := range subs {
subMap[s.ParentTradeId] = append(subMap[s.ParentTradeId], s)
}
list := make([]OrderWithSub, 0, len(rows))
for _, r := range rows {
children := subMap[r.TradeId]
if children == nil {
children = []mdb.Orders{}
}
list = append(list, OrderWithSub{Orders: r, SubOrders: children})
}
return c.SucJson(ctx, OrderWithSubListResponse{
List: list,
Total: total,
Page: f.Page,
PageSize: f.PageSize,
})
}
// GetOrderWithSub returns a single parent order together with all its child
// orders (any status), regardless of whether the caller passes a parent or
// child trade_id — if it is a child, the parent is resolved first.
// @Summary Get order with sub-orders
// @Description Returns an order and its child orders embedded in sub_orders
// @Tags Admin Orders
// @Security AdminJWT
// @Produce json
// @Param trade_id path string true "Trade ID"
// @Success 200 {object} response.ApiResponse{data=admin.OrderWithSub}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/orders/{trade_id}/with-sub [get]
func (c *BaseAdminController) GetOrderWithSub(ctx echo.Context) error {
tradeID := ctx.Param("trade_id")
order, err := data.GetOrderInfoByTradeId(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if order.ID == 0 {
return c.FailJson(ctx, errors.New("order not found"))
}
subOrders, err := data.GetAllSubOrders(tradeID)
if err != nil {
return c.FailJson(ctx, err)
}
if subOrders == nil {
subOrders = []mdb.Orders{}
}
return c.SucJson(ctx, OrderWithSub{Orders: *order, SubOrders: subOrders})
}
+190
View File
@@ -0,0 +1,190 @@
package admin
import (
"errors"
"strconv"
"strings"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/assimon/luuu/task"
"github.com/labstack/echo/v4"
)
// CreateRpcNodeRequest is the payload for creating an RPC node.
type CreateRpcNodeRequest struct {
Network string `json:"network" validate:"required" example:"tron"`
Url string `json:"url" validate:"required" example:"https://api.trongrid.io"`
// 连接类型 http=HTTP请求 ws=WebSocket长连接
Type string `json:"type" validate:"required|in:http,ws" enums:"http,ws" example:"http"`
Weight int `json:"weight" example:"1"`
ApiKey string `json:"api_key" example:""`
Enabled *bool `json:"enabled" example:"true"`
}
// UpdateRpcNodeRequest is the payload for updating an RPC node.
type UpdateRpcNodeRequest struct {
Url *string `json:"url" example:"https://api.trongrid.io"`
Weight *int `json:"weight" example:"1"`
ApiKey *string `json:"api_key" example:"your-api-key"`
Enabled *bool `json:"enabled" example:"true"`
}
// ListRpcNodes returns rows optionally filtered by network.
// @Summary List RPC nodes
// @Description Returns RPC nodes, optionally filtered by network
// @Tags Admin RPC Nodes
// @Security AdminJWT
// @Produce json
// @Param network query string false "Network filter"
// @Success 200 {object} response.ApiResponse{data=[]mdb.RpcNode}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/rpc-nodes [get]
func (c *BaseAdminController) ListRpcNodes(ctx echo.Context) error {
network := strings.ToLower(strings.TrimSpace(ctx.QueryParam("network")))
rows, err := data.ListRpcNodes(network)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// CreateRpcNode inserts a row. Status starts as "unknown" until the
// health-check task runs.
// @Summary Create RPC node
// @Description Create a new RPC node
// @Tags Admin RPC Nodes
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.CreateRpcNodeRequest true "RPC node payload"
// @Success 200 {object} response.ApiResponse{data=mdb.RpcNode}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/rpc-nodes [post]
func (c *BaseAdminController) CreateRpcNode(ctx echo.Context) error {
req := new(CreateRpcNodeRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
weight := req.Weight
if weight < 1 {
weight = 1
}
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
row := &mdb.RpcNode{
Network: strings.ToLower(strings.TrimSpace(req.Network)),
Url: strings.TrimSpace(req.Url),
Type: strings.ToLower(strings.TrimSpace(req.Type)),
Weight: weight,
ApiKey: req.ApiKey,
Enabled: enabled,
Status: mdb.RpcNodeStatusUnknown,
LastLatencyMs: -1,
}
if err := data.CreateRpcNode(row); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, row)
}
// UpdateRpcNode patches url/weight/api_key/enabled.
// @Summary Update RPC node
// @Description Patch RPC node fields
// @Tags Admin RPC Nodes
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "RPC node ID"
// @Param request body admin.UpdateRpcNodeRequest true "Fields to update"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/rpc-nodes/{id} [patch]
func (c *BaseAdminController) UpdateRpcNode(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(UpdateRpcNodeRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
fields := map[string]interface{}{}
if req.Url != nil {
fields["url"] = *req.Url
}
if req.Weight != nil {
fields["weight"] = *req.Weight
}
if req.ApiKey != nil {
fields["api_key"] = *req.ApiKey
}
if req.Enabled != nil {
fields["enabled"] = *req.Enabled
}
if err := data.UpdateRpcNodeFields(id, fields); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// DeleteRpcNode soft-deletes the row.
// @Summary Delete RPC node
// @Description Soft-delete an RPC node
// @Tags Admin RPC Nodes
// @Security AdminJWT
// @Produce json
// @Param id path int true "RPC node ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/rpc-nodes/{id} [delete]
func (c *BaseAdminController) DeleteRpcNode(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
if err := data.DeleteRpcNodeByID(id); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// HealthCheckRpcNode performs an on-demand probe and writes the result.
// For HTTP endpoints this is a GET to the URL with a short timeout; for
// WS we just attempt a TCP-level check via the same HTTP client (the
// handshake URL resolves the host identically).
// @Summary Health check RPC node
// @Description Perform an on-demand health probe on an RPC node
// @Tags Admin RPC Nodes
// @Security AdminJWT
// @Produce json
// @Param id path int true "RPC node ID"
// @Success 200 {object} response.ApiResponse{data=admin.RpcHealthCheckResponse}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/rpc-nodes/{id}/health-check [post]
func (c *BaseAdminController) HealthCheckRpcNode(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
row, err := data.GetRpcNodeByID(id)
if err != nil {
return c.FailJson(ctx, err)
}
if row.ID == 0 {
return c.FailJson(ctx, errors.New("node not found"))
}
status, latency := task.ProbeNode(row.Url)
if err := data.UpdateRpcNodeHealth(id, status, latency); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, map[string]interface{}{
"status": status,
"last_latency_ms": latency,
})
}
+153
View File
@@ -0,0 +1,153 @@
package admin
import (
"strings"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/assimon/luuu/telegram"
"github.com/labstack/echo/v4"
)
// SettingUpsertItem is a single setting entry for batch upsert.
// Supported groups and keys:
//
// - group=rate:
// rate.forced_usdt_rate (float) — override USDT exchange rate (0 = use api)
// rate.api_url (string) — external rate API URL
// rate.adjust_percent (float) — rate adjustment percentage
// rate.okx_c2c_enabled (bool) — use OKX C2C rate feed
//
// - group=epay:
// epay.default_token (string) — token for EPAY orders, e.g. "usdt" (default)
// epay.default_currency (string) — fiat currency for EPAY orders, e.g. "cny" (default)
// epay.default_network (string) — blockchain network for EPAY orders, e.g. "tron" (default)
//
// - group=brand:
// brand.site_name (string) — site display name
// brand.logo_url (string) — logo image URL
// brand.page_title (string) — payment page title
// brand.pay_success_text (string) — text shown on payment success
// brand.support_url (string) — support / help URL
//
// - group=system:
// system.order_expiration_time (int) — order expiry in minutes
type SettingUpsertItem struct {
Group string `json:"group" enums:"brand,rate,system,epay" example:"epay"`
Key string `json:"key" example:"epay.default_network"`
Value string `json:"value" example:"tron"`
Type string `json:"type" enums:"string,int,bool,json" example:"string"`
}
// SettingsUpsertRequest is the payload for batch upserting settings.
type SettingsUpsertRequest struct {
Items []SettingUpsertItem `json:"items" validate:"required"`
}
// ListSettings returns all rows, optionally filtered by group.
// @Summary List settings
// @Description Returns all settings, optionally filtered by group.
// @Description Available groups: brand, rate, system, epay.
// @Description See SettingUpsertItem for the full list of supported keys per group.
// @Tags Admin Settings
// @Security AdminJWT
// @Produce json
// @Param group query string false "Group filter (brand|rate|system|epay)"
// @Success 200 {object} response.ApiResponse{data=[]mdb.Setting}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/settings [get]
func (c *BaseAdminController) ListSettings(ctx echo.Context) error {
group := strings.ToLower(strings.TrimSpace(ctx.QueryParam("group")))
rows, err := data.ListSettingsByGroup(group)
if err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, rows)
}
// UpsertSettings batch-inserts / updates rows. Each item is treated
// independently so a malformed row in the middle doesn't drop earlier
// ones. Errors are returned per-key so the UI can surface them.
// @Summary Upsert settings
// @Description Batch insert/update settings. Returns per-key status.
// @Description Supported groups: brand, rate, system, epay.
// @Description epay group keys: epay.default_token (e.g. "usdt"), epay.default_currency (e.g. "cny"), epay.default_network (e.g. "tron").
// @Description rate group keys: rate.forced_usdt_rate, rate.api_url, rate.adjust_percent, rate.okx_c2c_enabled.
// @Description brand group keys: brand.site_name, brand.logo_url, brand.page_title, brand.pay_success_text, brand.support_url.
// @Description system group keys: system.order_expiration_time.
// @Tags Admin Settings
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.SettingsUpsertRequest true "Settings payload"
// @Success 200 {object} response.ApiResponse{data=[]admin.SettingsUpsertResult}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/settings [put]
func (c *BaseAdminController) UpsertSettings(ctx echo.Context) error {
req := new(SettingsUpsertRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
type result struct {
Key string `json:"key"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}
out := make([]result, 0, len(req.Items))
for _, item := range req.Items {
key := strings.TrimSpace(item.Key)
if key == "" {
out = append(out, result{Key: item.Key, OK: false, Error: "key required"})
continue
}
if err := data.SetSetting(item.Group, key, item.Value, item.Type); err != nil {
out = append(out, result{Key: key, OK: false, Error: err.Error()})
continue
}
out = append(out, result{Key: key, OK: true})
}
// When telegram credentials are updated via settings, reload the
// command bot so operators don't need to restart the process.
telegramKeys := map[string]bool{
"system.telegram_bot_token": true,
"system.telegram_chat_id": true,
}
for _, item := range req.Items {
if telegramKeys[strings.TrimSpace(item.Key)] {
telegram.ReloadBotAsync("settings upsert")
break
}
}
return c.SucJson(ctx, out)
}
// DeleteSetting removes one row. The next read of that key will fall
// back to the hardcoded default (see settings_data.GetSetting*).
// @Summary Delete setting
// @Description Remove a setting by key (falls back to default)
// @Tags Admin Settings
// @Security AdminJWT
// @Produce json
// @Param key path string true "Setting key"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/settings/{key} [delete]
func (c *BaseAdminController) DeleteSetting(ctx echo.Context) error {
key := strings.TrimSpace(ctx.Param("key"))
if key == "" {
return c.SucJson(ctx, nil)
}
if err := data.DeleteSetting(key); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// Public helper for the rate/usdt overrides — used by config package to
// read settings-backed values without importing the controller package.
var _ = mdb.SettingKeyRateForcedUsdt // ensure key constants remain referenced
+279
View File
@@ -0,0 +1,279 @@
package admin
import (
"errors"
"strconv"
"strings"
"github.com/assimon/luuu/model/dao"
"github.com/assimon/luuu/model/data"
"github.com/assimon/luuu/model/mdb"
"github.com/labstack/echo/v4"
)
// AdminAddWalletRequest is the payload for adding a wallet via admin.
type AdminAddWalletRequest struct {
Network string `json:"network" validate:"required" example:"tron"`
Address string `json:"address" validate:"required" example:"TTestTronAddress001"`
Remark string `json:"remark" example:"主钱包"`
}
// AdminUpdateWalletRequest is the payload for updating a wallet remark.
type AdminUpdateWalletRequest struct {
Remark *string `json:"remark" example:"已更新的备注"`
}
// AdminChangeWalletStatusRequest is the payload for toggling wallet status.
type AdminChangeWalletStatusRequest struct {
// 状态 1=启用 2=禁用
Status int `json:"status" validate:"required|in:1,2" enums:"1,2" example:"1"`
}
// AdminBatchImportRequest is the payload for batch importing wallets.
type AdminBatchImportRequest struct {
Network string `json:"network" validate:"required" example:"tron"`
// Addresses listed as observation-only wallets. Private-key import
// and API-managed modes are out of scope for v1.
Addresses []string `json:"addresses" validate:"required" example:"TAddr001,TAddr002,TAddr003"`
}
// WalletListItem extends WalletAddress with order count.
type WalletListItem struct {
mdb.WalletAddress
OrderCount int64 `json:"order_count" example:"5"`
}
// AdminListWallets extends the read model with per-wallet order counts
// so the UI can render the "订单数" column without an N+1 follow-up.
// @Summary List wallets (admin)
// @Description Returns wallets with per-wallet order counts
// @Tags Admin Wallets
// @Security AdminJWT
// @Produce json
// @Param network query string false "Network filter"
// @Param status query int false "Status filter (1=enabled, 2=disabled)"
// @Param keyword query string false "Search by address or remark"
// @Success 200 {object} response.ApiResponse{data=[]admin.WalletListItem}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets [get]
func (c *BaseAdminController) AdminListWallets(ctx echo.Context) error {
network := strings.ToLower(strings.TrimSpace(ctx.QueryParam("network")))
status := strings.TrimSpace(ctx.QueryParam("status"))
keyword := strings.TrimSpace(ctx.QueryParam("keyword"))
tx := dao.Mdb.Model(&mdb.WalletAddress{})
if network != "" {
tx = tx.Where("network = ?", network)
}
if status != "" {
if s, err := strconv.Atoi(status); err == nil {
tx = tx.Where("status = ?", s)
}
}
if keyword != "" {
kw := "%" + keyword + "%"
tx = tx.Where("address LIKE ? OR remark LIKE ?", kw, kw)
}
var rows []mdb.WalletAddress
if err := tx.Order("id DESC").Find(&rows).Error; err != nil {
return c.FailJson(ctx, err)
}
counts, err := data.CountOrdersByAddress()
if err != nil {
return c.FailJson(ctx, err)
}
out := make([]WalletListItem, 0, len(rows))
for _, r := range rows {
out = append(out, WalletListItem{WalletAddress: r, OrderCount: counts[r.Address]})
}
return c.SucJson(ctx, out)
}
// AdminAddWallet wraps the existing create with admin-exposed Remark +
// Source=manual so audit fields are populated.
// @Summary Add wallet (admin)
// @Description Create a wallet with admin-specific fields (remark, source=manual)
// @Tags Admin Wallets
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.AdminAddWalletRequest true "Wallet payload"
// @Success 200 {object} response.ApiResponse{data=mdb.WalletAddress}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets [post]
func (c *BaseAdminController) AdminAddWallet(ctx echo.Context) error {
req := new(AdminAddWalletRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
row, err := data.AddWalletAddressWithNetwork(req.Network, req.Address)
if err != nil {
return c.FailJson(ctx, err)
}
// Patch remark/source separately to avoid changing the existing
// package-level AddWalletAddressWithNetwork signature (used by
// Telegram bot + legacy endpoint).
fields := map[string]interface{}{"source": mdb.WalletSourceManual}
if req.Remark != "" {
fields["remark"] = req.Remark
}
_ = dao.Mdb.Model(&mdb.WalletAddress{}).Where("id = ?", row.ID).Updates(fields).Error
row.Remark = req.Remark
row.Source = mdb.WalletSourceManual
return c.SucJson(ctx, row)
}
// AdminGetWallet returns detail including order count for one wallet.
// @Summary Get wallet (admin)
// @Description Returns wallet detail with order count
// @Tags Admin Wallets
// @Security AdminJWT
// @Produce json
// @Param id path int true "Wallet ID"
// @Success 200 {object} response.ApiResponse{data=admin.WalletListItem}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets/{id} [get]
func (c *BaseAdminController) AdminGetWallet(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
wallet, err := data.GetWalletAddressById(id)
if err != nil {
return c.FailJson(ctx, err)
}
if wallet.ID == 0 {
return c.FailJson(ctx, errors.New("wallet not found"))
}
counts, _ := data.CountOrdersByAddress()
return c.SucJson(ctx, WalletListItem{WalletAddress: *wallet, OrderCount: counts[wallet.Address]})
}
// AdminUpdateWallet only patches remark (status has its own endpoint).
// @Summary Update wallet (admin)
// @Description Patch wallet remark
// @Tags Admin Wallets
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "Wallet ID"
// @Param request body admin.AdminUpdateWalletRequest true "Fields to update"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets/{id} [patch]
func (c *BaseAdminController) AdminUpdateWallet(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(AdminUpdateWalletRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
fields := map[string]interface{}{}
if req.Remark != nil {
fields["remark"] = *req.Remark
}
if len(fields) == 0 {
return c.SucJson(ctx, nil)
}
if err := dao.Mdb.Model(&mdb.WalletAddress{}).Where("id = ?", id).Updates(fields).Error; err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// AdminChangeWalletStatus reuses existing helper.
// @Summary Change wallet status (admin)
// @Description Toggle enable/disable for a wallet (1=enabled, 2=disabled)
// @Tags Admin Wallets
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param id path int true "Wallet ID"
// @Param request body admin.AdminChangeWalletStatusRequest true "Status payload"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets/{id}/status [post]
func (c *BaseAdminController) AdminChangeWalletStatus(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
req := new(AdminChangeWalletStatusRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
if err := data.ChangeWalletAddressStatus(id, req.Status); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// AdminDeleteWallet soft-deletes the wallet.
// @Summary Delete wallet (admin)
// @Description Soft-delete a wallet
// @Tags Admin Wallets
// @Security AdminJWT
// @Produce json
// @Param id path int true "Wallet ID"
// @Success 200 {object} response.ApiResponse
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets/{id} [delete]
func (c *BaseAdminController) AdminDeleteWallet(ctx echo.Context) error {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
return c.FailJson(ctx, err)
}
if err := data.DeleteWalletAddressById(id); err != nil {
return c.FailJson(ctx, err)
}
return c.SucJson(ctx, nil)
}
// AdminBatchImportWallets accepts a list of addresses and creates
// them all as observation wallets. Per-row failures are collected and
// returned so the UI can surface which addresses already existed.
// @Summary Batch import wallets
// @Description Import multiple wallet addresses at once. Per-row status is returned.
// @Tags Admin Wallets
// @Security AdminJWT
// @Accept json
// @Produce json
// @Param request body admin.AdminBatchImportRequest true "Batch import payload"
// @Success 200 {object} response.ApiResponse{data=[]admin.BatchImportResult}
// @Failure 400 {object} response.ApiResponse
// @Router /admin/api/v1/wallets/batch-import [post]
func (c *BaseAdminController) AdminBatchImportWallets(ctx echo.Context) error {
req := new(AdminBatchImportRequest)
if err := ctx.Bind(req); err != nil {
return c.FailJson(ctx, err)
}
if err := c.ValidateStruct(ctx, req); err != nil {
return c.FailJson(ctx, err)
}
type result struct {
Address string `json:"address"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}
out := make([]result, 0, len(req.Addresses))
for _, addr := range req.Addresses {
row, err := data.AddWalletAddressWithNetwork(req.Network, addr)
if err != nil {
out = append(out, result{Address: addr, OK: false, Error: err.Error()})
continue
}
_ = dao.Mdb.Model(&mdb.WalletAddress{}).Where("id = ?", row.ID).
Update("source", mdb.WalletSourceImport).Error
out = append(out, result{Address: addr, OK: true})
}
return c.SucJson(ctx, out)
}