Compare commits
16 Commits
8f064d4336
...
feature/bg
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf4c346e2d | ||
|
|
60bbeb9737 | ||
|
|
2acf50e46f | ||
|
|
1d77b6fb8e | ||
|
|
239a2c9591 | ||
|
|
64c48da05a | ||
|
|
2d7641cc20 | ||
|
|
24023570c7 | ||
|
|
359cc61115 | ||
|
|
71891a29be | ||
| 613db069b8 | |||
|
|
1183f0c7f6 | ||
| d1728546b1 | |||
| 9f5dab94af | |||
| 89fc4a782c | |||
|
|
abbe68888d |
@@ -1,11 +1,15 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__supabase__apply_migration",
|
||||
"mcp__supabase__list_tables",
|
||||
"mcp__supabase__execute_sql",
|
||||
"Bash(npm run build:*)",
|
||||
"mcp__supabase__get_advisors"
|
||||
]
|
||||
},
|
||||
"enableAllProjectMcpServers": true,
|
||||
"enabledMcpjsonServers": [
|
||||
"supabase"
|
||||
],
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__supabase__apply_migration"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ define(['./workbox-ca84f546'], (function (workbox) { 'use strict';
|
||||
"revision": "3ca0b8505b4bec776b69afdba2768812"
|
||||
}, {
|
||||
"url": "index.html",
|
||||
"revision": "0.ufhads5pjvs"
|
||||
"revision": "0.vigoqq958cg"
|
||||
}], {});
|
||||
workbox.cleanupOutdatedCaches();
|
||||
workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), {
|
||||
|
||||
10
src/App.tsx
10
src/App.tsx
@@ -11,6 +11,7 @@ import Community from './components/Community';
|
||||
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||
import { ToastProvider } from './contexts/ToastContext';
|
||||
import CardMosaicBackground from "./components/CardMosaicBackground.tsx";
|
||||
|
||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'search' | 'life-counter' | 'community';
|
||||
|
||||
@@ -40,7 +41,7 @@ function AppContent() {
|
||||
switch (currentPage) {
|
||||
case 'home':
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 animate-fade-in md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 animate-fade-in md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6 animate-slide-in-left">My Decks</h1>
|
||||
<DeckList
|
||||
@@ -78,9 +79,12 @@ function AppContent() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 flex flex-col">
|
||||
<div className="min-h-screen bg-gray-900 flex flex-col relative">
|
||||
{/* Animated card mosaic overlay */}
|
||||
<CardMosaicBackground />
|
||||
|
||||
<Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} />
|
||||
<main className="relative flex-1 overflow-y-auto">
|
||||
<main className="relative flex-1 overflow-y-auto z-20">
|
||||
<div className="relative min-h-full md:min-h-0 pt-0 md:pt-16 pb-20 md:pb-0">
|
||||
{renderPage()}
|
||||
</div>
|
||||
|
||||
155
src/components/CardMosaicBackground.tsx
Normal file
155
src/components/CardMosaicBackground.tsx
Normal file
@@ -0,0 +1,155 @@
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import { getRandomCards } from '../services/api';
|
||||
import { Card } from '../types';
|
||||
|
||||
export default function CardMosaicBackground() {
|
||||
const [cards, setCards] = useState<Card[]>([]);
|
||||
const [offset, setOffset] = useState({ x: 0, y: 0 });
|
||||
const animationRef = useRef<number>();
|
||||
|
||||
// Grid configuration - large grid to cover entire screen
|
||||
const cardsPerRow = 18;
|
||||
const cardsPerCol = 15;
|
||||
// Spacing adjusted for card transforms: w-64 = 256px
|
||||
// With rotateZ(15deg) and rotateX(60deg), cards need more space
|
||||
const cardWidth = 130; // Horizontal spacing to avoid overlap
|
||||
const cardHeight = 85; // Vertical spacing to avoid overlap
|
||||
const gridWidth = cardsPerRow * cardWidth;
|
||||
const gridHeight = cardsPerCol * cardHeight;
|
||||
|
||||
useEffect(() => {
|
||||
const fetchCards = async () => {
|
||||
try {
|
||||
// Fetch enough cards for one grid
|
||||
const totalCards = cardsPerRow * cardsPerCol;
|
||||
const randomCards = await getRandomCards(totalCards);
|
||||
setCards(randomCards);
|
||||
} catch (error) {
|
||||
console.error('Error fetching background cards:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchCards();
|
||||
}, []);
|
||||
|
||||
// Diagonal infinite scroll animation
|
||||
useEffect(() => {
|
||||
if (cards.length === 0) return;
|
||||
|
||||
const speed = 0.5; // Pixels per frame (diagonal speed)
|
||||
let lastTime = Date.now();
|
||||
|
||||
const animate = () => {
|
||||
const now = Date.now();
|
||||
const delta = now - lastTime;
|
||||
lastTime = now;
|
||||
|
||||
setOffset((prev) => {
|
||||
// Move diagonally: right and up
|
||||
let newX = prev.x + (speed * delta) / 16;
|
||||
let newY = prev.y - (speed * delta) / 16;
|
||||
|
||||
// Loop seamlessly when we've moved one full grid
|
||||
if (newX >= gridWidth) newX = newX % gridWidth;
|
||||
if (newY <= -gridHeight) newY = newY % gridHeight;
|
||||
|
||||
return { x: newX, y: newY };
|
||||
});
|
||||
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
|
||||
return () => {
|
||||
if (animationRef.current) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
}
|
||||
};
|
||||
}, [cards.length, gridWidth, gridHeight]);
|
||||
|
||||
if (cards.length === 0) return null;
|
||||
|
||||
// Render the card grid (will be duplicated 4 times for infinite effect)
|
||||
const renderGrid = (offsetX: number, offsetY: number, key: string) => (
|
||||
<div
|
||||
key={key}
|
||||
className="absolute"
|
||||
style={{
|
||||
left: `${offsetX}px`,
|
||||
top: `${offsetY}px`,
|
||||
width: `${gridWidth}px`,
|
||||
height: `${gridHeight}px`,
|
||||
perspective: '2000px', // Apply perspective to parent for uniform card sizes
|
||||
transformStyle: 'preserve-3d',
|
||||
}}
|
||||
>
|
||||
{cards.map((card, index) => {
|
||||
const col = index % cardsPerRow;
|
||||
const row = Math.floor(index / cardsPerRow);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${key}-${card.id}-${index}`}
|
||||
className="absolute"
|
||||
style={{
|
||||
left: `${col * cardWidth}px`,
|
||||
top: `${row * cardHeight}px`,
|
||||
transform: `
|
||||
perspective(1000px)
|
||||
rotateX(60deg)
|
||||
rotateY(5deg)
|
||||
rotateZ(15deg)
|
||||
`,
|
||||
opacity: 1.0, // Full opacity - gradient overlay handles the fade
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={card.image_uris?.normal || card.image_uris?.large}
|
||||
alt=""
|
||||
className="w-64 h-auto rounded-lg shadow-2xl"
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 overflow-hidden pointer-events-none z-10">
|
||||
{/* Scrolling grid container */}
|
||||
<div
|
||||
className="absolute"
|
||||
style={{
|
||||
transform: `translate(${offset.x}px, ${offset.y}px)`,
|
||||
willChange: 'transform',
|
||||
}}
|
||||
>
|
||||
{/* Duplicate grids in 2x2 pattern for seamless infinite scroll */}
|
||||
{/* Position grids to cover entire viewport and beyond */}
|
||||
{renderGrid(-gridWidth, window.innerHeight - gridHeight / 2, 'grid-tl')}
|
||||
{renderGrid(0, window.innerHeight - gridHeight / 2, 'grid-tr')}
|
||||
{renderGrid(-gridWidth, window.innerHeight - gridHeight / 2 + gridHeight, 'grid-bl')}
|
||||
{renderGrid(0, window.innerHeight - gridHeight / 2 + gridHeight, 'grid-br')}
|
||||
</div>
|
||||
|
||||
{/* Fixed gradient overlay - cards pass UNDER and fade naturally */}
|
||||
<div
|
||||
className="absolute inset-0 pointer-events-none z-10"
|
||||
style={{
|
||||
background: `
|
||||
linear-gradient(to top,
|
||||
transparent 0%,
|
||||
transparent 25%,
|
||||
rgba(3, 7, 18, 0.3) 40%,
|
||||
rgba(3, 7, 18, 0.6) 55%,
|
||||
rgba(3, 7, 18, 0.85) 70%,
|
||||
rgb(3, 7, 18) 85%
|
||||
)
|
||||
`
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -201,7 +201,7 @@ const CardSearch = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Card Search</h1>
|
||||
<form onSubmit={handleSearch} className="mb-8 space-y-4">
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { Search, Loader2, Trash2, CheckCircle, XCircle, RefreshCw, Plus, Minus, X } from 'lucide-react';
|
||||
import { Card } from '../types';
|
||||
import { getUserCollection, getCardsByIds, addCardToCollection } from '../services/api';
|
||||
import { getUserCollectionPaginated, getCardsByIds, addCardToCollection, getCollectionTotalValue } from '../services/api';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import ConfirmModal from './ConfirmModal';
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
export default function Collection() {
|
||||
const { user } = useAuth();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [collection, setCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
||||
const [filteredCollection, setFilteredCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
||||
const [isLoadingCollection, setIsLoadingCollection] = useState(true);
|
||||
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
const [totalCollectionValue, setTotalCollectionValue] = useState<number>(0);
|
||||
const [isLoadingTotalValue, setIsLoadingTotalValue] = useState(true);
|
||||
const [hoveredCard, setHoveredCard] = useState<Card | null>(null);
|
||||
const [selectedCard, setSelectedCard] = useState<{ card: Card; quantity: number } | null>(null);
|
||||
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||
@@ -22,6 +30,7 @@ export default function Collection() {
|
||||
cardId: string;
|
||||
cardName: string;
|
||||
}>({ isOpen: false, cardId: '', cardName: '' });
|
||||
const observerTarget = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Helper function to check if a card has an actual back face (not adventure/split/etc)
|
||||
const isDoubleFaced = (card: Card) => {
|
||||
@@ -62,6 +71,58 @@ export default function Collection() {
|
||||
});
|
||||
};
|
||||
|
||||
// Calculate total collection value (lightweight query from database)
|
||||
useEffect(() => {
|
||||
const calculateTotalValue = async () => {
|
||||
if (!user) {
|
||||
setIsLoadingTotalValue(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoadingTotalValue(true);
|
||||
// Get total value directly from database (no need to fetch all cards!)
|
||||
const totalValue = await getCollectionTotalValue(user.id);
|
||||
setTotalCollectionValue(totalValue);
|
||||
} catch (error) {
|
||||
console.error('Error calculating total collection value:', error);
|
||||
setTotalCollectionValue(0);
|
||||
} finally {
|
||||
setIsLoadingTotalValue(false);
|
||||
}
|
||||
};
|
||||
|
||||
calculateTotalValue();
|
||||
}, [user]);
|
||||
|
||||
// Subscribe to realtime updates for collection total value
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
const profileChannel = supabase
|
||||
.channel('profile-total-value-changes')
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'UPDATE',
|
||||
schema: 'public',
|
||||
table: 'profiles',
|
||||
filter: `id=eq.${user.id}`,
|
||||
},
|
||||
(payload: any) => {
|
||||
if (payload.new?.collection_total_value !== undefined) {
|
||||
console.log('Collection total value updated:', payload.new.collection_total_value);
|
||||
setTotalCollectionValue(payload.new.collection_total_value);
|
||||
}
|
||||
}
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return () => {
|
||||
supabase.removeChannel(profileChannel);
|
||||
};
|
||||
}, [user]);
|
||||
|
||||
// Load user's collection from Supabase on mount
|
||||
useEffect(() => {
|
||||
const loadCollection = async () => {
|
||||
@@ -72,26 +133,33 @@ export default function Collection() {
|
||||
|
||||
try {
|
||||
setIsLoadingCollection(true);
|
||||
// Get collection from Supabase (returns Map<card_id, quantity>)
|
||||
const collectionMap = await getUserCollection(user.id);
|
||||
setOffset(0);
|
||||
setCollection([]);
|
||||
|
||||
if (collectionMap.size === 0) {
|
||||
// Get paginated collection from Supabase
|
||||
const result = await getUserCollectionPaginated(user.id, PAGE_SIZE, 0);
|
||||
setTotalCount(result.totalCount);
|
||||
setHasMore(result.hasMore);
|
||||
|
||||
if (result.items.size === 0) {
|
||||
setCollection([]);
|
||||
setFilteredCollection([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the actual card data from Scryfall for all cards in collection
|
||||
const cardIds = Array.from(collectionMap.keys());
|
||||
// Get the actual card data from Scryfall for all cards in this page
|
||||
const cardIds = Array.from(result.items.keys());
|
||||
const cards = await getCardsByIds(cardIds);
|
||||
|
||||
// Combine card data with quantities
|
||||
const collectionWithCards = cards.map(card => ({
|
||||
card,
|
||||
quantity: collectionMap.get(card.id) || 0,
|
||||
quantity: result.items.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
setCollection(collectionWithCards);
|
||||
setFilteredCollection(collectionWithCards);
|
||||
setOffset(PAGE_SIZE);
|
||||
} catch (error) {
|
||||
console.error('Error loading collection:', error);
|
||||
setSnackbar({ message: 'Failed to load collection', type: 'error' });
|
||||
@@ -103,6 +171,70 @@ export default function Collection() {
|
||||
loadCollection();
|
||||
}, [user]);
|
||||
|
||||
// Load more cards for infinite scroll
|
||||
const loadMoreCards = useCallback(async () => {
|
||||
if (!user || isLoadingMore || !hasMore) return;
|
||||
|
||||
try {
|
||||
setIsLoadingMore(true);
|
||||
|
||||
// Get next page of collection
|
||||
const result = await getUserCollectionPaginated(user.id, PAGE_SIZE, offset);
|
||||
setHasMore(result.hasMore);
|
||||
|
||||
if (result.items.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get card data from Scryfall
|
||||
const cardIds = Array.from(result.items.keys());
|
||||
const cards = await getCardsByIds(cardIds);
|
||||
|
||||
// Combine card data with quantities
|
||||
const newCards = cards.map(card => ({
|
||||
card,
|
||||
quantity: result.items.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
// Deduplicate: only add cards that aren't already in the collection
|
||||
setCollection(prev => {
|
||||
const existingIds = new Set(prev.map(item => item.card.id));
|
||||
const uniqueNewCards = newCards.filter(item => !existingIds.has(item.card.id));
|
||||
return [...prev, ...uniqueNewCards];
|
||||
});
|
||||
|
||||
setOffset(prev => prev + PAGE_SIZE);
|
||||
} catch (error) {
|
||||
console.error('Error loading more cards:', error);
|
||||
setSnackbar({ message: 'Failed to load more cards', type: 'error' });
|
||||
} finally {
|
||||
setIsLoadingMore(false);
|
||||
}
|
||||
}, [user, offset, hasMore, isLoadingMore]);
|
||||
|
||||
// Intersection Observer for infinite scroll
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0].isIntersecting && hasMore && !isLoadingMore) {
|
||||
loadMoreCards();
|
||||
}
|
||||
},
|
||||
{ threshold: 0.1 }
|
||||
);
|
||||
|
||||
const currentTarget = observerTarget.current;
|
||||
if (currentTarget) {
|
||||
observer.observe(currentTarget);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (currentTarget) {
|
||||
observer.unobserve(currentTarget);
|
||||
}
|
||||
};
|
||||
}, [hasMore, isLoadingMore, loadMoreCards]);
|
||||
|
||||
// Filter collection based on search query
|
||||
useEffect(() => {
|
||||
if (!searchQuery.trim()) {
|
||||
@@ -189,7 +321,7 @@ export default function Collection() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">My Collection</h1>
|
||||
|
||||
@@ -209,9 +341,31 @@ export default function Collection() {
|
||||
|
||||
{/* Collection */}
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold mb-4">
|
||||
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
|
||||
</h2>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
|
||||
</h2>
|
||||
{/* Collection Value Summary */}
|
||||
<div className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2">
|
||||
<div className="text-xs text-gray-400 mb-0.5">
|
||||
{searchQuery ? 'Filtered Value' : 'Total Collection Value'}
|
||||
</div>
|
||||
<div className="text-lg font-bold text-green-400">
|
||||
{isLoadingTotalValue ? (
|
||||
<Loader2 className="animate-spin" size={20} />
|
||||
) : searchQuery ? (
|
||||
// For search results, calculate from filtered collection
|
||||
`$${filteredCollection.reduce((total, { card, quantity }) => {
|
||||
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
|
||||
return total + (price * quantity);
|
||||
}, 0).toFixed(2)}`
|
||||
) : (
|
||||
// For full collection, use pre-calculated total
|
||||
`$${totalCollectionValue.toFixed(2)}`
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoadingCollection ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
@@ -255,6 +409,12 @@ export default function Collection() {
|
||||
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs sm:text-sm font-bold px-2 py-1 rounded-full shadow-lg">
|
||||
x{quantity}
|
||||
</div>
|
||||
{/* Price badge */}
|
||||
{card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-[10px] sm:text-xs font-bold px-1.5 py-0.5 rounded shadow-lg">
|
||||
${card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
{/* Flip button for double-faced cards */}
|
||||
{isMultiFaced && (
|
||||
<button
|
||||
@@ -279,6 +439,25 @@ export default function Collection() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Infinite scroll loading indicator */}
|
||||
{!searchQuery && isLoadingMore && (
|
||||
<div className="flex justify-center py-8">
|
||||
<Loader2 className="animate-spin text-blue-500" size={32} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Observer target for infinite scroll */}
|
||||
{!searchQuery && hasMore && !isLoadingMore && (
|
||||
<div ref={observerTarget} className="h-20" />
|
||||
)}
|
||||
|
||||
{/* End of collection indicator */}
|
||||
{!searchQuery && !hasMore && collection.length > 0 && (
|
||||
<div className="text-center py-8 text-gray-500 text-sm">
|
||||
End of collection • {totalCount} total cards
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -77,7 +77,7 @@ const DeckList = ({ onDeckEdit, onCreateDeck }: DeckListProps) => {
|
||||
{/* Create New Deck Card */}
|
||||
<button
|
||||
onClick={onCreateDeck}
|
||||
className="bg-gray-800 rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
||||
className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
||||
>
|
||||
<PlusCircle size={48} className="text-gray-600 group-hover:text-blue-500 transition-colors" />
|
||||
<div className="text-center">
|
||||
|
||||
@@ -3,7 +3,7 @@ import { X, ArrowLeftRight, ArrowRight, ArrowLeft, Minus, Send, Gift, Loader2, S
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { createTrade } from '../services/tradesService';
|
||||
import { createTrade, updateTrade } from '../services/tradesService';
|
||||
import { Card } from '../types';
|
||||
|
||||
interface CollectionItem {
|
||||
@@ -182,6 +182,11 @@ interface TradeCreatorProps {
|
||||
receiverCollection: CollectionItem[];
|
||||
onClose: () => void;
|
||||
onTradeCreated: () => void;
|
||||
editMode?: boolean;
|
||||
existingTradeId?: string;
|
||||
initialSenderCards?: Card[];
|
||||
initialReceiverCards?: Card[];
|
||||
initialMessage?: string;
|
||||
}
|
||||
|
||||
type MobileStep = 'want' | 'give' | 'review';
|
||||
@@ -192,13 +197,18 @@ export default function TradeCreator({
|
||||
receiverCollection,
|
||||
onClose,
|
||||
onTradeCreated,
|
||||
editMode = false,
|
||||
existingTradeId,
|
||||
initialSenderCards = [],
|
||||
initialReceiverCards = [],
|
||||
initialMessage = '',
|
||||
}: TradeCreatorProps) {
|
||||
const { user } = useAuth();
|
||||
const toast = useToast();
|
||||
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [message, setMessage] = useState(initialMessage);
|
||||
|
||||
const [isGiftMode, setIsGiftMode] = useState(false);
|
||||
const [mobileStep, setMobileStep] = useState<MobileStep>('want');
|
||||
@@ -222,6 +232,57 @@ export default function TradeCreator({
|
||||
}
|
||||
}, [isGiftMode]);
|
||||
|
||||
// Pre-populate cards in edit mode
|
||||
useEffect(() => {
|
||||
if (!editMode || !myCollection.length || !receiverCollection.length) return;
|
||||
if (initialSenderCards.length === 0 && initialReceiverCards.length === 0) return;
|
||||
|
||||
console.log('Pre-populating cards', {
|
||||
initialSenderCards: initialSenderCards.length,
|
||||
initialReceiverCards: initialReceiverCards.length,
|
||||
myCollection: myCollection.length,
|
||||
receiverCollection: receiverCollection.length
|
||||
});
|
||||
|
||||
// Pre-populate sender cards with their quantities
|
||||
const senderMap = new Map<string, SelectedCard>();
|
||||
initialSenderCards.forEach(card => {
|
||||
const collectionItem = myCollection.find(c => c.card.id === card.id);
|
||||
if (collectionItem) {
|
||||
// Find the quantity from trade items if card has quantity property
|
||||
const quantity = (card as any).quantity || 1;
|
||||
console.log('Adding sender card:', card.name, 'qty:', quantity);
|
||||
senderMap.set(card.id, {
|
||||
card: card,
|
||||
quantity: quantity,
|
||||
maxQuantity: collectionItem.quantity,
|
||||
});
|
||||
} else {
|
||||
console.log('Card not found in my collection:', card.name, card.id);
|
||||
}
|
||||
});
|
||||
setMyOfferedCards(senderMap);
|
||||
|
||||
// Pre-populate receiver cards with their quantities
|
||||
const receiverMap = new Map<string, SelectedCard>();
|
||||
initialReceiverCards.forEach(card => {
|
||||
const collectionItem = receiverCollection.find(c => c.card.id === card.id);
|
||||
if (collectionItem) {
|
||||
// Find the quantity from trade items if card has quantity property
|
||||
const quantity = (card as any).quantity || 1;
|
||||
console.log('Adding receiver card:', card.name, 'qty:', quantity);
|
||||
receiverMap.set(card.id, {
|
||||
card: card,
|
||||
quantity: quantity,
|
||||
maxQuantity: collectionItem.quantity,
|
||||
});
|
||||
} else {
|
||||
console.log('Card not found in their collection:', card.name, card.id);
|
||||
}
|
||||
});
|
||||
setWantedCards(receiverMap);
|
||||
}, [editMode, myCollection, receiverCollection, initialSenderCards, initialReceiverCards]);
|
||||
|
||||
const loadMyCollection = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
@@ -314,28 +375,42 @@ export default function TradeCreator({
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const senderCards = Array.from(myOfferedCards.values()).map((item) => ({
|
||||
const myCards = Array.from(myOfferedCards.values()).map((item) => ({
|
||||
cardId: item.card.id,
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
|
||||
const receiverCards = Array.from(wantedCards.values()).map((item) => ({
|
||||
const theirCards = Array.from(wantedCards.values()).map((item) => ({
|
||||
cardId: item.card.id,
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
|
||||
await createTrade({
|
||||
senderId: user.id,
|
||||
receiverId,
|
||||
message: message || undefined,
|
||||
senderCards,
|
||||
receiverCards,
|
||||
});
|
||||
if (editMode && existingTradeId) {
|
||||
// Update existing trade
|
||||
await updateTrade({
|
||||
tradeId: existingTradeId,
|
||||
editorId: user.id,
|
||||
message: message || undefined,
|
||||
myCards,
|
||||
theirCards,
|
||||
});
|
||||
toast.success('Trade updated!');
|
||||
} else {
|
||||
// Create new trade
|
||||
await createTrade({
|
||||
user1Id: user.id,
|
||||
user2Id: receiverId,
|
||||
message: message || undefined,
|
||||
user1Cards: myCards,
|
||||
user2Cards: theirCards,
|
||||
});
|
||||
toast.success('Trade offer sent!');
|
||||
}
|
||||
|
||||
onTradeCreated();
|
||||
} catch (error) {
|
||||
console.error('Error creating trade:', error);
|
||||
toast.error('Failed to create trade');
|
||||
console.error('Error with trade:', error);
|
||||
toast.error(editMode ? 'Failed to update trade' : 'Failed to create trade');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -487,12 +562,6 @@ export default function TradeCreator({
|
||||
placeholder="Add a message..."
|
||||
className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
{message && (
|
||||
<div className="mt-2 p-2 bg-gray-900/50 rounded border border-gray-700">
|
||||
<p className="text-xs text-gray-400 mb-1">Preview:</p>
|
||||
<p className="text-sm text-gray-200">{message}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -559,7 +628,7 @@ export default function TradeCreator({
|
||||
<div className="flex items-center justify-between p-4 border-b border-gray-700">
|
||||
<div className="flex items-center gap-3">
|
||||
<ArrowLeftRight size={24} className="text-blue-400" />
|
||||
<h2 className="text-xl font-bold">Trade with {receiverUsername}</h2>
|
||||
<h2 className="text-xl font-bold">{editMode ? 'Edit Trade' : `Trade with ${receiverUsername}`}</h2>
|
||||
<label className="flex items-center gap-2 ml-4 cursor-pointer">
|
||||
<div
|
||||
className={`relative w-10 h-5 rounded-full transition-colors ${
|
||||
@@ -638,23 +707,14 @@ export default function TradeCreator({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-4">
|
||||
<div className="flex items-center gap-4 mb-4">
|
||||
<input
|
||||
type="text"
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
placeholder="Add a message (optional)"
|
||||
className="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
className="flex-1 px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
{message && (
|
||||
<div className="p-2 bg-gray-900/50 rounded border border-gray-700">
|
||||
<p className="text-xs text-gray-400 mb-1">Preview:</p>
|
||||
<p className="text-sm text-gray-200">{message}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition"
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, RefreshCcw } from 'lucide-react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History, AlertTriangle } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { Trade, TradeItem } from '../services/tradesService';
|
||||
import { Trade, TradeHistoryEntry, getTradeVersionHistory } from '../services/tradesService';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { Card } from '../types';
|
||||
import { getCardsByIds } from '../services/api';
|
||||
import TradeCreator from './TradeCreator';
|
||||
|
||||
interface TradeDetailProps {
|
||||
trade: Trade;
|
||||
onClose: () => void;
|
||||
onAccept: (tradeId: string) => Promise<void>;
|
||||
onDecline: (tradeId: string) => Promise<void>;
|
||||
onCounterOffer: (trade: Trade, senderCards: Card[], receiverCards: Card[]) => void;
|
||||
onTradeUpdated: () => void;
|
||||
}
|
||||
|
||||
interface TradeCardItem {
|
||||
@@ -19,6 +20,11 @@ interface TradeCardItem {
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface CollectionItem {
|
||||
card: Card;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
function calculateTotalPrice(items: TradeCardItem[]): number {
|
||||
return items.reduce((total, { card, quantity }) => {
|
||||
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
|
||||
@@ -31,7 +37,7 @@ export default function TradeDetail({
|
||||
onClose,
|
||||
onAccept,
|
||||
onDecline,
|
||||
onCounterOffer,
|
||||
onTradeUpdated,
|
||||
}: TradeDetailProps) {
|
||||
const { user } = useAuth();
|
||||
const toast = useToast();
|
||||
@@ -39,13 +45,20 @@ export default function TradeDetail({
|
||||
const [processing, setProcessing] = useState(false);
|
||||
const [senderCards, setSenderCards] = useState<TradeCardItem[]>([]);
|
||||
const [receiverCards, setReceiverCards] = useState<TradeCardItem[]>([]);
|
||||
const [showHistory, setShowHistory] = useState(false);
|
||||
const [history, setHistory] = useState<TradeHistoryEntry[]>([]);
|
||||
const [showEditMode, setShowEditMode] = useState(false);
|
||||
const [editReceiverCollection, setEditReceiverCollection] = useState<CollectionItem[]>([]);
|
||||
|
||||
const isSender = trade.sender_id === user?.id;
|
||||
const isReceiver = trade.receiver_id === user?.id;
|
||||
const otherUser = isSender ? trade.receiver : trade.sender;
|
||||
const isUser1 = trade.user1_id === user?.id;
|
||||
const isUser2 = trade.user2_id === user?.id;
|
||||
const otherUser = isUser1 ? trade.user2 : trade.user1;
|
||||
const myUserId = user?.id || '';
|
||||
const otherUserId = isUser1 ? trade.user2_id : trade.user1_id;
|
||||
|
||||
useEffect(() => {
|
||||
loadTradeCards();
|
||||
loadTradeHistory();
|
||||
}, [trade]);
|
||||
|
||||
const loadTradeCards = async () => {
|
||||
@@ -62,22 +75,22 @@ export default function TradeDetail({
|
||||
const cardMap = new Map<string, Card>();
|
||||
cards.forEach(card => cardMap.set(card.id, card));
|
||||
|
||||
const senderItems: TradeCardItem[] = [];
|
||||
const receiverItems: TradeCardItem[] = [];
|
||||
const myItems: TradeCardItem[] = [];
|
||||
const theirItems: TradeCardItem[] = [];
|
||||
|
||||
trade.items?.forEach(item => {
|
||||
const card = cardMap.get(item.card_id);
|
||||
if (!card) return;
|
||||
|
||||
if (item.owner_id === trade.sender_id) {
|
||||
senderItems.push({ card, quantity: item.quantity });
|
||||
if (item.owner_id === myUserId) {
|
||||
myItems.push({ card, quantity: item.quantity });
|
||||
} else {
|
||||
receiverItems.push({ card, quantity: item.quantity });
|
||||
theirItems.push({ card, quantity: item.quantity });
|
||||
}
|
||||
});
|
||||
|
||||
setSenderCards(senderItems);
|
||||
setReceiverCards(receiverItems);
|
||||
setSenderCards(myItems);
|
||||
setReceiverCards(theirItems);
|
||||
} catch (error) {
|
||||
console.error('Error loading trade cards:', error);
|
||||
toast.error('Failed to load trade details');
|
||||
@@ -86,6 +99,15 @@ export default function TradeDetail({
|
||||
}
|
||||
};
|
||||
|
||||
const loadTradeHistory = async () => {
|
||||
try {
|
||||
const historyData = await getTradeVersionHistory(trade.id);
|
||||
setHistory(historyData);
|
||||
} catch (error) {
|
||||
console.error('Error loading trade history:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAccept = async () => {
|
||||
setProcessing(true);
|
||||
try {
|
||||
@@ -110,20 +132,65 @@ export default function TradeDetail({
|
||||
}
|
||||
};
|
||||
|
||||
const handleCounterOffer = () => {
|
||||
const senderCardsList = senderCards.map(item => item.card);
|
||||
const receiverCardsList = receiverCards.map(item => item.card);
|
||||
onCounterOffer(trade, senderCardsList, receiverCardsList);
|
||||
onClose();
|
||||
const handleEdit = async () => {
|
||||
try {
|
||||
// Load the other user's collection for editing
|
||||
const collectionMap = await getUserCollection(otherUserId);
|
||||
const cardIds = Array.from(collectionMap.keys());
|
||||
const cards = await getCardsByIds(cardIds);
|
||||
const collection = cards.map((card) => ({
|
||||
card,
|
||||
quantity: collectionMap.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
setEditReceiverCollection(collection);
|
||||
setShowEditMode(true);
|
||||
} catch (error) {
|
||||
console.error('Error loading collection for edit:', error);
|
||||
toast.error('Failed to load collection');
|
||||
}
|
||||
};
|
||||
|
||||
const senderPrice = calculateTotalPrice(senderCards);
|
||||
const receiverPrice = calculateTotalPrice(receiverCards);
|
||||
// In the symmetric model, counter-offer is the same as edit
|
||||
const handleCounterOffer = handleEdit;
|
||||
|
||||
const yourCards = isSender ? senderCards : receiverCards;
|
||||
const theirCards = isSender ? receiverCards : senderCards;
|
||||
const yourPrice = isSender ? senderPrice : receiverPrice;
|
||||
const theirPrice = isSender ? receiverPrice : senderPrice;
|
||||
// senderCards = myCards, receiverCards = theirCards (already calculated correctly)
|
||||
const yourCards = senderCards;
|
||||
const theirCards = receiverCards;
|
||||
const yourPrice = calculateTotalPrice(yourCards);
|
||||
const theirPrice = calculateTotalPrice(theirCards);
|
||||
|
||||
// For edit mode, pre-populate with current cards
|
||||
// In the symmetric model, both edit and counter-offer use the same perspective:
|
||||
// - Your cards (what you're offering)
|
||||
// - Their cards (what you want)
|
||||
// Include quantity in the card object so TradeCreator can preserve it
|
||||
const editInitialSenderCards = yourCards.map(c => ({ ...c.card, quantity: c.quantity }));
|
||||
const editInitialReceiverCards = theirCards.map(c => ({ ...c.card, quantity: c.quantity }));
|
||||
|
||||
if (showEditMode) {
|
||||
return (
|
||||
<TradeCreator
|
||||
receiverId={otherUserId}
|
||||
receiverUsername={otherUser?.username || 'User'}
|
||||
receiverCollection={editReceiverCollection}
|
||||
onClose={() => {
|
||||
setShowEditMode(false);
|
||||
onClose();
|
||||
}}
|
||||
onTradeCreated={() => {
|
||||
setShowEditMode(false);
|
||||
onTradeUpdated();
|
||||
onClose();
|
||||
}}
|
||||
editMode={true}
|
||||
existingTradeId={trade.id}
|
||||
initialSenderCards={editInitialSenderCards}
|
||||
initialReceiverCards={editInitialReceiverCards}
|
||||
initialMessage={trade.message || ''}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-end md:items-center justify-center p-0 md:p-4">
|
||||
@@ -133,9 +200,9 @@ export default function TradeDetail({
|
||||
<div className="flex items-center gap-2">
|
||||
<ArrowLeftRight size={20} className="text-blue-400" />
|
||||
<div>
|
||||
<h2 className="text-lg font-bold">Trade Details</h2>
|
||||
<h2 className="text-lg font-bold">Trade Details {trade.version > 1 && `(v${trade.version})`}</h2>
|
||||
<p className="text-sm text-gray-400">
|
||||
{isSender ? 'To' : 'From'}: {otherUser?.username}
|
||||
With: {otherUser?.username}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -154,105 +221,150 @@ export default function TradeDetail({
|
||||
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Your Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-green-400">
|
||||
{isSender ? 'You Give' : 'You Receive'}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-green-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{yourPrice.toFixed(2)}
|
||||
<div className="space-y-4">
|
||||
{/* Invalid Trade Warning */}
|
||||
{trade.status === 'pending' && !trade.is_valid && (
|
||||
<div className="bg-red-900/30 border border-red-600 rounded-lg p-3 flex items-start gap-2">
|
||||
<AlertTriangle size={20} className="text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="font-semibold text-red-400 text-sm">Trade No Longer Valid</h4>
|
||||
<p className="text-red-200 text-xs mt-1">
|
||||
One or more cards in this trade are no longer available in the required quantities. This trade cannot be accepted until it is updated.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{yourCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{yourCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Your Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-green-400">
|
||||
You Give
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-green-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{yourPrice.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Their Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-blue-400">
|
||||
{isSender ? 'You Receive' : 'They Give'}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-blue-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{theirPrice.toFixed(2)}
|
||||
</div>
|
||||
{yourCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{yourCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{theirCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{theirCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{/* Their Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-blue-400">
|
||||
You Receive
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-blue-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{theirPrice.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Message */}
|
||||
{trade.message && (
|
||||
<div className="mt-4 p-3 bg-gray-800 rounded-lg">
|
||||
<p className="text-sm text-gray-400 mb-1">Message:</p>
|
||||
<p className="text-sm">{trade.message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Price Difference */}
|
||||
{!loading && (senderPrice > 0 || receiverPrice > 0) && (
|
||||
<div className="mt-4 p-3 bg-gray-800 rounded-lg">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-gray-400">Value Difference:</span>
|
||||
<span className={Math.abs(senderPrice - receiverPrice) > 5 ? 'text-yellow-400' : 'text-gray-300'}>
|
||||
${Math.abs(senderPrice - receiverPrice).toFixed(2)}
|
||||
{senderPrice > receiverPrice ? ' in your favor' : senderPrice < receiverPrice ? ' in their favor' : ' (balanced)'}
|
||||
</span>
|
||||
{theirCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{theirCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Message */}
|
||||
{trade.message && (
|
||||
<div className="p-3 bg-gray-800 rounded-lg">
|
||||
<p className="text-sm text-gray-400 mb-1">Message:</p>
|
||||
<p className="text-sm">{trade.message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Price Difference */}
|
||||
{!loading && (yourPrice > 0 || theirPrice > 0) && (
|
||||
<div className="p-3 bg-gray-800 rounded-lg">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-gray-400">Value Difference:</span>
|
||||
<span className={Math.abs(yourPrice - theirPrice) > 5 ? 'text-yellow-400' : 'text-gray-300'}>
|
||||
${Math.abs(yourPrice - theirPrice).toFixed(2)}
|
||||
{yourPrice > theirPrice ? ' in your favor' : yourPrice < theirPrice ? ' in their favor' : ' (balanced)'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* History */}
|
||||
{history.length > 0 && (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => setShowHistory(!showHistory)}
|
||||
className="flex items-center gap-2 text-sm text-blue-400 hover:text-blue-300"
|
||||
>
|
||||
<History size={16} />
|
||||
{showHistory ? 'Hide' : 'Show'} History ({history.length} {history.length === 1 ? 'version' : 'versions'})
|
||||
</button>
|
||||
|
||||
{showHistory && (
|
||||
<div className="mt-3 space-y-2">
|
||||
{history.map((entry) => (
|
||||
<div key={entry.id} className="p-3 bg-gray-800 rounded-lg text-sm">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="font-semibold text-purple-400">Version {entry.version}</span>
|
||||
<span className="text-gray-400 text-xs">
|
||||
Edited by {entry.editor?.username} • {new Date(entry.created_at).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
{entry.message && (
|
||||
<p className="text-gray-300 text-xs">{entry.message}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -260,13 +372,16 @@ export default function TradeDetail({
|
||||
{/* Actions - Only for pending trades */}
|
||||
{trade.status === 'pending' && !loading && (
|
||||
<div className="border-t border-gray-800 p-4 space-y-2">
|
||||
{isReceiver ? (
|
||||
{/* Only the user who DIDN'T make the last edit can respond */}
|
||||
{trade.editor_id && trade.editor_id !== user?.id ? (
|
||||
/* User receives the last edit - can accept/decline/counter */
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleAccept}
|
||||
disabled={processing}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
disabled={processing || !trade.is_valid}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-medium transition"
|
||||
title={!trade.is_valid ? 'This trade is no longer valid' : ''}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2 className="animate-spin" size={18} />
|
||||
@@ -289,16 +404,79 @@ export default function TradeDetail({
|
||||
<button
|
||||
onClick={handleCounterOffer}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<RefreshCcw size={18} />
|
||||
Make Counter Offer
|
||||
</button>
|
||||
</>
|
||||
) : trade.editor_id === user?.id ? (
|
||||
/* User made the last edit - can still edit while waiting for response */
|
||||
<>
|
||||
<p className="text-center text-gray-400 text-sm py-2">
|
||||
Waiting for {otherUser?.username} to respond...
|
||||
</p>
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<Edit size={18} />
|
||||
Modify Your Offer
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-center text-gray-400 text-sm py-2">
|
||||
Waiting for {otherUser?.username} to respond...
|
||||
</p>
|
||||
/* No editor yet (initial trade) */
|
||||
<>
|
||||
{isUser1 ? (
|
||||
/* User1 (initiator) can edit their initial offer */
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<Edit size={18} />
|
||||
Edit Trade Offer
|
||||
</button>
|
||||
) : (
|
||||
/* User2 (partner) can accept/decline/counter */
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleAccept}
|
||||
disabled={processing || !trade.is_valid}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-medium transition"
|
||||
title={!trade.is_valid ? 'This trade is no longer valid' : ''}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2 className="animate-spin" size={18} />
|
||||
) : (
|
||||
<>
|
||||
<Check size={18} />
|
||||
Accept Trade
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDecline}
|
||||
disabled={processing}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<X size={18} />
|
||||
Decline
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleCounterOffer}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<RefreshCcw size={18} />
|
||||
Make Counter Offer
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -167,6 +167,34 @@
|
||||
animation: float 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Diagonal Carousel - Cards flow from bottom-left to top-right diagonally and loop */
|
||||
@keyframes flowDiagonal {
|
||||
0% {
|
||||
translate: 0 0;
|
||||
opacity: 1;
|
||||
}
|
||||
60% {
|
||||
translate: 600px -600px;
|
||||
opacity: 1;
|
||||
}
|
||||
75% {
|
||||
translate: 900px -900px;
|
||||
opacity: 0.6;
|
||||
}
|
||||
85% {
|
||||
translate: 1100px -1100px;
|
||||
opacity: 0.3;
|
||||
}
|
||||
100% {
|
||||
translate: 1400px -1400px;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-flow-right {
|
||||
animation: flowDiagonal 40s linear infinite;
|
||||
}
|
||||
|
||||
/* Gradient Animation */
|
||||
@keyframes gradientShift {
|
||||
0% {
|
||||
|
||||
@@ -205,42 +205,55 @@ export type Database = {
|
||||
trades: {
|
||||
Row: {
|
||||
id: string
|
||||
sender_id: string
|
||||
receiver_id: string
|
||||
user1_id: string
|
||||
user2_id: string
|
||||
status: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||
message: string | null
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
version: number
|
||||
editor_id: string | null
|
||||
}
|
||||
Insert: {
|
||||
id?: string
|
||||
sender_id: string
|
||||
receiver_id: string
|
||||
user1_id: string
|
||||
user2_id: string
|
||||
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||
message?: string | null
|
||||
created_at?: string | null
|
||||
updated_at?: string | null
|
||||
version?: number
|
||||
editor_id?: string | null
|
||||
}
|
||||
Update: {
|
||||
id?: string
|
||||
sender_id?: string
|
||||
receiver_id?: string
|
||||
user1_id?: string
|
||||
user2_id?: string
|
||||
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||
message?: string | null
|
||||
created_at?: string | null
|
||||
updated_at?: string | null
|
||||
version?: number
|
||||
editor_id?: string | null
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "trades_sender_id_fkey"
|
||||
columns: ["sender_id"]
|
||||
foreignKeyName: "trades_user1_id_fkey"
|
||||
columns: ["user1_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "trades_receiver_id_fkey"
|
||||
columns: ["receiver_id"]
|
||||
foreignKeyName: "trades_user2_id_fkey"
|
||||
columns: ["user2_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "trades_editor_id_fkey"
|
||||
columns: ["editor_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["id"]
|
||||
|
||||
@@ -75,10 +75,76 @@ export const getUserCollection = async (userId: string): Promise<Map<string, num
|
||||
return collectionMap;
|
||||
};
|
||||
|
||||
// Paginated collection API
|
||||
export interface PaginatedCollectionResult {
|
||||
items: Map<string, number>; // card_id -> quantity
|
||||
totalCount: number;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
// Get total collection value from user profile (pre-calculated by triggers)
|
||||
export const getCollectionTotalValue = async (userId: string): Promise<number> => {
|
||||
const { data, error } = await supabase
|
||||
.from('profiles')
|
||||
.select('collection_total_value')
|
||||
.eq('id', userId)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching collection total value:', error);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return data?.collection_total_value || 0;
|
||||
};
|
||||
|
||||
export const getUserCollectionPaginated = async (
|
||||
userId: string,
|
||||
pageSize: number = 50,
|
||||
offset: number = 0
|
||||
): Promise<PaginatedCollectionResult> => {
|
||||
// First, get the total count
|
||||
const { count: totalCount, error: countError } = await supabase
|
||||
.from('collections')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('user_id', userId);
|
||||
|
||||
if (countError) {
|
||||
console.error('Error counting user collection:', countError);
|
||||
throw countError;
|
||||
}
|
||||
|
||||
// Then get the paginated data
|
||||
const { data, error } = await supabase
|
||||
.from('collections')
|
||||
.select('card_id, quantity')
|
||||
.eq('user_id', userId)
|
||||
.order('created_at', { ascending: false })
|
||||
.range(offset, offset + pageSize - 1);
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching user collection:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Create a map of card_id to quantity for easy lookup
|
||||
const collectionMap = new Map<string, number>();
|
||||
data?.forEach((item) => {
|
||||
collectionMap.set(item.card_id, item.quantity);
|
||||
});
|
||||
|
||||
return {
|
||||
items: collectionMap,
|
||||
totalCount: totalCount || 0,
|
||||
hasMore: offset + pageSize < (totalCount || 0),
|
||||
};
|
||||
};
|
||||
|
||||
export const addCardToCollection = async (
|
||||
userId: string,
|
||||
cardId: string,
|
||||
quantity: number = 1
|
||||
quantity: number = 1,
|
||||
priceUsd: number = 0
|
||||
): Promise<void> => {
|
||||
// Check if card already exists in collection
|
||||
const { data: existing, error: fetchError } = await supabase
|
||||
@@ -94,11 +160,12 @@ export const addCardToCollection = async (
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
// Update existing card quantity
|
||||
// Update existing card quantity and price
|
||||
const { error: updateError } = await supabase
|
||||
.from('collections')
|
||||
.update({
|
||||
quantity: existing.quantity + quantity,
|
||||
price_usd: priceUsd,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('id', existing.id);
|
||||
@@ -112,6 +179,7 @@ export const addCardToCollection = async (
|
||||
user_id: userId,
|
||||
card_id: cardId,
|
||||
quantity: quantity,
|
||||
price_usd: priceUsd,
|
||||
});
|
||||
|
||||
if (insertError) throw insertError;
|
||||
@@ -120,7 +188,7 @@ export const addCardToCollection = async (
|
||||
|
||||
export const addMultipleCardsToCollection = async (
|
||||
userId: string,
|
||||
cards: { cardId: string; quantity: number }[]
|
||||
cards: { cardId: string; quantity: number; priceUsd?: number }[]
|
||||
): Promise<void> => {
|
||||
// Fetch existing cards in collection
|
||||
const cardIds = cards.map(c => c.cardId);
|
||||
@@ -146,6 +214,7 @@ export const addMultipleCardsToCollection = async (
|
||||
toUpdate.push({
|
||||
id: existing.id,
|
||||
quantity: existing.quantity + card.quantity,
|
||||
price_usd: card.priceUsd || 0,
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
} else {
|
||||
@@ -153,6 +222,7 @@ export const addMultipleCardsToCollection = async (
|
||||
user_id: userId,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
price_usd: card.priceUsd || 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -170,7 +240,11 @@ export const addMultipleCardsToCollection = async (
|
||||
for (const update of toUpdate) {
|
||||
const { error: updateError } = await supabase
|
||||
.from('collections')
|
||||
.update({ quantity: update.quantity, updated_at: update.updated_at })
|
||||
.update({
|
||||
quantity: update.quantity,
|
||||
price_usd: update.price_usd,
|
||||
updated_at: update.updated_at
|
||||
})
|
||||
.eq('id', update.id);
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
@@ -10,23 +10,53 @@ export interface TradeItem {
|
||||
|
||||
export interface Trade {
|
||||
id: string;
|
||||
sender_id: string;
|
||||
receiver_id: string;
|
||||
user1_id: string;
|
||||
user2_id: string;
|
||||
status: 'pending' | 'accepted' | 'declined' | 'cancelled';
|
||||
message: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
sender?: { username: string | null };
|
||||
receiver?: { username: string | null };
|
||||
version: number;
|
||||
editor_id: string | null;
|
||||
is_valid: boolean;
|
||||
user1?: { username: string | null };
|
||||
user2?: { username: string | null };
|
||||
items?: TradeItem[];
|
||||
}
|
||||
|
||||
export interface TradeHistoryEntry {
|
||||
id: string;
|
||||
trade_id: string;
|
||||
version: number;
|
||||
editor_id: string;
|
||||
message: string | null;
|
||||
created_at: string;
|
||||
editor?: { username: string | null };
|
||||
items?: TradeHistoryItem[];
|
||||
}
|
||||
|
||||
export interface TradeHistoryItem {
|
||||
id: string;
|
||||
history_id: string;
|
||||
owner_id: string;
|
||||
card_id: string;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export interface CreateTradeParams {
|
||||
senderId: string;
|
||||
receiverId: string;
|
||||
user1Id: string;
|
||||
user2Id: string;
|
||||
message?: string;
|
||||
senderCards: { cardId: string; quantity: number }[];
|
||||
receiverCards: { cardId: string; quantity: number }[];
|
||||
user1Cards: { cardId: string; quantity: number }[];
|
||||
user2Cards: { cardId: string; quantity: number }[];
|
||||
}
|
||||
|
||||
export interface UpdateTradeParams {
|
||||
tradeId: string;
|
||||
editorId: string;
|
||||
message?: string;
|
||||
myCards: { cardId: string; quantity: number }[];
|
||||
theirCards: { cardId: string; quantity: number }[];
|
||||
}
|
||||
|
||||
// Get all trades for a user
|
||||
@@ -35,11 +65,11 @@ export async function getTrades(userId: string): Promise<Trade[]> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||
.or(`user1_id.eq.${userId},user2_id.eq.${userId}`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
@@ -52,12 +82,12 @@ export async function getPendingTrades(userId: string): Promise<Trade[]> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.eq('status', 'pending')
|
||||
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||
.or(`user1_id.eq.${userId},user2_id.eq.${userId}`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
@@ -70,8 +100,8 @@ export async function getTradeById(tradeId: string): Promise<Trade | null> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.eq('id', tradeId)
|
||||
@@ -83,39 +113,40 @@ export async function getTradeById(tradeId: string): Promise<Trade | null> {
|
||||
|
||||
// Create a new trade with items
|
||||
export async function createTrade(params: CreateTradeParams): Promise<Trade> {
|
||||
const { senderId, receiverId, message, senderCards, receiverCards } = params;
|
||||
const { user1Id, user2Id, message, user1Cards, user2Cards } = params;
|
||||
|
||||
// Create the trade
|
||||
const { data: trade, error: tradeError } = await supabase
|
||||
.from('trades')
|
||||
.insert({
|
||||
sender_id: senderId,
|
||||
receiver_id: receiverId,
|
||||
user1_id: user1Id,
|
||||
user2_id: user2Id,
|
||||
message,
|
||||
status: 'pending',
|
||||
// editor_id starts as null - gets set when someone edits the trade
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (tradeError) throw tradeError;
|
||||
|
||||
// Add sender's cards
|
||||
const senderItems = senderCards.map((card) => ({
|
||||
// Add user1's cards
|
||||
const user1Items = user1Cards.map((card) => ({
|
||||
trade_id: trade.id,
|
||||
owner_id: senderId,
|
||||
owner_id: user1Id,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
// Add receiver's cards (what sender wants)
|
||||
const receiverItems = receiverCards.map((card) => ({
|
||||
// Add user2's cards
|
||||
const user2Items = user2Cards.map((card) => ({
|
||||
trade_id: trade.id,
|
||||
owner_id: receiverId,
|
||||
owner_id: user2Id,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
const allItems = [...senderItems, ...receiverItems];
|
||||
const allItems = [...user1Items, ...user2Items];
|
||||
|
||||
if (allItems.length > 0) {
|
||||
const { error: itemsError } = await supabase
|
||||
@@ -130,6 +161,25 @@ export async function createTrade(params: CreateTradeParams): Promise<Trade> {
|
||||
|
||||
// Accept a trade (executes the card transfer)
|
||||
export async function acceptTrade(tradeId: string): Promise<boolean> {
|
||||
// First check if the trade is valid
|
||||
const { data: trade, error: tradeError } = await supabase
|
||||
.from('trades')
|
||||
.select('is_valid, status')
|
||||
.eq('id', tradeId)
|
||||
.single();
|
||||
|
||||
if (tradeError) throw tradeError;
|
||||
|
||||
// Prevent accepting invalid trades
|
||||
if (!trade.is_valid) {
|
||||
throw new Error('This trade is no longer valid. One or more cards are no longer available in the required quantities.');
|
||||
}
|
||||
|
||||
// Prevent accepting non-pending trades
|
||||
if (trade.status !== 'pending') {
|
||||
throw new Error('This trade has already been processed.');
|
||||
}
|
||||
|
||||
const { data, error } = await supabase.rpc('execute_trade', {
|
||||
trade_id: tradeId,
|
||||
});
|
||||
@@ -170,11 +220,11 @@ export async function getTradeHistory(userId: string): Promise<Trade[]> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||
.or(`user1_id.eq.${userId},user2_id.eq.${userId}`)
|
||||
.in('status', ['accepted', 'declined', 'cancelled'])
|
||||
.order('updated_at', { ascending: false })
|
||||
.limit(50);
|
||||
@@ -182,3 +232,116 @@ export async function getTradeHistory(userId: string): Promise<Trade[]> {
|
||||
if (error) throw error;
|
||||
return data as Trade[];
|
||||
}
|
||||
|
||||
// Update an existing trade (for edits and counter-offers)
|
||||
export async function updateTrade(params: UpdateTradeParams): Promise<Trade> {
|
||||
const { tradeId, editorId, message, myCards, theirCards } = params;
|
||||
|
||||
// Get current trade info
|
||||
const { data: currentTrade, error: tradeError } = await supabase
|
||||
.from('trades')
|
||||
.select('version, user1_id, user2_id')
|
||||
.eq('id', tradeId)
|
||||
.single();
|
||||
|
||||
if (tradeError) throw tradeError;
|
||||
|
||||
const newVersion = (currentTrade.version || 1) + 1;
|
||||
|
||||
// Determine the other user's ID
|
||||
const otherUserId = currentTrade.user1_id === editorId
|
||||
? currentTrade.user2_id
|
||||
: currentTrade.user1_id;
|
||||
|
||||
// Save current state to history before updating
|
||||
const { data: historyEntry, error: historyError } = await supabase
|
||||
.from('trade_history')
|
||||
.insert({
|
||||
trade_id: tradeId,
|
||||
version: currentTrade.version || 1,
|
||||
editor_id: editorId,
|
||||
message: message || null,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (historyError) throw historyError;
|
||||
|
||||
// Save current items to history
|
||||
const { data: currentItems } = await supabase
|
||||
.from('trade_items')
|
||||
.select('*')
|
||||
.eq('trade_id', tradeId);
|
||||
|
||||
if (currentItems && currentItems.length > 0) {
|
||||
const historyItems = currentItems.map(item => ({
|
||||
history_id: historyEntry.id,
|
||||
owner_id: item.owner_id,
|
||||
card_id: item.card_id,
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
|
||||
await supabase.from('trade_history_items').insert(historyItems);
|
||||
}
|
||||
|
||||
// Update the trade
|
||||
const { data: updatedTrade, error: updateError } = await supabase
|
||||
.from('trades')
|
||||
.update({
|
||||
message,
|
||||
version: newVersion,
|
||||
editor_id: editorId,
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', tradeId)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
// Delete existing items
|
||||
await supabase.from('trade_items').delete().eq('trade_id', tradeId);
|
||||
|
||||
// Add new items (myCards belong to editor, theirCards belong to other user)
|
||||
const myItems = myCards.map((card) => ({
|
||||
trade_id: tradeId,
|
||||
owner_id: editorId,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
const theirItems = theirCards.map((card) => ({
|
||||
trade_id: tradeId,
|
||||
owner_id: otherUserId,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
const allItems = [...myItems, ...theirItems];
|
||||
|
||||
if (allItems.length > 0) {
|
||||
const { error: itemsError } = await supabase
|
||||
.from('trade_items')
|
||||
.insert(allItems);
|
||||
|
||||
if (itemsError) throw itemsError;
|
||||
}
|
||||
|
||||
return updatedTrade;
|
||||
}
|
||||
|
||||
// Get version history for a trade
|
||||
export async function getTradeVersionHistory(tradeId: string): Promise<TradeHistoryEntry[]> {
|
||||
const { data, error } = await supabase
|
||||
.from('trade_history')
|
||||
.select(`
|
||||
*,
|
||||
editor:profiles!trade_history_editor_id_fkey(username),
|
||||
items:trade_history_items(*)
|
||||
`)
|
||||
.eq('trade_id', tradeId)
|
||||
.order('version', { ascending: true });
|
||||
|
||||
if (error) throw error;
|
||||
return data as TradeHistoryEntry[];
|
||||
}
|
||||
|
||||
273
supabase/migrations/20250124000000_friends_trades_visibility.sql
Normal file
273
supabase/migrations/20250124000000_friends_trades_visibility.sql
Normal file
@@ -0,0 +1,273 @@
|
||||
/*
|
||||
# Friends, Trades, and Collection Visibility
|
||||
|
||||
1. Changes to profiles
|
||||
- Add `collection_visibility` column (public, friends, private)
|
||||
|
||||
2. New Tables
|
||||
- `friendships` - Friend relationships between users
|
||||
- `trades` - Trade offers between users
|
||||
- `trade_items` - Cards included in trades
|
||||
|
||||
3. Security
|
||||
- RLS policies for all new tables
|
||||
- Updated collection policies for visibility
|
||||
*/
|
||||
|
||||
-- Add collection visibility to profiles
|
||||
ALTER TABLE public.profiles
|
||||
ADD COLUMN collection_visibility text DEFAULT 'private'
|
||||
CHECK (collection_visibility IN ('public', 'friends', 'private'));
|
||||
|
||||
-- =============================================
|
||||
-- FRIENDSHIPS TABLE
|
||||
-- =============================================
|
||||
CREATE TABLE public.friendships (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
requester_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
addressee_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
status text DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'declined')),
|
||||
created_at timestamptz DEFAULT now(),
|
||||
updated_at timestamptz DEFAULT now(),
|
||||
UNIQUE(requester_id, addressee_id),
|
||||
CHECK (requester_id != addressee_id)
|
||||
);
|
||||
|
||||
ALTER TABLE public.friendships ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can see friendships they're involved in
|
||||
CREATE POLICY "Users can view their friendships"
|
||||
ON public.friendships
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (requester_id = auth.uid() OR addressee_id = auth.uid());
|
||||
|
||||
-- Users can create friend requests
|
||||
CREATE POLICY "Users can send friend requests"
|
||||
ON public.friendships
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (requester_id = auth.uid());
|
||||
|
||||
-- Users can update friendships they received (accept/decline)
|
||||
CREATE POLICY "Users can respond to friend requests"
|
||||
ON public.friendships
|
||||
FOR UPDATE
|
||||
TO authenticated
|
||||
USING (addressee_id = auth.uid());
|
||||
|
||||
-- Users can delete their own friendships
|
||||
CREATE POLICY "Users can delete their friendships"
|
||||
ON public.friendships
|
||||
FOR DELETE
|
||||
TO authenticated
|
||||
USING (requester_id = auth.uid() OR addressee_id = auth.uid());
|
||||
|
||||
-- =============================================
|
||||
-- TRADES TABLE
|
||||
-- =============================================
|
||||
CREATE TABLE public.trades (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
sender_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
receiver_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
status text DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'declined', 'cancelled')),
|
||||
message text,
|
||||
created_at timestamptz DEFAULT now(),
|
||||
updated_at timestamptz DEFAULT now(),
|
||||
CHECK (sender_id != receiver_id)
|
||||
);
|
||||
|
||||
ALTER TABLE public.trades ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can see trades they're involved in
|
||||
CREATE POLICY "Users can view their trades"
|
||||
ON public.trades
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (sender_id = auth.uid() OR receiver_id = auth.uid());
|
||||
|
||||
-- Users can create trades
|
||||
CREATE POLICY "Users can create trades"
|
||||
ON public.trades
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (sender_id = auth.uid());
|
||||
|
||||
-- Sender can cancel, receiver can accept/decline
|
||||
CREATE POLICY "Users can update their trades"
|
||||
ON public.trades
|
||||
FOR UPDATE
|
||||
TO authenticated
|
||||
USING (sender_id = auth.uid() OR receiver_id = auth.uid());
|
||||
|
||||
-- =============================================
|
||||
-- TRADE ITEMS TABLE
|
||||
-- =============================================
|
||||
CREATE TABLE public.trade_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
trade_id uuid REFERENCES public.trades(id) ON DELETE CASCADE NOT NULL,
|
||||
owner_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
card_id text NOT NULL,
|
||||
quantity integer DEFAULT 1 CHECK (quantity > 0),
|
||||
created_at timestamptz DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE public.trade_items ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can see items in their trades
|
||||
CREATE POLICY "Users can view trade items"
|
||||
ON public.trade_items
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_items.trade_id
|
||||
AND (trades.sender_id = auth.uid() OR trades.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
-- Users can add items to trades they created
|
||||
CREATE POLICY "Users can add trade items"
|
||||
ON public.trade_items
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_items.trade_id
|
||||
AND trades.sender_id = auth.uid()
|
||||
AND trades.status = 'pending'
|
||||
)
|
||||
);
|
||||
|
||||
-- =============================================
|
||||
-- UPDATE COLLECTION POLICIES FOR VISIBILITY
|
||||
-- =============================================
|
||||
|
||||
-- Drop old restrictive policy
|
||||
DROP POLICY IF EXISTS "Users can view their own collection" ON public.collections;
|
||||
|
||||
-- New policy: view own collection OR public collections OR friend's collections (if friends visibility)
|
||||
CREATE POLICY "Users can view collections based on visibility"
|
||||
ON public.collections
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (
|
||||
user_id = auth.uid()
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM public.profiles
|
||||
WHERE profiles.id = collections.user_id
|
||||
AND profiles.collection_visibility = 'public'
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM public.profiles p
|
||||
JOIN public.friendships f ON (
|
||||
(f.requester_id = p.id AND f.addressee_id = auth.uid())
|
||||
OR (f.addressee_id = p.id AND f.requester_id = auth.uid())
|
||||
)
|
||||
WHERE p.id = collections.user_id
|
||||
AND p.collection_visibility = 'friends'
|
||||
AND f.status = 'accepted'
|
||||
)
|
||||
);
|
||||
|
||||
-- =============================================
|
||||
-- UPDATE PROFILES POLICY FOR PUBLIC VIEWING
|
||||
-- =============================================
|
||||
|
||||
-- Drop old restrictive policy
|
||||
DROP POLICY IF EXISTS "Users can view their own profile" ON public.profiles;
|
||||
|
||||
-- New policy: users can view all profiles (needed for friend search and public collections)
|
||||
CREATE POLICY "Users can view profiles"
|
||||
ON public.profiles
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (true);
|
||||
|
||||
-- =============================================
|
||||
-- FUNCTION: Execute trade (transfer cards)
|
||||
-- =============================================
|
||||
CREATE OR REPLACE FUNCTION public.execute_trade(trade_id uuid)
|
||||
RETURNS boolean
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_trade RECORD;
|
||||
v_item RECORD;
|
||||
BEGIN
|
||||
-- Get the trade
|
||||
SELECT * INTO v_trade FROM public.trades WHERE id = trade_id;
|
||||
|
||||
-- Check trade exists and is pending
|
||||
IF v_trade IS NULL OR v_trade.status != 'pending' THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Check caller is the receiver
|
||||
IF v_trade.receiver_id != auth.uid() THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Process each trade item
|
||||
FOR v_item IN SELECT * FROM public.trade_items WHERE trade_items.trade_id = execute_trade.trade_id
|
||||
LOOP
|
||||
-- Determine new owner
|
||||
DECLARE
|
||||
v_new_owner uuid;
|
||||
BEGIN
|
||||
IF v_item.owner_id = v_trade.sender_id THEN
|
||||
v_new_owner := v_trade.receiver_id;
|
||||
ELSE
|
||||
v_new_owner := v_trade.sender_id;
|
||||
END IF;
|
||||
|
||||
-- Remove from old owner's collection
|
||||
UPDATE public.collections
|
||||
SET quantity = quantity - v_item.quantity,
|
||||
updated_at = now()
|
||||
WHERE user_id = v_item.owner_id
|
||||
AND card_id = v_item.card_id;
|
||||
|
||||
-- Delete if quantity is 0 or less
|
||||
DELETE FROM public.collections
|
||||
WHERE user_id = v_item.owner_id
|
||||
AND card_id = v_item.card_id
|
||||
AND quantity <= 0;
|
||||
|
||||
-- Add to new owner's collection
|
||||
INSERT INTO public.collections (user_id, card_id, quantity)
|
||||
VALUES (v_new_owner, v_item.card_id, v_item.quantity)
|
||||
ON CONFLICT (user_id, card_id)
|
||||
DO UPDATE SET
|
||||
quantity = collections.quantity + v_item.quantity,
|
||||
updated_at = now();
|
||||
END;
|
||||
END LOOP;
|
||||
|
||||
-- Mark trade as accepted
|
||||
UPDATE public.trades
|
||||
SET status = 'accepted', updated_at = now()
|
||||
WHERE id = trade_id;
|
||||
|
||||
RETURN true;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Add unique constraint on collections for upsert
|
||||
ALTER TABLE public.collections
|
||||
ADD CONSTRAINT collections_user_card_unique UNIQUE (user_id, card_id);
|
||||
|
||||
-- =============================================
|
||||
-- INDEXES FOR PERFORMANCE
|
||||
-- =============================================
|
||||
CREATE INDEX idx_friendships_requester ON public.friendships(requester_id);
|
||||
CREATE INDEX idx_friendships_addressee ON public.friendships(addressee_id);
|
||||
CREATE INDEX idx_friendships_status ON public.friendships(status);
|
||||
CREATE INDEX idx_trades_sender ON public.trades(sender_id);
|
||||
CREATE INDEX idx_trades_receiver ON public.trades(receiver_id);
|
||||
CREATE INDEX idx_trades_status ON public.trades(status);
|
||||
CREATE INDEX idx_trade_items_trade ON public.trade_items(trade_id);
|
||||
CREATE INDEX idx_profiles_visibility ON public.profiles(collection_visibility);
|
||||
78
supabase/migrations/20250126000000_trade_history.sql
Normal file
78
supabase/migrations/20250126000000_trade_history.sql
Normal file
@@ -0,0 +1,78 @@
|
||||
-- Create trade_history table to track all versions of a trade
|
||||
CREATE TABLE IF NOT EXISTS public.trade_history (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
trade_id uuid REFERENCES public.trades(id) ON DELETE CASCADE NOT NULL,
|
||||
version integer NOT NULL,
|
||||
editor_id uuid REFERENCES public.profiles(id) NOT NULL,
|
||||
message text,
|
||||
created_at timestamptz DEFAULT now(),
|
||||
UNIQUE(trade_id, version)
|
||||
);
|
||||
|
||||
-- Create trade_history_items table to store cards for each version
|
||||
CREATE TABLE IF NOT EXISTS public.trade_history_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
history_id uuid REFERENCES public.trade_history(id) ON DELETE CASCADE NOT NULL,
|
||||
owner_id uuid REFERENCES public.profiles(id) NOT NULL,
|
||||
card_id text NOT NULL,
|
||||
quantity integer DEFAULT 1,
|
||||
created_at timestamptz DEFAULT now()
|
||||
);
|
||||
|
||||
-- Add version column to trades table to track current version
|
||||
ALTER TABLE public.trades ADD COLUMN IF NOT EXISTS version integer DEFAULT 1;
|
||||
|
||||
-- Add editor_id to track who last edited the trade
|
||||
ALTER TABLE public.trades ADD COLUMN IF NOT EXISTS editor_id uuid REFERENCES public.profiles(id);
|
||||
|
||||
-- Create indexes for better performance
|
||||
CREATE INDEX IF NOT EXISTS idx_trade_history_trade_id ON public.trade_history(trade_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_trade_history_items_history_id ON public.trade_history_items(history_id);
|
||||
|
||||
-- Enable RLS
|
||||
ALTER TABLE public.trade_history ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.trade_history_items ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- RLS policies for trade_history
|
||||
CREATE POLICY "Users can view history of their trades"
|
||||
ON public.trade_history FOR SELECT
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_history.trade_id
|
||||
AND (trades.sender_id = auth.uid() OR trades.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can create history for their trades"
|
||||
ON public.trade_history FOR INSERT
|
||||
WITH CHECK (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_history.trade_id
|
||||
AND (trades.sender_id = auth.uid() OR trades.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
-- RLS policies for trade_history_items
|
||||
CREATE POLICY "Users can view history items of their trades"
|
||||
ON public.trade_history_items FOR SELECT
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trade_history th
|
||||
JOIN public.trades t ON t.id = th.trade_id
|
||||
WHERE th.id = trade_history_items.history_id
|
||||
AND (t.sender_id = auth.uid() OR t.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can create history items for their trades"
|
||||
ON public.trade_history_items FOR INSERT
|
||||
WITH CHECK (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trade_history th
|
||||
JOIN public.trades t ON t.id = th.trade_id
|
||||
WHERE th.id = trade_history_items.history_id
|
||||
AND (t.sender_id = auth.uid() OR t.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Add price_usd column to collections table
|
||||
ALTER TABLE collections
|
||||
ADD COLUMN IF NOT EXISTS price_usd DECIMAL(10, 2) DEFAULT 0;
|
||||
|
||||
-- Create index for faster price calculations
|
||||
CREATE INDEX IF NOT EXISTS idx_collections_price ON collections(price_usd);
|
||||
|
||||
-- Add comment
|
||||
COMMENT ON COLUMN collections.price_usd IS 'USD price of the card at time of addition/update';
|
||||
101
supabase/migrations/20250127000001_add_trade_validation.sql
Normal file
101
supabase/migrations/20250127000001_add_trade_validation.sql
Normal file
@@ -0,0 +1,101 @@
|
||||
-- Add is_valid column to trades table
|
||||
ALTER TABLE public.trades
|
||||
ADD COLUMN IF NOT EXISTS is_valid BOOLEAN DEFAULT true;
|
||||
|
||||
-- Create index for filtering by validity
|
||||
CREATE INDEX IF NOT EXISTS idx_trades_is_valid ON public.trades(is_valid);
|
||||
|
||||
-- Function to validate if a trade can still be executed based on current collections
|
||||
CREATE OR REPLACE FUNCTION public.validate_trade(p_trade_id uuid)
|
||||
RETURNS boolean
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_item RECORD;
|
||||
v_collection_quantity integer;
|
||||
BEGIN
|
||||
-- Check each item in the trade
|
||||
FOR v_item IN
|
||||
SELECT owner_id, card_id, quantity
|
||||
FROM public.trade_items
|
||||
WHERE trade_id = p_trade_id
|
||||
LOOP
|
||||
-- Get the quantity of this card in the owner's collection
|
||||
SELECT COALESCE(quantity, 0) INTO v_collection_quantity
|
||||
FROM public.collections
|
||||
WHERE user_id = v_item.owner_id
|
||||
AND card_id = v_item.card_id;
|
||||
|
||||
-- If owner doesn't have enough of this card, trade is invalid
|
||||
IF v_collection_quantity < v_item.quantity THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
-- All items are available, trade is valid
|
||||
RETURN true;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Function to check and update validity of affected trades when collections change
|
||||
CREATE OR REPLACE FUNCTION public.update_affected_trades_validity()
|
||||
RETURNS TRIGGER
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_user_id uuid;
|
||||
v_card_id text;
|
||||
v_trade RECORD;
|
||||
v_is_valid boolean;
|
||||
BEGIN
|
||||
-- Get the user_id and card_id from the changed row
|
||||
IF (TG_OP = 'DELETE') THEN
|
||||
v_user_id := OLD.user_id;
|
||||
v_card_id := OLD.card_id;
|
||||
ELSE
|
||||
v_user_id := NEW.user_id;
|
||||
v_card_id := NEW.card_id;
|
||||
END IF;
|
||||
|
||||
-- Find all pending trades that involve this card from this user
|
||||
FOR v_trade IN
|
||||
SELECT DISTINCT t.id
|
||||
FROM public.trades t
|
||||
JOIN public.trade_items ti ON ti.trade_id = t.id
|
||||
WHERE t.status = 'pending'
|
||||
AND ti.owner_id = v_user_id
|
||||
AND ti.card_id = v_card_id
|
||||
LOOP
|
||||
-- Validate the trade
|
||||
v_is_valid := public.validate_trade(v_trade.id);
|
||||
|
||||
-- Update the trade's validity
|
||||
UPDATE public.trades
|
||||
SET is_valid = v_is_valid,
|
||||
updated_at = now()
|
||||
WHERE id = v_trade.id;
|
||||
END LOOP;
|
||||
|
||||
IF (TG_OP = 'DELETE') THEN
|
||||
RETURN OLD;
|
||||
ELSE
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Create trigger to auto-update trade validity when collections change
|
||||
CREATE TRIGGER update_trades_on_collection_change
|
||||
AFTER UPDATE OR DELETE ON public.collections
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.update_affected_trades_validity();
|
||||
|
||||
-- Add comment
|
||||
COMMENT ON COLUMN public.trades.is_valid IS 'Indicates if the trade can still be executed based on current collections. Auto-updated when collections change.';
|
||||
|
||||
-- Initial validation: set is_valid for all existing pending trades
|
||||
UPDATE public.trades
|
||||
SET is_valid = public.validate_trade(id)
|
||||
WHERE status = 'pending';
|
||||
104
vite.config.ts.timestamp-1764157043179-658c718c76681.mjs
Normal file
104
vite.config.ts.timestamp-1764157043179-658c718c76681.mjs
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user