Merge pull request #7 from RecentRunner/main
added shop functionality. Shop now pulls from db
This commit is contained in:
@@ -12,55 +12,78 @@ import {
|
|||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@/components/ui/card";
|
} from "@/components/ui/card";
|
||||||
import { HABIT_PET_DATA_UPDATED_EVENT } from "@/lib/app-events";
|
import { HABIT_PET_DATA_UPDATED_EVENT } from "@/lib/app-events";
|
||||||
import { getCoins } from "@/lib/avatar-progression-storage";
|
import {
|
||||||
|
getShopState,
|
||||||
|
purchaseShopItem,
|
||||||
|
type ShopItem,
|
||||||
|
} from "@/lib/shop-storage";
|
||||||
|
|
||||||
const shopItems = [
|
function formatItemType(type: string) {
|
||||||
{
|
return type.charAt(0).toUpperCase() + type.slice(1);
|
||||||
id: "hat",
|
}
|
||||||
name: "Pixel cap",
|
|
||||||
price: 50,
|
|
||||||
description: "A cozy cap for your habit pet.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "bed",
|
|
||||||
name: "Cloud bed",
|
|
||||||
price: 120,
|
|
||||||
description: "Boost recovery after tough days.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "snack",
|
|
||||||
name: "Berry snack",
|
|
||||||
price: 25,
|
|
||||||
description: "A small treat for good streaks.",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export function ShopContent() {
|
export function ShopContent() {
|
||||||
const [coins, setCoins] = useState<number | null>(null);
|
const [coins, setCoins] = useState<number | null>(null);
|
||||||
|
const [items, setItems] = useState<ShopItem[]>([]);
|
||||||
|
const [ownedItemIds, setOwnedItemIds] = useState<string[]>([]);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [purchaseError, setPurchaseError] = useState<string | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [pendingItemId, setPendingItemId] = useState<string | null>(null);
|
||||||
|
|
||||||
const refreshCoins = useCallback(async () => {
|
const refreshShop = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
setError(null);
|
setError(null);
|
||||||
setCoins(await getCoins());
|
const state = await getShopState();
|
||||||
|
setCoins(state.coins);
|
||||||
|
setItems(state.items);
|
||||||
|
setOwnedItemIds(state.ownedItemIds);
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
setError(
|
setError(
|
||||||
refreshError instanceof Error
|
refreshError instanceof Error
|
||||||
? refreshError.message
|
? refreshError.message
|
||||||
: "Could not load your balance.",
|
: "Could not load the shop.",
|
||||||
);
|
);
|
||||||
setCoins(0);
|
setCoins(0);
|
||||||
|
setItems([]);
|
||||||
|
setOwnedItemIds([]);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void refreshCoins();
|
void refreshShop();
|
||||||
|
|
||||||
window.addEventListener(HABIT_PET_DATA_UPDATED_EVENT, refreshCoins);
|
window.addEventListener(HABIT_PET_DATA_UPDATED_EVENT, refreshShop);
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener(HABIT_PET_DATA_UPDATED_EVENT, refreshCoins);
|
window.removeEventListener(HABIT_PET_DATA_UPDATED_EVENT, refreshShop);
|
||||||
};
|
};
|
||||||
}, [refreshCoins]);
|
}, [refreshShop]);
|
||||||
|
|
||||||
|
const handlePurchase = async (item: ShopItem) => {
|
||||||
|
if (pendingItemId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setPurchaseError(null);
|
||||||
|
setPendingItemId(item.id);
|
||||||
|
const remainingCoins = await purchaseShopItem(item.id);
|
||||||
|
setCoins(remainingCoins);
|
||||||
|
setOwnedItemIds((current) =>
|
||||||
|
current.includes(item.id) ? current : [...current, item.id],
|
||||||
|
);
|
||||||
|
} catch (purchaseFailure) {
|
||||||
|
setPurchaseError(
|
||||||
|
purchaseFailure instanceof Error
|
||||||
|
? purchaseFailure.message
|
||||||
|
: "Could not complete purchase.",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
setPendingItemId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -72,35 +95,63 @@ export function ShopContent() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error ? <p className="mb-4 text-sm text-red-500">{error}</p> : null}
|
{error ? <p className="mb-4 text-sm text-red-500">{error}</p> : null}
|
||||||
|
{purchaseError ? (
|
||||||
|
<p className="mb-4 text-sm text-red-500">{purchaseError}</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className="grid gap-4">
|
{isLoading ? (
|
||||||
{shopItems.map((item) => {
|
<p className="text-sm text-muted-foreground">Loading shop items...</p>
|
||||||
const canAfford = coins !== null && coins >= item.price;
|
) : items.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
No items in the shop yet. Add rows to the shop_items table in
|
||||||
|
Supabase.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-4">
|
||||||
|
{items.map((item) => {
|
||||||
|
const isOwned = ownedItemIds.includes(item.id);
|
||||||
|
const canAfford = coins !== null && coins >= item.price;
|
||||||
|
const isPending = pendingItemId === item.id;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card key={item.id}>
|
<Card key={item.id}>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className="text-base">{item.name}</CardTitle>
|
<CardTitle className="text-base">{item.name}</CardTitle>
|
||||||
<CardDescription>{item.description}</CardDescription>
|
<CardDescription>
|
||||||
|
{formatItemType(item.type)}
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Badge>{item.price} pts</Badge>
|
||||||
</div>
|
</div>
|
||||||
<Badge>{item.price} pts</Badge>
|
</CardHeader>
|
||||||
</div>
|
<CardContent>
|
||||||
</CardHeader>
|
<Button
|
||||||
<CardContent>
|
className="w-full"
|
||||||
<Button
|
variant={isOwned ? "secondary" : "outline"}
|
||||||
className="w-full"
|
disabled={
|
||||||
variant="outline"
|
isOwned ||
|
||||||
disabled={coins === null || !canAfford}
|
coins === null ||
|
||||||
>
|
isPending ||
|
||||||
{canAfford ? "Buy" : "Not enough points"}
|
(!isOwned && !canAfford)
|
||||||
</Button>
|
}
|
||||||
</CardContent>
|
onClick={() => void handlePurchase(item)}
|
||||||
</Card>
|
>
|
||||||
);
|
{isOwned
|
||||||
})}
|
? "Owned"
|
||||||
</div>
|
: isPending
|
||||||
|
? "Purchasing..."
|
||||||
|
: canAfford
|
||||||
|
? "Buy"
|
||||||
|
: "Not enough points"}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,3 +72,17 @@ export async function adjustCoins(delta: number): Promise<number> {
|
|||||||
|
|
||||||
return nextCoins;
|
return nextCoins;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function spendCoins(amount: number): Promise<number> {
|
||||||
|
if (amount <= 0) {
|
||||||
|
throw new Error("Purchase amount must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentCoins = await getCoins();
|
||||||
|
|
||||||
|
if (currentCoins < amount) {
|
||||||
|
throw new Error("Not enough points.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return adjustCoins(-amount);
|
||||||
|
}
|
||||||
|
|||||||
159
lib/shop-storage.ts
Normal file
159
lib/shop-storage.ts
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
import { notifyHabitPetDataUpdated } from "@/lib/app-events";
|
||||||
|
import { getCoins, spendCoins, adjustCoins } from "@/lib/avatar-progression-storage";
|
||||||
|
import { createClient } from "@/lib/supabase/client";
|
||||||
|
|
||||||
|
export type ShopItem = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
price: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ShopItemRow = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getPriceForType(type: string) {
|
||||||
|
switch (type.toLowerCase()) {
|
||||||
|
case "accessory":
|
||||||
|
return 30;
|
||||||
|
case "background":
|
||||||
|
return 40;
|
||||||
|
case "outfit":
|
||||||
|
return 50;
|
||||||
|
case "consumable":
|
||||||
|
case "snack":
|
||||||
|
return 25;
|
||||||
|
default:
|
||||||
|
return 50;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapShopItemRow(row: ShopItemRow): ShopItem {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
type: row.type,
|
||||||
|
price: getPriceForType(row.type),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAuthenticatedUserId() {
|
||||||
|
const supabase = createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
error,
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (error || !user) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getShopItems(): Promise<ShopItem[]> {
|
||||||
|
const supabase = createClient();
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("shop_items")
|
||||||
|
.select("id, name, type")
|
||||||
|
.order("type", { ascending: true })
|
||||||
|
.order("name", { ascending: true });
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(error.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ((data ?? []) as ShopItemRow[]).map(mapShopItemRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getOwnedItemIds(): Promise<string[]> {
|
||||||
|
const userId = await getAuthenticatedUserId();
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const supabase = createClient();
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("user_items")
|
||||||
|
.select("item_id")
|
||||||
|
.eq("user_id", userId);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(error.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (data ?? []).map((row) => row.item_id as string);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function purchaseShopItem(itemId: string): Promise<number> {
|
||||||
|
const userId = await getAuthenticatedUserId();
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
throw new Error("You must be signed in to purchase items.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const supabase = createClient();
|
||||||
|
const { data: itemRow, error: itemError } = await supabase
|
||||||
|
.from("shop_items")
|
||||||
|
.select("id, name, type")
|
||||||
|
.eq("id", itemId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (itemError) {
|
||||||
|
throw new Error(itemError.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!itemRow) {
|
||||||
|
throw new Error("Item not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = mapShopItemRow(itemRow as ShopItemRow);
|
||||||
|
|
||||||
|
const { data: existingPurchase, error: existingError } = await supabase
|
||||||
|
.from("user_items")
|
||||||
|
.select("item_id")
|
||||||
|
.eq("user_id", userId)
|
||||||
|
.eq("item_id", itemId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (existingError) {
|
||||||
|
throw new Error(existingError.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existingPurchase) {
|
||||||
|
throw new Error("You already own this item.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainingCoins = await spendCoins(item.price);
|
||||||
|
|
||||||
|
const { error: purchaseError } = await supabase.from("user_items").insert({
|
||||||
|
user_id: userId,
|
||||||
|
item_id: itemId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (purchaseError) {
|
||||||
|
await adjustCoins(item.price);
|
||||||
|
throw new Error(purchaseError.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyHabitPetDataUpdated();
|
||||||
|
return remainingCoins;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getShopState(): Promise<{
|
||||||
|
coins: number;
|
||||||
|
items: ShopItem[];
|
||||||
|
ownedItemIds: string[];
|
||||||
|
}> {
|
||||||
|
const [coins, items, ownedItemIds] = await Promise.all([
|
||||||
|
getCoins(),
|
||||||
|
getShopItems(),
|
||||||
|
getOwnedItemIds(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return { coins, items, ownedItemIds };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user