|
|
@@ -1,5 +1,9 @@
|
|
|
use uuid::Uuid;
|
|
|
use chrono::{DateTime, Utc};
|
|
|
+use sqlx::{PgPool, FromRow};
|
|
|
+use crate::{
|
|
|
+ http_error::HttpError
|
|
|
+};
|
|
|
|
|
|
#[derive(FromRow)]
|
|
|
pub struct Purchase {
|
|
|
@@ -7,16 +11,89 @@ pub struct Purchase {
|
|
|
pub user_id: Uuid,
|
|
|
pub stripe_id: String,
|
|
|
pub status: Status,
|
|
|
- pub token_packs: u32,
|
|
|
- pub cost_per_token: u32,
|
|
|
- pub tokens_purchased: u32,
|
|
|
- pub cost: u32,
|
|
|
+ pub pack_count: i32,
|
|
|
+ pub cost_per_pack: i32,
|
|
|
+ pub tokens_per_pack: i32,
|
|
|
pub created_at: DateTime<Utc>
|
|
|
}
|
|
|
|
|
|
-struct Status {
|
|
|
+enum Status {
|
|
|
Pending,
|
|
|
Succeeded,
|
|
|
Failed,
|
|
|
Refunded
|
|
|
}
|
|
|
+
|
|
|
+impl TryFrom<String> for Status {
|
|
|
+ type Error = HttpError;
|
|
|
+
|
|
|
+ fn try_from(s: String) -> Result<Status, HttpError> {
|
|
|
+ match s.as_str() {
|
|
|
+ "Pending" => Ok(Self::Pending),
|
|
|
+ "Succeeded" => Ok(Self::Succeeded),
|
|
|
+ "Failed" => Ok(Self::Failed),
|
|
|
+ "Refunded" => Ok(Self::Refunded),
|
|
|
+ _ => Err(HttpError::InternalError("Invalid purchase status".into()))
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl Status {
|
|
|
+ fn to_string(&self) -> String {
|
|
|
+ match self {
|
|
|
+ Status::Pending => "Pending".to_string(),
|
|
|
+ Status::Succeeded => "Succeeded".to_string(),
|
|
|
+ Status::Failed => "Failed".to_string(),
|
|
|
+ Status::Refunded => "Refunded".to_string()
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl Purchase {
|
|
|
+ pub fn new(
|
|
|
+ user_id: Uuid,
|
|
|
+ stripe_id: String,
|
|
|
+ status: String,
|
|
|
+ pack_count: i32,
|
|
|
+ cost_per_pack: i32,
|
|
|
+ tokens_per_pack: i32
|
|
|
+ ) -> Result<Self, HttpError> {
|
|
|
+ Ok(Self {
|
|
|
+ id: Uuid::now_v7(),
|
|
|
+ user_id: user_id,
|
|
|
+ stripe_id: stripe_id,
|
|
|
+ status: Status::try_from(status)?,
|
|
|
+ pack_count: pack_count,
|
|
|
+ cost_per_pack: cost_per_pack,
|
|
|
+ tokens_per_pack: tokens_per_pack,
|
|
|
+ created_at: Utc::now()
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn insert_one(&self, db: &PgPool) -> Result<(), HttpError> {
|
|
|
+ sqlx::query(
|
|
|
+ "INSERT INTO purchases(
|
|
|
+ id,
|
|
|
+ user_id,
|
|
|
+ stripe_id,
|
|
|
+ status,
|
|
|
+ pack_count,
|
|
|
+ cost_per_pack,
|
|
|
+ tokens_per_pack,
|
|
|
+ created_at
|
|
|
+ )
|
|
|
+ VALUES($1, $2, $3, $4, $5, $6, $7)"
|
|
|
+ )
|
|
|
+ .bind(&self.id)
|
|
|
+ .bind(&self.user_id)
|
|
|
+ .bind(&self.status.to_string())
|
|
|
+ .bind(&self.pack_count)
|
|
|
+ .bind(&self.cost_per_pack)
|
|
|
+ .bind(&self.tokens_per_pack)
|
|
|
+ .bind(&self.created_at)
|
|
|
+ .execute(db)
|
|
|
+ .await?;
|
|
|
+
|
|
|
+ Ok(())
|
|
|
+ }
|
|
|
+}
|