Compare commits
5 Commits
64c48da05a
...
feature/bg
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf4c346e2d | ||
|
|
60bbeb9737 | ||
|
|
2acf50e46f | ||
|
|
1d77b6fb8e | ||
|
|
239a2c9591 |
10
src/App.tsx
10
src/App.tsx
@@ -11,6 +11,7 @@ import Community from './components/Community';
|
||||
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||
import { ToastProvider } from './contexts/ToastContext';
|
||||
import CardMosaicBackground from "./components/CardMosaicBackground.tsx";
|
||||
|
||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'search' | 'life-counter' | 'community';
|
||||
|
||||
@@ -40,7 +41,7 @@ function AppContent() {
|
||||
switch (currentPage) {
|
||||
case 'home':
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 animate-fade-in md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 animate-fade-in md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6 animate-slide-in-left">My Decks</h1>
|
||||
<DeckList
|
||||
@@ -78,9 +79,12 @@ function AppContent() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 flex flex-col">
|
||||
<div className="min-h-screen bg-gray-900 flex flex-col relative">
|
||||
{/* Animated card mosaic overlay */}
|
||||
<CardMosaicBackground />
|
||||
|
||||
<Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} />
|
||||
<main className="relative flex-1 overflow-y-auto">
|
||||
<main className="relative flex-1 overflow-y-auto z-20">
|
||||
<div className="relative min-h-full md:min-h-0 pt-0 md:pt-16 pb-20 md:pb-0">
|
||||
{renderPage()}
|
||||
</div>
|
||||
|
||||
155
src/components/CardMosaicBackground.tsx
Normal file
155
src/components/CardMosaicBackground.tsx
Normal file
@@ -0,0 +1,155 @@
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import { getRandomCards } from '../services/api';
|
||||
import { Card } from '../types';
|
||||
|
||||
export default function CardMosaicBackground() {
|
||||
const [cards, setCards] = useState<Card[]>([]);
|
||||
const [offset, setOffset] = useState({ x: 0, y: 0 });
|
||||
const animationRef = useRef<number>();
|
||||
|
||||
// Grid configuration - large grid to cover entire screen
|
||||
const cardsPerRow = 18;
|
||||
const cardsPerCol = 15;
|
||||
// Spacing adjusted for card transforms: w-64 = 256px
|
||||
// With rotateZ(15deg) and rotateX(60deg), cards need more space
|
||||
const cardWidth = 130; // Horizontal spacing to avoid overlap
|
||||
const cardHeight = 85; // Vertical spacing to avoid overlap
|
||||
const gridWidth = cardsPerRow * cardWidth;
|
||||
const gridHeight = cardsPerCol * cardHeight;
|
||||
|
||||
useEffect(() => {
|
||||
const fetchCards = async () => {
|
||||
try {
|
||||
// Fetch enough cards for one grid
|
||||
const totalCards = cardsPerRow * cardsPerCol;
|
||||
const randomCards = await getRandomCards(totalCards);
|
||||
setCards(randomCards);
|
||||
} catch (error) {
|
||||
console.error('Error fetching background cards:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchCards();
|
||||
}, []);
|
||||
|
||||
// Diagonal infinite scroll animation
|
||||
useEffect(() => {
|
||||
if (cards.length === 0) return;
|
||||
|
||||
const speed = 0.5; // Pixels per frame (diagonal speed)
|
||||
let lastTime = Date.now();
|
||||
|
||||
const animate = () => {
|
||||
const now = Date.now();
|
||||
const delta = now - lastTime;
|
||||
lastTime = now;
|
||||
|
||||
setOffset((prev) => {
|
||||
// Move diagonally: right and up
|
||||
let newX = prev.x + (speed * delta) / 16;
|
||||
let newY = prev.y - (speed * delta) / 16;
|
||||
|
||||
// Loop seamlessly when we've moved one full grid
|
||||
if (newX >= gridWidth) newX = newX % gridWidth;
|
||||
if (newY <= -gridHeight) newY = newY % gridHeight;
|
||||
|
||||
return { x: newX, y: newY };
|
||||
});
|
||||
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
|
||||
return () => {
|
||||
if (animationRef.current) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
}
|
||||
};
|
||||
}, [cards.length, gridWidth, gridHeight]);
|
||||
|
||||
if (cards.length === 0) return null;
|
||||
|
||||
// Render the card grid (will be duplicated 4 times for infinite effect)
|
||||
const renderGrid = (offsetX: number, offsetY: number, key: string) => (
|
||||
<div
|
||||
key={key}
|
||||
className="absolute"
|
||||
style={{
|
||||
left: `${offsetX}px`,
|
||||
top: `${offsetY}px`,
|
||||
width: `${gridWidth}px`,
|
||||
height: `${gridHeight}px`,
|
||||
perspective: '2000px', // Apply perspective to parent for uniform card sizes
|
||||
transformStyle: 'preserve-3d',
|
||||
}}
|
||||
>
|
||||
{cards.map((card, index) => {
|
||||
const col = index % cardsPerRow;
|
||||
const row = Math.floor(index / cardsPerRow);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${key}-${card.id}-${index}`}
|
||||
className="absolute"
|
||||
style={{
|
||||
left: `${col * cardWidth}px`,
|
||||
top: `${row * cardHeight}px`,
|
||||
transform: `
|
||||
perspective(1000px)
|
||||
rotateX(60deg)
|
||||
rotateY(5deg)
|
||||
rotateZ(15deg)
|
||||
`,
|
||||
opacity: 1.0, // Full opacity - gradient overlay handles the fade
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={card.image_uris?.normal || card.image_uris?.large}
|
||||
alt=""
|
||||
className="w-64 h-auto rounded-lg shadow-2xl"
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 overflow-hidden pointer-events-none z-10">
|
||||
{/* Scrolling grid container */}
|
||||
<div
|
||||
className="absolute"
|
||||
style={{
|
||||
transform: `translate(${offset.x}px, ${offset.y}px)`,
|
||||
willChange: 'transform',
|
||||
}}
|
||||
>
|
||||
{/* Duplicate grids in 2x2 pattern for seamless infinite scroll */}
|
||||
{/* Position grids to cover entire viewport and beyond */}
|
||||
{renderGrid(-gridWidth, window.innerHeight - gridHeight / 2, 'grid-tl')}
|
||||
{renderGrid(0, window.innerHeight - gridHeight / 2, 'grid-tr')}
|
||||
{renderGrid(-gridWidth, window.innerHeight - gridHeight / 2 + gridHeight, 'grid-bl')}
|
||||
{renderGrid(0, window.innerHeight - gridHeight / 2 + gridHeight, 'grid-br')}
|
||||
</div>
|
||||
|
||||
{/* Fixed gradient overlay - cards pass UNDER and fade naturally */}
|
||||
<div
|
||||
className="absolute inset-0 pointer-events-none z-10"
|
||||
style={{
|
||||
background: `
|
||||
linear-gradient(to top,
|
||||
transparent 0%,
|
||||
transparent 25%,
|
||||
rgba(3, 7, 18, 0.3) 40%,
|
||||
rgba(3, 7, 18, 0.6) 55%,
|
||||
rgba(3, 7, 18, 0.85) 70%,
|
||||
rgb(3, 7, 18) 85%
|
||||
)
|
||||
`
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -201,7 +201,7 @@ const CardSearch = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Card Search</h1>
|
||||
<form onSubmit={handleSearch} className="mb-8 space-y-4">
|
||||
|
||||
@@ -95,6 +95,34 @@ export default function Collection() {
|
||||
calculateTotalValue();
|
||||
}, [user]);
|
||||
|
||||
// Subscribe to realtime updates for collection total value
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
const profileChannel = supabase
|
||||
.channel('profile-total-value-changes')
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'UPDATE',
|
||||
schema: 'public',
|
||||
table: 'profiles',
|
||||
filter: `id=eq.${user.id}`,
|
||||
},
|
||||
(payload: any) => {
|
||||
if (payload.new?.collection_total_value !== undefined) {
|
||||
console.log('Collection total value updated:', payload.new.collection_total_value);
|
||||
setTotalCollectionValue(payload.new.collection_total_value);
|
||||
}
|
||||
}
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return () => {
|
||||
supabase.removeChannel(profileChannel);
|
||||
};
|
||||
}, [user]);
|
||||
|
||||
// Load user's collection from Supabase on mount
|
||||
useEffect(() => {
|
||||
const loadCollection = async () => {
|
||||
@@ -168,7 +196,13 @@ export default function Collection() {
|
||||
quantity: result.items.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
setCollection(prev => [...prev, ...newCards]);
|
||||
// Deduplicate: only add cards that aren't already in the collection
|
||||
setCollection(prev => {
|
||||
const existingIds = new Set(prev.map(item => item.card.id));
|
||||
const uniqueNewCards = newCards.filter(item => !existingIds.has(item.card.id));
|
||||
return [...prev, ...uniqueNewCards];
|
||||
});
|
||||
|
||||
setOffset(prev => prev + PAGE_SIZE);
|
||||
} catch (error) {
|
||||
console.error('Error loading more cards:', error);
|
||||
@@ -287,7 +321,7 @@ export default function Collection() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">My Collection</h1>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft, RefreshCw, Plus, Minus } from 'lucide-react';
|
||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft, RefreshCw, Plus, Minus, AlertTriangle } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { supabase } from '../lib/supabase';
|
||||
@@ -208,6 +208,7 @@ export default function Community() {
|
||||
}, [user]);
|
||||
|
||||
// Subscribe to collection changes when viewing someone's collection
|
||||
// Auto-price trigger is disabled, so no more infinite loops!
|
||||
useEffect(() => {
|
||||
if (!user || !selectedUser) return;
|
||||
|
||||
@@ -221,10 +222,11 @@ export default function Community() {
|
||||
table: 'collections',
|
||||
},
|
||||
(payload: any) => {
|
||||
// Filter for the selected user's collections
|
||||
const data = payload.new || payload.old;
|
||||
if (data && data.user_id === selectedUser.id) {
|
||||
console.log('Collection change for viewed user:', payload);
|
||||
console.log('Collection change for viewed user:', payload.eventType);
|
||||
// Reload on any change (INSERT/UPDATE/DELETE)
|
||||
// No more infinite loops since auto-price trigger is disabled
|
||||
loadUserCollection(selectedUser.id);
|
||||
}
|
||||
}
|
||||
@@ -371,7 +373,13 @@ export default function Community() {
|
||||
quantity: result.items.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
setSelectedUserCollection(prev => [...prev, ...newCards]);
|
||||
// Deduplicate: only add cards that aren't already in the collection
|
||||
setSelectedUserCollection(prev => {
|
||||
const existingIds = new Set(prev.map(item => item.card.id));
|
||||
const uniqueNewCards = newCards.filter(item => !existingIds.has(item.card.id));
|
||||
return [...prev, ...uniqueNewCards];
|
||||
});
|
||||
|
||||
setUserCollectionOffset(prev => prev + PAGE_SIZE);
|
||||
} catch (error) {
|
||||
console.error('Error loading more cards:', error);
|
||||
@@ -405,6 +413,34 @@ export default function Community() {
|
||||
};
|
||||
}, [selectedUser, hasMoreUserCards, isLoadingMoreUserCards, loadMoreUserCards]);
|
||||
|
||||
// Subscribe to realtime updates for selected user's collection total value
|
||||
useEffect(() => {
|
||||
if (!selectedUser) return;
|
||||
|
||||
const userProfileChannel = supabase
|
||||
.channel(`user-profile-value-${selectedUser.id}`)
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'UPDATE',
|
||||
schema: 'public',
|
||||
table: 'profiles',
|
||||
filter: `id=eq.${selectedUser.id}`,
|
||||
},
|
||||
(payload: any) => {
|
||||
if (payload.new?.collection_total_value !== undefined) {
|
||||
console.log(`User ${selectedUser.username}'s collection total value updated:`, payload.new.collection_total_value);
|
||||
setUserCollectionTotalValue(payload.new.collection_total_value);
|
||||
}
|
||||
}
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return () => {
|
||||
supabase.removeChannel(userProfileChannel);
|
||||
};
|
||||
}, [selectedUser]);
|
||||
|
||||
// ============ FRIENDS FUNCTIONS ============
|
||||
const loadFriendsData = async () => {
|
||||
if (!user) return;
|
||||
@@ -660,7 +696,7 @@ export default function Community() {
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white min-h-screen">
|
||||
<div className="relative text-white min-h-screen">
|
||||
<div className="max-w-7xl mx-auto p-3 sm:p-6">
|
||||
{/* Header with Back and Trade buttons */}
|
||||
<div className="flex items-center justify-between gap-2 mb-4 md:mb-6">
|
||||
@@ -991,7 +1027,7 @@ export default function Community() {
|
||||
|
||||
// ============ MAIN VIEW ============
|
||||
return (
|
||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Header */}
|
||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Community</h1>
|
||||
@@ -1376,10 +1412,15 @@ export default function Community() {
|
||||
With: <strong>{otherUser?.username}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{trade.status === 'pending' && !trade.is_valid && (
|
||||
<AlertTriangle size={14} className="text-red-400" title="Trade no longer valid" />
|
||||
)}
|
||||
<span className={`text-xs capitalize ${statusColors[trade.status]}`}>
|
||||
{trade.status}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Items */}
|
||||
<div className="grid grid-cols-2 gap-2 text-sm">
|
||||
|
||||
@@ -77,7 +77,7 @@ const DeckList = ({ onDeckEdit, onCreateDeck }: DeckListProps) => {
|
||||
{/* Create New Deck Card */}
|
||||
<button
|
||||
onClick={onCreateDeck}
|
||||
className="bg-gray-800 rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
||||
className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
||||
>
|
||||
<PlusCircle size={48} className="text-gray-600 group-hover:text-blue-500 transition-colors" />
|
||||
<div className="text-center">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History } from 'lucide-react';
|
||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History, AlertTriangle } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { Trade, TradeHistoryEntry, getTradeVersionHistory } from '../services/tradesService';
|
||||
@@ -222,6 +222,18 @@ export default function TradeDetail({
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Invalid Trade Warning */}
|
||||
{trade.status === 'pending' && !trade.is_valid && (
|
||||
<div className="bg-red-900/30 border border-red-600 rounded-lg p-3 flex items-start gap-2">
|
||||
<AlertTriangle size={20} className="text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="font-semibold text-red-400 text-sm">Trade No Longer Valid</h4>
|
||||
<p className="text-red-200 text-xs mt-1">
|
||||
One or more cards in this trade are no longer available in the required quantities. This trade cannot be accepted until it is updated.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Your Side */}
|
||||
<div className="space-y-3">
|
||||
@@ -367,8 +379,9 @@ export default function TradeDetail({
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleAccept}
|
||||
disabled={processing}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
disabled={processing || !trade.is_valid}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-medium transition"
|
||||
title={!trade.is_valid ? 'This trade is no longer valid' : ''}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2 className="animate-spin" size={18} />
|
||||
@@ -431,8 +444,9 @@ export default function TradeDetail({
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleAccept}
|
||||
disabled={processing}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
||||
disabled={processing || !trade.is_valid}
|
||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-medium transition"
|
||||
title={!trade.is_valid ? 'This trade is no longer valid' : ''}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2 className="animate-spin" size={18} />
|
||||
|
||||
@@ -167,6 +167,34 @@
|
||||
animation: float 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Diagonal Carousel - Cards flow from bottom-left to top-right diagonally and loop */
|
||||
@keyframes flowDiagonal {
|
||||
0% {
|
||||
translate: 0 0;
|
||||
opacity: 1;
|
||||
}
|
||||
60% {
|
||||
translate: 600px -600px;
|
||||
opacity: 1;
|
||||
}
|
||||
75% {
|
||||
translate: 900px -900px;
|
||||
opacity: 0.6;
|
||||
}
|
||||
85% {
|
||||
translate: 1100px -1100px;
|
||||
opacity: 0.3;
|
||||
}
|
||||
100% {
|
||||
translate: 1400px -1400px;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-flow-right {
|
||||
animation: flowDiagonal 40s linear infinite;
|
||||
}
|
||||
|
||||
/* Gradient Animation */
|
||||
@keyframes gradientShift {
|
||||
0% {
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface Trade {
|
||||
updated_at: string | null;
|
||||
version: number;
|
||||
editor_id: string | null;
|
||||
is_valid: boolean;
|
||||
user1?: { username: string | null };
|
||||
user2?: { username: string | null };
|
||||
items?: TradeItem[];
|
||||
@@ -160,6 +161,25 @@ export async function createTrade(params: CreateTradeParams): Promise<Trade> {
|
||||
|
||||
// Accept a trade (executes the card transfer)
|
||||
export async function acceptTrade(tradeId: string): Promise<boolean> {
|
||||
// First check if the trade is valid
|
||||
const { data: trade, error: tradeError } = await supabase
|
||||
.from('trades')
|
||||
.select('is_valid, status')
|
||||
.eq('id', tradeId)
|
||||
.single();
|
||||
|
||||
if (tradeError) throw tradeError;
|
||||
|
||||
// Prevent accepting invalid trades
|
||||
if (!trade.is_valid) {
|
||||
throw new Error('This trade is no longer valid. One or more cards are no longer available in the required quantities.');
|
||||
}
|
||||
|
||||
// Prevent accepting non-pending trades
|
||||
if (trade.status !== 'pending') {
|
||||
throw new Error('This trade has already been processed.');
|
||||
}
|
||||
|
||||
const { data, error } = await supabase.rpc('execute_trade', {
|
||||
trade_id: tradeId,
|
||||
});
|
||||
|
||||
101
supabase/migrations/20250127000001_add_trade_validation.sql
Normal file
101
supabase/migrations/20250127000001_add_trade_validation.sql
Normal file
@@ -0,0 +1,101 @@
|
||||
-- Add is_valid column to trades table
|
||||
ALTER TABLE public.trades
|
||||
ADD COLUMN IF NOT EXISTS is_valid BOOLEAN DEFAULT true;
|
||||
|
||||
-- Create index for filtering by validity
|
||||
CREATE INDEX IF NOT EXISTS idx_trades_is_valid ON public.trades(is_valid);
|
||||
|
||||
-- Function to validate if a trade can still be executed based on current collections
|
||||
CREATE OR REPLACE FUNCTION public.validate_trade(p_trade_id uuid)
|
||||
RETURNS boolean
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_item RECORD;
|
||||
v_collection_quantity integer;
|
||||
BEGIN
|
||||
-- Check each item in the trade
|
||||
FOR v_item IN
|
||||
SELECT owner_id, card_id, quantity
|
||||
FROM public.trade_items
|
||||
WHERE trade_id = p_trade_id
|
||||
LOOP
|
||||
-- Get the quantity of this card in the owner's collection
|
||||
SELECT COALESCE(quantity, 0) INTO v_collection_quantity
|
||||
FROM public.collections
|
||||
WHERE user_id = v_item.owner_id
|
||||
AND card_id = v_item.card_id;
|
||||
|
||||
-- If owner doesn't have enough of this card, trade is invalid
|
||||
IF v_collection_quantity < v_item.quantity THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
-- All items are available, trade is valid
|
||||
RETURN true;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Function to check and update validity of affected trades when collections change
|
||||
CREATE OR REPLACE FUNCTION public.update_affected_trades_validity()
|
||||
RETURNS TRIGGER
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_user_id uuid;
|
||||
v_card_id text;
|
||||
v_trade RECORD;
|
||||
v_is_valid boolean;
|
||||
BEGIN
|
||||
-- Get the user_id and card_id from the changed row
|
||||
IF (TG_OP = 'DELETE') THEN
|
||||
v_user_id := OLD.user_id;
|
||||
v_card_id := OLD.card_id;
|
||||
ELSE
|
||||
v_user_id := NEW.user_id;
|
||||
v_card_id := NEW.card_id;
|
||||
END IF;
|
||||
|
||||
-- Find all pending trades that involve this card from this user
|
||||
FOR v_trade IN
|
||||
SELECT DISTINCT t.id
|
||||
FROM public.trades t
|
||||
JOIN public.trade_items ti ON ti.trade_id = t.id
|
||||
WHERE t.status = 'pending'
|
||||
AND ti.owner_id = v_user_id
|
||||
AND ti.card_id = v_card_id
|
||||
LOOP
|
||||
-- Validate the trade
|
||||
v_is_valid := public.validate_trade(v_trade.id);
|
||||
|
||||
-- Update the trade's validity
|
||||
UPDATE public.trades
|
||||
SET is_valid = v_is_valid,
|
||||
updated_at = now()
|
||||
WHERE id = v_trade.id;
|
||||
END LOOP;
|
||||
|
||||
IF (TG_OP = 'DELETE') THEN
|
||||
RETURN OLD;
|
||||
ELSE
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Create trigger to auto-update trade validity when collections change
|
||||
CREATE TRIGGER update_trades_on_collection_change
|
||||
AFTER UPDATE OR DELETE ON public.collections
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.update_affected_trades_validity();
|
||||
|
||||
-- Add comment
|
||||
COMMENT ON COLUMN public.trades.is_valid IS 'Indicates if the trade can still be executed based on current collections. Auto-updated when collections change.';
|
||||
|
||||
-- Initial validation: set is_valid for all existing pending trades
|
||||
UPDATE public.trades
|
||||
SET is_valid = public.validate_trade(id)
|
||||
WHERE status = 'pending';
|
||||
Reference in New Issue
Block a user