Add lessons Phase 2: schedule slots with conflict detection

Recurring weekly time slots linking instructors to lesson types.
Includes day/time overlap detection, instructor and day-of-week
filtering, and 17 new integration tests (40 total lessons tests).
This commit is contained in:
Ryan Moon
2026-03-30 09:20:03 -05:00
parent 5dbe837c08
commit f777ce5184
8 changed files with 513 additions and 3 deletions

View File

@@ -0,0 +1,14 @@
-- Phase 2: Schedule slots — recurring weekly time slots
CREATE TABLE "schedule_slot" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"instructor_id" uuid NOT NULL REFERENCES "instructor"("id"),
"lesson_type_id" uuid NOT NULL REFERENCES "lesson_type"("id"),
"day_of_week" integer NOT NULL,
"start_time" time NOT NULL,
"room" varchar(100),
"max_students" integer NOT NULL DEFAULT 1,
"is_active" boolean NOT NULL DEFAULT true,
"created_at" timestamptz NOT NULL DEFAULT now(),
"updated_at" timestamptz NOT NULL DEFAULT now()
);

View File

@@ -204,6 +204,13 @@
"when": 1774880000000,
"tag": "0028_lessons_foundation",
"breakpoints": true
},
{
"idx": 29,
"version": "7",
"when": 1774890000000,
"tag": "0029_schedule_slots",
"breakpoints": true
}
]
}

View File

