mirror of
https://github.com/fawney19/Aether.git
synced 2026-10-07 18:07:47 +08:00
refactor: 大规模模块拆分与重组,新增 aether-admin crate
- 新建独立 aether-admin crate 承载 admin 相关共享契约与纯辅助函数 - 拆分 ai_pipeline 下 kiro/private_envelope/conversion/planner 等大文件为子模块目录 - 重组 admin handlers 各业务域(billing/oauth/provider/system/users 等)为目录结构,移除 shared.rs/builders.rs 等反模式 - 移除 ai_pipeline runtime adapters 旧实现(claude/openai/gemini/kiro/vertex/antigravity 等),改由 provider transport 统一承载 - 移除 control_facade/execution_facade/auth_snapshot_facade 等冗余 facade 层 - 拆分 query/billing 与 query/monitoring 模块、state/runtime/payments 与 security 模块 - 扩展架构测试覆盖 admin_billing/admin_model/admin_users 等新模块 - 删除 docs/architecture/refactor-execution-plan.md 已完成的执行计划文档
This commit is contained in:
@@ -1,392 +0,0 @@
|
||||
use super::{
|
||||
admin_billing_optional_bool_filter, admin_billing_optional_filter, admin_billing_pages,
|
||||
admin_billing_parse_page, admin_billing_parse_page_size,
|
||||
admin_billing_validate_safe_expression, build_admin_billing_bad_request_response,
|
||||
build_admin_billing_not_found_response, build_admin_billing_read_only_response,
|
||||
default_admin_billing_true, normalize_admin_billing_optional_text,
|
||||
normalize_admin_billing_required_text,
|
||||
};
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
|
||||
use crate::{AppState, GatewayError};
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
fn default_admin_billing_collector_value_type() -> String {
|
||||
"float".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AdminBillingCollectorUpsertRequest {
|
||||
api_format: String,
|
||||
task_type: String,
|
||||
dimension_name: String,
|
||||
source_type: String,
|
||||
#[serde(default)]
|
||||
source_path: Option<String>,
|
||||
#[serde(default = "default_admin_billing_collector_value_type")]
|
||||
value_type: String,
|
||||
#[serde(default)]
|
||||
transform_expression: Option<String>,
|
||||
#[serde(default)]
|
||||
default_value: Option<String>,
|
||||
#[serde(default)]
|
||||
priority: i32,
|
||||
#[serde(default = "default_admin_billing_true")]
|
||||
is_enabled: bool,
|
||||
}
|
||||
|
||||
fn build_admin_billing_collector_payload_from_record(
|
||||
record: &crate::AdminBillingCollectorRecord,
|
||||
) -> serde_json::Value {
|
||||
json!({
|
||||
"id": record.id,
|
||||
"api_format": record.api_format,
|
||||
"task_type": record.task_type,
|
||||
"dimension_name": record.dimension_name,
|
||||
"source_type": record.source_type,
|
||||
"source_path": record.source_path,
|
||||
"value_type": record.value_type,
|
||||
"transform_expression": record.transform_expression,
|
||||
"default_value": record.default_value,
|
||||
"priority": record.priority,
|
||||
"is_enabled": record.is_enabled,
|
||||
"created_at": unix_secs_to_rfc3339(record.created_at_unix_secs),
|
||||
"updated_at": unix_secs_to_rfc3339(record.updated_at_unix_secs),
|
||||
})
|
||||
}
|
||||
|
||||
fn admin_billing_collector_id_from_path(request_path: &str) -> Option<String> {
|
||||
let value = request_path
|
||||
.strip_prefix("/api/admin/billing/collectors/")?
|
||||
.trim()
|
||||
.trim_matches('/')
|
||||
.to_string();
|
||||
if value.is_empty() || value.contains('/') {
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_admin_list_dimension_collectors_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.request_query_string.as_deref();
|
||||
let page = match admin_billing_parse_page(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let page_size = match admin_billing_parse_page_size(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let api_format = admin_billing_optional_filter(query, "api_format");
|
||||
let task_type = admin_billing_optional_filter(query, "task_type");
|
||||
let dimension_name = admin_billing_optional_filter(query, "dimension_name");
|
||||
let is_enabled = match admin_billing_optional_bool_filter(query, "is_enabled") {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
|
||||
let (items, total) = state
|
||||
.list_admin_billing_collectors(
|
||||
api_format.as_deref(),
|
||||
task_type.as_deref(),
|
||||
dimension_name.as_deref(),
|
||||
is_enabled,
|
||||
page,
|
||||
page_size,
|
||||
)
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(Json(json!({
|
||||
"items": items
|
||||
.iter()
|
||||
.map(build_admin_billing_collector_payload_from_record)
|
||||
.collect::<Vec<_>>(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": admin_billing_pages(total, page_size),
|
||||
}))
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn build_admin_get_dimension_collector_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(collector_id) = admin_billing_collector_id_from_path(&request_context.request_path)
|
||||
else {
|
||||
return Ok(build_admin_billing_bad_request_response(
|
||||
"缺少 collector_id",
|
||||
));
|
||||
};
|
||||
|
||||
match state.read_admin_billing_collector(&collector_id).await? {
|
||||
Some(record) => {
|
||||
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
|
||||
}
|
||||
None => Ok(build_admin_billing_not_found_response(
|
||||
"Dimension collector not found",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn parse_admin_billing_collector_request(
|
||||
state: &AppState,
|
||||
request_body: Option<&Bytes>,
|
||||
existing_id: Option<&str>,
|
||||
) -> Result<crate::AdminBillingCollectorWriteInput, Response<Body>> {
|
||||
let Some(request_body) = request_body else {
|
||||
return Err(build_admin_billing_bad_request_response("请求体不能为空"));
|
||||
};
|
||||
let request = match serde_json::from_slice::<AdminBillingCollectorUpsertRequest>(request_body) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
return Err(build_admin_billing_bad_request_response(format!(
|
||||
"Invalid request body: {err}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
|
||||
let api_format =
|
||||
match normalize_admin_billing_required_text(&request.api_format, "api_format", 50) {
|
||||
Ok(value) => value.to_ascii_uppercase(),
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let task_type = match normalize_admin_billing_required_text(&request.task_type, "task_type", 20)
|
||||
{
|
||||
Ok(value) => value.to_ascii_lowercase(),
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let dimension_name =
|
||||
match normalize_admin_billing_required_text(&request.dimension_name, "dimension_name", 100)
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let source_type = request.source_type.trim().to_ascii_lowercase();
|
||||
if !matches!(
|
||||
source_type.as_str(),
|
||||
"request" | "response" | "metadata" | "computed"
|
||||
) {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"source_type must be one of request, response, metadata, computed",
|
||||
));
|
||||
}
|
||||
let value_type = request.value_type.trim().to_ascii_lowercase();
|
||||
if !matches!(value_type.as_str(), "float" | "int" | "string") {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"value_type must be one of float, int, string",
|
||||
));
|
||||
}
|
||||
let source_path = match normalize_admin_billing_optional_text(request.source_path, 200) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let transform_expression =
|
||||
match normalize_admin_billing_optional_text(request.transform_expression, 4096) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let default_value = match normalize_admin_billing_optional_text(request.default_value, 100) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
|
||||
if source_type == "computed" {
|
||||
if source_path.is_some() {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"computed collector must have source_path=null",
|
||||
));
|
||||
}
|
||||
if transform_expression.is_none() {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"computed collector must have transform_expression",
|
||||
));
|
||||
}
|
||||
} else if source_path.is_none() {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"non-computed collector must have source_path",
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(transform_expression) = transform_expression.as_deref() {
|
||||
if let Err(detail) = admin_billing_validate_safe_expression(transform_expression) {
|
||||
return Err(build_admin_billing_bad_request_response(format!(
|
||||
"Invalid transform_expression: {detail}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if default_value.is_some() && request.is_enabled {
|
||||
match state
|
||||
.admin_billing_enabled_default_value_exists(
|
||||
&api_format,
|
||||
&task_type,
|
||||
&dimension_name,
|
||||
existing_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"default_value already exists for this (api_format, task_type, dimension_name)",
|
||||
))
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(err) => {
|
||||
let detail = match err {
|
||||
GatewayError::Internal(message) => message,
|
||||
other => format!("{other:?}"),
|
||||
};
|
||||
return Err((
|
||||
http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({ "detail": detail })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(crate::AdminBillingCollectorWriteInput {
|
||||
api_format,
|
||||
task_type,
|
||||
dimension_name,
|
||||
source_type,
|
||||
source_path,
|
||||
value_type,
|
||||
transform_expression,
|
||||
default_value,
|
||||
priority: request.priority,
|
||||
is_enabled: request.is_enabled,
|
||||
})
|
||||
}
|
||||
|
||||
async fn build_admin_create_dimension_collector_response(
|
||||
state: &AppState,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let input = match parse_admin_billing_collector_request(state, request_body, None).await {
|
||||
Ok(value) => value,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
match state.create_admin_billing_collector(&input).await? {
|
||||
crate::LocalMutationOutcome::Applied(record) => {
|
||||
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_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(
|
||||
"当前为只读模式,无法创建维度采集器",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_admin_update_dimension_collector_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(collector_id) = admin_billing_collector_id_from_path(&request_context.request_path)
|
||||
else {
|
||||
return Ok(build_admin_billing_bad_request_response(
|
||||
"缺少 collector_id",
|
||||
));
|
||||
};
|
||||
let input =
|
||||
match parse_admin_billing_collector_request(state, request_body, Some(&collector_id)).await
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
match state
|
||||
.update_admin_billing_collector(&collector_id, &input)
|
||||
.await?
|
||||
{
|
||||
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::Invalid(detail) => {
|
||||
Ok(build_admin_billing_bad_request_response(detail))
|
||||
}
|
||||
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
|
||||
"当前为只读模式,无法更新维度采集器",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_billing_collectors_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);
|
||||
};
|
||||
let path = request_context.request_path.as_str();
|
||||
|
||||
match decision.route_kind.as_deref() {
|
||||
Some("list_collectors")
|
||||
if request_context.request_method == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
build_admin_list_dimension_collectors_response(state, request_context).await?,
|
||||
))
|
||||
}
|
||||
Some("get_collector")
|
||||
if request_context.request_method == http::Method::GET
|
||||
&& path.starts_with("/api/admin/billing/collectors/") =>
|
||||
{
|
||||
Ok(Some(
|
||||
build_admin_get_dimension_collector_response(state, request_context).await?,
|
||||
))
|
||||
}
|
||||
Some("create_collector")
|
||||
if request_context.request_method == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
build_admin_create_dimension_collector_response(state, request_body).await?,
|
||||
))
|
||||
}
|
||||
Some("update_collector")
|
||||
if request_context.request_method == http::Method::PUT
|
||||
&& path.starts_with("/api/admin/billing/collectors/") =>
|
||||
{
|
||||
Ok(Some(
|
||||
build_admin_update_dimension_collector_response(
|
||||
state,
|
||||
request_context,
|
||||
request_body,
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
mod reads;
|
||||
mod support;
|
||||
mod writes;
|
||||
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http,
|
||||
response::Response,
|
||||
};
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_billing_collectors_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
let Some(decision) = request_context.decision() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = request_context.path();
|
||||
|
||||
match decision.route_kind.as_deref() {
|
||||
Some("list_collectors")
|
||||
if request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
reads::build_admin_list_dimension_collectors_response(state, request_context)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
Some("get_collector")
|
||||
if request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/billing/collectors/") =>
|
||||
{
|
||||
Ok(Some(
|
||||
reads::build_admin_get_dimension_collector_response(state, request_context).await?,
|
||||
))
|
||||
}
|
||||
Some("create_collector")
|
||||
if request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
writes::build_admin_create_dimension_collector_response(state, request_body)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
Some("update_collector")
|
||||
if request_context.method() == http::Method::PUT
|
||||
&& path.starts_with("/api/admin/billing/collectors/") =>
|
||||
{
|
||||
Ok(Some(
|
||||
writes::build_admin_update_dimension_collector_response(
|
||||
state,
|
||||
request_context,
|
||||
request_body,
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use super::support::{
|
||||
admin_billing_collector_id_from_path, admin_billing_optional_bool_filter,
|
||||
admin_billing_optional_filter, admin_billing_pages, admin_billing_parse_page,
|
||||
admin_billing_parse_page_size, build_admin_billing_bad_request_response,
|
||||
build_admin_billing_collector_payload_from_record, build_admin_billing_not_found_response,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) async fn build_admin_list_dimension_collectors_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.query_string();
|
||||
let page = match admin_billing_parse_page(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let page_size = match admin_billing_parse_page_size(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let api_format = admin_billing_optional_filter(query, "api_format");
|
||||
let task_type = admin_billing_optional_filter(query, "task_type");
|
||||
let dimension_name = admin_billing_optional_filter(query, "dimension_name");
|
||||
let is_enabled = match admin_billing_optional_bool_filter(query, "is_enabled") {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
|
||||
let (items, total) = state
|
||||
.list_admin_billing_collectors(
|
||||
api_format.as_deref(),
|
||||
task_type.as_deref(),
|
||||
dimension_name.as_deref(),
|
||||
is_enabled,
|
||||
page,
|
||||
page_size,
|
||||
)
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(Json(json!({
|
||||
"items": items
|
||||
.iter()
|
||||
.map(build_admin_billing_collector_payload_from_record)
|
||||
.collect::<Vec<_>>(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": admin_billing_pages(total, page_size),
|
||||
}))
|
||||
.into_response())
|
||||
}
|
||||
|
||||
pub(super) async fn build_admin_get_dimension_collector_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(collector_id) = admin_billing_collector_id_from_path(request_context.path()) else {
|
||||
return Ok(build_admin_billing_bad_request_response(
|
||||
"缺少 collector_id",
|
||||
));
|
||||
};
|
||||
|
||||
match state.read_admin_billing_collector(&collector_id).await? {
|
||||
Some(record) => {
|
||||
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
|
||||
}
|
||||
None => Ok(build_admin_billing_not_found_response(
|
||||
"Dimension collector not found",
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
use super::super::{
|
||||
admin_billing_validate_safe_expression, default_admin_billing_true,
|
||||
normalize_admin_billing_optional_text, normalize_admin_billing_required_text,
|
||||
};
|
||||
use crate::handlers::admin::request::AdminAppState;
|
||||
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
fn default_admin_billing_collector_value_type() -> String {
|
||||
"float".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct AdminBillingCollectorUpsertRequest {
|
||||
pub(super) api_format: String,
|
||||
pub(super) task_type: String,
|
||||
pub(super) dimension_name: String,
|
||||
pub(super) source_type: String,
|
||||
#[serde(default)]
|
||||
pub(super) source_path: Option<String>,
|
||||
#[serde(default = "default_admin_billing_collector_value_type")]
|
||||
pub(super) value_type: String,
|
||||
#[serde(default)]
|
||||
pub(super) transform_expression: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) default_value: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) priority: i32,
|
||||
#[serde(default = "default_admin_billing_true")]
|
||||
pub(super) is_enabled: bool,
|
||||
}
|
||||
|
||||
pub(super) fn build_admin_billing_collector_payload_from_record(
|
||||
record: &crate::AdminBillingCollectorRecord,
|
||||
) -> serde_json::Value {
|
||||
json!({
|
||||
"id": record.id,
|
||||
"api_format": record.api_format,
|
||||
"task_type": record.task_type,
|
||||
"dimension_name": record.dimension_name,
|
||||
"source_type": record.source_type,
|
||||
"source_path": record.source_path,
|
||||
"value_type": record.value_type,
|
||||
"transform_expression": record.transform_expression,
|
||||
"default_value": record.default_value,
|
||||
"priority": record.priority,
|
||||
"is_enabled": record.is_enabled,
|
||||
"created_at": unix_secs_to_rfc3339(record.created_at_unix_secs),
|
||||
"updated_at": unix_secs_to_rfc3339(record.updated_at_unix_secs),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn admin_billing_collector_id_from_path(request_path: &str) -> Option<String> {
|
||||
let value = request_path
|
||||
.strip_prefix("/api/admin/billing/collectors/")?
|
||||
.trim()
|
||||
.trim_matches('/')
|
||||
.to_string();
|
||||
if value.is_empty() || value.contains('/') {
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn parse_admin_billing_collector_request(
|
||||
state: &AdminAppState<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
existing_id: Option<&str>,
|
||||
) -> Result<crate::AdminBillingCollectorWriteInput, Response<Body>> {
|
||||
let Some(request_body) = request_body else {
|
||||
return Err(build_admin_billing_bad_request_response("请求体不能为空"));
|
||||
};
|
||||
let request = match serde_json::from_slice::<AdminBillingCollectorUpsertRequest>(request_body) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
return Err(build_admin_billing_bad_request_response(format!(
|
||||
"Invalid request body: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let api_format =
|
||||
match normalize_admin_billing_required_text(&request.api_format, "api_format", 50) {
|
||||
Ok(value) => value.to_ascii_uppercase(),
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let task_type = match normalize_admin_billing_required_text(&request.task_type, "task_type", 20)
|
||||
{
|
||||
Ok(value) => value.to_ascii_lowercase(),
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let dimension_name =
|
||||
match normalize_admin_billing_required_text(&request.dimension_name, "dimension_name", 100)
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let source_type = request.source_type.trim().to_ascii_lowercase();
|
||||
if !matches!(
|
||||
source_type.as_str(),
|
||||
"request" | "response" | "metadata" | "computed"
|
||||
) {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"source_type must be one of request, response, metadata, computed",
|
||||
));
|
||||
}
|
||||
let value_type = request.value_type.trim().to_ascii_lowercase();
|
||||
if !matches!(value_type.as_str(), "float" | "int" | "string") {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"value_type must be one of float, int, string",
|
||||
));
|
||||
}
|
||||
let source_path = match normalize_admin_billing_optional_text(request.source_path, 200) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let transform_expression =
|
||||
match normalize_admin_billing_optional_text(request.transform_expression, 4096) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
let default_value = match normalize_admin_billing_optional_text(request.default_value, 100) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
|
||||
};
|
||||
|
||||
if source_type == "computed" {
|
||||
if source_path.is_some() {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"computed collector must have source_path=null",
|
||||
));
|
||||
}
|
||||
if transform_expression.is_none() {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"computed collector must have transform_expression",
|
||||
));
|
||||
}
|
||||
} else if source_path.is_none() {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"non-computed collector must have source_path",
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(transform_expression) = transform_expression.as_deref() {
|
||||
if let Err(detail) = admin_billing_validate_safe_expression(transform_expression) {
|
||||
return Err(build_admin_billing_bad_request_response(format!(
|
||||
"Invalid transform_expression: {detail}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if default_value.is_some() && request.is_enabled {
|
||||
match state
|
||||
.admin_billing_enabled_default_value_exists(
|
||||
&api_format,
|
||||
&task_type,
|
||||
&dimension_name,
|
||||
existing_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => {
|
||||
return Err(build_admin_billing_bad_request_response(
|
||||
"default_value already exists for this (api_format, task_type, dimension_name)",
|
||||
));
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(err) => {
|
||||
let detail = match err {
|
||||
GatewayError::Internal(message) => message,
|
||||
other => format!("{other:?}"),
|
||||
};
|
||||
return Err((
|
||||
http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({ "detail": detail })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(crate::AdminBillingCollectorWriteInput {
|
||||
api_format,
|
||||
task_type,
|
||||
dimension_name,
|
||||
source_type,
|
||||
source_path,
|
||||
value_type,
|
||||
transform_expression,
|
||||
default_value,
|
||||
priority: request.priority,
|
||||
is_enabled: request.is_enabled,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in super::super) fn admin_billing_parse_page(query: Option<&str>) -> Result<u32, String> {
|
||||
super::super::admin_billing_parse_page(query)
|
||||
}
|
||||
|
||||
pub(in super::super) fn admin_billing_parse_page_size(query: Option<&str>) -> Result<u32, String> {
|
||||
super::super::admin_billing_parse_page_size(query)
|
||||
}
|
||||
|
||||
pub(in super::super) fn admin_billing_optional_filter(
|
||||
query: Option<&str>,
|
||||
key: &str,
|
||||
) -> Option<String> {
|
||||
super::super::admin_billing_optional_filter(query, key)
|
||||
}
|
||||
|
||||
pub(in super::super) fn admin_billing_optional_bool_filter(
|
||||
query: Option<&str>,
|
||||
key: &str,
|
||||
) -> Result<Option<bool>, String> {
|
||||
super::super::admin_billing_optional_bool_filter(query, key)
|
||||
}
|
||||
|
||||
pub(in super::super) fn admin_billing_pages(total: u64, page_size: u32) -> u64 {
|
||||
super::super::admin_billing_pages(total, page_size)
|
||||
}
|
||||
|
||||
pub(in super::super) fn build_admin_billing_bad_request_response(
|
||||
detail: impl Into<String>,
|
||||
) -> Response<Body> {
|
||||
super::super::build_admin_billing_bad_request_response(detail)
|
||||
}
|
||||
|
||||
pub(in super::super) fn build_admin_billing_not_found_response(
|
||||
detail: &'static str,
|
||||
) -> Response<Body> {
|
||||
super::super::build_admin_billing_not_found_response(detail)
|
||||
}
|
||||
|
||||
pub(in super::super) fn build_admin_billing_read_only_response(
|
||||
detail: &'static str,
|
||||
) -> Response<Body> {
|
||||
super::super::build_admin_billing_read_only_response(detail)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use super::support::{
|
||||
admin_billing_collector_id_from_path, build_admin_billing_bad_request_response,
|
||||
build_admin_billing_collector_payload_from_record, build_admin_billing_not_found_response,
|
||||
build_admin_billing_read_only_response, parse_admin_billing_collector_request,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
|
||||
pub(super) async fn build_admin_create_dimension_collector_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let input = match parse_admin_billing_collector_request(state, request_body, None).await {
|
||||
Ok(value) => value,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
match state.create_admin_billing_collector(&input).await? {
|
||||
crate::LocalMutationOutcome::Applied(record) => {
|
||||
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_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(
|
||||
"当前为只读模式,无法创建维度采集器",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn build_admin_update_dimension_collector_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(collector_id) = admin_billing_collector_id_from_path(request_context.path()) else {
|
||||
return Ok(build_admin_billing_bad_request_response(
|
||||
"缺少 collector_id",
|
||||
));
|
||||
};
|
||||
let input =
|
||||
match parse_admin_billing_collector_request(state, request_body, Some(&collector_id)).await
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
match state
|
||||
.update_admin_billing_collector(&collector_id, &input)
|
||||
.await?
|
||||
{
|
||||
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::Invalid(detail) => {
|
||||
Ok(build_admin_billing_bad_request_response(detail))
|
||||
}
|
||||
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
|
||||
"当前为只读模式,无法更新维度采集器",
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
|
||||
use crate::{AppState, GatewayError};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http,
|
||||
@@ -16,11 +16,13 @@ const ADMIN_BILLING_DATA_UNAVAILABLE_DETAIL: &str = "Admin billing data unavaila
|
||||
mod collectors;
|
||||
mod payments;
|
||||
mod presets;
|
||||
mod routes;
|
||||
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;
|
||||
pub(super) use self::payments::maybe_build_local_admin_payments_response;
|
||||
pub(super) use self::routes::maybe_build_local_admin_billing_routes_response;
|
||||
pub(super) use self::wallets::maybe_build_local_admin_wallets_response;
|
||||
|
||||
fn default_admin_billing_true() -> bool {
|
||||
true
|
||||
@@ -198,11 +200,11 @@ fn admin_billing_optional_epoch_value(
|
||||
}
|
||||
|
||||
pub(crate) async fn maybe_build_local_admin_billing_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
let Some(decision) = request_context.control_decision.as_ref() else {
|
||||
let Some(decision) = request_context.decision() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -210,47 +212,47 @@ pub(crate) async fn maybe_build_local_admin_billing_response(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let path = request_context.request_path.as_str();
|
||||
let is_billing_route = (request_context.request_method == http::Method::GET
|
||||
let path = request_context.path();
|
||||
let is_billing_route = (request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::POST
|
||||
|| (request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/billing/rules/")
|
||||
&& path.matches('/').count() == 5)
|
||||
|| (request_context.request_method == http::Method::POST
|
||||
|| (request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::PUT
|
||||
|| (request_context.method() == http::Method::PUT
|
||||
&& path.starts_with("/api/admin/billing/rules/")
|
||||
&& path.matches('/').count() == 5)
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/billing/collectors/")
|
||||
&& path.matches('/').count() == 5)
|
||||
|| (request_context.request_method == http::Method::POST
|
||||
|| (request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::PUT
|
||||
|| (request_context.method() == http::Method::PUT
|
||||
&& path.starts_with("/api/admin/billing/collectors/")
|
||||
&& path.matches('/').count() == 5);
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ use super::{
|
||||
build_admin_payments_bad_request_response, parse_admin_payments_limit,
|
||||
parse_admin_payments_offset,
|
||||
};
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::query_param_value;
|
||||
use crate::{AppState, GatewayError};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
@@ -14,8 +14,8 @@ use axum::{
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_payment_callbacks_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
route_kind: Option<&str>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
match route_kind {
|
||||
@@ -27,10 +27,10 @@ pub(super) async fn maybe_build_local_admin_payment_callbacks_response(
|
||||
}
|
||||
|
||||
async fn build_admin_payment_callbacks_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.request_query_string.as_deref();
|
||||
let query = request_context.query_string();
|
||||
let limit = match parse_admin_payments_limit(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::{AppState, GatewayError};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{body::Body, response::Response};
|
||||
|
||||
mod callbacks;
|
||||
@@ -21,8 +21,8 @@ use self::shared::{
|
||||
};
|
||||
|
||||
pub(crate) async fn maybe_build_local_admin_payments_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
routes::maybe_build_local_admin_payments_response(state, request_context, request_body).await
|
||||
|
||||
@@ -7,9 +7,9 @@ use super::{
|
||||
normalize_admin_payment_positive_number, parse_admin_payments_limit,
|
||||
parse_admin_payments_offset, AdminPaymentOrderCreditRequest,
|
||||
};
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{attach_admin_audit_response, query_param_value};
|
||||
use crate::{AppState, GatewayError};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
@@ -18,8 +18,8 @@ use axum::{
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_payment_orders_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
route_kind: Option<&str>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
@@ -44,10 +44,10 @@ pub(super) async fn maybe_build_local_admin_payment_orders_response(
|
||||
}
|
||||
|
||||
async fn build_admin_payment_list_orders_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.request_query_string.as_deref();
|
||||
let query = request_context.query_string();
|
||||
let limit = match parse_admin_payments_limit(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
|
||||
@@ -83,11 +83,10 @@ async fn build_admin_payment_list_orders_response(
|
||||
}
|
||||
|
||||
async fn build_admin_payment_get_order_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(order_id) = admin_payment_order_id_from_detail_path(&request_context.request_path)
|
||||
else {
|
||||
let Some(order_id) = admin_payment_order_id_from_detail_path(request_context.path()) else {
|
||||
return Ok(build_admin_payment_order_not_found_response());
|
||||
};
|
||||
match state.read_admin_payment_order(&order_id).await? {
|
||||
@@ -110,11 +109,10 @@ async fn build_admin_payment_get_order_response(
|
||||
}
|
||||
|
||||
async fn build_admin_payment_expire_order_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(order_id) =
|
||||
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/expire")
|
||||
let Some(order_id) = admin_payment_order_id_from_suffix_path(request_context.path(), "/expire")
|
||||
else {
|
||||
return Ok(build_admin_payment_order_not_found_response());
|
||||
};
|
||||
@@ -147,12 +145,11 @@ async fn build_admin_payment_expire_order_response(
|
||||
}
|
||||
|
||||
async fn build_admin_payment_credit_order_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
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")
|
||||
let Some(order_id) = admin_payment_order_id_from_suffix_path(request_context.path(), "/credit")
|
||||
else {
|
||||
return Ok(build_admin_payment_order_not_found_response());
|
||||
};
|
||||
@@ -241,11 +238,10 @@ async fn build_admin_payment_credit_order_response(
|
||||
}
|
||||
|
||||
async fn build_admin_payment_fail_order_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(order_id) =
|
||||
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/fail")
|
||||
let Some(order_id) = admin_payment_order_id_from_suffix_path(request_context.path(), "/fail")
|
||||
else {
|
||||
return Ok(build_admin_payment_order_not_found_response());
|
||||
};
|
||||
|
||||
@@ -3,16 +3,16 @@ use super::{
|
||||
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 crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{body::Body, http, response::Response};
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_payments_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
let Some(decision) = request_context.control_decision.as_ref() else {
|
||||
let Some(decision) = request_context.decision() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -20,30 +20,30 @@ pub(super) async fn maybe_build_local_admin_payments_response(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let normalized_path = request_context.request_path.trim_end_matches('/');
|
||||
let normalized_path = request_context.path().trim_end_matches('/');
|
||||
let path = if normalized_path.is_empty() {
|
||||
request_context.request_path.as_str()
|
||||
request_context.path()
|
||||
} else {
|
||||
normalized_path
|
||||
};
|
||||
let is_payments_route = (request_context.request_method == http::Method::GET
|
||||
let is_payments_route = (request_context.method() == http::Method::GET
|
||||
&& path == "/api/admin/payments/orders")
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/payments/orders/")
|
||||
&& path.matches('/').count() == 5)
|
||||
|| (request_context.request_method == http::Method::POST
|
||||
|| (request_context.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
|
||||
|| (request_context.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
|
||||
|| (request_context.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
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& path == "/api/admin/payments/callbacks");
|
||||
|
||||
if !is_payments_route {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::request::AdminRequestContext;
|
||||
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
|
||||
use crate::{GatewayAdminPaymentCallbackView, GatewayError};
|
||||
use axum::{
|
||||
@@ -175,11 +175,10 @@ pub(super) fn normalize_admin_payment_positive_number(
|
||||
}
|
||||
|
||||
pub(super) fn admin_payment_operator_id(
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Option<String> {
|
||||
request_context
|
||||
.control_decision
|
||||
.as_ref()
|
||||
.decision()
|
||||
.and_then(|decision| decision.admin_principal.as_ref())
|
||||
.map(|principal| principal.user_id.clone())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
use super::super::{
|
||||
build_admin_billing_bad_request_response, build_admin_billing_not_found_response,
|
||||
build_admin_billing_read_only_response,
|
||||
};
|
||||
use super::support::{
|
||||
parse_admin_billing_preset_apply_request, resolve_admin_billing_preset_collectors,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::attach_admin_audit_response;
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) async fn build_admin_apply_billing_preset_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let (preset, mode) = match parse_admin_billing_preset_apply_request(request_body) {
|
||||
Ok(value) => value,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
let Some((resolved_preset, collectors)) = resolve_admin_billing_preset_collectors(&preset)
|
||||
else {
|
||||
let payload = json!({
|
||||
"ok": false,
|
||||
"preset": preset,
|
||||
"mode": mode,
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"skipped": 0,
|
||||
"errors": ["Unknown preset: available presets are aether-core"],
|
||||
});
|
||||
return Ok(Json(payload).into_response());
|
||||
};
|
||||
|
||||
match state
|
||||
.apply_admin_billing_preset(resolved_preset, &mode, &collectors)
|
||||
.await?
|
||||
{
|
||||
crate::LocalMutationOutcome::Applied(result) => {
|
||||
let response = Json(json!({
|
||||
"ok": result.errors.is_empty(),
|
||||
"preset": result.preset,
|
||||
"mode": result.mode,
|
||||
"created": result.created,
|
||||
"updated": result.updated,
|
||||
"skipped": result.skipped,
|
||||
"errors": result.errors,
|
||||
}))
|
||||
.into_response();
|
||||
Ok(attach_admin_audit_response(
|
||||
response,
|
||||
"admin_billing_preset_applied",
|
||||
"apply_billing_preset",
|
||||
"billing_preset",
|
||||
resolved_preset,
|
||||
))
|
||||
}
|
||||
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",
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
mod apply;
|
||||
mod support;
|
||||
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_billing_presets_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
let Some(decision) = request_context.decision() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = request_context.path();
|
||||
|
||||
match decision.route_kind.as_deref() {
|
||||
Some("list_presets")
|
||||
if request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
Json(support::build_admin_billing_presets_payload()).into_response(),
|
||||
))
|
||||
}
|
||||
Some("apply_preset")
|
||||
if request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
apply::build_admin_apply_billing_preset_response(
|
||||
state,
|
||||
request_context,
|
||||
request_body,
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
+6
-107
@@ -1,14 +1,9 @@
|
||||
use super::{
|
||||
build_admin_billing_bad_request_response, build_admin_billing_not_found_response,
|
||||
build_admin_billing_read_only_response, normalize_admin_billing_required_text,
|
||||
use super::super::{
|
||||
build_admin_billing_bad_request_response, normalize_admin_billing_required_text,
|
||||
};
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::shared::attach_admin_audit_response;
|
||||
use crate::{AppState, GatewayError};
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
response::Response,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
@@ -24,7 +19,7 @@ struct AdminBillingPresetApplyRequest {
|
||||
mode: String,
|
||||
}
|
||||
|
||||
fn build_admin_billing_presets_payload() -> serde_json::Value {
|
||||
pub(super) fn build_admin_billing_presets_payload() -> serde_json::Value {
|
||||
json!({
|
||||
"items": [
|
||||
{
|
||||
@@ -234,7 +229,7 @@ fn build_admin_billing_aether_core_collectors() -> Vec<crate::AdminBillingCollec
|
||||
]
|
||||
}
|
||||
|
||||
fn resolve_admin_billing_preset_collectors(
|
||||
pub(super) fn resolve_admin_billing_preset_collectors(
|
||||
preset: &str,
|
||||
) -> Option<(&'static str, Vec<crate::AdminBillingCollectorWriteInput>)> {
|
||||
let normalized = preset.trim().to_ascii_lowercase();
|
||||
@@ -246,7 +241,7 @@ fn resolve_admin_billing_preset_collectors(
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_admin_billing_preset_apply_request(
|
||||
pub(super) fn parse_admin_billing_preset_apply_request(
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<(String, String), Response<Body>> {
|
||||
let Some(request_body) = request_body else {
|
||||
@@ -272,99 +267,3 @@ fn parse_admin_billing_preset_apply_request(
|
||||
}
|
||||
Ok((preset, mode))
|
||||
}
|
||||
|
||||
async fn build_admin_apply_billing_preset_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let (preset, mode) = match parse_admin_billing_preset_apply_request(request_body) {
|
||||
Ok(value) => value,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
let Some((resolved_preset, collectors)) = resolve_admin_billing_preset_collectors(&preset)
|
||||
else {
|
||||
let payload = json!({
|
||||
"ok": false,
|
||||
"preset": preset,
|
||||
"mode": mode,
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"skipped": 0,
|
||||
"errors": ["Unknown preset: available presets are aether-core"],
|
||||
});
|
||||
return Ok(Json(payload).into_response());
|
||||
};
|
||||
|
||||
match state
|
||||
.apply_admin_billing_preset(resolved_preset, &mode, &collectors)
|
||||
.await?
|
||||
{
|
||||
crate::LocalMutationOutcome::Applied(result) => {
|
||||
let response = Json(json!({
|
||||
"ok": result.errors.is_empty(),
|
||||
"preset": result.preset,
|
||||
"mode": result.mode,
|
||||
"created": result.created,
|
||||
"updated": result.updated,
|
||||
"skipped": result.skipped,
|
||||
"errors": result.errors,
|
||||
}))
|
||||
.into_response();
|
||||
Ok(attach_admin_audit_response(
|
||||
response,
|
||||
"admin_billing_preset_applied",
|
||||
"apply_billing_preset",
|
||||
"billing_preset",
|
||||
resolved_preset,
|
||||
))
|
||||
}
|
||||
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",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_billing_presets_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);
|
||||
};
|
||||
let path = request_context.request_path.as_str();
|
||||
|
||||
match decision.route_kind.as_deref() {
|
||||
Some("list_presets")
|
||||
if request_context.request_method == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
Json(build_admin_billing_presets_payload()).into_response(),
|
||||
))
|
||||
}
|
||||
Some("apply_preset")
|
||||
if request_context.request_method == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
|
||||
) =>
|
||||
{
|
||||
Ok(Some(
|
||||
build_admin_apply_billing_preset_response(state, request_context, request_body)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use super::{maybe_build_local_admin_billing_response, payments, wallets};
|
||||
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
|
||||
|
||||
pub(crate) async fn maybe_build_local_admin_billing_routes_response(
|
||||
request: AdminRouteRequest<'_>,
|
||||
) -> AdminRouteResult {
|
||||
if let Some(response) = maybe_build_local_admin_billing_response(
|
||||
&request.state(),
|
||||
&request.request_context(),
|
||||
request.request_body(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Ok(Some(response));
|
||||
}
|
||||
|
||||
if let Some(response) = payments::maybe_build_local_admin_payments_response(
|
||||
&request.state(),
|
||||
&request.request_context(),
|
||||
request.request_body(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Ok(Some(response));
|
||||
}
|
||||
|
||||
if let Some(response) = wallets::maybe_build_local_admin_wallets_response(
|
||||
&request.state(),
|
||||
&request.request_context(),
|
||||
request.request_body(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Ok(Some(response));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
@@ -6,9 +6,9 @@ use super::{
|
||||
default_admin_billing_json_object, default_admin_billing_true,
|
||||
normalize_admin_billing_optional_text, normalize_admin_billing_required_text,
|
||||
};
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
|
||||
use crate::{AppState, GatewayError};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http,
|
||||
@@ -170,10 +170,10 @@ fn parse_admin_billing_rule_request(
|
||||
}
|
||||
|
||||
async fn build_admin_list_billing_rules_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.request_query_string.as_deref();
|
||||
let query = request_context.query_string();
|
||||
let page = match admin_billing_parse_page(query) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
|
||||
@@ -214,10 +214,10 @@ async fn build_admin_list_billing_rules_response(
|
||||
}
|
||||
|
||||
async fn build_admin_get_billing_rule_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(rule_id) = admin_billing_rule_id_from_path(&request_context.request_path) else {
|
||||
let Some(rule_id) = admin_billing_rule_id_from_path(request_context.path()) else {
|
||||
return Ok(build_admin_billing_bad_request_response("缺少 rule_id"));
|
||||
};
|
||||
match state.read_admin_billing_rule(&rule_id).await? {
|
||||
@@ -231,7 +231,7 @@ async fn build_admin_get_billing_rule_response(
|
||||
}
|
||||
|
||||
async fn build_admin_create_billing_rule_response(
|
||||
state: &AppState,
|
||||
state: &AdminAppState<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let input = match parse_admin_billing_rule_request(request_body) {
|
||||
@@ -255,11 +255,11 @@ async fn build_admin_create_billing_rule_response(
|
||||
}
|
||||
|
||||
async fn build_admin_update_billing_rule_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(rule_id) = admin_billing_rule_id_from_path(&request_context.request_path) else {
|
||||
let Some(rule_id) = admin_billing_rule_id_from_path(request_context.path()) else {
|
||||
return Ok(build_admin_billing_bad_request_response("缺少 rule_id"));
|
||||
};
|
||||
let input = match parse_admin_billing_rule_request(request_body) {
|
||||
@@ -283,18 +283,18 @@ async fn build_admin_update_billing_rule_response(
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_billing_rules_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
let Some(decision) = request_context.control_decision.as_ref() else {
|
||||
let Some(decision) = request_context.decision() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = request_context.request_path.as_str();
|
||||
let path = request_context.path();
|
||||
|
||||
match decision.route_kind.as_deref() {
|
||||
Some("list_rules")
|
||||
if request_context.request_method == http::Method::GET
|
||||
if request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
|
||||
@@ -305,7 +305,7 @@ pub(super) async fn maybe_build_local_admin_billing_rules_response(
|
||||
))
|
||||
}
|
||||
Some("get_rule")
|
||||
if request_context.request_method == http::Method::GET
|
||||
if request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/billing/rules/") =>
|
||||
{
|
||||
Ok(Some(
|
||||
@@ -313,7 +313,7 @@ pub(super) async fn maybe_build_local_admin_billing_rules_response(
|
||||
))
|
||||
}
|
||||
Some("create_rule")
|
||||
if request_context.request_method == http::Method::POST
|
||||
if request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
|
||||
@@ -324,7 +324,7 @@ pub(super) async fn maybe_build_local_admin_billing_rules_response(
|
||||
))
|
||||
}
|
||||
Some("update_rule")
|
||||
if request_context.request_method == http::Method::PUT
|
||||
if request_context.method() == http::Method::PUT
|
||||
&& path.starts_with("/api/admin/billing/rules/") =>
|
||||
{
|
||||
Ok(Some(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::{AppState, GatewayError};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{body::Body, response::Response};
|
||||
|
||||
mod mutations;
|
||||
@@ -8,8 +8,8 @@ mod routes;
|
||||
mod shared;
|
||||
|
||||
pub(crate) async fn maybe_build_local_admin_wallets_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
routes::maybe_build_local_admin_wallets_routes_response(state, request_context, request_body)
|
||||
|
||||
@@ -1,474 +0,0 @@
|
||||
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,114 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_id_from_suffix_path, admin_wallet_operator_id,
|
||||
build_admin_wallet_not_found_response, 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,
|
||||
resolve_admin_wallet_owner_summary, AdminWalletAdjustRequest,
|
||||
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_adjust_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.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.has_postgres_pool();
|
||||
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,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_refund_ids_from_suffix_path, build_admin_wallet_not_found_response,
|
||||
build_admin_wallet_refund_not_found_response, build_admin_wallet_refund_payload,
|
||||
build_admin_wallets_bad_request_response, build_admin_wallets_data_unavailable_response,
|
||||
normalize_admin_wallet_optional_text, resolve_admin_wallet_owner_summary,
|
||||
AdminWalletRefundCompleteRequest, ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::attach_admin_audit_response;
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_complete_refund_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
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.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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_operator_id, admin_wallet_refund_ids_from_suffix_path,
|
||||
build_admin_wallet_not_found_response, 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_required_text,
|
||||
resolve_admin_wallet_owner_summary, AdminWalletRefundFailRequest,
|
||||
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_fail_refund_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
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.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,11 @@
|
||||
mod adjust;
|
||||
mod complete_refund;
|
||||
mod fail_refund;
|
||||
mod process_refund;
|
||||
mod recharge;
|
||||
|
||||
pub(super) use adjust::build_admin_wallet_adjust_response;
|
||||
pub(super) use complete_refund::build_admin_wallet_complete_refund_response;
|
||||
pub(super) use fail_refund::build_admin_wallet_fail_refund_response;
|
||||
pub(super) use process_refund::build_admin_wallet_process_refund_response;
|
||||
pub(super) use recharge::build_admin_wallet_recharge_response;
|
||||
@@ -0,0 +1,94 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_operator_id, admin_wallet_refund_ids_from_suffix_path,
|
||||
build_admin_wallet_not_found_response, 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, resolve_admin_wallet_owner_summary,
|
||||
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_process_refund_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some((wallet_id, refund_id)) =
|
||||
admin_wallet_refund_ids_from_suffix_path(request_context.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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_id_from_suffix_path, admin_wallet_operator_id,
|
||||
build_admin_wallet_not_found_response, build_admin_wallet_payment_order_payload,
|
||||
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
|
||||
build_admin_wallets_data_unavailable_response, normalize_admin_wallet_description,
|
||||
normalize_admin_wallet_payment_method, normalize_admin_wallet_positive_amount,
|
||||
resolve_admin_wallet_owner_summary, AdminWalletRechargeRequest,
|
||||
ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_recharge_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.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.has_postgres_pool();
|
||||
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,
|
||||
))
|
||||
}
|
||||
@@ -1,388 +0,0 @@
|
||||
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,37 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_id_from_detail_path, build_admin_wallet_not_found_response,
|
||||
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
|
||||
resolve_admin_wallet_owner_summary,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_detail_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(wallet_id) = admin_wallet_id_from_detail_path(request_context.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())
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use super::super::shared::{
|
||||
build_admin_wallets_bad_request_response, parse_admin_wallets_limit,
|
||||
parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
|
||||
wallet_owner_summary_from_fields,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_ledger_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.query_string();
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use super::super::shared::{
|
||||
build_admin_wallets_bad_request_response, parse_admin_wallets_limit,
|
||||
parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
|
||||
wallet_owner_summary_from_fields,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_list_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.query_string();
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
mod detail;
|
||||
mod ledger;
|
||||
mod list;
|
||||
mod refund_requests;
|
||||
mod refunds;
|
||||
mod transactions;
|
||||
|
||||
pub(super) use detail::build_admin_wallet_detail_response;
|
||||
pub(super) use ledger::build_admin_wallet_ledger_response;
|
||||
pub(super) use list::build_admin_wallet_list_response;
|
||||
pub(super) use refund_requests::build_admin_wallet_refund_requests_response;
|
||||
pub(super) use refunds::build_admin_wallet_refunds_response;
|
||||
pub(super) use transactions::build_admin_wallet_transactions_response;
|
||||
@@ -0,0 +1,96 @@
|
||||
use super::super::shared::{
|
||||
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::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_refund_requests_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let query = request_context.query_string();
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use super::super::shared::{
|
||||
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, resolve_admin_wallet_owner_summary,
|
||||
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_refunds_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.path(), "/refunds")
|
||||
else {
|
||||
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
|
||||
};
|
||||
let limit = match parse_admin_wallets_limit(request_context.query_string()) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
|
||||
};
|
||||
let offset = match parse_admin_wallets_offset(request_context.query_string()) {
|
||||
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,95 @@
|
||||
use super::super::shared::{
|
||||
admin_wallet_id_from_suffix_path, build_admin_wallet_not_found_response,
|
||||
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
|
||||
parse_admin_wallets_limit, parse_admin_wallets_offset, resolve_admin_wallet_owner_summary,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::super) async fn build_admin_wallet_transactions_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Result<Response<Body>, GatewayError> {
|
||||
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.path(), "/transactions")
|
||||
else {
|
||||
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
|
||||
};
|
||||
let limit = match parse_admin_wallets_limit(request_context.query_string()) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
|
||||
};
|
||||
let offset = match parse_admin_wallets_offset(request_context.query_string()) {
|
||||
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())
|
||||
}
|
||||
@@ -9,16 +9,16 @@ use super::reads::{
|
||||
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 crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::GatewayError;
|
||||
use axum::{body::Body, http, response::Response};
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_wallets_routes_response(
|
||||
state: &AppState,
|
||||
request_context: &GatewayPublicRequestContext,
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
request_body: Option<&axum::body::Bytes>,
|
||||
) -> Result<Option<Response<Body>>, GatewayError> {
|
||||
let Some(decision) = request_context.control_decision.as_ref() else {
|
||||
let Some(decision) = request_context.decision() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -26,31 +26,31 @@ pub(super) async fn maybe_build_local_admin_wallets_routes_response(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let path = request_context.request_path.as_str();
|
||||
let is_wallets_route = (request_context.request_method == http::Method::GET
|
||||
let path = request_context.path();
|
||||
let is_wallets_route = (request_context.method() == http::Method::GET
|
||||
&& matches!(path, "/api/admin/wallets" | "/api/admin/wallets/"))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/wallets/ledger" | "/api/admin/wallets/ledger/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/admin/wallets/refund-requests" | "/api/admin/wallets/refund-requests/"
|
||||
))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/wallets/")
|
||||
&& path.ends_with("/transactions"))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.method() == http::Method::GET
|
||||
&& path.starts_with("/api/admin/wallets/")
|
||||
&& path.ends_with("/refunds"))
|
||||
|| (request_context.request_method == http::Method::GET
|
||||
|| (request_context.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
|
||||
|| (request_context.method() == http::Method::POST
|
||||
&& matches!(
|
||||
decision.route_kind.as_deref(),
|
||||
Some(
|
||||
@@ -67,70 +67,70 @@ pub(super) async fn maybe_build_local_admin_wallets_routes_response(
|
||||
}
|
||||
|
||||
if decision.route_kind.as_deref() == Some("wallet_detail")
|
||||
&& request_context.request_method == http::Method::GET
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.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
|
||||
&& request_context.method() == http::Method::POST
|
||||
{
|
||||
return Ok(Some(
|
||||
build_admin_wallet_complete_refund_response(state, request_context, request_body)
|
||||
@@ -138,7 +138,7 @@ pub(super) async fn maybe_build_local_admin_wallets_routes_response(
|
||||
));
|
||||
}
|
||||
if decision.route_kind.as_deref() == Some("fail_refund")
|
||||
&& request_context.request_method == http::Method::POST
|
||||
&& request_context.method() == http::Method::POST
|
||||
{
|
||||
return Ok(Some(
|
||||
build_admin_wallet_fail_refund_response(state, request_context, request_body).await?,
|
||||
|
||||
@@ -1,580 +0,0 @@
|
||||
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),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
mod normalizers;
|
||||
mod payloads;
|
||||
mod requests;
|
||||
mod responses;
|
||||
mod support;
|
||||
|
||||
pub(super) use normalizers::*;
|
||||
pub(super) use payloads::*;
|
||||
pub(super) use requests::*;
|
||||
pub(super) use responses::*;
|
||||
pub(super) use support::*;
|
||||
@@ -0,0 +1,89 @@
|
||||
pub(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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)
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
use crate::handlers::admin::request::AdminAppState;
|
||||
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
|
||||
use crate::GatewayError;
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in super::super) struct AdminWalletOwnerSummary {
|
||||
pub(in super::super) owner_type: &'static str,
|
||||
pub(in super::super) owner_name: Option<String>,
|
||||
}
|
||||
|
||||
pub(in super::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(in super::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(in super::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(in super::super) async fn resolve_admin_wallet_owner_summary(
|
||||
state: &AdminAppState<'_>,
|
||||
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
|
||||
.list_auth_api_key_snapshots_by_ids(&api_key_ids)
|
||||
.await?;
|
||||
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(in super::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(in super::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),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
pub(in super::super) const ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL: &str =
|
||||
"Admin wallets data unavailable";
|
||||
pub(in super::super) const ADMIN_WALLETS_API_KEY_REFUND_DETAIL: &str = "独立密钥钱包不支持退款审批";
|
||||
pub(in super::super) const ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL: &str =
|
||||
"独立密钥钱包不支持充值,请使用调账";
|
||||
pub(in super::super) const ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL: &str =
|
||||
"独立密钥钱包不支持赠款调账";
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub(in super::super) struct AdminWalletRechargeRequest {
|
||||
pub(in super::super) amount_usd: f64,
|
||||
#[serde(default = "default_admin_wallet_payment_method")]
|
||||
pub(in super::super) payment_method: String,
|
||||
#[serde(default)]
|
||||
pub(in super::super) description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub(in super::super) struct AdminWalletAdjustRequest {
|
||||
pub(in super::super) amount_usd: f64,
|
||||
#[serde(default = "default_admin_wallet_balance_type")]
|
||||
pub(in super::super) balance_type: String,
|
||||
#[serde(default)]
|
||||
pub(in super::super) description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub(in super::super) struct AdminWalletRefundFailRequest {
|
||||
pub(in super::super) reason: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub(in super::super) struct AdminWalletRefundCompleteRequest {
|
||||
#[serde(default)]
|
||||
pub(in super::super) gateway_refund_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(in super::super) payout_reference: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(in super::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()
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use super::requests::ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL;
|
||||
use axum::{
|
||||
body::Body,
|
||||
http,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub(in super::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(in super::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(in super::super) fn build_admin_wallet_not_found_response() -> Response<Body> {
|
||||
(
|
||||
http::StatusCode::NOT_FOUND,
|
||||
Json(json!({ "detail": "Wallet not found" })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub(in super::super) fn build_admin_wallet_refund_not_found_response() -> Response<Body> {
|
||||
(
|
||||
http::StatusCode::NOT_FOUND,
|
||||
Json(json!({ "detail": "Refund request not found" })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
use super::requests::ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL;
|
||||
use crate::handlers::admin::request::AdminRequestContext;
|
||||
use crate::handlers::admin::shared::query_param_value;
|
||||
use crate::GatewayError;
|
||||
use sqlx::Row;
|
||||
|
||||
pub(in super::super) fn admin_wallet_operator_id(
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
) -> Option<String> {
|
||||
request_context
|
||||
.decision()
|
||||
.and_then(|decision| decision.admin_principal.as_ref())
|
||||
.map(|principal| principal.user_id.clone())
|
||||
}
|
||||
|
||||
pub(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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(in super::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(crate::handlers::admin::shared::unix_secs_to_rfc3339))
|
||||
}
|
||||
|
||||
pub(in super::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]
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user