support aquiring server props and test dropping them
This commit is contained in:
parent
3e1afb82c8
commit
7852790a1e
9 changed files with 858 additions and 150 deletions
|
|
@ -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<InventoryItem>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
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<PublicProp>,
|
||||
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<PropAcquisitionInfo>,
|
||||
}
|
||||
|
||||
/// A prop dropped in a channel, available for pickup.
|
||||
|
|
|
|||
|
|
@ -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<Vec<PublicProp>, AppError> {
|
||||
let props = sqlx::query_as::<_, PublicProp>(
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Vec<PropAcquisitionInfo>, 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<Vec<PublicProp>, AppError> {
|
||||
let props = sqlx::query_as::<_, PublicProp>(
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Vec<PropAcquisitionInfo>, 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<InventoryItem, AppError> {
|
||||
// Use a CTE to atomically check conditions and insert
|
||||
let result: Option<InventoryItem> = 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<AppError, AppError> {
|
||||
#[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<PropStatus> = 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<InventoryItem, AppError> {
|
||||
// Use a CTE to atomically check conditions and insert
|
||||
let result: Option<InventoryItem> = 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<AppError, AppError> {
|
||||
#[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<PropStatus> = 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(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<String>,
|
||||
) -> Result<Json<InventoryResponse>, 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::<Uuid>().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<Uuid>,
|
||||
Path((uuid_str, item_id)): Path<(String, Uuid)>,
|
||||
) -> Result<Json<serde_json::Value>, 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::<Uuid>().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<PgPool>,
|
||||
) -> Result<Json<PublicPropsResponse>, AppError> {
|
||||
let props = inventory::list_public_server_props(&pool).await?;
|
||||
OptionalAuthUser(maybe_user): OptionalAuthUser,
|
||||
) -> Result<Json<PropAcquisitionListResponse>, 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<PgPool>,
|
||||
OptionalAuthUser(maybe_user): OptionalAuthUser,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<Json<PublicPropsResponse>, AppError> {
|
||||
) -> Result<Json<PropAcquisitionListResponse>, 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<AcquirePropRequest>,
|
||||
) -> Result<Json<AcquirePropResponse>, 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<PgPool>,
|
||||
AuthUser(user): AuthUser,
|
||||
Path(slug): Path<String>,
|
||||
Json(req): Json<AcquirePropRequest>,
|
||||
) -> Result<Json<AcquirePropResponse>, 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,13 +58,22 @@ pub fn api_router() -> Router<AppState> {
|
|||
"/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),
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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::<Uuid>::None);
|
||||
let (dropping, set_dropping) = signal(false);
|
||||
|
||||
// Server props state
|
||||
let (server_props, set_server_props) = signal(Vec::<PublicProp>::new());
|
||||
// Server props state (with acquisition info for authenticated users)
|
||||
let (server_props, set_server_props) = signal(Vec::<PropAcquisitionInfo>::new());
|
||||
let (server_loading, set_server_loading) = signal(false);
|
||||
let (server_error, set_server_error) = signal(Option::<String>::None);
|
||||
|
||||
// Realm props state
|
||||
let (realm_props, set_realm_props) = signal(Vec::<PublicProp>::new());
|
||||
// Realm props state (with acquisition info for authenticated users)
|
||||
let (realm_props, set_realm_props) = signal(Vec::<PropAcquisitionInfo>::new());
|
||||
let (realm_loading, set_realm_loading) = signal(false);
|
||||
let (realm_error, set_realm_error) = signal(Option::<String>::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::<chattyness_db::models::PublicPropsResponse>()
|
||||
.json::<chattyness_db::models::PropAcquisitionListResponse>()
|
||||
.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::<chattyness_db::models::PublicPropsResponse>()
|
||||
.json::<chattyness_db::models::PropAcquisitionListResponse>()
|
||||
.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
|
||||
<Show when=move || active_tab.get() == "server">
|
||||
<PublicPropsTab
|
||||
<AcquisitionPropsTab
|
||||
props=server_props
|
||||
set_props=set_server_props
|
||||
loading=server_loading
|
||||
error=server_error
|
||||
tab_name="Server"
|
||||
empty_message="No public server props available"
|
||||
is_guest=is_guest
|
||||
acquire_endpoint="/api/server/inventory/request"
|
||||
on_acquired=Callback::new(move |_| {
|
||||
// Trigger inventory refresh and reset loaded state
|
||||
set_my_inventory_loaded.set(false);
|
||||
set_inventory_refresh_trigger.update(|n| *n += 1);
|
||||
})
|
||||
/>
|
||||
</Show>
|
||||
|
||||
// Realm tab
|
||||
<Show when=move || active_tab.get() == "realm">
|
||||
<PublicPropsTab
|
||||
<AcquisitionPropsTab
|
||||
props=realm_props
|
||||
set_props=set_realm_props
|
||||
loading=realm_loading
|
||||
error=realm_error
|
||||
tab_name="Realm"
|
||||
empty_message="No public realm props available"
|
||||
is_guest=is_guest
|
||||
acquire_endpoint_is_realm=true
|
||||
realm_slug=realm_slug
|
||||
on_acquired=Callback::new(move |_| {
|
||||
// Trigger inventory refresh and reset loaded state
|
||||
set_my_inventory_loaded.set(false);
|
||||
set_inventory_refresh_trigger.update(|n| *n += 1);
|
||||
})
|
||||
/>
|
||||
</Show>
|
||||
</div>
|
||||
|
|
@ -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<Vec<PublicProp>>,
|
||||
fn AcquisitionPropsTab(
|
||||
#[prop(into)] props: Signal<Vec<PropAcquisitionInfo>>,
|
||||
set_props: WriteSignal<Vec<PropAcquisitionInfo>>,
|
||||
#[prop(into)] loading: Signal<bool>,
|
||||
#[prop(into)] error: Signal<Option<String>>,
|
||||
tab_name: &'static str,
|
||||
empty_message: &'static str,
|
||||
#[prop(into)] is_guest: Signal<bool>,
|
||||
/// 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<String>,
|
||||
#[prop(into)] on_acquired: Callback<()>,
|
||||
) -> impl IntoView {
|
||||
// Selected prop for showing details
|
||||
let (selected_prop, set_selected_prop) = signal(Option::<Uuid>::None);
|
||||
let (acquiring, set_acquiring) = signal(false);
|
||||
let (acquire_error, set_acquire_error) = signal(Option::<String>::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::<serde_json::Value>().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(
|
|||
</div>
|
||||
</Show>
|
||||
|
||||
// Acquire error state
|
||||
<Show when=move || acquire_error.get().is_some()>
|
||||
<div class="bg-red-900/20 border border-red-600 rounded p-4 mb-4">
|
||||
<p class="text-red-400">{move || acquire_error.get().unwrap_or_default()}</p>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
// Empty state
|
||||
<Show when=move || !loading.get() && error.get().is_none() && props.get().is_empty()>
|
||||
<div class="flex flex-col items-center justify-center py-12 text-center">
|
||||
|
|
@ -501,7 +621,7 @@ fn PublicPropsTab(
|
|||
<For
|
||||
each=move || props.get()
|
||||
key=|prop| prop.id
|
||||
children=move |prop: PublicProp| {
|
||||
children=move |prop: PropAcquisitionInfo| {
|
||||
let prop_id = prop.id;
|
||||
let prop_name = prop.name.clone();
|
||||
let is_selected = move || selected_prop.get() == Some(prop_id);
|
||||
|
|
@ -511,13 +631,21 @@ fn PublicPropsTab(
|
|||
format!("/static/{}", prop.asset_path)
|
||||
};
|
||||
|
||||
// Visual indicator for ownership status
|
||||
let user_owns = prop.user_owns;
|
||||
let is_claimed = prop.is_claimed;
|
||||
|
||||
view! {
|
||||
<button
|
||||
type="button"
|
||||
class=move || format!(
|
||||
"aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 {}",
|
||||
"aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 relative {}",
|
||||
if is_selected() {
|
||||
"border-blue-500 bg-blue-900/30"
|
||||
} else if user_owns {
|
||||
"border-green-500/50 bg-green-900/20"
|
||||
} else if is_claimed {
|
||||
"border-red-500/50 bg-red-900/20 opacity-50"
|
||||
} else {
|
||||
"border-gray-600 hover:border-gray-500 bg-gray-700/50"
|
||||
}
|
||||
|
|
@ -534,27 +662,63 @@ fn PublicPropsTab(
|
|||
alt=""
|
||||
class="w-full h-full object-contain"
|
||||
/>
|
||||
// Ownership badge
|
||||
<Show when=move || user_owns>
|
||||
<span class="absolute top-0 right-0 w-3 h-3 bg-green-500 rounded-full transform translate-x-1 -translate-y-1" title="Owned" />
|
||||
</Show>
|
||||
</button>
|
||||
}
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
// 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! {
|
||||
<div class="mt-4 pt-4 border-t border-gray-700">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 class="text-white font-medium">{prop.name.clone()}</h3>
|
||||
{prop.description.map(|desc| view! {
|
||||
<h3 class="text-white font-medium">{prop_name}</h3>
|
||||
{prop_description.map(|desc| view! {
|
||||
<p class="text-gray-400 text-sm">{desc}</p>
|
||||
})}
|
||||
</div>
|
||||
<p class="text-gray-500 text-sm italic">"View only"</p>
|
||||
<button
|
||||
type="button"
|
||||
class=format!("px-4 py-2 rounded-lg transition-colors {}", button_class)
|
||||
on:click=move |_| {
|
||||
if !button_disabled {
|
||||
do_acquire.run(prop_id);
|
||||
}
|
||||
}
|
||||
disabled=button_disabled
|
||||
title=button_title
|
||||
>
|
||||
{button_text}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
})
|
||||
|
|
@ -563,3 +727,4 @@ fn PublicPropsTab(
|
|||
</Show>
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue