Merge pull request 'feature/trade-fix' (#13) from feature/trade-fix into master

Reviewed-on: #13
This commit was merged in pull request #13.
This commit is contained in:
2025-11-27 11:28:02 +01:00
10 changed files with 1330 additions and 352 deletions

View File

@@ -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, "enableAllProjectMcpServers": true,
"enabledMcpjsonServers": [ "enabledMcpjsonServers": [
"supabase" "supabase"
],
"permissions": {
"allow": [
"mcp__supabase__apply_migration"
] ]
} }
}

View File

@@ -82,7 +82,7 @@ define(['./workbox-ca84f546'], (function (workbox) { 'use strict';
"revision": "3ca0b8505b4bec776b69afdba2768812" "revision": "3ca0b8505b4bec776b69afdba2768812"
}, { }, {
"url": "index.html", "url": "index.html",
"revision": "0.ufhads5pjvs" "revision": "0.vigoqq958cg"
}], {}); }], {});
workbox.cleanupOutdatedCaches(); workbox.cleanupOutdatedCaches();
workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), { workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), {

View File

@@ -73,6 +73,8 @@ export default function Community() {
const [friendSearch, setFriendSearch] = useState(''); const [friendSearch, setFriendSearch] = useState('');
const [friendSearchResults, setFriendSearchResults] = useState<{ id: string; username: string | null }[]>([]); const [friendSearchResults, setFriendSearchResults] = useState<{ id: string; username: string | null }[]>([]);
const [searchingFriends, setSearchingFriends] = useState(false); const [searchingFriends, setSearchingFriends] = useState(false);
const [friendListFilter, setFriendListFilter] = useState('');
const [requestsFilter, setRequestsFilter] = useState('');
// Trades state // Trades state
const [tradesSubTab, setTradesSubTab] = useState<TradesSubTab>('pending'); const [tradesSubTab, setTradesSubTab] = useState<TradesSubTab>('pending');
@@ -81,12 +83,6 @@ export default function Community() {
const [tradeCardDetails, setTradeCardDetails] = useState<Map<string, Card>>(new Map()); const [tradeCardDetails, setTradeCardDetails] = useState<Map<string, Card>>(new Map());
const [processingTradeId, setProcessingTradeId] = useState<string | null>(null); const [processingTradeId, setProcessingTradeId] = useState<string | null>(null);
const [selectedTrade, setSelectedTrade] = useState<Trade | null>(null); const [selectedTrade, setSelectedTrade] = useState<Trade | null>(null);
const [counterOfferData, setCounterOfferData] = useState<{
receiverId: string;
receiverUsername: string;
receiverCollection: CollectionItem[];
initialOffer?: { senderCards: Card[]; receiverCards: Card[] };
} | null>(null);
// Profile state // Profile state
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
@@ -108,6 +104,126 @@ export default function Community() {
} }
}, [user]); }, [user]);
// ============ REALTIME SUBSCRIPTIONS ============
// Subscribe to trade changes
useEffect(() => {
if (!user) return;
const tradesChannel = supabase
.channel('trades-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'trades',
},
(payload: any) => {
// Filter for trades involving this user
const newData = payload.new || payload.old;
if (newData && (newData.user1_id === user.id || newData.user2_id === user.id)) {
console.log('Trade change:', payload);
loadTradesData();
}
}
)
.subscribe();
return () => {
supabase.removeChannel(tradesChannel);
};
}, [user]);
// Subscribe to friendship changes
useEffect(() => {
if (!user) return;
const friendshipsChannel = supabase
.channel('friendships-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'friendships',
},
(payload: any) => {
// Filter for friendships involving this user
const newData = payload.new || payload.old;
if (newData && (newData.requester_id === user.id || newData.addressee_id === user.id)) {
console.log('Friendship change:', payload);
loadFriendsData();
}
}
)
.subscribe();
return () => {
supabase.removeChannel(friendshipsChannel);
};
}, [user]);
// Subscribe to profile changes (for visibility updates)
useEffect(() => {
if (!user) return;
const profilesChannel = supabase
.channel('profiles-changes')
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'profiles',
},
(payload: any) => {
console.log('Profile change:', payload);
// Reload public users if a profile's visibility changed
if (payload.new && payload.old && payload.new.collection_visibility !== payload.old.collection_visibility) {
loadPublicUsers();
}
// Reload own profile if it's the current user
if (payload.new && payload.new.id === user.id) {
loadProfile();
}
}
)
.subscribe();
return () => {
supabase.removeChannel(profilesChannel);
};
}, [user]);
// Subscribe to collection changes when viewing someone's collection
useEffect(() => {
if (!user || !selectedUser) return;
const collectionsChannel = supabase
.channel(`collections-${selectedUser.id}`)
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
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);
loadUserCollection(selectedUser.id);
}
}
)
.subscribe();
return () => {
supabase.removeChannel(collectionsChannel);
};
}, [user, selectedUser]);
const loadAllData = async () => { const loadAllData = async () => {
if (!user) return; if (!user) return;
setLoading(true); setLoading(true);
@@ -318,37 +434,6 @@ export default function Community() {
}); });
}; };
const handleCounterOffer = async (trade: Trade, senderCards: Card[], receiverCards: Card[]) => {
try {
// Decline the original trade
await declineTrade(trade.id);
// Load the sender's collection for the counter-offer
const collectionMap = await getUserCollection(trade.sender_id);
const cardIds = Array.from(collectionMap.keys());
const cards = await getCardsByIds(cardIds);
const senderCollection = cards.map((card) => ({
card,
quantity: collectionMap.get(card.id) || 0,
}));
// Set up counter-offer data (swap sender and receiver)
setCounterOfferData({
receiverId: trade.sender_id,
receiverUsername: trade.sender?.username || 'User',
receiverCollection: senderCollection,
initialOffer: {
senderCards: receiverCards, // What you want to give back
receiverCards: senderCards, // What you want to receive
},
});
await loadTradesData();
} catch (error) {
console.error('Error setting up counter-offer:', error);
toast.error('Failed to set up counter-offer');
}
};
// ============ PROFILE FUNCTIONS ============ // ============ PROFILE FUNCTIONS ============
const loadProfile = async () => { const loadProfile = async () => {
@@ -539,13 +624,13 @@ export default function Community() {
// ============ MAIN VIEW ============ // ============ MAIN VIEW ============
return ( return (
<div className="relative bg-gray-900 text-white md:min-h-screen"> <div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
<div className="max-w-7xl mx-auto">
{/* Header */} {/* Header */}
<div className="sticky top-0 bg-gray-900/95 backdrop-blur border-b border-gray-800 p-3 z-10"> <h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Community</h1>
<h1 className="text-xl font-bold mb-3">Community</h1>
{/* Tabs - Scrollable on mobile */} {/* Tabs */}
<div className="flex gap-1 overflow-x-auto pb-1 -mx-3 px-3 scrollbar-hide"> <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide mb-4 md:mb-6">
{[ {[
{ id: 'browse' as Tab, label: 'Browse', icon: Globe }, { id: 'browse' as Tab, label: 'Browse', icon: Globe },
{ id: 'friends' as Tab, label: `Friends`, count: friends.length, icon: Users }, { id: 'friends' as Tab, label: `Friends`, count: friends.length, icon: Users },
@@ -573,10 +658,7 @@ export default function Community() {
</button> </button>
))} ))}
</div> </div>
</div>
{/* Content */}
<div className="p-3">
{/* ============ BROWSE TAB ============ */} {/* ============ BROWSE TAB ============ */}
{activeTab === 'browse' && ( {activeTab === 'browse' && (
<div className="space-y-3"> <div className="space-y-3">
@@ -675,11 +757,38 @@ export default function Community() {
{/* Friends List */} {/* Friends List */}
{friendsSubTab === 'list' && ( {friendsSubTab === 'list' && (
friends.length === 0 ? ( <div className="space-y-3">
{/* 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={friendListFilter}
onChange={(e) => setFriendListFilter(e.target.value)}
placeholder="Search friends..."
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"
/>
{friendListFilter && (
<button
onClick={() => setFriendListFilter('')}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
>
<X size={16} />
</button>
)}
</div>
{friends.length === 0 ? (
<p className="text-gray-400 text-center py-8 text-sm">No friends yet</p> <p className="text-gray-400 text-center py-8 text-sm">No friends yet</p>
) : friends.filter((f) =>
!friendListFilter || f.username?.toLowerCase().includes(friendListFilter.toLowerCase())
).length === 0 ? (
<p className="text-gray-400 text-center py-8 text-sm">No friends match "{friendListFilter}"</p>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
{friends.map((friend) => ( {friends
.filter((f) => !friendListFilter || f.username?.toLowerCase().includes(friendListFilter.toLowerCase()))
.map((friend) => (
<div key={friend.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg"> <div key={friend.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg">
<span className="font-medium truncate">{friend.username || 'Unknown'}</span> <span className="font-medium truncate">{friend.username || 'Unknown'}</span>
<div className="flex gap-1"> <div className="flex gap-1">
@@ -702,17 +811,48 @@ export default function Community() {
</div> </div>
))} ))}
</div> </div>
) )}
</div>
)} )}
{/* Requests */} {/* Requests */}
{friendsSubTab === 'requests' && ( {friendsSubTab === 'requests' && (
<div className="space-y-4"> <div className="space-y-3">
{pendingRequests.length > 0 && ( {/* 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={requestsFilter}
onChange={(e) => setRequestsFilter(e.target.value)}
placeholder="Search requests..."
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"
/>
{requestsFilter && (
<button
onClick={() => setRequestsFilter('')}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
>
<X size={16} />
</button>
)}
</div>
{(() => {
const filteredPending = pendingRequests.filter((r) =>
!requestsFilter || r.username?.toLowerCase().includes(requestsFilter.toLowerCase())
);
const filteredSent = sentRequests.filter((r) =>
!requestsFilter || r.username?.toLowerCase().includes(requestsFilter.toLowerCase())
);
return (
<>
{filteredPending.length > 0 && (
<div> <div>
<p className="text-xs text-gray-500 mb-2">Received</p> <p className="text-xs text-gray-500 mb-2">Received</p>
<div className="space-y-2"> <div className="space-y-2">
{pendingRequests.map((req) => ( {filteredPending.map((req) => (
<div key={req.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg"> <div key={req.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg">
<span className="font-medium truncate">{req.username || 'Unknown'}</span> <span className="font-medium truncate">{req.username || 'Unknown'}</span>
<div className="flex gap-1"> <div className="flex gap-1">
@@ -729,11 +869,11 @@ export default function Community() {
</div> </div>
)} )}
{sentRequests.length > 0 && ( {filteredSent.length > 0 && (
<div> <div>
<p className="text-xs text-gray-500 mb-2">Sent</p> <p className="text-xs text-gray-500 mb-2">Sent</p>
<div className="space-y-2"> <div className="space-y-2">
{sentRequests.map((req) => ( {filteredSent.map((req) => (
<div key={req.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg"> <div key={req.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Send size={14} className="text-gray-500" /> <Send size={14} className="text-gray-500" />
@@ -749,6 +889,14 @@ export default function Community() {
{pendingRequests.length === 0 && sentRequests.length === 0 && ( {pendingRequests.length === 0 && sentRequests.length === 0 && (
<p className="text-gray-400 text-center py-8 text-sm">No requests</p> <p className="text-gray-400 text-center py-8 text-sm">No requests</p>
)} )}
{(pendingRequests.length > 0 || sentRequests.length > 0) &&
filteredPending.length === 0 && filteredSent.length === 0 && (
<p className="text-gray-400 text-center py-8 text-sm">No requests match "{requestsFilter}"</p>
)}
</>
);
})()}
</div> </div>
)} )}
@@ -831,8 +979,10 @@ export default function Community() {
) : ( ) : (
<div className="space-y-3"> <div className="space-y-3">
{(tradesSubTab === 'pending' ? pendingTrades : tradeHistory).map((trade) => { {(tradesSubTab === 'pending' ? pendingTrades : tradeHistory).map((trade) => {
const isSender = trade.sender_id === user?.id; const isUser1 = trade.user1_id === user?.id;
const otherUser = isSender ? trade.receiver : trade.sender; const myUserId = user?.id || '';
const otherUserId = isUser1 ? trade.user2_id : trade.user1_id;
const otherUser = isUser1 ? trade.user2 : trade.user1;
const statusColors: Record<string, string> = { const statusColors: Record<string, string> = {
accepted: 'text-green-400', accepted: 'text-green-400',
declined: 'text-red-400', declined: 'text-red-400',
@@ -840,7 +990,8 @@ export default function Community() {
pending: 'text-yellow-400', pending: 'text-yellow-400',
}; };
const canViewDetails = !isSender && trade.status === 'pending'; // Both users can view details for pending trades
const canViewDetails = trade.status === 'pending';
return ( return (
<div <div
@@ -855,7 +1006,7 @@ export default function Community() {
<div className="flex items-center gap-2 min-w-0"> <div className="flex items-center gap-2 min-w-0">
<ArrowLeftRight size={16} className="text-blue-400 flex-shrink-0" /> <ArrowLeftRight size={16} className="text-blue-400 flex-shrink-0" />
<span className="text-sm truncate"> <span className="text-sm truncate">
{isSender ? 'To' : 'From'}: <strong>{otherUser?.username}</strong> With: <strong>{otherUser?.username}</strong>
</span> </span>
</div> </div>
<span className={`text-xs capitalize ${statusColors[trade.status]}`}> <span className={`text-xs capitalize ${statusColors[trade.status]}`}>
@@ -865,8 +1016,8 @@ export default function Community() {
{/* Items */} {/* Items */}
<div className="grid grid-cols-2 gap-2 text-sm"> <div className="grid grid-cols-2 gap-2 text-sm">
{renderTradeItems(trade.items, trade.sender_id, isSender ? 'Give' : 'Receive')} {renderTradeItems(trade.items, myUserId, 'You Give')}
{renderTradeItems(trade.items, trade.receiver_id, isSender ? 'Get' : 'Send')} {renderTradeItems(trade.items, otherUserId, 'You Get')}
</div> </div>
{canViewDetails && ( {canViewDetails && (
@@ -875,8 +1026,8 @@ export default function Community() {
</p> </p>
)} )}
{/* Actions - Only show quick actions for sender (cancel) */} {/* Actions - Allow any user to cancel pending trade */}
{tradesSubTab === 'pending' && isSender && ( {tradesSubTab === 'pending' && (
<div className="flex gap-2 pt-2 border-t border-gray-700" onClick={(e) => e.stopPropagation()}> <div className="flex gap-2 pt-2 border-t border-gray-700" onClick={(e) => e.stopPropagation()}>
<button <button
onClick={() => handleCancelTrade(trade.id)} onClick={() => handleCancelTrade(trade.id)}
@@ -941,7 +1092,6 @@ export default function Community() {
</button> </button>
</div> </div>
)} )}
</div>
{/* Trade Detail Modal */} {/* Trade Detail Modal */}
{selectedTrade && ( {selectedTrade && (
@@ -950,21 +1100,9 @@ export default function Community() {
onClose={() => setSelectedTrade(null)} onClose={() => setSelectedTrade(null)}
onAccept={handleAcceptTrade} onAccept={handleAcceptTrade}
onDecline={handleDeclineTrade} onDecline={handleDeclineTrade}
onCounterOffer={handleCounterOffer} onTradeUpdated={() => {
/> setSelectedTrade(null);
)}
{/* Counter Offer Creator */}
{counterOfferData && (
<TradeCreator
receiverId={counterOfferData.receiverId}
receiverUsername={counterOfferData.receiverUsername}
receiverCollection={counterOfferData.receiverCollection}
onClose={() => setCounterOfferData(null)}
onTradeCreated={() => {
setCounterOfferData(null);
loadTradesData(); loadTradesData();
toast.success('Counter offer sent!');
}} }}
/> />
)} )}
@@ -979,5 +1117,6 @@ export default function Community() {
variant={confirmModal.variant} variant={confirmModal.variant}
/> />
</div> </div>
</div>
); );
} }

View File

@@ -3,7 +3,7 @@ import { X, ArrowLeftRight, ArrowRight, ArrowLeft, Minus, Send, Gift, Loader2, S
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { useToast } from '../contexts/ToastContext'; import { useToast } from '../contexts/ToastContext';
import { getUserCollection, getCardsByIds } from '../services/api'; import { getUserCollection, getCardsByIds } from '../services/api';
import { createTrade } from '../services/tradesService'; import { createTrade, updateTrade } from '../services/tradesService';
import { Card } from '../types'; import { Card } from '../types';
interface CollectionItem { interface CollectionItem {
@@ -182,6 +182,11 @@ interface TradeCreatorProps {
receiverCollection: CollectionItem[]; receiverCollection: CollectionItem[];
onClose: () => void; onClose: () => void;
onTradeCreated: () => void; onTradeCreated: () => void;
editMode?: boolean;
existingTradeId?: string;
initialSenderCards?: Card[];
initialReceiverCards?: Card[];
initialMessage?: string;
} }
type MobileStep = 'want' | 'give' | 'review'; type MobileStep = 'want' | 'give' | 'review';
@@ -192,13 +197,18 @@ export default function TradeCreator({
receiverCollection, receiverCollection,
onClose, onClose,
onTradeCreated, onTradeCreated,
editMode = false,
existingTradeId,
initialSenderCards = [],
initialReceiverCards = [],
initialMessage = '',
}: TradeCreatorProps) { }: TradeCreatorProps) {
const { user } = useAuth(); const { user } = useAuth();
const toast = useToast(); const toast = useToast();
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]); const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState(''); const [message, setMessage] = useState(initialMessage);
const [isGiftMode, setIsGiftMode] = useState(false); const [isGiftMode, setIsGiftMode] = useState(false);
const [mobileStep, setMobileStep] = useState<MobileStep>('want'); const [mobileStep, setMobileStep] = useState<MobileStep>('want');
@@ -222,6 +232,57 @@ export default function TradeCreator({
} }
}, [isGiftMode]); }, [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 () => { const loadMyCollection = async () => {
if (!user) return; if (!user) return;
setLoading(true); setLoading(true);
@@ -314,28 +375,42 @@ export default function TradeCreator({
setSubmitting(true); setSubmitting(true);
try { try {
const senderCards = Array.from(myOfferedCards.values()).map((item) => ({ const myCards = Array.from(myOfferedCards.values()).map((item) => ({
cardId: item.card.id, cardId: item.card.id,
quantity: item.quantity, quantity: item.quantity,
})); }));
const receiverCards = Array.from(wantedCards.values()).map((item) => ({ const theirCards = Array.from(wantedCards.values()).map((item) => ({
cardId: item.card.id, cardId: item.card.id,
quantity: item.quantity, quantity: item.quantity,
})); }));
await createTrade({ if (editMode && existingTradeId) {
senderId: user.id, // Update existing trade
receiverId, await updateTrade({
tradeId: existingTradeId,
editorId: user.id,
message: message || undefined, message: message || undefined,
senderCards, myCards,
receiverCards, 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(); onTradeCreated();
} catch (error) { } catch (error) {
console.error('Error creating trade:', error); console.error('Error with trade:', error);
toast.error('Failed to create trade'); toast.error(editMode ? 'Failed to update trade' : 'Failed to create trade');
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -487,12 +562,6 @@ export default function TradeCreator({
placeholder="Add a message..." 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" 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>
</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 justify-between p-4 border-b border-gray-700">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<ArrowLeftRight size={24} className="text-blue-400" /> <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"> <label className="flex items-center gap-2 ml-4 cursor-pointer">
<div <div
className={`relative w-10 h-5 rounded-full transition-colors ${ className={`relative w-10 h-5 rounded-full transition-colors ${
@@ -638,23 +707,14 @@ export default function TradeCreator({
)} )}
</div> </div>
<div className="space-y-2 mb-4"> <div className="flex items-center gap-4 mb-4">
<input <input
type="text" type="text"
value={message} value={message}
onChange={(e) => setMessage(e.target.value)} onChange={(e) => setMessage(e.target.value)}
placeholder="Add a message (optional)" 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 <button
onClick={onClose} onClick={onClose}
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition" className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition"

View File

@@ -1,17 +1,18 @@
import React, { useState, useEffect } from 'react'; 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 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { useToast } from '../contexts/ToastContext'; 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 { Card } from '../types';
import { getCardsByIds } from '../services/api'; import TradeCreator from './TradeCreator';
interface TradeDetailProps { interface TradeDetailProps {
trade: Trade; trade: Trade;
onClose: () => void; onClose: () => void;
onAccept: (tradeId: string) => Promise<void>; onAccept: (tradeId: string) => Promise<void>;
onDecline: (tradeId: string) => Promise<void>; onDecline: (tradeId: string) => Promise<void>;
onCounterOffer: (trade: Trade, senderCards: Card[], receiverCards: Card[]) => void; onTradeUpdated: () => void;
} }
interface TradeCardItem { interface TradeCardItem {
@@ -19,6 +20,11 @@ interface TradeCardItem {
quantity: number; quantity: number;
} }
interface CollectionItem {
card: Card;
quantity: number;
}
function calculateTotalPrice(items: TradeCardItem[]): number { function calculateTotalPrice(items: TradeCardItem[]): number {
return items.reduce((total, { card, quantity }) => { return items.reduce((total, { card, quantity }) => {
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0; const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
@@ -31,7 +37,7 @@ export default function TradeDetail({
onClose, onClose,
onAccept, onAccept,
onDecline, onDecline,
onCounterOffer, onTradeUpdated,
}: TradeDetailProps) { }: TradeDetailProps) {
const { user } = useAuth(); const { user } = useAuth();
const toast = useToast(); const toast = useToast();
@@ -39,13 +45,20 @@ export default function TradeDetail({
const [processing, setProcessing] = useState(false); const [processing, setProcessing] = useState(false);
const [senderCards, setSenderCards] = useState<TradeCardItem[]>([]); const [senderCards, setSenderCards] = useState<TradeCardItem[]>([]);
const [receiverCards, setReceiverCards] = 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 isUser1 = trade.user1_id === user?.id;
const isReceiver = trade.receiver_id === user?.id; const isUser2 = trade.user2_id === user?.id;
const otherUser = isSender ? trade.receiver : trade.sender; const otherUser = isUser1 ? trade.user2 : trade.user1;
const myUserId = user?.id || '';
const otherUserId = isUser1 ? trade.user2_id : trade.user1_id;
useEffect(() => { useEffect(() => {
loadTradeCards(); loadTradeCards();
loadTradeHistory();
}, [trade]); }, [trade]);
const loadTradeCards = async () => { const loadTradeCards = async () => {
@@ -62,22 +75,22 @@ export default function TradeDetail({
const cardMap = new Map<string, Card>(); const cardMap = new Map<string, Card>();
cards.forEach(card => cardMap.set(card.id, card)); cards.forEach(card => cardMap.set(card.id, card));
const senderItems: TradeCardItem[] = []; const myItems: TradeCardItem[] = [];
const receiverItems: TradeCardItem[] = []; const theirItems: TradeCardItem[] = [];
trade.items?.forEach(item => { trade.items?.forEach(item => {
const card = cardMap.get(item.card_id); const card = cardMap.get(item.card_id);
if (!card) return; if (!card) return;
if (item.owner_id === trade.sender_id) { if (item.owner_id === myUserId) {
senderItems.push({ card, quantity: item.quantity }); myItems.push({ card, quantity: item.quantity });
} else { } else {
receiverItems.push({ card, quantity: item.quantity }); theirItems.push({ card, quantity: item.quantity });
} }
}); });
setSenderCards(senderItems); setSenderCards(myItems);
setReceiverCards(receiverItems); setReceiverCards(theirItems);
} catch (error) { } catch (error) {
console.error('Error loading trade cards:', error); console.error('Error loading trade cards:', error);
toast.error('Failed to load trade details'); 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 () => { const handleAccept = async () => {
setProcessing(true); setProcessing(true);
try { try {
@@ -110,20 +132,65 @@ export default function TradeDetail({
} }
}; };
const handleCounterOffer = () => { const handleEdit = async () => {
const senderCardsList = senderCards.map(item => item.card); try {
const receiverCardsList = receiverCards.map(item => item.card); // Load the other user's collection for editing
onCounterOffer(trade, senderCardsList, receiverCardsList); const collectionMap = await getUserCollection(otherUserId);
onClose(); 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); // In the symmetric model, counter-offer is the same as edit
const receiverPrice = calculateTotalPrice(receiverCards); const handleCounterOffer = handleEdit;
const yourCards = isSender ? senderCards : receiverCards; // senderCards = myCards, receiverCards = theirCards (already calculated correctly)
const theirCards = isSender ? receiverCards : senderCards; const yourCards = senderCards;
const yourPrice = isSender ? senderPrice : receiverPrice; const theirCards = receiverCards;
const theirPrice = isSender ? receiverPrice : senderPrice; 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 ( 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"> <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"> <div className="flex items-center gap-2">
<ArrowLeftRight size={20} className="text-blue-400" /> <ArrowLeftRight size={20} className="text-blue-400" />
<div> <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"> <p className="text-sm text-gray-400">
{isSender ? 'To' : 'From'}: {otherUser?.username} With: {otherUser?.username}
</p> </p>
</div> </div>
</div> </div>
@@ -154,12 +221,13 @@ export default function TradeDetail({
<Loader2 className="animate-spin text-blue-500" size={48} /> <Loader2 className="animate-spin text-blue-500" size={48} />
</div> </div>
) : ( ) : (
<div className="space-y-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* Your Side */} {/* Your Side */}
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="font-semibold text-green-400"> <h3 className="font-semibold text-green-400">
{isSender ? 'You Give' : 'You Receive'} You Give
</h3> </h3>
<div className="flex items-center gap-1 text-green-400 text-sm"> <div className="flex items-center gap-1 text-green-400 text-sm">
<DollarSign size={14} /> <DollarSign size={14} />
@@ -198,7 +266,7 @@ export default function TradeDetail({
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="font-semibold text-blue-400"> <h3 className="font-semibold text-blue-400">
{isSender ? 'You Receive' : 'They Give'} You Receive
</h3> </h3>
<div className="flex items-center gap-1 text-blue-400 text-sm"> <div className="flex items-center gap-1 text-blue-400 text-sm">
<DollarSign size={14} /> <DollarSign size={14} />
@@ -233,34 +301,68 @@ export default function TradeDetail({
)} )}
</div> </div>
</div> </div>
)}
{/* Message */} {/* Message */}
{trade.message && ( {trade.message && (
<div className="mt-4 p-3 bg-gray-800 rounded-lg"> <div className="p-3 bg-gray-800 rounded-lg">
<p className="text-sm text-gray-400 mb-1">Message:</p> <p className="text-sm text-gray-400 mb-1">Message:</p>
<p className="text-sm">{trade.message}</p> <p className="text-sm">{trade.message}</p>
</div> </div>
)} )}
{/* Price Difference */} {/* Price Difference */}
{!loading && (senderPrice > 0 || receiverPrice > 0) && ( {!loading && (yourPrice > 0 || theirPrice > 0) && (
<div className="mt-4 p-3 bg-gray-800 rounded-lg"> <div className="p-3 bg-gray-800 rounded-lg">
<div className="flex items-center justify-between text-sm"> <div className="flex items-center justify-between text-sm">
<span className="text-gray-400">Value Difference:</span> <span className="text-gray-400">Value Difference:</span>
<span className={Math.abs(senderPrice - receiverPrice) > 5 ? 'text-yellow-400' : 'text-gray-300'}> <span className={Math.abs(yourPrice - theirPrice) > 5 ? 'text-yellow-400' : 'text-gray-300'}>
${Math.abs(senderPrice - receiverPrice).toFixed(2)} ${Math.abs(yourPrice - theirPrice).toFixed(2)}
{senderPrice > receiverPrice ? ' in your favor' : senderPrice < receiverPrice ? ' in their favor' : ' (balanced)'} {yourPrice > theirPrice ? ' in your favor' : yourPrice < theirPrice ? ' in their favor' : ' (balanced)'}
</span> </span>
</div> </div>
</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> </div>
{/* Actions - Only for pending trades */} {/* Actions - Only for pending trades */}
{trade.status === 'pending' && !loading && ( {trade.status === 'pending' && !loading && (
<div className="border-t border-gray-800 p-4 space-y-2"> <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"> <div className="flex gap-2">
<button <button
@@ -289,16 +391,78 @@ export default function TradeDetail({
<button <button
onClick={handleCounterOffer} onClick={handleCounterOffer}
disabled={processing} 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} /> <RefreshCcw size={18} />
Make Counter Offer Make Counter Offer
</button> </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"> <p className="text-center text-gray-400 text-sm py-2">
Waiting for {otherUser?.username} to respond... Waiting for {otherUser?.username} to respond...
</p> </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>
</>
) : (
/* 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}
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"
>
{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> </div>
)} )}

View File

@@ -205,42 +205,55 @@ export type Database = {
trades: { trades: {
Row: { Row: {
id: string id: string
sender_id: string user1_id: string
receiver_id: string user2_id: string
status: 'pending' | 'accepted' | 'declined' | 'cancelled' status: 'pending' | 'accepted' | 'declined' | 'cancelled'
message: string | null message: string | null
created_at: string | null created_at: string | null
updated_at: string | null updated_at: string | null
version: number
editor_id: string | null
} }
Insert: { Insert: {
id?: string id?: string
sender_id: string user1_id: string
receiver_id: string user2_id: string
status?: 'pending' | 'accepted' | 'declined' | 'cancelled' status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
message?: string | null message?: string | null
created_at?: string | null created_at?: string | null
updated_at?: string | null updated_at?: string | null
version?: number
editor_id?: string | null
} }
Update: { Update: {
id?: string id?: string
sender_id?: string user1_id?: string
receiver_id?: string user2_id?: string
status?: 'pending' | 'accepted' | 'declined' | 'cancelled' status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
message?: string | null message?: string | null
created_at?: string | null created_at?: string | null
updated_at?: string | null updated_at?: string | null
version?: number
editor_id?: string | null
} }
Relationships: [ Relationships: [
{ {
foreignKeyName: "trades_sender_id_fkey" foreignKeyName: "trades_user1_id_fkey"
columns: ["sender_id"] columns: ["user1_id"]
isOneToOne: false isOneToOne: false
referencedRelation: "profiles" referencedRelation: "profiles"
referencedColumns: ["id"] referencedColumns: ["id"]
}, },
{ {
foreignKeyName: "trades_receiver_id_fkey" foreignKeyName: "trades_user2_id_fkey"
columns: ["receiver_id"] columns: ["user2_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
{
foreignKeyName: "trades_editor_id_fkey"
columns: ["editor_id"]
isOneToOne: false isOneToOne: false
referencedRelation: "profiles" referencedRelation: "profiles"
referencedColumns: ["id"] referencedColumns: ["id"]

View File

@@ -10,23 +10,52 @@ export interface TradeItem {
export interface Trade { export interface Trade {
id: string; id: string;
sender_id: string; user1_id: string;
receiver_id: string; user2_id: string;
status: 'pending' | 'accepted' | 'declined' | 'cancelled'; status: 'pending' | 'accepted' | 'declined' | 'cancelled';
message: string | null; message: string | null;
created_at: string | null; created_at: string | null;
updated_at: string | null; updated_at: string | null;
sender?: { username: string | null }; version: number;
receiver?: { username: string | null }; editor_id: string | null;
user1?: { username: string | null };
user2?: { username: string | null };
items?: TradeItem[]; 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 { export interface CreateTradeParams {
senderId: string; user1Id: string;
receiverId: string; user2Id: string;
message?: string; message?: string;
senderCards: { cardId: string; quantity: number }[]; user1Cards: { cardId: string; quantity: number }[];
receiverCards: { 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 // Get all trades for a user
@@ -35,11 +64,11 @@ export async function getTrades(userId: string): Promise<Trade[]> {
.from('trades') .from('trades')
.select(` .select(`
*, *,
sender:profiles!trades_sender_id_fkey(username), user1:profiles!trades_user1_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username), user2:profiles!trades_user2_id_fkey(username),
items:trade_items(*) 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 }); .order('created_at', { ascending: false });
if (error) throw error; if (error) throw error;
@@ -52,12 +81,12 @@ export async function getPendingTrades(userId: string): Promise<Trade[]> {
.from('trades') .from('trades')
.select(` .select(`
*, *,
sender:profiles!trades_sender_id_fkey(username), user1:profiles!trades_user1_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username), user2:profiles!trades_user2_id_fkey(username),
items:trade_items(*) items:trade_items(*)
`) `)
.eq('status', 'pending') .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 }); .order('created_at', { ascending: false });
if (error) throw error; if (error) throw error;
@@ -70,8 +99,8 @@ export async function getTradeById(tradeId: string): Promise<Trade | null> {
.from('trades') .from('trades')
.select(` .select(`
*, *,
sender:profiles!trades_sender_id_fkey(username), user1:profiles!trades_user1_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username), user2:profiles!trades_user2_id_fkey(username),
items:trade_items(*) items:trade_items(*)
`) `)
.eq('id', tradeId) .eq('id', tradeId)
@@ -83,39 +112,40 @@ export async function getTradeById(tradeId: string): Promise<Trade | null> {
// Create a new trade with items // Create a new trade with items
export async function createTrade(params: CreateTradeParams): Promise<Trade> { 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 // Create the trade
const { data: trade, error: tradeError } = await supabase const { data: trade, error: tradeError } = await supabase
.from('trades') .from('trades')
.insert({ .insert({
sender_id: senderId, user1_id: user1Id,
receiver_id: receiverId, user2_id: user2Id,
message, message,
status: 'pending', status: 'pending',
// editor_id starts as null - gets set when someone edits the trade
}) })
.select() .select()
.single(); .single();
if (tradeError) throw tradeError; if (tradeError) throw tradeError;
// Add sender's cards // Add user1's cards
const senderItems = senderCards.map((card) => ({ const user1Items = user1Cards.map((card) => ({
trade_id: trade.id, trade_id: trade.id,
owner_id: senderId, owner_id: user1Id,
card_id: card.cardId, card_id: card.cardId,
quantity: card.quantity, quantity: card.quantity,
})); }));
// Add receiver's cards (what sender wants) // Add user2's cards
const receiverItems = receiverCards.map((card) => ({ const user2Items = user2Cards.map((card) => ({
trade_id: trade.id, trade_id: trade.id,
owner_id: receiverId, owner_id: user2Id,
card_id: card.cardId, card_id: card.cardId,
quantity: card.quantity, quantity: card.quantity,
})); }));
const allItems = [...senderItems, ...receiverItems]; const allItems = [...user1Items, ...user2Items];
if (allItems.length > 0) { if (allItems.length > 0) {
const { error: itemsError } = await supabase const { error: itemsError } = await supabase
@@ -170,11 +200,11 @@ export async function getTradeHistory(userId: string): Promise<Trade[]> {
.from('trades') .from('trades')
.select(` .select(`
*, *,
sender:profiles!trades_sender_id_fkey(username), user1:profiles!trades_user1_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username), user2:profiles!trades_user2_id_fkey(username),
items:trade_items(*) 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']) .in('status', ['accepted', 'declined', 'cancelled'])
.order('updated_at', { ascending: false }) .order('updated_at', { ascending: false })
.limit(50); .limit(50);
@@ -182,3 +212,116 @@ export async function getTradeHistory(userId: string): Promise<Trade[]> {
if (error) throw error; if (error) throw error;
return data as Trade[]; 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[];
}

View 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);

View 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())
)
);

File diff suppressed because one or more lines are too long