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:
@@ -1,11 +1,15 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__supabase__apply_migration",
|
||||
"mcp__supabase__list_tables",
|
||||
"mcp__supabase__execute_sql",
|
||||
"Bash(npm run build:*)",
|
||||
"mcp__supabase__get_advisors"
|
||||
]
|
||||
},
|
||||
"enableAllProjectMcpServers": true,
|
||||
"enabledMcpjsonServers": [
|
||||
"supabase"
|
||||
],
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__supabase__apply_migration"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ define(['./workbox-ca84f546'], (function (workbox) { 'use strict';
|
||||
"revision": "3ca0b8505b4bec776b69afdba2768812"
|
||||
}, {
|
||||
"url": "index.html",
|
||||
"revision": "0.ufhads5pjvs"
|
||||
"revision": "0.vigoqq958cg"
|
||||
}], {});
|
||||
workbox.cleanupOutdatedCaches();
|
||||
workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), {
|
||||
|
||||
@@ -73,6 +73,8 @@ export default function Community() {
|
||||
const [friendSearch, setFriendSearch] = useState('');
|
||||
const [friendSearchResults, setFriendSearchResults] = useState<{ id: string; username: string | null }[]>([]);
|
||||
const [searchingFriends, setSearchingFriends] = useState(false);
|
||||
const [friendListFilter, setFriendListFilter] = useState('');
|
||||
const [requestsFilter, setRequestsFilter] = useState('');
|
||||
|
||||
// Trades state
|
||||
const [tradesSubTab, setTradesSubTab] = useState<TradesSubTab>('pending');
|
||||
@@ -81,12 +83,6 @@ export default function Community() {
|
||||
const [tradeCardDetails, setTradeCardDetails] = useState<Map<string, Card>>(new Map());
|
||||
const [processingTradeId, setProcessingTradeId] = useState<string | 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
|
||||
const [username, setUsername] = useState('');
|
||||
@@ -108,6 +104,126 @@ export default function Community() {
|
||||
}
|
||||
}, [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 () => {
|
||||
if (!user) return;
|
||||
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 ============
|
||||
const loadProfile = async () => {
|
||||
@@ -539,13 +624,13 @@ export default function Community() {
|
||||
|
||||
// ============ MAIN VIEW ============
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white md:min-h-screen">
|
||||
{/* Header */}
|
||||
<div className="sticky top-0 bg-gray-900/95 backdrop-blur border-b border-gray-800 p-3 z-10">
|
||||
<h1 className="text-xl font-bold mb-3">Community</h1>
|
||||
<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 */}
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Community</h1>
|
||||
|
||||
{/* Tabs - Scrollable on mobile */}
|
||||
<div className="flex gap-1 overflow-x-auto pb-1 -mx-3 px-3 scrollbar-hide">
|
||||
{/* Tabs */}
|
||||
<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: 'friends' as Tab, label: `Friends`, count: friends.length, icon: Users },
|
||||
@@ -573,10 +658,7 @@ export default function Community() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-3">
|
||||
{/* ============ BROWSE TAB ============ */}
|
||||
{activeTab === 'browse' && (
|
||||
<div className="space-y-3">
|
||||
@@ -675,80 +757,146 @@ export default function Community() {
|
||||
|
||||
{/* Friends List */}
|
||||
{friendsSubTab === 'list' && (
|
||||
friends.length === 0 ? (
|
||||
<p className="text-gray-400 text-center py-8 text-sm">No friends yet</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{friends.map((friend) => (
|
||||
<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>
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedUser({ id: friend.id, username: friend.username, collection_visibility: 'friends' });
|
||||
loadUserCollection(friend.id);
|
||||
}}
|
||||
className="p-2 text-blue-400 active:bg-blue-400/20 rounded-lg"
|
||||
>
|
||||
<Eye size={18} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleRemoveFriend(friend.friendshipId, friend.username || 'user')}
|
||||
className="p-2 text-red-400 active:bg-red-400/20 rounded-lg"
|
||||
>
|
||||
<UserMinus size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<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>
|
||||
) : 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">
|
||||
{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">
|
||||
<span className="font-medium truncate">{friend.username || 'Unknown'}</span>
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedUser({ id: friend.id, username: friend.username, collection_visibility: 'friends' });
|
||||
loadUserCollection(friend.id);
|
||||
}}
|
||||
className="p-2 text-blue-400 active:bg-blue-400/20 rounded-lg"
|
||||
>
|
||||
<Eye size={18} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleRemoveFriend(friend.friendshipId, friend.username || 'user')}
|
||||
className="p-2 text-red-400 active:bg-red-400/20 rounded-lg"
|
||||
>
|
||||
<UserMinus size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Requests */}
|
||||
{friendsSubTab === 'requests' && (
|
||||
<div className="space-y-4">
|
||||
{pendingRequests.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs text-gray-500 mb-2">Received</p>
|
||||
<div className="space-y-2">
|
||||
{pendingRequests.map((req) => (
|
||||
<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>
|
||||
<div className="flex gap-1">
|
||||
<button onClick={() => handleAcceptRequest(req.friendshipId)} className="p-2 text-green-400 active:bg-green-400/20 rounded-lg">
|
||||
<Check size={18} />
|
||||
</button>
|
||||
<button onClick={() => handleDeclineRequest(req.friendshipId)} className="p-2 text-red-400 active:bg-red-400/20 rounded-lg">
|
||||
<X size={18} />
|
||||
</button>
|
||||
<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={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>
|
||||
<p className="text-xs text-gray-500 mb-2">Received</p>
|
||||
<div className="space-y-2">
|
||||
{filteredPending.map((req) => (
|
||||
<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>
|
||||
<div className="flex gap-1">
|
||||
<button onClick={() => handleAcceptRequest(req.friendshipId)} className="p-2 text-green-400 active:bg-green-400/20 rounded-lg">
|
||||
<Check size={18} />
|
||||
</button>
|
||||
<button onClick={() => handleDeclineRequest(req.friendshipId)} className="p-2 text-red-400 active:bg-red-400/20 rounded-lg">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{sentRequests.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs text-gray-500 mb-2">Sent</p>
|
||||
<div className="space-y-2">
|
||||
{sentRequests.map((req) => (
|
||||
<div key={req.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<Send size={14} className="text-gray-500" />
|
||||
<span className="font-medium truncate">{req.username || 'Unknown'}</span>
|
||||
{filteredSent.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs text-gray-500 mb-2">Sent</p>
|
||||
<div className="space-y-2">
|
||||
{filteredSent.map((req) => (
|
||||
<div key={req.id} className="flex items-center justify-between bg-gray-800 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<Send size={14} className="text-gray-500" />
|
||||
<span className="font-medium truncate">{req.username || 'Unknown'}</span>
|
||||
</div>
|
||||
<span className="text-xs text-yellow-500">Pending</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-xs text-yellow-500">Pending</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{pendingRequests.length === 0 && sentRequests.length === 0 && (
|
||||
<p className="text-gray-400 text-center py-8 text-sm">No requests</p>
|
||||
)}
|
||||
{pendingRequests.length === 0 && sentRequests.length === 0 && (
|
||||
<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>
|
||||
)}
|
||||
|
||||
@@ -831,8 +979,10 @@ export default function Community() {
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{(tradesSubTab === 'pending' ? pendingTrades : tradeHistory).map((trade) => {
|
||||
const isSender = trade.sender_id === user?.id;
|
||||
const otherUser = isSender ? trade.receiver : trade.sender;
|
||||
const isUser1 = trade.user1_id === user?.id;
|
||||
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> = {
|
||||
accepted: 'text-green-400',
|
||||
declined: 'text-red-400',
|
||||
@@ -840,7 +990,8 @@ export default function Community() {
|
||||
pending: 'text-yellow-400',
|
||||
};
|
||||
|
||||
const canViewDetails = !isSender && trade.status === 'pending';
|
||||
// Both users can view details for pending trades
|
||||
const canViewDetails = trade.status === 'pending';
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -855,7 +1006,7 @@ export default function Community() {
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<ArrowLeftRight size={16} className="text-blue-400 flex-shrink-0" />
|
||||
<span className="text-sm truncate">
|
||||
{isSender ? 'To' : 'From'}: <strong>{otherUser?.username}</strong>
|
||||
With: <strong>{otherUser?.username}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<span className={`text-xs capitalize ${statusColors[trade.status]}`}>
|
||||
@@ -865,8 +1016,8 @@ export default function Community() {
|
||||
|
||||
{/* Items */}
|
||||
<div className="grid grid-cols-2 gap-2 text-sm">
|
||||
{renderTradeItems(trade.items, trade.sender_id, isSender ? 'Give' : 'Receive')}
|
||||
{renderTradeItems(trade.items, trade.receiver_id, isSender ? 'Get' : 'Send')}
|
||||
{renderTradeItems(trade.items, myUserId, 'You Give')}
|
||||
{renderTradeItems(trade.items, otherUserId, 'You Get')}
|
||||
</div>
|
||||
|
||||
{canViewDetails && (
|
||||
@@ -875,8 +1026,8 @@ export default function Community() {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Actions - Only show quick actions for sender (cancel) */}
|
||||
{tradesSubTab === 'pending' && isSender && (
|
||||
{/* Actions - Allow any user to cancel pending trade */}
|
||||
{tradesSubTab === 'pending' && (
|
||||
<div className="flex gap-2 pt-2 border-t border-gray-700" onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
onClick={() => handleCancelTrade(trade.id)}
|
||||
@@ -941,43 +1092,31 @@ export default function Community() {
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Trade Detail Modal */}
|
||||
{selectedTrade && (
|
||||
<TradeDetail
|
||||
trade={selectedTrade}
|
||||
onClose={() => setSelectedTrade(null)}
|
||||
onAccept={handleAcceptTrade}
|
||||
onDecline={handleDeclineTrade}
|
||||
onTradeUpdated={() => {
|
||||
setSelectedTrade(null);
|
||||
loadTradesData();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Confirm Modal */}
|
||||
<ConfirmModal
|
||||
isOpen={confirmModal.isOpen}
|
||||
onClose={() => setConfirmModal({ ...confirmModal, isOpen: false })}
|
||||
onConfirm={confirmModal.onConfirm}
|
||||
title={confirmModal.title}
|
||||
message={confirmModal.message}
|
||||
variant={confirmModal.variant}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Trade Detail Modal */}
|
||||
{selectedTrade && (
|
||||
<TradeDetail
|
||||
trade={selectedTrade}
|
||||
onClose={() => setSelectedTrade(null)}
|
||||
onAccept={handleAcceptTrade}
|
||||
onDecline={handleDeclineTrade}
|
||||
onCounterOffer={handleCounterOffer}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Counter Offer Creator */}
|
||||
{counterOfferData && (
|
||||
<TradeCreator
|
||||
receiverId={counterOfferData.receiverId}
|
||||
receiverUsername={counterOfferData.receiverUsername}
|
||||
receiverCollection={counterOfferData.receiverCollection}
|
||||
onClose={() => setCounterOfferData(null)}
|
||||
onTradeCreated={() => {
|
||||
setCounterOfferData(null);
|
||||
loadTradesData();
|
||||
toast.success('Counter offer sent!');
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Confirm Modal */}
|
||||
<ConfirmModal
|
||||
isOpen={confirmModal.isOpen}
|
||||
onClose={() => setConfirmModal({ ...confirmModal, isOpen: false })}
|
||||
onConfirm={confirmModal.onConfirm}
|
||||
title={confirmModal.title}
|
||||
message={confirmModal.message}
|
||||
variant={confirmModal.variant}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { X, ArrowLeftRight, ArrowRight, ArrowLeft, Minus, Send, Gift, Loader2, S
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { createTrade } from '../services/tradesService';
|
||||
import { createTrade, updateTrade } from '../services/tradesService';
|
||||
import { Card } from '../types';
|
||||
|
||||
interface CollectionItem {
|
||||
@@ -182,6 +182,11 @@ interface TradeCreatorProps {
|
||||
receiverCollection: CollectionItem[];
|
||||
onClose: () => void;
|
||||
onTradeCreated: () => void;
|
||||
editMode?: boolean;
|
||||
existingTradeId?: string;
|
||||
initialSenderCards?: Card[];
|
||||
initialReceiverCards?: Card[];
|
||||
initialMessage?: string;
|
||||
}
|
||||
|
||||
type MobileStep = 'want' | 'give' | 'review';
|
||||
@@ -192,13 +197,18 @@ export default function TradeCreator({
|
||||
receiverCollection,
|
||||
onClose,
|
||||
onTradeCreated,
|
||||
editMode = false,
|
||||
existingTradeId,
|
||||
initialSenderCards = [],
|
||||
initialReceiverCards = [],
|
||||
initialMessage = '',
|
||||
}: TradeCreatorProps) {
|
||||
const { user } = useAuth();
|
||||
const toast = useToast();
|
||||
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [message, setMessage] = useState(initialMessage);
|
||||
|
||||
const [isGiftMode, setIsGiftMode] = useState(false);
|
||||
const [mobileStep, setMobileStep] = useState<MobileStep>('want');
|
||||
@@ -222,6 +232,57 @@ export default function TradeCreator({
|
||||
}
|
||||
}, [isGiftMode]);
|
||||
|
||||
// Pre-populate cards in edit mode
|
||||
useEffect(() => {
|
||||
if (!editMode || !myCollection.length || !receiverCollection.length) return;
|
||||
if (initialSenderCards.length === 0 && initialReceiverCards.length === 0) return;
|
||||
|
||||
console.log('Pre-populating cards', {
|
||||
initialSenderCards: initialSenderCards.length,
|
||||
initialReceiverCards: initialReceiverCards.length,
|
||||
myCollection: myCollection.length,
|
||||
receiverCollection: receiverCollection.length
|
||||
});
|
||||
|
||||
// Pre-populate sender cards with their quantities
|
||||
const senderMap = new Map<string, SelectedCard>();
|
||||
initialSenderCards.forEach(card => {
|
||||
const collectionItem = myCollection.find(c => c.card.id === card.id);
|
||||
if (collectionItem) {
|
||||
// Find the quantity from trade items if card has quantity property
|
||||
const quantity = (card as any).quantity || 1;
|
||||
console.log('Adding sender card:', card.name, 'qty:', quantity);
|
||||
senderMap.set(card.id, {
|
||||
card: card,
|
||||
quantity: quantity,
|
||||
maxQuantity: collectionItem.quantity,
|
||||
});
|
||||
} else {
|
||||
console.log('Card not found in my collection:', card.name, card.id);
|
||||
}
|
||||
});
|
||||
setMyOfferedCards(senderMap);
|
||||
|
||||
// Pre-populate receiver cards with their quantities
|
||||
const receiverMap = new Map<string, SelectedCard>();
|
||||
initialReceiverCards.forEach(card => {
|
||||
const collectionItem = receiverCollection.find(c => c.card.id === card.id);
|
||||
if (collectionItem) {
|
||||
// Find the quantity from trade items if card has quantity property
|
||||
const quantity = (card as any).quantity || 1;
|
||||
console.log('Adding receiver card:', card.name, 'qty:', quantity);
|
||||
receiverMap.set(card.id, {
|
||||
card: card,
|
||||
quantity: quantity,
|
||||
maxQuantity: collectionItem.quantity,
|
||||
});
|
||||
} else {
|
||||
console.log('Card not found in their collection:', card.name, card.id);
|
||||
}
|
||||
});
|
||||
setWantedCards(receiverMap);
|
||||
}, [editMode, myCollection, receiverCollection, initialSenderCards, initialReceiverCards]);
|
||||
|
||||
const loadMyCollection = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
@@ -314,28 +375,42 @@ export default function TradeCreator({
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const senderCards = Array.from(myOfferedCards.values()).map((item) => ({
|
||||
const myCards = Array.from(myOfferedCards.values()).map((item) => ({
|
||||
cardId: item.card.id,
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
|
||||
const receiverCards = Array.from(wantedCards.values()).map((item) => ({
|
||||
const theirCards = Array.from(wantedCards.values()).map((item) => ({
|
||||
cardId: item.card.id,
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
|
||||
await createTrade({
|
||||
senderId: user.id,
|
||||
receiverId,
|
||||
message: message || undefined,
|
||||
senderCards,
|
||||
receiverCards,
|
||||
});
|
||||
if (editMode && existingTradeId) {
|
||||
// Update existing trade
|
||||
await updateTrade({
|
||||
tradeId: existingTradeId,
|
||||
editorId: user.id,
|
||||
message: message || undefined,
|
||||
myCards,
|
||||
theirCards,
|
||||
});
|
||||
toast.success('Trade updated!');
|
||||
} else {
|
||||
// Create new trade
|
||||
await createTrade({
|
||||
user1Id: user.id,
|
||||
user2Id: receiverId,
|
||||
message: message || undefined,
|
||||
user1Cards: myCards,
|
||||
user2Cards: theirCards,
|
||||
});
|
||||
toast.success('Trade offer sent!');
|
||||
}
|
||||
|
||||
onTradeCreated();
|
||||
} catch (error) {
|
||||
console.error('Error creating trade:', error);
|
||||
toast.error('Failed to create trade');
|
||||
console.error('Error with trade:', error);
|
||||
toast.error(editMode ? 'Failed to update trade' : 'Failed to create trade');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -487,12 +562,6 @@ export default function TradeCreator({
|
||||
placeholder="Add a message..."
|
||||
className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
{message && (
|
||||
<div className="mt-2 p-2 bg-gray-900/50 rounded border border-gray-700">
|
||||
<p className="text-xs text-gray-400 mb-1">Preview:</p>
|
||||
<p className="text-sm text-gray-200">{message}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -559,7 +628,7 @@ export default function TradeCreator({
|
||||
<div className="flex items-center justify-between p-4 border-b border-gray-700">
|
||||
<div className="flex items-center gap-3">
|
||||
<ArrowLeftRight size={24} className="text-blue-400" />
|
||||
<h2 className="text-xl font-bold">Trade with {receiverUsername}</h2>
|
||||
<h2 className="text-xl font-bold">{editMode ? 'Edit Trade' : `Trade with ${receiverUsername}`}</h2>
|
||||
<label className="flex items-center gap-2 ml-4 cursor-pointer">
|
||||
<div
|
||||
className={`relative w-10 h-5 rounded-full transition-colors ${
|
||||
@@ -638,23 +707,14 @@ export default function TradeCreator({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-4">
|
||||
<div className="flex items-center gap-4 mb-4">
|
||||
<input
|
||||
type="text"
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
placeholder="Add a message (optional)"
|
||||
className="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
className="flex-1 px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
{message && (
|
||||
<div className="p-2 bg-gray-900/50 rounded border border-gray-700">
|
||||
<p className="text-xs text-gray-400 mb-1">Preview:</p>
|
||||
<p className="text-sm text-gray-200">{message}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition"
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, RefreshCcw } from 'lucide-react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { Trade, TradeItem } from '../services/tradesService';
|
||||
import { Trade, TradeHistoryEntry, getTradeVersionHistory } from '../services/tradesService';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { Card } from '../types';
|
||||
import { getCardsByIds } from '../services/api';
|
||||
import TradeCreator from './TradeCreator';
|
||||
|
||||
interface TradeDetailProps {
|
||||
trade: Trade;
|
||||
onClose: () => void;
|
||||
onAccept: (tradeId: string) => Promise<void>;
|
||||
onDecline: (tradeId: string) => Promise<void>;
|
||||
onCounterOffer: (trade: Trade, senderCards: Card[], receiverCards: Card[]) => void;
|
||||
onTradeUpdated: () => void;
|
||||
}
|
||||
|
||||
interface TradeCardItem {
|
||||
@@ -19,6 +20,11 @@ interface TradeCardItem {
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface CollectionItem {
|
||||
card: Card;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
function calculateTotalPrice(items: TradeCardItem[]): number {
|
||||
return items.reduce((total, { card, quantity }) => {
|
||||
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
|
||||
@@ -31,7 +37,7 @@ export default function TradeDetail({
|
||||
onClose,
|
||||
onAccept,
|
||||
onDecline,
|
||||
onCounterOffer,
|
||||
onTradeUpdated,
|
||||
}: TradeDetailProps) {
|
||||
const { user } = useAuth();
|
||||
const toast = useToast();
|
||||
@@ -39,13 +45,20 @@ export default function TradeDetail({
|
||||
const [processing, setProcessing] = useState(false);
|
||||
const [senderCards, setSenderCards] = useState<TradeCardItem[]>([]);
|
||||
const [receiverCards, setReceiverCards] = useState<TradeCardItem[]>([]);
|
||||
const [showHistory, setShowHistory] = useState(false);
|
||||
const [history, setHistory] = useState<TradeHistoryEntry[]>([]);
|
||||
const [showEditMode, setShowEditMode] = useState(false);
|
||||
const [editReceiverCollection, setEditReceiverCollection] = useState<CollectionItem[]>([]);
|
||||
|
||||
const isSender = trade.sender_id === user?.id;
|
||||
const isReceiver = trade.receiver_id === user?.id;
|
||||
const otherUser = isSender ? trade.receiver : trade.sender;
|
||||
const isUser1 = trade.user1_id === user?.id;
|
||||
const isUser2 = trade.user2_id === user?.id;
|
||||
const otherUser = isUser1 ? trade.user2 : trade.user1;
|
||||
const myUserId = user?.id || '';
|
||||
const otherUserId = isUser1 ? trade.user2_id : trade.user1_id;
|
||||
|
||||
useEffect(() => {
|
||||
loadTradeCards();
|
||||
loadTradeHistory();
|
||||
}, [trade]);
|
||||
|
||||
const loadTradeCards = async () => {
|
||||
@@ -62,22 +75,22 @@ export default function TradeDetail({
|
||||
const cardMap = new Map<string, Card>();
|
||||
cards.forEach(card => cardMap.set(card.id, card));
|
||||
|
||||
const senderItems: TradeCardItem[] = [];
|
||||
const receiverItems: TradeCardItem[] = [];
|
||||
const myItems: TradeCardItem[] = [];
|
||||
const theirItems: TradeCardItem[] = [];
|
||||
|
||||
trade.items?.forEach(item => {
|
||||
const card = cardMap.get(item.card_id);
|
||||
if (!card) return;
|
||||
|
||||
if (item.owner_id === trade.sender_id) {
|
||||
senderItems.push({ card, quantity: item.quantity });
|
||||
if (item.owner_id === myUserId) {
|
||||
myItems.push({ card, quantity: item.quantity });
|
||||
} else {
|
||||
receiverItems.push({ card, quantity: item.quantity });
|
||||
theirItems.push({ card, quantity: item.quantity });
|
||||
}
|
||||
});
|
||||
|
||||
setSenderCards(senderItems);
|
||||
setReceiverCards(receiverItems);
|
||||
setSenderCards(myItems);
|
||||
setReceiverCards(theirItems);
|
||||
} catch (error) {
|
||||
console.error('Error loading trade cards:', error);
|
||||
toast.error('Failed to load trade details');
|
||||
@@ -86,6 +99,15 @@ export default function TradeDetail({
|
||||
}
|
||||
};
|
||||
|
||||
const loadTradeHistory = async () => {
|
||||
try {
|
||||
const historyData = await getTradeVersionHistory(trade.id);
|
||||
setHistory(historyData);
|
||||
} catch (error) {
|
||||
console.error('Error loading trade history:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAccept = async () => {
|
||||
setProcessing(true);
|
||||
try {
|
||||
@@ -110,20 +132,65 @@ export default function TradeDetail({
|
||||
}
|
||||
};
|
||||
|
||||
const handleCounterOffer = () => {
|
||||
const senderCardsList = senderCards.map(item => item.card);
|
||||
const receiverCardsList = receiverCards.map(item => item.card);
|
||||
onCounterOffer(trade, senderCardsList, receiverCardsList);
|
||||
onClose();
|
||||
const handleEdit = async () => {
|
||||
try {
|
||||
// Load the other user's collection for editing
|
||||
const collectionMap = await getUserCollection(otherUserId);
|
||||
const cardIds = Array.from(collectionMap.keys());
|
||||
const cards = await getCardsByIds(cardIds);
|
||||
const collection = cards.map((card) => ({
|
||||
card,
|
||||
quantity: collectionMap.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
setEditReceiverCollection(collection);
|
||||
setShowEditMode(true);
|
||||
} catch (error) {
|
||||
console.error('Error loading collection for edit:', error);
|
||||
toast.error('Failed to load collection');
|
||||
}
|
||||
};
|
||||
|
||||
const senderPrice = calculateTotalPrice(senderCards);
|
||||
const receiverPrice = calculateTotalPrice(receiverCards);
|
||||
// In the symmetric model, counter-offer is the same as edit
|
||||
const handleCounterOffer = handleEdit;
|
||||
|
||||
const yourCards = isSender ? senderCards : receiverCards;
|
||||
const theirCards = isSender ? receiverCards : senderCards;
|
||||
const yourPrice = isSender ? senderPrice : receiverPrice;
|
||||
const theirPrice = isSender ? receiverPrice : senderPrice;
|
||||
// senderCards = myCards, receiverCards = theirCards (already calculated correctly)
|
||||
const yourCards = senderCards;
|
||||
const theirCards = receiverCards;
|
||||
const yourPrice = calculateTotalPrice(yourCards);
|
||||
const theirPrice = calculateTotalPrice(theirCards);
|
||||
|
||||
// For edit mode, pre-populate with current cards
|
||||
// In the symmetric model, both edit and counter-offer use the same perspective:
|
||||
// - Your cards (what you're offering)
|
||||
// - Their cards (what you want)
|
||||
// Include quantity in the card object so TradeCreator can preserve it
|
||||
const editInitialSenderCards = yourCards.map(c => ({ ...c.card, quantity: c.quantity }));
|
||||
const editInitialReceiverCards = theirCards.map(c => ({ ...c.card, quantity: c.quantity }));
|
||||
|
||||
if (showEditMode) {
|
||||
return (
|
||||
<TradeCreator
|
||||
receiverId={otherUserId}
|
||||
receiverUsername={otherUser?.username || 'User'}
|
||||
receiverCollection={editReceiverCollection}
|
||||
onClose={() => {
|
||||
setShowEditMode(false);
|
||||
onClose();
|
||||
}}
|
||||
onTradeCreated={() => {
|
||||
setShowEditMode(false);
|
||||
onTradeUpdated();
|
||||
onClose();
|
||||
}}
|
||||
editMode={true}
|
||||
existingTradeId={trade.id}
|
||||
initialSenderCards={editInitialSenderCards}
|
||||
initialReceiverCards={editInitialReceiverCards}
|
||||
initialMessage={trade.message || ''}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-end md:items-center justify-center p-0 md:p-4">
|
||||
@@ -133,9 +200,9 @@ export default function TradeDetail({
|
||||
<div className="flex items-center gap-2">
|
||||
<ArrowLeftRight size={20} className="text-blue-400" />
|
||||
<div>
|
||||
<h2 className="text-lg font-bold">Trade Details</h2>
|
||||
<h2 className="text-lg font-bold">Trade Details {trade.version > 1 && `(v${trade.version})`}</h2>
|
||||
<p className="text-sm text-gray-400">
|
||||
{isSender ? 'To' : 'From'}: {otherUser?.username}
|
||||
With: {otherUser?.username}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -154,105 +221,138 @@ export default function TradeDetail({
|
||||
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Your Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-green-400">
|
||||
{isSender ? 'You Give' : 'You Receive'}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-green-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{yourPrice.toFixed(2)}
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Your Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-green-400">
|
||||
You Give
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-green-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{yourPrice.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{yourCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{yourCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{yourCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{yourCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{/* Their Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-blue-400">
|
||||
You Receive
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-blue-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{theirPrice.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{theirCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{theirCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
</div>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Their Side */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-blue-400">
|
||||
{isSender ? 'You Receive' : 'They Give'}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 text-blue-400 text-sm">
|
||||
<DollarSign size={14} />
|
||||
{theirPrice.toFixed(2)}
|
||||
{/* Message */}
|
||||
{trade.message && (
|
||||
<div className="p-3 bg-gray-800 rounded-lg">
|
||||
<p className="text-sm text-gray-400 mb-1">Message:</p>
|
||||
<p className="text-sm">{trade.message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Price Difference */}
|
||||
{!loading && (yourPrice > 0 || theirPrice > 0) && (
|
||||
<div className="p-3 bg-gray-800 rounded-lg">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-gray-400">Value Difference:</span>
|
||||
<span className={Math.abs(yourPrice - theirPrice) > 5 ? 'text-yellow-400' : 'text-gray-300'}>
|
||||
${Math.abs(yourPrice - theirPrice).toFixed(2)}
|
||||
{yourPrice > theirPrice ? ' in your favor' : yourPrice < theirPrice ? ' in their favor' : ' (balanced)'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{theirCards.length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">Gift (no cards)</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{theirCards.map((item, idx) => (
|
||||
<div key={idx} className="relative rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={item.card.image_uris?.small || item.card.image_uris?.normal}
|
||||
alt={item.card.name}
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
{item.quantity > 1 && (
|
||||
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded font-semibold">
|
||||
x{item.quantity}
|
||||
{/* 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>
|
||||
)}
|
||||
{item.card.prices?.usd && (
|
||||
<div className="absolute bottom-1 left-1 bg-gray-900/90 text-white text-[10px] px-1 py-0.5 rounded">
|
||||
${item.card.prices.usd}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Message */}
|
||||
{trade.message && (
|
||||
<div className="mt-4 p-3 bg-gray-800 rounded-lg">
|
||||
<p className="text-sm text-gray-400 mb-1">Message:</p>
|
||||
<p className="text-sm">{trade.message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Price Difference */}
|
||||
{!loading && (senderPrice > 0 || receiverPrice > 0) && (
|
||||
<div className="mt-4 p-3 bg-gray-800 rounded-lg">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-gray-400">Value Difference:</span>
|
||||
<span className={Math.abs(senderPrice - receiverPrice) > 5 ? 'text-yellow-400' : 'text-gray-300'}>
|
||||
${Math.abs(senderPrice - receiverPrice).toFixed(2)}
|
||||
{senderPrice > receiverPrice ? ' in your favor' : senderPrice < receiverPrice ? ' in their favor' : ' (balanced)'}
|
||||
</span>
|
||||
</div>
|
||||
{entry.message && (
|
||||
<p className="text-gray-300 text-xs">{entry.message}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -260,7 +360,9 @@ export default function TradeDetail({
|
||||
{/* Actions - Only for pending trades */}
|
||||
{trade.status === 'pending' && !loading && (
|
||||
<div className="border-t border-gray-800 p-4 space-y-2">
|
||||
{isReceiver ? (
|
||||
{/* Only the user who DIDN'T make the last edit can respond */}
|
||||
{trade.editor_id && trade.editor_id !== user?.id ? (
|
||||
/* User receives the last edit - can accept/decline/counter */
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
@@ -289,16 +391,78 @@ export default function TradeDetail({
|
||||
<button
|
||||
onClick={handleCounterOffer}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<RefreshCcw size={18} />
|
||||
Make Counter Offer
|
||||
</button>
|
||||
</>
|
||||
) : trade.editor_id === user?.id ? (
|
||||
/* User made the last edit - can still edit while waiting for response */
|
||||
<>
|
||||
<p className="text-center text-gray-400 text-sm py-2">
|
||||
Waiting for {otherUser?.username} to respond...
|
||||
</p>
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<Edit size={18} />
|
||||
Modify Your Offer
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-center text-gray-400 text-sm py-2">
|
||||
Waiting for {otherUser?.username} to respond...
|
||||
</p>
|
||||
/* No editor yet (initial trade) */
|
||||
<>
|
||||
{isUser1 ? (
|
||||
/* User1 (initiator) can edit their initial offer */
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
disabled={processing}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
>
|
||||
<Edit size={18} />
|
||||
Edit Trade Offer
|
||||
</button>
|
||||
) : (
|
||||
/* User2 (partner) can accept/decline/counter */
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleAccept}
|
||||
disabled={processing}
|
||||
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>
|
||||
)}
|
||||
|
||||
@@ -205,42 +205,55 @@ export type Database = {
|
||||
trades: {
|
||||
Row: {
|
||||
id: string
|
||||
sender_id: string
|
||||
receiver_id: string
|
||||
user1_id: string
|
||||
user2_id: string
|
||||
status: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||
message: string | null
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
version: number
|
||||
editor_id: string | null
|
||||
}
|
||||
Insert: {
|
||||
id?: string
|
||||
sender_id: string
|
||||
receiver_id: string
|
||||
user1_id: string
|
||||
user2_id: string
|
||||
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||
message?: string | null
|
||||
created_at?: string | null
|
||||
updated_at?: string | null
|
||||
version?: number
|
||||
editor_id?: string | null
|
||||
}
|
||||
Update: {
|
||||
id?: string
|
||||
sender_id?: string
|
||||
receiver_id?: string
|
||||
user1_id?: string
|
||||
user2_id?: string
|
||||
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||
message?: string | null
|
||||
created_at?: string | null
|
||||
updated_at?: string | null
|
||||
version?: number
|
||||
editor_id?: string | null
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "trades_sender_id_fkey"
|
||||
columns: ["sender_id"]
|
||||
foreignKeyName: "trades_user1_id_fkey"
|
||||
columns: ["user1_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "trades_receiver_id_fkey"
|
||||
columns: ["receiver_id"]
|
||||
foreignKeyName: "trades_user2_id_fkey"
|
||||
columns: ["user2_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "trades_editor_id_fkey"
|
||||
columns: ["editor_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["id"]
|
||||
|
||||
@@ -10,23 +10,52 @@ export interface TradeItem {
|
||||
|
||||
export interface Trade {
|
||||
id: string;
|
||||
sender_id: string;
|
||||
receiver_id: string;
|
||||
user1_id: string;
|
||||
user2_id: string;
|
||||
status: 'pending' | 'accepted' | 'declined' | 'cancelled';
|
||||
message: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
sender?: { username: string | null };
|
||||
receiver?: { username: string | null };
|
||||
version: number;
|
||||
editor_id: string | null;
|
||||
user1?: { username: string | null };
|
||||
user2?: { username: string | null };
|
||||
items?: TradeItem[];
|
||||
}
|
||||
|
||||
export interface TradeHistoryEntry {
|
||||
id: string;
|
||||
trade_id: string;
|
||||
version: number;
|
||||
editor_id: string;
|
||||
message: string | null;
|
||||
created_at: string;
|
||||
editor?: { username: string | null };
|
||||
items?: TradeHistoryItem[];
|
||||
}
|
||||
|
||||
export interface TradeHistoryItem {
|
||||
id: string;
|
||||
history_id: string;
|
||||
owner_id: string;
|
||||
card_id: string;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export interface CreateTradeParams {
|
||||
senderId: string;
|
||||
receiverId: string;
|
||||
user1Id: string;
|
||||
user2Id: string;
|
||||
message?: string;
|
||||
senderCards: { cardId: string; quantity: number }[];
|
||||
receiverCards: { cardId: string; quantity: number }[];
|
||||
user1Cards: { cardId: string; quantity: number }[];
|
||||
user2Cards: { cardId: string; quantity: number }[];
|
||||
}
|
||||
|
||||
export interface UpdateTradeParams {
|
||||
tradeId: string;
|
||||
editorId: string;
|
||||
message?: string;
|
||||
myCards: { cardId: string; quantity: number }[];
|
||||
theirCards: { cardId: string; quantity: number }[];
|
||||
}
|
||||
|
||||
// Get all trades for a user
|
||||
@@ -35,11 +64,11 @@ export async function getTrades(userId: string): Promise<Trade[]> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||
.or(`user1_id.eq.${userId},user2_id.eq.${userId}`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
@@ -52,12 +81,12 @@ export async function getPendingTrades(userId: string): Promise<Trade[]> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.eq('status', 'pending')
|
||||
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||
.or(`user1_id.eq.${userId},user2_id.eq.${userId}`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
@@ -70,8 +99,8 @@ export async function getTradeById(tradeId: string): Promise<Trade | null> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.eq('id', tradeId)
|
||||
@@ -83,39 +112,40 @@ export async function getTradeById(tradeId: string): Promise<Trade | null> {
|
||||
|
||||
// Create a new trade with items
|
||||
export async function createTrade(params: CreateTradeParams): Promise<Trade> {
|
||||
const { senderId, receiverId, message, senderCards, receiverCards } = params;
|
||||
const { user1Id, user2Id, message, user1Cards, user2Cards } = params;
|
||||
|
||||
// Create the trade
|
||||
const { data: trade, error: tradeError } = await supabase
|
||||
.from('trades')
|
||||
.insert({
|
||||
sender_id: senderId,
|
||||
receiver_id: receiverId,
|
||||
user1_id: user1Id,
|
||||
user2_id: user2Id,
|
||||
message,
|
||||
status: 'pending',
|
||||
// editor_id starts as null - gets set when someone edits the trade
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (tradeError) throw tradeError;
|
||||
|
||||
// Add sender's cards
|
||||
const senderItems = senderCards.map((card) => ({
|
||||
// Add user1's cards
|
||||
const user1Items = user1Cards.map((card) => ({
|
||||
trade_id: trade.id,
|
||||
owner_id: senderId,
|
||||
owner_id: user1Id,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
// Add receiver's cards (what sender wants)
|
||||
const receiverItems = receiverCards.map((card) => ({
|
||||
// Add user2's cards
|
||||
const user2Items = user2Cards.map((card) => ({
|
||||
trade_id: trade.id,
|
||||
owner_id: receiverId,
|
||||
owner_id: user2Id,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
const allItems = [...senderItems, ...receiverItems];
|
||||
const allItems = [...user1Items, ...user2Items];
|
||||
|
||||
if (allItems.length > 0) {
|
||||
const { error: itemsError } = await supabase
|
||||
@@ -170,11 +200,11 @@ export async function getTradeHistory(userId: string): Promise<Trade[]> {
|
||||
.from('trades')
|
||||
.select(`
|
||||
*,
|
||||
sender:profiles!trades_sender_id_fkey(username),
|
||||
receiver:profiles!trades_receiver_id_fkey(username),
|
||||
user1:profiles!trades_user1_id_fkey(username),
|
||||
user2:profiles!trades_user2_id_fkey(username),
|
||||
items:trade_items(*)
|
||||
`)
|
||||
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||
.or(`user1_id.eq.${userId},user2_id.eq.${userId}`)
|
||||
.in('status', ['accepted', 'declined', 'cancelled'])
|
||||
.order('updated_at', { ascending: false })
|
||||
.limit(50);
|
||||
@@ -182,3 +212,116 @@ export async function getTradeHistory(userId: string): Promise<Trade[]> {
|
||||
if (error) throw error;
|
||||
return data as Trade[];
|
||||
}
|
||||
|
||||
// Update an existing trade (for edits and counter-offers)
|
||||
export async function updateTrade(params: UpdateTradeParams): Promise<Trade> {
|
||||
const { tradeId, editorId, message, myCards, theirCards } = params;
|
||||
|
||||
// Get current trade info
|
||||
const { data: currentTrade, error: tradeError } = await supabase
|
||||
.from('trades')
|
||||
.select('version, user1_id, user2_id')
|
||||
.eq('id', tradeId)
|
||||
.single();
|
||||
|
||||
if (tradeError) throw tradeError;
|
||||
|
||||
const newVersion = (currentTrade.version || 1) + 1;
|
||||
|
||||
// Determine the other user's ID
|
||||
const otherUserId = currentTrade.user1_id === editorId
|
||||
? currentTrade.user2_id
|
||||
: currentTrade.user1_id;
|
||||
|
||||
// Save current state to history before updating
|
||||
const { data: historyEntry, error: historyError } = await supabase
|
||||
.from('trade_history')
|
||||
.insert({
|
||||
trade_id: tradeId,
|
||||
version: currentTrade.version || 1,
|
||||
editor_id: editorId,
|
||||
message: message || null,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (historyError) throw historyError;
|
||||
|
||||
// Save current items to history
|
||||
const { data: currentItems } = await supabase
|
||||
.from('trade_items')
|
||||
.select('*')
|
||||
.eq('trade_id', tradeId);
|
||||
|
||||
if (currentItems && currentItems.length > 0) {
|
||||
const historyItems = currentItems.map(item => ({
|
||||
history_id: historyEntry.id,
|
||||
owner_id: item.owner_id,
|
||||
card_id: item.card_id,
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
|
||||
await supabase.from('trade_history_items').insert(historyItems);
|
||||
}
|
||||
|
||||
// Update the trade
|
||||
const { data: updatedTrade, error: updateError } = await supabase
|
||||
.from('trades')
|
||||
.update({
|
||||
message,
|
||||
version: newVersion,
|
||||
editor_id: editorId,
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', tradeId)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
// Delete existing items
|
||||
await supabase.from('trade_items').delete().eq('trade_id', tradeId);
|
||||
|
||||
// Add new items (myCards belong to editor, theirCards belong to other user)
|
||||
const myItems = myCards.map((card) => ({
|
||||
trade_id: tradeId,
|
||||
owner_id: editorId,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
const theirItems = theirCards.map((card) => ({
|
||||
trade_id: tradeId,
|
||||
owner_id: otherUserId,
|
||||
card_id: card.cardId,
|
||||
quantity: card.quantity,
|
||||
}));
|
||||
|
||||
const allItems = [...myItems, ...theirItems];
|
||||
|
||||
if (allItems.length > 0) {
|
||||
const { error: itemsError } = await supabase
|
||||
.from('trade_items')
|
||||
.insert(allItems);
|
||||
|
||||
if (itemsError) throw itemsError;
|
||||
}
|
||||
|
||||
return updatedTrade;
|
||||
}
|
||||
|
||||
// Get version history for a trade
|
||||
export async function getTradeVersionHistory(tradeId: string): Promise<TradeHistoryEntry[]> {
|
||||
const { data, error } = await supabase
|
||||
.from('trade_history')
|
||||
.select(`
|
||||
*,
|
||||
editor:profiles!trade_history_editor_id_fkey(username),
|
||||
items:trade_history_items(*)
|
||||
`)
|
||||
.eq('trade_id', tradeId)
|
||||
.order('version', { ascending: true });
|
||||
|
||||
if (error) throw error;
|
||||
return data as TradeHistoryEntry[];
|
||||
}
|
||||
|
||||
273
supabase/migrations/20250124000000_friends_trades_visibility.sql
Normal file
273
supabase/migrations/20250124000000_friends_trades_visibility.sql
Normal file
@@ -0,0 +1,273 @@
|
||||
/*
|
||||
# Friends, Trades, and Collection Visibility
|
||||
|
||||
1. Changes to profiles
|
||||
- Add `collection_visibility` column (public, friends, private)
|
||||
|
||||
2. New Tables
|
||||
- `friendships` - Friend relationships between users
|
||||
- `trades` - Trade offers between users
|
||||
- `trade_items` - Cards included in trades
|
||||
|
||||
3. Security
|
||||
- RLS policies for all new tables
|
||||
- Updated collection policies for visibility
|
||||
*/
|
||||
|
||||
-- Add collection visibility to profiles
|
||||
ALTER TABLE public.profiles
|
||||
ADD COLUMN collection_visibility text DEFAULT 'private'
|
||||
CHECK (collection_visibility IN ('public', 'friends', 'private'));
|
||||
|
||||
-- =============================================
|
||||
-- FRIENDSHIPS TABLE
|
||||
-- =============================================
|
||||
CREATE TABLE public.friendships (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
requester_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
addressee_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
status text DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'declined')),
|
||||
created_at timestamptz DEFAULT now(),
|
||||
updated_at timestamptz DEFAULT now(),
|
||||
UNIQUE(requester_id, addressee_id),
|
||||
CHECK (requester_id != addressee_id)
|
||||
);
|
||||
|
||||
ALTER TABLE public.friendships ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can see friendships they're involved in
|
||||
CREATE POLICY "Users can view their friendships"
|
||||
ON public.friendships
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (requester_id = auth.uid() OR addressee_id = auth.uid());
|
||||
|
||||
-- Users can create friend requests
|
||||
CREATE POLICY "Users can send friend requests"
|
||||
ON public.friendships
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (requester_id = auth.uid());
|
||||
|
||||
-- Users can update friendships they received (accept/decline)
|
||||
CREATE POLICY "Users can respond to friend requests"
|
||||
ON public.friendships
|
||||
FOR UPDATE
|
||||
TO authenticated
|
||||
USING (addressee_id = auth.uid());
|
||||
|
||||
-- Users can delete their own friendships
|
||||
CREATE POLICY "Users can delete their friendships"
|
||||
ON public.friendships
|
||||
FOR DELETE
|
||||
TO authenticated
|
||||
USING (requester_id = auth.uid() OR addressee_id = auth.uid());
|
||||
|
||||
-- =============================================
|
||||
-- TRADES TABLE
|
||||
-- =============================================
|
||||
CREATE TABLE public.trades (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
sender_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
receiver_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
status text DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'declined', 'cancelled')),
|
||||
message text,
|
||||
created_at timestamptz DEFAULT now(),
|
||||
updated_at timestamptz DEFAULT now(),
|
||||
CHECK (sender_id != receiver_id)
|
||||
);
|
||||
|
||||
ALTER TABLE public.trades ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can see trades they're involved in
|
||||
CREATE POLICY "Users can view their trades"
|
||||
ON public.trades
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (sender_id = auth.uid() OR receiver_id = auth.uid());
|
||||
|
||||
-- Users can create trades
|
||||
CREATE POLICY "Users can create trades"
|
||||
ON public.trades
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (sender_id = auth.uid());
|
||||
|
||||
-- Sender can cancel, receiver can accept/decline
|
||||
CREATE POLICY "Users can update their trades"
|
||||
ON public.trades
|
||||
FOR UPDATE
|
||||
TO authenticated
|
||||
USING (sender_id = auth.uid() OR receiver_id = auth.uid());
|
||||
|
||||
-- =============================================
|
||||
-- TRADE ITEMS TABLE
|
||||
-- =============================================
|
||||
CREATE TABLE public.trade_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
trade_id uuid REFERENCES public.trades(id) ON DELETE CASCADE NOT NULL,
|
||||
owner_id uuid REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
|
||||
card_id text NOT NULL,
|
||||
quantity integer DEFAULT 1 CHECK (quantity > 0),
|
||||
created_at timestamptz DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE public.trade_items ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can see items in their trades
|
||||
CREATE POLICY "Users can view trade items"
|
||||
ON public.trade_items
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_items.trade_id
|
||||
AND (trades.sender_id = auth.uid() OR trades.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
-- Users can add items to trades they created
|
||||
CREATE POLICY "Users can add trade items"
|
||||
ON public.trade_items
|
||||
FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_items.trade_id
|
||||
AND trades.sender_id = auth.uid()
|
||||
AND trades.status = 'pending'
|
||||
)
|
||||
);
|
||||
|
||||
-- =============================================
|
||||
-- UPDATE COLLECTION POLICIES FOR VISIBILITY
|
||||
-- =============================================
|
||||
|
||||
-- Drop old restrictive policy
|
||||
DROP POLICY IF EXISTS "Users can view their own collection" ON public.collections;
|
||||
|
||||
-- New policy: view own collection OR public collections OR friend's collections (if friends visibility)
|
||||
CREATE POLICY "Users can view collections based on visibility"
|
||||
ON public.collections
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (
|
||||
user_id = auth.uid()
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM public.profiles
|
||||
WHERE profiles.id = collections.user_id
|
||||
AND profiles.collection_visibility = 'public'
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM public.profiles p
|
||||
JOIN public.friendships f ON (
|
||||
(f.requester_id = p.id AND f.addressee_id = auth.uid())
|
||||
OR (f.addressee_id = p.id AND f.requester_id = auth.uid())
|
||||
)
|
||||
WHERE p.id = collections.user_id
|
||||
AND p.collection_visibility = 'friends'
|
||||
AND f.status = 'accepted'
|
||||
)
|
||||
);
|
||||
|
||||
-- =============================================
|
||||
-- UPDATE PROFILES POLICY FOR PUBLIC VIEWING
|
||||
-- =============================================
|
||||
|
||||
-- Drop old restrictive policy
|
||||
DROP POLICY IF EXISTS "Users can view their own profile" ON public.profiles;
|
||||
|
||||
-- New policy: users can view all profiles (needed for friend search and public collections)
|
||||
CREATE POLICY "Users can view profiles"
|
||||
ON public.profiles
|
||||
FOR SELECT
|
||||
TO authenticated
|
||||
USING (true);
|
||||
|
||||
-- =============================================
|
||||
-- FUNCTION: Execute trade (transfer cards)
|
||||
-- =============================================
|
||||
CREATE OR REPLACE FUNCTION public.execute_trade(trade_id uuid)
|
||||
RETURNS boolean
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_trade RECORD;
|
||||
v_item RECORD;
|
||||
BEGIN
|
||||
-- Get the trade
|
||||
SELECT * INTO v_trade FROM public.trades WHERE id = trade_id;
|
||||
|
||||
-- Check trade exists and is pending
|
||||
IF v_trade IS NULL OR v_trade.status != 'pending' THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Check caller is the receiver
|
||||
IF v_trade.receiver_id != auth.uid() THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Process each trade item
|
||||
FOR v_item IN SELECT * FROM public.trade_items WHERE trade_items.trade_id = execute_trade.trade_id
|
||||
LOOP
|
||||
-- Determine new owner
|
||||
DECLARE
|
||||
v_new_owner uuid;
|
||||
BEGIN
|
||||
IF v_item.owner_id = v_trade.sender_id THEN
|
||||
v_new_owner := v_trade.receiver_id;
|
||||
ELSE
|
||||
v_new_owner := v_trade.sender_id;
|
||||
END IF;
|
||||
|
||||
-- Remove from old owner's collection
|
||||
UPDATE public.collections
|
||||
SET quantity = quantity - v_item.quantity,
|
||||
updated_at = now()
|
||||
WHERE user_id = v_item.owner_id
|
||||
AND card_id = v_item.card_id;
|
||||
|
||||
-- Delete if quantity is 0 or less
|
||||
DELETE FROM public.collections
|
||||
WHERE user_id = v_item.owner_id
|
||||
AND card_id = v_item.card_id
|
||||
AND quantity <= 0;
|
||||
|
||||
-- Add to new owner's collection
|
||||
INSERT INTO public.collections (user_id, card_id, quantity)
|
||||
VALUES (v_new_owner, v_item.card_id, v_item.quantity)
|
||||
ON CONFLICT (user_id, card_id)
|
||||
DO UPDATE SET
|
||||
quantity = collections.quantity + v_item.quantity,
|
||||
updated_at = now();
|
||||
END;
|
||||
END LOOP;
|
||||
|
||||
-- Mark trade as accepted
|
||||
UPDATE public.trades
|
||||
SET status = 'accepted', updated_at = now()
|
||||
WHERE id = trade_id;
|
||||
|
||||
RETURN true;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Add unique constraint on collections for upsert
|
||||
ALTER TABLE public.collections
|
||||
ADD CONSTRAINT collections_user_card_unique UNIQUE (user_id, card_id);
|
||||
|
||||
-- =============================================
|
||||
-- INDEXES FOR PERFORMANCE
|
||||
-- =============================================
|
||||
CREATE INDEX idx_friendships_requester ON public.friendships(requester_id);
|
||||
CREATE INDEX idx_friendships_addressee ON public.friendships(addressee_id);
|
||||
CREATE INDEX idx_friendships_status ON public.friendships(status);
|
||||
CREATE INDEX idx_trades_sender ON public.trades(sender_id);
|
||||
CREATE INDEX idx_trades_receiver ON public.trades(receiver_id);
|
||||
CREATE INDEX idx_trades_status ON public.trades(status);
|
||||
CREATE INDEX idx_trade_items_trade ON public.trade_items(trade_id);
|
||||
CREATE INDEX idx_profiles_visibility ON public.profiles(collection_visibility);
|
||||
78
supabase/migrations/20250126000000_trade_history.sql
Normal file
78
supabase/migrations/20250126000000_trade_history.sql
Normal file
@@ -0,0 +1,78 @@
|
||||
-- Create trade_history table to track all versions of a trade
|
||||
CREATE TABLE IF NOT EXISTS public.trade_history (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
trade_id uuid REFERENCES public.trades(id) ON DELETE CASCADE NOT NULL,
|
||||
version integer NOT NULL,
|
||||
editor_id uuid REFERENCES public.profiles(id) NOT NULL,
|
||||
message text,
|
||||
created_at timestamptz DEFAULT now(),
|
||||
UNIQUE(trade_id, version)
|
||||
);
|
||||
|
||||
-- Create trade_history_items table to store cards for each version
|
||||
CREATE TABLE IF NOT EXISTS public.trade_history_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
history_id uuid REFERENCES public.trade_history(id) ON DELETE CASCADE NOT NULL,
|
||||
owner_id uuid REFERENCES public.profiles(id) NOT NULL,
|
||||
card_id text NOT NULL,
|
||||
quantity integer DEFAULT 1,
|
||||
created_at timestamptz DEFAULT now()
|
||||
);
|
||||
|
||||
-- Add version column to trades table to track current version
|
||||
ALTER TABLE public.trades ADD COLUMN IF NOT EXISTS version integer DEFAULT 1;
|
||||
|
||||
-- Add editor_id to track who last edited the trade
|
||||
ALTER TABLE public.trades ADD COLUMN IF NOT EXISTS editor_id uuid REFERENCES public.profiles(id);
|
||||
|
||||
-- Create indexes for better performance
|
||||
CREATE INDEX IF NOT EXISTS idx_trade_history_trade_id ON public.trade_history(trade_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_trade_history_items_history_id ON public.trade_history_items(history_id);
|
||||
|
||||
-- Enable RLS
|
||||
ALTER TABLE public.trade_history ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.trade_history_items ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- RLS policies for trade_history
|
||||
CREATE POLICY "Users can view history of their trades"
|
||||
ON public.trade_history FOR SELECT
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_history.trade_id
|
||||
AND (trades.sender_id = auth.uid() OR trades.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can create history for their trades"
|
||||
ON public.trade_history FOR INSERT
|
||||
WITH CHECK (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trades
|
||||
WHERE trades.id = trade_history.trade_id
|
||||
AND (trades.sender_id = auth.uid() OR trades.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
-- RLS policies for trade_history_items
|
||||
CREATE POLICY "Users can view history items of their trades"
|
||||
ON public.trade_history_items FOR SELECT
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trade_history th
|
||||
JOIN public.trades t ON t.id = th.trade_id
|
||||
WHERE th.id = trade_history_items.history_id
|
||||
AND (t.sender_id = auth.uid() OR t.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can create history items for their trades"
|
||||
ON public.trade_history_items FOR INSERT
|
||||
WITH CHECK (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.trade_history th
|
||||
JOIN public.trades t ON t.id = th.trade_id
|
||||
WHERE th.id = trade_history_items.history_id
|
||||
AND (t.sender_id = auth.uid() OR t.receiver_id = auth.uid())
|
||||
)
|
||||
);
|
||||
104
vite.config.ts.timestamp-1764157043179-658c718c76681.mjs
Normal file
104
vite.config.ts.timestamp-1764157043179-658c718c76681.mjs
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user