2 Commits

Author SHA1 Message Date
Matthieu
459cc0eced Add trading and friends features with UI components and services 2025-11-24 14:43:49 +01:00
Matthieu
e94952ad20 Add Docker support with configuration files and environment setup 2025-11-24 14:21:42 +01:00
19 changed files with 2640 additions and 8 deletions

21
.dockerignore Normal file
View File

@@ -0,0 +1,21 @@
node_modules
dist
.git
.gitignore
.env
.env.*
!.env.example
*.md
!DOCKER.md
.vscode
.idea
*.log
npm-debug.log*
.DS_Store
Thumbs.db
coverage
.nyc_output
*.test.ts
*.test.tsx
*.spec.ts
*.spec.tsx

98
.env.example Normal file
View File

@@ -0,0 +1,98 @@
# =====================================================
# DECKERR DOCKER CONFIGURATION
# =====================================================
# Copy this file to .env and configure your settings
#
# Two deployment modes available:
# 1. External Supabase: Use docker-compose.yml (simpler)
# 2. Self-hosted Supabase: Use docker-compose.selfhosted.yml (full stack)
# =====================================================
# =====================================================
# MODE 1: EXTERNAL SUPABASE (docker-compose.yml)
# =====================================================
# Use this if you have:
# - A Supabase cloud account (supabase.com)
# - A separately self-hosted Supabase instance
# - Access to a paid hosted Supabase service
# Your Supabase project URL
VITE_SUPABASE_URL=https://your-project.supabase.co
# Your Supabase anonymous/public key
VITE_SUPABASE_ANON_KEY=your-anon-key-here
# Port to run Deckerr on (default: 3000)
PORT=3000
# =====================================================
# MODE 2: SELF-HOSTED SUPABASE (docker-compose.selfhosted.yml)
# =====================================================
# Use this to run everything locally, including Supabase
# --- Site Configuration ---
# Your domain or IP address (used for redirects)
SITE_URL=http://localhost:3000
# External API URL (Kong gateway)
API_EXTERNAL_URL=http://localhost:8000
# --- Port Configuration ---
DECKERR_PORT=3000
KONG_HTTP_PORT=8000
KONG_HTTPS_PORT=8443
POSTGRES_PORT=5432
# --- Security Keys ---
# IMPORTANT: Generate secure random values for production!
# You can use: openssl rand -base64 32
# PostgreSQL password
POSTGRES_PASSWORD=your-super-secret-postgres-password
# JWT Secret (must be at least 32 characters)
# Generate with: openssl rand -base64 32
JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters
# JWT Expiry in seconds (default: 3600 = 1 hour)
JWT_EXPIRY=3600
# Supabase Anonymous Key
# Generate at: https://supabase.com/docs/guides/self-hosting#api-keys
# Or use: npx @supabase/cli@latest gen key --type anon --jwt-secret "YOUR_JWT_SECRET"
ANON_KEY=your-anon-key
# Supabase Service Role Key (admin access)
# Generate at: https://supabase.com/docs/guides/self-hosting#api-keys
# Or use: npx @supabase/cli@latest gen key --type service_role --jwt-secret "YOUR_JWT_SECRET"
SERVICE_ROLE_KEY=your-service-role-key
# --- Email Configuration (Optional) ---
# Required for email verification and password reset
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-email@example.com
SMTP_PASS=your-email-password
SMTP_ADMIN_EMAIL=admin@example.com
SMTP_SENDER_NAME=Deckerr
# Enable email auto-confirm (set to true to skip email verification)
ENABLE_EMAIL_AUTOCONFIRM=true
# --- Feature Flags ---
# Disable new user signups
DISABLE_SIGNUP=false
# Enable email signup
ENABLE_EMAIL_SIGNUP=true
# Enable anonymous users
ENABLE_ANONYMOUS_USERS=false
# --- Advanced ---
# Additional redirect URLs (comma-separated)
ADDITIONAL_REDIRECT_URLS=
# PostgREST schemas
PGRST_DB_SCHEMAS=public,graphql_public

191
DOCKER.md Normal file
View File

@@ -0,0 +1,191 @@
# Deckerr Docker Deployment
Self-host Deckerr with two deployment options:
## Deployment Options
| Option | Use Case | Complexity |
|--------|----------|------------|
| **External Supabase** | Use hosted Supabase (cloud or paid) | Simple |
| **Self-hosted Supabase** | Run everything locally | Advanced |
---
## Option 1: External Supabase (Recommended)
Use your own Supabase instance (cloud, paid hosted, or separately self-hosted).
### Quick Start
```bash
# 1. Copy environment template
cp .env.example .env
# 2. Edit .env with your Supabase credentials
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key
PORT=3000
# 3. Run database migrations on your Supabase
# Go to Supabase Dashboard > SQL Editor and run:
# Contents of supabase/migrations/20250131132458_black_frost.sql
# 4. Start Deckerr
docker-compose up -d
# 5. Access at http://localhost:3000
```
### Using Hosted Supabase (Paid Service)
Contact the Deckerr team for access credentials to use the hosted backend.
---
## Option 2: Self-Hosted Supabase (Full Stack)
Run Deckerr with a complete self-hosted Supabase stack.
### Prerequisites
- Docker & Docker Compose
- 2GB+ RAM
- Ports: 3000, 5432, 8000
### Quick Start
```bash
# 1. Copy environment template
cp .env.example .env
# 2. Generate secure keys
# JWT Secret (required)
openssl rand -base64 32
# Generate Supabase API keys
# Option A: Use online generator at https://supabase.com/docs/guides/self-hosting#api-keys
# Option B: Use Supabase CLI
npx @supabase/cli@latest gen key --type anon --jwt-secret "YOUR_JWT_SECRET"
npx @supabase/cli@latest gen key --type service_role --jwt-secret "YOUR_JWT_SECRET"
# 3. Update .env with your generated values
POSTGRES_PASSWORD=<generated-password>
JWT_SECRET=<generated-jwt-secret>
ANON_KEY=<generated-anon-key>
SERVICE_ROLE_KEY=<generated-service-key>
# 4. Start all services
docker-compose -f docker-compose.selfhosted.yml up -d
# 5. Access Deckerr at http://localhost:3000
# API available at http://localhost:8000
```
### Generate Keys Script
```bash
#!/bin/bash
JWT_SECRET=$(openssl rand -base64 32)
echo "JWT_SECRET=$JWT_SECRET"
echo ""
echo "Now generate API keys at:"
echo "https://supabase.com/docs/guides/self-hosting#api-keys"
echo "Use this JWT secret: $JWT_SECRET"
```
### Self-Hosted Services
| Service | Port | Description |
|---------|------|-------------|
| Deckerr | 3000 | Frontend app |
| Kong | 8000 | API Gateway |
| PostgreSQL | 5432 | Database |
| Auth | 9999 | Authentication (internal) |
| REST | 3000 | PostgREST API (internal) |
| Realtime | 4000 | WebSocket (internal) |
---
## Environment Variables
### External Supabase Mode
| Variable | Required | Description |
|----------|----------|-------------|
| `VITE_SUPABASE_URL` | Yes | Supabase project URL |
| `VITE_SUPABASE_ANON_KEY` | Yes | Supabase anonymous key |
| `PORT` | No | App port (default: 3000) |
### Self-Hosted Mode
| Variable | Required | Description |
|----------|----------|-------------|
| `POSTGRES_PASSWORD` | Yes | PostgreSQL password |
| `JWT_SECRET` | Yes | JWT signing secret (32+ chars) |
| `ANON_KEY` | Yes | Supabase anonymous key |
| `SERVICE_ROLE_KEY` | Yes | Supabase service role key |
| `SITE_URL` | No | Your domain (default: localhost) |
| `SMTP_*` | No | Email configuration |
---
## Commands
```bash
# Start (external Supabase)
docker-compose up -d
# Start (self-hosted)
docker-compose -f docker-compose.selfhosted.yml up -d
# Stop
docker-compose down
# View logs
docker-compose logs -f
# Rebuild after code changes
docker-compose build --no-cache
docker-compose up -d
# Reset database (self-hosted only)
docker-compose -f docker-compose.selfhosted.yml down -v
docker-compose -f docker-compose.selfhosted.yml up -d
```
---
## Production Checklist
- [ ] Use strong passwords (generate with `openssl rand -base64 32`)
- [ ] Configure HTTPS with reverse proxy (nginx, Traefik, Caddy)
- [ ] Set up email (SMTP) for password reset
- [ ] Configure firewall rules
- [ ] Set up backups for PostgreSQL volume
- [ ] Consider rate limiting at reverse proxy level
---
## Troubleshooting
### Container won't start
```bash
docker-compose logs <service-name>
```
### Database connection issues
```bash
# Check if database is healthy
docker-compose exec db pg_isready -U postgres
```
### Reset everything
```bash
docker-compose down -v
docker-compose up -d --build
```
### Check service health
```bash
docker-compose ps
```

