feat(routes): 照抄上游 ServiceCatalog/Billing 两控制器(10 个端点)
严格对齐上游 ssw-tdc 的 ServiceCatalogController 与 BillingController:
- 服务目录:GET /ServiceCatalog、POST /ServiceCatalog/Buy、POST /ServiceCatalog/BuyBatch
- 连接器账单:GET /Billing/List、GET /Billing/LocalCompare,
PUT /Billing/{id}/{Dispute,Confirm,Settle,Receipt}、GET /Billing/{id}/Voucher
关键实现点:
- 身份解析照抄上游两套口径:宽松(显式 connectorId 优先,List/Dispute/Receipt/Voucher)
与严格(本端固定身份唯一,Confirm/Settle)
- 越权自检照抄上游 ownsLedger:先 listBillingForConnector 再比对 id,异常一律 fail-closed
- 信封拆解照抄上游 unwrap / unwrapStr:成功时 data 是账本 id 字符串而非对象
- OptionalJsonBody 还原上游 @RequestBody(required=false):空体 => null 而非失败
- Buy/BuyBatch 自动带出 buyerConnectorId(上游读的是 buyerConnectorId 不是 connectorId)
- LocalCompare 只读本地 tdc_api_consume_log,不发任何出向请求
- 业务失败一律 HTTP 200 + code 400;出向不可达用上游原话,NOOP 另给「未配置 TDS 地址」
Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
03e9f05736
commit
a2c0213908
3 files changed
+596
No files matched your search
@@ -7,6 +7,7 @@ pub mod crud;
|
||||
pub mod fallback;
|
||||
pub mod health;
|
||||
pub mod mw;
|
||||
pub mod tds_biz;
|
||||
|
||||
use axum::Router;
|
||||
|
||||
@@ -29,5 +30,6 @@ pub fn build_router(state: AppState) -> Router<AppState> {
|
||||
.merge(auth::router())
|
||||
.merge(account::router())
|
||||
.merge(crud::router())
|
||||
.merge(tds_biz::router())
|
||||
.with_state(state)
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
//! 服务目录 + 连接器账单(照抄上游 `ServiceCatalogController` + `BillingController`)。
|
||||
//!
|
||||
//! 上游真源:
|
||||
//! - `/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-controller/src/main/java/ssw/tdc/controller/ServiceCatalogController.java`
|
||||
//! - `/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-controller/src/main/java/ssw/tdc/controller/BillingController.java`
|
||||
//!
|
||||
//! 🔴 **只做上游的 standalone 分支**(`tdcInstanceContext != null` ⇒ 走 internal 通道)。
|
||||
//! 本仓恒为本地单机形态 ⇒ 一体化分支(转发 JNPF token 的 `catalogSearch` / `tradeOrderBuy`)
|
||||
//! **永不被触及**(spec §2.1)。
|
||||
//!
|
||||
//! 🔴 **鉴权**:上游每个方法首行都是 `requireInternalOrUser()`
|
||||
//! (内部令牌 **或** JNPF 登录,无凭证 fail-closed)。
|
||||
//! 本仓的入向鉴权中间件(`auth::auth_middleware`)对**所有** `/api/**` 路径
|
||||
//! 已经强制「内部令牌 **或** 会话令牌」⇒ 这层要求由中间件承担,本模块**不重复实现**。
|
||||
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Extension, FromRequest, Path, RawQuery, Request, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post, put};
|
||||
use axum::Router;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::body::BODY_FORMAT_ERROR;
|
||||
use crate::auth::Principal;
|
||||
use crate::crud::{param, parse_query, row_to_json};
|
||||
use crate::db::query_json_params;
|
||||
use crate::envelope::{ActionResult, CODE_SERVER_ERROR};
|
||||
use crate::state::AppState;
|
||||
use crate::tds;
|
||||
|
||||
/// 装配 10 个端点(路径/方法**逐字对齐上游**)。
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
// ---- 服务目录(上游 ServiceCatalogController) ----
|
||||
.route("/api/ssw/tdc/ServiceCatalog", get(service_catalog_list))
|
||||
.route("/api/ssw/tdc/ServiceCatalog/Buy", post(service_catalog_buy))
|
||||
.route(
|
||||
"/api/ssw/tdc/ServiceCatalog/BuyBatch",
|
||||
post(service_catalog_buy_batch),
|
||||
)
|
||||
// ---- 连接器账单(上游 BillingController) ----
|
||||
.route("/api/ssw/tdc/Billing/List", get(billing_list))
|
||||
.route(
|
||||
"/api/ssw/tdc/Billing/LocalCompare",
|
||||
get(billing_local_compare),
|
||||
)
|
||||
.route("/api/ssw/tdc/Billing/{id}/Dispute", put(billing_dispute))
|
||||
.route("/api/ssw/tdc/Billing/{id}/Confirm", put(billing_confirm))
|
||||
.route("/api/ssw/tdc/Billing/{id}/Settle", put(billing_settle))
|
||||
.route("/api/ssw/tdc/Billing/{id}/Receipt", put(billing_receipt))
|
||||
.route("/api/ssw/tdc/Billing/{id}/Voucher", get(billing_voucher))
|
||||
}
|
||||
|
||||
// ==================================================================
|
||||
// 抽取器
|
||||
// ==================================================================
|
||||
|
||||
/// **可选** JSON 请求体(≡ 上游 `@RequestBody(required = false)`)。
|
||||
///
|
||||
/// - **无体**(空 body)⇒ `Value::Null`(上游此时 `body == null`)
|
||||
/// - **体不是合法 JSON** ⇒ 业务失败「请求体格式有误…」(与 `JsonBody` 同一拒因)
|
||||
///
|
||||
/// 🔴 为什么不用 `super::body::JsonBody`:它把**空 body 判成失败**(那是上游**必填**
|
||||
/// `@RequestBody` 的语义)⇒ 而上游账单这五个动作端点全是 `required = false`
|
||||
/// (前端可能空体调用)⇒ 必须有一个「空体 ⇒ null」的抽取器。
|
||||
pub struct OptionalJsonBody(pub Value);
|
||||
|
||||
impl<S> FromRequest<S> for OptionalJsonBody
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = Response;
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let bytes = Bytes::from_request(req, state)
|
||||
.await
|
||||
.map_err(|_| ActionResult::fail(BODY_FORMAT_ERROR).into_response())?;
|
||||
if bytes.is_empty() {
|
||||
return Ok(OptionalJsonBody(Value::Null));
|
||||
}
|
||||
match serde_json::from_slice::<Value>(&bytes) {
|
||||
Ok(v) => Ok(OptionalJsonBody(v)),
|
||||
Err(_) => Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================================================
|
||||
// 身份解析(照抄上游两套口径)
|
||||
// ==================================================================
|
||||
|
||||
/// 本端固定身份(≡ 上游 `TdcInstanceContext.resolve()` 的固定实例身份)。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct LocalIdentity {
|
||||
/// `tdc_identity.f_tds_space_id`(空间;目录查询用)。
|
||||
space_id: Option<String>,
|
||||
/// `tdc_identity.f_tds_connector_id`(连接器;账单用)。
|
||||
connector_id: Option<String>,
|
||||
}
|
||||
|
||||
/// 取本端默认身份的 TDS 绑定(空间 + 连接器)。
|
||||
///
|
||||
/// 🔴 取**默认身份行**(`f_default_mark` 优先,其次 `f_id` 序)⇒ 与上游「固定实例身份」同口径。
|
||||
/// 两列 schema 里**已存在**(`tdc_identity.f_tds_space_id` / `f_tds_connector_id`)。
|
||||
async fn local_identity(state: &AppState) -> LocalIdentity {
|
||||
let sql = "SELECT f_tds_space_id, f_tds_connector_id FROM tdc_identity \
|
||||
WHERE f_delete_mark IS NULL OR f_delete_mark = 0 \
|
||||
ORDER BY f_default_mark DESC, f_id LIMIT 1";
|
||||
let rows = {
|
||||
let _g = state.db_lock.lock().await;
|
||||
query_json_params(state.db.as_ref(), sql, &[])
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let row = match rows.first() {
|
||||
Some(r) => r,
|
||||
None => return LocalIdentity::default(),
|
||||
};
|
||||
let pick = |k: &str| -> Option<String> {
|
||||
row.get(k)
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
};
|
||||
LocalIdentity {
|
||||
space_id: pick("f_tds_space_id"),
|
||||
connector_id: pick("f_tds_connector_id"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 宽松取字符串(照抄上游 `BillingController.asText`)。
|
||||
///
|
||||
/// `null` ⇒ `None`;字符串 ⇒ 原值;其它标量/结构 ⇒ 文本化。
|
||||
/// 🔴 上游 `dispute` / `receipt` 用的是 `(String) body.get("connectorId")` **硬转**
|
||||
/// ⇒ 传数字会抛 `ClassCastException`(500)。上游自己在 `asText` 处注了这一点
|
||||
/// (2026-09-19 审查 P2-7)⇒ 本仓统一用宽松取法,**不 500**。
|
||||
fn as_text(v: Option<&Value>) -> Option<String> {
|
||||
match v {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(s)) => Some(s.clone()),
|
||||
Some(other) => Some(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 取 body 里的某个键(宽松取文本)。
|
||||
fn body_text(body: &Value, key: &str) -> Option<String> {
|
||||
as_text(body.get(key))
|
||||
}
|
||||
|
||||
/// 是否空白(上游 `String.isBlank()` 的口径:trim 后为空)。
|
||||
fn is_blank(s: &str) -> bool {
|
||||
s.trim().is_empty()
|
||||
}
|
||||
|
||||
/// **宽松**身份解析(照抄上游 `BillingController.resolveConnectorId`)。
|
||||
///
|
||||
/// 显式 `connectorId` 优先;为空则取本端固定身份。两者都拿不到 ⇒ `None`(调用方 fail-closed 拒)。
|
||||
///
|
||||
/// ⚠️ 上游对**既有**端点(List/Dispute/Receipt/Voucher/LocalCompare)就是这个宽松口径
|
||||
/// (上游自己标注「既有安全面本批不加固」)⇒ 照抄,差异登记在 spec D1。
|
||||
fn resolve_connector_id_relaxed(explicit: Option<String>, local: &LocalIdentity) -> Option<String> {
|
||||
if let Some(e) = explicit {
|
||||
if !is_blank(&e) {
|
||||
return Some(e);
|
||||
}
|
||||
}
|
||||
local.connector_id.clone()
|
||||
}
|
||||
|
||||
/// **严格**身份解析(照抄上游 `BillingController.resolveOwnConnectorIdStrict`)。
|
||||
///
|
||||
/// 只认本端可解析身份;显式 id 与本端**不一致** ⇒ `None`(调用方拒)。
|
||||
/// 🔴 不沿用宽松口径(那会让调用方自供 id 通过自证)。
|
||||
fn resolve_connector_id_strict(explicit: Option<String>, local: &LocalIdentity) -> Option<String> {
|
||||
let local_id = match local.connector_id.as_ref() {
|
||||
Some(c) if !is_blank(c) => c.clone(),
|
||||
_ => return None,
|
||||
};
|
||||
if let Some(e) = explicit {
|
||||
if !is_blank(&e) && e != local_id {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(local_id)
|
||||
}
|
||||
|
||||
/// 越权自检(照抄上游 `BillingController.ownsLedger`)。
|
||||
///
|
||||
/// 先 `listBillingForConnector(cid)`(**不带 keyword**),在 `data.list` 里找 id 匹配 ⇒ 不匹配 ⇒ 拒。
|
||||
/// 🔴 任何异常(TDS 不可达 / 拒 / 形状不符)⇒ **false**(fail-closed)。
|
||||
async fn owns_ledger(state: &AppState, connector_id: &str, ledger_id: &str) -> bool {
|
||||
let env = match state
|
||||
.tds
|
||||
.list_billing_for_connector(connector_id, None)
|
||||
.await
|
||||
{
|
||||
Ok(e) => e,
|
||||
Err(_) => return false,
|
||||
};
|
||||
if env.get("code").and_then(|v| v.as_i64()) != Some(200) {
|
||||
return false;
|
||||
}
|
||||
let list = env
|
||||
.get("data")
|
||||
.and_then(|d| d.get("list"))
|
||||
.and_then(|l| l.as_array());
|
||||
match list {
|
||||
Some(rows) => rows
|
||||
.iter()
|
||||
.filter_map(|r| r.get("id"))
|
||||
.any(|id| json_text(id) == ledger_id),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON 值 ⇒ 文本(字符串去引号,其余原样文本化;照抄上游 `String.valueOf(...)`)。
|
||||
fn json_text(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================================================
|
||||
// 信封拆解(照抄上游 `unwrap` / `unwrapStr`)
|
||||
// ==================================================================
|
||||
|
||||
/// 整包型信封拆解(照抄上游 `unwrap`):`code==200` 且 `data` 是对象 ⇒ 取 `data`;
|
||||
/// `code==200` 但 `data` 不是对象 ⇒ 空对象;`code!=200` ⇒ 拒因取 `msg`。
|
||||
fn unwrap_envelope(env: &Value) -> Result<Value, String> {
|
||||
if env.get("code").and_then(|v| v.as_i64()) == Some(200) {
|
||||
match env.get("data") {
|
||||
Some(d) if d.is_object() => Ok(d.clone()),
|
||||
_ => Ok(json!({})),
|
||||
}
|
||||
} else {
|
||||
Err(envelope_msg(env, "平台处理失败"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 整包型信封拆解(照抄上游 `unwrapStr`):`code==200` ⇒ 成功,**`data` 是账本 id 字符串**;
|
||||
/// `code!=200` ⇒ 拒因取 `msg`。
|
||||
///
|
||||
/// 🔴 上游成功时 `data` 是**字符串**(账本 id),不是对象 —— 写测试时别想当然。
|
||||
fn unwrap_envelope_str(env: &Value, ledger_id: &str) -> Result<(String, String), String> {
|
||||
if env.get("code").and_then(|v| v.as_i64()) == Some(200) {
|
||||
Ok((envelope_msg(env, ""), ledger_id.to_string()))
|
||||
} else {
|
||||
Err(envelope_msg(env, "平台处理失败"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 取信封里的 `msg`(缺省时用兜底文案)。
|
||||
///
|
||||
/// ⚠️ 上游是 `String.valueOf(res.get("msg"))` ⇒ **`msg` 缺失时字面量是 `"null"`**
|
||||
/// (前端会显示一个 "null")。本仓用空串兜底(**已登记的刻意分歧**,见 docs/TDC-TDS-CONTRACT.md)。
|
||||
fn envelope_msg(env: &Value, fallback: &str) -> String {
|
||||
env.get("msg")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| fallback.to_string())
|
||||
}
|
||||
|
||||
/// 出向失败 ⇒ 业务拒因。
|
||||
///
|
||||
/// - **NOOP**(未配 `SSW_TDS_BASE_URL`)⇒ 用客户端给的原文
|
||||
/// (「未配置 TDS 地址(本地单机模式)」)—— 这**不是**「不可达」,别混为一谈。
|
||||
/// - 其它失败(不可达 / 超时 / 响应不是 JSON)⇒ 用**上游的原话**「…不可达」。
|
||||
fn unreachable_msg(upstream_msg: &str, err: &str) -> String {
|
||||
if err == tds::NOOP_MESSAGE {
|
||||
err.to_string()
|
||||
} else {
|
||||
upstream_msg.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================================================
|
||||
// 服务目录(上游 ServiceCatalogController)
|
||||
// ==================================================================
|
||||
|
||||
/// `GET /api/ssw/tdc/ServiceCatalog?keyword=`(上游 `search` 的 standalone 分支)。
|
||||
///
|
||||
/// ⚠️ 上游 standalone 分支**不翻页**(`internalCatalog` 无分页参数)⇒ `currentPage`/`pageSize` 忽略。
|
||||
async fn service_catalog_list(
|
||||
State(state): State<AppState>,
|
||||
q: RawQuery,
|
||||
_p: Option<Extension<Principal>>,
|
||||
) -> Response {
|
||||
let params = parse_query(q.0.as_deref());
|
||||
let keyword = param(¶ms, "keyword");
|
||||
let ident = local_identity(&state).await;
|
||||
let space_id = match ident.space_id.as_ref() {
|
||||
Some(s) if !is_blank(s) => s.clone(),
|
||||
_ => return ActionResult::fail("连接器未绑定空间,目录不可用").into_response(),
|
||||
};
|
||||
match state
|
||||
.tds
|
||||
.internal_catalog(&space_id, keyword.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(data) => ActionResult::ok(data).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/ssw/tdc/ServiceCatalog/Buy`(上游 `buy` 的 standalone 分支)。
|
||||
async fn service_catalog_buy(
|
||||
State(state): State<AppState>,
|
||||
_p: Option<Extension<Principal>>,
|
||||
body: OptionalJsonBody,
|
||||
) -> Response {
|
||||
// 上游:`if (body == null) body = new LinkedHashMap<>();` ⇒ 空体当空对象
|
||||
let mut payload = if body.0.is_null() { json!({}) } else { body.0 };
|
||||
// 买方连接器自动带出(上游:body 里没 `buyerConnectorId` 才补)
|
||||
fill_buyer_connector_id(&state, &mut payload).await;
|
||||
match state.tds.internal_apply(&payload).await {
|
||||
Ok(data) => ActionResult::ok(data).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/ssw/tdc/ServiceCatalog/BuyBatch`(上游 `buyBatch`)。
|
||||
async fn service_catalog_buy_batch(
|
||||
State(state): State<AppState>,
|
||||
_p: Option<Extension<Principal>>,
|
||||
body: OptionalJsonBody,
|
||||
) -> Response {
|
||||
// 上游:`if (body == null) return ActionResult.fail("请求体不能为空");`
|
||||
if body.0.is_null() {
|
||||
return ActionResult::fail("请求体不能为空").into_response();
|
||||
}
|
||||
let mut payload = body.0;
|
||||
fill_buyer_connector_id(&state, &mut payload).await;
|
||||
match state.tds.internal_apply_batch(&payload).await {
|
||||
Ok(data) => ActionResult::ok(data).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 买方连接器自动带出(照抄上游 `buy` / `buyBatch`)。
|
||||
///
|
||||
/// 上游口径:**body 里没有 `buyerConnectorId`**(null 或空白)⇒ 用本端固定身份补上。
|
||||
async fn fill_buyer_connector_id(state: &AppState, payload: &mut Value) {
|
||||
let existing = body_text(payload, "buyerConnectorId");
|
||||
if existing.map(|s| !is_blank(&s)).unwrap_or(false) {
|
||||
return;
|
||||
}
|
||||
let ident = local_identity(state).await;
|
||||
if let Some(cid) = ident.connector_id.as_ref() {
|
||||
if !is_blank(cid) {
|
||||
payload["buyerConnectorId"] = Value::String(cid.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================================================
|
||||
// 连接器账单(上游 BillingController)
|
||||
// ==================================================================
|
||||
|
||||
/// `GET /api/ssw/tdc/Billing/List?connectorId=&keyword=`(上游 `list`)。
|
||||
async fn billing_list(
|
||||
State(state): State<AppState>,
|
||||
q: RawQuery,
|
||||
_p: Option<Extension<Principal>>,
|
||||
) -> Response {
|
||||
let params = parse_query(q.0.as_deref());
|
||||
let explicit = param(¶ms, "connectorId");
|
||||
let keyword = param(¶ms, "keyword");
|
||||
let ident = local_identity(&state).await;
|
||||
let cid = match resolve_connector_id_relaxed(explicit, &ident) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)")
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
match state
|
||||
.tds
|
||||
.list_billing_for_connector(&cid, keyword.as_deref())
|
||||
.await
|
||||
{
|
||||
// 上游:`res == null` ⇒ "TDS 账单查询不可达"(`null` 只在异常时出现)
|
||||
Err(e) => ActionResult::fail(unreachable_msg("TDS 账单查询不可达", &e)).into_response(),
|
||||
Ok(env) => match unwrap_envelope(&env) {
|
||||
Ok(data) => ActionResult::ok(data).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUT /api/ssw/tdc/Billing/{id}/Dispute`(上游 `dispute`,**宽松**身份口径)。
|
||||
async fn billing_dispute(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
_p: Option<Extension<Principal>>,
|
||||
body: OptionalJsonBody,
|
||||
) -> Response {
|
||||
let ident = local_identity(&state).await;
|
||||
let cid = match resolve_connector_id_relaxed(body_text(&body.0, "connectorId"), &ident) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)")
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
if !owns_ledger(&state, &cid, &id).await {
|
||||
return ActionResult::fail("非本方账单,无权发起异议").into_response();
|
||||
}
|
||||
match state.tds.dispute_billing(&id).await {
|
||||
Err(e) => ActionResult::fail(unreachable_msg("TDS 异议提交不可达", &e)).into_response(),
|
||||
Ok(env) => match unwrap_envelope_str(&env, &id) {
|
||||
Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUT /api/ssw/tdc/Billing/{id}/Confirm`(上游 `confirm`,**严格**身份口径)。
|
||||
async fn billing_confirm(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
_p: Option<Extension<Principal>>,
|
||||
body: OptionalJsonBody,
|
||||
) -> Response {
|
||||
let ident = local_identity(&state).await;
|
||||
let cid = match resolve_connector_id_strict(body_text(&body.0, "connectorId"), &ident) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return ActionResult::fail(
|
||||
"无法确定连接器身份(本端固定身份不可用,或与传入 connectorId 不一致)",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
if !owns_ledger(&state, &cid, &id).await {
|
||||
return ActionResult::fail("非本方账单,无权确认").into_response();
|
||||
}
|
||||
match state.tds.confirm_billing(&id, &cid).await {
|
||||
Err(e) => ActionResult::fail(unreachable_msg("TDS 账单确认不可达", &e)).into_response(),
|
||||
Ok(env) => match unwrap_envelope_str(&env, &id) {
|
||||
Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUT /api/ssw/tdc/Billing/{id}/Settle`(上游 `settle`,**严格**身份口径)。
|
||||
async fn billing_settle(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
_p: Option<Extension<Principal>>,
|
||||
body: OptionalJsonBody,
|
||||
) -> Response {
|
||||
let ident = local_identity(&state).await;
|
||||
let cid = match resolve_connector_id_strict(body_text(&body.0, "connectorId"), &ident) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return ActionResult::fail(
|
||||
"无法确定连接器身份(本端固定身份不可用,或与传入 connectorId 不一致)",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
if !owns_ledger(&state, &cid, &id).await {
|
||||
return ActionResult::fail("非本方账单,无权结算").into_response();
|
||||
}
|
||||
match state.tds.settle_billing(&id, &cid).await {
|
||||
Err(e) => ActionResult::fail(unreachable_msg("TDS 账单结算不可达", &e)).into_response(),
|
||||
Ok(env) => match unwrap_envelope_str(&env, &id) {
|
||||
Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUT /api/ssw/tdc/Billing/{id}/Receipt`(上游 `receipt`,**宽松**身份口径)。
|
||||
async fn billing_receipt(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
_p: Option<Extension<Principal>>,
|
||||
body: OptionalJsonBody,
|
||||
) -> Response {
|
||||
let ident = local_identity(&state).await;
|
||||
let cid = match resolve_connector_id_relaxed(body_text(&body.0, "connectorId"), &ident) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)")
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
if !owns_ledger(&state, &cid, &id).await {
|
||||
return ActionResult::fail("非本方账单,无权上传结算回执").into_response();
|
||||
}
|
||||
match state.tds.receipt_billing(&id, &body.0).await {
|
||||
Err(e) => ActionResult::fail(unreachable_msg("TDS 回执存证不可达", &e)).into_response(),
|
||||
Ok(env) => match unwrap_envelope_str(&env, &id) {
|
||||
Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/ssw/tdc/Billing/{id}/Voucher`(上游 `voucher`)。
|
||||
async fn billing_voucher(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
q: RawQuery,
|
||||
_p: Option<Extension<Principal>>,
|
||||
) -> Response {
|
||||
let params = parse_query(q.0.as_deref());
|
||||
let ident = local_identity(&state).await;
|
||||
let cid = match resolve_connector_id_relaxed(param(¶ms, "connectorId"), &ident) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)")
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
if !owns_ledger(&state, &cid, &id).await {
|
||||
return ActionResult::fail("非本方账单,无权下载对账凭证").into_response();
|
||||
}
|
||||
match state.tds.voucher_billing(&id).await {
|
||||
Err(e) => ActionResult::fail(unreachable_msg("TDS 凭证下载不可达", &e)).into_response(),
|
||||
Ok(env) => {
|
||||
// 上游:`code==200` 且 `data` 是 Map ⇒ success(data);否则 fail(msg)
|
||||
if env.get("code").and_then(|v| v.as_i64()) == Some(200) {
|
||||
if let Some(d) = env.get("data") {
|
||||
if d.is_object() {
|
||||
return ActionResult::ok(d.clone()).into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
ActionResult::fail(envelope_msg(&env, "平台处理失败")).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/ssw/tdc/Billing/LocalCompare?contractId=`(上游 `localCompare`)。
|
||||
///
|
||||
/// 🔴 **本地表**(`tdc_api_consume_log`),**不发任何出向请求**。
|
||||
async fn billing_local_compare(
|
||||
State(state): State<AppState>,
|
||||
q: RawQuery,
|
||||
_p: Option<Extension<Principal>>,
|
||||
) -> Response {
|
||||
let params = parse_query(q.0.as_deref());
|
||||
let contract_id = match param(¶ms, "contractId") {
|
||||
Some(c) => c,
|
||||
None => return ActionResult::fail("contractId 必填").into_response(),
|
||||
};
|
||||
// 上游:`eq("f_contract_id", contractId).apply("f_delete_mark is null").orderByAsc("f_call_time").last("limit 200")`
|
||||
let sql = "SELECT f_id, f_app_id, f_order_code, f_product_id, f_delivery_task_id, \
|
||||
f_call_time, f_ip, f_status, f_error_msg, f_contract_id, f_rows, \
|
||||
f_report_mark, f_metric_type, f_metric_value, f_actor_id, f_version_no \
|
||||
FROM tdc_api_consume_log \
|
||||
WHERE f_contract_id = $1 AND (f_delete_mark IS NULL OR f_delete_mark = 0) \
|
||||
ORDER BY f_call_time ASC LIMIT 200";
|
||||
let rows = {
|
||||
let _g = state.db_lock.lock().await;
|
||||
query_json_params(state.db.as_ref(), sql, &[&contract_id]).await
|
||||
};
|
||||
let rows = match rows {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return ActionResult::fail_code(CODE_SERVER_ERROR, format!("查询本地计量失败: {}", e))
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
// 列名 ⇒ camelCase(上游 Jackson 输出属性名,形状逐字对齐)
|
||||
let local: Vec<Value> = rows.iter().map(row_to_json).collect();
|
||||
ActionResult::ok(json!({"local": local, "contractId": contract_id})).into_response()
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use tokio::sync::Mutex;
|
||||
use crate::account::AccountStore;
|
||||
use crate::config::Config;
|
||||
use crate::session::SessionStore;
|
||||
use crate::tds::TdsClient;
|
||||
|
||||
/// 进程级唯一的 DB 锁。
|
||||
///
|
||||
@@ -35,6 +36,11 @@ pub struct AppState {
|
||||
pub bootstrap: Arc<BootstrapIdentity>,
|
||||
/// 本连接器的本地账号库(默认是**内存空库** ⇒ 早期任务与单测不必改)。
|
||||
pub accounts: Arc<AccountStore>,
|
||||
/// TDS 出向客户端(≡ 上游 `TdsReportClient` 的 internal 通道)。
|
||||
///
|
||||
/// 🔴 未配 `SSW_TDS_BASE_URL` ⇒ **NOOP 模式**(出向请求一律回业务失败,
|
||||
/// 不发任何网络请求)⇒ 本地单机模式不会因为「没配 TDS」而 500。
|
||||
pub tds: Arc<TdsClient>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -52,6 +58,11 @@ impl AppState {
|
||||
sessions: Arc<SessionStore>,
|
||||
bootstrap: BootstrapIdentity,
|
||||
) -> Self {
|
||||
// 🔴 先从 `config` 取值再 move(`config` 随后被包进 `Arc`)。
|
||||
let tds = Arc::new(TdsClient::new(
|
||||
config.tds_base_url.clone(),
|
||||
config.tds_internal_token.clone(),
|
||||
));
|
||||
Self {
|
||||
config: Arc::new(config),
|
||||
db,
|
||||
@@ -59,6 +70,7 @@ impl AppState {
|
||||
sessions,
|
||||
bootstrap: Arc::new(bootstrap),
|
||||
accounts: Arc::new(AccountStore::empty()),
|
||||
tds,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +97,16 @@ impl AppState {
|
||||
pub fn with_accounts(self, accounts: Arc<AccountStore>) -> Self {
|
||||
Self { accounts, ..self }
|
||||
}
|
||||
|
||||
/// 换掉 TDS 出向客户端(**其余字段原样保留**,特别是 `db_lock`)。
|
||||
///
|
||||
/// 用途:集成测试里把客户端指向**假 TDS**(起一个本地 axum server)。
|
||||
pub fn with_tds(self, tds: TdsClient) -> Self {
|
||||
Self {
|
||||
tds: Arc::new(tds),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in new issue
Block a user