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

@ -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?;