39
Dockerfile Normal file
View File

@@ -0,0 +1,39 @@
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy source code
COPY . .
# Build arguments for Supabase configuration
ARG VITE_SUPABASE_URL
ARG VITE_SUPABASE_ANON_KEY
# Set environment variables for build
ENV VITE_SUPABASE_URL=$VITE_SUPABASE_URL
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
# Build the application
RUN npm run build
# Production stage
FROM nginx:alpine
# Copy custom nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Copy built assets from builder
COPY --from=builder /app/dist /usr/share/nginx/html
# Expose port 80
EXPOSE 80
# Start nginx
CMD ["nginx", "-g", "daemon off;"]

View File

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

View File

@@ -0,0 +1,201 @@
version: '3.8'
# Full self-hosted deployment with Supabase included
# This includes PostgreSQL, Auth, REST API, and the Deckerr frontend
services:
# ============================================
# DECKERR FRONTEND
# ============================================
deckerr:
build:
context: .
dockerfile: Dockerfile
args:
- VITE_SUPABASE_URL=http://${SITE_URL:-localhost}:${KONG_HTTP_PORT:-8000}
- VITE_SUPABASE_ANON_KEY=${ANON_KEY}
container_name: deckerr
ports:
- "${DECKERR_PORT:-3000}:80"
restart: unless-stopped
depends_on:
kong:
condition: service_healthy
# ============================================
# SUPABASE SERVICES
# ============================================
# PostgreSQL Database
db:
image: supabase/postgres:15.1.1.78
container_name: supabase-db
healthcheck:
test: pg_isready -U postgres -h localhost
interval: 5s
timeout: 5s
retries: 10
ports:
- "${POSTGRES_PORT:-5432}:5432"
environment:
POSTGRES_HOST: /var/run/postgresql
PGPORT: 5432
POSTGRES_PORT: 5432
PGPASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
PGDATABASE: postgres
POSTGRES_DB: postgres
volumes:
- supabase-db-data:/var/lib/postgresql/data
- ./supabase/migrations:/docker-entrypoint-initdb.d/migrations
restart: unless-stopped
# Supabase Kong API Gateway
kong:
image: kong:2.8.1
container_name: supabase-kong
restart: unless-stopped
ports:
- "${KONG_HTTP_PORT:-8000}:8000/tcp"
- "${KONG_HTTPS_PORT:-8443}:8443/tcp"
depends_on:
db:
condition: service_healthy
environment:
KONG_DATABASE: "off"
KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
KONG_DNS_ORDER: LAST,A,CNAME
KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
SUPABASE_ANON_KEY: ${ANON_KEY}
SUPABASE_SERVICE_KEY: ${SERVICE_ROLE_KEY}
volumes:
- ./docker/kong.yml:/home/kong/kong.yml:ro
healthcheck:
test: ["CMD", "kong", "health"]
interval: 10s
timeout: 10s
retries: 5
# Supabase Auth (GoTrue)
auth:
image: supabase/gotrue:v2.143.0
container_name: supabase-auth
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9999/health"]
interval: 5s
timeout: 5s
retries: 3
restart: unless-stopped
environment:
GOTRUE_API_HOST: 0.0.0.0
GOTRUE_API_PORT: 9999
API_EXTERNAL_URL: ${API_EXTERNAL_URL:-http://localhost:8000}
GOTRUE_DB_DRIVER: postgres
GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${POSTGRES_PASSWORD}@db:5432/postgres
GOTRUE_SITE_URL: ${SITE_URL:-http://localhost:3000}
GOTRUE_URI_ALLOW_LIST: ${ADDITIONAL_REDIRECT_URLS:-}
GOTRUE_DISABLE_SIGNUP: ${DISABLE_SIGNUP:-false}
GOTRUE_JWT_ADMIN_ROLES: service_role
GOTRUE_JWT_AUD: authenticated
GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
GOTRUE_JWT_EXP: ${JWT_EXPIRY:-3600}
GOTRUE_JWT_SECRET: ${JWT_SECRET}
GOTRUE_EXTERNAL_EMAIL_ENABLED: ${ENABLE_EMAIL_SIGNUP:-true}
GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: ${ENABLE_ANONYMOUS_USERS:-false}
GOTRUE_MAILER_AUTOCONFIRM: ${ENABLE_EMAIL_AUTOCONFIRM:-false}
GOTRUE_SMTP_HOST: ${SMTP_HOST:-}
GOTRUE_SMTP_PORT: ${SMTP_PORT:-587}
GOTRUE_SMTP_USER: ${SMTP_USER:-}
GOTRUE_SMTP_PASS: ${SMTP_PASS:-}
GOTRUE_SMTP_ADMIN_EMAIL: ${SMTP_ADMIN_EMAIL:-}
GOTRUE_SMTP_SENDER_NAME: ${SMTP_SENDER_NAME:-Deckerr}
GOTRUE_MAILER_URLPATHS_INVITE: /auth/v1/verify
GOTRUE_MAILER_URLPATHS_CONFIRMATION: /auth/v1/verify
GOTRUE_MAILER_URLPATHS_RECOVERY: /auth/v1/verify
GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: /auth/v1/verify
# Supabase REST API (PostgREST)
rest:
image: postgrest/postgrest:v12.0.1
container_name: supabase-rest
depends_on:
db:
condition: service_healthy
restart: unless-stopped
environment:
PGRST_DB_URI: postgres://authenticator:${POSTGRES_PASSWORD}@db:5432/postgres
PGRST_DB_SCHEMAS: ${PGRST_DB_SCHEMAS:-public,graphql_public}
PGRST_DB_ANON_ROLE: anon
PGRST_JWT_SECRET: ${JWT_SECRET}
PGRST_DB_USE_LEGACY_GUCS: "false"
PGRST_APP_SETTINGS_JWT_SECRET: ${JWT_SECRET}
PGRST_APP_SETTINGS_JWT_EXP: ${JWT_EXPIRY:-3600}
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:3000/ready || exit 1"]
interval: 10s
timeout: 5s
retries: 3
# Supabase Realtime
realtime:
image: supabase/realtime:v2.28.32
container_name: supabase-realtime
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "-sSfL", "--head", "-o", "/dev/null", "-H", "Authorization: Bearer ${ANON_KEY}", "http://localhost:4000/api/tenants/realtime-dev/health"]
interval: 10s
timeout: 5s
retries: 3
restart: unless-stopped
environment:
PORT: 4000
DB_HOST: db
DB_PORT: 5432
DB_USER: supabase_admin
DB_PASSWORD: ${POSTGRES_PASSWORD}
DB_NAME: postgres
DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'
DB_ENC_KEY: supabaserealtime
API_JWT_SECRET: ${JWT_SECRET}
SECRET_KEY_BASE: ${SECRET_KEY_BASE:-UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq}
ERL_AFLAGS: -proto_dist inet_tcp
DNS_NODES: "''"
RLIMIT_NOFILE: "10000"
APP_NAME: realtime
SEED_SELF_HOST: true
REPLICATION_MODE: RLS
REPLICATION_POLL_INTERVAL: 100
SECURE_CHANNELS: "true"
SLOT_NAME: supabase_realtime_rls
TEMPORARY_SLOT: "true"
# Supabase Meta (for Studio - optional)
meta:
image: supabase/postgres-meta:v0.80.0
container_name: supabase-meta
depends_on:
db:
condition: service_healthy
restart: unless-stopped
environment:
PG_META_PORT: 8080
PG_META_DB_HOST: db
PG_META_DB_PORT: 5432
PG_META_DB_NAME: postgres
PG_META_DB_USER: supabase_admin
PG_META_DB_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
supabase-db-data:

22
docker-compose.yml Normal file
View File

@@ -0,0 +1,22 @@
version: '3.8'
# Simple deployment - Uses external Supabase (hosted or self-hosted separately)
# For full self-hosted setup with Supabase included, use docker-compose.selfhosted.yml
services:
deckerr:
build:
context: .
dockerfile: Dockerfile
args:
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
container_name: deckerr
ports:
- "${PORT:-3000}:80"
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:80"]
interval: 30s
timeout: 10s
retries: 3

138
docker/kong.yml Normal file
View File

@@ -0,0 +1,138 @@
_format_version: "2.1"
_transform: true
###
### Consumers / Users
###
consumers:
- username: DASHBOARD
- username: anon
keyauth_credentials:
- key: ${SUPABASE_ANON_KEY}
- username: service_role
keyauth_credentials:
- key: ${SUPABASE_SERVICE_KEY}
###
### Access Control Lists
###
acls:
- consumer: anon
group: anon
- consumer: service_role
group: admin
###
### API Routes
###
services:
## Open Auth routes
- name: auth-v1-open
url: http://auth:9999/verify
routes:
- name: auth-v1-open
strip_path: true
paths:
- /auth/v1/verify
plugins:
- name: cors
- name: auth-v1-open-callback
url: http://auth:9999/callback
routes:
- name: auth-v1-open-callback
strip_path: true
paths:
- /auth/v1/callback
plugins:
- name: cors
- name: auth-v1-open-authorize
url: http://auth:9999/authorize
routes:
- name: auth-v1-open-authorize
strip_path: true
paths:
- /auth/v1/authorize
plugins:
- name: cors
## Secure Auth routes
- name: auth-v1
_comment: "GoTrue: /auth/v1/* -> http://auth:9999/*"
url: http://auth:9999/
routes:
- name: auth-v1-all
strip_path: true
paths:
- /auth/v1/
plugins:
- name: cors
- name: key-auth
config:
hide_credentials: false
- name: acl
config:
hide_groups_header: true
allow:
- admin
- anon
## Secure REST routes
- name: rest-v1
_comment: "PostgREST: /rest/v1/* -> http://rest:3000/*"
url: http://rest:3000/
routes:
- name: rest-v1-all
strip_path: true
paths:
- /rest/v1/
plugins:
- name: cors
- name: key-auth
config:
hide_credentials: false
- name: acl
config:
hide_groups_header: true
allow:
- admin
- anon
## Realtime routes
- name: realtime-v1
_comment: "Realtime: /realtime/v1/* -> ws://realtime:4000/socket/*"
url: http://realtime:4000/socket/
routes:
- name: realtime-v1-all
strip_path: true
paths:
- /realtime/v1/
plugins:
- name: cors
- name: key-auth
config:
hide_credentials: false
- name: acl
config:
hide_groups_header: true
allow:
- admin
- anon
## Meta routes (for Supabase Studio)
- name: meta
_comment: "pg-meta: /pg/* -> http://meta:8080/*"
url: http://meta:8080/
routes:
- name: meta-all
strip_path: true
paths:
- /pg/
plugins:
- name: key-auth
config:
hide_credentials: false
- name: acl
config:
hide_groups_header: true
allow:
- admin

29
nginx.conf Normal file
View File

@@ -0,0 +1,29 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/javascript application/json;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Handle SPA routing - serve index.html for all routes
location / {
try_files $uri $uri/ /index.html;
}
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
}

