From 7852790a1e0e1a62187244b8eb4dae580b0b543dab7f0ff2ca7dd56a47179ed5 Mon Sep 17 00:00:00 2001 From: Evan Carroll Date: Tue, 20 Jan 2026 18:33:15 -0600 Subject: [PATCH] support aquiring server props and test dropping them --- crates/chattyness-db/src/models.rs | 34 +- crates/chattyness-db/src/queries/inventory.rs | 467 ++++++++++++++++-- .../chattyness-db/src/queries/loose_props.rs | 28 +- .../chattyness-user-ui/src/api/inventory.rs | 164 +++++- crates/chattyness-user-ui/src/api/routes.rs | 19 +- .../chattyness-user-ui/src/api/websocket.rs | 14 + .../src/components/inventory.rs | 215 +++++++- db/schema/types/001_enums.sql | 5 +- stock/avatar/upload-stockavatars.sh | 62 +-- 9 files changed, 858 insertions(+), 150 deletions(-) diff --git a/crates/chattyness-db/src/models.rs b/crates/chattyness-db/src/models.rs index c943e18..7655989 100644 --- a/crates/chattyness-db/src/models.rs +++ b/crates/chattyness-db/src/models.rs @@ -295,6 +295,7 @@ pub enum AvatarLayer { #[default] Clothes, Accessories, + Emote, } impl std::fmt::Display for AvatarLayer { @@ -303,6 +304,7 @@ impl std::fmt::Display for AvatarLayer { AvatarLayer::Skin => write!(f, "skin"), AvatarLayer::Clothes => write!(f, "clothes"), AvatarLayer::Accessories => write!(f, "accessories"), + AvatarLayer::Emote => write!(f, "emote"), } } } @@ -315,6 +317,7 @@ impl std::str::FromStr for AvatarLayer { "skin" => Ok(AvatarLayer::Skin), "clothes" => Ok(AvatarLayer::Clothes), "accessories" => Ok(AvatarLayer::Accessories), + "emote" => Ok(AvatarLayer::Emote), _ => Err(format!("Invalid avatar layer: {}", s)), } } @@ -685,21 +688,40 @@ pub struct InventoryResponse { pub items: Vec, } -/// A public prop from server or realm library. -/// Used for the public inventory tabs (Server/Realm). +/// Extended prop info for acquisition UI (works for both server and realm props). +/// Includes ownership and availability status for the current user. #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))] -pub struct PublicProp { +pub struct PropAcquisitionInfo { pub id: Uuid, pub name: String, pub asset_path: String, pub description: Option, + pub is_unique: bool, + /// User already has this prop in their inventory. + pub user_owns: bool, + /// For unique props: someone has already claimed it. + pub is_claimed: bool, + /// Prop is within its availability window (or has no window). + pub is_available: bool, } -/// Response for public props list. +/// Request to acquire a prop (server or realm). #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PublicPropsResponse { - pub props: Vec, +pub struct AcquirePropRequest { + pub prop_id: Uuid, +} + +/// Response after acquiring a prop. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AcquirePropResponse { + pub item: InventoryItem, +} + +/// Response for prop acquisition list with status. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PropAcquisitionListResponse { + pub props: Vec, } /// A prop dropped in a channel, available for pickup. diff --git a/crates/chattyness-db/src/queries/inventory.rs b/crates/chattyness-db/src/queries/inventory.rs index 6047292..4c9d854 100644 --- a/crates/chattyness-db/src/queries/inventory.rs +++ b/crates/chattyness-db/src/queries/inventory.rs @@ -3,7 +3,7 @@ use sqlx::PgExecutor; use uuid::Uuid; -use crate::models::{InventoryItem, PublicProp}; +use crate::models::{InventoryItem, PropAcquisitionInfo}; use chattyness_error::AppError; /// List all inventory items for a user. @@ -92,66 +92,455 @@ pub async fn drop_inventory_item<'e>( Ok(()) } -/// List all public server props. +/// List public server props with optional acquisition status. /// -/// Returns props that are: -/// - Active (`is_active = true`) -/// - Public (`is_public = true`) -/// - Currently available (within availability window if set) -pub async fn list_public_server_props<'e>( +/// Returns props that are active and public, with flags indicating: +/// - `user_owns`: Whether the user already has this prop (false if no user_id) +/// - `is_claimed`: Whether a unique prop has been claimed by anyone +/// - `is_available`: Whether the prop is within its availability window +/// +/// When `user_id` is None, returns default values for user-specific fields. +pub async fn list_server_props<'e>( executor: impl PgExecutor<'e>, -) -> Result, AppError> { - let props = sqlx::query_as::<_, PublicProp>( + user_id: Option, +) -> Result, AppError> { + let props = sqlx::query_as::<_, PropAcquisitionInfo>( r#" SELECT - id, - name, - asset_path, - description - FROM server.props - WHERE is_active = true - AND is_public = true - AND (available_from IS NULL OR available_from <= now()) - AND (available_until IS NULL OR available_until > now()) - ORDER BY name ASC + p.id, + p.name, + p.asset_path, + p.description, + p.is_unique, + CASE + WHEN $1::uuid IS NOT NULL THEN EXISTS( + SELECT 1 FROM auth.inventory i + WHERE i.user_id = $1 AND i.server_prop_id = p.id + ) + ELSE false + END AS user_owns, + CASE + WHEN p.is_unique THEN EXISTS( + SELECT 1 FROM auth.inventory i WHERE i.server_prop_id = p.id + ) + ELSE false + END AS is_claimed, + (p.available_from IS NULL OR p.available_from <= now()) + AND (p.available_until IS NULL OR p.available_until > now()) AS is_available + FROM server.props p + WHERE p.is_active = true + AND p.is_public = true + ORDER BY p.name ASC "#, ) + .bind(user_id) .fetch_all(executor) .await?; Ok(props) } -/// List all public realm props for a specific realm. +/// List public realm props with optional acquisition status. /// -/// Returns props that are: -/// - In the specified realm -/// - Active (`is_active = true`) -/// - Public (`is_public = true`) -/// - Currently available (within availability window if set) -pub async fn list_public_realm_props<'e>( +/// Returns props that are active and public in the specified realm, with flags indicating: +/// - `user_owns`: Whether the user already has this prop (false if no user_id) +/// - `is_claimed`: Whether a unique prop has been claimed by anyone +/// - `is_available`: Whether the prop is within its availability window +/// +/// When `user_id` is None, returns default values for user-specific fields. +pub async fn list_realm_props<'e>( executor: impl PgExecutor<'e>, realm_id: Uuid, -) -> Result, AppError> { - let props = sqlx::query_as::<_, PublicProp>( + user_id: Option, +) -> Result, AppError> { + let props = sqlx::query_as::<_, PropAcquisitionInfo>( r#" SELECT - id, - name, - asset_path, - description - FROM realm.props - WHERE realm_id = $1 - AND is_active = true - AND is_public = true - AND (available_from IS NULL OR available_from <= now()) - AND (available_until IS NULL OR available_until > now()) - ORDER BY name ASC + p.id, + p.name, + p.asset_path, + p.description, + p.is_unique, + CASE + WHEN $2::uuid IS NOT NULL THEN EXISTS( + SELECT 1 FROM auth.inventory i + WHERE i.user_id = $2 AND i.realm_prop_id = p.id + ) + ELSE false + END AS user_owns, + CASE + WHEN p.is_unique THEN EXISTS( + SELECT 1 FROM auth.inventory i WHERE i.realm_prop_id = p.id + ) + ELSE false + END AS is_claimed, + (p.available_from IS NULL OR p.available_from <= now()) + AND (p.available_until IS NULL OR p.available_until > now()) AS is_available + FROM realm.props p + WHERE p.realm_id = $1 + AND p.is_active = true + AND p.is_public = true + ORDER BY p.name ASC "#, ) .bind(realm_id) + .bind(user_id) .fetch_all(executor) .await?; Ok(props) } + +/// Acquire a server prop into user's inventory. +/// +/// Atomically validates and acquires the prop: +/// - Validates prop is active, public, within availability window +/// - For unique props: checks no one owns it yet +/// - For non-unique props: checks user doesn't already own it +/// - Inserts into `auth.inventory` with `origin = server_library` +/// +/// Returns the created inventory item or an appropriate error. +pub async fn acquire_server_prop<'e>( + executor: impl PgExecutor<'e>, + prop_id: Uuid, + user_id: Uuid, +) -> Result { + // Use a CTE to atomically check conditions and insert + let result: Option = sqlx::query_as( + r#" + WITH prop_check AS ( + SELECT + p.id, + p.name, + p.asset_path, + p.default_layer, + p.is_unique, + p.is_transferable, + p.is_portable, + p.is_droppable, + p.is_active, + p.is_public, + (p.available_from IS NULL OR p.available_from <= now()) AS available_from_ok, + (p.available_until IS NULL OR p.available_until > now()) AS available_until_ok + FROM server.props p + WHERE p.id = $1 + ), + ownership_check AS ( + SELECT + pc.*, + EXISTS( + SELECT 1 FROM auth.inventory i + WHERE i.user_id = $2 AND i.server_prop_id = $1 + ) AS user_owns, + CASE + WHEN pc.is_unique THEN EXISTS( + SELECT 1 FROM auth.inventory i WHERE i.server_prop_id = $1 + ) + ELSE false + END AS is_claimed + FROM prop_check pc + ), + inserted AS ( + INSERT INTO auth.inventory ( + user_id, + server_prop_id, + prop_name, + prop_asset_path, + layer, + origin, + is_transferable, + is_portable, + is_droppable + ) + SELECT + $2, + oc.id, + oc.name, + oc.asset_path, + oc.default_layer, + 'server_library'::server.prop_origin, + oc.is_transferable, + oc.is_portable, + oc.is_droppable + FROM ownership_check oc + WHERE oc.is_active = true + AND oc.is_public = true + AND oc.available_from_ok = true + AND oc.available_until_ok = true + AND oc.user_owns = false + AND oc.is_claimed = false + RETURNING + id, + prop_name, + prop_asset_path, + layer, + is_transferable, + is_portable, + is_droppable, + origin, + acquired_at + ) + SELECT * FROM inserted + "#, + ) + .bind(prop_id) + .bind(user_id) + .fetch_optional(executor) + .await?; + + match result { + Some(item) => Ok(item), + None => { + // Need to determine the specific error case + // We'll do a separate query to understand why it failed + Err(AppError::Conflict( + "Unable to acquire prop - it may not exist, not be available, or already owned" + .to_string(), + )) + } + } +} + +/// Get detailed acquisition error for a server prop. +/// +/// This is called when acquire_server_prop fails to determine the specific error. +pub async fn get_server_prop_acquisition_error<'e>( + executor: impl PgExecutor<'e>, + prop_id: Uuid, + user_id: Uuid, +) -> Result { + #[derive(sqlx::FromRow)] + #[allow(dead_code)] + struct PropStatus { + exists: bool, + is_active: bool, + is_public: bool, + is_available: bool, + is_unique: bool, + user_owns: bool, + is_claimed: bool, + } + + let status: Option = sqlx::query_as( + r#" + SELECT + true AS exists, + p.is_active, + p.is_public, + (p.available_from IS NULL OR p.available_from <= now()) + AND (p.available_until IS NULL OR p.available_until > now()) AS is_available, + p.is_unique, + EXISTS( + SELECT 1 FROM auth.inventory i + WHERE i.user_id = $2 AND i.server_prop_id = $1 + ) AS user_owns, + CASE + WHEN p.is_unique THEN EXISTS( + SELECT 1 FROM auth.inventory i WHERE i.server_prop_id = $1 + ) + ELSE false + END AS is_claimed + FROM server.props p + WHERE p.id = $1 + "#, + ) + .bind(prop_id) + .bind(user_id) + .fetch_optional(executor) + .await?; + + match status { + None => Ok(AppError::NotFound("Server prop not found".to_string())), + Some(s) if !s.is_active || !s.is_public => { + Ok(AppError::Forbidden("This prop is not available".to_string())) + } + Some(s) if !s.is_available => Ok(AppError::Forbidden( + "This prop is not currently available".to_string(), + )), + Some(s) if s.user_owns => Ok(AppError::Conflict("You already own this prop".to_string())), + Some(s) if s.is_claimed => Ok(AppError::Conflict( + "This unique prop has already been claimed by another user".to_string(), + )), + Some(_) => Ok(AppError::Internal( + "Unknown error acquiring prop".to_string(), + )), + } +} + +/// Acquire a realm prop into user's inventory. +/// +/// Atomically validates and acquires the prop: +/// - Validates prop belongs to realm, is active, public, within availability window +/// - For unique props: checks no one owns it yet +/// - For non-unique props: checks user doesn't already own it +/// - Inserts into `auth.inventory` with `origin = realm_library` +/// +/// Returns the created inventory item or an appropriate error. +pub async fn acquire_realm_prop<'e>( + executor: impl PgExecutor<'e>, + prop_id: Uuid, + realm_id: Uuid, + user_id: Uuid, +) -> Result { + // Use a CTE to atomically check conditions and insert + let result: Option = sqlx::query_as( + r#" + WITH prop_check AS ( + SELECT + p.id, + p.name, + p.asset_path, + p.default_layer, + p.is_unique, + p.is_transferable, + p.is_droppable, + p.is_active, + p.is_public, + (p.available_from IS NULL OR p.available_from <= now()) AS available_from_ok, + (p.available_until IS NULL OR p.available_until > now()) AS available_until_ok + FROM realm.props p + WHERE p.id = $1 AND p.realm_id = $2 + ), + ownership_check AS ( + SELECT + pc.*, + EXISTS( + SELECT 1 FROM auth.inventory i + WHERE i.user_id = $3 AND i.realm_prop_id = $1 + ) AS user_owns, + CASE + WHEN pc.is_unique THEN EXISTS( + SELECT 1 FROM auth.inventory i WHERE i.realm_prop_id = $1 + ) + ELSE false + END AS is_claimed + FROM prop_check pc + ), + inserted AS ( + INSERT INTO auth.inventory ( + user_id, + realm_prop_id, + prop_name, + prop_asset_path, + layer, + origin, + is_transferable, + is_portable, + is_droppable + ) + SELECT + $3, + oc.id, + oc.name, + oc.asset_path, + oc.default_layer, + 'realm_library'::server.prop_origin, + oc.is_transferable, + true, -- realm props are portable by default + oc.is_droppable + FROM ownership_check oc + WHERE oc.is_active = true + AND oc.is_public = true + AND oc.available_from_ok = true + AND oc.available_until_ok = true + AND oc.user_owns = false + AND oc.is_claimed = false + RETURNING + id, + prop_name, + prop_asset_path, + layer, + is_transferable, + is_portable, + is_droppable, + origin, + acquired_at + ) + SELECT * FROM inserted + "#, + ) + .bind(prop_id) + .bind(realm_id) + .bind(user_id) + .fetch_optional(executor) + .await?; + + match result { + Some(item) => Ok(item), + None => { + // Need to determine the specific error case + Err(AppError::Conflict( + "Unable to acquire prop - it may not exist, not be available, or already owned" + .to_string(), + )) + } + } +} + +/// Get detailed acquisition error for a realm prop. +/// +/// This is called when acquire_realm_prop fails to determine the specific error. +pub async fn get_realm_prop_acquisition_error<'e>( + executor: impl PgExecutor<'e>, + prop_id: Uuid, + realm_id: Uuid, + user_id: Uuid, +) -> Result { + #[derive(sqlx::FromRow)] + #[allow(dead_code)] + struct PropStatus { + exists: bool, + is_active: bool, + is_public: bool, + is_available: bool, + is_unique: bool, + user_owns: bool, + is_claimed: bool, + } + + let status: Option = sqlx::query_as( + r#" + SELECT + true AS exists, + p.is_active, + p.is_public, + (p.available_from IS NULL OR p.available_from <= now()) + AND (p.available_until IS NULL OR p.available_until > now()) AS is_available, + p.is_unique, + EXISTS( + SELECT 1 FROM auth.inventory i + WHERE i.user_id = $3 AND i.realm_prop_id = $1 + ) AS user_owns, + CASE + WHEN p.is_unique THEN EXISTS( + SELECT 1 FROM auth.inventory i WHERE i.realm_prop_id = $1 + ) + ELSE false + END AS is_claimed + FROM realm.props p + WHERE p.id = $1 AND p.realm_id = $2 + "#, + ) + .bind(prop_id) + .bind(realm_id) + .bind(user_id) + .fetch_optional(executor) + .await?; + + match status { + None => Ok(AppError::NotFound("Realm prop not found".to_string())), + Some(s) if !s.is_active || !s.is_public => { + Ok(AppError::Forbidden("This prop is not available".to_string())) + } + Some(s) if !s.is_available => Ok(AppError::Forbidden( + "This prop is not currently available".to_string(), + )), + Some(s) if s.user_owns => Ok(AppError::Conflict("You already own this prop".to_string())), + Some(s) if s.is_claimed => Ok(AppError::Conflict( + "This unique prop has already been claimed by another user".to_string(), + )), + Some(_) => Ok(AppError::Internal( + "Unknown error acquiring prop".to_string(), + )), + } +} diff --git a/crates/chattyness-db/src/queries/loose_props.rs b/crates/chattyness-db/src/queries/loose_props.rs index 8819119..415d907 100644 --- a/crates/chattyness-db/src/queries/loose_props.rs +++ b/crates/chattyness-db/src/queries/loose_props.rs @@ -8,6 +8,30 @@ use uuid::Uuid; use crate::models::{InventoryItem, LooseProp}; use chattyness_error::AppError; +/// Ensure an instance exists for a scene. +/// +/// In this system, scenes are used directly as instances (channel_id = scene_id). +/// This creates an instance record if one doesn't exist, using the scene_id as the instance_id. +/// This is needed for loose_props foreign key constraint. +pub async fn ensure_scene_instance<'e>( + executor: impl PgExecutor<'e>, + scene_id: Uuid, +) -> Result<(), AppError> { + sqlx::query( + r#" + INSERT INTO scene.instances (id, scene_id, instance_type) + SELECT $1, $1, 'public'::scene.instance_type + WHERE EXISTS (SELECT 1 FROM realm.scenes WHERE id = $1) + ON CONFLICT (id) DO NOTHING + "#, + ) + .bind(scene_id) + .execute(executor) + .await?; + + Ok(()) +} + /// List all loose props in a channel (excluding expired). pub async fn list_channel_loose_props<'e>( executor: impl PgExecutor<'e>, @@ -106,8 +130,8 @@ pub async fn drop_prop_to_canvas<'e>( instance_id as channel_id, server_prop_id, realm_prop_id, - ST_X(position) as position_x, - ST_Y(position) as position_y, + ST_X(position)::real as position_x, + ST_Y(position)::real as position_y, dropped_by, expires_at, created_at diff --git a/crates/chattyness-user-ui/src/api/inventory.rs b/crates/chattyness-user-ui/src/api/inventory.rs index 7fd643c..dcb7b15 100644 --- a/crates/chattyness-user-ui/src/api/inventory.rs +++ b/crates/chattyness-user-ui/src/api/inventory.rs @@ -8,66 +8,194 @@ use sqlx::PgPool; use uuid::Uuid; use chattyness_db::{ - models::{InventoryResponse, PublicPropsResponse}, + User, + models::{ + AcquirePropRequest, AcquirePropResponse, InventoryResponse, PropAcquisitionListResponse, + }, queries::{inventory, realms}, }; use chattyness_error::AppError; -use crate::auth::{AuthUser, RlsConn}; +use crate::auth::{AuthUser, OptionalAuthUser, RlsConn}; /// Get user's full inventory. /// -/// GET /api/inventory -pub async fn get_inventory( +/// GET /api/user/{uuid}/inventory +/// +/// Supports "me" as a special UUID value to get the current user's inventory. +pub async fn get_user_inventory( rls_conn: RlsConn, AuthUser(user): AuthUser, + Path(uuid_str): Path, ) -> Result, AppError> { - let mut conn = rls_conn.acquire().await; + // Resolve "me" to current user ID, otherwise parse UUID + let target_user_id = if uuid_str.eq_ignore_ascii_case("me") { + user.id + } else { + uuid_str.parse::().map_err(|_| { + AppError::Validation(format!("Invalid user UUID: {}", uuid_str)) + })? + }; - let items = inventory::list_user_inventory(&mut *conn, user.id).await?; + // For now, users can only view their own inventory + if target_user_id != user.id { + return Err(AppError::Forbidden( + "You can only view your own inventory".to_string(), + )); + } + + let mut conn = rls_conn.acquire().await; + let items = inventory::list_user_inventory(&mut *conn, target_user_id).await?; Ok(Json(InventoryResponse { items })) } /// Drop an item from inventory. /// -/// DELETE /api/inventory/{item_id} +/// DELETE /api/user/{uuid}/inventory/{item_id} pub async fn drop_item( rls_conn: RlsConn, AuthUser(user): AuthUser, - Path(item_id): Path, + Path((uuid_str, item_id)): Path<(String, Uuid)>, ) -> Result, AppError> { - let mut conn = rls_conn.acquire().await; + // Resolve "me" to current user ID + let target_user_id = if uuid_str.eq_ignore_ascii_case("me") { + user.id + } else { + uuid_str.parse::().map_err(|_| { + AppError::Validation(format!("Invalid user UUID: {}", uuid_str)) + })? + }; + // Users can only drop from their own inventory + if target_user_id != user.id { + return Err(AppError::Forbidden( + "You can only drop items from your own inventory".to_string(), + )); + } + + let mut conn = rls_conn.acquire().await; inventory::drop_inventory_item(&mut *conn, user.id, item_id).await?; Ok(Json(serde_json::json!({ "success": true }))) } -/// Get public server props. +/// Get server prop catalog. /// -/// GET /api/inventory/server +/// GET /api/server/inventory +/// +/// Returns all public server props. If the user is authenticated (non-guest), +/// includes acquisition status (user_owns, is_claimed, is_available). +/// For guests/unauthenticated, returns default status values. pub async fn get_server_props( State(pool): State, -) -> Result, AppError> { - let props = inventory::list_public_server_props(&pool).await?; + OptionalAuthUser(maybe_user): OptionalAuthUser, +) -> Result, AppError> { + // Get user_id if authenticated and not a guest + let user_id = maybe_user + .as_ref() + .filter(|u: &&User| !u.is_guest()) + .map(|u| u.id); - Ok(Json(PublicPropsResponse { props })) + let props = inventory::list_server_props(&pool, user_id).await?; + + Ok(Json(PropAcquisitionListResponse { props })) } -/// Get public realm props. +/// Get realm prop catalog. /// /// GET /api/realms/{slug}/inventory +/// +/// Returns all public realm props for the specified realm. If the user is authenticated +/// (non-guest), includes acquisition status. For guests/unauthenticated, returns default status. pub async fn get_realm_props( State(pool): State, + OptionalAuthUser(maybe_user): OptionalAuthUser, Path(slug): Path, -) -> Result, AppError> { +) -> Result, AppError> { // Get the realm by slug to get its ID let realm = realms::get_realm_by_slug(&pool, &slug) .await? .ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?; - let props = inventory::list_public_realm_props(&pool, realm.id).await?; + // Get user_id if authenticated and not a guest + let user_id = maybe_user + .as_ref() + .filter(|u: &&User| !u.is_guest()) + .map(|u| u.id); - Ok(Json(PublicPropsResponse { props })) + let props = inventory::list_realm_props(&pool, realm.id, user_id).await?; + + Ok(Json(PropAcquisitionListResponse { props })) +} + +/// Acquire a server prop into user's inventory. +/// +/// POST /api/server/inventory/request +pub async fn acquire_server_prop( + rls_conn: RlsConn, + AuthUser(user): AuthUser, + Json(req): Json, +) -> Result, AppError> { + // Guests cannot acquire props + if user.is_guest() { + return Err(AppError::Forbidden( + "Guests cannot acquire props".to_string(), + )); + } + + let mut conn = rls_conn.acquire().await; + + // Try to acquire the prop + match inventory::acquire_server_prop(&mut *conn, req.prop_id, user.id).await { + Ok(item) => Ok(Json(AcquirePropResponse { item })), + Err(_) => { + // Get the specific error reason + let error = + inventory::get_server_prop_acquisition_error(&mut *conn, req.prop_id, user.id) + .await?; + Err(error) + } + } +} + +/// Acquire a realm prop into user's inventory. +/// +/// POST /api/realms/{slug}/inventory/request +pub async fn acquire_realm_prop( + rls_conn: RlsConn, + State(pool): State, + AuthUser(user): AuthUser, + Path(slug): Path, + Json(req): Json, +) -> Result, AppError> { + // Guests cannot acquire props + if user.is_guest() { + return Err(AppError::Forbidden( + "Guests cannot acquire props".to_string(), + )); + } + + // Get the realm by slug to get its ID + let realm = realms::get_realm_by_slug(&pool, &slug) + .await? + .ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?; + + let mut conn = rls_conn.acquire().await; + + // Try to acquire the prop + match inventory::acquire_realm_prop(&mut *conn, req.prop_id, realm.id, user.id).await { + Ok(item) => Ok(Json(AcquirePropResponse { item })), + Err(_) => { + // Get the specific error reason + let error = inventory::get_realm_prop_acquisition_error( + &mut *conn, + req.prop_id, + realm.id, + user.id, + ) + .await?; + Err(error) + } + } } diff --git a/crates/chattyness-user-ui/src/api/routes.rs b/crates/chattyness-user-ui/src/api/routes.rs index 273df49..dd528e4 100644 --- a/crates/chattyness-user-ui/src/api/routes.rs +++ b/crates/chattyness-user-ui/src/api/routes.rs @@ -58,13 +58,22 @@ pub fn api_router() -> Router { "/realms/{slug}/avatar/slot", axum::routing::put(avatars::assign_slot).delete(avatars::clear_slot), ) - // Inventory routes (require authentication) - .route("/inventory", get(inventory::get_inventory)) + // User inventory routes + .route("/user/{uuid}/inventory", get(inventory::get_user_inventory)) .route( - "/inventory/{item_id}", + "/user/{uuid}/inventory/{item_id}", axum::routing::delete(inventory::drop_item), ) - // Public inventory routes (public server/realm props) - .route("/inventory/server", get(inventory::get_server_props)) + // Server prop catalog (enriched if authenticated) + .route("/server/inventory", get(inventory::get_server_props)) + .route( + "/server/inventory/request", + axum::routing::post(inventory::acquire_server_prop), + ) + // Realm prop catalog (enriched if authenticated) .route("/realms/{slug}/inventory", get(inventory::get_realm_props)) + .route( + "/realms/{slug}/inventory/request", + axum::routing::post(inventory::acquire_realm_prop), + ) } diff --git a/crates/chattyness-user-ui/src/api/websocket.rs b/crates/chattyness-user-ui/src/api/websocket.rs index 56f8e08..14766e1 100644 --- a/crates/chattyness-user-ui/src/api/websocket.rs +++ b/crates/chattyness-user-ui/src/api/websocket.rs @@ -607,6 +607,20 @@ async fn handle_socket( } } ClientMessage::DropProp { inventory_item_id } => { + // Ensure instance exists for this scene (required for loose_props FK) + // In this system, channel_id = scene_id + if let Err(e) = loose_props::ensure_scene_instance( + &mut *recv_conn, + channel_id, + ) + .await + { + tracing::error!( + "[WS] Failed to ensure scene instance: {:?}", + e + ); + } + // Get user's current position for random offset let member_info = channel_members::get_channel_member( &mut *recv_conn, diff --git a/crates/chattyness-user-ui/src/components/inventory.rs b/crates/chattyness-user-ui/src/components/inventory.rs index add9e96..67fa342 100644 --- a/crates/chattyness-user-ui/src/components/inventory.rs +++ b/crates/chattyness-user-ui/src/components/inventory.rs @@ -4,7 +4,7 @@ use leptos::prelude::*; use leptos::reactive::owner::LocalStorage; use uuid::Uuid; -use chattyness_db::models::{InventoryItem, PublicProp}; +use chattyness_db::models::{InventoryItem, PropAcquisitionInfo}; #[cfg(feature = "hydrate")] use chattyness_db::ws_messages::ClientMessage; @@ -46,13 +46,13 @@ pub fn InventoryPopup( let (selected_item, set_selected_item) = signal(Option::::None); let (dropping, set_dropping) = signal(false); - // Server props state - let (server_props, set_server_props) = signal(Vec::::new()); + // Server props state (with acquisition info for authenticated users) + let (server_props, set_server_props) = signal(Vec::::new()); let (server_loading, set_server_loading) = signal(false); let (server_error, set_server_error) = signal(Option::::None); - // Realm props state - let (realm_props, set_realm_props) = signal(Vec::::new()); + // Realm props state (with acquisition info for authenticated users) + let (realm_props, set_realm_props) = signal(Vec::::new()); let (realm_loading, set_realm_loading) = signal(false); let (realm_error, set_realm_error) = signal(Option::::None); @@ -61,6 +61,9 @@ pub fn InventoryPopup( let (server_loaded, set_server_loaded) = signal(false); let (realm_loaded, set_realm_loaded) = signal(false); + // Trigger to refresh my inventory after acquisition + let (inventory_refresh_trigger, set_inventory_refresh_trigger) = signal(0u32); + // Fetch my inventory when popup opens or tab is selected #[cfg(feature = "hydrate")] { @@ -68,6 +71,9 @@ pub fn InventoryPopup( use leptos::task::spawn_local; Effect::new(move |_| { + // Track refresh trigger to refetch after acquisition + let _refresh = inventory_refresh_trigger.get(); + if !open.get() { // Reset state when closing set_selected_item.set(None); @@ -86,7 +92,7 @@ pub fn InventoryPopup( set_error.set(None); spawn_local(async move { - let response = Request::get("/api/inventory").send().await; + let response = Request::get("/api/user/me/inventory").send().await; match response { Ok(resp) if resp.ok() => { if let Ok(data) = resp @@ -112,6 +118,7 @@ pub fn InventoryPopup( } // Fetch server props when server tab is selected + // Uses status endpoint if authenticated (non-guest), otherwise basic endpoint #[cfg(feature = "hydrate")] { use gloo_net::http::Request; @@ -126,17 +133,19 @@ pub fn InventoryPopup( set_server_error.set(None); spawn_local(async move { - let response = Request::get("/api/inventory/server").send().await; + // Single endpoint returns enriched data if authenticated + let response = Request::get("/api/server/inventory").send().await; match response { Ok(resp) if resp.ok() => { if let Ok(data) = resp - .json::() + .json::() .await { set_server_props.set(data.props); set_server_loaded.set(true); } else { - set_server_error.set(Some("Failed to parse server props".to_string())); + set_server_error + .set(Some("Failed to parse server props".to_string())); } } Ok(resp) => { @@ -175,19 +184,20 @@ pub fn InventoryPopup( set_realm_error.set(None); spawn_local(async move { - let response = Request::get(&format!("/api/realms/{}/inventory", slug)) - .send() - .await; + // Single endpoint returns enriched data if authenticated + let endpoint = format!("/api/realms/{}/inventory", slug); + let response = Request::get(&endpoint).send().await; match response { Ok(resp) if resp.ok() => { if let Ok(data) = resp - .json::() + .json::() .await { set_realm_props.set(data.props); set_realm_loaded.set(true); } else { - set_realm_error.set(Some("Failed to parse realm props".to_string())); + set_realm_error + .set(Some("Failed to parse realm props".to_string())); } } Ok(resp) => { @@ -272,23 +282,40 @@ pub fn InventoryPopup( // Server tab - // Realm tab - @@ -450,17 +477,103 @@ fn MyInventoryTab( } } -/// Public props tab content (read-only display). +/// Acquisition props tab content with acquire functionality. #[component] -fn PublicPropsTab( - #[prop(into)] props: Signal>, +fn AcquisitionPropsTab( + #[prop(into)] props: Signal>, + set_props: WriteSignal>, #[prop(into)] loading: Signal, #[prop(into)] error: Signal>, tab_name: &'static str, empty_message: &'static str, + #[prop(into)] is_guest: Signal, + /// Static endpoint for server props (e.g., "/api/server/inventory/request") + #[prop(optional)] + acquire_endpoint: Option<&'static str>, + /// Whether this is a realm props tab (uses dynamic endpoint with slug) + #[prop(optional, default = false)] + acquire_endpoint_is_realm: bool, + /// Realm slug for realm prop acquisition (required if acquire_endpoint_is_realm is true) + #[prop(optional, into)] + realm_slug: Signal, + #[prop(into)] on_acquired: Callback<()>, ) -> impl IntoView { // Selected prop for showing details let (selected_prop, set_selected_prop) = signal(Option::::None); + let (acquiring, set_acquiring) = signal(false); + let (acquire_error, set_acquire_error) = signal(Option::::None); + + // Handle acquire action + let acquire_endpoint_opt = acquire_endpoint.map(|s| s.to_string()); + let do_acquire = Callback::new(move |prop_id: Uuid| { + #[cfg(feature = "hydrate")] + { + set_acquiring.set(true); + set_acquire_error.set(None); + + let endpoint = if acquire_endpoint_is_realm { + let slug = realm_slug.get(); + if slug.is_empty() { + set_acquire_error.set(Some("No realm selected".to_string())); + set_acquiring.set(false); + return; + } + format!("/api/realms/{}/inventory/request", slug) + } else { + acquire_endpoint_opt.clone().unwrap_or_default() + }; + + let on_acquired = on_acquired.clone(); + + leptos::task::spawn_local(async move { + use gloo_net::http::Request; + + // Simple body with just prop_id - realm_id comes from URL for realm props + let body = serde_json::json!({ + "prop_id": prop_id + }); + + let response = Request::post(&endpoint) + .header("Content-Type", "application/json") + .body(body.to_string()) + .unwrap() + .send() + .await; + + match response { + Ok(resp) if resp.ok() => { + // Update local state to mark prop as owned + set_props.update(|props| { + if let Some(prop) = props.iter_mut().find(|p| p.id == prop_id) { + prop.user_owns = true; + } + }); + // Notify parent to refresh inventory + on_acquired.run(()); + } + Ok(resp) => { + // Try to parse error message from response + if let Ok(error_json) = resp.json::().await { + let error_msg = error_json + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("Unknown error"); + set_acquire_error.set(Some(error_msg.to_string())); + } else { + set_acquire_error.set(Some(format!( + "Failed to acquire prop: {}", + resp.status() + ))); + } + } + Err(e) => { + set_acquire_error.set(Some(format!("Network error: {}", e))); + } + } + set_acquiring.set(false); + }); + } + }); view! { // Loading state @@ -477,6 +590,13 @@ fn PublicPropsTab( + // Acquire error state + +
+

{move || acquire_error.get().unwrap_or_default()}

+
+
+ // Empty state
@@ -501,7 +621,7 @@ fn PublicPropsTab( + // Ownership badge + + + } } />
- // Selected prop details (read-only) + // Selected prop details with acquire button {move || { let prop_id = selected_prop.get()?; let prop = props.get().into_iter().find(|p| p.id == prop_id)?; + let guest = is_guest.get(); + let is_acquiring = acquiring.get(); + + // Determine button state + let (button_text, button_class, button_disabled, button_title) = if guest { + ("Sign in to Acquire", "bg-gray-600 text-gray-400 cursor-not-allowed", true, "Guests cannot acquire props") + } else if prop.user_owns { + ("Already Owned", "bg-green-700 text-white cursor-default", true, "You already own this prop") + } else if prop.is_claimed && prop.is_unique { + ("Claimed", "bg-red-700 text-white cursor-not-allowed", true, "This unique prop has been claimed by another user") + } else if !prop.is_available { + ("Unavailable", "bg-gray-600 text-gray-400 cursor-not-allowed", true, "This prop is not currently available") + } else if is_acquiring { + ("Acquiring...", "bg-blue-600 text-white opacity-50", true, "") + } else { + ("Acquire", "bg-blue-600 hover:bg-blue-700 text-white", false, "Add this prop to your inventory") + }; + + let prop_name = prop.name.clone(); + let prop_description = prop.description.clone(); Some(view! {
-

{prop.name.clone()}

- {prop.description.map(|desc| view! { +

{prop_name}

+ {prop_description.map(|desc| view! {

{desc}

})}
-

"View only"

+
}) @@ -563,3 +727,4 @@ fn PublicPropsTab(
} } + diff --git a/db/schema/types/001_enums.sql b/db/schema/types/001_enums.sql index fa7e9e6..6e5e659 100644 --- a/db/schema/types/001_enums.sql +++ b/db/schema/types/001_enums.sql @@ -71,9 +71,10 @@ COMMENT ON TYPE server.portability IS 'Whether prop can be used outside origin r CREATE TYPE server.avatar_layer AS ENUM ( 'skin', -- Background layer (behind user, body/face) 'clothes', -- Middle layer (with user, worn items) - 'accessories' -- Foreground layer (in front of user, held/attached items) + 'accessories', -- Foreground layer (in front of user, held/attached items) + 'emote' -- Facial expression layer (overlays face) ); -COMMENT ON TYPE server.avatar_layer IS 'Z-layer for avatar prop positioning: skin (behind), clothes (with), accessories (front)'; +COMMENT ON TYPE server.avatar_layer IS 'Z-layer for avatar prop positioning: skin (behind), clothes (with), accessories (front), emote (expressions)'; -- Emotion state for avatar overlays (moved from props schema) CREATE TYPE server.emotion_state AS ENUM ( diff --git a/stock/avatar/upload-stockavatars.sh b/stock/avatar/upload-stockavatars.sh index 2272cf0..1670fcb 100755 --- a/stock/avatar/upload-stockavatars.sh +++ b/stock/avatar/upload-stockavatars.sh @@ -58,24 +58,16 @@ capitalize() { } # Function to determine tags based on filename -# Tags complement default_layer/default_emotion - avoid redundant info +# Tags complement default_layer - avoid redundant info get_tags() { local filename="$1" case "$filename" in face.svg) - # Content layer prop - "skin" is already in default_layer + # Base face prop - "skin" is already in default_layer echo '["base", "face"]' ;; - smile.svg | happy.svg | neutral.svg | sad.svg | angry.svg | surprised.svg | thinking.svg | laughing.svg | crying.svg | love.svg | confused.svg) - # Emotion props - emotion is already in default_emotion - echo '["face"]' - ;; - sleeping.svg) - # Emotion prop for sleeping - echo '["face"]' - ;; - wink.svg) - # Emotion prop for wink + neutral.svg | smile.svg | sad.svg | angry.svg | surprised.svg | thinking.svg | laughing.svg | crying.svg | love.svg | confused.svg | sleeping.svg | wink.svg) + # Facial expression props - "emote" is already in default_layer echo '["face"]' ;; *) @@ -85,7 +77,7 @@ get_tags() { } # Function to get positioning fields based on filename -# Returns: "layer:" for content layer props, "emotion:" for emotion props, "none" for generic props +# Returns: "layer:" for content layer props, "none" for generic props get_positioning() { local filename="$1" case "$filename" in @@ -93,41 +85,9 @@ get_positioning() { # Base face is a content layer prop (skin layer) echo "layer:skin" ;; - neutral.svg) - echo "emotion:neutral" - ;; - smile.svg) - echo "emotion:happy" - ;; - sad.svg) - echo "emotion:sad" - ;; - angry.svg) - echo "emotion:angry" - ;; - surprised.svg) - echo "emotion:surprised" - ;; - thinking.svg) - echo "emotion:thinking" - ;; - laughing.svg) - echo "emotion:laughing" - ;; - crying.svg) - echo "emotion:crying" - ;; - love.svg) - echo "emotion:love" - ;; - confused.svg) - echo "emotion:confused" - ;; - sleeping.svg) - echo "emotion:sleeping" - ;; - wink.svg) - echo "emotion:wink" + neutral.svg | smile.svg | sad.svg | angry.svg | surprised.svg | thinking.svg | laughing.svg | crying.svg | love.svg | confused.svg | sleeping.svg | wink.svg) + # Facial expression props use the emote layer + echo "layer:emote" ;; *) echo "none" @@ -159,13 +119,9 @@ for file in "$STOCKAVATAR_DIR"/*.svg; do case "$positioning_type" in layer) - # Content layer prop + # Content layer prop (skin, clothes, accessories, emote) positioning_json="\"default_layer\": \"$positioning_value\", \"default_position\": 4" ;; - emotion) - # Emotion layer prop - positioning_json="\"default_emotion\": \"$positioning_value\", \"default_position\": 4" - ;; *) # Generic prop (no default positioning) positioning_json=""