Compare commits
9 Commits
feature/tr
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2acf50e46f | ||
|
|
1d77b6fb8e | ||
|
|
239a2c9591 | ||
|
|
64c48da05a | ||
|
|
2d7641cc20 | ||
|
|
24023570c7 | ||
|
|
359cc61115 | ||
|
|
71891a29be | ||
| 613db069b8 |
@@ -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()) {
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft } from 'lucide-react';
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft, RefreshCw, Plus, Minus, AlertTriangle } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { supabase } from '../lib/supabase';
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
Trade,
|
||||
TradeItem,
|
||||
} from '../services/tradesService';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { getUserCollectionPaginated, getCardsByIds, getCollectionTotalValue } from '../services/api';
|
||||
import { Card } from '../types';
|
||||
import TradeCreator from './TradeCreator';
|
||||
import TradeDetail from './TradeDetail';
|
||||
@@ -50,6 +50,8 @@ const VISIBILITY_OPTIONS = [
|
||||
{ value: 'private', label: 'Private', description: 'Only you' },
|
||||
] as const;
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
export default function Community() {
|
||||
const { user } = useAuth();
|
||||
const toast = useToast();
|
||||
@@ -62,8 +64,18 @@ export default function Community() {
|
||||
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
|
||||
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
|
||||
const [loadingCollection, setLoadingCollection] = useState(false);
|
||||
const [isLoadingMoreUserCards, setIsLoadingMoreUserCards] = useState(false);
|
||||
const [hasMoreUserCards, setHasMoreUserCards] = useState(false);
|
||||
const [userCollectionOffset, setUserCollectionOffset] = useState(0);
|
||||
const [userCollectionTotalCount, setUserCollectionTotalCount] = useState(0);
|
||||
const [userCollectionTotalValue, setUserCollectionTotalValue] = useState<number>(0);
|
||||
const [isLoadingUserTotalValue, setIsLoadingUserTotalValue] = useState(true);
|
||||
const [showTradeCreator, setShowTradeCreator] = useState(false);
|
||||
const [userCollectionSearch, setUserCollectionSearch] = useState('');
|
||||
const [hoveredUserCard, setHoveredUserCard] = useState<Card | null>(null);
|
||||
const [selectedUserCard, setSelectedUserCard] = useState<CollectionItem | null>(null);
|
||||
const [userCardFaceIndex, setUserCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||
const userCollectionObserverTarget = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Friends state
|
||||
const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list');
|
||||
@@ -196,6 +208,7 @@ export default function Community() {
|
||||
}, [user]);
|
||||
|
||||
// Subscribe to collection changes when viewing someone's collection
|
||||
// Auto-price trigger is disabled, so no more infinite loops!
|
||||
useEffect(() => {
|
||||
if (!user || !selectedUser) return;
|
||||
|
||||
@@ -209,10 +222,11 @@ export default function Community() {
|
||||
table: 'collections',
|
||||
},
|
||||
(payload: any) => {
|
||||
// Filter for the selected user's collections
|
||||
const data = payload.new || payload.old;
|
||||
if (data && data.user_id === selectedUser.id) {
|
||||
console.log('Collection change for viewed user:', payload);
|
||||
console.log('Collection change for viewed user:', payload.eventType);
|
||||
// Reload on any change (INSERT/UPDATE/DELETE)
|
||||
// No more infinite loops since auto-price trigger is disabled
|
||||
loadUserCollection(selectedUser.id);
|
||||
}
|
||||
}
|
||||
@@ -224,6 +238,44 @@ export default function Community() {
|
||||
};
|
||||
}, [user, selectedUser]);
|
||||
|
||||
// Helper function to check if a card has an actual back face
|
||||
const isDoubleFaced = (card: Card) => {
|
||||
const backFaceLayouts = ['transform', 'modal_dfc', 'double_faced_token', 'reversible_card'];
|
||||
return card.card_faces && card.card_faces.length > 1 && backFaceLayouts.includes(card.layout);
|
||||
};
|
||||
|
||||
// Helper function to get the current face index for a card
|
||||
const getCurrentFaceIndex = (cardId: string) => {
|
||||
return userCardFaceIndex.get(cardId) || 0;
|
||||
};
|
||||
|
||||
// Helper function to get the image URI for a card
|
||||
const getCardImageUri = (card: Card, faceIndex: number = 0) => {
|
||||
if (isDoubleFaced(card) && card.card_faces) {
|
||||
return card.card_faces[faceIndex]?.image_uris?.normal || card.card_faces[faceIndex]?.image_uris?.small;
|
||||
}
|
||||
return card.image_uris?.normal || card.image_uris?.small;
|
||||
};
|
||||
|
||||
// Helper function to get the large image URI for hover preview
|
||||
const getCardLargeImageUri = (card: Card, faceIndex: number = 0) => {
|
||||
if (isDoubleFaced(card) && card.card_faces) {
|
||||
return card.card_faces[faceIndex]?.image_uris?.large || card.card_faces[faceIndex]?.image_uris?.normal;
|
||||
}
|
||||
return card.image_uris?.large || card.image_uris?.normal;
|
||||
};
|
||||
|
||||
// Toggle card face
|
||||
const toggleCardFace = (cardId: string, totalFaces: number) => {
|
||||
setUserCardFaceIndex(prev => {
|
||||
const newMap = new Map(prev);
|
||||
const currentIndex = prev.get(cardId) || 0;
|
||||
const nextIndex = (currentIndex + 1) % totalFaces;
|
||||
newMap.set(cardId, nextIndex);
|
||||
return newMap;
|
||||
});
|
||||
};
|
||||
|
||||
const loadAllData = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
@@ -257,26 +309,138 @@ export default function Community() {
|
||||
|
||||
const loadUserCollection = async (userId: string) => {
|
||||
setLoadingCollection(true);
|
||||
setIsLoadingUserTotalValue(true);
|
||||
setSelectedUserCollection([]);
|
||||
setUserCollectionOffset(0);
|
||||
|
||||
try {
|
||||
const collectionMap = await getUserCollection(userId);
|
||||
if (collectionMap.size === 0) {
|
||||
// Load paginated collection for display
|
||||
const result = await getUserCollectionPaginated(userId, PAGE_SIZE, 0);
|
||||
setUserCollectionTotalCount(result.totalCount);
|
||||
setHasMoreUserCards(result.hasMore);
|
||||
|
||||
if (result.items.size === 0) {
|
||||
setSelectedUserCollection([]);
|
||||
setUserCollectionTotalValue(0);
|
||||
setIsLoadingUserTotalValue(false);
|
||||
return;
|
||||
}
|
||||
const cardIds = Array.from(collectionMap.keys());
|
||||
|
||||
const cardIds = Array.from(result.items.keys());
|
||||
const cards = await getCardsByIds(cardIds);
|
||||
setSelectedUserCollection(cards.map((card) => ({
|
||||
card,
|
||||
quantity: collectionMap.get(card.id) || 0,
|
||||
quantity: result.items.get(card.id) || 0,
|
||||
})));
|
||||
setUserCollectionOffset(PAGE_SIZE);
|
||||
|
||||
// Calculate total value (lightweight query from database)
|
||||
const totalValue = await getCollectionTotalValue(userId);
|
||||
setUserCollectionTotalValue(totalValue);
|
||||
} catch (error) {
|
||||
console.error('Error loading collection:', error);
|
||||
setSelectedUserCollection([]);
|
||||
setUserCollectionTotalValue(0);
|
||||
} finally {
|
||||
setLoadingCollection(false);
|
||||
setIsLoadingUserTotalValue(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Load more cards for infinite scroll in user collection view
|
||||
const loadMoreUserCards = useCallback(async () => {
|
||||
if (!selectedUser || isLoadingMoreUserCards || !hasMoreUserCards) return;
|
||||
|
||||
try {
|
||||
setIsLoadingMoreUserCards(true);
|
||||
|
||||
const result = await getUserCollectionPaginated(
|
||||
selectedUser.id,
|
||||
PAGE_SIZE,
|
||||
userCollectionOffset
|
||||
);
|
||||
setHasMoreUserCards(result.hasMore);
|
||||
|
||||
if (result.items.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cardIds = Array.from(result.items.keys());
|
||||
const cards = await getCardsByIds(cardIds);
|
||||
|
||||
const newCards = cards.map(card => ({
|
||||
card,
|
||||
quantity: result.items.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
// Deduplicate: only add cards that aren't already in the collection
|
||||
setSelectedUserCollection(prev => {
|
||||
const existingIds = new Set(prev.map(item => item.card.id));
|
||||
const uniqueNewCards = newCards.filter(item => !existingIds.has(item.card.id));
|
||||
return [...prev, ...uniqueNewCards];
|
||||
});
|
||||
|
||||
setUserCollectionOffset(prev => prev + PAGE_SIZE);
|
||||
} catch (error) {
|
||||
console.error('Error loading more cards:', error);
|
||||
} finally {
|
||||
setIsLoadingMoreUserCards(false);
|
||||
}
|
||||
}, [selectedUser, userCollectionOffset, hasMoreUserCards, isLoadingMoreUserCards]);
|
||||
|
||||
// Intersection Observer for infinite scroll in user collection view
|
||||
useEffect(() => {
|
||||
if (!selectedUser) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0].isIntersecting && hasMoreUserCards && !isLoadingMoreUserCards) {
|
||||
loadMoreUserCards();
|
||||
}
|
||||
},
|
||||
{ threshold: 0.1 }
|
||||
);
|
||||
|
||||
const currentTarget = userCollectionObserverTarget.current;
|
||||
if (currentTarget) {
|
||||
observer.observe(currentTarget);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (currentTarget) {
|
||||
observer.unobserve(currentTarget);
|
||||
}
|
||||
};
|
||||
}, [selectedUser, hasMoreUserCards, isLoadingMoreUserCards, loadMoreUserCards]);
|
||||
|
||||
// Subscribe to realtime updates for selected user's collection total value
|
||||
useEffect(() => {
|
||||
if (!selectedUser) return;
|
||||
|
||||
const userProfileChannel = supabase
|
||||
.channel(`user-profile-value-${selectedUser.id}`)
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'UPDATE',
|
||||
schema: 'public',
|
||||
table: 'profiles',
|
||||
filter: `id=eq.${selectedUser.id}`,
|
||||
},
|
||||
(payload: any) => {
|
||||
if (payload.new?.collection_total_value !== undefined) {
|
||||
console.log(`User ${selectedUser.username}'s collection total value updated:`, payload.new.collection_total_value);
|
||||
setUserCollectionTotalValue(payload.new.collection_total_value);
|
||||
}
|
||||
}
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return () => {
|
||||
supabase.removeChannel(userProfileChannel);
|
||||
};
|
||||
}, [selectedUser]);
|
||||
|
||||
// ============ FRIENDS FUNCTIONS ============
|
||||
const loadFriendsData = async () => {
|
||||
if (!user) return;
|
||||
@@ -532,74 +696,313 @@ export default function Community() {
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="bg-gray-900 text-white min-h-screen">
|
||||
{/* Header */}
|
||||
<div className="sticky top-0 bg-gray-900/95 backdrop-blur border-b border-gray-800 p-3 z-10">
|
||||
<div className="flex items-center justify-between gap-2 mb-3">
|
||||
<div className="relative bg-gray-900 text-white min-h-screen">
|
||||
<div className="max-w-7xl mx-auto p-3 sm:p-6">
|
||||
{/* Header with Back and Trade buttons */}
|
||||
<div className="flex items-center justify-between gap-2 mb-4 md:mb-6">
|
||||
<button
|
||||
onClick={() => { setSelectedUser(null); setSelectedUserCollection([]); setUserCollectionSearch(''); }}
|
||||
className="flex items-center gap-1 text-blue-400 text-sm min-w-0"
|
||||
onClick={() => {
|
||||
setSelectedUser(null);
|
||||
setSelectedUserCollection([]);
|
||||
setUserCollectionSearch('');
|
||||
setSelectedUserCard(null);
|
||||
setHoveredUserCard(null);
|
||||
}}
|
||||
className="flex items-center gap-1 text-blue-400 hover:text-blue-300 text-sm"
|
||||
>
|
||||
<ChevronLeft size={20} />
|
||||
<span className="hidden sm:inline">Back</span>
|
||||
<span>Back</span>
|
||||
</button>
|
||||
<h1 className="text-lg font-bold truncate flex-1 text-center">{selectedUser.username}</h1>
|
||||
<h1 className="text-2xl md:text-3xl font-bold truncate flex-1 text-center">{selectedUser.username}'s Collection</h1>
|
||||
<button
|
||||
onClick={() => setShowTradeCreator(true)}
|
||||
className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm whitespace-nowrap"
|
||||
className="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm whitespace-nowrap"
|
||||
>
|
||||
<ArrowLeftRight size={16} />
|
||||
<span className="hidden sm:inline">Trade</span>
|
||||
<span className="hidden sm:inline">Propose Trade</span>
|
||||
<span className="sm:hidden">Trade</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Search input */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
|
||||
<input
|
||||
type="text"
|
||||
value={userCollectionSearch}
|
||||
onChange={(e) => setUserCollectionSearch(e.target.value)}
|
||||
placeholder="Search cards..."
|
||||
className="w-full pl-9 pr-8 py-2 bg-gray-700 border border-gray-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
{userCollectionSearch && (
|
||||
<button
|
||||
onClick={() => setUserCollectionSearch('')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
<div className="mb-8">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
|
||||
<input
|
||||
type="text"
|
||||
value={userCollectionSearch}
|
||||
onChange={(e) => setUserCollectionSearch(e.target.value)}
|
||||
placeholder="Search cards by name, type, or text..."
|
||||
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Collection */}
|
||||
<div>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{userCollectionSearch
|
||||
? `Found ${filteredUserCollection.length} card(s)`
|
||||
: `Cards (${selectedUserCollection.length} unique, ${selectedUserCollection.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">
|
||||
{userCollectionSearch ? 'Filtered Value' : 'Total Collection Value'}
|
||||
</div>
|
||||
<div className="text-lg font-bold text-green-400">
|
||||
{isLoadingUserTotalValue ? (
|
||||
<Loader2 className="animate-spin" size={20} />
|
||||
) : userCollectionSearch ? (
|
||||
// For search results, calculate from filtered collection
|
||||
`$${filteredUserCollection.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
|
||||
`$${userCollectionTotalValue.toFixed(2)}`
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loadingCollection ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||
</div>
|
||||
) : selectedUserCollection.length === 0 ? (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<p className="text-lg">Empty collection</p>
|
||||
</div>
|
||||
) : filteredUserCollection.length === 0 ? (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<p className="text-lg mb-2">No cards found</p>
|
||||
<p className="text-sm">Try a different search term</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 xl:grid-cols-10 gap-1.5 sm:gap-2">
|
||||
{filteredUserCollection.map(({ card, quantity }) => {
|
||||
const currentFaceIndex = getCurrentFaceIndex(card.id);
|
||||
const isMultiFaced = isDoubleFaced(card);
|
||||
const displayName = isMultiFaced && card.card_faces
|
||||
? card.card_faces[currentFaceIndex]?.name || card.name
|
||||
: card.name;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={card.id}
|
||||
className="relative group cursor-pointer"
|
||||
onMouseEnter={() => setHoveredUserCard(card)}
|
||||
onMouseLeave={() => setHoveredUserCard(null)}
|
||||
onClick={() => setSelectedUserCard({ card, quantity })}
|
||||
>
|
||||
{/* Card thumbnail */}
|
||||
<div className="relative rounded-lg overflow-hidden shadow-lg transition-all group-hover:ring-2 group-hover:ring-blue-500">
|
||||
<img
|
||||
src={getCardImageUri(card, currentFaceIndex)}
|
||||
alt={displayName}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{/* Quantity badge */}
|
||||
<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
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleCardFace(card.id, card.card_faces!.length);
|
||||
}}
|
||||
className="absolute bottom-1 right-1 bg-purple-600 hover:bg-purple-700 text-white p-1 rounded-full shadow-lg transition-all"
|
||||
title="Flip card"
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Card name below thumbnail */}
|
||||
<div className="mt-1 text-xs text-center truncate px-1">
|
||||
{displayName}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Infinite scroll loading indicator */}
|
||||
{!userCollectionSearch && isLoadingMoreUserCards && (
|
||||
<div className="flex justify-center py-8">
|
||||
<Loader2 className="animate-spin text-blue-500" size={32} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Observer target for infinite scroll */}
|
||||
{!userCollectionSearch && hasMoreUserCards && !isLoadingMoreUserCards && (
|
||||
<div ref={userCollectionObserverTarget} className="h-20" />
|
||||
)}
|
||||
|
||||
{/* End of collection indicator */}
|
||||
{!userCollectionSearch && !hasMoreUserCards && selectedUserCollection.length > 0 && (
|
||||
<div className="text-center py-8 text-gray-500 text-sm">
|
||||
End of collection • {userCollectionTotalCount} total cards
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Collection Grid */}
|
||||
<div className="p-3">
|
||||
{loadingCollection ? (
|
||||
<div className="flex justify-center py-12">
|
||||
<Loader2 className="animate-spin text-blue-500" size={32} />
|
||||
</div>
|
||||
) : selectedUserCollection.length === 0 ? (
|
||||
<p className="text-gray-400 text-center py-12">Empty collection</p>
|
||||
) : filteredUserCollection.length === 0 ? (
|
||||
<p className="text-gray-400 text-center py-12">No cards match "{userCollectionSearch}"</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
|
||||
{filteredUserCollection.map(({ card, quantity }) => (
|
||||
<div key={card.id} className="relative">
|
||||
{/* Hover Card Preview - desktop only, only show if no card is selected */}
|
||||
{hoveredUserCard && !selectedUserCard && (() => {
|
||||
const currentFaceIndex = getCurrentFaceIndex(hoveredUserCard.id);
|
||||
const isMultiFaced = isDoubleFaced(hoveredUserCard);
|
||||
const currentFace = isMultiFaced && hoveredUserCard.card_faces
|
||||
? hoveredUserCard.card_faces[currentFaceIndex]
|
||||
: null;
|
||||
|
||||
const displayName = currentFace?.name || hoveredUserCard.name;
|
||||
const displayTypeLine = currentFace?.type_line || hoveredUserCard.type_line;
|
||||
const displayOracleText = currentFace?.oracle_text || hoveredUserCard.oracle_text;
|
||||
|
||||
return (
|
||||
<div className="hidden lg:block fixed top-1/2 right-8 transform -translate-y-1/2 z-30 pointer-events-none">
|
||||
<div className="bg-gray-800 rounded-lg shadow-2xl p-4 max-w-md">
|
||||
<div className="relative">
|
||||
<img
|
||||
src={card.image_uris?.small || card.image_uris?.normal}
|
||||
alt={card.name}
|
||||
className="w-full h-auto rounded-lg"
|
||||
src={getCardLargeImageUri(hoveredUserCard, currentFaceIndex)}
|
||||
alt={displayName}
|
||||
className="w-full h-auto rounded-lg shadow-lg"
|
||||
/>
|
||||
<span className="absolute top-1 right-1 bg-blue-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full">
|
||||
x{quantity}
|
||||
</span>
|
||||
{isMultiFaced && (
|
||||
<div className="absolute top-2 right-2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg">
|
||||
Face {currentFaceIndex + 1}/{hoveredUserCard.card_faces!.length}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<div className="mt-3 space-y-2">
|
||||
<h3 className="text-xl font-bold">{displayName}</h3>
|
||||
<p className="text-sm text-gray-400">{displayTypeLine}</p>
|
||||
{displayOracleText && (
|
||||
<p className="text-sm text-gray-300 border-t border-gray-700 pt-2">
|
||||
{displayOracleText}
|
||||
</p>
|
||||
)}
|
||||
{hoveredUserCard.prices?.usd && (
|
||||
<div className="text-sm text-green-400 font-semibold border-t border-gray-700 pt-2">
|
||||
${hoveredUserCard.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Card Detail Panel - slides in from right */}
|
||||
{selectedUserCard && (() => {
|
||||
const currentFaceIndex = getCurrentFaceIndex(selectedUserCard.card.id);
|
||||
const isMultiFaced = isDoubleFaced(selectedUserCard.card);
|
||||
const currentFace = isMultiFaced && selectedUserCard.card.card_faces
|
||||
? selectedUserCard.card.card_faces[currentFaceIndex]
|
||||
: null;
|
||||
|
||||
const displayName = currentFace?.name || selectedUserCard.card.name;
|
||||
const displayTypeLine = currentFace?.type_line || selectedUserCard.card.type_line;
|
||||
const displayOracleText = currentFace?.oracle_text || selectedUserCard.card.oracle_text;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="fixed inset-0 bg-black bg-opacity-50 z-[110] transition-opacity duration-300"
|
||||
onClick={() => setSelectedUserCard(null)}
|
||||
/>
|
||||
|
||||
{/* Sliding Panel */}
|
||||
<div className="fixed top-0 right-0 h-full w-full md:w-96 bg-gray-800 shadow-2xl z-[120] overflow-y-auto animate-slide-in-right">
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={() => setSelectedUserCard(null)}
|
||||
className="fixed top-4 right-4 bg-gray-700 hover:bg-gray-600 text-white p-2 md:p-1.5 rounded-full transition-colors z-[130] shadow-lg"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X size={24} className="md:w-5 md:h-5" />
|
||||
</button>
|
||||
|
||||
<div className="p-4 sm:p-6">
|
||||
{/* Card Image */}
|
||||
<div className="relative mb-4 max-w-sm mx-auto">
|
||||
<img
|
||||
src={getCardLargeImageUri(selectedUserCard.card, currentFaceIndex)}
|
||||
alt={displayName}
|
||||
className="w-full h-auto rounded-lg shadow-lg"
|
||||
/>
|
||||
{isMultiFaced && (
|
||||
<>
|
||||
<div className="absolute top-2 right-2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg">
|
||||
Face {currentFaceIndex + 1}/{selectedUserCard.card.card_faces!.length}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => toggleCardFace(selectedUserCard.card.id, selectedUserCard.card.card_faces!.length)}
|
||||
className="absolute bottom-2 right-2 bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-lg transition-all"
|
||||
title="Flip card"
|
||||
>
|
||||
<RefreshCw size={20} />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Card Info */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-xl md:text-2xl font-bold text-white mb-2">{displayName}</h2>
|
||||
<p className="text-xs sm:text-sm text-gray-400">{displayTypeLine}</p>
|
||||
</div>
|
||||
|
||||
{displayOracleText && (
|
||||
<div className="border-t border-gray-700 pt-3">
|
||||
<p className="text-sm text-gray-300">{displayOracleText}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedUserCard.card.prices?.usd && (
|
||||
<div className="border-t border-gray-700 pt-3">
|
||||
<div className="text-lg text-green-400 font-semibold">
|
||||
${selectedUserCard.card.prices.usd} each
|
||||
</div>
|
||||
<div className="text-sm text-gray-400">
|
||||
Total value: ${(parseFloat(selectedUserCard.card.prices.usd) * selectedUserCard.quantity).toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quantity Display */}
|
||||
<div className="border-t border-gray-700 pt-3">
|
||||
<h3 className="text-lg font-semibold mb-3">Quantity in Collection</h3>
|
||||
<div className="flex items-center justify-center bg-gray-900 rounded-lg p-4">
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold">{selectedUserCard.quantity}</div>
|
||||
<div className="text-xs text-gray-400">copies</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
|
||||
{showTradeCreator && (
|
||||
<TradeCreator
|
||||
@@ -1009,9 +1412,14 @@ export default function Community() {
|
||||
With: <strong>{otherUser?.username}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<span className={`text-xs capitalize ${statusColors[trade.status]}`}>
|
||||
{trade.status}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{trade.status === 'pending' && !trade.is_valid && (
|
||||
<AlertTriangle size={14} className="text-red-400" title="Trade no longer valid" />
|
||||
)}
|
||||
<span className={`text-xs capitalize ${statusColors[trade.status]}`}>
|
||||
{trade.status}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Items */}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History } 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, TradeHistoryEntry, getTradeVersionHistory } from '../services/tradesService';
|
||||
@@ -222,6 +222,18 @@ export default function TradeDetail({
|
||||
</div>
|
||||
) : (
|
||||
<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>
|
||||
)}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Your Side */}
|
||||
<div className="space-y-3">
|
||||
@@ -367,8 +379,9 @@ export default function TradeDetail({
|
||||
<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} />
|
||||
@@ -431,8 +444,9 @@ export default function TradeDetail({
|
||||
<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} />
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface Trade {
|
||||
updated_at: string | null;
|
||||
version: number;
|
||||
editor_id: string | null;
|
||||
is_valid: boolean;
|
||||
user1?: { username: string | null };
|
||||
user2?: { username: string | null };
|
||||
items?: TradeItem[];
|
||||
@@ -160,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,
|
||||
});
|
||||
|
||||
@@ -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';
|
||||
Reference in New Issue
Block a user