View File

@@ -8,10 +8,13 @@ import React, { useState } from 'react';
import Profile from './components/Profile';
import CardSearch from './components/CardSearch';
import LifeCounter from './components/LifeCounter';
import Friends from './components/Friends';
import Trades from './components/Trades';
import Community from './components/Community';
import PWAInstallPrompt from './components/PWAInstallPrompt';
import { AuthProvider, useAuth } from './contexts/AuthContext';
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'profile' | 'search' | 'life-counter';
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
function AppContent() {
const [currentPage, setCurrentPage] = useState<Page>('home');
@@ -69,6 +72,12 @@ import React, { useState } from 'react';
return <CardSearch />;
case 'life-counter':
return <LifeCounter />;
case 'friends':
return <Friends />;
case 'trades':
return <Trades />;
case 'community':
return <Community />;
case 'login':
return <LoginForm />;
default:

View File

@@ -0,0 +1,305 @@
import React, { useState, useEffect } from 'react';
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
import { getFriends, Friend } from '../services/friendsService';
import { getUserCollection, getCardsByIds } from '../services/api';
import { Card } from '../types';
import TradeCreator from './TradeCreator';
interface UserProfile {
id: string;
username: string | null;
collection_visibility: 'public' | 'friends' | 'private' | null;
}
interface CollectionItem {
card: Card;
quantity: number;
}
type Tab = 'public' | 'friends';
export default function Community() {
const { user } = useAuth();
const [activeTab, setActiveTab] = useState<Tab>('public');
const [searchQuery, setSearchQuery] = useState('');
const [publicUsers, setPublicUsers] = useState<UserProfile[]>([]);
const [friends, setFriends] = useState<Friend[]>([]);
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
const [loading, setLoading] = useState(true);
const [loadingCollection, setLoadingCollection] = useState(false);
const [showTradeCreator, setShowTradeCreator] = useState(false);
useEffect(() => {
if (user) {
loadData();
}
}, [user]);
const loadData = async () => {
if (!user) return;
setLoading(true);
try {
const [publicData, friendsData] = await Promise.all([
loadPublicUsers(),
getFriends(user.id),
]);
setPublicUsers(publicData);
setFriends(friendsData);
} catch (error) {
console.error('Error loading community data:', error);
} finally {
setLoading(false);
}
};
const loadPublicUsers = async (): Promise<UserProfile[]> => {
const { data, error } = await supabase
.from('profiles')
.select('id, username, collection_visibility')
.eq('collection_visibility', 'public')
.neq('id', user?.id)
.order('username');
if (error) throw error;
return data || [];
};
const loadUserCollection = async (userId: string) => {
setLoadingCollection(true);
try {
const collectionMap = await getUserCollection(userId);
if (collectionMap.size === 0) {
setSelectedUserCollection([]);
return;
}
const cardIds = Array.from(collectionMap.keys());
const cards = await getCardsByIds(cardIds);
const collectionWithCards = cards.map((card) => ({
card,
quantity: collectionMap.get(card.id) || 0,
}));
setSelectedUserCollection(collectionWithCards);
} catch (error) {
console.error('Error loading collection:', error);
setSelectedUserCollection([]);
} finally {
setLoadingCollection(false);
}
};
const handleViewCollection = async (userProfile: UserProfile) => {
setSelectedUser(userProfile);
await loadUserCollection(userProfile.id);
};
const filteredPublicUsers = publicUsers.filter(
(u) => !searchQuery || u.username?.toLowerCase().includes(searchQuery.toLowerCase())
);
const friendProfiles: UserProfile[] = friends.map((f) => ({
id: f.id,
username: f.username,
collection_visibility: 'friends' as const,
}));
const filteredFriends = friendProfiles.filter(
(f) => !searchQuery || f.username?.toLowerCase().includes(searchQuery.toLowerCase())
);
if (loading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
// If viewing a user's collection
if (selectedUser) {
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-6">
<div>
<button
onClick={() => {
setSelectedUser(null);
setSelectedUserCollection([]);
}}
className="text-blue-400 hover:text-blue-300 mb-2"
>
Back to Community
</button>
<h1 className="text-3xl font-bold">{selectedUser.username}'s Collection</h1>
</div>
<button
onClick={() => setShowTradeCreator(true)}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition"
>
<ArrowLeftRight size={20} />
Propose Trade
</button>
</div>
{/* Collection Grid */}
{loadingCollection ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="animate-spin text-blue-500" size={48} />
</div>
) : selectedUserCollection.length === 0 ? (
<p className="text-gray-400 text-center py-12">This collection is empty</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-7 xl:grid-cols-9 gap-2 sm:gap-3">
{selectedUserCollection.map(({ card, quantity }) => (
<div key={card.id} className="relative group">
<div className="rounded-lg overflow-hidden shadow-lg">
<img
src={card.image_uris?.normal || card.image_uris?.small}
alt={card.name}
className="w-full h-auto"
/>
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs font-bold px-2 py-1 rounded-full">
x{quantity}
</div>
</div>
<div className="mt-1 text-xs text-center truncate px-1">{card.name}</div>
</div>
))}
</div>
)}
{/* Trade Creator Modal */}
{showTradeCreator && (
<TradeCreator
receiverId={selectedUser.id}
receiverUsername={selectedUser.username || 'Unknown'}
receiverCollection={selectedUserCollection}
onClose={() => setShowTradeCreator(false)}
onTradeCreated={() => {
setShowTradeCreator(false);
alert('Trade proposal sent!');
}}
/>
)}
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-4xl mx-auto">
<h1 className="text-3xl font-bold mb-6">Community</h1>
{/* Search */}
<div className="relative mb-6">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search users..."
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
{/* Tabs */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setActiveTab('public')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'public'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Globe size={18} />
Public Collections ({filteredPublicUsers.length})
</button>
<button
onClick={() => setActiveTab('friends')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'friends'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Users size={18} />
Friends ({filteredFriends.length})
</button>
</div>
{/* User List */}
<div className="space-y-3">
{activeTab === 'public' && (
<>
{filteredPublicUsers.length === 0 ? (
<p className="text-gray-400 text-center py-8">
No public collections found
</p>
) : (
filteredPublicUsers.map((userProfile) => (
<div
key={userProfile.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<div className="flex items-center gap-3">
<Globe size={20} className="text-green-400" />
<span className="font-medium">{userProfile.username || 'Unknown'}</span>
</div>
<button
onClick={() => handleViewCollection(userProfile)}
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
>
<Eye size={16} />
View Collection
</button>
</div>
))
)}
</>
)}
{activeTab === 'friends' && (
<>
{filteredFriends.length === 0 ? (
<p className="text-gray-400 text-center py-8">
{friends.length === 0
? 'Add friends to see their collections'
: 'No friends match your search'}
</p>
) : (
filteredFriends.map((friend) => (
<div
key={friend.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<div className="flex items-center gap-3">
<Users size={20} className="text-blue-400" />
<span className="font-medium">{friend.username || 'Unknown'}</span>
</div>
<button
onClick={() => handleViewCollection(friend)}
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
>
<Eye size={16} />
View Collection
</button>
</div>
))
)}
</>
)}
</div>
</div>
</div>
);
}

312
src/components/Friends.tsx Normal file
View File

@@ -0,0 +1,312 @@
import React, { useState, useEffect } from 'react';
import { Search, UserPlus, UserMinus, Check, X, Users, Clock, Send } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import {
getFriends,
getPendingRequests,
getSentRequests,
searchUsers,
sendFriendRequest,
acceptFriendRequest,
declineFriendRequest,
removeFriend,
Friend,
} from '../services/friendsService';
type Tab = 'friends' | 'requests' | 'search';
export default function Friends() {
const { user } = useAuth();
const [activeTab, setActiveTab] = useState<Tab>('friends');
const [friends, setFriends] = useState<Friend[]>([]);
const [pendingRequests, setPendingRequests] = useState<Friend[]>([]);
const [sentRequests, setSentRequests] = useState<Friend[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<{ id: string; username: string | null }[]>([]);
const [loading, setLoading] = useState(true);
const [searching, setSearching] = useState(false);
useEffect(() => {
if (user) {
loadFriendsData();
}
}, [user]);
const loadFriendsData = async () => {
if (!user) return;
setLoading(true);
try {
const [friendsData, pendingData, sentData] = await Promise.all([
getFriends(user.id),
getPendingRequests(user.id),
getSentRequests(user.id),
]);
setFriends(friendsData);
setPendingRequests(pendingData);
setSentRequests(sentData);
} catch (error) {
console.error('Error loading friends:', error);
} finally {
setLoading(false);
}
};
const handleSearch = async () => {
if (!user || searchQuery.trim().length < 2) return;
setSearching(true);
try {
const results = await searchUsers(searchQuery, user.id);
setSearchResults(results || []);
} catch (error) {
console.error('Error searching users:', error);
} finally {
setSearching(false);
}
};
const handleSendRequest = async (addresseeId: string) => {
if (!user) return;
try {
await sendFriendRequest(user.id, addresseeId);
setSearchResults((prev) => prev.filter((u) => u.id !== addresseeId));
await loadFriendsData();
} catch (error) {
console.error('Error sending friend request:', error);
alert('Failed to send friend request');
}
};
const handleAcceptRequest = async (friendshipId: string) => {
try {
await acceptFriendRequest(friendshipId);
await loadFriendsData();
} catch (error) {
console.error('Error accepting request:', error);
}
};
const handleDeclineRequest = async (friendshipId: string) => {
try {
await declineFriendRequest(friendshipId);
await loadFriendsData();
} catch (error) {
console.error('Error declining request:', error);
}
};
const handleRemoveFriend = async (friendshipId: string) => {
if (!confirm('Remove this friend?')) return;
try {
await removeFriend(friendshipId);
await loadFriendsData();
} catch (error) {
console.error('Error removing friend:', error);
}
};
const isAlreadyFriendOrPending = (userId: string) => {
return (
friends.some((f) => f.id === userId) ||
pendingRequests.some((f) => f.id === userId) ||
sentRequests.some((f) => f.id === userId)
);
};
if (loading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-2xl mx-auto">
<h1 className="text-3xl font-bold mb-6">Friends</h1>
{/* Tabs */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setActiveTab('friends')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'friends'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Users size={18} />
Friends ({friends.length})
</button>
<button
onClick={() => setActiveTab('requests')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'requests'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Clock size={18} />
Requests ({pendingRequests.length})
</button>
<button
onClick={() => setActiveTab('search')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'search'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Search size={18} />
Search
</button>
</div>
{/* Friends List */}
{activeTab === 'friends' && (
<div className="space-y-3">
{friends.length === 0 ? (
<p className="text-gray-400 text-center py-8">
No friends yet. Search for users to add them!
</p>
) : (
friends.map((friend) => (
<div
key={friend.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<span className="font-medium">{friend.username || 'Unknown'}</span>
<button
onClick={() => handleRemoveFriend(friend.friendshipId)}
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
title="Remove friend"
>
<UserMinus size={20} />
</button>
</div>
))
)}
</div>
)}
{/* Requests Tab */}
{activeTab === 'requests' && (
<div className="space-y-6">
{/* Received Requests */}
<div>
<h2 className="text-lg font-semibold mb-3 text-gray-300">Received Requests</h2>
{pendingRequests.length === 0 ? (
<p className="text-gray-500 text-sm">No pending requests</p>
) : (
<div className="space-y-3">
{pendingRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<span className="font-medium">{request.username || 'Unknown'}</span>
<div className="flex gap-2">
<button
onClick={() => handleAcceptRequest(request.friendshipId)}
className="p-2 text-green-400 hover:bg-green-400/20 rounded-lg transition"
title="Accept"
>
<Check size={20} />
</button>
<button
onClick={() => handleDeclineRequest(request.friendshipId)}
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
title="Decline"
>
<X size={20} />
</button>
</div>
</div>
))}
</div>
)}
</div>
{/* Sent Requests */}
<div>
<h2 className="text-lg font-semibold mb-3 text-gray-300">Sent Requests</h2>
{sentRequests.length === 0 ? (
<p className="text-gray-500 text-sm">No sent requests</p>
) : (
<div className="space-y-3">
{sentRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<div className="flex items-center gap-2">
<Send size={16} className="text-gray-500" />
<span className="font-medium">{request.username || 'Unknown'}</span>
</div>
<span className="text-sm text-yellow-500">Pending</span>
</div>
))}
</div>
)}
</div>
</div>
)}
{/* Search Tab */}
{activeTab === 'search' && (
<div className="space-y-4">
<div className="flex gap-2">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
placeholder="Search by username..."
className="flex-1 px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<button
onClick={handleSearch}
disabled={searching || searchQuery.trim().length < 2}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg transition"
>
{searching ? (
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
) : (
<Search size={20} />
)}
</button>
</div>
{searchResults.length > 0 && (
<div className="space-y-3">
{searchResults.map((result) => (
<div
key={result.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<span className="font-medium">{result.username || 'Unknown'}</span>
{isAlreadyFriendOrPending(result.id) ? (
<span className="text-sm text-gray-500">Already connected</span>
) : (
<button
onClick={() => handleSendRequest(result.id)}
className="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition text-sm"
>
<UserPlus size={16} />
Add Friend
</button>
)}
</div>
))}
</div>
)}
{searchQuery.length >= 2 && searchResults.length === 0 && !searching && (
<p className="text-gray-400 text-center py-4">No users found</p>
)}
</div>
)}
</div>
</div>
);
}

View File

@@ -1,9 +1,9 @@
import React, { useState, useRef, useEffect } from 'react';
import { Home, PlusSquare, Library, LogOut, Settings, ChevronDown, Search, Heart, Menu } from 'lucide-react';
import { Home, PlusSquare, Library, LogOut, Settings, ChevronDown, Search, Heart, Menu, Users, ArrowLeftRight, Globe } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter';
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
interface NavigationProps {
currentPage: Page;
@@ -53,8 +53,11 @@ import React, { useState, useRef, useEffect } from 'react';
const navItems = [
{ id: 'home' as const, label: 'Decks', icon: Library },
{ id: 'collection' as const, label: 'Collection', icon: Library },
{ id: 'community' as const, label: 'Community', icon: Globe },
{ id: 'friends' as const, label: 'Friends', icon: Users },
{ id: 'trades' as const, label: 'Trades', icon: ArrowLeftRight },
{ id: 'search' as const, label: 'Search', icon: Search },
{ id: 'life-counter' as const, label: 'Life Counter', icon: Heart },
{ id: 'life-counter' as const, label: 'Life', icon: Heart },
];
const handleSignOut = async () => {

View File

@@ -1,14 +1,23 @@
import React, { useState, useEffect } from 'react';
import { Save } from 'lucide-react';
import { Save, Globe, Users, Lock } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
const THEME_COLORS = ['red', 'green', 'blue', 'yellow', 'grey', 'purple'];
const VISIBILITY_OPTIONS = [
{ value: 'public', label: 'Public', icon: Globe, description: 'Anyone can view your collection' },
{ value: 'friends', label: 'Friends Only', icon: Users, description: 'Only friends can view your collection' },
{ value: 'private', label: 'Private', icon: Lock, description: 'Only you can view your collection' },
] as const;
type CollectionVisibility = 'public' | 'friends' | 'private';
export default function Profile() {
const { user } = useAuth();
const [username, setUsername] = useState('');
const [themeColor, setThemeColor] = useState('blue');
const [collectionVisibility, setCollectionVisibility] = useState<CollectionVisibility>('private');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -17,13 +26,14 @@ export default function Profile() {
if (user) {
const { data, error } = await supabase
.from('profiles')
.select('username, theme_color')
.select('username, theme_color, collection_visibility')
.eq('id', user.id)
.single();
if (data) {
setUsername(data.username || '');
setThemeColor(data.theme_color || 'blue');
setCollectionVisibility((data.collection_visibility as CollectionVisibility) || 'private');
}
setLoading(false);
}
@@ -44,6 +54,7 @@ export default function Profile() {
id: user.id,
username,
theme_color: themeColor,
collection_visibility: collectionVisibility,
updated_at: new Date()
});
@@ -107,6 +118,35 @@ export default function Profile() {
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Collection Visibility
</label>
<div className="space-y-2">
{VISIBILITY_OPTIONS.map((option) => {
const Icon = option.icon;
return (
<button
key={option.value}
type="button"
onClick={() => setCollectionVisibility(option.value)}
className={`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left
${collectionVisibility === option.value
? 'border-blue-500 bg-blue-500/10'
: 'border-gray-700 hover:border-gray-600 bg-gray-800'
}`}
>
<Icon size={20} className={collectionVisibility === option.value ? 'text-blue-400' : 'text-gray-400'} />
<div>
<div className="font-medium">{option.label}</div>
<div className="text-sm text-gray-400">{option.description}</div>
</div>
</button>
);
})}
</div>
</div>
<button
type="submit"
disabled={saving}

View File

@@ -0,0 +1,380 @@
import React, { useState, useEffect } from 'react';
import { X, ArrowLeftRight, Plus, Minus, Send, Gift } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { getUserCollection, getCardsByIds } from '../services/api';
import { createTrade } from '../services/tradesService';
import { Card } from '../types';
interface CollectionItem {
card: Card;
quantity: number;
}
interface TradeCreatorProps {
receiverId: string;
receiverUsername: string;
receiverCollection: CollectionItem[];
onClose: () => void;
onTradeCreated: () => void;
}
interface SelectedCard {
card: Card;
quantity: number;
maxQuantity: number;
}
export default function TradeCreator({
receiverId,
receiverUsername,
receiverCollection,
onClose,
onTradeCreated,
}: TradeCreatorProps) {
const { user } = useAuth();
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState('');
// Cards I'm offering (from my collection)
const [myOfferedCards, setMyOfferedCards] = useState<Map<string, SelectedCard>>(new Map());
// Cards I want (from their collection)
const [wantedCards, setWantedCards] = useState<Map<string, SelectedCard>>(new Map());
useEffect(() => {
loadMyCollection();
}, [user]);
const loadMyCollection = async () => {
if (!user) return;
setLoading(true);
try {
const collectionMap = await getUserCollection(user.id);
if (collectionMap.size === 0) {
setMyCollection([]);
return;
}
const cardIds = Array.from(collectionMap.keys());
const cards = await getCardsByIds(cardIds);
const collectionWithCards = cards.map((card) => ({
card,
quantity: collectionMap.get(card.id) || 0,
}));
setMyCollection(collectionWithCards);
} catch (error) {
console.error('Error loading my collection:', error);
} finally {
setLoading(false);
}
};
const addToOffer = (card: Card, maxQuantity: number) => {
setMyOfferedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(card.id);
if (existing) {
if (existing.quantity < existing.maxQuantity) {
newMap.set(card.id, { ...existing, quantity: existing.quantity + 1 });
}
} else {
newMap.set(card.id, { card, quantity: 1, maxQuantity });
}
return newMap;
});
};
const removeFromOffer = (cardId: string) => {
setMyOfferedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(cardId);
if (existing && existing.quantity > 1) {
newMap.set(cardId, { ...existing, quantity: existing.quantity - 1 });
} else {
newMap.delete(cardId);
}
return newMap;
});
};
const addToWanted = (card: Card, maxQuantity: number) => {
setWantedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(card.id);
if (existing) {
if (existing.quantity < existing.maxQuantity) {
newMap.set(card.id, { ...existing, quantity: existing.quantity + 1 });
}
} else {
newMap.set(card.id, { card, quantity: 1, maxQuantity });
}
return newMap;
});
};
const removeFromWanted = (cardId: string) => {
setWantedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(cardId);
if (existing && existing.quantity > 1) {
newMap.set(cardId, { ...existing, quantity: existing.quantity - 1 });
} else {
newMap.delete(cardId);
}
return newMap;
});
};
const handleSubmit = async () => {
if (!user) return;
// At least one side should have cards (allowing gifts)
if (myOfferedCards.size === 0 && wantedCards.size === 0) {
alert('Please select at least one card to trade or gift');
return;
}
setSubmitting(true);
try {
const senderCards = Array.from(myOfferedCards.values()).map((item) => ({
cardId: item.card.id,
quantity: item.quantity,
}));
const receiverCards = Array.from(wantedCards.values()).map((item) => ({
cardId: item.card.id,
quantity: item.quantity,
}));
await createTrade({
senderId: user.id,
receiverId,
message: message || undefined,
senderCards,
receiverCards,
});
onTradeCreated();
} catch (error) {
console.error('Error creating trade:', error);
alert('Failed to create trade');
} finally {
setSubmitting(false);
}
};
const isGift = myOfferedCards.size > 0 && wantedCards.size === 0;
const isRequest = myOfferedCards.size === 0 && wantedCards.size > 0;
return (
<div className="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center p-4">
<div className="bg-gray-800 rounded-lg w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-gray-700">
<div className="flex items-center gap-2">
<ArrowLeftRight size={24} className="text-blue-400" />
<h2 className="text-xl font-bold">Trade with {receiverUsername}</h2>
</div>
<button
onClick={onClose}
className="p-2 hover:bg-gray-700 rounded-lg transition"
>
<X size={24} />
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-hidden flex flex-col md:flex-row">
{/* My Collection (Left) */}
<div className="flex-1 p-4 border-b md:border-b-0 md:border-r border-gray-700 overflow-y-auto">
<h3 className="text-lg font-semibold mb-3 text-green-400">
My Collection (I give)
</h3>
{loading ? (
<div className="flex justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
) : myCollection.length === 0 ? (
<p className="text-gray-400 text-center py-4">Your collection is empty</p>
) : (
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
{myCollection.map(({ card, quantity }) => {
const offered = myOfferedCards.get(card.id);
const remainingQty = quantity - (offered?.quantity || 0);
return (
<div
key={card.id}
className={`relative cursor-pointer rounded-lg overflow-hidden transition ${
offered ? 'ring-2 ring-green-500' : 'hover:ring-2 hover:ring-gray-500'
}`}
onClick={() => remainingQty > 0 && addToOffer(card, quantity)}
>
<img
src={card.image_uris?.small}
alt={card.name}
className={`w-full h-auto ${remainingQty === 0 ? 'opacity-50' : ''}`}
/>
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
{remainingQty}/{quantity}
</div>
{offered && (
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded">
+{offered.quantity}
</div>
)}
</div>
);
})}
</div>
)}
</div>
{/* Their Collection (Right) */}
<div className="flex-1 p-4 overflow-y-auto">
<h3 className="text-lg font-semibold mb-3 text-blue-400">
{receiverUsername}'s Collection (I want)
</h3>
{receiverCollection.length === 0 ? (
<p className="text-gray-400 text-center py-4">Their collection is empty</p>
) : (
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
{receiverCollection.map(({ card, quantity }) => {
const wanted = wantedCards.get(card.id);
const remainingQty = quantity - (wanted?.quantity || 0);
return (
<div
key={card.id}
className={`relative cursor-pointer rounded-lg overflow-hidden transition ${
wanted ? 'ring-2 ring-blue-500' : 'hover:ring-2 hover:ring-gray-500'
}`}
onClick={() => remainingQty > 0 && addToWanted(card, quantity)}
>
<img
src={card.image_uris?.small}
alt={card.name}
className={`w-full h-auto ${remainingQty === 0 ? 'opacity-50' : ''}`}
/>
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
{remainingQty}/{quantity}
</div>
{wanted && (
<div className="absolute bottom-1 left-1 bg-blue-500 text-white text-xs px-1.5 py-0.5 rounded">
+{wanted.quantity}
</div>
)}
</div>
);
})}
</div>
)}
</div>
</div>
{/* Trade Summary */}
<div className="border-t border-gray-700 p-4">
<div className="flex flex-col md:flex-row gap-4 mb-4">
{/* I Give */}
<div className="flex-1">
<h4 className="text-sm font-semibold text-green-400 mb-2">I Give:</h4>
{myOfferedCards.size === 0 ? (
<p className="text-gray-500 text-sm">Nothing selected (gift request)</p>
) : (
<div className="flex flex-wrap gap-2">
{Array.from(myOfferedCards.values()).map((item) => (
<div
key={item.card.id}
className="flex items-center gap-1 bg-green-900/50 px-2 py-1 rounded text-sm"
>
<span>{item.card.name}</span>
<span className="text-green-400">x{item.quantity}</span>
<button
onClick={() => removeFromOffer(item.card.id)}
className="ml-1 text-red-400 hover:text-red-300"
>
<Minus size={14} />
</button>
</div>
))}
</div>
)}
</div>
{/* I Want */}
<div className="flex-1">
<h4 className="text-sm font-semibold text-blue-400 mb-2">I Want:</h4>
{wantedCards.size === 0 ? (
<p className="text-gray-500 text-sm">Nothing selected (gift)</p>
) : (
<div className="flex flex-wrap gap-2">
{Array.from(wantedCards.values()).map((item) => (
<div
key={item.card.id}
className="flex items-center gap-1 bg-blue-900/50 px-2 py-1 rounded text-sm"
>
<span>{item.card.name}</span>
<span className="text-blue-400">x{item.quantity}</span>
<button
onClick={() => removeFromWanted(item.card.id)}
className="ml-1 text-red-400 hover:text-red-300"
>
<Minus size={14} />
</button>
</div>
))}
</div>
)}
</div>
</div>
{/* Message */}
<div className="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"
/>
</div>
{/* Submit */}
<div className="flex justify-end gap-3">
<button
onClick={onClose}
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={submitting || (myOfferedCards.size === 0 && wantedCards.size === 0)}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg transition"
>
{submitting ? (
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
) : isGift ? (
<>
<Gift size={20} />
Send Gift
</>
) : isRequest ? (
<>
<Send size={20} />
Request Cards
</>
) : (
<>
<Send size={20} />
Propose Trade
</>
)}
</button>
</div>
</div>
</div>
</div>
);
}

326
src/components/Trades.tsx Normal file
View File

@@ -0,0 +1,326 @@
import React, { useState, useEffect } from 'react';
import { ArrowLeftRight, Check, X, Clock, History, Plus, Package } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import {
getTrades,
getTradeHistory,
acceptTrade,
declineTrade,
cancelTrade,
Trade,
TradeItem,
} from '../services/tradesService';
import { getCardsByIds } from '../services/api';
import { Card } from '../types';
type Tab = 'pending' | 'history';
interface TradeWithCards extends Trade {
cardDetails?: Map<string, Card>;
}
export default function Trades() {
const { user } = useAuth();
const [activeTab, setActiveTab] = useState<Tab>('pending');
const [pendingTrades, setPendingTrades] = useState<TradeWithCards[]>([]);
const [tradeHistory, setTradeHistory] = useState<TradeWithCards[]>([]);
const [loading, setLoading] = useState(true);
const [processingTradeId, setProcessingTradeId] = useState<string | null>(null);
useEffect(() => {
if (user) {
loadTrades();
}
}, [user]);
const loadTrades = async () => {
if (!user) return;
setLoading(true);
try {
const [pending, history] = await Promise.all([
getTrades(user.id).then((trades) => trades.filter((t) => t.status === 'pending')),
getTradeHistory(user.id),
]);
// Load card details for all trades
const allCardIds = new Set<string>();
[...pending, ...history].forEach((trade) => {
trade.items?.forEach((item) => allCardIds.add(item.card_id));
});
let cardDetails = new Map<string, Card>();
if (allCardIds.size > 0) {
const cards = await getCardsByIds(Array.from(allCardIds));
cards.forEach((card) => cardDetails.set(card.id, card));
}
setPendingTrades(pending.map((t) => ({ ...t, cardDetails })));
setTradeHistory(history.map((t) => ({ ...t, cardDetails })));
} catch (error) {
console.error('Error loading trades:', error);
} finally {
setLoading(false);
}
};
const handleAccept = async (tradeId: string) => {
setProcessingTradeId(tradeId);
try {
const success = await acceptTrade(tradeId);
if (success) {
await loadTrades();
} else {
alert('Failed to execute trade. Please check your collection.');
}
} catch (error) {
console.error('Error accepting trade:', error);
alert('Error accepting trade');
} finally {
setProcessingTradeId(null);
}
};
const handleDecline = async (tradeId: string) => {
setProcessingTradeId(tradeId);
try {
await declineTrade(tradeId);
await loadTrades();
} catch (error) {
console.error('Error declining trade:', error);
} finally {
setProcessingTradeId(null);
}
};
const handleCancel = async (tradeId: string) => {
if (!confirm('Cancel this trade offer?')) return;
setProcessingTradeId(tradeId);
try {
await cancelTrade(tradeId);
await loadTrades();
} catch (error) {
console.error('Error cancelling trade:', error);
} finally {
setProcessingTradeId(null);
}
};
const getStatusColor = (status: Trade['status']) => {
switch (status) {
case 'accepted':
return 'text-green-400';
case 'declined':
return 'text-red-400';
case 'cancelled':
return 'text-gray-400';
default:
return 'text-yellow-400';
}
};
const renderTradeItems = (
items: TradeItem[] | undefined,
ownerId: string,
cardDetails: Map<string, Card> | undefined,
label: string
) => {
const ownerItems = items?.filter((i) => i.owner_id === ownerId) || [];
if (ownerItems.length === 0) {
return (
<div className="text-gray-500 text-sm italic">
{label}: Nothing (gift)
</div>
);
}
return (
<div>
<div className="text-gray-400 text-sm mb-1">{label}:</div>
<div className="flex flex-wrap gap-2">
{ownerItems.map((item) => {
const card = cardDetails?.get(item.card_id);
return (
<div
key={item.id}
className="flex items-center gap-2 bg-gray-700 px-2 py-1 rounded text-sm"
>
{card?.image_uris?.small && (
<img
src={card.image_uris.small}
alt={card.name}
className="w-8 h-11 rounded"
/>
)}
<span>{card?.name || item.card_id}</span>
{item.quantity > 1 && (
<span className="text-gray-400">x{item.quantity}</span>
)}
</div>
);
})}
</div>
</div>
);
};
const renderTrade = (trade: TradeWithCards, showActions: boolean) => {
const isSender = trade.sender_id === user?.id;
const otherUser = isSender ? trade.receiver : trade.sender;
return (
<div key={trade.id} className="bg-gray-800 rounded-lg p-4 space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ArrowLeftRight size={18} className="text-blue-400" />
<span className="font-medium">
{isSender ? `To: ${otherUser?.username}` : `From: ${otherUser?.username}`}
</span>
</div>
<span className={`text-sm capitalize ${getStatusColor(trade.status)}`}>
{trade.status}
</span>
</div>
{/* Trade Items */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{renderTradeItems(
trade.items,
trade.sender_id,
trade.cardDetails,
isSender ? 'You give' : 'They give'
)}
{renderTradeItems(
trade.items,
trade.receiver_id,
trade.cardDetails,
isSender ? 'You receive' : 'They receive'
)}
</div>
{/* Message */}
{trade.message && (
<div className="text-gray-400 text-sm">
<span className="text-gray-500">Message:</span> {trade.message}
</div>
)}
{/* Actions */}
{showActions && trade.status === 'pending' && (
<div className="flex gap-2 pt-2 border-t border-gray-700">
{isSender ? (
<button
onClick={() => handleCancel(trade.id)}
disabled={processingTradeId === trade.id}
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
>
<X size={16} />
Cancel
</button>
) : (
<>
<button
onClick={() => handleAccept(trade.id)}
disabled={processingTradeId === trade.id}
className="flex items-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 rounded-lg transition text-sm"
>
{processingTradeId === trade.id ? (
<div className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white"></div>
) : (
<Check size={16} />
)}
Accept
</button>
<button
onClick={() => handleDecline(trade.id)}
disabled={processingTradeId === trade.id}
className="flex items-center gap-2 px-3 py-2 bg-red-600 hover:bg-red-700 rounded-lg transition text-sm"
>
<X size={16} />
Decline
</button>
</>
)}
</div>
)}
{/* Timestamp */}
<div className="text-gray-500 text-xs">
{new Date(trade.created_at || '').toLocaleDateString()}
</div>
</div>
);
};
if (loading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-3xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h1 className="text-3xl font-bold">Trades</h1>
</div>
{/* Tabs */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setActiveTab('pending')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'pending'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Clock size={18} />
Pending ({pendingTrades.length})
</button>
<button
onClick={() => setActiveTab('history')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'history'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<History size={18} />
History
</button>
</div>
{/* Pending Trades */}
{activeTab === 'pending' && (
<div className="space-y-4">
{pendingTrades.length === 0 ? (
<div className="text-center py-12">
<Package size={48} className="mx-auto text-gray-600 mb-4" />
<p className="text-gray-400">No pending trades</p>
<p className="text-gray-500 text-sm mt-2">
Visit a friend's collection to propose a trade
</p>
</div>
) : (
pendingTrades.map((trade) => renderTrade(trade, true))
)}
</div>
)}
{/* Trade History */}
{activeTab === 'history' && (
<div className="space-y-4">
{tradeHistory.length === 0 ? (
<p className="text-gray-400 text-center py-8">No trade history yet</p>
) : (
tradeHistory.map((trade) => renderTrade(trade, false))
)}
</div>
)}
</div>
</div>
);
}

View File

@@ -143,6 +143,7 @@ export type Database = {
theme_color: string | null
updated_at: string | null
username: string | null
collection_visibility: 'public' | 'friends' | 'private' | null
}
Insert: {
created_at?: string | null
@@ -150,6 +151,7 @@ export type Database = {
theme_color?: string | null
updated_at?: string | null
username?: string | null
collection_visibility?: 'public' | 'friends' | 'private' | null
}
Update: {
created_at?: string | null
@@ -157,9 +159,139 @@ export type Database = {
theme_color?: string | null
updated_at?: string | null
username?: string | null
collection_visibility?: 'public' | 'friends' | 'private' | null
}
Relationships: []
}
friendships: {
Row: {
id: string
requester_id: string
addressee_id: string
status: 'pending' | 'accepted' | 'declined'
created_at: string | null
updated_at: string | null
}
Insert: {
id?: string
requester_id: string
addressee_id: string
status?: 'pending' | 'accepted' | 'declined'
created_at?: string | null
updated_at?: string | null
}
Update: {
id?: string
requester_id?: string
addressee_id?: string
status?: 'pending' | 'accepted' | 'declined'
created_at?: string | null
updated_at?: string | null
}
Relationships: [
{
foreignKeyName: "friendships_requester_id_fkey"
columns: ["requester_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
{
foreignKeyName: "friendships_addressee_id_fkey"
columns: ["addressee_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
}
]
}
trades: {
Row: {
id: string
sender_id: string
receiver_id: string
status: 'pending' | 'accepted' | 'declined' | 'cancelled'
message: string | null
created_at: string | null
updated_at: string | null
}
Insert: {
id?: string
sender_id: string
receiver_id: string
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
message?: string | null
created_at?: string | null
updated_at?: string | null
}
Update: {
id?: string
sender_id?: string
receiver_id?: string
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
message?: string | null
created_at?: string | null
updated_at?: string | null
}
Relationships: [
{
foreignKeyName: "trades_sender_id_fkey"
columns: ["sender_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
{
foreignKeyName: "trades_receiver_id_fkey"
columns: ["receiver_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
}
]
}
trade_items: {
Row: {
id: string
trade_id: string
owner_id: string
card_id: string
quantity: number
created_at: string | null
}
Insert: {
id?: string
trade_id: string
owner_id: string
card_id: string
quantity?: number
created_at?: string | null
}
Update: {
id?: string
trade_id?: string
owner_id?: string
card_id?: string
quantity?: number
created_at?: string | null
}
Relationships: [
{
foreignKeyName: "trade_items_trade_id_fkey"
columns: ["trade_id"]
isOneToOne: false
referencedRelation: "trades"
referencedColumns: ["id"]
},
{
foreignKeyName: "trade_items_owner_id_fkey"
columns: ["owner_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
}
]
}
}
Views: {
[_ in never]: never
@@ -271,4 +403,4 @@ export type CompositeTypes<
? Database[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"][CompositeTypeName]
: PublicCompositeTypeNameOrOptions extends keyof PublicSchema["CompositeTypes"]
? PublicSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions]
: never
: never

View File

@@ -0,0 +1,202 @@
import { supabase } from '../lib/supabase';
export interface Friend {
id: string;
odship_id: string;
username: string | null;
status: 'pending' | 'accepted' | 'declined';
isRequester: boolean;
created_at: string | null;
}
export interface FriendshipWithProfile {
id: string;
requester_id: string;
addressee_id: string;
status: 'pending' | 'accepted' | 'declined';
created_at: string | null;
requester: { username: string | null };
addressee: { username: string | null };
}
// Get all friends (accepted friendships)
export async function getFriends(userId: string): Promise<Friend[]> {
const { data, error } = await supabase
.from('friendships')
.select(`
id,
requester_id,
addressee_id,
status,
created_at,
requester:profiles!friendships_requester_id_fkey(username),
addressee:profiles!friendships_addressee_id_fkey(username)
`)
.eq('status', 'accepted')
.or(`requester_id.eq.${userId},addressee_id.eq.${userId}`);
if (error) throw error;
return (data as unknown as FriendshipWithProfile[]).map((f) => {
const isRequester = f.requester_id === userId;
return {
id: isRequester ? f.addressee_id : f.requester_id,
friendshipId: f.id,
username: isRequester ? f.addressee?.username : f.requester?.username,
status: f.status,
isRequester,
created_at: f.created_at,
};
});
}
// Get pending friend requests (received)
export async function getPendingRequests(userId: string): Promise<Friend[]> {
const { data, error } = await supabase
.from('friendships')
.select(`
id,
requester_id,
addressee_id,
status,
created_at,
requester:profiles!friendships_requester_id_fkey(username)
`)
.eq('status', 'pending')
.eq('addressee_id', userId);
if (error) throw error;
return (data as any[]).map((f) => ({
id: f.requester_id,
friendshipId: f.id,
username: f.requester?.username,
status: f.status,
isRequester: false,
created_at: f.created_at,
}));
}
// Get sent friend requests (pending)
export async function getSentRequests(userId: string): Promise<Friend[]> {
const { data, error } = await supabase
.from('friendships')
.select(`
id,
requester_id,
addressee_id,
status,
created_at,
addressee:profiles!friendships_addressee_id_fkey(username)
`)
.eq('status', 'pending')
.eq('requester_id', userId);
if (error) throw error;
return (data as any[]).map((f) => ({
id: f.addressee_id,
friendshipId: f.id,
username: f.addressee?.username,
status: f.status,
isRequester: true,
created_at: f.created_at,
}));
}
// Search users by username
export async function searchUsers(query: string, currentUserId: string) {
const { data, error } = await supabase
.from('profiles')
.select('id, username')
.ilike('username', `%${query}%`)
.neq('id', currentUserId)
.limit(10);
if (error) throw error;
return data;
}
// Send friend request
export async function sendFriendRequest(requesterId: string, addresseeId: string) {
const { data, error } = await supabase
.from('friendships')
.insert({
requester_id: requesterId,
addressee_id: addresseeId,
status: 'pending',
})
.select()
.single();
if (error) throw error;
return data;
}
// Accept friend request
export async function acceptFriendRequest(friendshipId: string) {
const { data, error } = await supabase
.from('friendships')
.update({ status: 'accepted', updated_at: new Date().toISOString() })
.eq('id', friendshipId)
.select()
.single();
if (error) throw error;
return data;
}
// Decline friend request
export async function declineFriendRequest(friendshipId: string) {
const { data, error } = await supabase
.from('friendships')
.update({ status: 'declined', updated_at: new Date().toISOString() })
.eq('id', friendshipId)
.select()
.single();
if (error) throw error;
return data;
}
// Remove friend (delete friendship)
export async function removeFriend(friendshipId: string) {
const { error } = await supabase
.from('friendships')
.delete()
.eq('id', friendshipId);
if (error) throw error;
}
// Check if two users are friends
export async function areFriends(userId1: string, userId2: string): Promise<boolean> {
const { data, error } = await supabase
.from('friendships')
.select('id')
.eq('status', 'accepted')
.or(`and(requester_id.eq.${userId1},addressee_id.eq.${userId2}),and(requester_id.eq.${userId2},addressee_id.eq.${userId1})`)
.maybeSingle();
if (error) throw error;
return data !== null;
}
// Get friendship status between two users
export async function getFriendshipStatus(userId1: string, userId2: string) {
const { data, error } = await supabase
.from('friendships')
.select('id, status, requester_id')
.or(`and(requester_id.eq.${userId1},addressee_id.eq.${userId2}),and(requester_id.eq.${userId2},addressee_id.eq.${userId1})`)
.maybeSingle();
if (error) throw error;
if (!data) return { status: 'none' as const, friendshipId: null, isRequester: false };
return {
status: data.status as 'pending' | 'accepted' | 'declined',
friendshipId: data.id,
isRequester: data.requester_id === userId1,
};
}

View File

@@ -0,0 +1,184 @@
import { supabase } from '../lib/supabase';
export interface TradeItem {
id: string;
trade_id: string;
owner_id: string;
card_id: string;
quantity: number;
}
export interface Trade {
id: string;
sender_id: string;
receiver_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 };
items?: TradeItem[];
}
export interface CreateTradeParams {
senderId: string;
receiverId: string;
message?: string;
senderCards: { cardId: string; quantity: number }[];
receiverCards: { cardId: string; quantity: number }[];
}
// Get all trades for a user
export async function getTrades(userId: string): Promise<Trade[]> {
const { data, error } = await supabase
.from('trades')
.select(`
*,
sender:profiles!trades_sender_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username),
items:trade_items(*)
`)
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
.order('created_at', { ascending: false });
if (error) throw error;
return data as Trade[];
}
// Get pending trades for a user
export async function getPendingTrades(userId: string): Promise<Trade[]> {
const { data, error } = await supabase
.from('trades')
.select(`
*,
sender:profiles!trades_sender_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username),
items:trade_items(*)
`)
.eq('status', 'pending')
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
.order('created_at', { ascending: false });
if (error) throw error;
return data as Trade[];
}
// Get trade by ID
export async function getTradeById(tradeId: string): Promise<Trade | null> {
const { data, error } = await supabase
.from('trades')
.select(`
*,
sender:profiles!trades_sender_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username),
items:trade_items(*)
`)
.eq('id', tradeId)
.single();
if (error) throw error;
return data as Trade;
}
// Create a new trade with items
export async function createTrade(params: CreateTradeParams): Promise<Trade> {
const { senderId, receiverId, message, senderCards, receiverCards } = params;
// Create the trade
const { data: trade, error: tradeError } = await supabase
.from('trades')
.insert({
sender_id: senderId,
receiver_id: receiverId,
message,
status: 'pending',
})
.select()
.single();
if (tradeError) throw tradeError;
// Add sender's cards
const senderItems = senderCards.map((card) => ({
trade_id: trade.id,
owner_id: senderId,
card_id: card.cardId,
quantity: card.quantity,
}));
// Add receiver's cards (what sender wants)
const receiverItems = receiverCards.map((card) => ({
trade_id: trade.id,
owner_id: receiverId,
card_id: card.cardId,
quantity: card.quantity,
}));
const allItems = [...senderItems, ...receiverItems];
if (allItems.length > 0) {
const { error: itemsError } = await supabase
.from('trade_items')
.insert(allItems);
if (itemsError) throw itemsError;
}
return trade;
}
// Accept a trade (executes the card transfer)
export async function acceptTrade(tradeId: string): Promise<boolean> {
const { data, error } = await supabase.rpc('execute_trade', {
trade_id: tradeId,
});
if (error) throw error;
return data as boolean;
}
// Decline a trade
export async function declineTrade(tradeId: string): Promise<Trade> {
const { data, error } = await supabase
.from('trades')
.update({ status: 'declined', updated_at: new Date().toISOString() })
.eq('id', tradeId)
.select()
.single();
if (error) throw error;
return data;
}
// Cancel a trade (sender only)
export async function cancelTrade(tradeId: string): Promise<Trade> {
const { data, error } = await supabase
.from('trades')
.update({ status: 'cancelled', updated_at: new Date().toISOString() })
.eq('id', tradeId)
.select()
.single();
if (error) throw error;
return data;
}
// Get trade history (completed/cancelled/declined trades)
export async function getTradeHistory(userId: string): Promise<Trade[]> {
const { data, error } = await supabase
.from('trades')
.select(`
*,
sender:profiles!trades_sender_id_fkey(username),
receiver:profiles!trades_receiver_id_fkey(username),
items:trade_items(*)
`)
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
.in('status', ['accepted', 'declined', 'cancelled'])
.order('updated_at', { ascending: false })
.limit(50);
if (error) throw error;
return data as Trade[];
}