Skip to main content

acosmi/billing/
packages.rs

1//! Token Packages / 商城业务方法。端口自 `billing/packages.ts`
2//! (declaration-merging → 此处 `impl Client` 块)。
3
4use super::entitlements::urlencoding;
5use super::types::{BuyResponse, OrderListItem, PayPayload, TokenPackage};
6use crate::core::client::Client;
7use crate::core::http::{is_order_success, is_order_terminal};
8use crate::shared::{Error, Result, YudaoPageResult};
9use tokio_util::sync::CancellationToken;
10
11impl Client {
12    /// 获取商城流量包列表(兼容 yudao 分页和直接数组两种格式)。对应 TS `listTokenPackages`。
13    pub async fn list_token_packages(
14        &self,
15        signal: Option<CancellationToken>,
16    ) -> Result<Vec<TokenPackage>> {
17        let raw: serde_json::Value = self.billing_get("/token-packages", signal).await?;
18        decode_list_or_page("token packages", raw)
19    }
20
21    /// 获取流量包详情。对应 TS `getTokenPackageDetail`。
22    pub async fn get_token_package_detail(
23        &self,
24        package_id: &str,
25        signal: Option<CancellationToken>,
26    ) -> Result<TokenPackage> {
27        let path = format!("/token-packages/{}", urlencoding(package_id));
28        self.billing_get(&path, signal).await
29    }
30
31    /// 购买流量包(创建订单)。对应 TS `buyTokenPackage`。
32    pub async fn buy_token_package(
33        &self,
34        package_id: &str,
35        payload: Option<&PayPayload>,
36        signal: Option<CancellationToken>,
37    ) -> Result<BuyResponse> {
38        let path = format!("/token-packages/{}/buy", urlencoding(package_id));
39        let body = match payload {
40            Some(p) => Some(
41                serde_json::to_string(p)
42                    .map_err(|e| Error::other(format!("serialize pay payload: {e}")))?,
43            ),
44            None => None,
45        };
46        self.billing_post_body(&path, body.as_deref(), signal).await
47    }
48
49    /// 查询订单支付状态。对应 TS `getOrderStatus`。
50    pub async fn get_order_status(
51        &self,
52        order_id: &str,
53        signal: Option<CancellationToken>,
54    ) -> Result<BuyResponse> {
55        let path = format!("/token-packages/orders/{}/status", urlencoding(order_id));
56        self.billing_get(&path, signal).await
57    }
58
59    /// 查询我的订单列表。对应 TS `listMyOrders`。
60    pub async fn list_my_orders(
61        &self,
62        signal: Option<CancellationToken>,
63    ) -> Result<Vec<OrderListItem>> {
64        let raw: serde_json::Value = self.billing_get("/token-packages/my", signal).await?;
65        decode_list_or_page("orders", raw)
66    }
67
68    /// 轮询订单支付状态直到终态。对应 TS `waitForPayment`。
69    ///
70    /// 成功支付返回 [`BuyResponse`];终态失败抛 [`Error::OrderTerminal`]。
71    /// 终态判定基于 `paymentStatus`(回退 `orderStatus`)。`poll_interval_ms <= 0` 时默认 2 秒。
72    pub async fn wait_for_payment(
73        &self,
74        order_id: &str,
75        mut poll_interval_ms: i64,
76        signal: Option<CancellationToken>,
77    ) -> Result<BuyResponse> {
78        if poll_interval_ms <= 0 {
79            poll_interval_ms = 2000;
80        }
81        loop {
82            let status = self.get_order_status(order_id, signal.clone()).await?;
83            let st = if status.payment_status.is_empty() {
84                status.order_status.clone()
85            } else {
86                status.payment_status.clone()
87            };
88            if is_order_terminal(&st) {
89                if is_order_success(&st) {
90                    return Ok(status);
91                }
92                return Err(Error::OrderTerminal {
93                    order_id: order_id.to_string(),
94                    status: st,
95                });
96            }
97            sleep_with_cancel(poll_interval_ms as u64, signal.as_ref()).await?;
98        }
99    }
100}
101
102/// yudao 分页 `{list:[...]}` 或裸数组两种形态解码(对齐 TS `listTokenPackages`/`listMyOrders`)。
103fn decode_list_or_page<T: serde::de::DeserializeOwned>(
104    what: &str,
105    raw: serde_json::Value,
106) -> Result<Vec<T>> {
107    // 尝试 yudao 分页格式。
108    if raw.is_object() && raw.get("list").is_some() {
109        let page: YudaoPageResult<T> =
110            serde_json::from_value(raw).map_err(|e| Error::other(format!("decode {what}: {e}")))?;
111        return Ok(page.list);
112    }
113    // 降级:直接数组。
114    if raw.is_array() {
115        return serde_json::from_value(raw)
116            .map_err(|e| Error::other(format!("decode {what}: {e}")));
117    }
118    Err(Error::other(format!("decode {what}: unexpected shape")))
119}
120
121/// 可取消 sleep(对应 TS `sleepWithSignal`);取消触发抛 aborted。
122async fn sleep_with_cancel(ms: u64, signal: Option<&CancellationToken>) -> Result<()> {
123    if ms == 0 {
124        return Ok(());
125    }
126    match signal {
127        Some(c) if c.is_cancelled() => Err(Error::other("aborted")),
128        Some(c) => {
129            tokio::select! {
130                _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => Ok(()),
131                _ = c.cancelled() => Err(Error::other("aborted")),
132            }
133        }
134        None => {
135            tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
136            Ok(())
137        }
138    }
139}