Files
mp-pilates/docs/TIME_SLOT_INDEX.md
richarjiang b6986ba30c feat(admin): implement full day-by-day schedule editor with live preview
## Features

### Admin Schedule Page (`packages/app/src/pages/admin/schedule.vue`)
- Interactive date-based slot editor for managing daily schedules
- Real-time slot editing: start/end times, capacity adjustments
- Slot deletion with conflict warnings when bookings exist
- Add new slots with modal dialog
- Live booking status display (booked count, people names)
- Publish/Save changes with sync feedback
- Revert unsaved changes with confirmation
- Skeleton loading states and empty state handling
- Responsive design with optimized mobile UX

### Backend Enhancements
- **New DTO** (`PublishDaySlotsDto`): Structured slot publishing with validation
  - Date string validation
  - Slot array with existing slot IDs for updates
  - Time and capacity validation per slot

- **Schedule Preview API** (`getSchedulePreview`):
  - Check for existing published slots
  - Fallback to active WeekTemplates for unpublished dates
  - Unified response format with isPublished flag

- **Publish Slots API** (`publishDaySlots`):
  - Atomic transaction for consistency
  - Update existing slots with new times/capacity
  - Create new slots from template data
  - Delete unpublished slots or set to CLOSED if bookings exist
  - Prevent capacity reduction below existing bookings
  - Returns all published slots for feedback

### State Management
- Enhanced admin store with schedule state
- Support for pending/unsaved slot changes
- Optimistic UI updates with server sync

### Documentation
- Comprehensive scheduling system architecture docs
- Quick reference for admin workflows
- Flow diagrams and state transitions
- Implementation guide for future maintenance

## Breaking Changes
None

## Testing Recommendations
- Create slots for future dates via schedule editor
- Verify booking prevention for locked/full slots
- Test capacity adjustments with existing bookings
- Confirm template-based schedule generation
- Verify transaction rollback on publish failures

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:18:49 +08:00

365 lines
12 KiB
Markdown

