add: single_use products

This commit is contained in:
trisua 2025-08-08 14:17:40 -04:00
parent 7fbc732290
commit e5e6d5cddb
12 changed files with 149 additions and 7 deletions

View file

@ -337,9 +337,11 @@ version = "1.0.0"
"economy:label.create_new" = "Create new product" "economy:label.create_new" = "Create new product"
"economy:label.price" = "Price" "economy:label.price" = "Price"
"economy:label.on_sale" = "On sale" "economy:label.on_sale" = "On sale"
"economy:label.single_use" = "Only allow users to purchase once"
"economy:label.stock" = "Stock" "economy:label.stock" = "Stock"
"economy:label.unlimited" = "Unlimited" "economy:label.unlimited" = "Unlimited"
"economy:label.fulfillment_style" = "Fulfillment style" "economy:label.fulfillment_style" = "Fulfillment style"
"economy:label.use_automail" = "Use automail" "economy:label.use_automail" = "Use automail"
"economy:label.automail_message" = "Automail message" "economy:label.automail_message" = "Automail message"
"economy:action.buy" = "Buy" "economy:action.buy" = "Buy"
"economy:label.already_purchased" = "Already purchased"

View file

@ -77,6 +77,18 @@
("oninput" "event.preventDefault(); update_on_sale_from_form(event.target.checked)")) ("oninput" "event.preventDefault(); update_on_sale_from_form(event.target.checked)"))
(span (span
(str (text "economy:label.on_sale")))) (str (text "economy:label.on_sale"))))
(label
("for" "single_use")
("class" "flex items_center gap_2")
(input
("type" "checkbox")
("id" "single_use")
("name" "single_use")
("class" "w_content")
("checked" "{{ product.single_use }}")
("oninput" "event.preventDefault(); update_single_use_from_form(event.target.checked)"))
(span
(str (text "economy:label.single_use"))))
(div (div
("class" "flex flex_col gap_1") ("class" "flex flex_col gap_1")
(label (label
@ -240,6 +252,27 @@
}); });
} }
async function update_single_use_from_form(single_use) {
await trigger(\"atto::debounce\", [\"products::update\"]);
fetch(\"/api/v1/products/{{ product.id }}/single_use\", {
method: \"POST\",
headers: {
\"Content-Type\": \"application/json\",
},
body: JSON.stringify({
single_use,
}),
})
.then((res) => res.json())
.then((res) => {
trigger(\"atto::toast\", [
res.ok ? \"success\" : \"error\",
res.message,
]);
});
}
async function update_price_from_form(e) { async function update_price_from_form(e) {
e.preventDefault(); e.preventDefault();
await trigger(\"atto::debounce\", [\"products::update\"]); await trigger(\"atto::debounce\", [\"products::update\"]);

View file

@ -28,12 +28,19 @@
(icon (text "badge-cent")) (icon (text "badge-cent"))
(text "{{ product.price }}")) (text "{{ product.price }}"))
(text "{% if user.id != product.owner -%}") (text "{% if user.id != product.owner -%}")
(text "{% if not already_purchased -%}")
(button (button
("onclick" "purchase()") ("onclick" "purchase()")
("disabled" "{{ product.stock == 0 }}") ("disabled" "{{ product.stock == 0 }}")
(icon (text "piggy-bank")) (icon (text "piggy-bank"))
(str (text "economy:action.buy"))) (str (text "economy:action.buy")))
(text "{% else %}") (text "{% else %}")
(span
("class" "green flex items_center gap_2")
(icon (text "circle-check"))
(str (text "economy:label.already_purchased")))
(text "{%- endif %}")
(text "{% else %}")
(a (a
("class" "button") ("class" "button")
("href" "/product/{{ product.id }}/edit") ("href" "/product/{{ product.id }}/edit")

View file

@ -304,7 +304,7 @@
globalThis.request_transfer = async () => { globalThis.request_transfer = async () => {
await trigger(\"atto::debounce\", [\"economy::transfer\"]); await trigger(\"atto::debounce\", [\"economy::transfer\"]);
const amount = Number.parseInt((await trigger(\"atto::prompt\", [\"Request amount:\"])) || \"\"); const amount = Number.parseInt((await trigger(\"atto::prompt\", [\"Request amount:\"])) || \"0\");
if (amount === 0) { if (amount === 0) {
return; return;

View file

@ -732,6 +732,10 @@ pub fn routes() -> Router {
"/products/{id}/on_sale", "/products/{id}/on_sale",
post(products::update_on_sale_request), post(products::update_on_sale_request),
) )
.route(
"/products/{id}/single_use",
post(products::update_single_use_request),
)
.route("/products/{id}/price", post(products::update_price_request)) .route("/products/{id}/price", post(products::update_price_request))
.route( .route(
"/products/{id}/method", "/products/{id}/method",
@ -1275,6 +1279,11 @@ pub struct UpdateProductOnSale {
pub on_sale: bool, pub on_sale: bool,
} }
#[derive(Deserialize)]
pub struct UpdateProductSingleUse {
pub single_use: bool,
}
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct UpdateProductPrice { pub struct UpdateProductPrice {
pub price: i32, pub price: i32,

View file

@ -3,7 +3,7 @@ use axum::{extract::Path, response::IntoResponse, Extension, Json};
use tetratto_core::model::{economy::Product, oauth, ApiReturn, Error}; use tetratto_core::model::{economy::Product, oauth, ApiReturn, Error};
use super::{ use super::{
CreateProduct, UpdateProductDescription, UpdateProductMethod, UpdateProductOnSale, CreateProduct, UpdateProductDescription, UpdateProductMethod, UpdateProductOnSale,
UpdateProductPrice, UpdateProductStock, UpdateProductTitle, UpdateProductPrice, UpdateProductSingleUse, UpdateProductStock, UpdateProductTitle,
}; };
pub async fn create_request( pub async fn create_request(
@ -137,6 +137,31 @@ pub async fn update_on_sale_request(
} }
} }
pub async fn update_single_use_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateProductSingleUse>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data, oauth::AppScope::UserManageProducts) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data
.update_product_single_use(id, &user, if req.single_use { 1 } else { 0 })
.await
{
Ok(_) => Json(ApiReturn {
ok: true,
message: "Product updated".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn update_price_request( pub async fn update_price_request(
jar: CookieJar, jar: CookieJar,
Extension(data): Extension<State>, Extension(data): Extension<State>,

View file

@ -4,7 +4,7 @@ use axum::{
Extension, Extension,
}; };
use crate::cookie::CookieJar; use crate::cookie::CookieJar;
use tetratto_core::model::Error; use tetratto_core::model::{economy::CoinTransferMethod, Error};
use crate::{assets::initial_context, get_lang, get_user_from_token, State}; use crate::{assets::initial_context, get_lang, get_user_from_token, State};
use super::{render_error, PaginatedQuery}; use super::{render_error, PaginatedQuery};
@ -138,11 +138,21 @@ pub async fn product_request(
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)), Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
}; };
let already_purchased = if product.single_use {
data.0
.get_transfer_by_sender_method(user.id, CoinTransferMethod::Purchase(product.id))
.await
.is_ok()
} else {
false
};
let lang = get_lang!(jar, data.0); let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0.0, lang, &Some(user)).await; let mut context = initial_context(&data.0.0.0, lang, &Some(user)).await;
context.insert("product", &product); context.insert("product", &product);
context.insert("owner", &owner); context.insert("owner", &owner);
context.insert("already_purchased", &already_purchased);
// return // return
Ok(Html( Ok(Html(

View file

@ -7,5 +7,6 @@ CREATE TABLE IF NOT EXISTS products (
method TEXT NOT NULL, method TEXT NOT NULL,
on_sale INT NOT NULL, on_sale INT NOT NULL,
price INT NOT NULL, price INT NOT NULL,
stock INT NOT NULL stock INT NOT NULL,
single_use INT NOT NULL
) )

View file

@ -45,3 +45,7 @@ ADD COLUMN IF NOT EXISTS data TEXT DEFAULT '"Null"';
-- users checkouts -- users checkouts
ALTER TABLE users ALTER TABLE users
ADD COLUMN IF NOT EXISTS checkouts TEXT DEFAULT '[]'; ADD COLUMN IF NOT EXISTS checkouts TEXT DEFAULT '[]';
-- products single_use
ALTER TABLE products
ADD COLUMN IF NOT EXISTS single_use INT DEFAULT 1;

View file

@ -21,6 +21,7 @@ impl DataManager {
on_sale: get!(x->6(i32)) as i8 == 1, on_sale: get!(x->6(i32)) as i8 == 1,
price: get!(x->7(i32)), price: get!(x->7(i32)),
stock: get!(x->8(i32)), stock: get!(x->8(i32)),
single_use: get!(x->9(i32)) as i8 == 1,
} }
} }
@ -103,7 +104,7 @@ impl DataManager {
let res = execute!( let res = execute!(
&conn, &conn,
"INSERT INTO products VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", "INSERT INTO products VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
params![ params![
&(data.id as i64), &(data.id as i64),
&(data.created as i64), &(data.created as i64),
@ -113,7 +114,8 @@ impl DataManager {
&serde_json::to_string(&data.method).unwrap(), &serde_json::to_string(&data.method).unwrap(),
&{ if data.on_sale { 1 } else { 0 } }, &{ if data.on_sale { 1 } else { 0 } },
&data.price, &data.price,
&(data.stock as i32) &(data.stock as i32),
&{ if data.single_use { 1 } else { 0 } },
] ]
); );
@ -131,6 +133,22 @@ impl DataManager {
customer: &mut User, customer: &mut User,
) -> Result<CoinTransfer> { ) -> Result<CoinTransfer> {
let product = self.get_product_by_id(product).await?; let product = self.get_product_by_id(product).await?;
// handle single_use product
if product.single_use {
if self
.get_transfer_by_sender_method(
customer.id,
CoinTransferMethod::Purchase(product.id),
)
.await
.is_ok()
{
return Err(Error::MiscError("You already own this product".to_string()));
}
}
// ...
let mut transfer = CoinTransfer::new( let mut transfer = CoinTransfer::new(
customer.id, customer.id,
product.owner, product.owner,
@ -231,6 +249,7 @@ If your product is a purchase of goods or services, please be sure to fulfill th
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_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_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_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_single_use(i32)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET single_use = $1 WHERE id = $2" --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!(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!(incr_product_stock() -> "UPDATE products SET stock = stock + 1 WHERE id = $1" --cache-key-tmpl="atto.product:{}" --incr);

View file

@ -5,7 +5,7 @@ use crate::model::{
auth::{Notification, User}, auth::{Notification, User},
}; };
use crate::{auto_method, DataManager}; use crate::{auto_method, DataManager};
use oiseau::{cache::Cache, execute, get, params, query_rows, PostgresRow}; use oiseau::{cache::Cache, execute, get, params, query_row, query_rows, PostgresRow};
impl DataManager { impl DataManager {
/// Get a [`CoinTransfer`] from an SQL row. /// Get a [`CoinTransfer`] from an SQL row.
@ -101,6 +101,35 @@ impl DataManager {
Ok(res.unwrap()) Ok(res.unwrap())
} }
/// Get a transfer by user and method.
///
/// # Arguments
/// * `id` - the ID of the user to fetch transfers for
/// * `method` - the transfer method
pub async fn get_transfer_by_sender_method(
&self,
id: usize,
method: CoinTransferMethod,
) -> Result<CoinTransfer> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_row!(
&conn,
"SELECT * FROM transfers WHERE sender = $1 AND method = $2 LIMIT 1",
params![&(id as i64), &serde_json::to_string(&method).unwrap()],
|x| { Ok(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. /// Create a new transfer in the database.
/// ///
/// # Arguments /// # Arguments

View file

@ -29,6 +29,8 @@ pub struct Product {
/// ///
/// A negative stock means the product has unlimited stock. /// A negative stock means the product has unlimited stock.
pub stock: i32, pub stock: i32,
/// If this product is limited to one purchase per person.
pub single_use: bool,
} }
impl Product { impl Product {
@ -44,6 +46,7 @@ impl Product {
on_sale: false, on_sale: false,
price: 0, price: 0,
stock: 0, stock: 0,
single_use: true,
} }
} }
} }