# Admin Seat Details Endpoint - Complete Analysis & Specification

## 📋 Overview

This workspace contains a comprehensive analysis and specification for a new **admin-only API endpoint** that returns detailed information about individual seats, including ownership, reservation status, pricing history, and admin context.

**Purpose**: Enable admin tooltips to display seat owner information and provide complete context for seat management operations.

**Status**: ✅ **Analysis Complete** - Ready for Implementation

---

## 📁 Documentation Files

### 1. **ADMIN_SEAT_ENDPOINT_SUMMARY.md** ⭐ **START HERE**
- Executive summary of the missing functionality
- Key data that will be returned
- Use cases (tooltips, operations, support)
- Implementation priority phases
- Success metrics

**Read this first** for a high-level understanding.

---

### 2. **ADMIN_SEAT_DETAILS_ENDPOINT_SPEC.md** 📖 **COMPLETE SPECIFICATION**
- Full endpoint specification (request/response)
- Comprehensive data structure with all fields
- Business logic and calculations
- Error responses (404, 403, 422)
- Performance considerations
- Query optimization strategies
- Security & compliance (GDPR, audit logging)
- Implementation checklist

**Use this** for complete technical details.

---

### 3. **DATA_RELATIONSHIPS_DIAGRAM.md** 🗺️ **VISUAL GUIDE**
- Entity relationship diagrams
- Database table connections
- Query flow with SQL examples
- Join strategy for optimal performance
- Index requirements
- N+1 query prevention

**Use this** to understand how data flows through the system.

---

### 4. **IMPLEMENTATION_EXAMPLES.md** 💻 **CODE EXAMPLES**
- Complete Laravel controller implementation
- Route definition with middleware
- TypeScript interfaces for frontend
- API client with React Query
- Seat tooltip React component
- Error handling patterns

**Use this** as a starting point for actual implementation.

---

## 🎯 The Problem

### Current State
The existing `/api/venue/availability/{eventId}` endpoint returns:
- ✅ Seat status (available/held/booked)
- ✅ Seat price
- ❌ **NO owner information** (customer name, email)
- ❌ **NO order details** (order ID, payment status)

### User Impact
Admins **cannot see who owns a seat** without:
1. Clicking on the seat
2. Navigating to order details page
3. Searching for the order
4. Reading customer information

**This is slow and frustrating** for:
- Customer support inquiries
- Seat management operations
- Fire marshal capacity checks
- Revenue analytics

---

## ✨ The Solution

### New Endpoint
```
GET /api/admin/seats/{seat_id}/details?event_id={event_id}
```

**Authentication**: Admin JWT required

**Returns**: Comprehensive seat data in a single API call

---

## 📊 What Information Will Be Returned

### Core Data (Always Included)
1. **Seat Information**
   - Seat ID, row, number, type, zone
   - Position, accessibility, price
   - Section ID, parent table

2. **Reservation Status** ⭐
   - Current status (available/held/booked/shadow_sold/blocked)
   - Hold details (token, expiry, seconds remaining)
   - Price snapshot vs current price

3. **Owner Information** ⭐ **CRITICAL - PRIMARY NEED**
   - Customer name: `"John Doe"`
   - Customer email: `"john.doe@example.com"`
   - Customer phone: `"+1234567890"`
   - User ID (if registered) or guest status

4. **Order Details**
   - Order ID: `#5678`
   - Total amount: `€183.25`
   - Status: `"completed"`, `"paid"`
   - Payment method: `"stripe"`
   - Created timestamp

5. **Payment Transaction**
   - Payment gateway: `"stripe"`
   - Transaction ID: `"pi_1J2K3L4M5N6O7P8Q"`
   - Amount, currency, status
   - Initiated/completed timestamps

6. **Admin Context**
   - Is shadow sold / blocked / comp ticket
   - Created by admin ID and name
   - Admin notes
   - Available actions (release, reassign, refund)

### Optional Data (Query Parameters)
7. **Reservation History** (`?include_history=true`)
   - Previous holds, bookings, status changes
   - Timestamps for each transition

8. **Audit Logs** (`?include_audit_logs=true`)
   - Admin actions (shadow sold, releases, etc.)
   - System events (bookings, payments)
   - Performed by user/admin/system