@@ -3,6 +3,7 @@ import {
uuid,
varchar,
text,
time,
timestamp,
boolean,
integer,
@@ -39,9 +40,28 @@ export const lessonTypes = pgTable('lesson_type', {
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})
export const scheduleSlots = pgTable('schedule_slot', {
id: uuid('id').primaryKey().defaultRandom(),
instructorId: uuid('instructor_id')
.notNull()
.references(() => instructors.id),
lessonTypeId: uuid('lesson_type_id')
.notNull()
.references(() => lessonTypes.id),
dayOfWeek: integer('day_of_week').notNull(), // 0=Sunday, 6=Saturday
startTime: time('start_time').notNull(),
room: varchar('room', { length: 100 }),
maxStudents: integer('max_students').notNull().default(1),
isActive: boolean('is_active').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})
// --- Type exports ---
export type Instructor = typeof instructors.$inferSelect
export type InstructorInsert = typeof instructors.$inferInsert
export type LessonType = typeof lessonTypes.$inferSelect
export type LessonTypeInsert = typeof lessonTypes.$inferInsert
export type ScheduleSlot = typeof scheduleSlots.$inferSelect
export type ScheduleSlotInsert = typeof scheduleSlots.$inferInsert

View File

@@ -5,8 +5,10 @@ import {
InstructorUpdateSchema,
LessonTypeCreateSchema,
LessonTypeUpdateSchema,
ScheduleSlotCreateSchema,
ScheduleSlotUpdateSchema,
} from '@lunarfront/shared/schemas'
import { InstructorService, LessonTypeService } from '../../services/lesson.service.js'
import { InstructorService, LessonTypeService, ScheduleSlotService } from '../../services/lesson.service.js'
export const lessonRoutes: FastifyPluginAsync = async (app) => {
// --- Instructors ---
@@ -92,4 +94,57 @@ export const lessonRoutes: FastifyPluginAsync = async (app) => {
if (!lessonType) return reply.status(404).send({ error: { message: 'Lesson type not found', statusCode: 404 } })
return reply.send(lessonType)
})
// --- Schedule Slots ---
app.post('/schedule-slots', { preHandler: [app.authenticate, app.requirePermission('lessons.admin')] }, async (request, reply) => {
const parsed = ScheduleSlotCreateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const result = await ScheduleSlotService.create(app.db, parsed.data)
if ('error' in result) {
return reply.status(409).send({ error: { message: result.error, statusCode: 409 } })
}
return reply.status(201).send(result)
})
app.get('/schedule-slots', { preHandler: [app.authenticate, app.requirePermission('lessons.view')] }, async (request, reply) => {
const query = request.query as Record<string, string | undefined>
const params = PaginationSchema.parse(query)
const filters = {
instructorId: query.instructorId,
dayOfWeek: query.dayOfWeek !== undefined ? Number(query.dayOfWeek) : undefined,
}
const result = await ScheduleSlotService.list(app.db, params, filters)
return reply.send(result)
})
app.get('/schedule-slots/:id', { preHandler: [app.authenticate, app.requirePermission('lessons.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const slot = await ScheduleSlotService.getById(app.db, id)
if (!slot) return reply.status(404).send({ error: { message: 'Schedule slot not found', statusCode: 404 } })
return reply.send(slot)
})
app.patch('/schedule-slots/:id', { preHandler: [app.authenticate, app.requirePermission('lessons.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const parsed = ScheduleSlotUpdateSchema.safeParse(request.body)
if (!parsed.success) {
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
}
const result = await ScheduleSlotService.update(app.db, id, parsed.data)
if (!result) return reply.status(404).send({ error: { message: 'Schedule slot not found', statusCode: 404 } })
if ('error' in result) {
return reply.status(409).send({ error: { message: result.error, statusCode: 409 } })
}
return reply.send(result)
})
app.delete('/schedule-slots/:id', { preHandler: [app.authenticate, app.requirePermission('lessons.admin')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const slot = await ScheduleSlotService.delete(app.db, id)
if (!slot) return reply.status(404).send({ error: { message: 'Schedule slot not found', statusCode: 404 } })
return reply.send(slot)
})
}

View File

@@ -1,11 +1,13 @@
import { eq, and, count, type Column } from 'drizzle-orm'
import { eq, and, count, type Column, type SQL } from 'drizzle-orm'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import { instructors, lessonTypes } from '../db/schema/lessons.js'
import { instructors, lessonTypes, scheduleSlots } from '../db/schema/lessons.js'
import type {
InstructorCreateInput,
InstructorUpdateInput,
LessonTypeCreateInput,
LessonTypeUpdateInput,
ScheduleSlotCreateInput,
ScheduleSlotUpdateInput,
PaginationInput,
} from '@lunarfront/shared/schemas'
import {
@@ -152,3 +154,128 @@ export const LessonTypeService = {
return lessonType ?? null
},
}
export const ScheduleSlotService = {
async create(db: PostgresJsDatabase<any>, input: ScheduleSlotCreateInput) {
// Check for overlapping slot on same instructor, day, and time
const [conflict] = await db
.select({ id: scheduleSlots.id })
.from(scheduleSlots)
.where(
and(
eq(scheduleSlots.instructorId, input.instructorId),
eq(scheduleSlots.dayOfWeek, input.dayOfWeek),
eq(scheduleSlots.startTime, input.startTime),
eq(scheduleSlots.isActive, true),
),
)
.limit(1)
if (conflict) {
return { error: 'Instructor already has a slot at this day and time' }
}
const [slot] = await db
.insert(scheduleSlots)
.values({
instructorId: input.instructorId,
lessonTypeId: input.lessonTypeId,
dayOfWeek: input.dayOfWeek,
startTime: input.startTime,
room: input.room,
maxStudents: input.maxStudents,
})
.returning()
return slot
},
async getById(db: PostgresJsDatabase<any>, id: string) {
const [slot] = await db
.select()
.from(scheduleSlots)
.where(eq(scheduleSlots.id, id))
.limit(1)
return slot ?? null
},
async list(db: PostgresJsDatabase<any>, params: PaginationInput, filters?: {
instructorId?: string
dayOfWeek?: number
}) {
const conditions: SQL[] = [eq(scheduleSlots.isActive, true)]
if (params.q) {
const search = buildSearchCondition(params.q, [scheduleSlots.room])
if (search) conditions.push(search)
}
if (filters?.instructorId) {
conditions.push(eq(scheduleSlots.instructorId, filters.instructorId))
}
if (filters?.dayOfWeek !== undefined) {
conditions.push(eq(scheduleSlots.dayOfWeek, filters.dayOfWeek))
}
const where = and(...conditions)
const sortableColumns: Record<string, Column> = {
day_of_week: scheduleSlots.dayOfWeek,
start_time: scheduleSlots.startTime,
room: scheduleSlots.room,
created_at: scheduleSlots.createdAt,
}
let query = db.select().from(scheduleSlots).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, scheduleSlots.dayOfWeek)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(scheduleSlots).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async update(db: PostgresJsDatabase<any>, id: string, input: ScheduleSlotUpdateInput) {
// If changing day/time/instructor, check for conflicts
if (input.instructorId || input.dayOfWeek !== undefined || input.startTime) {
const existing = await ScheduleSlotService.getById(db, id)
if (!existing) return null
const checkInstructorId = input.instructorId ?? existing.instructorId
const checkDay = input.dayOfWeek ?? existing.dayOfWeek
const checkTime = input.startTime ?? existing.startTime
const [conflict] = await db
.select({ id: scheduleSlots.id })
.from(scheduleSlots)
.where(
and(
eq(scheduleSlots.instructorId, checkInstructorId),
eq(scheduleSlots.dayOfWeek, checkDay),
eq(scheduleSlots.startTime, checkTime),
eq(scheduleSlots.isActive, true),
),
)
.limit(1)
if (conflict && conflict.id !== id) {
return { error: 'Instructor already has a slot at this day and time' }
}
}
const [slot] = await db
.update(scheduleSlots)
.set({ ...input, updatedAt: new Date() })
.where(eq(scheduleSlots.id, id))
.returning()
return slot ?? null
},
async delete(db: PostgresJsDatabase<any>, id: string) {
const [slot] = await db
.update(scheduleSlots)
.set({ isActive: false, updatedAt: new Date() })
.where(eq(scheduleSlots.id, id))
.returning()
return slot ?? null
},
}