Files
blackcanyontickets/CLAUDE.md
dzinesco 0956873381 feat: Enhance calendar component with glassmorphism design and modular architecture
- Refactored Calendar.tsx into modular component structure
- Added glassmorphism theming with CSS custom properties
- Implemented reusable calendar subcomponents:
  - CalendarGrid: Month view with improved day/event display
  - CalendarHeader: Navigation and view controls
  - EventList: List view for events
  - TrendingEvents: Location-based trending events
  - UpcomingEvents: Quick upcoming events preview
- Enhanced responsive design for mobile devices
- Added Playwright testing framework for automated testing
- Updated Docker development commands in CLAUDE.md
- Improved accessibility and user experience

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-13 12:07:33 -06:00

279 lines
12 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Black Canyon Tickets is a self-service ticketing platform designed for upscale venues. The platform runs at `portal.blackcanyontickets.com` and serves high-end events like dance performances, weddings, and galas.
## Development Commands
All commands are run from the root directory:
```bash
# Development
npm run dev # Start development server at localhost:4321
npm run start # Alias for npm run dev
# Building & Testing
npm run build # Type check and build for production
npm run typecheck # Run Astro type checking only
npm run preview # Preview production build locally
# Database
node setup-schema.js # Initialize database schema (run once)
# Docker Development (IMPORTANT: Always use --no-cache when rebuilding)
docker-compose build --no-cache # Clean rebuild when cache issues occur
docker-compose down && docker-compose up -d # Clean restart containers
# Stripe MCP (Model Context Protocol)
npm run mcp:stripe # Start Stripe MCP server for AI integration
npm run mcp:stripe:debug # Start MCP server with debugging interface
```
## Tech Stack
- **Frontend:** Astro 5.x with React islands for interactive components
- **Styling:** Tailwind CSS 4.x with custom glassmorphism design system
- **Database & Auth:** Supabase (PostgreSQL + Supabase Auth)
- **Payments:** Stripe + Stripe Connect for automated payouts and platform fees
- **QR Scanning:** Mobile-friendly browser-based scanner using HTML5 canvas
- **Emails:** Resend for transactional emails
- **Monitoring:** Sentry for error tracking and performance monitoring
- **Hosting:** Self-hosted Node.js with standalone adapter
## Architecture
### Core Application Flow
1. **Authentication**: Supabase Auth with organization-based access control
2. **Event Management**: Multi-tenant system with Row Level Security (RLS)
3. **Ticket Sales**: Inventory management with pessimistic locking
4. **Payment Processing**: Stripe Connect for direct payouts to organizers
5. **QR Scanning**: UUID-based tickets for secure door management
### Key Routes
- `/` - Homepage (public)
- `/login` - Authentication portal
- `/dashboard` - Event list and revenue summary (authenticated)
- `/events/new` - Event creation form (authenticated)
- `/events/[id]/manage` - Comprehensive event management with tabs (authenticated)
- `/e/[slug]` - Public ticket checkout page (embeddable)
- `/scan` - QR scanning interface for door staff (authenticated)
- `/admin/` - Platform administration (admin only)
### Database Schema (Core Tables)
- `organizations`: Multi-tenant isolation with Stripe Connect accounts
- `users`: Organization membership with role-based access
- `events`: Event metadata with slugs and seating configuration
- `ticket_types`: Pricing tiers with inventory tracking
- `tickets`: Individual ticket records with UUIDs for QR codes
- `presale_codes`: Time-limited access codes with usage tracking
- `seating_maps`: Venue layouts for assigned seating events
### Multi-Tenant Security
- **Row Level Security (RLS)**: All tables filtered by organization_id
- **Authentication**: Supabase Auth with organization context
- **Admin Override**: Special admin role bypasses organization filtering
- **API Security**: All API routes validate organization membership
## Key Integrations
### Supabase Configuration
- **URL**: `https://zctjaivtfyfxokfaemek.supabase.co`
- **Environment Variables**: `PUBLIC_SUPABASE_URL`, `PUBLIC_SUPABASE_ANON_KEY`
- **Auth**: Built-in authentication with organization assignment
- **Database**: PostgreSQL with migrations in `/supabase/migrations/`
### Stripe Integration
- **Connect**: Organizers onboard via Stripe Connect for direct payouts
- **Platform Fees**: Automatically split from each transaction
- **Webhooks**: Payment confirmation and dispute handling
- **Environment**: Uses publishable/secret key pairs
- **MCP Server**: AI-powered Stripe operations through Model Context Protocol
### Stripe MCP (Model Context Protocol)
- **Purpose**: AI-powered interactions with Stripe API and knowledge base
- **Tools**: Customer management, payment processing, subscriptions, refunds
- **Configuration**: See `MCP_SETUP.md` for detailed setup instructions
- **Commands**: `npm run mcp:stripe` (production) or `npm run mcp:stripe:debug` (development)
- **Integration**: Works with Claude Desktop and other AI agents
### Design System
- **Theme**: Glassmorphism with dark gradients (see DESIGN_SYSTEM.md)
- **Colors**: Blue/purple gradients with white text on dark backgrounds
- **Layouts**: `Layout.astro` (public), `SecureLayout.astro` (authenticated)
- **Animations**: CSS keyframes for fadeInUp, slideIn, and float effects
## File Structure
```
src/
├── components/ # Reusable UI components
│ ├── Navigation.astro # Main navigation with auth state
│ ├── TicketCheckout.tsx # React component for ticket purchasing
│ └── ProtectedRoute.astro # Auth guard wrapper
├── layouts/
│ ├── Layout.astro # Base layout with SEO and meta
│ └── SecureLayout.astro # Authenticated layout with glassmorphism
├── lib/ # Utility modules
│ ├── supabase.ts # Database client configuration
│ ├── stripe.ts # Payment processing utilities
│ ├── auth.ts # Authentication helpers
│ ├── database.types.ts # Generated TypeScript types
│ └── validation.ts # Form validation schemas
├── middleware.ts # Security headers and HTTPS redirect
├── pages/
│ ├── api/ # API endpoints
│ │ ├── inventory/ # Ticket reservation and purchase
│ │ ├── webhooks/ # External service callbacks
│ │ └── admin/ # Admin-only endpoints
│ ├── events/[id]/
│ │ └── manage.astro # Complex event management interface
│ └── e/[slug].astro # Public ticket sales page
└── styles/
├── global.css # Global styles and imports
└── glassmorphism.css # Design system utilities
```
## Development Patterns
### Component Architecture
- **Astro Components**: Server-rendered with minimal JavaScript
- **React Islands**: Interactive components (forms, real-time updates)
- **TypeScript**: Strict typing with generated database types
- **Props Validation**: Zod schemas for API and form validation
### State Management
- **Server State**: Supabase real-time subscriptions
- **Client State**: React hooks for interactive components
- **Form State**: Native form handling with progressive enhancement
- **Auth State**: Supabase auth context with organization data
### API System
- **Centralized API Client**: `/src/lib/api-client.ts` - Main client with authentication
- **API Router**: `/src/lib/api-router.ts` - Browser-friendly wrapper for common operations
- **Authentication**: Automatic session management and organization context
- **Error Handling**: Consistent error responses with user-friendly messages
- **Usage**: Use `import { api } from '../lib/api-router'` in components
#### API System Usage Examples:
```typescript
// In Astro components (client-side scripts)
const { api } = await import('../lib/api-router');
// Load event stats
const stats = await api.loadEventStats(eventId);
// Load event details
const event = await api.loadEventDetails(eventId);
// Load complete event page data
const { event, stats, error } = await api.loadEventPage(eventId);
// Format currency and dates
const formattedPrice = api.formatCurrency(priceInCents);
const formattedDate = api.formatDate(dateString);
```
### API Design
- **RESTful**: Standard HTTP methods with proper status codes
- **Authentication**: Automatic Supabase JWT validation on all API calls
- **Error Handling**: Consistent error responses with user-friendly messages
- **Rate Limiting**: Built-in protection against abuse
## Security Implementation
### Content Security Policy
- **Strict CSP**: Defined in middleware.ts with Stripe and Supabase exceptions
- **HTTPS**: Forced in production with HSTS headers
- **XSS Protection**: Content type validation and frame options
### Data Protection
- **Row Level Security**: Database-level access control
- **Input Validation**: Zod schemas for all user inputs
- **SQL Injection**: Parameterized queries via Supabase client
- **Secrets Management**: Environment variables for all sensitive data
## Testing & Monitoring
### Error Tracking
- **Sentry**: Configured for both client and server-side errors
- **Logging**: Winston for server-side logging to files
- **Performance**: Sentry performance monitoring enabled
### Environment Variables Required
```bash
# Supabase
PUBLIC_SUPABASE_URL=https://zctjaivtfyfxokfaemek.supabase.co
PUBLIC_SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
# Stripe
STRIPE_PUBLISHABLE_KEY=pk_...
STRIPE_SECRET_KEY=sk_...
STRIPE_WEBHOOK_SECRET=whsec_...
# Email
RESEND_API_KEY=re_...
# Monitoring
SENTRY_DSN=https://...
```
## Common Development Tasks
### Adding New Features
1. **Database Changes**: Add migration to `/supabase/migrations/`
2. **API Endpoints**: Create in `/src/pages/api/` with proper validation
3. **UI Components**: Follow glassmorphism design system patterns
4. **Types**: Update `database.types.ts` or regenerate from Supabase
### Event Management System
The `/events/[id]/manage.astro` page is the core of the platform:
- **Tab-based Interface**: Tickets, Venue, Orders, Attendees, Analytics
- **Real-time Updates**: Supabase subscriptions for live data
- **Complex State**: Multiple modals and forms with validation
- **Responsive Design**: Mobile-first with glassmorphism effects
### QR Code System
- **Generation**: UUID-based tickets prevent enumeration
- **Scanning**: HTML5 camera API with canvas processing
- **Validation**: Server-side verification with attendance tracking
- **Security**: Tamper-proof tickets with database verification
## Important Notes
- **Mobile-First**: Scanner interface optimized for phone screens
- **Performance**: Glassmorphism effects may impact mobile performance
- **Accessibility**: WCAG AA compliance maintained throughout
- **SEO**: Server-side rendering for public pages
- **Multi-tenant**: All features must respect organization boundaries
## Authentication System - CRITICAL FIX APPLIED
### Login Loop Issue (RESOLVED)
**Problem**: Users experienced infinite login loops where successful authentication would redirect to dashboard, then immediately back to login page.
**Root Cause**: Client-server authentication mismatch due to httpOnly cookies:
- Login API sets httpOnly cookies using server-side Supabase client ✅
- Dashboard server reads httpOnly cookies correctly ✅
- Dashboard client script tried to read httpOnly cookies using client-side Supabase ❌
**Solution Implemented**:
1. **Fixed Admin Dashboard**: Removed non-existent `is_super_admin` column references in `/src/pages/admin/dashboard.astro`
2. **Created Auth Check API**: `/src/pages/api/admin/auth-check.ts` provides server-side auth validation for client scripts
3. **Updated Admin API Router**: `/src/lib/admin-api-router.ts` now uses auth check API instead of client-side Supabase
**Key Files Modified**:
- `/src/pages/admin/dashboard.astro` - Fixed database queries
- `/src/pages/api/admin/auth-check.ts` - NEW: Server-side auth validation API
- `/src/lib/admin-api-router.ts` - Uses API calls instead of client-side auth
- `/src/pages/api/auth/session.ts` - Return 200 status for unauthenticated users
- `/src/pages/login.astro` - Enhanced cache clearing and session management
**Testing**: Automated Playwright tests in `/test-login.js` validate end-to-end login flow
**Documentation**: See `AUTHENTICATION_FIX.md` for complete technical details
**⚠️ IMPORTANT**: Do NOT modify the authentication system without understanding this fix. The httpOnly cookie approach is intentional for security and requires server-side validation for client scripts.