2024-07-24 14:38:56 +00:00
|
|
|
use mongod::{derive::{Model, Referencable}, Validate};
|
2024-06-22 00:05:22 +00:00
|
|
|
use mongodb::bson::doc;
|
2024-07-24 14:38:56 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2024-06-22 00:05:22 +00:00
|
|
|
use serde_json::json;
|
|
|
|
|
2024-07-24 14:38:56 +00:00
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, Model, Referencable)]
|
|
|
|
pub struct Transaction {
|
|
|
|
pub _id: String,
|
|
|
|
pub item: String,
|
|
|
|
pub variant: String,
|
|
|
|
pub price: Price,
|
|
|
|
pub origin: Option<String>,
|
|
|
|
pub consumed: Option<Consumed>,
|
|
|
|
pub timestamp: i64,
|
2024-05-03 16:22:59 +00:00
|
|
|
}
|
|
|
|
|
2024-07-24 14:38:56 +00:00
|
|
|
impl Validate for Transaction {
|
|
|
|
async fn validate(&self) -> Result<(), String> {
|
|
|
|
Ok(())
|
2024-05-03 16:22:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-24 14:38:56 +00:00
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
|
|
|
pub struct Consumed {
|
|
|
|
pub destination: String,
|
2024-05-03 16:22:59 +00:00
|
|
|
pub price: Price,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Transaction {
|
2024-07-24 14:38:56 +00:00
|
|
|
pub fn new(item: &str, variant: &str, price: Price, origin: Option<&str>) -> Self {
|
2024-05-03 16:22:59 +00:00
|
|
|
Self {
|
2024-07-24 14:38:56 +00:00
|
|
|
_id: uuid::Uuid::new_v4().to_string(),
|
2024-05-03 16:22:59 +00:00
|
|
|
item: item.to_string(),
|
|
|
|
variant: variant.to_string(),
|
|
|
|
price,
|
2024-07-24 14:38:56 +00:00
|
|
|
consumed: None,
|
|
|
|
origin: origin.map(|x| x.to_string()),
|
2024-05-03 16:22:59 +00:00
|
|
|
timestamp: chrono::Utc::now().timestamp(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-22 00:05:22 +00:00
|
|
|
pub fn api_json(&self) -> serde_json::Value {
|
|
|
|
json!({
|
2024-07-24 14:38:56 +00:00
|
|
|
"uuid": self._id,
|
2024-06-22 00:05:22 +00:00
|
|
|
"item": self.item,
|
|
|
|
"variant": self.variant,
|
|
|
|
"price": self.price,
|
|
|
|
"origin": self.origin,
|
|
|
|
"timestamp": self.timestamp
|
|
|
|
})
|
|
|
|
}
|
2024-06-21 19:14:45 +00:00
|
|
|
}
|
2024-05-03 16:22:59 +00:00
|
|
|
|
2024-07-24 14:38:56 +00:00
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
2024-05-03 16:22:59 +00:00
|
|
|
pub struct Price {
|
|
|
|
pub value: f64,
|
|
|
|
pub currency: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Price {
|
|
|
|
pub fn new(value: f64, currency: &str) -> Self {
|
|
|
|
Self {
|
|
|
|
value,
|
|
|
|
currency: currency.to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parse(price: &str) -> Option<Self> {
|
|
|
|
let (value, currency) = price.split_once(' ')?;
|
|
|
|
|
|
|
|
Some(Self {
|
|
|
|
value: value.parse().ok()?,
|
|
|
|
currency: currency.to_string(),
|
|
|
|
})
|
|
|
|
}
|
2024-06-21 19:14:45 +00:00
|
|
|
}
|
2024-05-03 16:22:59 +00:00
|
|
|
|
|
|
|
impl TryFrom<String> for Price {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
|
|
|
Self::parse(&value).ok_or(())
|
|
|
|
}
|
|
|
|
}
|