add: products api

This commit is contained in:
trisua 2025-08-07 13:52:48 -04:00
parent 3c4ce1fae5
commit df5eaf24f7
29 changed files with 1022 additions and 110 deletions

View file

@ -315,6 +315,9 @@ pub struct Config {
/// to post in by default. This should be some sort of "general" topic.
#[serde(default)]
pub town_square_forum_topic: usize,
/// The ID of the "system" user which will send system mails to users.
#[serde(default)]
pub system_user: usize,
#[serde(default)]
pub connections: ConnectionsConfig,
/// The path to the HTML footer file. The contents of this file are embedded
@ -396,6 +399,8 @@ fn default_banned_usernames() -> Vec<String> {
"services".to_string(),
"domains".to_string(),
"mail".to_string(),
"product".to_string(),
"wallet".to_string(),
]
}
@ -439,6 +444,7 @@ impl Default for Config {
town_square: 0,
town_square_forum: 0,
town_square_forum_topic: 0,
system_user: 0,
connections: default_connections(),
html_footer_path: String::new(),
stripe: None,

View file

@ -44,6 +44,8 @@ impl DataManager {
execute!(&conn, common::CREATE_TABLE_SERVICES).unwrap();
execute!(&conn, common::CREATE_TABLE_APP_DATA).unwrap();
execute!(&conn, common::CREATE_TABLE_LETTERS).unwrap();
execute!(&conn, common::CREATE_TABLE_TRANSFERS).unwrap();
execute!(&conn, common::CREATE_TABLE_PRODUCTS).unwrap();
for x in common::VERSION_MIGRATIONS.split(";") {
execute!(&conn, x).unwrap();

View file

@ -32,3 +32,5 @@ pub const CREATE_TABLE_DOMAINS: &str = include_str!("./sql/create_domains.sql");
pub const CREATE_TABLE_SERVICES: &str = include_str!("./sql/create_services.sql");
pub const CREATE_TABLE_APP_DATA: &str = include_str!("./sql/create_app_data.sql");
pub const CREATE_TABLE_LETTERS: &str = include_str!("./sql/create_letters.sql");
pub const CREATE_TABLE_TRANSFERS: &str = include_str!("./sql/create_transfers.sql");
pub const CREATE_TABLE_PRODUCTS: &str = include_str!("./sql/create_products.sql");

View file

@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS products (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
method TEXT NOT NULL,
on_sale INT NOT NULL,
price INT NOT NULL,
stock INT NOT NULL
)

View file

@ -4,5 +4,6 @@ CREATE TABLE IF NOT EXISTS requests (
owner BIGINT NOT NULL,
action_type TEXT NOT NULL,
linked_asset BIGINT NOT NULL,
data TEXT NOT NULL,
PRIMARY KEY (id, owner, linked_asset)
)

View file

@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS transfers (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
sender BIGINT NOT NULL,
receiver BIGINT NOT NULL,
amount INT NOT NULL,
is_pending INT NOT NULL,
method TEXT NOT NULL
)

View file

@ -37,3 +37,7 @@ DROP COLUMN IF EXISTS seller_data;
-- users coins
ALTER TABLE users
ADD COLUMN IF NOT EXISTS coins INT DEFAULT 0;
-- requests data
ALTER TABLE requests
ADD COLUMN IF NOT EXISTS data TEXT DEFAULT '"Null"';

View file

@ -1,91 +0,0 @@
use crate::model::economy::CoinTransfer;
use crate::model::{Error, Result};
use crate::{auto_method, DataManager};
use oiseau::{cache::Cache, execute, get, params, query_rows, PostgresRow};
impl DataManager {
/// Get a [`CoinTransfer`] from an SQL row.
pub(crate) fn get_transfer_from_row(x: &PostgresRow) -> CoinTransfer {
CoinTransfer {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
sender: get!(x->2(i64)) as usize,
receiver: get!(x->3(i64)) as usize,
amount: get!(x->4(i32)),
}
}
auto_method!(get_transfer_by_id(usize as i64)@get_transfer_from_row -> "SELECT * FROM transfers WHERE id = $1" --name="transfer" --returns=CoinTransfer --cache-key-tmpl="atto.transfer:{}");
/// Get all transfers by user.
///
/// # Arguments
/// * `id` - the ID of the user to fetch transfers for
/// * `batch` - the limit of items in each page
/// * `page` - the page number
pub async fn get_transfers_by_user(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<CoinTransfer>> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM transfers WHERE sender = $1 OR receiver = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[&(id as i64), &(batch as i64), &((page * batch) as i64)],
|x| { Self::get_transfer_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("transfer".to_string()));
}
Ok(res.unwrap())
}
/// Create a new transfer in the database.
///
/// # Arguments
/// * `data` - a mock [`CoinTransfer`] object to insert
pub async fn create_transfer(&self, data: CoinTransfer) -> Result<CoinTransfer> {
// check values
let mut sender = self.get_user_by_id(data.sender).await?;
let mut receiver = self.get_user_by_id(data.receiver).await?;
let (sender_bankrupt, receiver_bankrupt) = data.apply(&mut sender, &mut receiver);
if sender_bankrupt | receiver_bankrupt {
return Err(Error::MiscError(
"One party of this transfer cannot afford this".to_string(),
));
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO transfers VALUES ($1, $2, $3, $4, $5)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.sender as i64),
&(data.receiver as i64),
&data.amount
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
}

View file

@ -200,6 +200,7 @@ impl DataManager {
community.owner,
ActionType::CommunityJoin,
community.id,
None,
))
.await?;

View file

@ -9,7 +9,6 @@ pub mod connections;
mod domains;
mod drafts;
mod drivers;
mod economy;
mod emojis;
mod invite_codes;
mod ipbans;
@ -24,6 +23,7 @@ mod notifications;
mod polls;
mod pollvotes;
mod posts;
mod products;
mod questions;
mod reactions;
mod reports;
@ -31,6 +31,7 @@ mod requests;
mod services;
mod stackblocks;
mod stacks;
mod transfers;
mod uploads;
mod user_warnings;
mod userblocks;

View file

@ -0,0 +1,228 @@
use crate::model::{
auth::User,
economy::{CoinTransfer, CoinTransferMethod, Product, ProductFulfillmentMethod},
mail::Letter,
permissions::FinePermission,
Error, Result,
};
use crate::{auto_method, DataManager};
use oiseau::{cache::Cache, execute, get, params, query_rows, PostgresRow};
impl DataManager {
/// Get a [`Product`] from an SQL row.
pub(crate) fn get_product_from_row(x: &PostgresRow) -> Product {
Product {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
title: get!(x->3(String)),
description: get!(x->4(String)),
method: serde_json::from_str(&get!(x->5(String))).unwrap(),
on_sale: get!(x->6(i32)) as i8 == 1,
price: get!(x->7(i32)),
stock: get!(x->8(i32)),
}
}
auto_method!(get_product_by_id(usize as i64)@get_product_from_row -> "SELECT * FROM products WHERE id = $1" --name="product" --returns=Product --cache-key-tmpl="atto.product:{}");
/// Get all products by user.
///
/// # Arguments
/// * `id` - the ID of the user to fetch products for
/// * `batch` - the limit of items in each page
/// * `page` - the page number
pub async fn get_products_by_user(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<Product>> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM products WHERE owner = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[&(id as i64), &(batch as i64), &((page * batch) as i64)],
|x| { Self::get_product_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("product".to_string()));
}
Ok(res.unwrap())
}
const MAXIMUM_FREE_PRODUCTS: usize = 5;
/// Create a new product in the database.
///
/// # Arguments
/// * `data` - a mock [`Product`] object to insert
pub async fn create_product(&self, mut data: Product) -> Result<Product> {
data.title = data.title.trim().to_string();
data.description = data.description.trim().to_string();
// check values
if data.title.len() < 2 {
return Err(Error::DataTooShort("title".to_string()));
} else if data.title.len() > 128 {
return Err(Error::DataTooLong("title".to_string()));
}
if data.description.len() < 2 {
return Err(Error::DataTooShort("description".to_string()));
} else if data.description.len() > 1024 {
return Err(Error::DataTooLong("description".to_string()));
}
// check number of stacks
let owner = self.get_user_by_id(data.owner).await?;
if !owner.permissions.check(FinePermission::SUPPORTER) {
let products = self
.get_table_row_count_where("products", &format!("owner = {}", owner.id))
.await? as usize;
if products >= Self::MAXIMUM_FREE_PRODUCTS {
return Err(Error::MiscError(
"You already have the maximum number of products you can have".to_string(),
));
}
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO products VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&data.title,
&data.description,
&serde_json::to_string(&data.method).unwrap(),
&{ if data.on_sale { 1 } else { 0 } },
&data.price,
&(data.stock as i32)
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
/// Purchase the given product as the given user.
pub async fn purchase_product(
&self,
product: usize,
customer: &mut User,
) -> Result<CoinTransfer> {
let product = self.get_product_by_id(product).await?;
let mut transfer = CoinTransfer::new(
customer.id,
product.owner,
product.price,
CoinTransferMethod::Purchase(product.id),
);
if !product.stock.is_negative() {
// check stock
if product.stock == 0 {
return Err(Error::MiscError("No remaining stock".to_string()));
} else {
self.decr_product_stock(product.id).await?;
}
}
match product.method {
ProductFulfillmentMethod::AutoMail(message) => {
// we're basically done, transfer coins and send mail
self.create_transfer(&mut transfer, false).await?;
self.create_letter(Letter::new(
self.0.0.system_user,
vec![customer.id],
format!("Thank you for purchasing \"{}\"", product.title),
format!("The message below was supplied by the product owner, and was automatically sent.\n***\n{message}"),
0,
))
.await?;
Ok(transfer)
}
ProductFulfillmentMethod::ManualMail => {
// mark transfer as pending and create it
self.create_transfer(&mut transfer, false).await?;
// tell product owner they have a new pending purchase
self.create_letter(Letter::new(
self.0.0.system_user,
vec![product.owner],
"New product purchase pending".to_string(),
format!(
"Somebody has purchased your [product](/product/{}) \"{}\". Per your product's settings, the payment will not be completed until you manually mail them a letter **using the link below**.
If your product is a purchase of goods or services, please be sure to fulfill this purchase either in the letter or elsewhere. The customer may request support if you fail to do so.
***
<a class=\"button\" href=\"/mail/compose?receivers=id:{}&title=Product%20fulfillment&transfer_id={}\">Fulfill purchase</a>",
product.id, product.title, customer.id, transfer.id
),
0,
))
.await?;
// return
Ok(transfer)
}
}
}
pub async fn delete_product(&self, id: usize, user: &User) -> Result<()> {
let product = self.get_product_by_id(id).await?;
// check user permission
if user.id != product.owner && !user.permissions.check(FinePermission::MANAGE_USERS) {
return Err(Error::NotAllowed);
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(&conn, "DELETE FROM products WHERE id = $1", &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// ...
self.0.1.remove(format!("atto.product:{}", id)).await;
Ok(())
}
auto_method!(update_product_title(&str)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET title = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
auto_method!(update_product_description(&str)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET description = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
auto_method!(update_product_price(i32)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET price = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
auto_method!(update_product_on_sale(i32)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET on_sale = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
auto_method!(update_product_method(ProductFulfillmentMethod)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET method = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.product:{}");
auto_method!(update_product_stock(i32)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET stock = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
auto_method!(incr_product_stock() -> "UPDATE products SET stock = stock + 1 WHERE id = $1" --cache-key-tmpl="atto.product:{}" --incr);
auto_method!(decr_product_stock()@get_product_by_id -> "UPDATE products SET stock = stock - 1 WHERE id = $1" --cache-key-tmpl="atto.product:{}" --decr=stock);
}

View file

@ -506,6 +506,7 @@ impl DataManager {
data.receiver,
ActionType::Answer,
data.id,
None,
))
.await?;
}

View file

@ -14,6 +14,7 @@ impl DataManager {
owner: get!(x->2(i64)) as usize,
action_type: serde_json::from_str(&get!(x->3(String))).unwrap(),
linked_asset: get!(x->4(i64)) as usize,
data: serde_json::from_str(&get!(x->5(String))).unwrap(),
}
}
@ -118,13 +119,14 @@ impl DataManager {
let res = execute!(
&conn,
"INSERT INTO requests VALUES ($1, $2, $3, $4, $5)",
"INSERT INTO requests VALUES ($1, $2, $3, $4, $5, $6)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&serde_json::to_string(&data.action_type).unwrap().as_str(),
&(data.linked_asset as i64),
&serde_json::to_string(&data.data).unwrap().as_str(),
]
);

View file

@ -0,0 +1,175 @@
use std::collections::HashMap;
use crate::model::auth::User;
use crate::model::economy::{CoinTransferMethod, Product};
use crate::model::{Error, Result, economy::CoinTransfer};
use crate::{auto_method, DataManager};
use oiseau::{cache::Cache, execute, get, params, query_rows, PostgresRow};
impl DataManager {
/// Get a [`CoinTransfer`] from an SQL row.
pub(crate) fn get_transfer_from_row(x: &PostgresRow) -> CoinTransfer {
CoinTransfer {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
sender: get!(x->2(i64)) as usize,
receiver: get!(x->3(i64)) as usize,
amount: get!(x->4(i32)),
is_pending: get!(x->5(i32)) as i8 == 1,
method: serde_json::from_str(&get!(x->6(String))).unwrap(),
}
}
auto_method!(get_transfer_by_id(usize as i64)@get_transfer_from_row -> "SELECT * FROM transfers WHERE id = $1" --name="transfer" --returns=CoinTransfer --cache-key-tmpl="atto.transfer:{}");
/// Fill a list of transfers with their users and product.
pub async fn fill_transfers(
&self,
list: Vec<CoinTransfer>,
) -> Result<Vec<(usize, usize, i32, User, User, Option<Product>, bool)>> {
let mut out = Vec::new();
let mut seen_users: HashMap<usize, User> = HashMap::new();
let mut seen_products: HashMap<usize, Product> = HashMap::new();
for transfer in list {
out.push((
transfer.id,
transfer.created,
transfer.amount,
if let Some(user) = seen_users.get(&transfer.sender) {
user.to_owned()
} else {
let user = self.get_user_by_id(transfer.sender).await?;
seen_users.insert(user.id, user.clone());
user
},
if let Some(user) = seen_users.get(&transfer.receiver) {
user.to_owned()
} else {
let user = self.get_user_by_id(transfer.receiver).await?;
seen_users.insert(user.id, user.clone());
user
},
match transfer.method {
CoinTransferMethod::Transfer => None,
CoinTransferMethod::Purchase(id) => {
Some(if let Some(product) = seen_products.get(&id) {
product.to_owned()
} else {
let product = self.get_product_by_id(id).await?;
seen_products.insert(product.id, product.clone());
product
})
}
},
transfer.is_pending,
));
}
Ok(out)
}
/// Get all transfers by user.
///
/// # Arguments
/// * `id` - the ID of the user to fetch transfers for
/// * `batch` - the limit of items in each page
/// * `page` - the page number
pub async fn get_transfers_by_user(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<CoinTransfer>> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM transfers WHERE sender = $1 OR receiver = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[&(id as i64), &(batch as i64), &((page * batch) as i64)],
|x| { Self::get_transfer_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("transfer".to_string()));
}
Ok(res.unwrap())
}
/// Create a new transfer in the database.
///
/// # Arguments
/// * `data` - a mock [`CoinTransfer`] object to insert
pub async fn create_transfer(&self, data: &mut CoinTransfer, apply: bool) -> Result<usize> {
// check values
let mut sender = self.get_user_by_id(data.sender).await?;
let mut receiver = self.get_user_by_id(data.receiver).await?;
let (sender_bankrupt, receiver_bankrupt) = data.apply(&mut sender, &mut receiver);
if sender_bankrupt | receiver_bankrupt {
return Err(Error::MiscError(
"One party of this transfer cannot afford this".to_string(),
));
}
if apply {
self.update_user_coins(sender.id, sender.coins).await?;
self.update_user_coins(receiver.id, receiver.coins).await?;
} else {
// we haven't applied the transfer, so this must be pending
data.is_pending = true;
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO transfers VALUES ($1, $2, $3, $4, $5, $6, $7)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.sender as i64),
&(data.receiver as i64),
&data.amount,
&{ if data.is_pending { 1 } else { 0 } },
&serde_json::to_string(&data.method).unwrap(),
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data.id)
}
/// Apply a pending transfer.
pub async fn apply_transfer(&self, id: usize) -> Result<()> {
let transfer = self.get_transfer_by_id(id).await?;
let mut sender = self.get_user_by_id(transfer.sender).await?;
let mut receiver = self.get_user_by_id(transfer.receiver).await?;
let (sender_bankrupt, receiver_bankrupt) = transfer.apply(&mut sender, &mut receiver);
if sender_bankrupt | receiver_bankrupt {
return Err(Error::MiscError(
"One party of this transfer cannot afford this".to_string(),
));
}
self.update_user_coins(sender.id, sender.coins).await?;
self.update_user_coins(receiver.id, receiver.coins).await?;
self.update_transfer_is_pending(id, 0).await?;
Ok(())
}
auto_method!(update_transfer_is_pending(i32) -> "UPDATE products SET is_pending = $1 WHERE id = $2" --cache-key-tmpl="atto.transfer:{}");
}

View file

@ -276,6 +276,7 @@ impl DataManager {
data.receiver,
ActionType::Follow,
data.receiver,
None,
))
.await?;

View file

@ -1,8 +1,60 @@
use serde::{Serialize, Deserialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
use super::auth::User;
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ProductFulfillmentMethod {
/// Automatically send a letter to the customer with the specified content.
AutoMail(String),
/// Manually send a letter to the customer with the specified content.
///
/// This will leave the [`CoinTransfer`] pending until you send this mail.
ManualMail,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Product {
pub id: usize,
pub created: usize,
pub owner: usize,
pub title: String,
pub description: String,
/// How this product will be delivered.
pub method: ProductFulfillmentMethod,
/// If this product is actually for sale.
pub on_sale: bool,
/// The price of this product.
pub price: i32,
/// The number of times this product can be purchased.
///
/// A negative stock means the product has unlimited stock.
pub stock: i32,
}
impl Product {
/// Create a new [`Product`].
pub fn new(owner: usize, title: String, description: String) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
owner,
title,
description,
method: ProductFulfillmentMethod::ManualMail,
on_sale: false,
price: 0,
stock: 0,
}
}
}
#[derive(Serialize, Deserialize)]
pub enum CoinTransferMethod {
Transfer,
/// A [`Product`] purchase with the product's ID.
Purchase(usize),
}
#[derive(Serialize, Deserialize)]
pub struct CoinTransfer {
pub id: usize,
@ -10,17 +62,21 @@ pub struct CoinTransfer {
pub sender: usize,
pub receiver: usize,
pub amount: i32,
pub is_pending: bool,
pub method: CoinTransferMethod,
}
impl CoinTransfer {
/// Create a new [`CoinTransfer`].
pub fn new(sender: usize, receiver: usize, amount: i32) -> Self {
pub fn new(sender: usize, receiver: usize, amount: i32, method: CoinTransferMethod) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
sender,
receiver,
amount,
is_pending: false,
method,
}
}

View file

@ -74,10 +74,10 @@ pub enum AppScope {
UserReadDomains,
/// Read the user's services.
UserReadServices,
/// Read the user's products.
UserReadProducts,
/// Read the user's letters.
UserReadLetters,
/// Read the user's products.
UserReadProducts,
/// Create posts as the user.
UserCreatePosts,
/// Create messages as the user.
@ -102,10 +102,10 @@ pub enum AppScope {
UserCreateDomains,
/// Create services on behalf of the user.
UserCreateServices,
/// Create products on behalf of the user.
UserCreateProducts,
/// Create letters on behalf of the user.
UserCreateLetters,
/// Create products on behalf of the user.
UserCreateProducts,
/// Send coins on behalf of the user.
UserSendCoins,
/// Delete posts owned by the user.
@ -148,12 +148,12 @@ pub enum AppScope {
UserManageDomains,
/// Manage the user's services.
UserManageServices,
/// Manage the user's products.
UserManageProducts,
/// Manage the user's channel mutes.
UserManageChannelMutes,
/// Manage the user's letters.
UserManageLetters,
/// Manage the user's products.
UserManageProducts,
/// Edit posts created by the user.
UserEditPosts,
/// Edit drafts created by the user.

View file

@ -1,6 +1,51 @@
use serde::{Serialize, Deserialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
#[derive(Serialize, Deserialize, PartialEq, Eq)]
pub enum ActionData {
String(String),
Int32(i32),
Usize(usize),
Many(Vec<ActionData>),
Null,
}
impl ActionData {
pub fn read_string(self) -> String {
match self {
ActionData::String(x) => x,
_ => String::default(),
}
}
pub fn read_int32(self) -> i32 {
match self {
ActionData::Int32(x) => x,
_ => i32::default(),
}
}
pub fn read_usize(self) -> usize {
match self {
ActionData::Usize(x) => x,
_ => usize::default(),
}
}
pub fn read_many(self) -> Vec<ActionData> {
match self {
ActionData::Many(x) => x,
_ => Vec::default(),
}
}
}
impl Default for ActionData {
fn default() -> Self {
Self::Null
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq)]
pub enum ActionType {
/// A request to join a community.
@ -15,6 +60,10 @@ pub enum ActionType {
///
/// `users` table.
Follow,
/// A request for the `owner` user (sender) to send the `linked_asset` user (receiver) coins.
///
/// Expects a `data` value of [`ActionData::Int32`] representing the coin amount.
Transfer,
}
#[derive(Serialize, Deserialize)]
@ -26,28 +75,49 @@ pub struct ActionRequest {
/// The ID of the asset this request links to. Should exist in the correct
/// table for the given [`ActionType`].
pub linked_asset: usize,
/// Optional data attached to the action request.
pub data: ActionData,
}
impl ActionRequest {
/// Create a new [`ActionRequest`].
pub fn new(owner: usize, action_type: ActionType, linked_asset: usize) -> Self {
pub fn new(
owner: usize,
action_type: ActionType,
linked_asset: usize,
data: Option<ActionData>,
) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
owner,
action_type,
linked_asset,
data: match data {
Some(x) => x,
None => ActionData::default(),
},
}
}
/// Create a new [`ActionRequest`] with the given `id`.
pub fn with_id(id: usize, owner: usize, action_type: ActionType, linked_asset: usize) -> Self {
pub fn with_id(
id: usize,
owner: usize,
action_type: ActionType,
linked_asset: usize,
data: Option<ActionData>,
) -> Self {
Self {
id,
created: unix_epoch_timestamp(),
owner,
action_type,
linked_asset,
data: match data {
Some(x) => x,
None => ActionData::default(),
},
}
}
}