9. **Line Items** (if order exists)
   - Individual ticket line items
   - Booking fees, taxes, discounts
   - Per-item pricing

10. **Related Seats**
    - Parent table (if table child)
    - Section statistics (capacity, occupied)

---

## 🎨 Example Use Case: Admin Tooltip

### Before (Current State) ❌
```
Seat A1
Status: Booked
Price: €150.00

[Admin must click to see who owns it]
```

### After (With New Endpoint) ✅
```
Seat A1 (VIP Zone)
Status: Booked ✓
Owner: John Doe
Email: john.doe@example.com
Order: #5678 - Paid (€183.25)
Booked: Oct 20, 2025 3:32 PM

[Release] [Reassign] [Refund]
```

**One API call gives admin everything they need!**

---

## 📈 Performance Considerations

### Query Optimization
- **Eager loading** to prevent N+1 queries
- **Conditional loading** for expensive queries (history, audit logs)
- **Database indexes** on `seat_id`, `event_id`, `order_id`

### Expected Performance
- **Query count**: 2-5 queries (with eager loading)
- **Response time**: < 300ms target (95th percentile)
- **Cache duration**: 10 seconds (seat status changes frequently)

### Scaling Strategy
- Short-term caching for high-traffic events
- Response compression (gzip)
- Optional pagination for history/audit logs

---

## 🔒 Security & Compliance

### Authentication & Authorization
- ✅ Admin JWT required (`auth.admin.jwt` middleware)
- ✅ Rate limiting (`api.rate.limit:admin`)
- ⚠️ Optional: Granular permissions (`seats.view_details`)

### Audit Logging (GDPR Compliance)
Every access logged:
```
ADMIN_SEAT_DETAILS_ACCESS
- admin_id: 42
- seat_id: seat-A1-12345
- event_id: 123
- timestamp: 2025-10-28T10:30:00Z
```

### Data Privacy
- Customer PII only visible to authenticated admins
- Respect GDPR anonymization flags
- Optional: PII viewing requires `customers.view_pii` permission

---

## 📋 Implementation Checklist

### Backend (Laravel)
- [ ] Create `app/Http/Controllers/API/Admin/SeatDetailsController.php`
- [ ] Add route to `routes/api/admin/seats.php`
- [ ] Implement query with eager loading
- [ ] Add validation (seat_id, event_id)
- [ ] Add error handling (404, 403, 422, 500)
- [ ] Add audit logging for GDPR compliance
- [ ] Write tests (PHPUnit)

**Location**: `/Users/charlie/code/showprima/`

### Frontend (Next.js)
- [ ] Create TypeScript interface for response
- [ ] Add API client method in admin package
- [ ] Update seat tooltip component
- [ ] Add loading states and error handling
- [ ] Implement caching (React Query)
- [ ] Add seat operations panel with admin actions
- [ ] Test with various seat states
- [ ] Write tests (Jest)

**Location**: `/Users/charlie/code/showprima-frontend/`

---

## 🚀 Implementation Phases

### Phase 1: Core Functionality ⭐ **HIGH PRIORITY**
**Goal**: Enable admin tooltips with owner information

- Basic seat information
- Current reservation status
- Owner information (customer name, email)
- Order details (ID, status, amount)
- Availability flags (can release, can refund)

**Deliverable**: Tooltip shows seat owner without additional clicks

---

### Phase 2: Enhanced Details ⭐ **MEDIUM PRIORITY**
**Goal**: Enable seat operations panel and customer support

- Payment transaction details
- Line items breakdown
- Admin context (shadow sold, comp, notes)
- Related seats context
- Admin action buttons (release, reassign, refund)

**Deliverable**: Full seat operations panel with all admin actions

---

### Phase 3: Historical & Audit ⭐ **LOW PRIORITY**
**Goal**: Enable advanced troubleshooting and compliance

- Reservation history
- Audit logs
- Real-time updates (WebSocket/SSE)
- Bulk seat details endpoint

**Deliverable**: Complete audit trail for compliance reporting

---

## 📊 Success Metrics

### Improved Admin Experience
- ✅ Admins can see seat owner without clicking into order details
- ✅ Reduce time to resolve customer support tickets (target: 50% reduction)
- ✅ Eliminate need to check database directly
- ✅ Enable proactive customer service

