feat: implement payment order system (create-order, mock-confirm, get-quota)

This commit is contained in:
2026-04-17 12:45:53 +08:00
parent 454139f70d
commit 562528a1f0
7 changed files with 296 additions and 3 deletions

View File

@@ -311,3 +311,96 @@ pub async fn update_user_profile(
Err(e) => Err(format!("更新用户个人信息失败: {}", e)),
}
}
// ===== 支付系统 DB 函数 =====
/// 创建待支付订单
pub async fn create_payment_order(
pool: &PgPool,
user_id: i32,
order_no: &str,
package_type: &str,
amount: i32,
expires_at: Option<chrono::DateTime<chrono::Utc>>,
) -> Result<(), String> {
let query = r#"
INSERT INTO payment_orders (user_id, order_no, package_type, amount, expires_at)
VALUES ($1, $2, $3, $4, $5)
"#;
sqlx::query(query)
.bind(user_id)
.bind(order_no)
.bind(package_type)
.bind(amount)
.bind(expires_at)
.execute(pool)
.await
.map_err(|e| format!("创建订单失败: {}", e))?;
Ok(())
}
/// 确认订单支付(模拟):更新订单状态 + 激活用户付费
///
/// 返回该订单的 expires_at永久会员为 None
pub async fn confirm_payment_order(
pool: &PgPool,
order_no: &str,
user_id: i32,
) -> Result<Option<chrono::DateTime<chrono::Utc>>, String> {
let row = sqlx::query_as::<_, (i32, String, Option<chrono::DateTime<chrono::Utc>>)>(
r#"SELECT user_id, status, expires_at FROM payment_orders WHERE order_no = $1"#,
)
.bind(order_no)
.fetch_optional(pool)
.await
.map_err(|e| format!("查询订单失败: {}", e))?;
let (order_user_id, status, expires_at) = match row {
Some(r) => r,
None => return Err("订单不存在".to_string()),
};
if order_user_id != user_id {
return Err("无权操作此订单".to_string());
}
if status != "pending" {
return Err("订单状态异常,无法确认支付".to_string());
}
sqlx::query(
r#"UPDATE payment_orders SET status = 'paid', paid_at = NOW() WHERE order_no = $1"#,
)
.bind(order_no)
.execute(pool)
.await
.map_err(|e| format!("更新订单状态失败: {}", e))?;
sqlx::query(
r#"UPDATE users SET is_paid = true, paid_expires_at = $1 WHERE id = $2"#,
)
.bind(expires_at)
.bind(user_id)
.execute(pool)
.await
.map_err(|e| format!("更新用户付费状态失败: {}", e))?;
Ok(expires_at)
}
/// 获取用户配额信息
///
/// 返回 (已用条数, 是否付费活跃, 到期时间)
pub async fn get_user_quota(
pool: &PgPool,
user_id: i32,
) -> Result<(i64, bool, Option<chrono::DateTime<chrono::Utc>>), String> {
let user = get_user_by_id(pool, user_id).await?;
let is_paid_active = user.is_paid
&& (user.paid_expires_at.is_none()
|| user.paid_expires_at.unwrap() > chrono::Utc::now());
let used = count_user_weather_data(pool, user_id).await?;
Ok((used, is_paid_active, user.paid_expires_at))
}