refactor: 大规模模块拆分与代码精简,新增 ai-pipeline/data-contracts 独立 crate

- 新增 aether-ai-pipeline 和 aether-data-contracts crate,将 pipeline 逻辑与数据契约从 gateway 中解耦
- 重构 admin handlers:拆分单体模块为 auth/billing/endpoint/features/model/observability/provider/system 等独立子模块
- 合并 chat/cli 重复代码路径:精简 conversion、finalize、planner 中的 sync/chat/cli 分支
- 重构 scheduler/executor/data 层,引入 facade 模式降低模块间耦合
- 移除冗余的 intent 模块,将 plan_fallback/policy/stream_path/sync_path 迁移至 executor
- 前端适配:调整 admin API 调用和 provider 模型测试对话框
This commit is contained in:
fawney19
2026-04-07 02:50:19 +08:00
parent 763ff03a7b
commit 5d96d6673b
732 changed files with 28589 additions and 20662 deletions
@@ -7,7 +7,7 @@ use super::{
normalize_admin_billing_required_text,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::unix_secs_to_rfc3339;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
@@ -288,12 +288,12 @@ async fn build_admin_create_dimension_collector_response(
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(
build_admin_billing_not_found_response("Dimension collector not found"),
),
crate::LocalMutationOutcome::Unavailable => Ok(
build_admin_billing_read_only_response("当前为只读模式,无法创建维度采集器"),
),
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法创建维度采集器",
)),
}
}
@@ -321,15 +321,15 @@ async fn build_admin_update_dimension_collector_response(
crate::LocalMutationOutcome::Applied(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
crate::LocalMutationOutcome::NotFound => Ok(
build_admin_billing_not_found_response("Dimension collector not found"),
),
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::Unavailable => Ok(
build_admin_billing_read_only_response("当前为只读模式,无法更新维度采集器"),
),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法更新维度采集器",
)),
}
}
@@ -0,0 +1,289 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
use regex::Regex;
use serde_json::json;
use sqlx::Row;
const ADMIN_BILLING_DATA_UNAVAILABLE_DETAIL: &str = "Admin billing data unavailable";
mod collectors;
mod payments;
mod presets;
mod rules;
mod wallets;
pub(crate) use self::payments::maybe_build_local_admin_payments_response;
pub(crate) use self::wallets::maybe_build_local_admin_wallets_response;
fn default_admin_billing_true() -> bool {
true
}
fn default_admin_billing_json_object() -> serde_json::Value {
json!({})
}
fn build_admin_billing_data_unavailable_response() -> Response<Body> {
(
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_BILLING_DATA_UNAVAILABLE_DETAIL })),
)
.into_response()
}
fn build_admin_billing_bad_request_response(detail: impl Into<String>) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
fn build_admin_billing_read_only_response(detail: &'static str) -> Response<Body> {
(
http::StatusCode::CONFLICT,
Json(json!({
"detail": detail,
"error_code": "read_only_mode",
})),
)
.into_response()
}
fn build_admin_billing_not_found_response(detail: &'static str) -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": detail })),
)
.into_response()
}
fn admin_billing_parse_page(query: Option<&str>) -> Result<u32, String> {
match query_param_value(query, "page") {
None => Ok(1),
Some(value) => {
let parsed = value
.parse::<u32>()
.map_err(|_| "page must be between 1 and 100000".to_string())?;
if !(1..=100_000).contains(&parsed) {
return Err("page must be between 1 and 100000".to_string());
}
Ok(parsed)
}
}
}
fn admin_billing_parse_page_size(query: Option<&str>) -> Result<u32, String> {
match query_param_value(query, "page_size") {
None => Ok(50),
Some(value) => {
let parsed = value
.parse::<u32>()
.map_err(|_| "page_size must be between 1 and 200".to_string())?;
if !(1..=200).contains(&parsed) {
return Err("page_size must be between 1 and 200".to_string());
}
Ok(parsed)
}
}
}
fn admin_billing_optional_filter(query: Option<&str>, key: &str) -> Option<String> {
query_param_value(query, key)
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn admin_billing_optional_bool_filter(
query: Option<&str>,
key: &str,
) -> Result<Option<bool>, String> {
match query_param_value(query, key) {
None => Ok(None),
Some(value) => match value.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" => Ok(Some(true)),
"false" | "0" | "no" => Ok(Some(false)),
_ => Err(format!("{key} must be a boolean")),
},
}
}
fn admin_billing_pages(total: u64, page_size: u32) -> u64 {
if total == 0 {
0
} else {
total.div_ceil(u64::from(page_size))
}
}
fn normalize_admin_billing_required_text(
value: &str,
field: &str,
max_len: usize,
) -> Result<String, String> {
let value = value.trim();
if value.is_empty() {
return Err(format!("{field} must be a non-empty string"));
}
if value.len() > max_len {
return Err(format!("{field} exceeds maximum length {max_len}"));
}
Ok(value.to_string())
}
fn normalize_admin_billing_optional_text(
value: Option<String>,
max_len: usize,
) -> Result<Option<String>, String> {
let Some(value) = value else {
return Ok(None);
};
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
if trimmed.len() > max_len {
return Err(format!("field exceeds maximum length {max_len}"));
}
Ok(Some(trimmed.to_string()))
}
fn admin_billing_validate_safe_expression(expression: &str) -> Result<(), String> {
let expression = expression.trim();
if expression.is_empty() {
return Err("expression must not be empty".to_string());
}
if expression.contains("__") {
return Err("Dunder names are not allowed".to_string());
}
let allowed_chars = Regex::new(r"^[A-Za-z0-9_+\-*/%().,\s]+$").expect("regex should compile");
if !allowed_chars.is_match(expression) {
return Err("Expression contains unsupported characters".to_string());
}
let identifier = Regex::new(r"[A-Za-z_][A-Za-z0-9_]*").expect("regex should compile");
const ALLOWED_FUNCTIONS: &[&str] = &["min", "max", "abs", "round", "int", "float"];
for matched in identifier.find_iter(expression) {
let name = matched.as_str();
let next_non_ws = expression[matched.end()..]
.chars()
.find(|value| !value.is_whitespace());
if next_non_ws == Some('(') && !ALLOWED_FUNCTIONS.iter().any(|value| value == &name) {
return Err(format!("Function not allowed: {name}"));
}
}
Ok(())
}
fn admin_billing_optional_epoch_value(
row: &sqlx::postgres::PgRow,
field: &str,
) -> Result<Option<String>, GatewayError> {
let value = row
.try_get::<Option<i64>, _>(field)
.map_err(|err| GatewayError::Internal(err.to_string()))?;
match value {
None => Ok(None),
Some(value) if value < 0 => Ok(None),
Some(value) => Ok(unix_secs_to_rfc3339(value as u64)),
}
}
pub(crate) async fn maybe_build_local_admin_billing_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("billing_manage") {
return Ok(None);
}
let path = request_context.request_path.as_str();
let is_billing_route = (request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
))
|| (request_context.request_method == http::Method::POST
&& matches!(
path,
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
))
|| (request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
))
|| (request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/billing/rules/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::POST
&& matches!(
path,
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
))
|| (request_context.request_method == http::Method::PUT
&& path.starts_with("/api/admin/billing/rules/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
))
|| (request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/billing/collectors/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::POST
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
))
|| (request_context.request_method == http::Method::PUT
&& path.starts_with("/api/admin/billing/collectors/")
&& path.matches('/').count() == 5);
if !is_billing_route {
return Ok(None);
}
if let Some(response) = presets::maybe_build_local_admin_billing_presets_response(
state,
request_context,
request_body,
)
.await?
{
return Ok(Some(response));
}
if let Some(response) =
rules::maybe_build_local_admin_billing_rules_response(state, request_context, request_body)
.await?
{
return Ok(Some(response));
}
if let Some(response) = collectors::maybe_build_local_admin_billing_collectors_response(
state,
request_context,
request_body,
)
.await?
{
return Ok(Some(response));
}
match decision.route_kind.as_deref() {
_ => Ok(Some(build_admin_billing_data_unavailable_response())),
}
}
@@ -0,0 +1,59 @@
use super::{
build_admin_payment_callback_payload, build_admin_payment_callback_payload_from_record,
build_admin_payments_bad_request_response, parse_admin_payments_limit,
parse_admin_payments_offset,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::query_param_value;
use crate::{AppState, GatewayError};
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn maybe_build_local_admin_payment_callbacks_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
route_kind: Option<&str>,
) -> Result<Option<Response<Body>>, GatewayError> {
match route_kind {
Some("list_callbacks") => Ok(Some(
build_admin_payment_callbacks_response(state, request_context).await?,
)),
_ => Ok(None),
}
}
async fn build_admin_payment_callbacks_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_payments_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let offset = match parse_admin_payments_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let payment_method = query_param_value(query, "payment_method");
let (items, total) = state
.list_admin_payment_callbacks(payment_method.as_deref(), limit, offset)
.await?
.unwrap_or_default();
Ok(Json(json!({
"items": items
.iter()
.map(build_admin_payment_callback_payload_from_record)
.collect::<Vec<_>>(),
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
@@ -0,0 +1,29 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use axum::{body::Body, response::Response};
mod callbacks;
mod orders;
#[path = "../../payment/postgres.rs"]
mod payment_postgres;
mod routes;
mod shared;
use self::shared::{
admin_payment_operator_id, admin_payment_order_id_from_detail_path,
admin_payment_order_id_from_suffix_path, build_admin_payment_callback_payload,
build_admin_payment_callback_payload_from_record, build_admin_payment_order_not_found_response,
build_admin_payment_order_payload, build_admin_payment_orders_page_response,
build_admin_payments_backend_unavailable_response, build_admin_payments_bad_request_response,
build_admin_payments_data_unavailable_response, normalize_admin_payment_currency,
normalize_admin_payment_optional_string, normalize_admin_payment_positive_number,
parse_admin_payments_limit, parse_admin_payments_offset, AdminPaymentOrderCreditRequest,
};
pub(crate) async fn maybe_build_local_admin_payments_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_payments_response(state, request_context, request_body).await
}
@@ -0,0 +1,275 @@
use super::{
admin_payment_operator_id, admin_payment_order_id_from_detail_path,
admin_payment_order_id_from_suffix_path, build_admin_payment_order_not_found_response,
build_admin_payment_order_payload, build_admin_payment_orders_page_response,
build_admin_payments_backend_unavailable_response, build_admin_payments_bad_request_response,
normalize_admin_payment_currency, normalize_admin_payment_optional_string,
normalize_admin_payment_positive_number, parse_admin_payments_limit,
parse_admin_payments_offset, AdminPaymentOrderCreditRequest,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{attach_admin_audit_response, query_param_value};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn maybe_build_local_admin_payment_orders_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
route_kind: Option<&str>,
) -> Result<Option<Response<Body>>, GatewayError> {
match route_kind {
Some("list_orders") => Ok(Some(
build_admin_payment_list_orders_response(state, request_context).await?,
)),
Some("get_order") => Ok(Some(
build_admin_payment_get_order_response(state, request_context).await?,
)),
Some("expire_order") => Ok(Some(
build_admin_payment_expire_order_response(state, request_context).await?,
)),
Some("credit_order") => Ok(Some(
build_admin_payment_credit_order_response(state, request_context, request_body).await?,
)),
Some("fail_order") => Ok(Some(
build_admin_payment_fail_order_response(state, request_context).await?,
)),
_ => Ok(None),
}
}
async fn build_admin_payment_list_orders_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_payments_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let offset = match parse_admin_payments_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let payment_method = query_param_value(query, "payment_method");
let Some((items, total)) = state
.list_admin_payment_orders(status.as_deref(), payment_method.as_deref(), limit, offset)
.await?
else {
return Ok(build_admin_payment_orders_page_response(
Vec::new(),
0,
limit,
offset,
));
};
Ok(build_admin_payment_orders_page_response(
items
.iter()
.map(build_admin_payment_order_payload)
.collect::<Vec<_>>(),
total,
limit,
offset,
))
}
async fn build_admin_payment_get_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) = admin_payment_order_id_from_detail_path(&request_context.request_path)
else {
return Ok(build_admin_payment_order_not_found_response());
};
match state.read_admin_payment_order(&order_id).await? {
crate::AdminWalletMutationOutcome::Applied(order) => Ok(Json(json!({
"order": build_admin_payment_order_payload(&order),
}))
.into_response()),
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_payment_order_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_payments_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_payments_backend_unavailable_response(
"Payment order read backend unavailable",
))
}
}
}
async fn build_admin_payment_expire_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) =
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/expire")
else {
return Ok(build_admin_payment_order_not_found_response());
};
match state.admin_expire_payment_order(&order_id).await? {
crate::AdminWalletMutationOutcome::Applied((order, expired)) => {
Ok(attach_admin_audit_response(
Json(json!({
"order": build_admin_payment_order_payload(&order),
"expired": expired,
}))
.into_response(),
"admin_payment_order_expired",
"expire_payment_order",
"payment_order",
&order_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_payment_order_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_payments_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_payments_backend_unavailable_response(
"Payment order write backend unavailable",
))
}
}
}
async fn build_admin_payment_credit_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) =
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/credit")
else {
return Ok(build_admin_payment_order_not_found_response());
};
let payload = match request_body {
Some(body) if !body.is_empty() => {
match serde_json::from_slice::<AdminPaymentOrderCreditRequest>(body) {
Ok(value) => value,
Err(_) => {
return Ok(build_admin_payments_bad_request_response(
"请求数据验证失败",
));
}
}
}
_ => AdminPaymentOrderCreditRequest::default(),
};
let gateway_order_id = match normalize_admin_payment_optional_string(
payload.gateway_order_id,
"gateway_order_id",
128,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let pay_amount = match normalize_admin_payment_positive_number(payload.pay_amount, "pay_amount")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let pay_currency = match normalize_admin_payment_currency(payload.pay_currency) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
let exchange_rate =
match normalize_admin_payment_positive_number(payload.exchange_rate, "exchange_rate") {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
};
if payload
.gateway_response
.as_ref()
.is_some_and(|value| !value.is_object())
{
return Ok(build_admin_payments_bad_request_response(
"gateway_response 必须为对象",
));
}
let operator_id = admin_payment_operator_id(request_context);
match state
.admin_credit_payment_order(
&order_id,
gateway_order_id.as_deref(),
pay_amount,
pay_currency.as_deref(),
exchange_rate,
payload.gateway_response,
operator_id.as_deref(),
)
.await?
{
crate::AdminWalletMutationOutcome::Applied((order, credited)) => {
Ok(attach_admin_audit_response(
Json(json!({
"order": build_admin_payment_order_payload(&order),
"credited": credited,
}))
.into_response(),
"admin_payment_order_credited",
"credit_payment_order",
"payment_order",
&order_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_payment_order_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_payments_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_payments_backend_unavailable_response(
"Payment order write backend unavailable",
))
}
}
}
async fn build_admin_payment_fail_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) =
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/fail")
else {
return Ok(build_admin_payment_order_not_found_response());
};
match state.admin_fail_payment_order(&order_id).await? {
crate::AdminWalletMutationOutcome::Applied(order) => Ok(attach_admin_audit_response(
Json(json!({
"order": build_admin_payment_order_payload(&order),
}))
.into_response(),
"admin_payment_order_failed",
"fail_payment_order",
"payment_order",
&order_id,
)),
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_payment_order_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_payments_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_payments_backend_unavailable_response(
"Payment order write backend unavailable",
))
}
}
}
@@ -0,0 +1,72 @@
use super::{
build_admin_payments_data_unavailable_response,
callbacks::maybe_build_local_admin_payment_callbacks_response,
orders::maybe_build_local_admin_payment_orders_response,
};
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use axum::{body::Body, http, response::Response};
pub(super) async fn maybe_build_local_admin_payments_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("payments_manage") {
return Ok(None);
}
let normalized_path = request_context.request_path.trim_end_matches('/');
let path = if normalized_path.is_empty() {
request_context.request_path.as_str()
} else {
normalized_path
};
let is_payments_route = (request_context.request_method == http::Method::GET
&& path == "/api/admin/payments/orders")
|| (request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/payments/orders/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::POST
&& path.starts_with("/api/admin/payments/orders/")
&& path.ends_with("/expire")
&& path.matches('/').count() == 6)
|| (request_context.request_method == http::Method::POST
&& path.starts_with("/api/admin/payments/orders/")
&& path.ends_with("/credit")
&& path.matches('/').count() == 6)
|| (request_context.request_method == http::Method::POST
&& path.starts_with("/api/admin/payments/orders/")
&& path.ends_with("/fail")
&& path.matches('/').count() == 6)
|| (request_context.request_method == http::Method::GET
&& path == "/api/admin/payments/callbacks");
if !is_payments_route {
return Ok(None);
}
let route_kind = decision.route_kind.as_deref();
if let Some(response) = maybe_build_local_admin_payment_orders_response(
state,
request_context,
request_body,
route_kind,
)
.await?
{
return Ok(Some(response));
}
if let Some(response) =
maybe_build_local_admin_payment_callbacks_response(state, request_context, route_kind)
.await?
{
return Ok(Some(response));
}
Ok(Some(build_admin_payments_data_unavailable_response()))
}
@@ -0,0 +1,270 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{GatewayAdminPaymentCallbackView, GatewayError};
use axum::{
body::Body,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
use sqlx::Row;
const ADMIN_PAYMENTS_DATA_UNAVAILABLE_DETAIL: &str = "Admin payments data unavailable";
#[derive(Debug, Default, serde::Deserialize)]
pub(super) struct AdminPaymentOrderCreditRequest {
#[serde(default)]
pub(super) gateway_order_id: Option<String>,
#[serde(default)]
pub(super) pay_amount: Option<f64>,
#[serde(default)]
pub(super) pay_currency: Option<String>,
#[serde(default)]
pub(super) exchange_rate: Option<f64>,
#[serde(default)]
pub(super) gateway_response: Option<serde_json::Value>,
}
pub(super) fn build_admin_payments_data_unavailable_response() -> Response<Body> {
(
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_PAYMENTS_DATA_UNAVAILABLE_DETAIL })),
)
.into_response()
}
pub(super) fn build_admin_payments_bad_request_response(
detail: impl Into<String>,
) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(super) fn build_admin_payments_backend_unavailable_response(
detail: impl Into<String>,
) -> Response<Body> {
(
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(super) fn build_admin_payment_order_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Payment order not found" })),
)
.into_response()
}
pub(super) fn build_admin_payment_orders_page_response(
items: Vec<serde_json::Value>,
total: u64,
limit: usize,
offset: usize,
) -> Response<Body> {
Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response()
}
pub(super) fn parse_admin_payments_limit(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "limit") {
Some(value) => {
let parsed = value
.parse::<usize>()
.map_err(|_| "limit must be an integer between 1 and 200".to_string())?;
if (1..=200).contains(&parsed) {
Ok(parsed)
} else {
Err("limit must be an integer between 1 and 200".to_string())
}
}
None => Ok(50),
}
}
pub(super) fn parse_admin_payments_offset(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "offset") {
Some(value) => value
.parse::<usize>()
.map_err(|_| "offset must be a non-negative integer".to_string()),
None => Ok(0),
}
}
pub(super) fn admin_payment_order_id_from_detail_path(request_path: &str) -> Option<String> {
request_path
.strip_prefix("/api/admin/payments/orders/")?
.trim()
.trim_matches('/')
.split('/')
.next()
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| !value.contains('/'))
.map(ToOwned::to_owned)
}
pub(super) fn admin_payment_order_id_from_suffix_path(
request_path: &str,
suffix: &str,
) -> Option<String> {
request_path
.trim()
.trim_end_matches('/')
.strip_prefix("/api/admin/payments/orders/")?
.strip_suffix(suffix)
.map(|value| value.trim().trim_matches('/').to_string())
.filter(|value| !value.is_empty() && !value.contains('/'))
}
pub(super) fn normalize_admin_payment_optional_string(
value: Option<String>,
field_name: &str,
max_len: usize,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(Some(trimmed.to_string()))
}
}
}
pub(super) fn normalize_admin_payment_currency(
value: Option<String>,
) -> Result<Option<String>, String> {
let Some(value) = normalize_admin_payment_optional_string(value, "pay_currency", 3)? else {
return Ok(None);
};
let normalized = value.to_ascii_uppercase();
if normalized.len() != 3 {
return Err("pay_currency 必须是 3 位货币代码".to_string());
}
Ok(Some(normalized))
}
pub(super) fn normalize_admin_payment_positive_number(
value: Option<f64>,
field_name: &str,
) -> Result<Option<f64>, String> {
let Some(value) = value else {
return Ok(None);
};
if !value.is_finite() || value <= 0.0 {
return Err(format!("{field_name} 必须为大于 0 的有限数字"));
}
Ok(Some(value))
}
pub(super) fn admin_payment_operator_id(
request_context: &GatewayPublicRequestContext,
) -> Option<String> {
request_context
.control_decision
.as_ref()
.and_then(|decision| decision.admin_principal.as_ref())
.map(|principal| principal.user_id.clone())
}
pub(super) fn admin_payment_effective_status(
status: &str,
expires_at_unix_secs: Option<u64>,
) -> String {
let now_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
if status == "pending" && expires_at_unix_secs.is_some_and(|value| value < now_unix_secs) {
"expired".to_string()
} else {
status.to_string()
}
}
pub(super) fn build_admin_payment_order_payload(
record: &crate::AdminWalletPaymentOrderRecord,
) -> serde_json::Value {
json!({
"id": record.id,
"order_no": record.order_no,
"wallet_id": record.wallet_id,
"user_id": record.user_id,
"amount_usd": record.amount_usd,
"pay_amount": record.pay_amount,
"pay_currency": record.pay_currency,
"exchange_rate": record.exchange_rate,
"refunded_amount_usd": record.refunded_amount_usd,
"refundable_amount_usd": record.refundable_amount_usd,
"payment_method": record.payment_method,
"gateway_order_id": record.gateway_order_id,
"gateway_response": record.gateway_response,
"status": admin_payment_effective_status(&record.status, record.expires_at_unix_secs),
"created_at": unix_secs_to_rfc3339(record.created_at_unix_secs),
"paid_at": record.paid_at_unix_secs.and_then(unix_secs_to_rfc3339),
"credited_at": record.credited_at_unix_secs.and_then(unix_secs_to_rfc3339),
"expires_at": record.expires_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
}
pub(super) fn build_admin_payment_callback_payload(
row: &sqlx::postgres::PgRow,
) -> Result<serde_json::Value, GatewayError> {
Ok(json!({
"id": row.try_get::<String, _>("id").map_err(|err| GatewayError::Internal(err.to_string()))?,
"payment_order_id": row.try_get::<Option<String>, _>("payment_order_id").map_err(|err| GatewayError::Internal(err.to_string()))?,
"payment_method": row.try_get::<String, _>("payment_method").map_err(|err| GatewayError::Internal(err.to_string()))?,
"callback_key": row.try_get::<String, _>("callback_key").map_err(|err| GatewayError::Internal(err.to_string()))?,
"order_no": row.try_get::<Option<String>, _>("order_no").map_err(|err| GatewayError::Internal(err.to_string()))?,
"gateway_order_id": row.try_get::<Option<String>, _>("gateway_order_id").map_err(|err| GatewayError::Internal(err.to_string()))?,
"payload_hash": row.try_get::<Option<String>, _>("payload_hash").map_err(|err| GatewayError::Internal(err.to_string()))?,
"signature_valid": row.try_get::<bool, _>("signature_valid").map_err(|err| GatewayError::Internal(err.to_string()))?,
"status": row.try_get::<String, _>("status").map_err(|err| GatewayError::Internal(err.to_string()))?,
"payload": row.try_get::<Option<serde_json::Value>, _>("payload").map_err(|err| GatewayError::Internal(err.to_string()))?,
"error_message": row.try_get::<Option<String>, _>("error_message").map_err(|err| GatewayError::Internal(err.to_string()))?,
"created_at": row
.try_get::<Option<i64>, _>("created_at_unix_secs")
.map_err(|err| GatewayError::Internal(err.to_string()))?
.and_then(|value| u64::try_from(value).ok())
.and_then(unix_secs_to_rfc3339),
"processed_at": row
.try_get::<Option<i64>, _>("processed_at_unix_secs")
.map_err(|err| GatewayError::Internal(err.to_string()))?
.and_then(|value| u64::try_from(value).ok())
.and_then(unix_secs_to_rfc3339),
}))
}
pub(super) fn build_admin_payment_callback_payload_from_record(
record: &GatewayAdminPaymentCallbackView,
) -> serde_json::Value {
json!({
"id": record.id,
"payment_order_id": record.payment_order_id,
"payment_method": record.payment_method,
"callback_key": record.callback_key,
"order_no": record.order_no,
"gateway_order_id": record.gateway_order_id,
"payload_hash": record.payload_hash,
"signature_valid": record.signature_valid,
"status": record.status,
"payload": record.payload,
"error_message": record.error_message,
"created_at": unix_secs_to_rfc3339(record.created_at_unix_secs),
"processed_at": record.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
}
@@ -3,7 +3,7 @@ use super::{
build_admin_billing_read_only_response, normalize_admin_billing_required_text,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::misc_helpers::attach_admin_audit_response;
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
@@ -37,8 +37,7 @@ fn build_admin_billing_presets_payload() -> serde_json::Value {
})
}
fn build_admin_billing_aether_core_collectors(
) -> Vec<crate::AdminBillingCollectorWriteInput> {
fn build_admin_billing_aether_core_collectors() -> Vec<crate::AdminBillingCollectorWriteInput> {
vec![
crate::AdminBillingCollectorWriteInput {
api_format: "OPENAI:CHAT".to_string(),
@@ -237,10 +236,7 @@ fn build_admin_billing_aether_core_collectors(
fn resolve_admin_billing_preset_collectors(
preset: &str,
) -> Option<(
&'static str,
Vec<crate::AdminBillingCollectorWriteInput>,
)> {
) -> Option<(&'static str, Vec<crate::AdminBillingCollectorWriteInput>)> {
let normalized = preset.trim().to_ascii_lowercase();
match normalized.as_str() {
"aether-core" | "default" => {
@@ -323,15 +319,15 @@ async fn build_admin_apply_billing_preset_response(
resolved_preset,
))
}
crate::LocalMutationOutcome::Unavailable => Ok(
build_admin_billing_read_only_response("当前为只读模式,无法应用计费预设"),
),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法应用计费预设",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(
build_admin_billing_not_found_response("Billing preset not found"),
),
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Billing preset not found",
)),
}
}
@@ -7,7 +7,7 @@ use super::{
normalize_admin_billing_optional_text, normalize_admin_billing_required_text,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::unix_secs_to_rfc3339;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
@@ -245,12 +245,12 @@ async fn build_admin_create_billing_rule_response(
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(
build_admin_billing_not_found_response("Billing rule not found"),
),
crate::LocalMutationOutcome::Unavailable => Ok(
build_admin_billing_read_only_response("当前为只读模式,无法创建计费规则"),
),
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Billing rule not found",
)),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法创建计费规则",
)),
}
}
@@ -270,15 +270,15 @@ async fn build_admin_update_billing_rule_response(
crate::LocalMutationOutcome::Applied(record) => {
Ok(Json(build_admin_billing_rule_payload_from_record(&record)).into_response())
}
crate::LocalMutationOutcome::NotFound => Ok(
build_admin_billing_not_found_response("Billing rule not found"),
),
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Billing rule not found",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::Unavailable => Ok(
build_admin_billing_read_only_response("当前为只读模式,无法更新计费规则"),
),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法更新计费规则",
)),
}
}
@@ -0,0 +1,17 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use axum::{body::Body, response::Response};
mod mutations;
mod reads;
mod routes;
mod shared;
pub(crate) async fn maybe_build_local_admin_wallets_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_wallets_routes_response(state, request_context, request_body)
.await
}
@@ -0,0 +1,474 @@
use super::shared::{
admin_wallet_id_from_suffix_path, admin_wallet_operator_id,
admin_wallet_refund_ids_from_suffix_path, build_admin_wallet_not_found_response,
build_admin_wallet_payment_order_payload, build_admin_wallet_refund_not_found_response,
build_admin_wallet_refund_payload, build_admin_wallet_summary_payload,
build_admin_wallet_transaction_payload, build_admin_wallets_bad_request_response,
build_admin_wallets_data_unavailable_response, normalize_admin_wallet_balance_type,
normalize_admin_wallet_description, normalize_admin_wallet_non_zero_amount,
normalize_admin_wallet_optional_text, normalize_admin_wallet_payment_method,
normalize_admin_wallet_positive_amount, normalize_admin_wallet_required_text,
resolve_admin_wallet_owner_summary, AdminWalletAdjustRequest, AdminWalletRechargeRequest,
AdminWalletRefundCompleteRequest, AdminWalletRefundFailRequest,
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL, ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_wallet_adjust_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/adjust")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletAdjustRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let amount_usd = match normalize_admin_wallet_non_zero_amount(payload.amount_usd, "amount_usd")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let balance_type = match normalize_admin_wallet_balance_type(payload.balance_type) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let description = match normalize_admin_wallet_description(payload.description) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() && balance_type == "gift" {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
let has_postgres = state.postgres_pool().is_some();
let Some((wallet, transaction)) = state
.admin_adjust_wallet_balance(
&wallet_id,
amount_usd,
&balance_type,
operator_id.as_deref(),
description.as_deref(),
)
.await?
else {
return if has_postgres {
Ok(build_admin_wallet_not_found_response())
} else {
Ok(build_admin_wallets_data_unavailable_response())
};
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let transaction_payload = build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
);
let response = Json(json!({
"wallet": wallet_payload,
"transaction": transaction_payload,
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_balance_adjusted",
"adjust_wallet_balance",
"wallet",
&wallet_id,
))
}
pub(super) async fn build_admin_wallet_recharge_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/recharge")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRechargeRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let amount_usd = match normalize_admin_wallet_positive_amount(payload.amount_usd, "amount_usd")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let payment_method = match normalize_admin_wallet_payment_method(payload.payment_method) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let description = match normalize_admin_wallet_description(payload.description) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
let has_postgres = state.postgres_pool().is_some();
let Some((wallet, payment_order)) = state
.admin_create_manual_wallet_recharge(
&wallet_id,
amount_usd,
&payment_method,
operator_id.as_deref(),
description.as_deref(),
)
.await?
else {
return if has_postgres {
Ok(build_admin_wallet_not_found_response())
} else {
Ok(build_admin_wallets_data_unavailable_response())
};
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"payment_order": build_admin_wallet_payment_order_payload(
payment_order.id,
payment_order.order_no,
payment_order.amount_usd,
payment_order.payment_method,
payment_order.status,
unix_secs_to_rfc3339(payment_order.created_at_unix_secs),
payment_order
.credited_at_unix_secs
.and_then(unix_secs_to_rfc3339),
),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_manual_recharge_created",
"create_manual_wallet_recharge",
"wallet",
&wallet_id,
))
}
pub(super) async fn build_admin_wallet_process_refund_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(&request_context.request_path, "/process")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
match state
.admin_process_wallet_refund(&wallet_id, &refund_id, operator_id.as_deref())
.await?
{
crate::AdminWalletMutationOutcome::Applied((wallet, refund, transaction)) => {
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
"transaction": build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_processed",
"process_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}
pub(super) async fn build_admin_wallet_complete_refund_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(&request_context.request_path, "/complete")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRefundCompleteRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let gateway_refund_id = match normalize_admin_wallet_optional_text(
payload.gateway_refund_id,
"gateway_refund_id",
128,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let payout_reference = match normalize_admin_wallet_optional_text(
payload.payout_reference,
"payout_reference",
255,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
if payload
.payout_proof
.as_ref()
.is_some_and(|value| !value.is_object())
{
return Ok(build_admin_wallets_bad_request_response(
"payout_proof 必须为对象",
));
}
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
match state
.admin_complete_wallet_refund(
&wallet_id,
&refund_id,
gateway_refund_id.as_deref(),
payout_reference.as_deref(),
payload.payout_proof,
)
.await?
{
crate::AdminWalletMutationOutcome::Applied(refund) => {
let response = Json(json!({
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_completed",
"complete_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
let detail = if detail == "refund status must be processing before completion" {
"只有 processing 状态的退款可以标记完成".to_string()
} else {
detail
};
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}
pub(super) async fn build_admin_wallet_fail_refund_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(&request_context.request_path, "/fail")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRefundFailRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let reason = match normalize_admin_wallet_required_text(payload.reason, "reason", 500) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
match state
.admin_fail_wallet_refund(&wallet_id, &refund_id, &reason, operator_id.as_deref())
.await?
{
crate::AdminWalletMutationOutcome::Applied((wallet, refund, transaction)) => {
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
"transaction": transaction.map(|transaction| build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
)).unwrap_or(serde_json::Value::Null),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_failed",
"fail_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}
@@ -0,0 +1,388 @@
use super::shared::{
admin_wallet_id_from_detail_path, admin_wallet_id_from_suffix_path,
build_admin_wallet_not_found_response, build_admin_wallet_refund_payload,
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
parse_admin_wallets_limit, parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
resolve_admin_wallet_owner_summary, wallet_owner_summary_from_fields,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_wallet_detail_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_detail_path(&request_context.request_path) else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let mut payload = build_admin_wallet_summary_payload(&wallet, &owner);
if let Some(object) = payload.as_object_mut() {
object.insert("pending_refund_count".to_string(), serde_json::Value::Null);
}
Ok(Json(payload).into_response())
}
pub(super) async fn build_admin_wallet_list_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let owner_type = parse_admin_wallets_owner_type_filter(query);
let (wallets, total) = state
.list_admin_wallets(status.as_deref(), owner_type.as_deref(), limit, offset)
.await?;
let items = wallets
.into_iter()
.map(|wallet| {
let owner = wallet_owner_summary_from_fields(
wallet.user_id.as_deref(),
wallet.user_name.clone(),
wallet.api_key_id.as_deref(),
wallet.api_key_name.clone(),
);
json!({
"id": wallet.id,
"user_id": wallet.user_id,
"api_key_id": wallet.api_key_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"balance": wallet.balance + wallet.gift_balance,
"recharge_balance": wallet.balance,
"gift_balance": wallet.gift_balance,
"refundable_balance": wallet.balance,
"currency": wallet.currency,
"status": wallet.status,
"limit_mode": wallet.limit_mode.clone(),
"unlimited": wallet.limit_mode.eq_ignore_ascii_case("unlimited"),
"total_recharged": wallet.total_recharged,
"total_consumed": wallet.total_consumed,
"total_refunded": wallet.total_refunded,
"total_adjusted": wallet.total_adjusted,
"created_at": wallet.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
"updated_at": wallet.updated_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
})
.collect::<Vec<_>>();
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_ledger_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let category = query_param_value(query, "category");
let reason_code = query_param_value(query, "reason_code");
let owner_type = parse_admin_wallets_owner_type_filter(query);
let (ledger, total) = state
.list_admin_wallet_ledger(
category.as_deref(),
reason_code.as_deref(),
owner_type.as_deref(),
limit,
offset,
)
.await?;
let items = ledger
.into_iter()
.map(|entry| {
let owner = wallet_owner_summary_from_fields(
entry.wallet_user_id.as_deref(),
entry.wallet_user_name.clone(),
entry.wallet_api_key_id.as_deref(),
entry.api_key_name.clone(),
);
json!({
"id": entry.id,
"wallet_id": entry.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"wallet_status": entry.wallet_status,
"category": entry.category,
"reason_code": entry.reason_code,
"amount": entry.amount,
"balance_before": entry.balance_before,
"balance_after": entry.balance_after,
"recharge_balance_before": entry.recharge_balance_before,
"recharge_balance_after": entry.recharge_balance_after,
"gift_balance_before": entry.gift_balance_before,
"gift_balance_after": entry.gift_balance_after,
"link_type": entry.link_type,
"link_id": entry.link_id,
"operator_id": entry.operator_id,
"operator_name": entry.operator_name,
"operator_email": entry.operator_email,
"description": entry.description,
"created_at": entry.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
})
.collect::<Vec<_>>();
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_refund_requests_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let owner_type = parse_admin_wallets_owner_type_filter(query);
if owner_type.as_deref() == Some("api_key") {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let (refunds, total) = state
.list_admin_wallet_refund_requests(status.as_deref(), limit, offset)
.await?;
let mut items = Vec::with_capacity(refunds.len());
for refund in refunds {
let mut owner = wallet_owner_summary_from_fields(
refund.wallet_user_id.as_deref(),
refund.wallet_user_name.clone(),
refund.wallet_api_key_id.as_deref(),
refund.api_key_name.clone(),
);
if owner.owner_name.is_none() {
if let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&refund.wallet_id,
))
.await?
{
owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
}
}
items.push(json!({
"id": refund.id,
"refund_no": refund.refund_no,
"wallet_id": refund.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"wallet_status": refund.wallet_status,
"user_id": refund.user_id,
"payment_order_id": refund.payment_order_id,
"source_type": refund.source_type,
"source_id": refund.source_id,
"refund_mode": refund.refund_mode,
"amount_usd": refund.amount_usd,
"status": refund.status,
"reason": refund.reason,
"failure_reason": refund.failure_reason,
"gateway_refund_id": refund.gateway_refund_id,
"payout_method": refund.payout_method,
"payout_reference": refund.payout_reference,
"payout_proof": refund.payout_proof,
"requested_by": refund.requested_by,
"approved_by": refund.approved_by,
"processed_by": refund.processed_by,
"created_at": refund.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
"updated_at": refund.updated_at_unix_secs.and_then(unix_secs_to_rfc3339),
"processed_at": refund.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
"completed_at": refund.completed_at_unix_secs.and_then(unix_secs_to_rfc3339),
}));
}
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_transactions_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/transactions")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let limit = match parse_admin_wallets_limit(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let (transactions, total) = state
.list_admin_wallet_transactions(&wallet.id, limit, offset)
.await?;
let mut items = Vec::with_capacity(transactions.len());
for transaction in transactions {
let (operator_name, operator_email) =
if transaction.operator_name.is_some() || transaction.operator_email.is_some() {
(transaction.operator_name, transaction.operator_email)
} else {
match transaction.operator_id.as_deref() {
Some(operator_id) => state
.find_user_auth_by_id(operator_id)
.await?
.map(|user| (Some(user.username), user.email))
.unwrap_or((None, None)),
None => (None, None),
}
};
items.push(json!({
"id": transaction.id,
"wallet_id": transaction.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status.clone(),
"category": transaction.category,
"reason_code": transaction.reason_code,
"amount": transaction.amount,
"balance_before": transaction.balance_before,
"balance_after": transaction.balance_after,
"recharge_balance_before": transaction.recharge_balance_before,
"recharge_balance_after": transaction.recharge_balance_after,
"gift_balance_before": transaction.gift_balance_before,
"gift_balance_after": transaction.gift_balance_after,
"link_type": transaction.link_type,
"link_id": transaction.link_id,
"operator_id": transaction.operator_id,
"operator_name": operator_name,
"operator_email": operator_email,
"description": transaction.description,
"created_at": transaction.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
}));
}
Ok(Json(json!({
"wallet": wallet_payload,
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_refunds_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/refunds")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let limit = match parse_admin_wallets_limit(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let (refunds, total) = state
.list_admin_wallet_refunds(&wallet.id, limit, offset)
.await?;
let items = refunds
.into_iter()
.map(|refund| build_admin_wallet_refund_payload(&wallet, &owner, &refund))
.collect::<Vec<_>>();
Ok(Json(json!({
"wallet": wallet_payload,
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
@@ -0,0 +1,149 @@
use super::mutations::{
build_admin_wallet_adjust_response, build_admin_wallet_complete_refund_response,
build_admin_wallet_fail_refund_response, build_admin_wallet_process_refund_response,
build_admin_wallet_recharge_response,
};
use super::reads::{
build_admin_wallet_detail_response, build_admin_wallet_ledger_response,
build_admin_wallet_list_response, build_admin_wallet_refund_requests_response,
build_admin_wallet_refunds_response, build_admin_wallet_transactions_response,
};
use super::shared::build_admin_wallets_data_unavailable_response;
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use axum::{body::Body, http, response::Response};
pub(super) async fn maybe_build_local_admin_wallets_routes_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("wallets_manage") {
return Ok(None);
}
let path = request_context.request_path.as_str();
let is_wallets_route = (request_context.request_method == http::Method::GET
&& matches!(path, "/api/admin/wallets" | "/api/admin/wallets/"))
|| (request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/wallets/ledger" | "/api/admin/wallets/ledger/"
))
|| (request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/wallets/refund-requests" | "/api/admin/wallets/refund-requests/"
))
|| (request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/wallets/")
&& path.ends_with("/transactions"))
|| (request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/wallets/")
&& path.ends_with("/refunds"))
|| (request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/wallets/")
&& !path.ends_with("/transactions")
&& !path.ends_with("/refunds")
&& path.matches('/').count() == 4)
|| (request_context.request_method == http::Method::POST
&& matches!(
decision.route_kind.as_deref(),
Some(
"adjust_balance"
| "recharge_balance"
| "process_refund"
| "complete_refund"
| "fail_refund"
)
));
if !is_wallets_route {
return Ok(None);
}
if decision.route_kind.as_deref() == Some("wallet_detail")
&& request_context.request_method == http::Method::GET
{
return Ok(Some(
build_admin_wallet_detail_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_wallets")
&& request_context.request_method == http::Method::GET
{
return Ok(Some(
build_admin_wallet_list_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("ledger")
&& request_context.request_method == http::Method::GET
{
return Ok(Some(
build_admin_wallet_ledger_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_refund_requests")
&& request_context.request_method == http::Method::GET
{
return Ok(Some(
build_admin_wallet_refund_requests_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_wallet_transactions")
&& request_context.request_method == http::Method::GET
{
return Ok(Some(
build_admin_wallet_transactions_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_wallet_refunds")
&& request_context.request_method == http::Method::GET
{
return Ok(Some(
build_admin_wallet_refunds_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("adjust_balance")
&& request_context.request_method == http::Method::POST
{
return Ok(Some(
build_admin_wallet_adjust_response(state, request_context, request_body).await?,
));
}
if decision.route_kind.as_deref() == Some("recharge_balance")
&& request_context.request_method == http::Method::POST
{
return Ok(Some(
build_admin_wallet_recharge_response(state, request_context, request_body).await?,
));
}
if decision.route_kind.as_deref() == Some("process_refund")
&& request_context.request_method == http::Method::POST
{
return Ok(Some(
build_admin_wallet_process_refund_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("complete_refund")
&& request_context.request_method == http::Method::POST
{
return Ok(Some(
build_admin_wallet_complete_refund_response(state, request_context, request_body)
.await?,
));
}
if decision.route_kind.as_deref() == Some("fail_refund")
&& request_context.request_method == http::Method::POST
{
return Ok(Some(
build_admin_wallet_fail_refund_response(state, request_context, request_body).await?,
));
}
Ok(Some(build_admin_wallets_data_unavailable_response()))
}
@@ -0,0 +1,580 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
use sqlx::Row;
pub(super) const ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL: &str = "Admin wallets data unavailable";
pub(super) const ADMIN_WALLETS_API_KEY_REFUND_DETAIL: &str = "独立密钥钱包不支持退款审批";
pub(super) const ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL: &str = "独立密钥钱包不支持充值,请使用调账";
pub(super) const ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL: &str = "独立密钥钱包不支持赠款调账";
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletRechargeRequest {
pub(super) amount_usd: f64,
#[serde(default = "default_admin_wallet_payment_method")]
pub(super) payment_method: String,
#[serde(default)]
pub(super) description: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletAdjustRequest {
pub(super) amount_usd: f64,
#[serde(default = "default_admin_wallet_balance_type")]
pub(super) balance_type: String,
#[serde(default)]
pub(super) description: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletRefundFailRequest {
pub(super) reason: String,
}
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletRefundCompleteRequest {
#[serde(default)]
pub(super) gateway_refund_id: Option<String>,
#[serde(default)]
pub(super) payout_reference: Option<String>,
#[serde(default)]
pub(super) payout_proof: Option<serde_json::Value>,
}
fn default_admin_wallet_payment_method() -> String {
"admin_manual".to_string()
}
fn default_admin_wallet_balance_type() -> String {
"recharge".to_string()
}
pub(super) fn build_admin_wallets_data_unavailable_response() -> Response<Body> {
(
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL })),
)
.into_response()
}
pub(super) fn build_admin_wallets_bad_request_response(
detail: impl Into<String>,
) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(super) fn build_admin_wallet_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Wallet not found" })),
)
.into_response()
}
pub(super) fn build_admin_wallet_refund_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Refund request not found" })),
)
.into_response()
}
pub(super) fn build_admin_wallet_payment_order_payload(
order_id: String,
order_no: String,
amount_usd: f64,
payment_method: String,
status: String,
created_at: Option<String>,
credited_at: Option<String>,
) -> serde_json::Value {
json!({
"id": order_id,
"order_no": order_no,
"amount_usd": amount_usd,
"payment_method": payment_method,
"status": status,
"created_at": created_at,
"credited_at": credited_at,
})
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_admin_wallet_transaction_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
transaction_id: String,
category: &str,
reason_code: &str,
amount: f64,
balance_before: f64,
balance_after: f64,
recharge_balance_before: f64,
recharge_balance_after: f64,
gift_balance_before: f64,
gift_balance_after: f64,
link_type: Option<&str>,
link_id: Option<&str>,
operator_id: Option<&str>,
description: Option<&str>,
created_at: Option<String>,
) -> serde_json::Value {
json!({
"id": transaction_id,
"wallet_id": wallet.id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status,
"category": category,
"reason_code": reason_code,
"amount": amount,
"balance_before": balance_before,
"balance_after": balance_after,
"recharge_balance_before": recharge_balance_before,
"recharge_balance_after": recharge_balance_after,
"gift_balance_before": gift_balance_before,
"gift_balance_after": gift_balance_after,
"link_type": link_type,
"link_id": link_id,
"operator_id": operator_id,
"operator_name": serde_json::Value::Null,
"operator_email": serde_json::Value::Null,
"description": description,
"created_at": created_at,
})
}
pub(super) fn admin_wallet_build_order_no(now: chrono::DateTime<chrono::Utc>) -> String {
format!(
"po_{}_{}",
now.format("%Y%m%d%H%M%S%6f"),
&uuid::Uuid::new_v4().simple().to_string()[..12]
)
}
pub(super) fn normalize_admin_wallet_description(
value: Option<String>,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
Ok(Some(trimmed.chars().take(500).collect()))
}
}
}
pub(super) fn normalize_admin_wallet_required_text(
value: String,
field_name: &str,
max_len: usize,
) -> Result<String, String> {
let trimmed = value.trim();
if trimmed.is_empty() {
return Err(format!("{field_name} 不能为空"));
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(trimmed.to_string())
}
pub(super) fn normalize_admin_wallet_optional_text(
value: Option<String>,
field_name: &str,
max_len: usize,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(Some(trimmed.to_string()))
}
}
}
pub(super) fn normalize_admin_wallet_payment_method(value: String) -> Result<String, String> {
let normalized = value.trim();
if normalized.is_empty() {
return Err("payment_method 不能为空".to_string());
}
Ok(normalized.chars().take(30).collect())
}
pub(super) fn normalize_admin_wallet_balance_type(value: String) -> Result<String, String> {
let normalized = value.trim().to_ascii_lowercase();
match normalized.as_str() {
"recharge" | "gift" => Ok(normalized),
_ => Err("balance_type 必须为 recharge 或 gift".to_string()),
}
}
pub(super) fn normalize_admin_wallet_positive_amount(
value: f64,
field_name: &str,
) -> Result<f64, String> {
if !value.is_finite() || value <= 0.0 {
return Err(format!("{field_name} 必须为大于 0 的有限数字"));
}
Ok(value)
}
pub(super) fn normalize_admin_wallet_non_zero_amount(
value: f64,
field_name: &str,
) -> Result<f64, String> {
if !value.is_finite() || value == 0.0 {
return Err(format!("{field_name} 不能为 0,且必须为有限数字"));
}
Ok(value)
}
pub(super) fn admin_wallet_operator_id(
request_context: &GatewayPublicRequestContext,
) -> Option<String> {
request_context
.control_decision
.as_ref()
.and_then(|decision| decision.admin_principal.as_ref())
.map(|principal| principal.user_id.clone())
}
pub(super) fn admin_wallet_recharge_reason_code(payment_method: &str) -> &'static str {
match payment_method {
"card_code" | "gift_code" | "card_recharge" => "topup_card_code",
_ => "topup_admin_manual",
}
}
pub(super) fn admin_wallet_apply_manual_recharge_to_snapshot(
wallet: &mut aether_data::repository::wallet::StoredWalletSnapshot,
amount_usd: f64,
) -> (f64, f64, f64, f64, f64, f64) {
let recharge_before = wallet.balance;
let gift_before = wallet.gift_balance;
let balance_before = recharge_before + gift_before;
wallet.balance += amount_usd;
wallet.total_recharged += amount_usd;
wallet.updated_at_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
let recharge_after = wallet.balance;
let gift_after = wallet.gift_balance;
let balance_after = recharge_after + gift_after;
(
balance_before,
balance_after,
recharge_before,
recharge_after,
gift_before,
gift_after,
)
}
pub(super) fn admin_wallet_apply_adjust_to_snapshot(
wallet: &mut aether_data::repository::wallet::StoredWalletSnapshot,
amount_usd: f64,
balance_type: &str,
) -> Result<(f64, f64, f64, f64, f64, f64), String> {
if amount_usd == 0.0 {
return Err("adjust amount must not be zero".to_string());
}
if balance_type == "gift" && wallet.api_key_id.is_some() {
return Err(ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL.to_string());
}
let recharge_before = wallet.balance;
let gift_before = wallet.gift_balance;
let balance_before = recharge_before + gift_before;
let mut recharge_after = recharge_before;
let mut gift_after = gift_before;
if amount_usd > 0.0 {
if balance_type == "gift" {
gift_after += amount_usd;
} else {
recharge_after += amount_usd;
}
} else {
let mut remaining = -amount_usd;
let consume_positive_bucket = |balance: &mut f64, remaining: &mut f64| {
if *remaining <= 0.0 {
return;
}
let available = balance.max(0.0);
let consumed = available.min(*remaining);
*balance -= consumed;
*remaining -= consumed;
};
if balance_type == "gift" {
consume_positive_bucket(&mut gift_after, &mut remaining);
consume_positive_bucket(&mut recharge_after, &mut remaining);
} else {
consume_positive_bucket(&mut recharge_after, &mut remaining);
consume_positive_bucket(&mut gift_after, &mut remaining);
}
if remaining > 0.0 {
recharge_after -= remaining;
}
if gift_after < 0.0 {
return Err("gift balance cannot be negative".to_string());
}
}
wallet.balance = recharge_after;
wallet.gift_balance = gift_after;
wallet.total_adjusted += amount_usd;
wallet.updated_at_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
Ok((
balance_before,
recharge_after + gift_after,
recharge_before,
recharge_after,
gift_before,
gift_after,
))
}
pub(super) fn admin_wallet_id_from_detail_path(request_path: &str) -> Option<String> {
request_path
.strip_prefix("/api/admin/wallets/")?
.trim()
.trim_matches('/')
.split('/')
.next()
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| !value.contains('/'))
.map(ToOwned::to_owned)
}
pub(super) fn admin_wallet_id_from_suffix_path(request_path: &str, suffix: &str) -> Option<String> {
request_path
.strip_prefix("/api/admin/wallets/")?
.strip_suffix(suffix)
.map(|value| value.trim().trim_matches('/').to_string())
.filter(|value| !value.is_empty() && !value.contains('/'))
}
pub(super) fn admin_wallet_refund_ids_from_suffix_path(
request_path: &str,
suffix: &str,
) -> Option<(String, String)> {
let trimmed = request_path
.strip_prefix("/api/admin/wallets/")?
.strip_suffix(suffix)?
.trim()
.trim_matches('/');
let mut segments = trimmed.split('/');
let wallet_id = segments.next()?.trim();
let literal = segments.next()?.trim();
let refund_id = segments.next()?.trim();
if literal != "refunds"
|| wallet_id.is_empty()
|| refund_id.is_empty()
|| wallet_id.contains('/')
|| refund_id.contains('/')
|| segments.next().is_some()
{
return None;
}
Some((wallet_id.to_string(), refund_id.to_string()))
}
pub(super) fn parse_admin_wallets_limit(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "limit") {
Some(value) => {
let parsed = value
.parse::<usize>()
.map_err(|_| "limit must be an integer between 1 and 200".to_string())?;
if (1..=200).contains(&parsed) {
Ok(parsed)
} else {
Err("limit must be an integer between 1 and 200".to_string())
}
}
None => Ok(50),
}
}
pub(super) fn parse_admin_wallets_offset(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "offset") {
Some(value) => value
.parse::<usize>()
.map_err(|_| "offset must be a non-negative integer".to_string()),
None => Ok(0),
}
}
pub(super) fn parse_admin_wallets_owner_type_filter(query: Option<&str>) -> Option<String> {
match query_param_value(query, "owner_type") {
Some(value) if value.eq_ignore_ascii_case("user") => Some("user".to_string()),
Some(value) if value.eq_ignore_ascii_case("api_key") => Some("api_key".to_string()),
_ => None,
}
}
pub(super) fn wallet_owner_summary_from_fields(
user_id: Option<&str>,
user_name: Option<String>,
api_key_id: Option<&str>,
api_key_name: Option<String>,
) -> AdminWalletOwnerSummary {
if user_id.is_some() {
return AdminWalletOwnerSummary {
owner_type: "user",
owner_name: user_name,
};
}
if let Some(api_key_id) = api_key_id {
return AdminWalletOwnerSummary {
owner_type: "api_key",
owner_name: api_key_name
.filter(|value| !value.trim().is_empty())
.or_else(|| Some(format!("Key-{}", &api_key_id[..api_key_id.len().min(8)]))),
};
}
AdminWalletOwnerSummary {
owner_type: "orphaned",
owner_name: None,
}
}
pub(super) fn optional_epoch_value(
row: &sqlx::postgres::PgRow,
key: &str,
) -> Result<Option<String>, GatewayError> {
Ok(row
.try_get::<Option<i64>, _>(key)
.map_err(|err| GatewayError::Internal(err.to_string()))?
.and_then(|value| u64::try_from(value).ok())
.and_then(unix_secs_to_rfc3339))
}
#[derive(Clone)]
pub(super) struct AdminWalletOwnerSummary {
pub(super) owner_type: &'static str,
pub(super) owner_name: Option<String>,
}
pub(super) async fn resolve_admin_wallet_owner_summary(
state: &AppState,
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
) -> Result<AdminWalletOwnerSummary, GatewayError> {
if let Some(user_id) = wallet.user_id.as_deref() {
let user = state.find_user_auth_by_id(user_id).await?;
Ok(AdminWalletOwnerSummary {
owner_type: "user",
owner_name: user.map(|record| record.username),
})
} else if let Some(api_key_id) = wallet.api_key_id.as_deref() {
let api_key_ids = vec![api_key_id.to_string()];
let snapshots = state
.data
.list_auth_api_key_snapshots_by_ids(&api_key_ids)
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?;
let owner_name = snapshots
.into_iter()
.find(|snapshot| snapshot.api_key_id == api_key_id)
.and_then(|snapshot| snapshot.api_key_name)
.filter(|value| !value.trim().is_empty())
.or_else(|| Some(format!("Key-{}", &api_key_id[..api_key_id.len().min(8)])));
Ok(AdminWalletOwnerSummary {
owner_type: "api_key",
owner_name,
})
} else {
Ok(AdminWalletOwnerSummary {
owner_type: "orphaned",
owner_name: None,
})
}
}
pub(super) fn build_admin_wallet_summary_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
) -> serde_json::Value {
json!({
"id": wallet.id.clone(),
"user_id": wallet.user_id.clone(),
"api_key_id": wallet.api_key_id.clone(),
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"balance": wallet.balance + wallet.gift_balance,
"recharge_balance": wallet.balance,
"gift_balance": wallet.gift_balance,
"refundable_balance": wallet.balance,
"currency": wallet.currency.clone(),
"status": wallet.status.clone(),
"limit_mode": wallet.limit_mode.clone(),
"unlimited": wallet.limit_mode.eq_ignore_ascii_case("unlimited"),
"total_recharged": wallet.total_recharged,
"total_consumed": wallet.total_consumed,
"total_refunded": wallet.total_refunded,
"total_adjusted": wallet.total_adjusted,
"created_at": serde_json::Value::Null,
"updated_at": unix_secs_to_rfc3339(wallet.updated_at_unix_secs),
})
}
pub(super) fn build_admin_wallet_refund_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
refund: &crate::AdminWalletRefundRecord,
) -> serde_json::Value {
json!({
"id": refund.id.clone(),
"refund_no": refund.refund_no.clone(),
"wallet_id": refund.wallet_id.clone(),
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status.clone(),
"user_id": refund.user_id.clone(),
"payment_order_id": refund.payment_order_id.clone(),
"source_type": refund.source_type.clone(),
"source_id": refund.source_id.clone(),
"refund_mode": refund.refund_mode.clone(),
"amount_usd": refund.amount_usd,
"status": refund.status.clone(),
"reason": refund.reason.clone(),
"failure_reason": refund.failure_reason.clone(),
"gateway_refund_id": refund.gateway_refund_id.clone(),
"payout_method": refund.payout_method.clone(),
"payout_reference": refund.payout_reference.clone(),
"payout_proof": refund.payout_proof.clone(),
"requested_by": refund.requested_by.clone(),
"approved_by": refund.approved_by.clone(),
"processed_by": refund.processed_by.clone(),
"created_at": unix_secs_to_rfc3339(refund.created_at_unix_secs),
"updated_at": unix_secs_to_rfc3339(refund.updated_at_unix_secs),
"processed_at": refund.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
"completed_at": refund.completed_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
}