### Technical Metrics
- ✅ Response time < 300ms (95th percentile)
- ✅ Cache hit rate > 80% during events
- ✅ Zero N+1 query issues
- ✅ 100% test coverage for business logic

### Business Impact
- ✅ Faster customer support resolution
- ✅ Better seat management efficiency
- ✅ Improved admin user satisfaction
- ✅ Reduced database query load

---

## 🔗 Related Documentation

### Backend (Laravel)
- `/Users/charlie/code/showprima/CLAUDE.md` - Backend architecture overview
- `/Users/charlie/code/showprima/app/Model/Seat.php` - Seat model
- `/Users/charlie/code/showprima/app/Model/SeatReservation.php` - Reservation model
- `/Users/charlie/code/showprima/app/Model/Order.php` - Order model

### Frontend (Next.js)
- `/Users/charlie/code/showprima-frontend/CLAUDE.md` - Frontend monorepo guide
- `/Users/charlie/code/showprima-frontend/apps/admin/` - Admin dashboard
- `/Users/charlie/code/showprima-frontend/packages/admin-ui/` - Admin components

---

## ❓ Questions & Considerations

### 1. Should we include customer's full order history?
**Recommendation**: No, keep focused on single seat. Provide link to customer page.

### 2. Should we include ticket PDF download link?
**Recommendation**: Yes, add in Phase 2 as `ticket.pdf_url` field.

### 3. How to handle seats that have never been reserved?
**Recommendation**: Return seat data with `reservation: null` and `availability.is_available: true`.

### 4. Should history include expired holds that were never confirmed?
**Recommendation**: Yes, useful for troubleshooting abandoned carts.

### 5. Real-time updates vs polling?
**Recommendation**: Start with polling (every 10s), add WebSocket in Phase 3 if needed.

---

## 🎓 Next Steps

### For Backend Developer
1. Read **ADMIN_SEAT_ENDPOINT_SUMMARY.md** (overview)
2. Read **ADMIN_SEAT_DETAILS_ENDPOINT_SPEC.md** (full spec)
3. Review **DATA_RELATIONSHIPS_DIAGRAM.md** (database queries)
4. Copy code from **IMPLEMENTATION_EXAMPLES.md**
5. Create controller, route, tests
6. Test with Postman/curl

### For Frontend Developer
1. Read **ADMIN_SEAT_ENDPOINT_SUMMARY.md** (overview)
2. Review TypeScript interfaces in **IMPLEMENTATION_EXAMPLES.md**
3. Create API client method
4. Update seat tooltip component
5. Add React Query for caching
6. Test with various seat states

### For Product/PM
1. Read **ADMIN_SEAT_ENDPOINT_SUMMARY.md** (overview)
2. Review use cases and success metrics
3. Prioritize phases (1, 2, 3)
4. Define acceptance criteria
5. Create tickets/stories

---

## 🏁 Conclusion

This comprehensive analysis provides **everything needed** to implement a powerful admin seat details endpoint:

✅ **Problem Definition**: Clear understanding of current gap
✅ **Complete Specification**: Full API design with all fields
✅ **Data Architecture**: Database relationships and queries
✅ **Code Examples**: Ready-to-use backend and frontend code
✅ **Implementation Plan**: Phased approach with priorities
✅ **Success Metrics**: Measurable business and technical goals

**Estimated Implementation Time**:
- **Phase 1** (Core): 1-2 days (backend) + 1-2 days (frontend) = **2-4 days**
- **Phase 2** (Enhanced): 1 day (backend) + 1 day (frontend) = **2 days**
- **Phase 3** (Historical): 1 day (backend) + 1 day (frontend) = **2 days**

**Total**: **6-8 days** for complete implementation across all phases.

---

## 📞 Contact

For questions about this analysis:
- **Backend**: See `/Users/charlie/code/showprima/CLAUDE.md`
- **Frontend**: See `/Users/charlie/code/showprima-frontend/CLAUDE.md`
- **Architecture**: Review `DATA_RELATIONSHIPS_DIAGRAM.md`
- **Implementation**: Start with `IMPLEMENTATION_EXAMPLES.md`

---

**Created**: 2025-10-28
**Workspace**: `/Users/charlie/code/showprima/.conductor/riga-v4`
**Branch**: `admin-seat-details-endpoint`
**Status**: ✅ Ready for Implementation