# Time-Slot & Scheduling System - Documentation Index
This directory contains comprehensive documentation of the NestJS backend time-slot and scheduling system for the pilates studio booking platform.
## 📚 Documentation Files
### 1. **TIME_SLOT_SCHEDULING_SYSTEM.md** (966 lines, 24KB)
**Most comprehensive reference** - Full system analysis with all details
**Contents:**
- Executive Summary
- Data Models (WeekTemplate, TimeSlot, Booking) with Prisma schema
- SlotGeneratorService (4 key methods: generateSlots, cleanupExpiredSlots, checkExpiredMemberships, completeBookings)
- TimeSlotService (queries and management)
- TimeSlotController & AdminTimeSlotController (all endpoints)
- SchedulerService (4 daily cron jobs at 02:00, 02:30, 03:00, 22:00 UTC)
- BookingService (integration with time slots)
- Data Flow Diagrams
- DTOs & Request/Response examples
- Shared Constants & Enums
- File Structure Summary
- Key Architectural Patterns
- Example Scenarios
- Testing Guide
- Configuration & Environment
- Performance Considerations
- Security Notes
- Future Enhancement Ideas
**When to use:** Deep dive into how the system works, understanding all components
---
### 2. **TIME_SLOT_QUICK_REFERENCE.md** (355 lines, 9KB)
**Quick lookup guide** - Essential information at a glance
**Contents:**
- File Locations (all key files in one table)
- Key Concepts (WeekTemplate, TimeSlot, Booking)
- Daily Scheduler Jobs (quick table with times and purposes)
- Important Methods (TypeScript signatures for all key methods)
- API Endpoints (member and admin endpoints with request/response)
- Status Values (all enum values explained)
- Key Logic (booking creation & cancellation flows in pseudocode)
- Weekday Mapping (ISO standard vs JavaScript)
- Database Constraints
- Configuration
- Common Errors (troubleshooting table)
- Testing
- Development Workflow
- Architecture Highlights
**When to use:** Quick lookup while coding, API reference, debugging errors
---
### 3. **TIME_SLOT_DIAGRAMS.md** (606 lines, 25KB)
**Visual references** - ASCII diagrams and flowcharts
**Contents:**
1. Data Model Relationships (entity diagram)
2. Daily Scheduler Timeline (24-hour cron schedule visualization)
3. Booking Lifecycle (detailed creation and cancellation flows)
4. Slot Generation from Template (step-by-step with example)
5. User Booking Flow (frontend → backend interaction)
6. State Transitions (TimeSlot, Booking, Membership status flows)
7. Timezone & Date Handling (UTC, local time conversion)
8. Error Handling Tree (decision tree for POST /booking and cancellation)
9. Integration Points (module dependencies)
**When to use:** Understanding the big picture, presenting to team, tracing flow execution
---
## 🔍 Key Information at a Glance
### Source Code Locations
```
Backend Time-Slot System:
├── packages/server/src/time-slot/
│ ├── slot-generator.service.ts (172 lines)
│ ├── time-slot.service.ts (142 lines)
│ ├── time-slot.controller.ts (93 lines)
│ ├── time-slot.module.ts
│ └── dto/
│ ├── query-slots.dto.ts
│ ├── create-manual-slot.dto.ts
│ └── week-template.dto.ts
├── packages/server/src/scheduler/
│ ├── scheduler.service.ts (55 lines)
│ └── scheduler.module.ts
├── packages/server/src/booking/
│ ├── booking.service.ts (367 lines)
│ ├── booking.controller.ts (82 lines)
│ ├── booking.module.ts
│ └── dto/
│ └── create-booking.dto.ts
├── packages/server/prisma/
│ └── schema.prisma (Models: WeekTemplate, TimeSlot, Booking)
└── packages/shared/src/
├── constants.ts (Slot generation, capacity defaults)
├── enums.ts (TimeSlotStatus, BookingStatus, etc.)
└── types/
└── time-slot.ts (Type definitions)
```
### Daily Scheduler (UTC)
| Time | Job | Method |
|------|-----|--------|
| 02:00 | Generate 14 days of slots | `SlotGeneratorService.generateSlots(14)` |
| 02:30 | Close expired OPEN slots | `SlotGeneratorService.cleanupExpiredSlots()` |
| 03:00 | Expire memberships | `SlotGeneratorService.checkExpiredMemberships()` |
| 22:00 | Complete past bookings | `SlotGeneratorService.completeBookings()` |
### Important Constants
```
DEFAULT_SLOT_CAPACITY = 1 (private lessons)
SLOT_GENERATION_DAYS = 14 (days ahead to auto-generate)
DEFAULT_CANCEL_HOURS_LIMIT = 2 (hours before slot to allow refund)
```
### API Endpoints
**Member:**
```
GET /time-slot/available?date=YYYY-MM-DD
GET /time-slot/:id
POST /booking
PUT /booking/:id/cancel
GET /booking/my
GET /booking/my/upcoming
```
**Admin:**
```
GET /admin/week-template
PUT /admin/week-template
POST /admin/time-slot/manual
PUT /admin/time-slot/:id/close
POST /admin/generate-slots
GET /admin/bookings
```
---
## 🎯 Common Tasks & Where to Find Info
| Task | Reference |
|------|-----------|
| **Understand slot generation algorithm** | TIME_SLOT_SCHEDULING_SYSTEM.md § 2.2 or DIAGRAMS § 4 |
| **See all API endpoints** | QUICK_REFERENCE § "API Endpoints" or TIME_SLOT_SCHEDULING_SYSTEM.md § 4 |
| **Booking creation logic** | TIME_SLOT_DIAGRAMS.md § 3 or QUICK_REFERENCE § "Key Logic" |
| **Weekday mapping (ISO vs JS)** | QUICK_REFERENCE § "Weekday Mapping" or DIAGRAMS § 7 |
| **Cancellation refund policy** | TIME_SLOT_SCHEDULING_SYSTEM.md § 6.1 or DIAGRAMS § 3 |
| **Scheduler jobs timeline** | QUICK_REFERENCE § "Daily Scheduler Jobs" or DIAGRAMS § 2 |
| **Error handling** | QUICK_REFERENCE § "Common Errors" or DIAGRAMS § 8 |
| **Data model relationships** | DIAGRAMS § 1 or TIME_SLOT_SCHEDULING_SYSTEM.md § 1 |
| **Configuration & setup** | QUICK_REFERENCE § "Configuration" or TIME_SLOT_SCHEDULING_SYSTEM.md § 14 |
| **Performance tips** | TIME_SLOT_SCHEDULING_SYSTEM.md § 15 or QUICK_REFERENCE § "Performance Tips" |
| **Module dependencies** | DIAGRAMS § 9 or TIME_SLOT_SCHEDULING_SYSTEM.md § 11.2 |
| **Testing** | TIME_SLOT_SCHEDULING_SYSTEM.md § 13 or QUICK_REFERENCE § "Testing" |
---
## 📋 System Overview
### What It Does
This system manages the complete lifecycle of time slots and bookings for a pilates studio:
1. **Automated Slot Generation**: Every day at 02:00 UTC, generates 14 days of time slots from reusable weekly templates
2. **Capacity Management**: Tracks slot capacity and prevents overbooking
3. **Booking Management**: Allows members to book slots with their memberships
4. **Cancellation & Refunds**: Members can cancel with conditional refunds (within 2-hour window)
5. **Membership Expiration**: Automatically expires memberships by date or used sessions
6. **Cleanup**: Marks past slots as closed and completed bookings as finished
### Key Concepts
- **WeekTemplate**: Defines recurring schedule (e.g., "Monday 09:00-10:00")
- **TimeSlot**: Individual class instance (e.g., "April 10, 2026 09:00-10:00")
- **Booking**: User's reservation (links user + slot + membership)
- **Status Tracking**: OPEN → FULL → CLOSED (slots) and CONFIRMED → COMPLETED (bookings)
### Architecture Highlights
**Idempotent** - Safe to re-run slot generation
**Transactional** - ACID compliance for bookings
**Automated** - 4 daily cron jobs maintain state
**Flexible** - Supports TIMES, DURATION, and TRIAL memberships
**Scalable** - Batch operations, proper database indexes
**Secure** - Role-based access, comprehensive validation
---
## 🚀 Getting Started
### For New Developers
1. **Start with**: TIME_SLOT_QUICK_REFERENCE.md
- Get oriented with file locations and key methods
2. **Then read**: TIME_SLOT_DIAGRAMS.md § 1 (Data Model)
- Understand how entities relate
3. **Deep dive**: TIME_SLOT_SCHEDULING_SYSTEM.md § 2
- Study the SlotGeneratorService algorithm
4. **Explore the code**: Read actual source files for implementation details
### For System Integration
1. Review TIME_SLOT_DIAGRAMS.md § 9 (Integration Points)
2. Check the module imports in `app.module.ts`
3. Understand dependencies in QUICK_REFERENCE.md § "Configuration"
### For API Integration
1. Start with TIME_SLOT_QUICK_REFERENCE.md § "API Endpoints"
2. See examples in TIME_SLOT_SCHEDULING_SYSTEM.md § 12
3. Check DTOs in TIME_SLOT_SCHEDULING_SYSTEM.md § 8
### For Debugging
1. Check common errors in QUICK_REFERENCE.md § "Common Errors"
2. Trace error handling in DIAGRAMS.md § 8
3. Review actual error handling in source code
---
## 📖 Reading Recommendations by Role
### Backend Developer
1. TIME_SLOT_SCHEDULING_SYSTEM.md (all)
2. TIME_SLOT_DIAGRAMS.md (all)
3. Source code in `packages/server/src/time-slot/`
### Frontend Developer
1. TIME_SLOT_QUICK_REFERENCE.md (API Endpoints section)
2. TIME_SLOT_SCHEDULING_SYSTEM.md § 12 (Example Scenarios)
3. TIME_SLOT_DIAGRAMS.md § 5 (User Booking Flow)
### DevOps / Sysadmin
1. TIME_SLOT_SCHEDULING_SYSTEM.md § 14 (Configuration)
2. TIME_SLOT_QUICK_REFERENCE.md § "Daily Scheduler Jobs"
3. TIME_SLOT_DIAGRAMS.md § 2 (Scheduler Timeline)
### Product Manager
1. TIME_SLOT_SCHEDULING_SYSTEM.md § "Executive Summary"
2. TIME_SLOT_DIAGRAMS.md § 3 & 5 (Booking flows)
3. TIME_SLOT_QUICK_REFERENCE.md § "Architecture Highlights"
### QA / Tester
1. TIME_SLOT_QUICK_REFERENCE.md (all)
2. TIME_SLOT_SCHEDULING_SYSTEM.md § 13 (Testing Guide)
3. TIME_SLOT_SCHEDULING_SYSTEM.md § 12 (Example Scenarios)
---
## 🔗 Related Documentation
- **Database Schema**: See `packages/server/prisma/schema.prisma` (lines 113-168)
- **Shared Types**: See `packages/shared/src/types/` and `enums.ts`
- **Authentication**: See booking endpoints require JwtAuthGuard
- **Membership System**: See `BookingService` integration with `MembershipService`
- **Studio Config**: See `StudioService` for `cancelHoursLimit`
---
## 📊 Document Statistics
| File | Lines | Size | Topics |
|------|-------|------|--------|
| TIME_SLOT_SCHEDULING_SYSTEM.md | 966 | 24KB | 17 comprehensive sections |
| TIME_SLOT_QUICK_REFERENCE.md | 355 | 9KB | 15 quick-lookup sections |
| TIME_SLOT_DIAGRAMS.md | 606 | 25KB | 9 visual flowcharts |
| **Total** | **1,927** | **58KB** | **Complete system coverage** |
---
## 🎓 Learning Path
```
Entry Level
├─ README.md (this file)
├─ TIME_SLOT_QUICK_REFERENCE.md (20 min read)
└─ TIME_SLOT_DIAGRAMS.md § 1 (5 min)
Intermediate
├─ TIME_SLOT_DIAGRAMS.md (all, 15 min)
├─ TIME_SLOT_QUICK_REFERENCE.md (re-read, 15 min)
└─ TIME_SLOT_SCHEDULING_SYSTEM.md § 1-6 (30 min)
Advanced
├─ TIME_SLOT_SCHEDULING_SYSTEM.md (full, 60 min)
├─ Source code reading (packages/server/src/time-slot/)
└─ Prisma schema study
Expert
└─ Code review + contributions
```
---
## 🤝 Contributing
When adding features or making changes:
1. **Update the code** in `packages/server/src/time-slot/` and related modules
2. **Update tests** in `__tests__/` directories
3. **Update documentation** in this docs folder if behavior changes
4. Use the **Quick Reference** as checklist for all affected pieces
---
## ❓ FAQ
**Q: Where do time slots come from?**
A: Auto-generated from WeekTemplates every day at 02:00 UTC by `generateSlots(14)`.
**Q: Can I disable slot generation?**
A: Yes, make templates `isActive: false` or disable the cron job in `scheduler.service.ts`.
**Q: How is capacity managed?**
A: `bookedCount` increments on booking, slot status becomes FULL when `bookedCount >= capacity`.
**Q: What if I cancel a booking?**
A: `bookedCount` decrements; if within 2-hour window, membership refunded; slot status restored if was FULL.
**Q: Timezone support?**
A: All times stored in UTC. Scheduler uses UTC times (02:00, 02:30, etc.). See DIAGRAMS § 7.
**Q: How are memberships expired?**
A: Automatically by scheduler job at 03:00 UTC daily; marks EXPIRED if date passed or USED_UP if sessions depleted.
---
## 📞 Quick Reference Card
### Status Values
- **TimeSlot**: OPEN | FULL | CLOSED
- **Booking**: CONFIRMED | CANCELLED | COMPLETED | NO_SHOW
- **Membership**: ACTIVE | EXPIRED | USED_UP
### Key Dates & Times
- **Slot generation**: Daily 02:00 UTC (14 days ahead)
- **Cleanup**: Daily 02:30 UTC
- **Membership check**: Daily 03:00 UTC
- **Booking completion**: Daily 22:00 UTC
- **Cancellation window**: 2 hours before slot (configurable)
### Key Files
- **Slot generation**: `slot-generator.service.ts`
- **Slot queries**: `time-slot.service.ts`
- **Booking logic**: `booking.service.ts`
- **Database**: `prisma/schema.prisma`